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
695f575e0affe24783489f7ad63622fec7741f4a
16,415,365,060,328
c05af3e8eb70444e5df92d023801658af4a31a1c
/bin/Release/work/org/w3c/dom/Attr.java
3053d7d53fb227e4aded388132c3dccefc0c3cc1
[]
no_license
zengge2/Java2Smali
https://github.com/zengge2/Java2Smali
e2b69b652cb7d36af0b0d764ff9a873521899acb
a6a73ab490d273d378f078e468997975ef3b6278
refs/heads/master
2020-06-28T05:09:36.642000
2019-08-02T02:22:02
2019-08-02T02:22:02
200,149,211
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2004 World Wide Web Consortium, * * (Massachusetts Institute of Technology, European Research Consortium for * Informatics and Mathematics, Keio University). All Rights Reserved. This * work is distributed under the W3C(r) Software License [1] in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 */ package org.w3c.dom; public interface Attr extends org.w3c.dom.Node { public abstract java.lang.String getName(); public abstract boolean getSpecified(); public abstract java.lang.String getValue(); public abstract void setValue(java.lang.String value) throws org.w3c.dom.DOMException; public abstract org.w3c.dom.Element getOwnerElement(); public abstract org.w3c.dom.TypeInfo getSchemaTypeInfo(); public abstract boolean isId(); }
UTF-8
Java
941
java
Attr.java
Java
[]
null
[]
/* * Copyright (c) 2004 World Wide Web Consortium, * * (Massachusetts Institute of Technology, European Research Consortium for * Informatics and Mathematics, Keio University). All Rights Reserved. This * work is distributed under the W3C(r) Software License [1] in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 */ package org.w3c.dom; public interface Attr extends org.w3c.dom.Node { public abstract java.lang.String getName(); public abstract boolean getSpecified(); public abstract java.lang.String getValue(); public abstract void setValue(java.lang.String value) throws org.w3c.dom.DOMException; public abstract org.w3c.dom.Element getOwnerElement(); public abstract org.w3c.dom.TypeInfo getSchemaTypeInfo(); public abstract boolean isId(); }
941
0.780021
0.753454
24
38.208332
29.366901
87
false
false
0
0
0
0
0
0
0.541667
false
false
15
01c074347b910e1b083533c52ff64723866a62f3
13,219,909,399,608
a22a237ff77fc11b3f73b030a680a4362bebd172
/yums-starter-http/src/main/java/cn/chenjy/yums/http/template/OkHttpTemplate.java
9fb14f08f2453c31d63a739a7676ab3d1cb783de
[ "Apache-2.0" ]
permissive
chenjy1991/yums-starter
https://github.com/chenjy1991/yums-starter
f197e53bc3814f82defaa05b5dc5f15bf7825bcc
8f4b2b01293a1946c3cdba9fd5bbf5ce077f7629
refs/heads/master
2023-06-04T08:17:20.340000
2021-06-21T06:19:24
2021-06-21T06:19:24
374,720,815
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.chenjy.yums.http.template; import cn.chenjy.yums.http.CharConst; import com.google.gson.Gson; import okhttp3.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.Iterator; import java.util.Map; /** * @author ChenJY * @create 2021/6/18 11:13 上午 * @DESCRIPTION */ public class OkHttpTemplate implements HttpTemplate { private static final Logger LOG = LoggerFactory.getLogger(OkHttpTemplate.class); private static final String TAG = "OkHttpTemplate"; @Autowired OkHttpClient okHttpClient; @Override public String get(String url) { return get(url,null); } @Override public String get(String url, Map<String, String> params) { Request request = getGetRquest(url, params); String responseStr = execRequest(request); return responseStr; } @Override public String post(String url) { return postByForm(url,null); } @Override public String postByForm(String url, Map<String, String> params) { Request request = getPostFormRequest(url, params); String responseStr = execRequest(request); return responseStr; } @Override public String postByJson(String url, Map<String, Object> params) { Request request = getPostJsonRequest(url, params); String responseStr = execRequest(request); return responseStr; } /** * 发送请求 * * @param request * @return */ private String execRequest(Request request) { Response response = null; try { response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } } catch (IOException e) { throw new RuntimeException(e); } finally { if (response != null) { response.close(); } } return null; } /** * 获取参数拼接在URL中的地址 * * @param url * @param params * @return */ private String getQueryUrlString(String url, Map<String, String> params) { StringBuilder urlSb = new StringBuilder(url); if (params != null && params.keySet().size() > 0) { urlSb.append(CharConst.QUESTION_MARK); Iterator<Map.Entry<String, String>> is = params.entrySet().iterator(); while (is.hasNext()) { Map.Entry<String, String> item = is.next(); urlSb.append(item.getKey()).append("=").append(item.getValue()).append("&"); } urlSb.deleteCharAt(urlSb.lastIndexOf("&")); } return urlSb.toString(); } /** * 获取GET方法的Request * * @param url * @return */ private Request getGetRquest(String url, Map<String, String> params) { return new Request.Builder().url(getQueryUrlString(url, params)).build(); } /** * 获取POST-FORM方法的Request * * @param url * @param params * @return */ private Request getPostFormRequest(String url, Map<String, String> params) { FormBody.Builder builder = new FormBody.Builder(); //添加参数 if (params != null && params.keySet().size() > 0) { for (String key : params.keySet()) { builder.add(key, params.get(key)); } } Request request = new Request.Builder().url(url).post(builder.build()).build(); return request; } /** * 获取POST-JSON方法的Request * * @param url * @param params * @return */ private Request getPostJsonRequest(String url, Map<String, Object> params) { Gson gson = new Gson(); String jsonParams = gson.toJson(params); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams); Request request = new Request.Builder().url(url).post(requestBody).build(); return request; } }
UTF-8
Java
4,171
java
OkHttpTemplate.java
Java
[ { "context": "il.Iterator;\nimport java.util.Map;\n\n/**\n * @author ChenJY\n * @create 2021/6/18 11:13 上午\n * @DESCRIPTION\n */", "end": 344, "score": 0.993626594543457, "start": 338, "tag": "USERNAME", "value": "ChenJY" } ]
null
[]
package cn.chenjy.yums.http.template; import cn.chenjy.yums.http.CharConst; import com.google.gson.Gson; import okhttp3.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.Iterator; import java.util.Map; /** * @author ChenJY * @create 2021/6/18 11:13 上午 * @DESCRIPTION */ public class OkHttpTemplate implements HttpTemplate { private static final Logger LOG = LoggerFactory.getLogger(OkHttpTemplate.class); private static final String TAG = "OkHttpTemplate"; @Autowired OkHttpClient okHttpClient; @Override public String get(String url) { return get(url,null); } @Override public String get(String url, Map<String, String> params) { Request request = getGetRquest(url, params); String responseStr = execRequest(request); return responseStr; } @Override public String post(String url) { return postByForm(url,null); } @Override public String postByForm(String url, Map<String, String> params) { Request request = getPostFormRequest(url, params); String responseStr = execRequest(request); return responseStr; } @Override public String postByJson(String url, Map<String, Object> params) { Request request = getPostJsonRequest(url, params); String responseStr = execRequest(request); return responseStr; } /** * 发送请求 * * @param request * @return */ private String execRequest(Request request) { Response response = null; try { response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } } catch (IOException e) { throw new RuntimeException(e); } finally { if (response != null) { response.close(); } } return null; } /** * 获取参数拼接在URL中的地址 * * @param url * @param params * @return */ private String getQueryUrlString(String url, Map<String, String> params) { StringBuilder urlSb = new StringBuilder(url); if (params != null && params.keySet().size() > 0) { urlSb.append(CharConst.QUESTION_MARK); Iterator<Map.Entry<String, String>> is = params.entrySet().iterator(); while (is.hasNext()) { Map.Entry<String, String> item = is.next(); urlSb.append(item.getKey()).append("=").append(item.getValue()).append("&"); } urlSb.deleteCharAt(urlSb.lastIndexOf("&")); } return urlSb.toString(); } /** * 获取GET方法的Request * * @param url * @return */ private Request getGetRquest(String url, Map<String, String> params) { return new Request.Builder().url(getQueryUrlString(url, params)).build(); } /** * 获取POST-FORM方法的Request * * @param url * @param params * @return */ private Request getPostFormRequest(String url, Map<String, String> params) { FormBody.Builder builder = new FormBody.Builder(); //添加参数 if (params != null && params.keySet().size() > 0) { for (String key : params.keySet()) { builder.add(key, params.get(key)); } } Request request = new Request.Builder().url(url).post(builder.build()).build(); return request; } /** * 获取POST-JSON方法的Request * * @param url * @param params * @return */ private Request getPostJsonRequest(String url, Map<String, Object> params) { Gson gson = new Gson(); String jsonParams = gson.toJson(params); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams); Request request = new Request.Builder().url(url).post(requestBody).build(); return request; } }
4,171
0.597707
0.593559
144
27.465279
24.988585
117
false
false
0
0
0
0
0
0
0.5
false
false
15
704f1e1ae2f380bc0d08f1d6a3a0aeff33f99e77
39,024,072,885,821
7f8cc05559cbd696c04d0307b26544375403c33d
/blog-api/src/main/java/com/titxu/blog/dao/mapper/CommentMapper.java
c833fc8076376bfa1a42dedcfece0589b6a575d0
[]
no_license
titxue/lxueblog-api
https://github.com/titxue/lxueblog-api
201e0eb40d1f8cd1030581da545228fc024aa506
c38f32566564eb8b82fc798cc696d89a8b53c733
refs/heads/master
2023-07-16T14:12:49.782000
2021-08-28T13:11:26
2021-08-28T13:11:26
400,788,755
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.titxu.blog.dao.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.titxu.blog.dao.pojo.Comment; import org.springframework.stereotype.Repository; /** * @author lxue * @date 2021/7/31 * @apiNate */ @Repository public interface CommentMapper extends BaseMapper<Comment> { }
UTF-8
Java
313
java
CommentMapper.java
Java
[ { "context": "ngframework.stereotype.Repository;\n\n/**\n * @author lxue\n * @date 2021/7/31\n * @apiNate\n */\n@Repository\npu", "end": 202, "score": 0.9996709823608398, "start": 198, "tag": "USERNAME", "value": "lxue" } ]
null
[]
package com.titxu.blog.dao.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.titxu.blog.dao.pojo.Comment; import org.springframework.stereotype.Repository; /** * @author lxue * @date 2021/7/31 * @apiNate */ @Repository public interface CommentMapper extends BaseMapper<Comment> { }
313
0.773163
0.750799
14
21.357143
20.92028
60
false
false
0
0
0
0
0
0
0.285714
false
false
15
f14c8d3686e699bb4b3fbd42999664a7331e4296
36,567,351,597,071
03e2a7337d8fe3d9735ca448169428674908e9af
/starter/critter/src/main/java/com/udacity/jdnd/course3/critter/schedule/ScheduleService.java
da4c46a312befc15ebb8af4b4f756f66cc1ffff4
[ "MIT" ]
permissive
rishabh1994/data-store-and-persistence-udacity
https://github.com/rishabh1994/data-store-and-persistence-udacity
162ad89f67f414c990920ae752df5db024f4f54a
69815b462ad93e39e7b26ab50b406da711e37d9e
refs/heads/master
2023-01-12T05:12:44.122000
2020-11-07T18:16:12
2020-11-07T18:16:12
304,870,266
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.udacity.jdnd.course3.critter.schedule; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; @Service @Slf4j @Transactional public class ScheduleService { @Autowired private ScheduleRepository scheduleRepository; public ScheduleEntity saveSchedule(ScheduleEntity scheduleEntity) { log.info("Input schedule to save : {}", scheduleEntity); ScheduleEntity savedSchedule = scheduleRepository.save(scheduleEntity); log.info("saved schedule : {}", savedSchedule); return savedSchedule; } public List<ScheduleEntity> getAllSchedules() { List<ScheduleEntity> scheduleEntityList = (List<ScheduleEntity>) scheduleRepository.findAll(); log.info("Fetched all the schedules from the DB"); return scheduleEntityList; } }
UTF-8
Java
960
java
ScheduleService.java
Java
[]
null
[]
package com.udacity.jdnd.course3.critter.schedule; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; @Service @Slf4j @Transactional public class ScheduleService { @Autowired private ScheduleRepository scheduleRepository; public ScheduleEntity saveSchedule(ScheduleEntity scheduleEntity) { log.info("Input schedule to save : {}", scheduleEntity); ScheduleEntity savedSchedule = scheduleRepository.save(scheduleEntity); log.info("saved schedule : {}", savedSchedule); return savedSchedule; } public List<ScheduleEntity> getAllSchedules() { List<ScheduleEntity> scheduleEntityList = (List<ScheduleEntity>) scheduleRepository.findAll(); log.info("Fetched all the schedules from the DB"); return scheduleEntityList; } }
960
0.747917
0.74375
32
29
28.148046
102
false
false
0
0
0
0
0
0
0.5
false
false
15
57547bb27f37f6d359e4f9f2e6ecd930882931ba
36,636,071,065,633
50eb6638d0fd7feda397b9c667e229236d7e1f01
/src/org/launchcode/studio7/Main.java
2aa348c2a76dda5dcd968605e0b4ad1901e349c7
[]
no_license
MulesKC/java-web-dev-studio7
https://github.com/MulesKC/java-web-dev-studio7
4bff571b3f2ae8b20d47f333718ed5491f3c8442
6e73329c17ccbb8754828056449f6ae57a51b5ee
refs/heads/master
2021-01-05T08:27:13.925000
2020-02-18T01:27:44
2020-02-18T01:27:44
240,952,973
0
0
null
true
2020-02-16T19:33:55
2020-02-16T19:33:55
2019-11-08T20:58:43
2019-11-08T22:13:52
10
0
0
0
null
false
false
package org.launchcode.studio7; public class Main { public static void main(String[] args){ CD music = new CD("Summer Jamz", 80, 20, 80, 12); DVD movie = new DVD("Avatar", 300, 40, 120, 127); // TODO: Declare and initialize a CD and a DVD object. // TODO: Call each CD and DVD method to verify that they work as expected. System.out.println("Spin methods:"); music.spinDisc(); movie.spinDisc(); System.out.println("\n"); System.out.println("Store methods:"); music.storeData(); movie.storeData(); System.out.println("\n"); System.out.println("Write methods:"); music.writeData(); movie.writeData(); System.out.println("\n"); System.out.println("Read methods:"); music.readData(); movie.readData(); System.out.println("\n"); System.out.println("Report basic info methods:"); music.reportInfo(); movie.reportInfo(); System.out.println("\n"); System.out.println("Store physical disc methods:"); music.storeDisc(); movie.storeDisc(); System.out.println("\n"); System.out.println("Microwave methods:"); music.microwaveDisc(); movie.microwaveDisc(); } }
UTF-8
Java
1,322
java
Main.java
Java
[ { "context": "d main(String[] args){\n CD music = new CD(\"Summer Jamz\", 80, 20, 80, 12);\n\n DVD movie = new DVD(\"", "end": 136, "score": 0.9997612237930298, "start": 125, "tag": "NAME", "value": "Summer Jamz" } ]
null
[]
package org.launchcode.studio7; public class Main { public static void main(String[] args){ CD music = new CD("<NAME>", 80, 20, 80, 12); DVD movie = new DVD("Avatar", 300, 40, 120, 127); // TODO: Declare and initialize a CD and a DVD object. // TODO: Call each CD and DVD method to verify that they work as expected. System.out.println("Spin methods:"); music.spinDisc(); movie.spinDisc(); System.out.println("\n"); System.out.println("Store methods:"); music.storeData(); movie.storeData(); System.out.println("\n"); System.out.println("Write methods:"); music.writeData(); movie.writeData(); System.out.println("\n"); System.out.println("Read methods:"); music.readData(); movie.readData(); System.out.println("\n"); System.out.println("Report basic info methods:"); music.reportInfo(); movie.reportInfo(); System.out.println("\n"); System.out.println("Store physical disc methods:"); music.storeDisc(); movie.storeDisc(); System.out.println("\n"); System.out.println("Microwave methods:"); music.microwaveDisc(); movie.microwaveDisc(); } }
1,317
0.569592
0.554463
54
23.481482
21.033255
82
false
false
0
0
0
0
0
0
0.703704
false
false
15
f83e8858ee017716efc59c9fb0ccb997ea95ad11
38,869,454,038,802
112faa1916a63d974f362d446f15da7938046e3f
/src/main/java/org/jetlinks/supports/rsocket/RSocketManager.java
f164ef66e95a573e2a3d0425b71dff63d71fe95a
[]
no_license
yuzhuguan/jetlinks-supports
https://github.com/yuzhuguan/jetlinks-supports
549ffb040cb4f5638ca653f46eb2dc7a7df8bb7c
2da02249fa38a75c84b2520452f59aa5f23c9fa6
refs/heads/master
2023-01-30T05:37:37.444000
2020-12-11T10:09:16
2020-12-11T10:09:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.jetlinks.supports.rsocket; import reactor.core.publisher.Mono; import java.util.List; public interface RSocketManager { Mono<ServerNode> getServer(String serverId); List<ServerNode> getServers(); }
UTF-8
Java
225
java
RSocketManager.java
Java
[]
null
[]
package org.jetlinks.supports.rsocket; import reactor.core.publisher.Mono; import java.util.List; public interface RSocketManager { Mono<ServerNode> getServer(String serverId); List<ServerNode> getServers(); }
225
0.76
0.76
14
15.071428
17.974047
48
false
false
0
0
0
0
0
0
0.357143
false
false
15
7dee66213ef9c8d7dcc94670aad41a1f3cadcf61
35,167,192,265,199
38cd382f64cd1eb48658b86c71af0ef1f51ffb5c
/src/main/java/jorge/rolmap/controller/TaskController.java
900d51fd8052059a6e1260793ebe0440a7e9f5a5
[]
no_license
JorgeLopezMartin/rolmap-backend-java
https://github.com/JorgeLopezMartin/rolmap-backend-java
f5cf366eb214072f06e4798df665438676c63fc8
c12c5fc034c167263a8f0e3c235f71550c05aaa1
refs/heads/master
2023-02-04T17:56:58.110000
2020-12-27T12:22:27
2020-12-27T12:22:27
318,585,685
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jorge.rolmap.controller; import com.google.gson.Gson; import jorge.rolmap.controller.util.ControllerUtils; import jorge.rolmap.controller.util.requests.tasks.TaskPost; import jorge.rolmap.model.Task; import jorge.rolmap.service.TaskService; import jorge.rolmap.util.exception.InstanceNotFoundException; import jorge.rolmap.util.exception.InvalidArgumentException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping("/task") public class TaskController { @Autowired private TaskService taskService; @GetMapping("") public ResponseEntity<String> getTasks() { return ResponseEntity.status(HttpStatus.OK).body(new Gson().toJson(taskService.getTasks())); } @PostMapping("") public ResponseEntity<String> postTask(@RequestBody @Valid TaskPost taskPost, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return this.validationErrorHandler(bindingResult); } try { Task task = taskService.createTask(taskPost.getTitle(), taskPost.getDescription(), taskPost.getIsDone()); return ResponseEntity.status(HttpStatus.CREATED).body(new Gson().toJson(task)); } catch (InvalidArgumentException e) { return new ResponseEntity<String>(ControllerUtils.parseError(e), HttpStatus.BAD_REQUEST); } } @PutMapping("/{taskId}") public ResponseEntity<String> markTask(@PathVariable("taskId") Integer id, @RequestBody @Valid TaskPost taskIsDonePut, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return this.validationErrorHandler(bindingResult); } try { Task task = taskService.markAsDone(id, taskIsDonePut.getIsDone()); return ResponseEntity.ok(new Gson().toJson(task)); } catch (InstanceNotFoundException e) { return new ResponseEntity<String>(ControllerUtils.parseError(e), HttpStatus.NOT_FOUND); } } @DeleteMapping("/{taskId}") public ResponseEntity<String> deleteTask(@PathVariable("taskId") Integer id) { try{ taskService.removeTask(id); return ResponseEntity.ok(null); } catch (InstanceNotFoundException e) { return new ResponseEntity<String>(ControllerUtils.parseError(e), HttpStatus.NOT_FOUND); } } private ResponseEntity<String> validationErrorHandler(BindingResult bindingResult) { return new ResponseEntity<String>(ControllerUtils.parseError(new InvalidArgumentException(bindingResult.getFieldError().getField())), HttpStatus.BAD_REQUEST); } }
UTF-8
Java
2,862
java
TaskController.java
Java
[]
null
[]
package jorge.rolmap.controller; import com.google.gson.Gson; import jorge.rolmap.controller.util.ControllerUtils; import jorge.rolmap.controller.util.requests.tasks.TaskPost; import jorge.rolmap.model.Task; import jorge.rolmap.service.TaskService; import jorge.rolmap.util.exception.InstanceNotFoundException; import jorge.rolmap.util.exception.InvalidArgumentException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping("/task") public class TaskController { @Autowired private TaskService taskService; @GetMapping("") public ResponseEntity<String> getTasks() { return ResponseEntity.status(HttpStatus.OK).body(new Gson().toJson(taskService.getTasks())); } @PostMapping("") public ResponseEntity<String> postTask(@RequestBody @Valid TaskPost taskPost, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return this.validationErrorHandler(bindingResult); } try { Task task = taskService.createTask(taskPost.getTitle(), taskPost.getDescription(), taskPost.getIsDone()); return ResponseEntity.status(HttpStatus.CREATED).body(new Gson().toJson(task)); } catch (InvalidArgumentException e) { return new ResponseEntity<String>(ControllerUtils.parseError(e), HttpStatus.BAD_REQUEST); } } @PutMapping("/{taskId}") public ResponseEntity<String> markTask(@PathVariable("taskId") Integer id, @RequestBody @Valid TaskPost taskIsDonePut, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return this.validationErrorHandler(bindingResult); } try { Task task = taskService.markAsDone(id, taskIsDonePut.getIsDone()); return ResponseEntity.ok(new Gson().toJson(task)); } catch (InstanceNotFoundException e) { return new ResponseEntity<String>(ControllerUtils.parseError(e), HttpStatus.NOT_FOUND); } } @DeleteMapping("/{taskId}") public ResponseEntity<String> deleteTask(@PathVariable("taskId") Integer id) { try{ taskService.removeTask(id); return ResponseEntity.ok(null); } catch (InstanceNotFoundException e) { return new ResponseEntity<String>(ControllerUtils.parseError(e), HttpStatus.NOT_FOUND); } } private ResponseEntity<String> validationErrorHandler(BindingResult bindingResult) { return new ResponseEntity<String>(ControllerUtils.parseError(new InvalidArgumentException(bindingResult.getFieldError().getField())), HttpStatus.BAD_REQUEST); } }
2,862
0.721523
0.721523
70
39.885715
37.754677
166
false
false
0
0
0
0
0
0
0.542857
false
false
15
533fd44f2915a1de36c58daf3938af7aa480a4bb
15,908,558,928,615
0072599445cadd84bcbb04471be331a60ef44817
/QRcode/src/com/ljl/CreatQRcode.java
ac7c618d616d17df70cf746e03000594ce849c4f
[]
no_license
liujialing123/erweima
https://github.com/liujialing123/erweima
628229415196bb8ab33b1d9bbf3f58796c51f2d9
4e5d5d15ad4c21b190a48b7002c677fef8ce4b05
refs/heads/master
2020-03-22T11:11:55.121000
2018-07-06T08:55:21
2018-07-06T08:55:21
139,954,653
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ljl; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import com.swetake.util.Qrcode; public class CreatQRcode { public static void creatQRcode (String content1,String imgPath,int version,String startRgb,String endRgb) throws IOException { int imgSize=67+(version-1)*12; //创建二维码对象 Qrcode qrcode = new Qrcode(); qrcode.setQrcodeVersion(version); //生成一个图片缓存对象 BufferedImage bufferedImage = new BufferedImage(imgSize,imgSize,BufferedImage.TYPE_INT_BGR); //创建绘画对象 Graphics2D gs=bufferedImage.createGraphics(); //设置背景颜色 gs.setBackground(Color.white); //设置填充颜色 gs.setColor(Color.blue); //清空画板 gs.clearRect(0,0,imgSize,imgSize); //二维码内容 //声明偏移量 int pixoff=2; int startR=0, startG=0, startB=0; int endR=0,endG=0, endB=0; if(null!=startRgb) { String[] split=startRgb.split(","); startR=Integer.valueOf(split[0]); startG=Integer.valueOf(split[1]); startB=Integer.valueOf(split[2]); } if(null!=endRgb) { String[] split=endRgb.split(","); endR=Integer.valueOf(split[0]); endG=Integer.valueOf(split[1]); endB=Integer.valueOf(split[2]); } //通过二维码要填充的内容获取一个布尔类型的二维数组 boolean[][] calQrcode=qrcode.calQrcode(content1.getBytes("UTF-8")); for(int i=0;i<calQrcode.length;i++){//遍历行 System.out.println("行数:"+calQrcode.length+"列数:"+calQrcode[i].length); for(int j=0;j<calQrcode.length;j++){//遍历列 if(calQrcode[i][j]){//true填充二维码颜色 false则不填充 int r=startR+(endR-startR)/calQrcode.length*(j+1); int g=startG+(endG-startR)/calQrcode.length*(j+1); int b=startB+(endB-startR)/calQrcode.length*(j+1); Color color = new Color(r,g,b); gs.setColor(color); gs.fillRect(i*3+pixoff, j*3+pixoff, 3, 3); } } } BufferedImage logo=ImageIO.read(new File("D:/logo.jpg")); int logoSize=imgSize/4; int o=(imgSize-logoSize)/2; gs.drawImage(logo,o,o,logoSize,logoSize,null); //关闭绘画对象 gs.dispose(); //把缓存区图片输出到内存当中 bufferedImage.flush(); try{ //把内存当中的图片输出到硬盘当中 ImageIO.write(bufferedImage,"png",new File("D:/qr.png")); } catch(IOException e){ e.printStackTrace(); } System.out.println("成功"); } public static void main(String[] args) throws IOException { String content1="BEGIN:VCARD\r\n" + "FN:姓名:刘嘉玲\r\n"+ "ORG:学校:河北科技师范学院 学院:数信\r\n"+ "TITLE:在校生\r\n" + "TEL;WORK;VOICE:1238\r\n"+ "TEL;HOME;VOICE:456\r\n"+ "TEL;CELL;VOICE:15533516959\r\n"+ "ADR;WORK:河北科技师范学院数信学院科技1603\r\n"+ "ADR;HOME:南院6号楼\r\n"+ "URL:http://www.百度.com\r\n"+ "EMAIL;HOME:244861262@qq.com\r\n" + "END:VCARD"; String imgPath="D:/qr.png"; int version=16; String startRgb="0,0,255"; String endRgb="255,0,0"; creatQRcode(content1,imgPath,version,startRgb,endRgb); } }
GB18030
Java
3,131
java
CreatQRcode.java
Java
[ { "context": "\t\n\t\tString content1=\"BEGIN:VCARD\\r\\n\" + \n\t\t\"FN:姓名:刘嘉玲\\r\\n\"+\n\t\t\"ORG:学校:河北科技师范学院\t学院:数信\\r\\n\"+\n\t\t\"TITLE:在校生", "end": 2317, "score": 0.9998713135719299, "start": 2314, "tag": "NAME", "value": "刘嘉玲" } ]
null
[]
package com.ljl; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import com.swetake.util.Qrcode; public class CreatQRcode { public static void creatQRcode (String content1,String imgPath,int version,String startRgb,String endRgb) throws IOException { int imgSize=67+(version-1)*12; //创建二维码对象 Qrcode qrcode = new Qrcode(); qrcode.setQrcodeVersion(version); //生成一个图片缓存对象 BufferedImage bufferedImage = new BufferedImage(imgSize,imgSize,BufferedImage.TYPE_INT_BGR); //创建绘画对象 Graphics2D gs=bufferedImage.createGraphics(); //设置背景颜色 gs.setBackground(Color.white); //设置填充颜色 gs.setColor(Color.blue); //清空画板 gs.clearRect(0,0,imgSize,imgSize); //二维码内容 //声明偏移量 int pixoff=2; int startR=0, startG=0, startB=0; int endR=0,endG=0, endB=0; if(null!=startRgb) { String[] split=startRgb.split(","); startR=Integer.valueOf(split[0]); startG=Integer.valueOf(split[1]); startB=Integer.valueOf(split[2]); } if(null!=endRgb) { String[] split=endRgb.split(","); endR=Integer.valueOf(split[0]); endG=Integer.valueOf(split[1]); endB=Integer.valueOf(split[2]); } //通过二维码要填充的内容获取一个布尔类型的二维数组 boolean[][] calQrcode=qrcode.calQrcode(content1.getBytes("UTF-8")); for(int i=0;i<calQrcode.length;i++){//遍历行 System.out.println("行数:"+calQrcode.length+"列数:"+calQrcode[i].length); for(int j=0;j<calQrcode.length;j++){//遍历列 if(calQrcode[i][j]){//true填充二维码颜色 false则不填充 int r=startR+(endR-startR)/calQrcode.length*(j+1); int g=startG+(endG-startR)/calQrcode.length*(j+1); int b=startB+(endB-startR)/calQrcode.length*(j+1); Color color = new Color(r,g,b); gs.setColor(color); gs.fillRect(i*3+pixoff, j*3+pixoff, 3, 3); } } } BufferedImage logo=ImageIO.read(new File("D:/logo.jpg")); int logoSize=imgSize/4; int o=(imgSize-logoSize)/2; gs.drawImage(logo,o,o,logoSize,logoSize,null); //关闭绘画对象 gs.dispose(); //把缓存区图片输出到内存当中 bufferedImage.flush(); try{ //把内存当中的图片输出到硬盘当中 ImageIO.write(bufferedImage,"png",new File("D:/qr.png")); } catch(IOException e){ e.printStackTrace(); } System.out.println("成功"); } public static void main(String[] args) throws IOException { String content1="BEGIN:VCARD\r\n" + "FN:姓名:刘嘉玲\r\n"+ "ORG:学校:河北科技师范学院 学院:数信\r\n"+ "TITLE:在校生\r\n" + "TEL;WORK;VOICE:1238\r\n"+ "TEL;HOME;VOICE:456\r\n"+ "TEL;CELL;VOICE:15533516959\r\n"+ "ADR;WORK:河北科技师范学院数信学院科技1603\r\n"+ "ADR;HOME:南院6号楼\r\n"+ "URL:http://www.百度.com\r\n"+ "EMAIL;HOME:244861262@qq.com\r\n" + "END:VCARD"; String imgPath="D:/qr.png"; int version=16; String startRgb="0,0,255"; String endRgb="255,0,0"; creatQRcode(content1,imgPath,version,startRgb,endRgb); } }
3,131
0.700323
0.670859
106
25.245283
20.626879
125
false
false
0
0
0
0
0
0
2.169811
false
false
15
2e1d4929cf578636bcf6f5749eebbb9057cad3bf
25,237,227,898,633
95e944448000c08dd3d6915abb468767c9f29d3c
/sources/com/p280ss/android/ugc/aweme/share/improve/pkg/UserSharePackage.java
3d210df06c819eedea26556dc2bbcb676bdd2c58
[]
no_license
xrealm/tiktok-src
https://github.com/xrealm/tiktok-src
261b1faaf7b39d64bb7cb4106dc1a35963bd6868
90f305b5f981d39cfb313d75ab231326c9fca597
refs/heads/master
2022-11-12T06:43:07.401000
2020-07-04T20:21:12
2020-07-04T20:21:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.p280ss.android.ugc.aweme.share.improve.pkg; import android.app.Activity; import android.content.Context; import android.os.Handler; import android.os.Parcel; import android.os.Parcelable.Creator; import android.text.TextUtils; import com.alibaba.fastjson.JSON; import com.bytedance.ies.abmock.C6384b; import com.bytedance.ies.dmt.p262ui.p563c.C10761a; import com.bytedance.ies.ugc.appcontext.C6399b; import com.p280ss.android.ugc.aweme.IAccountUserService; import com.p280ss.android.ugc.aweme.account.C21115b; import com.p280ss.android.ugc.aweme.account.C6861a; import com.p280ss.android.ugc.aweme.app.C22903bl; import com.p280ss.android.ugc.aweme.app.SharePrefCache; import com.p280ss.android.ugc.aweme.base.model.UrlModel; import com.p280ss.android.ugc.aweme.base.share.ShareInfo; import com.p280ss.android.ugc.aweme.common.C25652b; import com.p280ss.android.ugc.aweme.experiment.HidePushSettingsExperiment; import com.p280ss.android.ugc.aweme.feed.model.Aweme; import com.p280ss.android.ugc.aweme.feed.model.Video; import com.p280ss.android.ugc.aweme.feed.p1233i.C28442a; import com.p280ss.android.ugc.aweme.metrics.C33228ab; import com.p280ss.android.ugc.aweme.metrics.C33228ab.C33229a; import com.p280ss.android.ugc.aweme.p313im.C30553b; import com.p280ss.android.ugc.aweme.profile.model.GeneralPermission; import com.p280ss.android.ugc.aweme.profile.model.User; import com.p280ss.android.ugc.aweme.share.C37984ap; import com.p280ss.android.ugc.aweme.share.improve.CommonShareDialog; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38071ab; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38076af; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38090d; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38096f; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38129t; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38136x; import com.p280ss.android.ugc.aweme.share.improve.p1539b.C38142a; import com.p280ss.android.ugc.aweme.share.improve.p1539b.C38144b; import com.p280ss.android.ugc.aweme.share.improve.p1540c.C38157b; import com.p280ss.android.ugc.aweme.share.improve.p1540c.C38159c; import com.p280ss.android.ugc.aweme.sharer.C38343b; import com.p280ss.android.ugc.aweme.sharer.C38354f; import com.p280ss.android.ugc.aweme.sharer.C38356g; import com.p280ss.android.ugc.aweme.sharer.p338ui.C38380c; import com.p280ss.android.ugc.aweme.sharer.p338ui.C38380c.C38382b; import com.p280ss.android.ugc.aweme.sharer.p338ui.C38386d; import com.p280ss.android.ugc.aweme.sharer.p338ui.C38386d.C38387a; import com.p280ss.android.ugc.aweme.sharer.p338ui.C38389f; import com.p280ss.android.ugc.aweme.sharer.p338ui.SharePackage; import com.p280ss.android.ugc.aweme.sharer.p338ui.SharePackage.C7219a; import com.p280ss.android.ugc.aweme.utils.C43122ff; import com.zhiliaoapp.musically.df_live_zego_link.R; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import kotlin.jvm.internal.C7571f; import kotlin.jvm.internal.C7573i; /* renamed from: com.ss.android.ugc.aweme.share.improve.pkg.UserSharePackage */ public final class UserSharePackage extends SharePackage { public static final Creator<UserSharePackage> CREATOR = new C38230c(); /* renamed from: b */ public static final C38228b f99381b = new C38228b(null); /* renamed from: a */ public final User f99382a; /* renamed from: com.ss.android.ugc.aweme.share.improve.pkg.UserSharePackage$a */ public static final class C38227a extends C7219a<UserSharePackage> { /* renamed from: a */ public User f99383a; /* access modifiers changed from: private */ /* renamed from: b */ public UserSharePackage mo18866a() { return new UserSharePackage(this); } /* renamed from: a */ public final C38227a mo95814a(User user) { C7573i.m23587b(user, "user"); this.f99383a = user; return this; } /* renamed from: a */ public final C38227a mo18867b(Parcel parcel) { C7573i.m23587b(parcel, "source"); super.mo18867b(parcel); Serializable readSerializable = parcel.readSerializable(); if (!(readSerializable instanceof User)) { readSerializable = null; } this.f99383a = (User) readSerializable; return this; } } /* renamed from: com.ss.android.ugc.aweme.share.improve.pkg.UserSharePackage$b */ public static final class C38228b { /* renamed from: com.ss.android.ugc.aweme.share.improve.pkg.UserSharePackage$b$a */ public static final class C38229a implements C38386d { /* renamed from: a */ final /* synthetic */ UserSharePackage f99384a; /* renamed from: b */ final /* synthetic */ String f99385b; /* renamed from: c */ final /* synthetic */ Activity f99386c; /* renamed from: d */ final /* synthetic */ User f99387d; /* renamed from: e */ final /* synthetic */ Handler f99388e; /* renamed from: a */ public final void mo67217a(SharePackage sharePackage, Context context) { C7573i.m23587b(sharePackage, "sharePackage"); C7573i.m23587b(context, "context"); C38387a.m122614b(this, sharePackage, context); } /* renamed from: b */ public final void mo67219b(SharePackage sharePackage, Context context) { C7573i.m23587b(sharePackage, "sharePackage"); C7573i.m23587b(context, "context"); C38387a.m122613a(this, sharePackage, context); } /* renamed from: a */ public final void mo67218a(C38389f fVar, SharePackage sharePackage, Context context) { C7573i.m23587b(fVar, "action"); C7573i.m23587b(sharePackage, "sharePackage"); C7573i.m23587b(context, "context"); if (fVar instanceof C38090d) { C38228b.m122130a("copy", this.f99387d); m122132a(fVar.mo95715b(), true, sharePackage, context, this.f99387d); return; } if (fVar instanceof C38076af) { C38228b.m122130a("report", this.f99387d); } } /* renamed from: a */ public final void mo67216a(C38343b bVar, boolean z, SharePackage sharePackage, Context context) { C7573i.m23587b(bVar, "channel"); C7573i.m23587b(context, "context"); m122132a(bVar.mo95739b(), z, sharePackage, context, this.f99387d); if (bVar instanceof C38142a) { C38228b.m122130a("copy", this.f99387d); } } C38229a(UserSharePackage userSharePackage, String str, Activity activity, User user, Handler handler) { this.f99384a = userSharePackage; this.f99385b = str; this.f99386c = activity; this.f99387d = user; this.f99388e = handler; } /* renamed from: a */ private static void m122132a(String str, boolean z, SharePackage sharePackage, Context context, User user) { C7573i.m23587b(str, "channelKey"); C7573i.m23587b(context, "context"); if (z && C6399b.m19944t() && user != null) { C25652b bVar = new C25652b(); bVar.mo66536a(new C28442a()); bVar.mo56976a(user.getUid(), Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(-1), Integer.valueOf(-1), Integer.valueOf(4), str); } } } private C38228b() { } public /* synthetic */ C38228b(C7571f fVar) { this(); } /* renamed from: a */ public static void m122130a(String str, User user) { String str2; C7573i.m23587b(str, "type"); if (user != null) { C33229a b = C33228ab.m107200a("share_person").mo85057b("platform", str).mo85057b("target_id", user.getUid()); String str3 = "enter_from"; if (C43122ff.m136787r(user)) { str2 = "personal_homepage"; } else { str2 = "others_homepage"; } b.mo85057b(str3, str2).mo85252e(); } } /* renamed from: a */ private static UserSharePackage m122129a(User user, Context context, List<? extends Aweme> list) { boolean z; String str; C7573i.m23587b(user, "user"); C7573i.m23587b(context, "context"); C38227a a = new C38227a().mo95814a(user); String uid = user.getUid(); C7573i.m23582a((Object) uid, "user.uid"); String string = context.getString(R.string.jf); C7573i.m23582a((Object) string, "context.getString(R.string.app_name)"); C7219a a2 = a.mo18869e(uid).mo18865a("app_name", string); ShareInfo shareInfo = user.getShareInfo(); C7573i.m23582a((Object) shareInfo, "user.shareInfo"); String shareTitle = shareInfo.getShareTitle(); C7573i.m23582a((Object) shareTitle, "user.shareInfo.shareTitle"); C7219a f = a2.mo18870f(shareTitle); ShareInfo shareInfo2 = user.getShareInfo(); C7573i.m23582a((Object) shareInfo2, "user.shareInfo"); String shareWeiboDesc = shareInfo2.getShareWeiboDesc(); C7573i.m23582a((Object) shareWeiboDesc, "user.shareInfo.shareWeiboDesc"); C7219a g = f.mo18871g(shareWeiboDesc); ShareInfo shareInfo3 = user.getShareInfo(); C7573i.m23582a((Object) shareInfo3, "user.shareInfo"); String b = C38157b.m121908b(C38157b.m121905a(shareInfo3.getShareUrl())); if (b == null) { b = ""; } String uid2 = user.getUid(); C7573i.m23582a((Object) uid2, "user.uid"); C7219a a3 = g.mo18872h(b).mo18868d("user").mo18865a("uid", uid2); String str2 = "sec_user_id"; String secUid = user.getSecUid(); if (secUid == null) { secUid = ""; } String nickname = user.getNickname(); C7573i.m23582a((Object) nickname, "user.nickname"); C7219a a4 = a3.mo18865a(str2, secUid).mo18865a("name", nickname); String str3 = "desc"; CharSequence uniqueId = user.getUniqueId(); int i = 0; if (uniqueId == null || uniqueId.length() == 0) { z = true; } else { z = false; } if (z) { str = user.getShortId(); } else { str = user.getUniqueId(); } C7573i.m23582a((Object) str, "if (user.uniqueId.isNull…hortId else user.uniqueId"); C7219a a5 = a4.mo18865a(str3, str); if (!C43122ff.m136769b(user, C43122ff.m136787r(user)) && list != null && list.size() >= 3) { List arrayList = new ArrayList(); for (Aweme aweme : list) { if (aweme.getAwemeType() == 2) { UrlModel a6 = C38159c.m121913a(aweme); if (a6 != null) { arrayList.add(a6); } } else { Video video = aweme.getVideo(); C7573i.m23582a((Object) video, "aweme.video"); UrlModel cover = video.getCover(); C7573i.m23582a((Object) cover, "aweme.video.cover"); arrayList.add(cover); } i++; if (i >= 3) { break; } } if (arrayList.size() >= 3) { String jSONString = JSON.toJSONString(arrayList); C7573i.m23582a((Object) jSONString, "JSON.toJSONString(models)"); a5.mo18865a("aweme_cover_list", jSONString); } } UserSharePackage userSharePackage = (UserSharePackage) a5.mo18866a(); userSharePackage.f20186l.putSerializable("video_cover", user.getAvatarMedium()); return userSharePackage; } /* renamed from: a */ public final void mo95815a(Handler handler, Activity activity, User user, List<? extends Aweme> list, boolean z) { String str; String str2; Handler handler2 = handler; Activity activity2 = activity; User user2 = user; C7573i.m23587b(activity2, "activity"); if (user2 != null && user.getShareInfo() != null) { UserSharePackage a = m122129a(user2, activity2, list); if (C43122ff.m136787r(user)) { str = "personal_homepage"; } else { str = "others_homepage"; } String str3 = str; C38382b bVar = new C38382b(); SharePackage sharePackage = a; C38144b bVar2 = new C38144b(sharePackage, str3, 0, 4, null); bVar.mo95963a((C38343b) bVar2); C37984ap.m121301a().injectUniversalConfig(bVar, activity, true); GeneralPermission generalPermission = user.getGeneralPermission(); if (generalPermission != null) { str2 = generalPermission.getShareProfileToast(); } else { str2 = null; } boolean z2 = false; if (!TextUtils.isEmpty(str2)) { bVar.mo95977b(false); } if (C6861a.m21337f().isMe(user.getUid()) || !user.isSecret()) { bVar.mo95963a((C38343b) new C38142a()); } else { bVar.mo95974b(); bVar.mo95977b(false); } if (C6399b.m19946v() && !C43122ff.m136787r(user) && C6384b.m19835a().mo15287a(HidePushSettingsExperiment.class, true, "m_post_push_group", C6384b.m19835a().mo15295d().m_post_push_group, 1) != 3) { if (C43122ff.m136769b(user2, C6861a.m21337f().isMe(user.getUid()))) { if (C43122ff.m136761a(user.getFollowStatus())) { if (user.getWatchwStatus() == 1) { z2 = true; } bVar.mo95967a((C38389f) new C38136x(user2, z2)); } } else if (!user.isBlock()) { if (user.getWatchwStatus() == 1) { z2 = true; } bVar.mo95967a((C38389f) new C38136x(user2, z2)); } } if (handler2 != null) { bVar.mo95967a((C38389f) new C38076af(user2)); IAccountUserService a2 = C21115b.m71197a(); C7573i.m23582a((Object) a2, "AccountUserProxyService.get()"); if (a2.isLogin()) { bVar.mo95967a((C38389f) new C38096f(user2, handler2)); } if (!user2.isBlock && C30553b.m99785a() && !C43122ff.m136767b()) { bVar.mo95967a((C38389f) new C38129t(handler2)); } SharePrefCache inst = SharePrefCache.inst(); C7573i.m23582a((Object) inst, "SharePrefCache.inst()"); C22903bl removeFollowerSwitch = inst.getRemoveFollowerSwitch(); C7573i.m23582a((Object) removeFollowerSwitch, "SharePrefCache.inst().removeFollowerSwitch"); Object d = removeFollowerSwitch.mo59877d(); C7573i.m23582a(d, "SharePrefCache.inst().removeFollowerSwitch.cache"); if (((Boolean) d).booleanValue() && user.getFollowerStatus() == 1) { bVar.mo95967a((C38389f) new C38071ab(handler2)); } } bVar.mo95964a(sharePackage); C38229a aVar = new C38229a(a, str3, activity, user, handler); bVar.mo95966a((C38386d) aVar); C38380c a3 = bVar.mo95972a(); if (!activity.isFinishing()) { CommonShareDialog commonShareDialog = new CommonShareDialog(activity, a3, 0, 4, null); commonShareDialog.show(); } } } } /* renamed from: com.ss.android.ugc.aweme.share.improve.pkg.UserSharePackage$c */ public static final class C38230c implements Creator<UserSharePackage> { C38230c() { } /* renamed from: a */ private static UserSharePackage[] m122138a(int i) { return new UserSharePackage[i]; } public final /* synthetic */ Object createFromParcel(Parcel parcel) { return m122137a(parcel); } public final /* synthetic */ Object[] newArray(int i) { return m122138a(i); } /* renamed from: a */ private static UserSharePackage m122137a(Parcel parcel) { C7573i.m23587b(parcel, "parcel"); return new UserSharePackage(parcel); } } /* renamed from: a */ public static final void m122120a(Handler handler, Activity activity, User user, List<? extends Aweme> list, boolean z) { f99381b.mo95815a(handler, activity, user, list, z); } public final int describeContents() { return 0; } public UserSharePackage(Parcel parcel) { C7573i.m23587b(parcel, "parcel"); this(new C38227a().mo18867b(parcel)); } /* renamed from: a */ public final C38354f mo18860a(C38343b bVar) { C7573i.m23587b(bVar, "channel"); return new C38356g(C38159c.m121914a(this.f20185k, bVar), this.f20183i, this.f20184j); } public UserSharePackage(C38227a aVar) { C7573i.m23587b(aVar, "builder"); super(aVar); User user = aVar.f99383a; if (user == null) { C7573i.m23580a(); } this.f99382a = user; } public final void writeToParcel(Parcel parcel, int i) { super.writeToParcel(parcel, i); if (parcel != null) { parcel.writeSerializable(this.f99382a); } } /* renamed from: a */ public final boolean mo18862a(C38389f fVar, Context context) { CharSequence charSequence; C7573i.m23587b(fVar, "action"); C7573i.m23587b(context, "context"); if (fVar instanceof C38090d) { GeneralPermission generalPermission = this.f99382a.getGeneralPermission(); String str = null; if (generalPermission != null) { charSequence = generalPermission.getShareProfileToast(); } else { charSequence = null; } if (!TextUtils.isEmpty(charSequence)) { GeneralPermission generalPermission2 = this.f99382a.getGeneralPermission(); if (generalPermission2 != null) { str = generalPermission2.getShareProfileToast(); } C10761a.m31403c(context, str).mo25750a(); return true; } } return false; } /* renamed from: a */ public final boolean mo18861a(C38343b bVar, Context context) { CharSequence charSequence; C7573i.m23587b(bVar, "channel"); C7573i.m23587b(context, "context"); GeneralPermission generalPermission = this.f99382a.getGeneralPermission(); String str = null; if (generalPermission != null) { charSequence = generalPermission.getShareProfileToast(); } else { charSequence = null; } if (!TextUtils.isEmpty(charSequence)) { GeneralPermission generalPermission2 = this.f99382a.getGeneralPermission(); if (generalPermission2 != null) { str = generalPermission2.getShareProfileToast(); } C10761a.m31403c(context, str).mo25750a(); return true; } C37984ap.m121302b().addShareRecord(bVar.mo95739b(), 2); return false; } }
UTF-8
Java
20,814
java
UserSharePackage.java
Java
[]
null
[]
package com.p280ss.android.ugc.aweme.share.improve.pkg; import android.app.Activity; import android.content.Context; import android.os.Handler; import android.os.Parcel; import android.os.Parcelable.Creator; import android.text.TextUtils; import com.alibaba.fastjson.JSON; import com.bytedance.ies.abmock.C6384b; import com.bytedance.ies.dmt.p262ui.p563c.C10761a; import com.bytedance.ies.ugc.appcontext.C6399b; import com.p280ss.android.ugc.aweme.IAccountUserService; import com.p280ss.android.ugc.aweme.account.C21115b; import com.p280ss.android.ugc.aweme.account.C6861a; import com.p280ss.android.ugc.aweme.app.C22903bl; import com.p280ss.android.ugc.aweme.app.SharePrefCache; import com.p280ss.android.ugc.aweme.base.model.UrlModel; import com.p280ss.android.ugc.aweme.base.share.ShareInfo; import com.p280ss.android.ugc.aweme.common.C25652b; import com.p280ss.android.ugc.aweme.experiment.HidePushSettingsExperiment; import com.p280ss.android.ugc.aweme.feed.model.Aweme; import com.p280ss.android.ugc.aweme.feed.model.Video; import com.p280ss.android.ugc.aweme.feed.p1233i.C28442a; import com.p280ss.android.ugc.aweme.metrics.C33228ab; import com.p280ss.android.ugc.aweme.metrics.C33228ab.C33229a; import com.p280ss.android.ugc.aweme.p313im.C30553b; import com.p280ss.android.ugc.aweme.profile.model.GeneralPermission; import com.p280ss.android.ugc.aweme.profile.model.User; import com.p280ss.android.ugc.aweme.share.C37984ap; import com.p280ss.android.ugc.aweme.share.improve.CommonShareDialog; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38071ab; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38076af; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38090d; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38096f; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38129t; import com.p280ss.android.ugc.aweme.share.improve.p1538a.C38136x; import com.p280ss.android.ugc.aweme.share.improve.p1539b.C38142a; import com.p280ss.android.ugc.aweme.share.improve.p1539b.C38144b; import com.p280ss.android.ugc.aweme.share.improve.p1540c.C38157b; import com.p280ss.android.ugc.aweme.share.improve.p1540c.C38159c; import com.p280ss.android.ugc.aweme.sharer.C38343b; import com.p280ss.android.ugc.aweme.sharer.C38354f; import com.p280ss.android.ugc.aweme.sharer.C38356g; import com.p280ss.android.ugc.aweme.sharer.p338ui.C38380c; import com.p280ss.android.ugc.aweme.sharer.p338ui.C38380c.C38382b; import com.p280ss.android.ugc.aweme.sharer.p338ui.C38386d; import com.p280ss.android.ugc.aweme.sharer.p338ui.C38386d.C38387a; import com.p280ss.android.ugc.aweme.sharer.p338ui.C38389f; import com.p280ss.android.ugc.aweme.sharer.p338ui.SharePackage; import com.p280ss.android.ugc.aweme.sharer.p338ui.SharePackage.C7219a; import com.p280ss.android.ugc.aweme.utils.C43122ff; import com.zhiliaoapp.musically.df_live_zego_link.R; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import kotlin.jvm.internal.C7571f; import kotlin.jvm.internal.C7573i; /* renamed from: com.ss.android.ugc.aweme.share.improve.pkg.UserSharePackage */ public final class UserSharePackage extends SharePackage { public static final Creator<UserSharePackage> CREATOR = new C38230c(); /* renamed from: b */ public static final C38228b f99381b = new C38228b(null); /* renamed from: a */ public final User f99382a; /* renamed from: com.ss.android.ugc.aweme.share.improve.pkg.UserSharePackage$a */ public static final class C38227a extends C7219a<UserSharePackage> { /* renamed from: a */ public User f99383a; /* access modifiers changed from: private */ /* renamed from: b */ public UserSharePackage mo18866a() { return new UserSharePackage(this); } /* renamed from: a */ public final C38227a mo95814a(User user) { C7573i.m23587b(user, "user"); this.f99383a = user; return this; } /* renamed from: a */ public final C38227a mo18867b(Parcel parcel) { C7573i.m23587b(parcel, "source"); super.mo18867b(parcel); Serializable readSerializable = parcel.readSerializable(); if (!(readSerializable instanceof User)) { readSerializable = null; } this.f99383a = (User) readSerializable; return this; } } /* renamed from: com.ss.android.ugc.aweme.share.improve.pkg.UserSharePackage$b */ public static final class C38228b { /* renamed from: com.ss.android.ugc.aweme.share.improve.pkg.UserSharePackage$b$a */ public static final class C38229a implements C38386d { /* renamed from: a */ final /* synthetic */ UserSharePackage f99384a; /* renamed from: b */ final /* synthetic */ String f99385b; /* renamed from: c */ final /* synthetic */ Activity f99386c; /* renamed from: d */ final /* synthetic */ User f99387d; /* renamed from: e */ final /* synthetic */ Handler f99388e; /* renamed from: a */ public final void mo67217a(SharePackage sharePackage, Context context) { C7573i.m23587b(sharePackage, "sharePackage"); C7573i.m23587b(context, "context"); C38387a.m122614b(this, sharePackage, context); } /* renamed from: b */ public final void mo67219b(SharePackage sharePackage, Context context) { C7573i.m23587b(sharePackage, "sharePackage"); C7573i.m23587b(context, "context"); C38387a.m122613a(this, sharePackage, context); } /* renamed from: a */ public final void mo67218a(C38389f fVar, SharePackage sharePackage, Context context) { C7573i.m23587b(fVar, "action"); C7573i.m23587b(sharePackage, "sharePackage"); C7573i.m23587b(context, "context"); if (fVar instanceof C38090d) { C38228b.m122130a("copy", this.f99387d); m122132a(fVar.mo95715b(), true, sharePackage, context, this.f99387d); return; } if (fVar instanceof C38076af) { C38228b.m122130a("report", this.f99387d); } } /* renamed from: a */ public final void mo67216a(C38343b bVar, boolean z, SharePackage sharePackage, Context context) { C7573i.m23587b(bVar, "channel"); C7573i.m23587b(context, "context"); m122132a(bVar.mo95739b(), z, sharePackage, context, this.f99387d); if (bVar instanceof C38142a) { C38228b.m122130a("copy", this.f99387d); } } C38229a(UserSharePackage userSharePackage, String str, Activity activity, User user, Handler handler) { this.f99384a = userSharePackage; this.f99385b = str; this.f99386c = activity; this.f99387d = user; this.f99388e = handler; } /* renamed from: a */ private static void m122132a(String str, boolean z, SharePackage sharePackage, Context context, User user) { C7573i.m23587b(str, "channelKey"); C7573i.m23587b(context, "context"); if (z && C6399b.m19944t() && user != null) { C25652b bVar = new C25652b(); bVar.mo66536a(new C28442a()); bVar.mo56976a(user.getUid(), Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(-1), Integer.valueOf(-1), Integer.valueOf(4), str); } } } private C38228b() { } public /* synthetic */ C38228b(C7571f fVar) { this(); } /* renamed from: a */ public static void m122130a(String str, User user) { String str2; C7573i.m23587b(str, "type"); if (user != null) { C33229a b = C33228ab.m107200a("share_person").mo85057b("platform", str).mo85057b("target_id", user.getUid()); String str3 = "enter_from"; if (C43122ff.m136787r(user)) { str2 = "personal_homepage"; } else { str2 = "others_homepage"; } b.mo85057b(str3, str2).mo85252e(); } } /* renamed from: a */ private static UserSharePackage m122129a(User user, Context context, List<? extends Aweme> list) { boolean z; String str; C7573i.m23587b(user, "user"); C7573i.m23587b(context, "context"); C38227a a = new C38227a().mo95814a(user); String uid = user.getUid(); C7573i.m23582a((Object) uid, "user.uid"); String string = context.getString(R.string.jf); C7573i.m23582a((Object) string, "context.getString(R.string.app_name)"); C7219a a2 = a.mo18869e(uid).mo18865a("app_name", string); ShareInfo shareInfo = user.getShareInfo(); C7573i.m23582a((Object) shareInfo, "user.shareInfo"); String shareTitle = shareInfo.getShareTitle(); C7573i.m23582a((Object) shareTitle, "user.shareInfo.shareTitle"); C7219a f = a2.mo18870f(shareTitle); ShareInfo shareInfo2 = user.getShareInfo(); C7573i.m23582a((Object) shareInfo2, "user.shareInfo"); String shareWeiboDesc = shareInfo2.getShareWeiboDesc(); C7573i.m23582a((Object) shareWeiboDesc, "user.shareInfo.shareWeiboDesc"); C7219a g = f.mo18871g(shareWeiboDesc); ShareInfo shareInfo3 = user.getShareInfo(); C7573i.m23582a((Object) shareInfo3, "user.shareInfo"); String b = C38157b.m121908b(C38157b.m121905a(shareInfo3.getShareUrl())); if (b == null) { b = ""; } String uid2 = user.getUid(); C7573i.m23582a((Object) uid2, "user.uid"); C7219a a3 = g.mo18872h(b).mo18868d("user").mo18865a("uid", uid2); String str2 = "sec_user_id"; String secUid = user.getSecUid(); if (secUid == null) { secUid = ""; } String nickname = user.getNickname(); C7573i.m23582a((Object) nickname, "user.nickname"); C7219a a4 = a3.mo18865a(str2, secUid).mo18865a("name", nickname); String str3 = "desc"; CharSequence uniqueId = user.getUniqueId(); int i = 0; if (uniqueId == null || uniqueId.length() == 0) { z = true; } else { z = false; } if (z) { str = user.getShortId(); } else { str = user.getUniqueId(); } C7573i.m23582a((Object) str, "if (user.uniqueId.isNull…hortId else user.uniqueId"); C7219a a5 = a4.mo18865a(str3, str); if (!C43122ff.m136769b(user, C43122ff.m136787r(user)) && list != null && list.size() >= 3) { List arrayList = new ArrayList(); for (Aweme aweme : list) { if (aweme.getAwemeType() == 2) { UrlModel a6 = C38159c.m121913a(aweme); if (a6 != null) { arrayList.add(a6); } } else { Video video = aweme.getVideo(); C7573i.m23582a((Object) video, "aweme.video"); UrlModel cover = video.getCover(); C7573i.m23582a((Object) cover, "aweme.video.cover"); arrayList.add(cover); } i++; if (i >= 3) { break; } } if (arrayList.size() >= 3) { String jSONString = JSON.toJSONString(arrayList); C7573i.m23582a((Object) jSONString, "JSON.toJSONString(models)"); a5.mo18865a("aweme_cover_list", jSONString); } } UserSharePackage userSharePackage = (UserSharePackage) a5.mo18866a(); userSharePackage.f20186l.putSerializable("video_cover", user.getAvatarMedium()); return userSharePackage; } /* renamed from: a */ public final void mo95815a(Handler handler, Activity activity, User user, List<? extends Aweme> list, boolean z) { String str; String str2; Handler handler2 = handler; Activity activity2 = activity; User user2 = user; C7573i.m23587b(activity2, "activity"); if (user2 != null && user.getShareInfo() != null) { UserSharePackage a = m122129a(user2, activity2, list); if (C43122ff.m136787r(user)) { str = "personal_homepage"; } else { str = "others_homepage"; } String str3 = str; C38382b bVar = new C38382b(); SharePackage sharePackage = a; C38144b bVar2 = new C38144b(sharePackage, str3, 0, 4, null); bVar.mo95963a((C38343b) bVar2); C37984ap.m121301a().injectUniversalConfig(bVar, activity, true); GeneralPermission generalPermission = user.getGeneralPermission(); if (generalPermission != null) { str2 = generalPermission.getShareProfileToast(); } else { str2 = null; } boolean z2 = false; if (!TextUtils.isEmpty(str2)) { bVar.mo95977b(false); } if (C6861a.m21337f().isMe(user.getUid()) || !user.isSecret()) { bVar.mo95963a((C38343b) new C38142a()); } else { bVar.mo95974b(); bVar.mo95977b(false); } if (C6399b.m19946v() && !C43122ff.m136787r(user) && C6384b.m19835a().mo15287a(HidePushSettingsExperiment.class, true, "m_post_push_group", C6384b.m19835a().mo15295d().m_post_push_group, 1) != 3) { if (C43122ff.m136769b(user2, C6861a.m21337f().isMe(user.getUid()))) { if (C43122ff.m136761a(user.getFollowStatus())) { if (user.getWatchwStatus() == 1) { z2 = true; } bVar.mo95967a((C38389f) new C38136x(user2, z2)); } } else if (!user.isBlock()) { if (user.getWatchwStatus() == 1) { z2 = true; } bVar.mo95967a((C38389f) new C38136x(user2, z2)); } } if (handler2 != null) { bVar.mo95967a((C38389f) new C38076af(user2)); IAccountUserService a2 = C21115b.m71197a(); C7573i.m23582a((Object) a2, "AccountUserProxyService.get()"); if (a2.isLogin()) { bVar.mo95967a((C38389f) new C38096f(user2, handler2)); } if (!user2.isBlock && C30553b.m99785a() && !C43122ff.m136767b()) { bVar.mo95967a((C38389f) new C38129t(handler2)); } SharePrefCache inst = SharePrefCache.inst(); C7573i.m23582a((Object) inst, "SharePrefCache.inst()"); C22903bl removeFollowerSwitch = inst.getRemoveFollowerSwitch(); C7573i.m23582a((Object) removeFollowerSwitch, "SharePrefCache.inst().removeFollowerSwitch"); Object d = removeFollowerSwitch.mo59877d(); C7573i.m23582a(d, "SharePrefCache.inst().removeFollowerSwitch.cache"); if (((Boolean) d).booleanValue() && user.getFollowerStatus() == 1) { bVar.mo95967a((C38389f) new C38071ab(handler2)); } } bVar.mo95964a(sharePackage); C38229a aVar = new C38229a(a, str3, activity, user, handler); bVar.mo95966a((C38386d) aVar); C38380c a3 = bVar.mo95972a(); if (!activity.isFinishing()) { CommonShareDialog commonShareDialog = new CommonShareDialog(activity, a3, 0, 4, null); commonShareDialog.show(); } } } } /* renamed from: com.ss.android.ugc.aweme.share.improve.pkg.UserSharePackage$c */ public static final class C38230c implements Creator<UserSharePackage> { C38230c() { } /* renamed from: a */ private static UserSharePackage[] m122138a(int i) { return new UserSharePackage[i]; } public final /* synthetic */ Object createFromParcel(Parcel parcel) { return m122137a(parcel); } public final /* synthetic */ Object[] newArray(int i) { return m122138a(i); } /* renamed from: a */ private static UserSharePackage m122137a(Parcel parcel) { C7573i.m23587b(parcel, "parcel"); return new UserSharePackage(parcel); } } /* renamed from: a */ public static final void m122120a(Handler handler, Activity activity, User user, List<? extends Aweme> list, boolean z) { f99381b.mo95815a(handler, activity, user, list, z); } public final int describeContents() { return 0; } public UserSharePackage(Parcel parcel) { C7573i.m23587b(parcel, "parcel"); this(new C38227a().mo18867b(parcel)); } /* renamed from: a */ public final C38354f mo18860a(C38343b bVar) { C7573i.m23587b(bVar, "channel"); return new C38356g(C38159c.m121914a(this.f20185k, bVar), this.f20183i, this.f20184j); } public UserSharePackage(C38227a aVar) { C7573i.m23587b(aVar, "builder"); super(aVar); User user = aVar.f99383a; if (user == null) { C7573i.m23580a(); } this.f99382a = user; } public final void writeToParcel(Parcel parcel, int i) { super.writeToParcel(parcel, i); if (parcel != null) { parcel.writeSerializable(this.f99382a); } } /* renamed from: a */ public final boolean mo18862a(C38389f fVar, Context context) { CharSequence charSequence; C7573i.m23587b(fVar, "action"); C7573i.m23587b(context, "context"); if (fVar instanceof C38090d) { GeneralPermission generalPermission = this.f99382a.getGeneralPermission(); String str = null; if (generalPermission != null) { charSequence = generalPermission.getShareProfileToast(); } else { charSequence = null; } if (!TextUtils.isEmpty(charSequence)) { GeneralPermission generalPermission2 = this.f99382a.getGeneralPermission(); if (generalPermission2 != null) { str = generalPermission2.getShareProfileToast(); } C10761a.m31403c(context, str).mo25750a(); return true; } } return false; } /* renamed from: a */ public final boolean mo18861a(C38343b bVar, Context context) { CharSequence charSequence; C7573i.m23587b(bVar, "channel"); C7573i.m23587b(context, "context"); GeneralPermission generalPermission = this.f99382a.getGeneralPermission(); String str = null; if (generalPermission != null) { charSequence = generalPermission.getShareProfileToast(); } else { charSequence = null; } if (!TextUtils.isEmpty(charSequence)) { GeneralPermission generalPermission2 = this.f99382a.getGeneralPermission(); if (generalPermission2 != null) { str = generalPermission2.getShareProfileToast(); } C10761a.m31403c(context, str).mo25750a(); return true; } C37984ap.m121302b().addShareRecord(bVar.mo95739b(), 2); return false; } }
20,814
0.569719
0.474053
484
42
27.952366
212
false
false
0
0
0
0
0
0
0.826446
false
false
15
7e7fa6e1d0c3b6bfaed985fdf7c736f0f8ff26f5
42,949,742,097
012c90ea8955abb8bca532bd2511de6f24b56960
/tests/TeamTests.java
204ea914c1111d2e24eae65142461f0e1ca68b55
[]
no_license
michaelcmkay/NarratorTester
https://github.com/michaelcmkay/NarratorTester
5ab393506b180e0bcd72d2a9b39ed8c7e9c75644
5174107a94ccc0a756710b6b36eac358006dcffa
refs/heads/master
2018-02-07T19:11:45.070000
2018-02-03T21:51:07
2018-02-03T21:51:07
46,630,287
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tests; import shared.logic.Player; import shared.logic.Team; import shared.logic.exceptions.NamingException; import shared.logic.exceptions.TeamSettingsException; import shared.logic.support.Constants; import shared.logic.templates.BasicRoles; import shared.setups.GoT; import shared.setups.Setup; public class TeamTests extends SuperTest { public TeamTests(String name) { super(name); } public void testChangeColor(){ super.internetToDo(null); assertNotNull(n.getTeam(Setup.TOWN_C)); try{ n.addTeam(Setup.TOWN_C); fail(); }catch(NamingException e){} } public void testChangeColorTeamAfterStart(){ addPlayer(BasicRoles.SerialKiller()); addPlayer(BasicRoles.Tailor()); addPlayer(BasicRoles.SerialKiller()); nightStart(); try{ n.getTeam(Setup.THREAT_C).setColor(GoT.baratheon_c); fail(); }catch(TeamSettingsException e){} try{ n.getTeam(Setup.THREAT_C).setName("Joe"); fail(); }catch(TeamSettingsException e){} } public void testInvalidTeamColor(){ super.internetToDo(null); tryTeamColor(null); tryTeamColor(Setup.MAFIA_C); tryTeamColor("#234"); tryTeamColor(Constants.A_NEUTRAL); tryTeamColor(Constants.A_RANDOM); tryTeamColor(Constants.A_SKIP); tryTeamColor("FFFFFE", GOOD); tryTeamColor("Fd1ddd", GOOD); } private static final boolean GOOD = true, BAD = false; private void tryTeamColor(String color){ tryTeamColor(color, BAD); } private void tryTeamColor(String color, boolean isGoodColor){ try{ color = n.getTeam(Setup.TOWN_C).setColor(color); if(!isGoodColor) fail(); n.getTeam(color).setColor(Setup.TOWN_C); }catch(TeamSettingsException e){ if(isGoodColor) fail(); } } public void testInvalidTeamName(){ String name = "Crypt"; String tName = "TheTeam"; n.addPlayer(name); n.addRole(BasicRoles.Doctor()); Team t = n.addTeam("#ff0011"); try{t.setName(name); fail(); }catch(NamingException e){} t.setName(tName); Team t2 = n.addTeam("#fe0021"); try{ t2.setName(tName); fail(); }catch(NamingException e){} try{ t2.setName("Randoms"); fail(); }catch(NamingException e){} try{ t2.setName("Random"); fail(); }catch(NamingException e){} try{ t2.setName("Neutrals"); fail(); }catch(NamingException e){} try{ t2.setName("Neutral"); fail(); }catch(NamingException e){} try{ t2.setName(BasicRoles.Doctor().getName()); fail(); }catch(NamingException e){} } public void testPrefersChanging(){ Player p = addPlayer("joe"); p.teamPrefer(Setup.TOWN_C); assertTrue(p._tPrefers.contains(Setup.TOWN_C)); addRole(BasicRoles.Sheriff()); String newColor = "#E04908"; n.getTeam(Setup.TOWN_C).setColor(newColor); assertTrue(p._tPrefers.contains(newColor)); assertEquals(newColor, n.getRolesList().get(0).getColor()); n.getTeam(newColor).setColor(Setup.TOWN_C); n.getTeam(Setup.MAFIA_C).setColor(newColor); } public void testTeamEnemyAndDetectablesChanging(){ super.internetToDo(null); String newColor = "#E04908"; n.getTeam(Setup.MAFIA_C).setColor(newColor); assertTrue(n.getTeam(Setup.TOWN_C).isEnemy(newColor)); assertTrue(n.getTeam(Setup.TOWN_C).sheriffDetects(newColor)); } }
UTF-8
Java
3,345
java
TeamTests.java
Java
[ { "context": "}\n\t\t\n\t\ttry{\n\t\t\tn.getTeam(Setup.THREAT_C).setName(\"Joe\");\n\t\t\tfail();\n\t\t}catch(TeamSettingsException e){}", "end": 933, "score": 0.9991803765296936, "start": 930, "tag": "NAME", "value": "Joe" }, { "context": "blic void testInvalidTeamName(){\n\t\tStrin...
null
[]
package tests; import shared.logic.Player; import shared.logic.Team; import shared.logic.exceptions.NamingException; import shared.logic.exceptions.TeamSettingsException; import shared.logic.support.Constants; import shared.logic.templates.BasicRoles; import shared.setups.GoT; import shared.setups.Setup; public class TeamTests extends SuperTest { public TeamTests(String name) { super(name); } public void testChangeColor(){ super.internetToDo(null); assertNotNull(n.getTeam(Setup.TOWN_C)); try{ n.addTeam(Setup.TOWN_C); fail(); }catch(NamingException e){} } public void testChangeColorTeamAfterStart(){ addPlayer(BasicRoles.SerialKiller()); addPlayer(BasicRoles.Tailor()); addPlayer(BasicRoles.SerialKiller()); nightStart(); try{ n.getTeam(Setup.THREAT_C).setColor(GoT.baratheon_c); fail(); }catch(TeamSettingsException e){} try{ n.getTeam(Setup.THREAT_C).setName("Joe"); fail(); }catch(TeamSettingsException e){} } public void testInvalidTeamColor(){ super.internetToDo(null); tryTeamColor(null); tryTeamColor(Setup.MAFIA_C); tryTeamColor("#234"); tryTeamColor(Constants.A_NEUTRAL); tryTeamColor(Constants.A_RANDOM); tryTeamColor(Constants.A_SKIP); tryTeamColor("FFFFFE", GOOD); tryTeamColor("Fd1ddd", GOOD); } private static final boolean GOOD = true, BAD = false; private void tryTeamColor(String color){ tryTeamColor(color, BAD); } private void tryTeamColor(String color, boolean isGoodColor){ try{ color = n.getTeam(Setup.TOWN_C).setColor(color); if(!isGoodColor) fail(); n.getTeam(color).setColor(Setup.TOWN_C); }catch(TeamSettingsException e){ if(isGoodColor) fail(); } } public void testInvalidTeamName(){ String name = "Crypt"; String tName = "TheTeam"; n.addPlayer(name); n.addRole(BasicRoles.Doctor()); Team t = n.addTeam("#ff0011"); try{t.setName(name); fail(); }catch(NamingException e){} t.setName(tName); Team t2 = n.addTeam("#fe0021"); try{ t2.setName(tName); fail(); }catch(NamingException e){} try{ t2.setName("Randoms"); fail(); }catch(NamingException e){} try{ t2.setName("Random"); fail(); }catch(NamingException e){} try{ t2.setName("Neutrals"); fail(); }catch(NamingException e){} try{ t2.setName("Neutral"); fail(); }catch(NamingException e){} try{ t2.setName(BasicRoles.Doctor().getName()); fail(); }catch(NamingException e){} } public void testPrefersChanging(){ Player p = addPlayer("joe"); p.teamPrefer(Setup.TOWN_C); assertTrue(p._tPrefers.contains(Setup.TOWN_C)); addRole(BasicRoles.Sheriff()); String newColor = "#E04908"; n.getTeam(Setup.TOWN_C).setColor(newColor); assertTrue(p._tPrefers.contains(newColor)); assertEquals(newColor, n.getRolesList().get(0).getColor()); n.getTeam(newColor).setColor(Setup.TOWN_C); n.getTeam(Setup.MAFIA_C).setColor(newColor); } public void testTeamEnemyAndDetectablesChanging(){ super.internetToDo(null); String newColor = "#E04908"; n.getTeam(Setup.MAFIA_C).setColor(newColor); assertTrue(n.getTeam(Setup.TOWN_C).isEnemy(newColor)); assertTrue(n.getTeam(Setup.TOWN_C).sheriffDetects(newColor)); } }
3,345
0.673842
0.664873
139
23.071943
17.147535
64
false
false
0
0
0
0
0
0
2.115108
false
false
15
1ded2ef0e99be9cf8f94faab6b6028c8884efad5
16,252,156,255,675
99343c5809b930f9946c3872f6e4ba4c4e7cf572
/src/main/java/com/moglix/salesops/service/CatalogueService.java
c8b448b1a8df465f29bd0f2a58c5423fd35290e1
[]
no_license
ravi282/gradlepro
https://github.com/ravi282/gradlepro
aa2d885a40cc109318e9c08285550daa5ae6da51
9ea0cfbd762951aaa75ad40360fcd472d5086070
refs/heads/master
2020-07-22T14:45:53.711000
2019-09-09T06:15:24
2019-09-09T06:15:24
207,237,138
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.moglix.salesops.service; import com.google.gson.Gson; import com.moglix.salesops.constant.Constants; import com.moglix.salesops.dto.catalogue.AssignUomRequestDto; import com.moglix.salesops.dto.catalogue.CatalogueApiResponse; import com.moglix.salesops.dto.catalogue.ItemRefMsnInfoDto; import com.moglix.salesops.dto.catalogue.MsnGroupUomInfoDto; import com.moglix.salesops.dto.core.ApiResponse; import com.moglix.salesops.entity.ApplicationUser; import com.moglix.salesops.entity.OrderItemInfo; import com.moglix.salesops.repository.OrderItemInfoRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; @Service public class CatalogueService { private static final Logger logger = LoggerFactory.getLogger(CatalogueService.class); @Value ("${sops.catalogue.uom.url}") private String CATALOGUE_UOM_URI; @Value ("${sops.catalogue.msn.url}") private String CATALOGUE_MSN_URI; /* @Value ("${sops.invalid.groupedmsn.conversionfactor.email}") private String GROUPED_MSN_INVALID_CONVERSION_FACTOR_EMAIL;*/ private MessageByLocaleService localeService; private RestTemplate restTemplate; private OrderItemInfoRepository orderItemInfoRepository; private EmailService emailService; @Autowired public CatalogueService(RestTemplate restTemplate, MessageByLocaleService localeService, OrderItemInfoRepository orderItemInfoRepository, EmailService emailService) { this.restTemplate = restTemplate; this.localeService = localeService; this.orderItemInfoRepository = orderItemInfoRepository; this.emailService = emailService; } public ApiResponse getUomDetails(String msn) { try { logger.info("Catalog request : fetch uoms of msn " + new Gson().toJson(new MsnGroupUomInfoDto(msn))); CatalogueApiResponse apiResponse = restTemplate.postForObject(CATALOGUE_UOM_URI + Constants.PATH_CATALOGUE_FETCH_UOM, new MsnGroupUomInfoDto(msn), CatalogueApiResponse.class); logger.info("Catalog response : fetch uoms of msn " + new Gson().toJson(apiResponse)); if (apiResponse.getStatus()) { List<MsnGroupUomInfoDto> uomList = apiResponse.getMsnGroupUomInfoDto(); // if it is single MSN and conversion factor = 0,then we should change to 1 // if it is grouped MSN check for msn's having conversion factor= 0,then send an email if (!apiResponse.getGroupFlag()) { for (MsnGroupUomInfoDto uom : uomList) { if (uom.getConversionFactor() == null || uom.getConversionFactor() == 0) uom.setConversionFactor(1); } } else { List<MsnGroupUomInfoDto> inValidUomList = uomList.parallelStream().filter(uom -> uom.getConversionFactor() == null || uom.getConversionFactor() == 0).collect(Collectors.toList()); /*if (inValidUomList.size() > 0) { CompletableFuture.supplyAsync(() -> emailService.sendEmail(new EmailBean(GROUPED_MSN_INVALID_CONVERSION_FACTOR_EMAIL, Constants.GROUPED_MSN_INVALID_CONVERSION_FACTOR_EMAIL_SUBJECT, String.format("%s doesn't have valid conversion factors in catalogue system!", inValidUomList.parallelStream().map(uom -> uom.getMsn()).collect(Collectors.joining(",")))))); }*/ } return new ApiResponse(HttpStatus.OK, Constants.ResponseStatus.SUCCESS, uomList); } else return new ApiResponse(HttpStatus.NOT_FOUND, Constants.ResponseStatus.WARNING, StringUtils.isEmpty(apiResponse.getMessage()) ? localeService.getMessage("catalogue.uom.notfound") : apiResponse.getMessage()); } catch (RestClientException re) { logger.error(String.format("Something went wrong while fetching uom list for MSN : %s from catalogue system!, %s", msn, re.getMessage())); re.printStackTrace(); return new ApiResponse(HttpStatus.INTERNAL_SERVER_ERROR, Constants.ResponseStatus.ERROR, localeService.getMessage("catalogue.uom.error")); } } /** * Method to itemref to catalogue system to get the msn,version and id * * @param orderItemInfo */ public OrderItemInfo syncVersionAgainstItemRef(OrderItemInfo orderItemInfo) { CatalogueApiResponse apiResponse = this.fetchMsnAgainstItemRef(Arrays.asList(orderItemInfo.getCustomerPoItemId())); if (apiResponse.getStatus()) { Optional<ItemRefMsnInfoDto> msnInfo = apiResponse.getItemRefMsnInfoList().parallelStream() .filter(itemRefMsn -> itemRefMsn.getItemId().equalsIgnoreCase(orderItemInfo.getCustomerPoItemId())).findFirst(); if (msnInfo.isPresent()) { ItemRefMsnInfoDto msnInfoDto = msnInfo.get(); orderItemInfo.setCpnId(msnInfoDto.getId()); orderItemInfo.setCpnVersion(msnInfoDto.getVersion()); } } return orderItemInfo; } private CatalogueApiResponse fetchMsnAgainstItemRef(List<String> itemRefs) { logger.info("Catalogue request for fetch msn against itemref : " + new ItemRefMsnInfoDto(itemRefs)); CatalogueApiResponse apiResponse = null; try { apiResponse = restTemplate.postForObject(CATALOGUE_MSN_URI + Constants.PATH_CATALOGUE_FETCH_MSN, new ItemRefMsnInfoDto(itemRefs), CatalogueApiResponse.class); logger.info("catalog response for fetch msn against itemref : " + new Gson().toJson(apiResponse)); } catch (RestClientException re) { logger.error(String.format("Something went wrong while fetching MSN against itemRefs : %s from catalogue system!", itemRefs.toString())); re.printStackTrace(); } return apiResponse; } public ApiResponse assignUom(MsnGroupUomInfoDto msnGroupUomInfoDto, OrderItemInfo orderItemInfo, ApplicationUser loggedInUser) { try { logger.info("Catalogue request for Assign UOM : " + new Gson().toJson(new AssignUomRequestDto(msnGroupUomInfoDto, orderItemInfo, loggedInUser))); CatalogueApiResponse apiResponse = restTemplate.postForObject(CATALOGUE_MSN_URI + Constants.PATH_CATALOGUE_ASSIGN_UOM, new AssignUomRequestDto(msnGroupUomInfoDto, orderItemInfo, loggedInUser), CatalogueApiResponse.class); logger.info("Catalogue response for Assign UOM : " + new Gson().toJson(apiResponse)); if (apiResponse.getStatus()) return new ApiResponse(HttpStatus.OK, Constants.ResponseStatus.SUCCESS, null); else return new ApiResponse(HttpStatus.INTERNAL_SERVER_ERROR, Constants.ResponseStatus.WARNING, StringUtils.isEmpty(apiResponse.getMessage()) ? localeService.getMessage("catalogue.uom.assign.error") : "Catalogue system : " + apiResponse.getMessage()); } catch (RestClientException re) { logger.error(String.format("Something went wrong while pushing UOM assignment details to catalogue system for order item : %s", orderItemInfo.getCustomerPoItemId())); re.printStackTrace(); return new ApiResponse(HttpStatus.INTERNAL_SERVER_ERROR, Constants.ResponseStatus.ERROR, localeService.getMessage("catalogue.uom.assign.error")); } } public CatalogueApiResponse isOrderItemEligibleToAssignMsn(ItemRefMsnInfoDto itemRefMsnInfoDto) { if (StringUtils.isEmpty(itemRefMsnInfoDto.getItemRef())) { logger.warn("itemref is required!"); return new CatalogueApiResponse(Boolean.FALSE, null, "itemref is required!"); } Optional<OrderItemInfo> orderItemOptional = orderItemInfoRepository.findOneByCustomerPoItemId(itemRefMsnInfoDto.getItemRef()); if (!orderItemOptional.isPresent()) { logger.warn(String.format("itemref %s not exist in salesops system", itemRefMsnInfoDto.getItemRef())); return new CatalogueApiResponse(Boolean.FALSE, itemRefMsnInfoDto.getItemRef(), String.format("itemref %s not exist in salesops system", itemRefMsnInfoDto.getItemRef())); } OrderItemInfo orderItemInfo = orderItemOptional.get(); boolean isEligible = Stream.of(Constants.OrderItemStatus.MSN_NOT_AVAILABLE, Constants.OrderItemStatus.UOM_NOT_AVAILABLE) .anyMatch(status -> status.equals(orderItemInfo.getStatus())); if (isEligible) { logger.info(String.format("itemref %s is eligible to assign msn", itemRefMsnInfoDto.getItemRef()), itemRefMsnInfoDto.getItemRef()); return new CatalogueApiResponse(Boolean.TRUE, itemRefMsnInfoDto.getItemRef(), String.format("itemref %s is eligible to assign msn", itemRefMsnInfoDto.getItemRef())); } logger.warn(String.format("itemref %s is not eligible to assign msn", itemRefMsnInfoDto.getItemRef()), itemRefMsnInfoDto.getItemRef()); return new CatalogueApiResponse(Boolean.FALSE, itemRefMsnInfoDto.getItemRef(), String.format("itemref %s is not eligible to assign msn", itemRefMsnInfoDto.getItemRef())); } }
UTF-8
Java
9,648
java
CatalogueService.java
Java
[]
null
[]
package com.moglix.salesops.service; import com.google.gson.Gson; import com.moglix.salesops.constant.Constants; import com.moglix.salesops.dto.catalogue.AssignUomRequestDto; import com.moglix.salesops.dto.catalogue.CatalogueApiResponse; import com.moglix.salesops.dto.catalogue.ItemRefMsnInfoDto; import com.moglix.salesops.dto.catalogue.MsnGroupUomInfoDto; import com.moglix.salesops.dto.core.ApiResponse; import com.moglix.salesops.entity.ApplicationUser; import com.moglix.salesops.entity.OrderItemInfo; import com.moglix.salesops.repository.OrderItemInfoRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; @Service public class CatalogueService { private static final Logger logger = LoggerFactory.getLogger(CatalogueService.class); @Value ("${sops.catalogue.uom.url}") private String CATALOGUE_UOM_URI; @Value ("${sops.catalogue.msn.url}") private String CATALOGUE_MSN_URI; /* @Value ("${sops.invalid.groupedmsn.conversionfactor.email}") private String GROUPED_MSN_INVALID_CONVERSION_FACTOR_EMAIL;*/ private MessageByLocaleService localeService; private RestTemplate restTemplate; private OrderItemInfoRepository orderItemInfoRepository; private EmailService emailService; @Autowired public CatalogueService(RestTemplate restTemplate, MessageByLocaleService localeService, OrderItemInfoRepository orderItemInfoRepository, EmailService emailService) { this.restTemplate = restTemplate; this.localeService = localeService; this.orderItemInfoRepository = orderItemInfoRepository; this.emailService = emailService; } public ApiResponse getUomDetails(String msn) { try { logger.info("Catalog request : fetch uoms of msn " + new Gson().toJson(new MsnGroupUomInfoDto(msn))); CatalogueApiResponse apiResponse = restTemplate.postForObject(CATALOGUE_UOM_URI + Constants.PATH_CATALOGUE_FETCH_UOM, new MsnGroupUomInfoDto(msn), CatalogueApiResponse.class); logger.info("Catalog response : fetch uoms of msn " + new Gson().toJson(apiResponse)); if (apiResponse.getStatus()) { List<MsnGroupUomInfoDto> uomList = apiResponse.getMsnGroupUomInfoDto(); // if it is single MSN and conversion factor = 0,then we should change to 1 // if it is grouped MSN check for msn's having conversion factor= 0,then send an email if (!apiResponse.getGroupFlag()) { for (MsnGroupUomInfoDto uom : uomList) { if (uom.getConversionFactor() == null || uom.getConversionFactor() == 0) uom.setConversionFactor(1); } } else { List<MsnGroupUomInfoDto> inValidUomList = uomList.parallelStream().filter(uom -> uom.getConversionFactor() == null || uom.getConversionFactor() == 0).collect(Collectors.toList()); /*if (inValidUomList.size() > 0) { CompletableFuture.supplyAsync(() -> emailService.sendEmail(new EmailBean(GROUPED_MSN_INVALID_CONVERSION_FACTOR_EMAIL, Constants.GROUPED_MSN_INVALID_CONVERSION_FACTOR_EMAIL_SUBJECT, String.format("%s doesn't have valid conversion factors in catalogue system!", inValidUomList.parallelStream().map(uom -> uom.getMsn()).collect(Collectors.joining(",")))))); }*/ } return new ApiResponse(HttpStatus.OK, Constants.ResponseStatus.SUCCESS, uomList); } else return new ApiResponse(HttpStatus.NOT_FOUND, Constants.ResponseStatus.WARNING, StringUtils.isEmpty(apiResponse.getMessage()) ? localeService.getMessage("catalogue.uom.notfound") : apiResponse.getMessage()); } catch (RestClientException re) { logger.error(String.format("Something went wrong while fetching uom list for MSN : %s from catalogue system!, %s", msn, re.getMessage())); re.printStackTrace(); return new ApiResponse(HttpStatus.INTERNAL_SERVER_ERROR, Constants.ResponseStatus.ERROR, localeService.getMessage("catalogue.uom.error")); } } /** * Method to itemref to catalogue system to get the msn,version and id * * @param orderItemInfo */ public OrderItemInfo syncVersionAgainstItemRef(OrderItemInfo orderItemInfo) { CatalogueApiResponse apiResponse = this.fetchMsnAgainstItemRef(Arrays.asList(orderItemInfo.getCustomerPoItemId())); if (apiResponse.getStatus()) { Optional<ItemRefMsnInfoDto> msnInfo = apiResponse.getItemRefMsnInfoList().parallelStream() .filter(itemRefMsn -> itemRefMsn.getItemId().equalsIgnoreCase(orderItemInfo.getCustomerPoItemId())).findFirst(); if (msnInfo.isPresent()) { ItemRefMsnInfoDto msnInfoDto = msnInfo.get(); orderItemInfo.setCpnId(msnInfoDto.getId()); orderItemInfo.setCpnVersion(msnInfoDto.getVersion()); } } return orderItemInfo; } private CatalogueApiResponse fetchMsnAgainstItemRef(List<String> itemRefs) { logger.info("Catalogue request for fetch msn against itemref : " + new ItemRefMsnInfoDto(itemRefs)); CatalogueApiResponse apiResponse = null; try { apiResponse = restTemplate.postForObject(CATALOGUE_MSN_URI + Constants.PATH_CATALOGUE_FETCH_MSN, new ItemRefMsnInfoDto(itemRefs), CatalogueApiResponse.class); logger.info("catalog response for fetch msn against itemref : " + new Gson().toJson(apiResponse)); } catch (RestClientException re) { logger.error(String.format("Something went wrong while fetching MSN against itemRefs : %s from catalogue system!", itemRefs.toString())); re.printStackTrace(); } return apiResponse; } public ApiResponse assignUom(MsnGroupUomInfoDto msnGroupUomInfoDto, OrderItemInfo orderItemInfo, ApplicationUser loggedInUser) { try { logger.info("Catalogue request for Assign UOM : " + new Gson().toJson(new AssignUomRequestDto(msnGroupUomInfoDto, orderItemInfo, loggedInUser))); CatalogueApiResponse apiResponse = restTemplate.postForObject(CATALOGUE_MSN_URI + Constants.PATH_CATALOGUE_ASSIGN_UOM, new AssignUomRequestDto(msnGroupUomInfoDto, orderItemInfo, loggedInUser), CatalogueApiResponse.class); logger.info("Catalogue response for Assign UOM : " + new Gson().toJson(apiResponse)); if (apiResponse.getStatus()) return new ApiResponse(HttpStatus.OK, Constants.ResponseStatus.SUCCESS, null); else return new ApiResponse(HttpStatus.INTERNAL_SERVER_ERROR, Constants.ResponseStatus.WARNING, StringUtils.isEmpty(apiResponse.getMessage()) ? localeService.getMessage("catalogue.uom.assign.error") : "Catalogue system : " + apiResponse.getMessage()); } catch (RestClientException re) { logger.error(String.format("Something went wrong while pushing UOM assignment details to catalogue system for order item : %s", orderItemInfo.getCustomerPoItemId())); re.printStackTrace(); return new ApiResponse(HttpStatus.INTERNAL_SERVER_ERROR, Constants.ResponseStatus.ERROR, localeService.getMessage("catalogue.uom.assign.error")); } } public CatalogueApiResponse isOrderItemEligibleToAssignMsn(ItemRefMsnInfoDto itemRefMsnInfoDto) { if (StringUtils.isEmpty(itemRefMsnInfoDto.getItemRef())) { logger.warn("itemref is required!"); return new CatalogueApiResponse(Boolean.FALSE, null, "itemref is required!"); } Optional<OrderItemInfo> orderItemOptional = orderItemInfoRepository.findOneByCustomerPoItemId(itemRefMsnInfoDto.getItemRef()); if (!orderItemOptional.isPresent()) { logger.warn(String.format("itemref %s not exist in salesops system", itemRefMsnInfoDto.getItemRef())); return new CatalogueApiResponse(Boolean.FALSE, itemRefMsnInfoDto.getItemRef(), String.format("itemref %s not exist in salesops system", itemRefMsnInfoDto.getItemRef())); } OrderItemInfo orderItemInfo = orderItemOptional.get(); boolean isEligible = Stream.of(Constants.OrderItemStatus.MSN_NOT_AVAILABLE, Constants.OrderItemStatus.UOM_NOT_AVAILABLE) .anyMatch(status -> status.equals(orderItemInfo.getStatus())); if (isEligible) { logger.info(String.format("itemref %s is eligible to assign msn", itemRefMsnInfoDto.getItemRef()), itemRefMsnInfoDto.getItemRef()); return new CatalogueApiResponse(Boolean.TRUE, itemRefMsnInfoDto.getItemRef(), String.format("itemref %s is eligible to assign msn", itemRefMsnInfoDto.getItemRef())); } logger.warn(String.format("itemref %s is not eligible to assign msn", itemRefMsnInfoDto.getItemRef()), itemRefMsnInfoDto.getItemRef()); return new CatalogueApiResponse(Boolean.FALSE, itemRefMsnInfoDto.getItemRef(), String.format("itemref %s is not eligible to assign msn", itemRefMsnInfoDto.getItemRef())); } }
9,648
0.712168
0.711235
154
61.649349
57.348167
262
false
false
0
0
0
0
0
0
0.915584
false
false
15
e381cdc7aa1f607fca3a20db684ecefa759d2c5a
13,846,974,586,959
cd67a211099c9e42728f3a7484487660ef3cee72
/agency-backend/src/main/java/com/itechart/agency/entity/QuestionType.java
fb240fa68bccbd63aec8ff9f5c1b874407c5dea4
[]
no_license
sherbenko/Recruiting-Agency
https://github.com/sherbenko/Recruiting-Agency
9002cf8923b3c38d761d6f19ce43bcdc1f654d9d
a2ba5ec1c8cabf2a7ac46dc9f6fa5b12f9281c55
refs/heads/master
2022-12-30T14:26:41.698000
2020-10-19T10:25:14
2020-10-19T10:25:14
305,086,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.itechart.agency.entity; import com.sun.istack.NotNull; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.util.List; @Entity @Table(name = "question_types") @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class QuestionType { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") @NotNull private String name; @OneToMany(mappedBy = "questionType", cascade = CascadeType.ALL, orphanRemoval = true) private List<Question> questions; }
UTF-8
Java
641
java
QuestionType.java
Java
[]
null
[]
package com.itechart.agency.entity; import com.sun.istack.NotNull; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.util.List; @Entity @Table(name = "question_types") @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class QuestionType { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") @NotNull private String name; @OneToMany(mappedBy = "questionType", cascade = CascadeType.ALL, orphanRemoval = true) private List<Question> questions; }
641
0.74883
0.74883
32
19.03125
19.04351
90
false
false
0
0
0
0
0
0
0.40625
false
false
15
7b408dc7a822f2f20fae460494288296c64f10f0
30,820,685,337,405
19d0649d62a59a90c8a405c7a01b29921ec28407
/src/main/java/com/myway/crawler/redis/WechatStatusCacheService.java
c0bf47dfb9ba14e81193ed16a8ebd0421669f221
[]
no_license
zy117/wcz
https://github.com/zy117/wcz
e44c839c8b9dbc1b03feebfe057ac485a719de5f
dc63c198d5c5d3cba4fca3622d8d4691aef46028
refs/heads/master
2020-04-02T12:51:40.645000
2018-10-24T07:17:02
2018-10-24T07:17:02
154,455,308
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.myway.crawler.redis; import org.springframework.stereotype.Service; import com.myway.usf.redis.common.KeyGenerator; import com.myway.usf.redis.service.BaseHashCacheService; /** * * 结果缓存 * * @author zhangy * @version 2018年10月11日 */ @Service public class WechatStatusCacheService extends BaseHashCacheService<WechatStatusCache, WechatStatusCache> { @Override public String setCacheKey() { return KeyGenerator.generateKey("wechat", "crawler", "result"); } @Override public WechatStatusCache toCache(WechatStatusCache fromObject) { return fromObject; } @Override public WechatStatusCache toObject(WechatStatusCache cache) { return cache; } }
UTF-8
Java
777
java
WechatStatusCacheService.java
Java
[ { "context": "acheService;\r\n\r\n/**\r\n * \r\n * 结果缓存\r\n * \r\n * @author zhangy\r\n * @version 2018年10月11日\r\n */\r\n@Service\r\npublic c", "end": 234, "score": 0.9996485710144043, "start": 228, "tag": "USERNAME", "value": "zhangy" } ]
null
[]
package com.myway.crawler.redis; import org.springframework.stereotype.Service; import com.myway.usf.redis.common.KeyGenerator; import com.myway.usf.redis.service.BaseHashCacheService; /** * * 结果缓存 * * @author zhangy * @version 2018年10月11日 */ @Service public class WechatStatusCacheService extends BaseHashCacheService<WechatStatusCache, WechatStatusCache> { @Override public String setCacheKey() { return KeyGenerator.generateKey("wechat", "crawler", "result"); } @Override public WechatStatusCache toCache(WechatStatusCache fromObject) { return fromObject; } @Override public WechatStatusCache toObject(WechatStatusCache cache) { return cache; } }
777
0.689384
0.678899
32
21.84375
23.636715
76
false
false
0
0
0
0
0
0
0.3125
false
false
15
b248057004d0f7b9cd7bbc0c38fc7d8c10c7bba2
31,353,261,268,258
e2c452e2dbd4757f9d7488f8fd55622efadd0511
/src/main/java/org/just/computer/mathproject/Entity/Homework/Zuoye3.java
ecdb851abc4b34ca3d87096316647c6e93aecb3c
[]
no_license
GodofOrange/mathproject
https://github.com/GodofOrange/mathproject
4712b93aae25c55b9a623f580026c6192345943c
d2c0b25fe2285b455a493844894be1f79094f23d
refs/heads/master
2020-07-11T06:56:14.586000
2020-02-03T08:30:22
2020-02-03T08:30:22
204,471,224
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.just.computer.mathproject.Entity.Homework; import javax.persistence.*; /** * 作业3表 */ @Entity(name="Zuoye3") public class Zuoye3 { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id",columnDefinition="bigint COMMENT '主键,自动生成'") private Integer id; @Column(name = "diy", columnDefinition = "varchar(255)") private String diy; @Column(name = "classifyid",columnDefinition="bigint") private Integer classifyid; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDiy() { return diy; } public void setDiy(String diy) { this.diy = diy; } public Integer getClassifyid() { return classifyid; } public void setClassifyid(Integer classifyid) { this.classifyid = classifyid; } }
UTF-8
Java
913
java
Zuoye3.java
Java
[]
null
[]
package org.just.computer.mathproject.Entity.Homework; import javax.persistence.*; /** * 作业3表 */ @Entity(name="Zuoye3") public class Zuoye3 { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id",columnDefinition="bigint COMMENT '主键,自动生成'") private Integer id; @Column(name = "diy", columnDefinition = "varchar(255)") private String diy; @Column(name = "classifyid",columnDefinition="bigint") private Integer classifyid; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDiy() { return diy; } public void setDiy(String diy) { this.diy = diy; } public Integer getClassifyid() { return classifyid; } public void setClassifyid(Integer classifyid) { this.classifyid = classifyid; } }
913
0.629339
0.62262
42
20.261906
19.464325
68
false
false
0
0
0
0
0
0
0.333333
false
false
15
361f3765b2d68ea5216e40dc85b832b9641548db
27,857,157,892,025
300ae76f170f263eacc0196208d9a87445b030dc
/banque/src/test/java/fr/ides/gestion/banque/RetraitTest.java
2e5221593e0e96a0269647b9e3af8adeac197a8c
[]
no_license
abellaaj/banque
https://github.com/abellaaj/banque
799b3e50dbc6557d8052b61bbe3f37bde477bc78
0b0de4d9facfc2640b1162f91370b1c2affca3fd
refs/heads/master
2022-12-07T14:49:54.660000
2022-11-20T12:53:06
2022-11-20T12:53:06
76,808,977
0
0
null
false
2022-11-20T12:51:14
2016-12-18T21:56:34
2022-11-20T12:18:21
2022-11-20T12:44:04
28
0
0
0
Java
false
false
package fr.ides.gestion.banque; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.sql.SQLException; import org.dbunit.DatabaseUnitException; import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; import org.dbunit.operation.DatabaseOperation; import static org.junit.Assert.assertArrayEquals; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import fr.ides.gestion.banque.entities.Compte; import fr.ides.gestion.banque.metier.IbanqueMetier; /** * * @author abellaaj * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/applicationContext.xml" }) public class RetraitTest extends CommonTest{ @Autowired IbanqueMetier banqueMetier; @Test public void testRetrait(){ Compte compte1 = banqueMetier.consulterCompte("compte1027_1"); banqueMetier.retrait("compte1027_1", 500); Compte compte2 = banqueMetier.consulterCompte("compte1027_1"); double[] l1= {compte1.getSolde()-500}; double[] l2= {compte2.getSolde()}; assertArrayEquals(l1, l2, 0); } @BeforeClass public static void beforeTest() { InputStream inputStreamXML; try{ dbUnitConnection=getConnection(); FlatXmlDataSetBuilder xmlDSBuilder = new FlatXmlDataSetBuilder(); xmlDSBuilder.setCaseSensitiveTableNames(false); inputStreamXML = new FileInputStream("src/test/resources/dataSet/Client.xml"); dataSet = xmlDSBuilder.build(inputStreamXML); //DatabaseOperation.DELETE.execute(dbUnitConnection, dataSet); DatabaseOperation.UPDATE.execute(dbUnitConnection, dataSet); } catch (DatabaseUnitException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } // j'ai commenté l'afterClass pour pouvoir visualiser le résultat dans la base de donnée //@AfterClass public static void afterTest() { try { DatabaseOperation.DELETE.execute(dbUnitConnection, dataSet); } catch (DatabaseUnitException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
UTF-8
Java
2,518
java
RetraitTest.java
Java
[ { "context": "nque.metier.IbanqueMetier;\r\n\r\n/**\r\n * \r\n * @author abellaaj\r\n *\r\n */\r\n@RunWith(SpringJUnit4ClassRunner.class)", "end": 785, "score": 0.998772382736206, "start": 777, "tag": "USERNAME", "value": "abellaaj" } ]
null
[]
package fr.ides.gestion.banque; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.sql.SQLException; import org.dbunit.DatabaseUnitException; import org.dbunit.dataset.xml.FlatXmlDataSetBuilder; import org.dbunit.operation.DatabaseOperation; import static org.junit.Assert.assertArrayEquals; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import fr.ides.gestion.banque.entities.Compte; import fr.ides.gestion.banque.metier.IbanqueMetier; /** * * @author abellaaj * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/applicationContext.xml" }) public class RetraitTest extends CommonTest{ @Autowired IbanqueMetier banqueMetier; @Test public void testRetrait(){ Compte compte1 = banqueMetier.consulterCompte("compte1027_1"); banqueMetier.retrait("compte1027_1", 500); Compte compte2 = banqueMetier.consulterCompte("compte1027_1"); double[] l1= {compte1.getSolde()-500}; double[] l2= {compte2.getSolde()}; assertArrayEquals(l1, l2, 0); } @BeforeClass public static void beforeTest() { InputStream inputStreamXML; try{ dbUnitConnection=getConnection(); FlatXmlDataSetBuilder xmlDSBuilder = new FlatXmlDataSetBuilder(); xmlDSBuilder.setCaseSensitiveTableNames(false); inputStreamXML = new FileInputStream("src/test/resources/dataSet/Client.xml"); dataSet = xmlDSBuilder.build(inputStreamXML); //DatabaseOperation.DELETE.execute(dbUnitConnection, dataSet); DatabaseOperation.UPDATE.execute(dbUnitConnection, dataSet); } catch (DatabaseUnitException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } // j'ai commenté l'afterClass pour pouvoir visualiser le résultat dans la base de donnée //@AfterClass public static void afterTest() { try { DatabaseOperation.DELETE.execute(dbUnitConnection, dataSet); } catch (DatabaseUnitException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
2,518
0.733201
0.72008
81
29.049383
23.481487
89
false
false
0
0
0
0
0
0
1.506173
false
false
15
1204eac9de76ea4c1b51ab532263e873b7f719c7
27,857,157,891,352
95496ce117a22b111f457756c0bc954b9ae219fc
/src/main/java/fr/ippon/tatami/service/pipeline/tweet/rendering/TweetRenderingHandler.java
ef963711345adf21e188e07aec3c9c3cee6cce9f
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
doanduyhai/tatami
https://github.com/doanduyhai/tatami
7085c8ead83e1a957aa3ec4025dd08e36fb51971
5902bc7f0632849d6029c6679d602d5c8e792b10
refs/heads/master
2021-01-17T14:30:21.435000
2012-06-23T23:32:26
2012-06-23T23:32:26
3,767,015
8
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.ippon.tatami.service.pipeline.tweet.rendering; import fr.ippon.tatami.domain.Tweet; public interface TweetRenderingHandler { public void onRender(Tweet tweet); }
UTF-8
Java
176
java
TweetRenderingHandler.java
Java
[]
null
[]
package fr.ippon.tatami.service.pipeline.tweet.rendering; import fr.ippon.tatami.domain.Tweet; public interface TweetRenderingHandler { public void onRender(Tweet tweet); }
176
0.8125
0.8125
8
21
21.470911
57
false
false
0
0
0
0
0
0
0.5
false
false
15
bc476d81f0558fdca0f7ce20327cc8bbebf69b98
28,733,331,257,404
32c6c02b75a92b1c134743de32115398e3cebda0
/Simple/src/se/dixum/simple/utils/SimpleGesture.java
9b928ac2d90b3f1ca70e78b3f66157d03988d9be
[ "Apache-2.0" ]
permissive
DavidSkeppstedt/Simple
https://github.com/DavidSkeppstedt/Simple
c9c926016b69abfdd5c4281c21e10b4cc3c7b9e9
acc9106e50424ea825e5269b6be8302ef3da9ddc
refs/heads/master
2021-01-19T00:23:54.520000
2013-12-12T18:35:41
2013-12-12T18:35:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package se.dixum.simple.utils; import com.badlogic.gdx.input.GestureDetector.GestureListener; import com.badlogic.gdx.math.Vector2; public class SimpleGesture implements GestureListener { public static boolean PAN = false,FLING = false; public static float PAN_DX = 0, PAN_DY =0; @Override public boolean touchDown(float x, float y, int pointer, int button) { return false; } @Override public boolean tap(float x, float y, int count, int button) { return false; } @Override public boolean longPress(float x, float y) { return false; } @Override public boolean fling(float velocityX, float velocityY, int button) { PAN = false; PAN_DX = 0; PAN_DY = 0; return false; } @Override public boolean pan(float x, float y, float deltaX, float deltaY) { PAN = true; PAN_DX = deltaX; PAN_DY = deltaY; return false; } @Override public boolean zoom(float initialDistance, float distance) { return false; } @Override public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) { return false; } @Override public boolean panStop(float x, float y, int pointer, int button) { return false; } }
UTF-8
Java
1,231
java
SimpleGesture.java
Java
[]
null
[]
package se.dixum.simple.utils; import com.badlogic.gdx.input.GestureDetector.GestureListener; import com.badlogic.gdx.math.Vector2; public class SimpleGesture implements GestureListener { public static boolean PAN = false,FLING = false; public static float PAN_DX = 0, PAN_DY =0; @Override public boolean touchDown(float x, float y, int pointer, int button) { return false; } @Override public boolean tap(float x, float y, int count, int button) { return false; } @Override public boolean longPress(float x, float y) { return false; } @Override public boolean fling(float velocityX, float velocityY, int button) { PAN = false; PAN_DX = 0; PAN_DY = 0; return false; } @Override public boolean pan(float x, float y, float deltaX, float deltaY) { PAN = true; PAN_DX = deltaX; PAN_DY = deltaY; return false; } @Override public boolean zoom(float initialDistance, float distance) { return false; } @Override public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) { return false; } @Override public boolean panStop(float x, float y, int pointer, int button) { return false; } }
1,231
0.696182
0.685621
71
16.338028
21.711906
71
false
false
0
0
0
0
0
0
1.71831
false
false
15
678f0a383f101a16283388471ec3626c7f58b02f
2,568,390,477,000
7e2b2d00c7d687d87ed6ef7be2acb32116f0cb81
/InstaFood/app/src/main/java/com/example/asd/modica/db/models/Anunciante.java
a2ad740cb0921bb629734ded70e829955e407611
[]
no_license
1213lego/proyectoSoftware
https://github.com/1213lego/proyectoSoftware
d9fa88391f67f5bf771c21c6c0aee85d415cfae7
3299bfb9a2036f04c46bc55374265eb8f2ef88d4
refs/heads/master
2018-12-23T13:01:15.959000
2018-12-22T02:21:23
2018-12-22T02:21:23
150,771,415
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.asd.modica.db.models; import android.arch.persistence.room.Entity; import android.arch.persistence.room.ForeignKey; import android.arch.persistence.room.Index; import android.arch.persistence.room.PrimaryKey; import android.arch.persistence.room.TypeConverters; import com.example.asd.modica.db.database.TimestampConverter; import java.util.Date; @Entity ( indices = @Index(value = {"idAnunciante", "emailUsuario"}, unique = true), foreignKeys = @ForeignKey(entity = Usuario.class, parentColumns ="email", childColumns = "emailUsuario") ) public class Anunciante implements IDto { @PrimaryKey(autoGenerate = true) private int idAnunciante; //llave foranea private String emailUsuario; private double preciooSucripcion; @TypeConverters({TimestampConverter.class}) private Date fechaSuscripcion; public Anunciante(String emailUsuario, double preciooSucripcion, Date fechaSuscripcion) { this.emailUsuario = emailUsuario; this.preciooSucripcion = preciooSucripcion; this.fechaSuscripcion = fechaSuscripcion; } public int getIdAnunciante() { return idAnunciante; } public void setIdAnunciante(int idAnunciante) { this.idAnunciante = idAnunciante; } public String getEmailUsuario() { return emailUsuario; } public void setEmailUsuario(String emailUsuario) { this.emailUsuario = emailUsuario; } public double getPreciooSucripcion() { return preciooSucripcion; } public void setPreciooSucripcion(double preciooSucripcion) { this.preciooSucripcion = preciooSucripcion; } public Date getFechaSuscripcion() { return fechaSuscripcion; } public void setFechaSuscripcion(Date fechaSuscripcion) { this.fechaSuscripcion = fechaSuscripcion; } }
UTF-8
Java
1,930
java
Anunciante.java
Java
[]
null
[]
package com.example.asd.modica.db.models; import android.arch.persistence.room.Entity; import android.arch.persistence.room.ForeignKey; import android.arch.persistence.room.Index; import android.arch.persistence.room.PrimaryKey; import android.arch.persistence.room.TypeConverters; import com.example.asd.modica.db.database.TimestampConverter; import java.util.Date; @Entity ( indices = @Index(value = {"idAnunciante", "emailUsuario"}, unique = true), foreignKeys = @ForeignKey(entity = Usuario.class, parentColumns ="email", childColumns = "emailUsuario") ) public class Anunciante implements IDto { @PrimaryKey(autoGenerate = true) private int idAnunciante; //llave foranea private String emailUsuario; private double preciooSucripcion; @TypeConverters({TimestampConverter.class}) private Date fechaSuscripcion; public Anunciante(String emailUsuario, double preciooSucripcion, Date fechaSuscripcion) { this.emailUsuario = emailUsuario; this.preciooSucripcion = preciooSucripcion; this.fechaSuscripcion = fechaSuscripcion; } public int getIdAnunciante() { return idAnunciante; } public void setIdAnunciante(int idAnunciante) { this.idAnunciante = idAnunciante; } public String getEmailUsuario() { return emailUsuario; } public void setEmailUsuario(String emailUsuario) { this.emailUsuario = emailUsuario; } public double getPreciooSucripcion() { return preciooSucripcion; } public void setPreciooSucripcion(double preciooSucripcion) { this.preciooSucripcion = preciooSucripcion; } public Date getFechaSuscripcion() { return fechaSuscripcion; } public void setFechaSuscripcion(Date fechaSuscripcion) { this.fechaSuscripcion = fechaSuscripcion; } }
1,930
0.698964
0.698964
74
25.081081
25.482244
120
false
false
0
0
0
0
0
0
0.405405
false
false
15
165e6043809ed5a0cdd80f48c6e26c9caf35efe9
27,255,862,465,769
9e4c294d87ee4099df496f91c72fda7faa1f6e41
/app/src/main/java/com/android/moviestreamer/ui/people/PeoplePosterAdapter.java
c25205e6044c9368d9e7d584fbe984a724b5f3a6
[]
no_license
diljots99-old/android-client-side-streaming-app
https://github.com/diljots99-old/android-client-side-streaming-app
05e064234768d719b58190658d50e70ce87a218e
fcb92659549c21083d538c5930b7375d4b13b6a2
refs/heads/master
2023-01-27T16:13:14.558000
2020-12-08T11:19:30
2020-12-08T11:19:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.moviestreamer.ui.people; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.RecyclerView; import com.android.moviestreamer.R; import com.android.moviestreamer.ui.movies.MoviePosterAdapter; import com.bumptech.glide.Glide; import com.facebook.shimmer.Shimmer; import com.facebook.shimmer.ShimmerDrawable; import org.json.JSONException; import org.json.JSONObject; import java.util.List; public class PeoplePosterAdapter extends RecyclerView.Adapter<PeoplePosterAdapter.ViewHolder> { private static final String TAG = "PeoplePosterAdapter"; Context mContext; List<JSONObject> mData; public PeoplePosterAdapter(Context mContext, List<JSONObject> mData) { this.mContext = mContext; this.mData = mData; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.people_poster_item, parent, false); return new PeoplePosterAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { try { holder.tv_person_name.setText(mData.get(position).getString("name")); if (mData.get(position).getString("type").contains("cast")) { holder.tv_character_name.setText('"'+mData.get(position).getString("character")+'"'); } else { holder.tv_character_name.setText('"'+mData.get(position).getString("job")+'"'); } Shimmer shimmer = new Shimmer.AlphaHighlightBuilder().setAutoStart(true).setBaseAlpha(0.9f).setHighlightAlpha(0.8f).setDirection(Shimmer.Direction.LEFT_TO_RIGHT).build(); // Shimmer shimmer = new Shimmer.AlphaHighlightBuilder().setAutoStart(true).build(); String url = mContext.getString(R.string.API_BASE_URL) + mContext.getString(R.string.API_MOVIE_PEOPLE_PROFILE_IMAGE) + mData.get(position).getInt("id") + "?width=200"; ShimmerDrawable shimmerDrawable = new ShimmerDrawable(); shimmerDrawable.setShimmer(shimmer); Glide.with(mContext) .load(url) .placeholder(shimmerDrawable) .error(R.drawable.poster_placeholder_dark) .centerCrop() .fitCenter() .into(holder.iv_people_poster); } catch (JSONException e) { e.printStackTrace(); } } @Override public int getItemCount() { return mData.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public TextView tv_character_name, tv_person_name; public ImageView iv_people_poster; public ConstraintLayout cl_container; public ViewHolder(@NonNull View itemView) { super(itemView); tv_character_name = itemView.findViewById(R.id.tv_character_name); tv_person_name = itemView.findViewById(R.id.tv_person_name); iv_people_poster = itemView.findViewById(R.id.iv_people_poster); } } }
UTF-8
Java
3,403
java
PeoplePosterAdapter.java
Java
[]
null
[]
package com.android.moviestreamer.ui.people; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.RecyclerView; import com.android.moviestreamer.R; import com.android.moviestreamer.ui.movies.MoviePosterAdapter; import com.bumptech.glide.Glide; import com.facebook.shimmer.Shimmer; import com.facebook.shimmer.ShimmerDrawable; import org.json.JSONException; import org.json.JSONObject; import java.util.List; public class PeoplePosterAdapter extends RecyclerView.Adapter<PeoplePosterAdapter.ViewHolder> { private static final String TAG = "PeoplePosterAdapter"; Context mContext; List<JSONObject> mData; public PeoplePosterAdapter(Context mContext, List<JSONObject> mData) { this.mContext = mContext; this.mData = mData; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.people_poster_item, parent, false); return new PeoplePosterAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { try { holder.tv_person_name.setText(mData.get(position).getString("name")); if (mData.get(position).getString("type").contains("cast")) { holder.tv_character_name.setText('"'+mData.get(position).getString("character")+'"'); } else { holder.tv_character_name.setText('"'+mData.get(position).getString("job")+'"'); } Shimmer shimmer = new Shimmer.AlphaHighlightBuilder().setAutoStart(true).setBaseAlpha(0.9f).setHighlightAlpha(0.8f).setDirection(Shimmer.Direction.LEFT_TO_RIGHT).build(); // Shimmer shimmer = new Shimmer.AlphaHighlightBuilder().setAutoStart(true).build(); String url = mContext.getString(R.string.API_BASE_URL) + mContext.getString(R.string.API_MOVIE_PEOPLE_PROFILE_IMAGE) + mData.get(position).getInt("id") + "?width=200"; ShimmerDrawable shimmerDrawable = new ShimmerDrawable(); shimmerDrawable.setShimmer(shimmer); Glide.with(mContext) .load(url) .placeholder(shimmerDrawable) .error(R.drawable.poster_placeholder_dark) .centerCrop() .fitCenter() .into(holder.iv_people_poster); } catch (JSONException e) { e.printStackTrace(); } } @Override public int getItemCount() { return mData.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public TextView tv_character_name, tv_person_name; public ImageView iv_people_poster; public ConstraintLayout cl_container; public ViewHolder(@NonNull View itemView) { super(itemView); tv_character_name = itemView.findViewById(R.id.tv_character_name); tv_person_name = itemView.findViewById(R.id.tv_person_name); iv_people_poster = itemView.findViewById(R.id.iv_people_poster); } } }
3,403
0.67558
0.673523
96
34.447918
35.799171
182
false
false
0
0
0
0
0
0
0.510417
false
false
15
025391600a98abba8adf2080cf32d5ca7a457ae0
7,078,106,109,357
7e0ebf2fc9010e569698e9a4c502a8e53f4454c5
/src/main/java/me/reb4ck/hyperskills/addons/MVDWPlaceholderAPIManager.java
701582f6dea89880c7f175b682a6181237881f3c
[]
no_license
EnZiiK/HyperSkills
https://github.com/EnZiiK/HyperSkills
e6b1dab3f869ceddb012500ab82dbedaeebf5c20
83f0f79d1bcf92a97065255278656707194d0c78
refs/heads/master
2023-05-31T06:46:42.281000
2021-06-29T06:13:21
2021-06-29T06:13:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.reb4ck.hyperskills.addons; import be.maximvdw.placeholderapi.PlaceholderAPI; import me.reb4ck.hyperskills.HyperSkills; import me.reb4ck.hyperskills.api.HyperSkillsAPI; import me.reb4ck.hyperskills.objects.abilities.Ability; import me.reb4ck.hyperskills.objects.SkillType; import me.reb4ck.hyperskills.objects.perks.Perk; import me.reb4ck.hyperskills.utils.Utils; public class MVDWPlaceholderAPIManager { public MVDWPlaceholderAPIManager(HyperSkills plugin) { if (!plugin.getServer().getPluginManager().isPluginEnabled("MVdWPlaceholderAPI")) { return; } HyperSkillsAPI api = plugin.getApi(); PlaceholderAPI.registerPlaceholder(plugin, "skills_current_health", e -> Utils.getHealth(e.getPlayer()) + ""); for(Ability ability : Ability.values()) { PlaceholderAPI.registerPlaceholder(plugin, "skills_" + ability.getLowName() + "_total", e -> api.getTotalAbility(e.getPlayer().getUniqueId(), ability) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+ability.getLowName()+"_extra", e -> api.getExtraAbility(e.getPlayer().getUniqueId(), ability) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+ability.getLowName()+"_simple", e -> api.getSimpleAbility(e.getPlayer().getUniqueId(), ability) + ""); } for(Perk perk : Perk.values()) { PlaceholderAPI.registerPlaceholder(plugin, "skills_" + perk.getLowName() + "_total", e -> api.getTotalPerk(e.getPlayer().getUniqueId(), perk) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+perk.getLowName()+"_extra", e -> api.getExtraPerk(e.getPlayer().getUniqueId(), perk) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+perk.getLowName()+"_simple", e -> api.getSimplePerk(e.getPlayer().getUniqueId(), perk) + ""); } for(SkillType skillType : SkillType.values()) { PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_level", e -> api.getLevel(e.getPlayer().getUniqueId(), skillType) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_xp", e -> api.getLevel(e.getPlayer().getUniqueId(), skillType) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_progressbar", e -> Utils.getProgressBar(e.getPlayer().getUniqueId(), skillType) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_xp_left", e -> plugin.getRequirements().getLevelRequirement(skillType, api.getLevel(e.getPlayer().getUniqueId(), skillType)) - api.getXP(e.getPlayer().getUniqueId(), skillType) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_rank", e -> api.getRank(e.getPlayer().getUniqueId(), skillType) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_level_roman", e -> Utils.toRoman(api.getLevel(e.getPlayer().getUniqueId(), skillType)) + ""); } } }
UTF-8
Java
3,050
java
MVDWPlaceholderAPIManager.java
Java
[]
null
[]
package me.reb4ck.hyperskills.addons; import be.maximvdw.placeholderapi.PlaceholderAPI; import me.reb4ck.hyperskills.HyperSkills; import me.reb4ck.hyperskills.api.HyperSkillsAPI; import me.reb4ck.hyperskills.objects.abilities.Ability; import me.reb4ck.hyperskills.objects.SkillType; import me.reb4ck.hyperskills.objects.perks.Perk; import me.reb4ck.hyperskills.utils.Utils; public class MVDWPlaceholderAPIManager { public MVDWPlaceholderAPIManager(HyperSkills plugin) { if (!plugin.getServer().getPluginManager().isPluginEnabled("MVdWPlaceholderAPI")) { return; } HyperSkillsAPI api = plugin.getApi(); PlaceholderAPI.registerPlaceholder(plugin, "skills_current_health", e -> Utils.getHealth(e.getPlayer()) + ""); for(Ability ability : Ability.values()) { PlaceholderAPI.registerPlaceholder(plugin, "skills_" + ability.getLowName() + "_total", e -> api.getTotalAbility(e.getPlayer().getUniqueId(), ability) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+ability.getLowName()+"_extra", e -> api.getExtraAbility(e.getPlayer().getUniqueId(), ability) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+ability.getLowName()+"_simple", e -> api.getSimpleAbility(e.getPlayer().getUniqueId(), ability) + ""); } for(Perk perk : Perk.values()) { PlaceholderAPI.registerPlaceholder(plugin, "skills_" + perk.getLowName() + "_total", e -> api.getTotalPerk(e.getPlayer().getUniqueId(), perk) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+perk.getLowName()+"_extra", e -> api.getExtraPerk(e.getPlayer().getUniqueId(), perk) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+perk.getLowName()+"_simple", e -> api.getSimplePerk(e.getPlayer().getUniqueId(), perk) + ""); } for(SkillType skillType : SkillType.values()) { PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_level", e -> api.getLevel(e.getPlayer().getUniqueId(), skillType) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_xp", e -> api.getLevel(e.getPlayer().getUniqueId(), skillType) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_progressbar", e -> Utils.getProgressBar(e.getPlayer().getUniqueId(), skillType) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_xp_left", e -> plugin.getRequirements().getLevelRequirement(skillType, api.getLevel(e.getPlayer().getUniqueId(), skillType)) - api.getXP(e.getPlayer().getUniqueId(), skillType) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_rank", e -> api.getRank(e.getPlayer().getUniqueId(), skillType) + ""); PlaceholderAPI.registerPlaceholder(plugin, "skills_"+skillType.getLowName()+"_level_roman", e -> Utils.toRoman(api.getLevel(e.getPlayer().getUniqueId(), skillType)) + ""); } } }
3,050
0.693443
0.691148
40
75.275002
71.053848
273
false
false
0
0
0
0
0
0
1.575
false
false
15
74afe5cdc2ac1609559ec0fbb589a16bec5278f8
3,917,010,177,465
bacc02e0730b9dbe5c81815882a8595e64677e19
/app/src/main/java/com/example/iit/dhakathon/CandidateList.java
c1c32322e94fc154538289bec131fca7ad570164
[]
no_license
kazisrabon/VotesFor
https://github.com/kazisrabon/VotesFor
e340148552fb86bb041e0421575e8f2d8ba593a7
8b8d5c6e2943a995441eef32948a6c5674482227
refs/heads/master
2021-01-01T18:03:26.942000
2015-04-22T18:57:43
2015-04-22T18:57:43
34,131,548
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.iit.dhakathon; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import com.mikepenz.iconics.typeface.FontAwesome; import com.mikepenz.materialdrawer.Drawer; import com.mikepenz.materialdrawer.accountswitcher.AccountHeader; import com.mikepenz.materialdrawer.model.PrimaryDrawerItem; import com.mikepenz.materialdrawer.model.ProfileDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IProfile; import com.mikepenz.materialdrawer.model.interfaces.Nameable; import java.util.ArrayList; import java.util.List; public class CandidateList extends ActionBarActivity implements View.OnClickListener { Spinner spCityCorporation, spCandidateType; int spCCTypeSelected = 0; int spCouncilorTypeSelected = 0; Button bSearch; private Drawer.Result result; private AccountHeader.Result headerResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_candidate_list); init(); initDrawer(); } private void init() { spCandidateType = (Spinner) findViewById(R.id.spCityCorporationType); spCityCorporation = (Spinner) findViewById(R.id.spCityCorporationName); setSpinnerAdapter(); setSpinnerListener(); bSearch = (Button) findViewById(R.id.bSearch); bSearch.setOnClickListener(this); } private void setSpinnerListener() { spCityCorporation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { spCCTypeSelected = i; } @Override public void onNothingSelected(AdapterView<?> adapterView) { spCCTypeSelected = 0; } }); spCandidateType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { spCouncilorTypeSelected = i; } @Override public void onNothingSelected(AdapterView<?> adapterView) { spCouncilorTypeSelected = 0; } }); } private void setSpinnerAdapter() { List<String> listOfRMO = new ArrayList<String>(); listOfRMO.add("Dhaka North City Corporation"); listOfRMO.add("Dhaka South City Corporation"); listOfRMO.add("Chittagong City Corporation"); ArrayAdapter<String> dataAdapterOfRMO = new ArrayAdapter<String>(this, R.layout.custom_simple_spinner, listOfRMO); dataAdapterOfRMO.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spCityCorporation.setAdapter(dataAdapterOfRMO); List<String> listOfRMO2 = new ArrayList<String>(); listOfRMO2.add("Mayor"); listOfRMO2.add("Councilor"); listOfRMO2.add("Reserved Councilor"); ArrayAdapter<String> dataAdapterOfRMO2 = new ArrayAdapter<String>(this, R.layout.custom_simple_spinner, listOfRMO2); dataAdapterOfRMO2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spCandidateType.setAdapter(dataAdapterOfRMO2); } private void initDrawer() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(false); headerResult = new AccountHeader() .withActivity(this) .withHeaderBackground(R.drawable.header) .addProfiles( new ProfileDrawerItem().withName("Test").withEmail("test@gmail.com").withIcon(getResources().getDrawable(R.drawable.profile)) ) .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { @Override public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) { return false; } }) .build(); // Handle Toolbar result = new Drawer() .withActivity(this) .withHeader(R.layout.header) .withAccountHeader(headerResult) .addDrawerItems( new PrimaryDrawerItem().withName(R.string.drawer_item_candidates).withIcon(FontAwesome.Icon.faw_male).withIdentifier(0), new PrimaryDrawerItem().withName(R.string.drawer_item_polling_stations).withIcon(FontAwesome.Icon.faw_home).withIdentifier(1), new PrimaryDrawerItem().withName(R.string.drawer_item_map).withIcon(FontAwesome.Icon.faw_globe).withIdentifier(2), new PrimaryDrawerItem().withName(R.string.drawer_item_section_nearest).withIcon(FontAwesome.Icon.faw_map_marker).withIdentifier(3), new PrimaryDrawerItem().withName(R.string.drawer_item_share).withIcon(FontAwesome.Icon.faw_share_alt).withIdentifier(4), new PrimaryDrawerItem().withName(R.string.drawer_item_info).withIcon(FontAwesome.Icon.faw_info_circle).withIdentifier(5) ) .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem) { if (drawerItem instanceof Nameable) { if (drawerItem.getIdentifier() == 0) { //startActivity(new Intent(CandidateList.this, CandidateList.class)); } else if (drawerItem.getIdentifier() == 1) { startActivity(new Intent(CandidateList.this, PollingStationActivity.class)); } else if (drawerItem.getIdentifier() == 2) { startActivity(new Intent(CandidateList.this, Map.class)); } else if (drawerItem.getIdentifier() == 3) { startActivity(new Intent(CandidateList.this, NearestVenue.class)); } else if (drawerItem.getIdentifier() == 4) { startActivity(new Intent(CandidateList.this, ShareActivity.class)); } else if (drawerItem.getIdentifier() == 5) { startActivity(new Intent(CandidateList.this, Info1.class)); } } } }) .withSelectedItem(0) .build(); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // getSupportActionBar().setHomeButtonEnabled(false); // result.getActionBarDrawerToggle().setDrawerIndicatorEnabled(true); } @Override public void onClick(View view) { if (view == bSearch) { Intent intent=new Intent(CandidateList.this,ListViewOfCandidates.class); intent.putExtra("url",URL.URL[spCCTypeSelected][spCouncilorTypeSelected]); startActivity(intent); } } }
UTF-8
Java
7,736
java
CandidateList.java
Java
[ { "context": " new ProfileDrawerItem().withName(\"Test\").withEmail(\"test@gmail.com\").withIcon(getResourc", "end": 4162, "score": 0.898324191570282, "start": 4158, "tag": "NAME", "value": "Test" }, { "context": "w ProfileDrawerItem().withName(\"Test\").withEmail(\"te...
null
[]
package com.example.iit.dhakathon; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import com.mikepenz.iconics.typeface.FontAwesome; import com.mikepenz.materialdrawer.Drawer; import com.mikepenz.materialdrawer.accountswitcher.AccountHeader; import com.mikepenz.materialdrawer.model.PrimaryDrawerItem; import com.mikepenz.materialdrawer.model.ProfileDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IProfile; import com.mikepenz.materialdrawer.model.interfaces.Nameable; import java.util.ArrayList; import java.util.List; public class CandidateList extends ActionBarActivity implements View.OnClickListener { Spinner spCityCorporation, spCandidateType; int spCCTypeSelected = 0; int spCouncilorTypeSelected = 0; Button bSearch; private Drawer.Result result; private AccountHeader.Result headerResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_candidate_list); init(); initDrawer(); } private void init() { spCandidateType = (Spinner) findViewById(R.id.spCityCorporationType); spCityCorporation = (Spinner) findViewById(R.id.spCityCorporationName); setSpinnerAdapter(); setSpinnerListener(); bSearch = (Button) findViewById(R.id.bSearch); bSearch.setOnClickListener(this); } private void setSpinnerListener() { spCityCorporation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { spCCTypeSelected = i; } @Override public void onNothingSelected(AdapterView<?> adapterView) { spCCTypeSelected = 0; } }); spCandidateType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { spCouncilorTypeSelected = i; } @Override public void onNothingSelected(AdapterView<?> adapterView) { spCouncilorTypeSelected = 0; } }); } private void setSpinnerAdapter() { List<String> listOfRMO = new ArrayList<String>(); listOfRMO.add("Dhaka North City Corporation"); listOfRMO.add("Dhaka South City Corporation"); listOfRMO.add("Chittagong City Corporation"); ArrayAdapter<String> dataAdapterOfRMO = new ArrayAdapter<String>(this, R.layout.custom_simple_spinner, listOfRMO); dataAdapterOfRMO.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spCityCorporation.setAdapter(dataAdapterOfRMO); List<String> listOfRMO2 = new ArrayList<String>(); listOfRMO2.add("Mayor"); listOfRMO2.add("Councilor"); listOfRMO2.add("Reserved Councilor"); ArrayAdapter<String> dataAdapterOfRMO2 = new ArrayAdapter<String>(this, R.layout.custom_simple_spinner, listOfRMO2); dataAdapterOfRMO2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spCandidateType.setAdapter(dataAdapterOfRMO2); } private void initDrawer() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(false); headerResult = new AccountHeader() .withActivity(this) .withHeaderBackground(R.drawable.header) .addProfiles( new ProfileDrawerItem().withName("Test").withEmail("<EMAIL>").withIcon(getResources().getDrawable(R.drawable.profile)) ) .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { @Override public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) { return false; } }) .build(); // Handle Toolbar result = new Drawer() .withActivity(this) .withHeader(R.layout.header) .withAccountHeader(headerResult) .addDrawerItems( new PrimaryDrawerItem().withName(R.string.drawer_item_candidates).withIcon(FontAwesome.Icon.faw_male).withIdentifier(0), new PrimaryDrawerItem().withName(R.string.drawer_item_polling_stations).withIcon(FontAwesome.Icon.faw_home).withIdentifier(1), new PrimaryDrawerItem().withName(R.string.drawer_item_map).withIcon(FontAwesome.Icon.faw_globe).withIdentifier(2), new PrimaryDrawerItem().withName(R.string.drawer_item_section_nearest).withIcon(FontAwesome.Icon.faw_map_marker).withIdentifier(3), new PrimaryDrawerItem().withName(R.string.drawer_item_share).withIcon(FontAwesome.Icon.faw_share_alt).withIdentifier(4), new PrimaryDrawerItem().withName(R.string.drawer_item_info).withIcon(FontAwesome.Icon.faw_info_circle).withIdentifier(5) ) .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem) { if (drawerItem instanceof Nameable) { if (drawerItem.getIdentifier() == 0) { //startActivity(new Intent(CandidateList.this, CandidateList.class)); } else if (drawerItem.getIdentifier() == 1) { startActivity(new Intent(CandidateList.this, PollingStationActivity.class)); } else if (drawerItem.getIdentifier() == 2) { startActivity(new Intent(CandidateList.this, Map.class)); } else if (drawerItem.getIdentifier() == 3) { startActivity(new Intent(CandidateList.this, NearestVenue.class)); } else if (drawerItem.getIdentifier() == 4) { startActivity(new Intent(CandidateList.this, ShareActivity.class)); } else if (drawerItem.getIdentifier() == 5) { startActivity(new Intent(CandidateList.this, Info1.class)); } } } }) .withSelectedItem(0) .build(); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // getSupportActionBar().setHomeButtonEnabled(false); // result.getActionBarDrawerToggle().setDrawerIndicatorEnabled(true); } @Override public void onClick(View view) { if (view == bSearch) { Intent intent=new Intent(CandidateList.this,ListViewOfCandidates.class); intent.putExtra("url",URL.URL[spCCTypeSelected][spCouncilorTypeSelected]); startActivity(intent); } } }
7,729
0.632497
0.628878
176
42.954544
36.403954
155
false
false
0
0
0
0
0
0
0.596591
false
false
15
fe51db8fb51d76cce7bc5740a4956112ec5a1f3e
3,161,095,930,718
f4975d6249933a19c104b79cd5abd72c80a65b34
/src/main/java/com/jiin/admin/website/server/service/TegolaService.java
3d320320772560f24abe9a8af81f4a411c729664
[]
no_license
tails5555/admin-view
https://github.com/tails5555/admin-view
1e77f8555a340e9cb5dc8227acbea58b3ad0d75c
9ca3c66f651e0eb30f1c68c66c1e867d5a44a587
refs/heads/master
2023-02-03T18:34:43.518000
2020-12-22T16:44:25
2020-12-22T16:44:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jiin.admin.website.server.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; @Service public class TegolaService { @Value("${project.data-path}") private String dataPath; public Map loadTegolaConfig() { File tomlFile = new File(dataPath, "vectortiles/config.toml"); Map results = new HashMap(); try { Scanner reader = new Scanner(tomlFile); while (reader.hasNextLine()) { String line = reader.nextLine(); if (line.trim().equals("[[maps.layers]]")) { String name = null, minzoom = null, maxzoom = null; while (reader.hasNextLine()) { String innerLine = reader.nextLine(); if (innerLine.trim().equals("[[maps.layers]]")) { break; }else if (innerLine.trim().startsWith("name")) { name = innerLine.split("=")[1].trim().replaceAll("\"",""); }else if (innerLine.trim().startsWith("min_zoom")) { minzoom = innerLine.split("=")[1].trim(); }else if (innerLine.trim().startsWith("max_zoom")) { maxzoom = innerLine.split("=")[1].trim(); } } if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(minzoom) && !StringUtils.isEmpty(maxzoom)) { Map map = new HashMap(); map.put("name",name); map.put("minzoom",minzoom); map.put("maxzoom",maxzoom); results.put(name,map); } } } return results; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } } }
UTF-8
Java
2,223
java
TegolaService.java
Java
[]
null
[]
package com.jiin.admin.website.server.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; @Service public class TegolaService { @Value("${project.data-path}") private String dataPath; public Map loadTegolaConfig() { File tomlFile = new File(dataPath, "vectortiles/config.toml"); Map results = new HashMap(); try { Scanner reader = new Scanner(tomlFile); while (reader.hasNextLine()) { String line = reader.nextLine(); if (line.trim().equals("[[maps.layers]]")) { String name = null, minzoom = null, maxzoom = null; while (reader.hasNextLine()) { String innerLine = reader.nextLine(); if (innerLine.trim().equals("[[maps.layers]]")) { break; }else if (innerLine.trim().startsWith("name")) { name = innerLine.split("=")[1].trim().replaceAll("\"",""); }else if (innerLine.trim().startsWith("min_zoom")) { minzoom = innerLine.split("=")[1].trim(); }else if (innerLine.trim().startsWith("max_zoom")) { maxzoom = innerLine.split("=")[1].trim(); } } if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(minzoom) && !StringUtils.isEmpty(maxzoom)) { Map map = new HashMap(); map.put("name",name); map.put("minzoom",minzoom); map.put("maxzoom",maxzoom); results.put(name,map); } } } return results; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } } }
2,223
0.489879
0.488529
59
36.677967
23.876406
86
false
false
0
0
0
0
0
0
0.610169
false
false
15
e1ca27302c2b9982dd8468bfa213c97e1573bc99
6,682,969,125,452
c247f6bef7b31975c37092fa3d8ca37342f3f221
/ssm/easybuy/src/main/java/cn/bdqn/easybuy/controller/IndexController.java
afdad9519e775354ca59e02c9e9c070de6120215
[]
no_license
leepengtao/IdeaProjects
https://github.com/leepengtao/IdeaProjects
beb628272e2e645d9c5921ea4f25ed652a50d596
9458f1a4c1b0e60fe27aaddf137f44a6bc20db12
refs/heads/master
2023-03-08T14:44:07.928000
2021-02-26T11:14:37
2021-02-26T11:14:39
342,444,269
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.bdqn.easybuy.controller; import cn.bdqn.easybuy.Service.CategoryService; import cn.bdqn.easybuy.Service.NewsService; import cn.bdqn.easybuy.Service.ProductService; import cn.bdqn.easybuy.entity.CategoryVo; import cn.bdqn.easybuy.entity.News; import cn.bdqn.easybuy.entity.Product; import cn.bdqn.easybuy.util.PageBean; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller @RequestMapping("/Index") public class IndexController { @Autowired private NewsService newsService; @Autowired private CategoryService categoryService; @Autowired private ProductService productService; @RequestMapping("/index") public String findTopFive(@RequestParam int pageNo, Model model) { System.out.println("控制器中的查询所有"); // 1.前5条新闻 List<News> newsList = newsService.findTopFive(); // 2.所有的三层目录 List<CategoryVo> cvList = categoryService.findAllCategory(); // 3.商品分页 int pageSize = 6; PageBean<Product> proPage = productService.findByPage(pageNo, pageSize); model.addAttribute("newsList",newsList); model.addAttribute("cvList",cvList); model.addAttribute("proPage",proPage); return "index"; } // ajax实现商品翻页 @RequestMapping(value = "/findProduct") public @ResponseBody PageBean findProduct(@Param("pageNo") Integer pageNo) { // Integer pageNo = Integer.parseInt(pageNoStr); System.out.println("findProduct方法执行了"); int pageSize = 6; PageBean<Product> proPage = productService.findByPage(pageNo, pageSize); return proPage; } }
UTF-8
Java
1,905
java
IndexController.java
Java
[]
null
[]
package cn.bdqn.easybuy.controller; import cn.bdqn.easybuy.Service.CategoryService; import cn.bdqn.easybuy.Service.NewsService; import cn.bdqn.easybuy.Service.ProductService; import cn.bdqn.easybuy.entity.CategoryVo; import cn.bdqn.easybuy.entity.News; import cn.bdqn.easybuy.entity.Product; import cn.bdqn.easybuy.util.PageBean; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller @RequestMapping("/Index") public class IndexController { @Autowired private NewsService newsService; @Autowired private CategoryService categoryService; @Autowired private ProductService productService; @RequestMapping("/index") public String findTopFive(@RequestParam int pageNo, Model model) { System.out.println("控制器中的查询所有"); // 1.前5条新闻 List<News> newsList = newsService.findTopFive(); // 2.所有的三层目录 List<CategoryVo> cvList = categoryService.findAllCategory(); // 3.商品分页 int pageSize = 6; PageBean<Product> proPage = productService.findByPage(pageNo, pageSize); model.addAttribute("newsList",newsList); model.addAttribute("cvList",cvList); model.addAttribute("proPage",proPage); return "index"; } // ajax实现商品翻页 @RequestMapping(value = "/findProduct") public @ResponseBody PageBean findProduct(@Param("pageNo") Integer pageNo) { // Integer pageNo = Integer.parseInt(pageNoStr); System.out.println("findProduct方法执行了"); int pageSize = 6; PageBean<Product> proPage = productService.findByPage(pageNo, pageSize); return proPage; } }
1,905
0.719346
0.716076
57
31.192982
22.385332
80
false
false
0
0
0
0
0
0
0.649123
false
false
15
630a28ac9ae342ce1b0fba32f79ecd11a8ac1cd5
8,521,215,131,208
295d9b062e9c24a384b77a6a2251784f1974494c
/Lien/JavaFastTrack/src/sinhVien/ATM.java
b241db929d0b1f1bc2f39048f681d526503a74b1
[]
no_license
FASTTRACKSE/FTJD1801_JavaCore
https://github.com/FASTTRACKSE/FTJD1801_JavaCore
63a0da63ce6c809a70204b3a9ba5c23855574f56
df6ac17cd0e595a791108d3d7697af94dc626350
refs/heads/master
2020-03-18T14:24:37.757000
2019-05-09T10:20:14
2019-05-09T10:20:14
134,846,650
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sinhVien; import java.util.Scanner; import baitapStudent.QuanLiSinhVien; public class ATM { public String maTK; public String tenTK; public int soDu; public String loaiTien; public String trangThai; public ATM() { super(); } public ATM(String maTK, String tenTK, int soDu, String loaiTien, String trangThai) { super(); this.maTK = maTK; this.tenTK = tenTK; this.soDu = soDu; this.loaiTien = loaiTien; this.trangThai = trangThai; } public String getMaTK() { return maTK; } public void setMaTK(String maTK) { this.maTK = maTK; } public String getTenTK() { return tenTK; } public void setTenTK(String tenTK) { this.tenTK = tenTK; } public int getSoDu() { return soDu; } public void setSoDu(int soDu) { this.soDu = soDu; } public String getLoaiTien() { return loaiTien; } public void setLoaiTien(String loaiTien) { this.loaiTien = loaiTien; } public String getTrangThai() { return trangThai; } public void setTrangThai(String trangThai) { this.trangThai = trangThai; } public void user() { Scanner sc= new Scanner(System.in); System.out.println("Vui lòng nhập mã tài khoản:"); maTK = sc.nextLine(); System.out.println("Vui lòng nhập tên tài khoản: "); tenTK = sc.nextLine(); System.out.println("Vui lòng nhập số dư tài khoản: "); soDu = Integer.parseInt(sc.nextLine()) ; System.out.println("Vui lòng nhập loại tiền: "); loaiTien = sc.nextLine(); System.out.println("trạng thái: "); trangThai = sc.nextLine(); } public static void main(String[] args) { // TODO Auto-generated method stub } }
UTF-8
Java
1,653
java
ATM.java
Java
[]
null
[]
package sinhVien; import java.util.Scanner; import baitapStudent.QuanLiSinhVien; public class ATM { public String maTK; public String tenTK; public int soDu; public String loaiTien; public String trangThai; public ATM() { super(); } public ATM(String maTK, String tenTK, int soDu, String loaiTien, String trangThai) { super(); this.maTK = maTK; this.tenTK = tenTK; this.soDu = soDu; this.loaiTien = loaiTien; this.trangThai = trangThai; } public String getMaTK() { return maTK; } public void setMaTK(String maTK) { this.maTK = maTK; } public String getTenTK() { return tenTK; } public void setTenTK(String tenTK) { this.tenTK = tenTK; } public int getSoDu() { return soDu; } public void setSoDu(int soDu) { this.soDu = soDu; } public String getLoaiTien() { return loaiTien; } public void setLoaiTien(String loaiTien) { this.loaiTien = loaiTien; } public String getTrangThai() { return trangThai; } public void setTrangThai(String trangThai) { this.trangThai = trangThai; } public void user() { Scanner sc= new Scanner(System.in); System.out.println("Vui lòng nhập mã tài khoản:"); maTK = sc.nextLine(); System.out.println("Vui lòng nhập tên tài khoản: "); tenTK = sc.nextLine(); System.out.println("Vui lòng nhập số dư tài khoản: "); soDu = Integer.parseInt(sc.nextLine()) ; System.out.println("Vui lòng nhập loại tiền: "); loaiTien = sc.nextLine(); System.out.println("trạng thái: "); trangThai = sc.nextLine(); } public static void main(String[] args) { // TODO Auto-generated method stub } }
1,653
0.676543
0.676543
87
17.620689
17.357128
85
false
false
0
0
0
0
0
0
1.666667
false
false
15
2c9c3db4dbc3ea3424ed9db18c44c615661b2a0b
30,700,426,257,080
f1528b73c79cf67644b247bc1fcb82ffa8d2f751
/app/src/main/java/com/example/usuario/tcu_655/BaseDeDatos/TomasDeAgua.java
05acc6c1917277258e7f4f0f411c3f88176f0937
[]
no_license
geraldvindas/tcu_655_aplicacion
https://github.com/geraldvindas/tcu_655_aplicacion
0373b518e10e0a36bb7d65c8f2acea621e6d9f84
1e87416ad9ad15f831cd93ee2422d31259138707
refs/heads/master
2020-04-21T02:58:54.983000
2019-02-23T13:34:10
2019-02-23T13:34:10
169,270,845
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.usuario.tcu_655.BaseDeDatos; public class TomasDeAgua { String zona; String calidad; String imagen1; String descripcion1; String imagen2; String descripcion2; public TomasDeAgua(String zona, String calidad, String imagen1, String descripcion1, String imagen2, String descripcion2){ this.setZona(zona); this.setCalidad(calidad); this.setImagen1(imagen1); this.setDescripcion1(descripcion1); this.setImagen2(imagen2); this.setDescripcion2(descripcion2); } public String getZona() { return zona; } public void setZona(String zona) { this.zona = zona; } public String getCalidad() { return calidad; } public void setCalidad(String calidad) { this.calidad = calidad; } public String getImagen1() { return imagen1; } public void setImagen1(String imagen1) { this.imagen1 = imagen1; } public String getDescripcion1() { return descripcion1; } public void setDescripcion1(String descripcion1) { this.descripcion1 = descripcion1; } public String getImagen2() { return imagen2; } public void setImagen2(String imagen2) { this.imagen2 = imagen2; } public String getDescripcion2() { return descripcion2; } public void setDescripcion2(String descripcion2) { this.descripcion2 = descripcion2; } }
UTF-8
Java
1,488
java
TomasDeAgua.java
Java
[]
null
[]
package com.example.usuario.tcu_655.BaseDeDatos; public class TomasDeAgua { String zona; String calidad; String imagen1; String descripcion1; String imagen2; String descripcion2; public TomasDeAgua(String zona, String calidad, String imagen1, String descripcion1, String imagen2, String descripcion2){ this.setZona(zona); this.setCalidad(calidad); this.setImagen1(imagen1); this.setDescripcion1(descripcion1); this.setImagen2(imagen2); this.setDescripcion2(descripcion2); } public String getZona() { return zona; } public void setZona(String zona) { this.zona = zona; } public String getCalidad() { return calidad; } public void setCalidad(String calidad) { this.calidad = calidad; } public String getImagen1() { return imagen1; } public void setImagen1(String imagen1) { this.imagen1 = imagen1; } public String getDescripcion1() { return descripcion1; } public void setDescripcion1(String descripcion1) { this.descripcion1 = descripcion1; } public String getImagen2() { return imagen2; } public void setImagen2(String imagen2) { this.imagen2 = imagen2; } public String getDescripcion2() { return descripcion2; } public void setDescripcion2(String descripcion2) { this.descripcion2 = descripcion2; } }
1,488
0.637097
0.608199
67
21.208956
20.943804
126
false
false
0
0
0
0
0
0
0.447761
false
false
15
08a035861b20ea877cf671d6e4cfb597b4efa995
12,292,196,416,036
94acef5d37af5dcecf9ac544a92bb95c70dac7fa
/app/src/main/java/com/projects/wens/kandoeteami/organisation/data/GroupItem.java
e7abd3de6a87806a4f424efd5dcc841beacb0041
[]
no_license
teamiip2kdgbe/kandoeteami
https://github.com/teamiip2kdgbe/kandoeteami
74579b6ae6ec5e82aa4f68dd9bd666759aab8cef
46941813e8e4019d161b2a9e80562974ff909c63
refs/heads/master
2021-01-10T02:51:48.904000
2016-03-25T08:55:15
2016-03-25T08:55:15
52,361,135
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.projects.wens.kandoeteami.organisation.data; import java.util.ArrayList; import java.util.List; /** * Created by senne on 04/03/2016. */ public class GroupItem { public String title; public List<ChildItem> children; public GroupItem(String title) { this.title = title; children = new ArrayList<ChildItem>(); } public String getTitle() { return title; } public List<ChildItem> getChildren() { return children; } public void addChildren(ChildItem item){ children.add(item); } }
UTF-8
Java
576
java
GroupItem.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by senne on 04/03/2016.\n */\npublic class GroupItem {\n p", "end": 133, "score": 0.9986711740493774, "start": 128, "tag": "USERNAME", "value": "senne" } ]
null
[]
package com.projects.wens.kandoeteami.organisation.data; import java.util.ArrayList; import java.util.List; /** * Created by senne on 04/03/2016. */ public class GroupItem { public String title; public List<ChildItem> children; public GroupItem(String title) { this.title = title; children = new ArrayList<ChildItem>(); } public String getTitle() { return title; } public List<ChildItem> getChildren() { return children; } public void addChildren(ChildItem item){ children.add(item); } }
576
0.644097
0.630208
29
18.862068
16.857872
56
false
false
0
0
0
0
0
0
0.344828
false
false
15
bd6ec980ce661898d215261f16d76290edbaa508
7,876,970,069,945
f4b9a1e84ad1be2552ec1765ed68b320451e7d91
/src/main/java/stepan/lys/service/utils/FixerIoClient.java
fdfae533ced2cd69333bef6a8be8fa2d85af98a4
[]
no_license
stepanLys/intelliarts
https://github.com/stepanLys/intelliarts
f6554608bd7d1cdfceaf6775144b51bda87b6dce
78eacff1b0bcbc259b274a57297eb6dedaea97e1
refs/heads/master
2020-05-17T15:29:02.922000
2019-05-14T12:51:54
2019-05-14T12:51:54
183,791,572
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package stepan.lys.service.utils; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import java.util.Objects; import java.util.Set; import static stepan.lys.constants.FixerIoConst.FIXERIO_URL; @Component public class FixerIoClient { private RestTemplate restTemplate; private Map rates; private Set currency; public FixerIoClient() { restTemplate = new RestTemplate(); } public Map getRates() { try { rates = (Map) Objects.requireNonNull( restTemplate.getForObject(new URI(FIXERIO_URL), Map.class) ).get("rates"); } catch (URISyntaxException e) { e.printStackTrace(); } return rates; } public Set getCurrency() { currency = getRates().keySet(); return currency; } }
UTF-8
Java
954
java
FixerIoClient.java
Java
[]
null
[]
package stepan.lys.service.utils; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import java.util.Objects; import java.util.Set; import static stepan.lys.constants.FixerIoConst.FIXERIO_URL; @Component public class FixerIoClient { private RestTemplate restTemplate; private Map rates; private Set currency; public FixerIoClient() { restTemplate = new RestTemplate(); } public Map getRates() { try { rates = (Map) Objects.requireNonNull( restTemplate.getForObject(new URI(FIXERIO_URL), Map.class) ).get("rates"); } catch (URISyntaxException e) { e.printStackTrace(); } return rates; } public Set getCurrency() { currency = getRates().keySet(); return currency; } }
954
0.655136
0.655136
42
21.714285
19.047916
78
false
false
0
0
0
0
0
0
0.452381
false
false
15
ca83598bb376e69d5880193f55871a4b7e3482a2
6,786,048,335,966
82ec7a38b9c68455a6a4ff42499ab1d40533e84f
/src/main/java/com/yinhai/weixin/model/message/TextMessage.java
0ee798593915743556e29d4bb519869a5357c620
[]
no_license
hanjiangriver/cdsi-weixin-pay
https://github.com/hanjiangriver/cdsi-weixin-pay
8301d08c2482bbd093479eb13a9ec91965f679c5
d39c87f7f97df74b081fa21698f9640ed0d48b51
refs/heads/master
2020-04-07T12:37:33.171000
2018-03-12T02:25:28
2018-03-12T02:25:28
124,212,030
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yinhai.weixin.model.message; /** * 文本消息 * Created by 张汉江 on 2018/3/11 */ public class TextMessage extends BasicMessage { //消息内容 private String content; public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "TextMessage{" + "content='" + content + '\'' + "} " + super.toString(); } }
UTF-8
Java
520
java
TextMessage.java
Java
[ { "context": ".weixin.model.message;\n\n/**\n * 文本消息\n * Created by 张汉江 on 2018/3/11\n */\npublic class TextMessage extends", "end": 71, "score": 0.9993627667427063, "start": 68, "tag": "NAME", "value": "张汉江" } ]
null
[]
package com.yinhai.weixin.model.message; /** * 文本消息 * Created by 张汉江 on 2018/3/11 */ public class TextMessage extends BasicMessage { //消息内容 private String content; public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "TextMessage{" + "content='" + content + '\'' + "} " + super.toString(); } }
520
0.566265
0.552209
25
18.92
16.646729
47
false
false
0
0
0
0
0
0
0.2
false
false
15
00ba8636e5a3e284558ae60dc1d3dbe092e54e6e
14,851,996,918,002
5240af522533bff8dee146016f0607c9789b9659
/app/model/Round.java
68f04bbcc4caaaf766c4f456e3b62d029fe9a238
[]
no_license
komielHmadih/src
https://github.com/komielHmadih/src
2ebcd0996e32bc3c99893161cdec2025037271b1
a8feb07170c866a942841e0bd3a8214705efdf66
refs/heads/master
2023-06-01T17:11:38.581000
2021-06-17T14:15:32
2021-06-17T14:15:32
377,531,696
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app.model; import java.util.List; import java.util.Scanner; public class Round { private int id; private int playerStarted; private Earth mat1; private Earth mat2; int score1 = 8000; int score2 = 8000; //constructor public Round() { } public int getScore1() { return score1; } public void setScore1(int score1) { this.score1 = score1; } public int getScore2() { return score2; } public void setScore2(int score2) { this.score2 = score2; } public Earth getMat1() { return mat1; } public void setMat1(Earth mat1) { this.mat1 = mat1; } public Earth getMat2() { return mat2; } public void setMat2(Earth mat2) { this.mat2 = mat2; } //get and set public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPlayerStarted() { return playerStarted; } public void setPlayerStarted(int playerStarted) { this.playerStarted = playerStarted; } //methods public void startGame() { } public void ai() { } // to increase my money public void increaseMoney() { System.out.println(" enter code money"); Scanner scan = new Scanner(System.in); if (scan.next().equals("increaseMoney")) { this.setScore1(8000); } } // to decrease the money of the second player public void decreaseMoney() { System.out.println(" enter code money"); Scanner scan = new Scanner(System.in); if (scan.next().equals("decreaseMoney")) { this.setScore2(100); } } // to add force card public Card addForceCard(List<Card> cardList) { System.out.println("enter name card"); Card ca = new Card(); Scanner scan = new Scanner(System.in); for (Card card : cardList) { if (card.getName().equals(scan.next())) { ca = card; } } if (ca.getPlace() instanceof Place1) { ((Place1) ca.getPlace()).getCardList().remove(ca); Place2 place[] = (Place2[]) this.getMat1().getHandPlace(); //for (Place place : this.getMat1().getPlaceList()) { // if (place.getType().equals(TypePlace.INHAND)) { // if (place instanceof Place1) for(int i=0;i<place.length;i++){ if(place[i].getCard() == null){ place[i].setCard(ca) ; break; } } } //} return ca; } // to make me the winner public void makeMeWinner() { this.setScore2(0); System.out.println("you win"); } }
UTF-8
Java
2,835
java
Round.java
Java
[]
null
[]
package app.model; import java.util.List; import java.util.Scanner; public class Round { private int id; private int playerStarted; private Earth mat1; private Earth mat2; int score1 = 8000; int score2 = 8000; //constructor public Round() { } public int getScore1() { return score1; } public void setScore1(int score1) { this.score1 = score1; } public int getScore2() { return score2; } public void setScore2(int score2) { this.score2 = score2; } public Earth getMat1() { return mat1; } public void setMat1(Earth mat1) { this.mat1 = mat1; } public Earth getMat2() { return mat2; } public void setMat2(Earth mat2) { this.mat2 = mat2; } //get and set public int getId() { return id; } public void setId(int id) { this.id = id; } public int getPlayerStarted() { return playerStarted; } public void setPlayerStarted(int playerStarted) { this.playerStarted = playerStarted; } //methods public void startGame() { } public void ai() { } // to increase my money public void increaseMoney() { System.out.println(" enter code money"); Scanner scan = new Scanner(System.in); if (scan.next().equals("increaseMoney")) { this.setScore1(8000); } } // to decrease the money of the second player public void decreaseMoney() { System.out.println(" enter code money"); Scanner scan = new Scanner(System.in); if (scan.next().equals("decreaseMoney")) { this.setScore2(100); } } // to add force card public Card addForceCard(List<Card> cardList) { System.out.println("enter name card"); Card ca = new Card(); Scanner scan = new Scanner(System.in); for (Card card : cardList) { if (card.getName().equals(scan.next())) { ca = card; } } if (ca.getPlace() instanceof Place1) { ((Place1) ca.getPlace()).getCardList().remove(ca); Place2 place[] = (Place2[]) this.getMat1().getHandPlace(); //for (Place place : this.getMat1().getPlaceList()) { // if (place.getType().equals(TypePlace.INHAND)) { // if (place instanceof Place1) for(int i=0;i<place.length;i++){ if(place[i].getCard() == null){ place[i].setCard(ca) ; break; } } } //} return ca; } // to make me the winner public void makeMeWinner() { this.setScore2(0); System.out.println("you win"); } }
2,835
0.529101
0.5097
128
21.148438
18.019127
70
false
false
0
0
0
0
0
0
0.3125
false
false
15
cb83c63de529a84cb0e5b0163f0478beea3129c7
420,906,799,079
df1fe670c5ebf5ecd54778fd66044ee070468514
/src/com/magicare/smartnurse/activity/ConcernActivity.java
2e13b987ad715d254125ce81a68df5b64ded2a90
[]
no_license
rice1985/SmartNurse
https://github.com/rice1985/SmartNurse
852c7e109cc13fa7629b9da9718c2384aec48f18
7fd236e300f6f365f3d6ba5498a7d941211ee065
refs/heads/master
2016-09-06T11:42:31.441000
2015-11-26T17:16:21
2015-11-26T17:16:21
39,117,249
0
1
null
false
2015-11-26T12:07:31
2015-07-15T05:02:25
2015-07-15T08:54:57
2015-11-26T12:07:30
48,377
0
0
0
Java
null
null
package com.magicare.smartnurse.activity; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.MediaStore; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.magicare.smartnurse.R; import com.magicare.smartnurse.adapter.ConcernDetailAdapter; import com.magicare.smartnurse.bean.BaseBean; import com.magicare.smartnurse.bean.ConcernBean; import com.magicare.smartnurse.bean.UserBean; import com.magicare.smartnurse.database.dao.DBUser; import com.magicare.smartnurse.net.HttpClientUtil; import com.magicare.smartnurse.net.IOperationResult; import com.magicare.smartnurse.utils.BitmpUtils; import com.magicare.smartnurse.utils.ConfigManager; import com.magicare.smartnurse.utils.Constants; import com.magicare.smartnurse.utils.FileUtils; import com.magicare.smartnurse.utils.LogUtil; import com.magicare.smartnurse.utils.PromptManager; import com.magicare.smartnurse.view.CircleImageView; public class ConcernActivity extends BaseActivity { private ListView lv_concern; private TextView child_name; private Button concernHistory; private ConcernBean concern; private CircleImageView iv_photo; private Button btn_back; private Button send_concern; private Button add_image; private EditText et_concern; private Context mContext; private Bitmap reply_img; private UserBean userBean; private final int REFRESH_CONCERN = 0; private final int REFRESH_IMAGE = 1; private final int REPLY_IMAGE = 2; public static final String action = "ConcernActivity action"; private ConcernDetailAdapter mAdapter; private List<ConcernBean> concernlist = new ArrayList<ConcernBean>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_concern); mContext = ConcernActivity.this; lv_concern = (ListView) findViewById(R.id.lv_concern); child_name = (TextView) findViewById(R.id.child_name); concernHistory = (Button) findViewById(R.id.concern_history); iv_photo = (CircleImageView) findViewById(R.id.iv_photo); btn_back = (Button) findViewById(R.id.btn_back); send_concern = (Button) findViewById(R.id.send_concern); add_image = (Button) findViewById(R.id.add_image); et_concern = (EditText) findViewById(R.id.et_concern); btn_back.setOnClickListener(this); send_concern.setOnClickListener(this); add_image.setOnClickListener(this); concernHistory.setOnClickListener(this); et_concern.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() > 0) { add_image.setVisibility(View.GONE); send_concern.setVisibility(View.VISIBLE); } else { add_image.setVisibility(View.VISIBLE); send_concern.setVisibility(View.GONE); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); initConcern(); } /** * 叮嘱详情初始化 */ private void initConcern() { concern = (ConcernBean) getIntent().getSerializableExtra("concernbean"); String photopath = FileUtils.SDPATH + concern.getOld_id() + ".JPEG"; File file = new File(photopath); if (file.exists()) { Bitmap bitmap = BitmpUtils.getLoacalBitmap(photopath); bitmap = BitmpUtils.createFramedPhoto(480, 480, bitmap, (int) (10 * 1.6f)); iv_photo.setImageBitmap(bitmap); } DBUser dbuser = DBUser.getInstance(ConcernActivity.this); dbuser.open(); userBean = dbuser.getUserInfoById(concern.getOld_id() + ""); dbuser.close(); child_name.setText(userBean.getName() + "之" + userBean.getChild_relation() + concern.getChild_name() + "的叮嘱"); concernlist.add(concern); mAdapter = new ConcernDetailAdapter(ConcernActivity.this, concernlist); lv_concern.setAdapter(mAdapter); } @Override public void onClick(View view) { super.onClick(view); switch (view.getId()) { case R.id.btn_back: finish(); break; case R.id.concern_history: Intent intent = new Intent(this, ConcernHistory.class); intent.putExtra("userbean", userBean); startActivity(intent); break; case R.id.send_concern: if (!TextUtils.isEmpty(et_concern.getText())) { concern.setReply_content(et_concern.getText().toString()); concern.setStatus(1); } concernlist.clear(); concernlist.add(concern); mHandler.sendEmptyMessage(REFRESH_CONCERN); break; case R.id.add_image: String sdcardState = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(sdcardState)) { new PopupWindows(ConcernActivity.this, lv_concern); } else { PromptManager.showToast(getApplicationContext(), false, "sdcard已拔出,不能选择照片"); } break; default: break; } } @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case REFRESH_CONCERN: // 在线程中刷新叮嘱详情界面 Log.e("dingzhu_concernactivity", ""); if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } else { mAdapter = new ConcernDetailAdapter(ConcernActivity.this, concernlist); lv_concern.setAdapter(mAdapter); } updateConcern(); /* * Intent intent = new Intent(action); intent.putExtra("data", * ""); * * ConcernActivity.this.sendBroadcast(intent); */ break; case REFRESH_IMAGE: if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } else { mAdapter = new ConcernDetailAdapter(ConcernActivity.this, concernlist); lv_concern.setAdapter(mAdapter); } updateConcernImg(); // 上传图片 break; // case REPLY_IMAGE: // replyImg(); //返回叮嘱图片路径到一条叮嘱中 default: break; } }; }; /** * * Function:上传叮嘱回复信息 * */ private void updateConcern() { HttpClientUtil client = HttpClientUtil.getInstance(); client.updateConcern(mContext, ConfigManager.getStringValue(mContext, Constants.ACCESS_TOKEN), concern.getExhort_id(), concern.getReply_images(), concern.getReply_content(), new IOperationResult() { @Override public void operationResult(boolean isSuccess, String json, String errors) { if (isSuccess) { if (TextUtils.isEmpty(json) || !json.startsWith("{")) { PromptManager.showToast( getApplicationContext(), false, "数据为空,请检查您的网络,重新操作一次!"); } else { BaseBean baseBean = JSON.parseObject(json, BaseBean.class); if (baseBean.getStatus() == 0) { et_concern.setText(""); PromptManager.showToast(mContext, "上传文字成功"); } else { PromptManager.showToast(mContext, false, errors); } } } else { PromptManager.showToast(mContext, false, errors); } } }); } /** * * Function:上传叮嘱回复图片 * */ private void updateConcernImg() { String img = FileUtils.SDPATH + userBean.getOld_id() + "rice.JPEG"; HttpClientUtil client = HttpClientUtil.getInstance(); client.uploadImg(this, ConfigManager.getStringValue( getApplicationContext(), Constants.ACCESS_TOKEN), img, new IOperationResult() { @Override public void operationResult(boolean isSuccess, String json, String errors) { if (isSuccess) { if (TextUtils.isEmpty(json) || !json.startsWith("{")) { PromptManager.showToast( getApplicationContext(), false, "上传图片失败,请检查网络!"); } else { BaseBean baseBean = JSON.parseObject(json, BaseBean.class); if (baseBean.getStatus() == 0) { JSONObject object = JSONObject .parseObject(baseBean.getData()); // String img_id = // object.getString("img_id"); // String img_url = // object.getString("img_url"); LogUtil.info("lhw", "object=" + object.toJSONString()); concern.setReply_images("[" + object.toJSONString() + "]"); replyImg();// 上传图片链接 } else { PromptManager.showToast( getApplicationContext(), false, baseBean.getInfo()); } } } else { PromptManager.showToast(getApplicationContext(), false, errors); } } }); } /** * * Function:上传叮嘱图片链接 * */ private void replyImg() { HttpClientUtil client = HttpClientUtil.getInstance(); client.updateConcern(mContext, ConfigManager.getStringValue(mContext, Constants.ACCESS_TOKEN), concern.getExhort_id(), concern.getReply_images(), concern.getReply_content(), new IOperationResult() { @Override public void operationResult(boolean isSuccess, String json, String errors) { if (isSuccess) { if (TextUtils.isEmpty(json) || !json.startsWith("{")) { PromptManager.showToast(mContext, false, "数据为空,请检查您的网络,重新操作一次!"); } else { BaseBean baseBean = JSON.parseObject(json, BaseBean.class); if (baseBean.getStatus() == 0) { PromptManager.showToast(mContext, "上传图片成功"); } else { PromptManager.showToast(mContext, false, errors); } } } else { PromptManager.showToast(mContext, false, errors); } } }); } private static final int TAKE_PICTURE = 0; private static final int RESULT_LOAD_IMAGE = 1; private String path = ""; private Uri photoUri; public class PopupWindows extends PopupWindow { public PopupWindows(Context mContext, View parent) { View view = View .inflate(mContext, R.layout.item_popupwindows, null); view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins)); setWidth(LayoutParams.MATCH_PARENT); setHeight(LayoutParams.MATCH_PARENT); setBackgroundDrawable(new BitmapDrawable()); setFocusable(true); setOutsideTouchable(true); setContentView(view); showAtLocation(parent, Gravity.BOTTOM, 0, 0); update(); Button bt1 = (Button) view .findViewById(R.id.item_popupwindows_camera); Button bt2 = (Button) view .findViewById(R.id.item_popupwindows_Photo); Button bt3 = (Button) view .findViewById(R.id.item_popupwindows_cancel); bt1.setOnClickListener(new OnClickListener() { public void onClick(View v) { photo(); dismiss(); } }); bt2.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE); dismiss(); } }); bt3.setOnClickListener(new OnClickListener() { public void onClick(View v) { dismiss(); } }); } } public void photo() { try { Intent openCameraIntent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); String sdcardState = Environment.getExternalStorageState(); String sdcardPathDir = android.os.Environment .getExternalStorageDirectory().getPath() + "/tempImage/"; File file = null; if (Environment.MEDIA_MOUNTED.equals(sdcardState)) { // 有sd卡,是否有myImage文件夹 File fileDir = new File(sdcardPathDir); if (!fileDir.exists()) { fileDir.mkdirs(); } // 是否有headImg文件 file = new File(sdcardPathDir + userBean.getOld_id() + "rice.JPEG"); } if (file != null) { path = file.getPath(); photoUri = Uri.fromFile(file); openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); startActivityForResult(openCameraIntent, TAKE_PICTURE); } } catch (Exception e) { e.printStackTrace(); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case TAKE_PICTURE: if (resultCode == -1) {// 拍照 savePhoto(null); } break; case RESULT_LOAD_IMAGE: if (resultCode == RESULT_OK && null != data) {// 相册返回 Uri uri = data.getData(); if (uri != null) { savePhoto(uri); } } break; } } private void savePhoto(Uri uri) { try { if (!FileUtils.isFileExist("")) { FileUtils.createSDDir(""); } if (uri != null) { // reply_img = // BitmpUtils.getLoacalBitmap(getRealPathFromURI(uri)); reply_img = BitmpUtils .revitionImageSize(getRealPathFromURI(uri)); } else { // reply_img = BitmpUtils.getLoacalBitmap(path); reply_img = BitmpUtils.revitionImageSize(path); } FileUtils.saveBitmap(reply_img, userBean.getOld_id() + "rice"); concernlist.clear(); concern.setStatus(1); concernlist.add(concern); mHandler.sendEmptyMessage(REFRESH_IMAGE); String sdcardPathDir = android.os.Environment .getExternalStorageDirectory().getPath() + "/tempImage/"; FileUtils.deleteDir(sdcardPathDir); } catch (IOException e) { e.printStackTrace(); } } public String getRealPathFromURI(Uri contentUri) { String res = null; String[] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null); if (cursor.moveToFirst()) { int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); res = cursor.getString(column_index); } cursor.close(); return res; } }
UTF-8
Java
15,032
java
ConcernActivity.java
Java
[]
null
[]
package com.magicare.smartnurse.activity; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.MediaStore; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.magicare.smartnurse.R; import com.magicare.smartnurse.adapter.ConcernDetailAdapter; import com.magicare.smartnurse.bean.BaseBean; import com.magicare.smartnurse.bean.ConcernBean; import com.magicare.smartnurse.bean.UserBean; import com.magicare.smartnurse.database.dao.DBUser; import com.magicare.smartnurse.net.HttpClientUtil; import com.magicare.smartnurse.net.IOperationResult; import com.magicare.smartnurse.utils.BitmpUtils; import com.magicare.smartnurse.utils.ConfigManager; import com.magicare.smartnurse.utils.Constants; import com.magicare.smartnurse.utils.FileUtils; import com.magicare.smartnurse.utils.LogUtil; import com.magicare.smartnurse.utils.PromptManager; import com.magicare.smartnurse.view.CircleImageView; public class ConcernActivity extends BaseActivity { private ListView lv_concern; private TextView child_name; private Button concernHistory; private ConcernBean concern; private CircleImageView iv_photo; private Button btn_back; private Button send_concern; private Button add_image; private EditText et_concern; private Context mContext; private Bitmap reply_img; private UserBean userBean; private final int REFRESH_CONCERN = 0; private final int REFRESH_IMAGE = 1; private final int REPLY_IMAGE = 2; public static final String action = "ConcernActivity action"; private ConcernDetailAdapter mAdapter; private List<ConcernBean> concernlist = new ArrayList<ConcernBean>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_concern); mContext = ConcernActivity.this; lv_concern = (ListView) findViewById(R.id.lv_concern); child_name = (TextView) findViewById(R.id.child_name); concernHistory = (Button) findViewById(R.id.concern_history); iv_photo = (CircleImageView) findViewById(R.id.iv_photo); btn_back = (Button) findViewById(R.id.btn_back); send_concern = (Button) findViewById(R.id.send_concern); add_image = (Button) findViewById(R.id.add_image); et_concern = (EditText) findViewById(R.id.et_concern); btn_back.setOnClickListener(this); send_concern.setOnClickListener(this); add_image.setOnClickListener(this); concernHistory.setOnClickListener(this); et_concern.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() > 0) { add_image.setVisibility(View.GONE); send_concern.setVisibility(View.VISIBLE); } else { add_image.setVisibility(View.VISIBLE); send_concern.setVisibility(View.GONE); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); initConcern(); } /** * 叮嘱详情初始化 */ private void initConcern() { concern = (ConcernBean) getIntent().getSerializableExtra("concernbean"); String photopath = FileUtils.SDPATH + concern.getOld_id() + ".JPEG"; File file = new File(photopath); if (file.exists()) { Bitmap bitmap = BitmpUtils.getLoacalBitmap(photopath); bitmap = BitmpUtils.createFramedPhoto(480, 480, bitmap, (int) (10 * 1.6f)); iv_photo.setImageBitmap(bitmap); } DBUser dbuser = DBUser.getInstance(ConcernActivity.this); dbuser.open(); userBean = dbuser.getUserInfoById(concern.getOld_id() + ""); dbuser.close(); child_name.setText(userBean.getName() + "之" + userBean.getChild_relation() + concern.getChild_name() + "的叮嘱"); concernlist.add(concern); mAdapter = new ConcernDetailAdapter(ConcernActivity.this, concernlist); lv_concern.setAdapter(mAdapter); } @Override public void onClick(View view) { super.onClick(view); switch (view.getId()) { case R.id.btn_back: finish(); break; case R.id.concern_history: Intent intent = new Intent(this, ConcernHistory.class); intent.putExtra("userbean", userBean); startActivity(intent); break; case R.id.send_concern: if (!TextUtils.isEmpty(et_concern.getText())) { concern.setReply_content(et_concern.getText().toString()); concern.setStatus(1); } concernlist.clear(); concernlist.add(concern); mHandler.sendEmptyMessage(REFRESH_CONCERN); break; case R.id.add_image: String sdcardState = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(sdcardState)) { new PopupWindows(ConcernActivity.this, lv_concern); } else { PromptManager.showToast(getApplicationContext(), false, "sdcard已拔出,不能选择照片"); } break; default: break; } } @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case REFRESH_CONCERN: // 在线程中刷新叮嘱详情界面 Log.e("dingzhu_concernactivity", ""); if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } else { mAdapter = new ConcernDetailAdapter(ConcernActivity.this, concernlist); lv_concern.setAdapter(mAdapter); } updateConcern(); /* * Intent intent = new Intent(action); intent.putExtra("data", * ""); * * ConcernActivity.this.sendBroadcast(intent); */ break; case REFRESH_IMAGE: if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } else { mAdapter = new ConcernDetailAdapter(ConcernActivity.this, concernlist); lv_concern.setAdapter(mAdapter); } updateConcernImg(); // 上传图片 break; // case REPLY_IMAGE: // replyImg(); //返回叮嘱图片路径到一条叮嘱中 default: break; } }; }; /** * * Function:上传叮嘱回复信息 * */ private void updateConcern() { HttpClientUtil client = HttpClientUtil.getInstance(); client.updateConcern(mContext, ConfigManager.getStringValue(mContext, Constants.ACCESS_TOKEN), concern.getExhort_id(), concern.getReply_images(), concern.getReply_content(), new IOperationResult() { @Override public void operationResult(boolean isSuccess, String json, String errors) { if (isSuccess) { if (TextUtils.isEmpty(json) || !json.startsWith("{")) { PromptManager.showToast( getApplicationContext(), false, "数据为空,请检查您的网络,重新操作一次!"); } else { BaseBean baseBean = JSON.parseObject(json, BaseBean.class); if (baseBean.getStatus() == 0) { et_concern.setText(""); PromptManager.showToast(mContext, "上传文字成功"); } else { PromptManager.showToast(mContext, false, errors); } } } else { PromptManager.showToast(mContext, false, errors); } } }); } /** * * Function:上传叮嘱回复图片 * */ private void updateConcernImg() { String img = FileUtils.SDPATH + userBean.getOld_id() + "rice.JPEG"; HttpClientUtil client = HttpClientUtil.getInstance(); client.uploadImg(this, ConfigManager.getStringValue( getApplicationContext(), Constants.ACCESS_TOKEN), img, new IOperationResult() { @Override public void operationResult(boolean isSuccess, String json, String errors) { if (isSuccess) { if (TextUtils.isEmpty(json) || !json.startsWith("{")) { PromptManager.showToast( getApplicationContext(), false, "上传图片失败,请检查网络!"); } else { BaseBean baseBean = JSON.parseObject(json, BaseBean.class); if (baseBean.getStatus() == 0) { JSONObject object = JSONObject .parseObject(baseBean.getData()); // String img_id = // object.getString("img_id"); // String img_url = // object.getString("img_url"); LogUtil.info("lhw", "object=" + object.toJSONString()); concern.setReply_images("[" + object.toJSONString() + "]"); replyImg();// 上传图片链接 } else { PromptManager.showToast( getApplicationContext(), false, baseBean.getInfo()); } } } else { PromptManager.showToast(getApplicationContext(), false, errors); } } }); } /** * * Function:上传叮嘱图片链接 * */ private void replyImg() { HttpClientUtil client = HttpClientUtil.getInstance(); client.updateConcern(mContext, ConfigManager.getStringValue(mContext, Constants.ACCESS_TOKEN), concern.getExhort_id(), concern.getReply_images(), concern.getReply_content(), new IOperationResult() { @Override public void operationResult(boolean isSuccess, String json, String errors) { if (isSuccess) { if (TextUtils.isEmpty(json) || !json.startsWith("{")) { PromptManager.showToast(mContext, false, "数据为空,请检查您的网络,重新操作一次!"); } else { BaseBean baseBean = JSON.parseObject(json, BaseBean.class); if (baseBean.getStatus() == 0) { PromptManager.showToast(mContext, "上传图片成功"); } else { PromptManager.showToast(mContext, false, errors); } } } else { PromptManager.showToast(mContext, false, errors); } } }); } private static final int TAKE_PICTURE = 0; private static final int RESULT_LOAD_IMAGE = 1; private String path = ""; private Uri photoUri; public class PopupWindows extends PopupWindow { public PopupWindows(Context mContext, View parent) { View view = View .inflate(mContext, R.layout.item_popupwindows, null); view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins)); setWidth(LayoutParams.MATCH_PARENT); setHeight(LayoutParams.MATCH_PARENT); setBackgroundDrawable(new BitmapDrawable()); setFocusable(true); setOutsideTouchable(true); setContentView(view); showAtLocation(parent, Gravity.BOTTOM, 0, 0); update(); Button bt1 = (Button) view .findViewById(R.id.item_popupwindows_camera); Button bt2 = (Button) view .findViewById(R.id.item_popupwindows_Photo); Button bt3 = (Button) view .findViewById(R.id.item_popupwindows_cancel); bt1.setOnClickListener(new OnClickListener() { public void onClick(View v) { photo(); dismiss(); } }); bt2.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE); dismiss(); } }); bt3.setOnClickListener(new OnClickListener() { public void onClick(View v) { dismiss(); } }); } } public void photo() { try { Intent openCameraIntent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); String sdcardState = Environment.getExternalStorageState(); String sdcardPathDir = android.os.Environment .getExternalStorageDirectory().getPath() + "/tempImage/"; File file = null; if (Environment.MEDIA_MOUNTED.equals(sdcardState)) { // 有sd卡,是否有myImage文件夹 File fileDir = new File(sdcardPathDir); if (!fileDir.exists()) { fileDir.mkdirs(); } // 是否有headImg文件 file = new File(sdcardPathDir + userBean.getOld_id() + "rice.JPEG"); } if (file != null) { path = file.getPath(); photoUri = Uri.fromFile(file); openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); startActivityForResult(openCameraIntent, TAKE_PICTURE); } } catch (Exception e) { e.printStackTrace(); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case TAKE_PICTURE: if (resultCode == -1) {// 拍照 savePhoto(null); } break; case RESULT_LOAD_IMAGE: if (resultCode == RESULT_OK && null != data) {// 相册返回 Uri uri = data.getData(); if (uri != null) { savePhoto(uri); } } break; } } private void savePhoto(Uri uri) { try { if (!FileUtils.isFileExist("")) { FileUtils.createSDDir(""); } if (uri != null) { // reply_img = // BitmpUtils.getLoacalBitmap(getRealPathFromURI(uri)); reply_img = BitmpUtils .revitionImageSize(getRealPathFromURI(uri)); } else { // reply_img = BitmpUtils.getLoacalBitmap(path); reply_img = BitmpUtils.revitionImageSize(path); } FileUtils.saveBitmap(reply_img, userBean.getOld_id() + "rice"); concernlist.clear(); concern.setStatus(1); concernlist.add(concern); mHandler.sendEmptyMessage(REFRESH_IMAGE); String sdcardPathDir = android.os.Environment .getExternalStorageDirectory().getPath() + "/tempImage/"; FileUtils.deleteDir(sdcardPathDir); } catch (IOException e) { e.printStackTrace(); } } public String getRealPathFromURI(Uri contentUri) { String res = null; String[] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null); if (cursor.moveToFirst()) { int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); res = cursor.getString(column_index); } cursor.close(); return res; } }
15,032
0.657938
0.655897
502
27.286852
19.941383
80
false
false
0
0
0
0
0
0
3.73506
false
false
15
314ae513e0a925fa9e2694200f704f5692c672d9
8,813,272,902,671
e0e56d3cd5453bde1a35c5442c51d4c6483d5972
/MathNotes/src/com/mathnotes/DrawingSurface.java
7eb7b7e99738b098e94746ad5f3e6dfdea8be009
[]
no_license
LadySnowy/math-notes
https://github.com/LadySnowy/math-notes
88563894ac1391cf8abeeb723977772f46e2a56c
4a8b696af3822d48351f12e291288a8b30970efa
refs/heads/master
2016-09-06T03:55:49.503000
2012-11-27T07:18:47
2012-11-27T07:18:47
33,732,231
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mathnotes; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PorterDuff; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.multitouchcontroller.MultiTouchController; import com.multitouchcontroller.PinchWidget; import com.multitouchcontroller.MultiTouchController.MultiTouchObjectCanvas; import com.multitouchcontroller.MultiTouchController.PointInfo; import com.multitouchcontroller.MultiTouchController.PositionAndScale; public class DrawingSurface extends SurfaceView implements SurfaceHolder.Callback, MultiTouchObjectCanvas<PinchWidget> { private Boolean _run; protected DrawThread thread; public static Bitmap mBitmap; public boolean isDrawing = true; public boolean isDrawCircle = false; public DrawingPath previewPath; private CommandManager commandManager; public static final int UI_MODE_ROTATE = 1; public static final int UI_MODE_ANISOTROPIC_SCALE = 2; public int mUIMode = UI_MODE_ROTATE; public MultiTouchController<PinchWidget> mMultiTouchController = new MultiTouchController<PinchWidget>(this); public int mWidth, mHeight; public static PinchWidget mPinchWidget; public static Context mContext; public static Canvas mCanvas; public DrawingSurface(Context context) { super(context); } public DrawingSurface(Context context, AttributeSet attrs) { super(context, attrs); getHolder().addCallback(this); setCommandManager(new CommandManager()); thread = new DrawThread(getHolder()); mContext = context; } public DrawingSurface(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @SuppressLint("HandlerLeak") private Handler previewDoneHandler = new Handler() { @Override public void handleMessage(Message msg) { isDrawing = false; } }; class DrawThread extends Thread { private SurfaceHolder mSurfaceHolder; public DrawThread(SurfaceHolder surfaceHolder) { mSurfaceHolder = surfaceHolder; } public void setRunning(boolean run) { _run = run; } @Override public void run() { Canvas canvas = null; while (_run) { if (isDrawing == true) { try { canvas = mSurfaceHolder.lockCanvas(null); if (mBitmap == null) { mBitmap = Bitmap.createBitmap(1280, 768, Bitmap.Config.ARGB_8888); } final Canvas c = new Canvas(mBitmap); c.drawColor(0, PorterDuff.Mode.CLEAR); canvas.drawColor(0, PorterDuff.Mode.CLEAR); canvas.drawColor(0xffffffff); commandManager.executeAll(c, previewDoneHandler); previewPath.draw(c); canvas.drawBitmap(mBitmap, 0, 0, null); mCanvas = canvas; } finally { mSurfaceHolder.unlockCanvasAndPost(canvas); } isDrawing = false; } } } } public void addDrawingPath(ICanvasCommand drawingPath) { getCommandManager().addCommand(drawingPath); } public boolean hasMoreRedo() { return getCommandManager().hasMoreRedo(); } public void redo() { isDrawing = true; getCommandManager().redo(); } public void undo() { isDrawing = true; getCommandManager().undo(); } public boolean hasMoreUndo() { return getCommandManager().hasMoreUndo(); } public Bitmap getBitmap() { return mBitmap; } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); } public void surfaceCreated(SurfaceHolder holder) { thread.setRunning(true); thread.start(); } public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; thread.setRunning(false); while (retry) { try { thread.join(); retry = false; } catch (InterruptedException e) { // we will try it again and again... } } } // stuff for MultiTouchController and PinchWidget public static void setPinchWidget(Bitmap bitmap) { mPinchWidget = new PinchWidget(bitmap); mPinchWidget.init(mContext.getResources()); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mWidth = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); mHeight = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(mWidth, mHeight); } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); if (mPinchWidget != null) { mPinchWidget.draw(canvas); } } public PinchWidget getDraggableObjectAtPoint(PointInfo pt) { float x = pt.getX(), y = pt.getY(); if (mPinchWidget != null) { if (mPinchWidget.containsPoint(x, y)) { return mPinchWidget; } } return null; } public void getPositionAndScale(PinchWidget pinchWidget, PositionAndScale objPosAndScaleOut) { objPosAndScaleOut.set(pinchWidget.getCenterX(), pinchWidget.getCenterY(), (mUIMode & UI_MODE_ANISOTROPIC_SCALE) == 0, (pinchWidget.getScaleFactor() + pinchWidget.getScaleFactor()) / 2, (mUIMode & UI_MODE_ANISOTROPIC_SCALE) != 0, pinchWidget.getScaleFactor(), pinchWidget.getScaleFactor(), (mUIMode & UI_MODE_ROTATE) != 0, pinchWidget.getAngle()); } public boolean setPositionAndScale(PinchWidget pinchWidget, PositionAndScale newImgPosAndScale, PointInfo touchPoint) { boolean ok = pinchWidget.setPos(newImgPosAndScale, mUIMode, UI_MODE_ANISOTROPIC_SCALE, touchPoint.isMultiTouch()); if (ok) { invalidate(); } return ok; } public void selectObject(PinchWidget pinchWidget, PointInfo touchPoint) { if (touchPoint.isDown()) { mPinchWidget = pinchWidget; } invalidate(); } public CommandManager getCommandManager() { return commandManager; } public void setCommandManager(CommandManager commandManager) { this.commandManager = commandManager; } }
UTF-8
Java
5,858
java
DrawingSurface.java
Java
[]
null
[]
package com.mathnotes; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PorterDuff; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.multitouchcontroller.MultiTouchController; import com.multitouchcontroller.PinchWidget; import com.multitouchcontroller.MultiTouchController.MultiTouchObjectCanvas; import com.multitouchcontroller.MultiTouchController.PointInfo; import com.multitouchcontroller.MultiTouchController.PositionAndScale; public class DrawingSurface extends SurfaceView implements SurfaceHolder.Callback, MultiTouchObjectCanvas<PinchWidget> { private Boolean _run; protected DrawThread thread; public static Bitmap mBitmap; public boolean isDrawing = true; public boolean isDrawCircle = false; public DrawingPath previewPath; private CommandManager commandManager; public static final int UI_MODE_ROTATE = 1; public static final int UI_MODE_ANISOTROPIC_SCALE = 2; public int mUIMode = UI_MODE_ROTATE; public MultiTouchController<PinchWidget> mMultiTouchController = new MultiTouchController<PinchWidget>(this); public int mWidth, mHeight; public static PinchWidget mPinchWidget; public static Context mContext; public static Canvas mCanvas; public DrawingSurface(Context context) { super(context); } public DrawingSurface(Context context, AttributeSet attrs) { super(context, attrs); getHolder().addCallback(this); setCommandManager(new CommandManager()); thread = new DrawThread(getHolder()); mContext = context; } public DrawingSurface(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @SuppressLint("HandlerLeak") private Handler previewDoneHandler = new Handler() { @Override public void handleMessage(Message msg) { isDrawing = false; } }; class DrawThread extends Thread { private SurfaceHolder mSurfaceHolder; public DrawThread(SurfaceHolder surfaceHolder) { mSurfaceHolder = surfaceHolder; } public void setRunning(boolean run) { _run = run; } @Override public void run() { Canvas canvas = null; while (_run) { if (isDrawing == true) { try { canvas = mSurfaceHolder.lockCanvas(null); if (mBitmap == null) { mBitmap = Bitmap.createBitmap(1280, 768, Bitmap.Config.ARGB_8888); } final Canvas c = new Canvas(mBitmap); c.drawColor(0, PorterDuff.Mode.CLEAR); canvas.drawColor(0, PorterDuff.Mode.CLEAR); canvas.drawColor(0xffffffff); commandManager.executeAll(c, previewDoneHandler); previewPath.draw(c); canvas.drawBitmap(mBitmap, 0, 0, null); mCanvas = canvas; } finally { mSurfaceHolder.unlockCanvasAndPost(canvas); } isDrawing = false; } } } } public void addDrawingPath(ICanvasCommand drawingPath) { getCommandManager().addCommand(drawingPath); } public boolean hasMoreRedo() { return getCommandManager().hasMoreRedo(); } public void redo() { isDrawing = true; getCommandManager().redo(); } public void undo() { isDrawing = true; getCommandManager().undo(); } public boolean hasMoreUndo() { return getCommandManager().hasMoreUndo(); } public Bitmap getBitmap() { return mBitmap; } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); } public void surfaceCreated(SurfaceHolder holder) { thread.setRunning(true); thread.start(); } public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; thread.setRunning(false); while (retry) { try { thread.join(); retry = false; } catch (InterruptedException e) { // we will try it again and again... } } } // stuff for MultiTouchController and PinchWidget public static void setPinchWidget(Bitmap bitmap) { mPinchWidget = new PinchWidget(bitmap); mPinchWidget.init(mContext.getResources()); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mWidth = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); mHeight = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(mWidth, mHeight); } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); if (mPinchWidget != null) { mPinchWidget.draw(canvas); } } public PinchWidget getDraggableObjectAtPoint(PointInfo pt) { float x = pt.getX(), y = pt.getY(); if (mPinchWidget != null) { if (mPinchWidget.containsPoint(x, y)) { return mPinchWidget; } } return null; } public void getPositionAndScale(PinchWidget pinchWidget, PositionAndScale objPosAndScaleOut) { objPosAndScaleOut.set(pinchWidget.getCenterX(), pinchWidget.getCenterY(), (mUIMode & UI_MODE_ANISOTROPIC_SCALE) == 0, (pinchWidget.getScaleFactor() + pinchWidget.getScaleFactor()) / 2, (mUIMode & UI_MODE_ANISOTROPIC_SCALE) != 0, pinchWidget.getScaleFactor(), pinchWidget.getScaleFactor(), (mUIMode & UI_MODE_ROTATE) != 0, pinchWidget.getAngle()); } public boolean setPositionAndScale(PinchWidget pinchWidget, PositionAndScale newImgPosAndScale, PointInfo touchPoint) { boolean ok = pinchWidget.setPos(newImgPosAndScale, mUIMode, UI_MODE_ANISOTROPIC_SCALE, touchPoint.isMultiTouch()); if (ok) { invalidate(); } return ok; } public void selectObject(PinchWidget pinchWidget, PointInfo touchPoint) { if (touchPoint.isDown()) { mPinchWidget = pinchWidget; } invalidate(); } public CommandManager getCommandManager() { return commandManager; } public void setCommandManager(CommandManager commandManager) { this.commandManager = commandManager; } }
5,858
0.741891
0.737453
219
25.753426
27.089458
121
false
false
0
0
0
0
0
0
2.187215
false
false
15
28be41e0c9ab31358de90299c9362db50848d01b
5,566,277,616,268
fac5d6126ab147e3197448d283f9a675733f3c34
/src/main/java/dji/internal/diagnostics/handler/FlightControllerDiagnosticsHandler$$Lambda$101.java
b6ff3825e84b0c8782222a11b9987dadc5b1b30d
[]
no_license
KnzHz/fpv_live
https://github.com/KnzHz/fpv_live
412e1dc8ab511b1a5889c8714352e3a373cdae2f
7902f1a4834d581ee6afd0d17d87dc90424d3097
refs/heads/master
2022-12-18T18:15:39.101000
2020-09-24T19:42:03
2020-09-24T19:42:03
294,176,898
0
0
null
true
2020-09-09T17:03:58
2020-09-09T17:03:57
2020-07-13T03:26:16
2020-04-29T00:01:57
65,458
0
0
0
null
false
false
package dji.internal.diagnostics.handler; import dji.internal.diagnostics.DJIDiagnosticsImpl; import dji.utils.function.Consumer; import dji.utils.function.Consumer$$CC; import java.util.Set; final /* synthetic */ class FlightControllerDiagnosticsHandler$$Lambda$101 implements Consumer { private final Set arg$1; private FlightControllerDiagnosticsHandler$$Lambda$101(Set set) { this.arg$1 = set; } static Consumer get$Lambda(Set set) { return new FlightControllerDiagnosticsHandler$$Lambda$101(set); } public void accept(Object obj) { this.arg$1.add((DJIDiagnosticsImpl) obj); } public Consumer andThen(Consumer consumer) { return Consumer$$CC.andThen(this, consumer); } }
UTF-8
Java
749
java
FlightControllerDiagnosticsHandler$$Lambda$101.java
Java
[]
null
[]
package dji.internal.diagnostics.handler; import dji.internal.diagnostics.DJIDiagnosticsImpl; import dji.utils.function.Consumer; import dji.utils.function.Consumer$$CC; import java.util.Set; final /* synthetic */ class FlightControllerDiagnosticsHandler$$Lambda$101 implements Consumer { private final Set arg$1; private FlightControllerDiagnosticsHandler$$Lambda$101(Set set) { this.arg$1 = set; } static Consumer get$Lambda(Set set) { return new FlightControllerDiagnosticsHandler$$Lambda$101(set); } public void accept(Object obj) { this.arg$1.add((DJIDiagnosticsImpl) obj); } public Consumer andThen(Consumer consumer) { return Consumer$$CC.andThen(this, consumer); } }
749
0.720961
0.70494
26
27.807692
26.514175
96
false
false
0
0
0
0
0
0
0.423077
false
false
15
806fd39b55fb2c75034a64c0f37f3fe4c59c25f8
8,469,675,541,522
0551a40441b093bc4d61baecae9ab678fc790828
/gulimall-order/src/main/java/com/james/gulimall/order/service/OrderOperateHistoryService.java
c54ac6e8014f246465a35f3877754fa4b023281e
[]
no_license
Jamesjayedm/gulimall
https://github.com/Jamesjayedm/gulimall
e6496d1510b8c75468cd081c350e919eda68e725
4b8817775b5af6932ff155ac07445dbc1c7c87f4
refs/heads/main
2023-07-02T05:59:18.322000
2021-07-22T12:16:09
2021-07-22T12:16:09
323,590,406
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.james.gulimall.order.service; import com.baomidou.mybatisplus.extension.service.IService; import com.james.common.utils.PageUtils; import com.james.gulimall.order.entity.OrderOperateHistoryEntity; import java.util.Map; /** * 订单操作历史记录 * * @author pyj * @email 631967081@gmail.com * @date 2020-12-28 18:20:44 */ public interface OrderOperateHistoryService extends IService<OrderOperateHistoryEntity> { PageUtils queryPage(Map<String, Object> params); }
UTF-8
Java
494
java
OrderOperateHistoryService.java
Java
[ { "context": "port java.util.Map;\n\n/**\n * 订单操作历史记录\n *\n * @author pyj\n * @email 631967081@gmail.com\n * @date 2020-12-28", "end": 267, "score": 0.9996211528778076, "start": 264, "tag": "USERNAME", "value": "pyj" }, { "context": "Map;\n\n/**\n * 订单操作历史记录\n *\n * @author pyj\n * @...
null
[]
package com.james.gulimall.order.service; import com.baomidou.mybatisplus.extension.service.IService; import com.james.common.utils.PageUtils; import com.james.gulimall.order.entity.OrderOperateHistoryEntity; import java.util.Map; /** * 订单操作历史记录 * * @author pyj * @email <EMAIL> * @date 2020-12-28 18:20:44 */ public interface OrderOperateHistoryService extends IService<OrderOperateHistoryEntity> { PageUtils queryPage(Map<String, Object> params); }
482
0.780335
0.732218
19
24.105263
26.135063
89
false
false
0
0
0
0
0
0
0.368421
false
false
15
a207c2b93875d40faa247466052788c1f582af32
28,235,115,045,064
46c8f77816e1212d3e21fb5dce9be122ac48bee8
/app/src/main/java/dev/atharvakulkarni/messenger/view/ui/chat_person.java
256f2e38029a3f039bb8de0fca1cd2171a7377b3
[]
no_license
rahul4452/Messenger-Android
https://github.com/rahul4452/Messenger-Android
2f758cd047c465a2ed329db0f252591fdb41f708
bd146f30324fbd1babc401c2f2e814a03aa02d02
refs/heads/master
2023-06-05T00:09:03.749000
2021-06-24T18:39:08
2021-06-24T18:39:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dev.atharvakulkarni.messenger.view.ui; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreSettings; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import dev.atharvakulkarni.messenger.view.adapter.ChatPersonAdapter; import dev.atharvakulkarni.messenger.service.model.ChatWithModel; import dev.atharvakulkarni.messenger.service.model.MessagesModel; import dev.atharvakulkarni.messenger.R; import dev.atharvakulkarni.messenger.service.model.UserModel; public class chat_person extends AppCompatActivity { EditText message_edittext; FrameLayout send; String message, chatwith_username; TextView chat_with, on_off_status; FirebaseFirestore db; private String saveCurrentTime, saveCurrentDate; private ChatPersonAdapter chatPersonAdapter; private RecyclerView userMessagesList; private LinearLayoutManager linearLayoutManager; private final List<MessagesModel> messagesList = new ArrayList<>(); private FirebaseAuth mAuth; // String messageSenderId; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chat_person); message_edittext = findViewById(R.id.editText_message); chat_with = findViewById(R.id.chat_with); send = findViewById(R.id.send); on_off_status = findViewById(R.id.on_off_status); Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show(); mAuth = FirebaseAuth.getInstance(); // Access a Cloud Firestore instance from your Activity db = FirebaseFirestore.getInstance(); IntializeControllers(); // messageSenderId = mAuth.getCurrentUser().getUid(); chatwith_username = getIntent().getExtras().getString("username"); /* int x = ChatWithGetData.user(username); if(x == 1) { chat_with.setText(ChatWithModel.getName()); }*/ FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder() .setPersistenceEnabled(true) .build(); db.setFirestoreSettings(settings); chatPersonAdapter.notifyDataSetChanged(); x(); // Toast.makeText(this,UserModel.getUsername()+" "+ chadwick_username, Toast.LENGTH_SHORT).show(); //ChatWithModel.setUsername(username); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SendMessage(); } }); DisplayLastSeen(); } void x() { DocumentReference docRef = db.collection("users").document(chatwith_username); docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { String name = document.getString("name"); String last_seen = document.getString("last_seen"); String on_off_stat = document.getString("on_off_status"); String photo = document.getString("photo"); String status = document.getString("status"); ChatWithModel.setLast_seen(last_seen); ChatWithModel.setOn_off_status(on_off_stat); ChatWithModel.setStatus(status); ChatWithModel.setName(name); ChatWithModel.setPhoto(photo); ChatWithModel.setUsername(chatwith_username); // Toast.makeText(context, ChatWithModel.getUsername(), Toast.LENGTH_SHORT).show(); chat_with.setText(name); on_off_status.setText(on_off_stat); Log.d("TAG", "DocumentSnapshot data1111: " + document.getData()); } else { Log.d("TAG", "No such document"); } } else { Log.d("TAG", "get failed with ", task.getException()); } } }); db.collection("Atharva2204").document("person").collection(chatwith_username) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { // Log.d(TAG, document.getId() + " => " + document.getData()); MessagesModel messages = document.toObject(MessagesModel.class); messagesList.add(messages); chatPersonAdapter.notifyDataSetChanged(); userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount()); } } else { Log.d("TAG", "Error getting documents: ", task.getException()); } } }); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { /*MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.chat_person_more, menu);*/ getMenuInflater().inflate(R.menu.chat_person_more, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.view_contact: Toast.makeText(this, "Item 1 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.search: Toast.makeText(this, "Item 2 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.more: Toast.makeText(this, "Item 3 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.report: Toast.makeText(this, "Sub Item 1 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.block: Toast.makeText(this, "Sub Item 2 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.clear_chat: Toast.makeText(this, "Sub Item 2 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.add_shortcut: Toast.makeText(this, "Sub Item 2 selected", Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } private void IntializeControllers() { chatPersonAdapter = new ChatPersonAdapter(messagesList,chat_person.this); userMessagesList = (RecyclerView) findViewById(R.id.private_messages_list_of_users); linearLayoutManager = new LinearLayoutManager(this); // linearLayoutManager.setReverseLayout(true); // linearLayoutManager.setStackFromEnd(true); userMessagesList.setLayoutManager(linearLayoutManager); userMessagesList.setAdapter(chatPersonAdapter); Calendar calendar = Calendar.getInstance(); SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy"); saveCurrentDate = currentDate.format(calendar.getTime()); SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm a"); saveCurrentTime = currentTime.format(calendar.getTime()); } private void DisplayLastSeen() { } private void SendMessage() { message = message_edittext.getText().toString(); // message_textview.setText(message); if (TextUtils.isEmpty(message)) { Toast.makeText(this, "first write your message...", Toast.LENGTH_SHORT).show(); } else { // Create a new user with a first and last name Map<String, Object> msg = new HashMap<>(); msg.put("from", UserModel.getUsername()); msg.put("time", saveCurrentTime); msg.put("date", saveCurrentDate); msg.put("text", message); // Add a new document with a generated ID db.collection("Atharva2204").document("person").collection(chatwith_username).document(String.valueOf(System.currentTimeMillis())).set(msg).addOnSuccessListener(new OnSuccessListener<Void>() { private static final String TAG = "a"; @Override public void onSuccess(Void aVoid) { //Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); Toast.makeText(chat_person.this, "success", Toast.LENGTH_SHORT).show(); message_edittext.setText(""); chatPersonAdapter.notifyDataSetChanged(); x(); //onStart(); } }) .addOnFailureListener(new OnFailureListener() { private static final String TAG = "b"; @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } }); Map<String, Object> msg1 = new HashMap<>(); msg1.put("from", UserModel.getUsername()); msg1.put("time", saveCurrentTime); msg1.put("date", saveCurrentDate); msg1.put("text", message); // Add a new document with a generated ID db.collection(chatwith_username).document("person").collection(UserModel.getUsername()).document(String.valueOf(System.currentTimeMillis())).set(msg1).addOnSuccessListener(new OnSuccessListener<Void>() { private static final String TAG = "a"; @Override public void onSuccess(Void aVoid) { //Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); Toast.makeText(chat_person.this, "success", Toast.LENGTH_SHORT).show(); message_edittext.setText(""); chatPersonAdapter.notifyDataSetChanged(); //onStart(); } }) .addOnFailureListener(new OnFailureListener() { private static final String TAG = "b"; @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } }); Map<String, Object> msg2 = new HashMap<>(); msg2.put("name",ChatWithModel.getName()); msg2.put("photo",ChatWithModel.getPhoto()); msg2.put("last_message", message); msg2.put("last_time", saveCurrentTime); // Add a new document with a generated ID db.collection(UserModel.getUsername()).document("chatlist").collection("chatlist").document(chatwith_username).set(msg2).addOnSuccessListener(new OnSuccessListener<Void>() { private static final String TAG = "a"; @Override public void onSuccess(Void aVoid) { //Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); // Toast.makeText(chat_person.this, "success", Toast.LENGTH_SHORT).show(); // message_edittext.setText(""); // chatPersonAdapter.notifyDataSetChanged(); // onStart(); } }) .addOnFailureListener(new OnFailureListener() { private static final String TAG = "b"; @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } }); } } @Override protected void onStart() { super.onStart(); /* DocumentReference docRef = db.collection(messageSenderId).document("person").collection("Adwait"); docRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { private static final String TAG = "s"; @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { // message_textview.setText(); Messages1 messages = document.toObject(Messages1.class); messagesList.add(messages); messageAdapter.notifyDataSetChanged(); userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount()); Log.d(TAG, "DocumentSnapshot data: " + document.getData()); } else { Log.d(TAG, "No such document"); } } else { Log.d(TAG, "get failed with ", task.getException()); } } });*/ } }
UTF-8
Java
15,849
java
chat_person.java
Java
[ { "context": " ChatWithModel.setUsername(chatwith_username);\n\n // Toast.makeText(cont", "end": 5044, "score": 0.9938907623291016, "start": 5027, "tag": "USERNAME", "value": "chatwith_username" }, { "context": "t with a generated ID\n ...
null
[]
package dev.atharvakulkarni.messenger.view.ui; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreSettings; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import dev.atharvakulkarni.messenger.view.adapter.ChatPersonAdapter; import dev.atharvakulkarni.messenger.service.model.ChatWithModel; import dev.atharvakulkarni.messenger.service.model.MessagesModel; import dev.atharvakulkarni.messenger.R; import dev.atharvakulkarni.messenger.service.model.UserModel; public class chat_person extends AppCompatActivity { EditText message_edittext; FrameLayout send; String message, chatwith_username; TextView chat_with, on_off_status; FirebaseFirestore db; private String saveCurrentTime, saveCurrentDate; private ChatPersonAdapter chatPersonAdapter; private RecyclerView userMessagesList; private LinearLayoutManager linearLayoutManager; private final List<MessagesModel> messagesList = new ArrayList<>(); private FirebaseAuth mAuth; // String messageSenderId; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chat_person); message_edittext = findViewById(R.id.editText_message); chat_with = findViewById(R.id.chat_with); send = findViewById(R.id.send); on_off_status = findViewById(R.id.on_off_status); Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show(); mAuth = FirebaseAuth.getInstance(); // Access a Cloud Firestore instance from your Activity db = FirebaseFirestore.getInstance(); IntializeControllers(); // messageSenderId = mAuth.getCurrentUser().getUid(); chatwith_username = getIntent().getExtras().getString("username"); /* int x = ChatWithGetData.user(username); if(x == 1) { chat_with.setText(ChatWithModel.getName()); }*/ FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder() .setPersistenceEnabled(true) .build(); db.setFirestoreSettings(settings); chatPersonAdapter.notifyDataSetChanged(); x(); // Toast.makeText(this,UserModel.getUsername()+" "+ chadwick_username, Toast.LENGTH_SHORT).show(); //ChatWithModel.setUsername(username); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SendMessage(); } }); DisplayLastSeen(); } void x() { DocumentReference docRef = db.collection("users").document(chatwith_username); docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { String name = document.getString("name"); String last_seen = document.getString("last_seen"); String on_off_stat = document.getString("on_off_status"); String photo = document.getString("photo"); String status = document.getString("status"); ChatWithModel.setLast_seen(last_seen); ChatWithModel.setOn_off_status(on_off_stat); ChatWithModel.setStatus(status); ChatWithModel.setName(name); ChatWithModel.setPhoto(photo); ChatWithModel.setUsername(chatwith_username); // Toast.makeText(context, ChatWithModel.getUsername(), Toast.LENGTH_SHORT).show(); chat_with.setText(name); on_off_status.setText(on_off_stat); Log.d("TAG", "DocumentSnapshot data1111: " + document.getData()); } else { Log.d("TAG", "No such document"); } } else { Log.d("TAG", "get failed with ", task.getException()); } } }); db.collection("Atharva2204").document("person").collection(chatwith_username) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { // Log.d(TAG, document.getId() + " => " + document.getData()); MessagesModel messages = document.toObject(MessagesModel.class); messagesList.add(messages); chatPersonAdapter.notifyDataSetChanged(); userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount()); } } else { Log.d("TAG", "Error getting documents: ", task.getException()); } } }); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { /*MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.chat_person_more, menu);*/ getMenuInflater().inflate(R.menu.chat_person_more, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.view_contact: Toast.makeText(this, "Item 1 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.search: Toast.makeText(this, "Item 2 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.more: Toast.makeText(this, "Item 3 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.report: Toast.makeText(this, "Sub Item 1 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.block: Toast.makeText(this, "Sub Item 2 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.clear_chat: Toast.makeText(this, "Sub Item 2 selected", Toast.LENGTH_SHORT).show(); return true; case R.id.add_shortcut: Toast.makeText(this, "Sub Item 2 selected", Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } private void IntializeControllers() { chatPersonAdapter = new ChatPersonAdapter(messagesList,chat_person.this); userMessagesList = (RecyclerView) findViewById(R.id.private_messages_list_of_users); linearLayoutManager = new LinearLayoutManager(this); // linearLayoutManager.setReverseLayout(true); // linearLayoutManager.setStackFromEnd(true); userMessagesList.setLayoutManager(linearLayoutManager); userMessagesList.setAdapter(chatPersonAdapter); Calendar calendar = Calendar.getInstance(); SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy"); saveCurrentDate = currentDate.format(calendar.getTime()); SimpleDateFormat currentTime = new SimpleDateFormat("hh:mm a"); saveCurrentTime = currentTime.format(calendar.getTime()); } private void DisplayLastSeen() { } private void SendMessage() { message = message_edittext.getText().toString(); // message_textview.setText(message); if (TextUtils.isEmpty(message)) { Toast.makeText(this, "first write your message...", Toast.LENGTH_SHORT).show(); } else { // Create a new user with a first and last name Map<String, Object> msg = new HashMap<>(); msg.put("from", UserModel.getUsername()); msg.put("time", saveCurrentTime); msg.put("date", saveCurrentDate); msg.put("text", message); // Add a new document with a generated ID db.collection("Atharva2204").document("person").collection(chatwith_username).document(String.valueOf(System.currentTimeMillis())).set(msg).addOnSuccessListener(new OnSuccessListener<Void>() { private static final String TAG = "a"; @Override public void onSuccess(Void aVoid) { //Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); Toast.makeText(chat_person.this, "success", Toast.LENGTH_SHORT).show(); message_edittext.setText(""); chatPersonAdapter.notifyDataSetChanged(); x(); //onStart(); } }) .addOnFailureListener(new OnFailureListener() { private static final String TAG = "b"; @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } }); Map<String, Object> msg1 = new HashMap<>(); msg1.put("from", UserModel.getUsername()); msg1.put("time", saveCurrentTime); msg1.put("date", saveCurrentDate); msg1.put("text", message); // Add a new document with a generated ID db.collection(chatwith_username).document("person").collection(UserModel.getUsername()).document(String.valueOf(System.currentTimeMillis())).set(msg1).addOnSuccessListener(new OnSuccessListener<Void>() { private static final String TAG = "a"; @Override public void onSuccess(Void aVoid) { //Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); Toast.makeText(chat_person.this, "success", Toast.LENGTH_SHORT).show(); message_edittext.setText(""); chatPersonAdapter.notifyDataSetChanged(); //onStart(); } }) .addOnFailureListener(new OnFailureListener() { private static final String TAG = "b"; @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } }); Map<String, Object> msg2 = new HashMap<>(); msg2.put("name",ChatWithModel.getName()); msg2.put("photo",ChatWithModel.getPhoto()); msg2.put("last_message", message); msg2.put("last_time", saveCurrentTime); // Add a new document with a generated ID db.collection(UserModel.getUsername()).document("chatlist").collection("chatlist").document(chatwith_username).set(msg2).addOnSuccessListener(new OnSuccessListener<Void>() { private static final String TAG = "a"; @Override public void onSuccess(Void aVoid) { //Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); // Toast.makeText(chat_person.this, "success", Toast.LENGTH_SHORT).show(); // message_edittext.setText(""); // chatPersonAdapter.notifyDataSetChanged(); // onStart(); } }) .addOnFailureListener(new OnFailureListener() { private static final String TAG = "b"; @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } }); } } @Override protected void onStart() { super.onStart(); /* DocumentReference docRef = db.collection(messageSenderId).document("person").collection("Adwait"); docRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { private static final String TAG = "s"; @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { // message_textview.setText(); Messages1 messages = document.toObject(Messages1.class); messagesList.add(messages); messageAdapter.notifyDataSetChanged(); userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount()); Log.d(TAG, "DocumentSnapshot data: " + document.getData()); } else { Log.d(TAG, "No such document"); } } else { Log.d(TAG, "get failed with ", task.getException()); } } });*/ } }
15,849
0.553978
0.551833
426
36.206573
30.99045
213
false
false
0
0
0
0
0
0
0.624413
false
false
15
f2d674bd510032b2c0d69daeb335e05d162e66fc
14,585,708,938,957
174dc5d55498510994b3b9fb07704386f0d8c417
/src/main/java/com/midea/emall/service/impl/CategoryServiceImpl.java
bbb2f1798ba248e345fc23cb7982da2c0fa4b393
[]
no_license
JoeyEarlyToBed/springboot-project
https://github.com/JoeyEarlyToBed/springboot-project
50a6f82ef9ae88862068f6f9abca122860fde97f
a1199f0bd6ddf8c0d8637f9afb9ed5f85402fb4f
refs/heads/master
2023-07-16T19:09:11.201000
2021-08-06T12:42:15
2021-08-06T12:42:15
393,370,240
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.midea.emall.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.midea.emall.exception.MideaMallException; import com.midea.emall.exception.MideaMallExceptionEnum; import com.midea.emall.model.dao.CategoryMapper; import com.midea.emall.model.pojo.Category; import com.midea.emall.model.request.AddCategoryReq; import com.midea.emall.model.vo.CategoryVO; import com.midea.emall.service.CategoryService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.RequestParam; import java.util.ArrayList; import java.util.List; @Service public class CategoryServiceImpl implements CategoryService { @Autowired CategoryMapper categoryMapper; @Override public void add(AddCategoryReq addCategoryReq) { Category category = new Category(); BeanUtils.copyProperties(addCategoryReq, category); Category categoryOld = categoryMapper.selectByName(addCategoryReq.getName()); if (categoryOld != null) { throw new MideaMallException(MideaMallExceptionEnum.NAME_EXIT); } int count = categoryMapper.insertSelective(category); if (count == 0) { throw new MideaMallException(MideaMallExceptionEnum.CREATE_FAILED); } } @Override public void update(Category updateCategory) { //如果更新的目录不为空 if (updateCategory.getName() != null) { Category oldCategory = categoryMapper.selectByName(updateCategory.getName()); //如果该目录存在,并且,id值不相同 if (oldCategory != null && !oldCategory.getId().equals(updateCategory.getId())) { throw new MideaMallException(MideaMallExceptionEnum.NAME_EXIT); } } int count = categoryMapper.updateByPrimaryKeySelective(updateCategory); if (count == 0) { throw new MideaMallException(MideaMallExceptionEnum.UPDATE_FAIL); } } @Override public void delete(Integer id) { Category oldCategory = categoryMapper.selectByPrimaryKey(id); if (oldCategory == null) { throw new MideaMallException(MideaMallExceptionEnum.DELETE_FAILED); } int count = categoryMapper.deleteByPrimaryKey(id); if (count == 0) { throw new MideaMallException(MideaMallExceptionEnum.DELETE_FAILED); } } @Override public PageInfo listForAdmin(@RequestParam Integer pageNum, @RequestParam Integer pageSize) { PageHelper.startPage(pageNum, pageSize, "type,order_num"); List<Category> categoryList = categoryMapper.selectList(); PageInfo pageInfo = new PageInfo<>(categoryList); return pageInfo; } @Override @Cacheable(value = "listCategoryForCustomer") public List<CategoryVO> listCategoryForCustomer() { List<CategoryVO> categoryVOList = new ArrayList<>(); recursivelyFindCategories(categoryVOList, 0); return categoryVOList; } @Override public List<CategoryVO> listCategoryForCustomer(Integer categoryId) { List<CategoryVO> categoryVOList = new ArrayList<>(); recursivelyFindCategories(categoryVOList, categoryId); return categoryVOList; } private void recursivelyFindCategories(List<CategoryVO> categoryVOList, Integer parentId) { //递归获取所有子类别,并组合成一个“目录树” List<Category> categoryList = categoryMapper.selectCategoriesByParentId(parentId); if (!CollectionUtils.isEmpty(categoryList)) { for (Category category : categoryList) { CategoryVO categoryVO = new CategoryVO(); BeanUtils.copyProperties(category, categoryVO); categoryVOList.add(categoryVO); recursivelyFindCategories(categoryVO.getChildCategory(), categoryVO.getId()); } } } }
UTF-8
Java
4,187
java
CategoryServiceImpl.java
Java
[]
null
[]
package com.midea.emall.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.midea.emall.exception.MideaMallException; import com.midea.emall.exception.MideaMallExceptionEnum; import com.midea.emall.model.dao.CategoryMapper; import com.midea.emall.model.pojo.Category; import com.midea.emall.model.request.AddCategoryReq; import com.midea.emall.model.vo.CategoryVO; import com.midea.emall.service.CategoryService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.RequestParam; import java.util.ArrayList; import java.util.List; @Service public class CategoryServiceImpl implements CategoryService { @Autowired CategoryMapper categoryMapper; @Override public void add(AddCategoryReq addCategoryReq) { Category category = new Category(); BeanUtils.copyProperties(addCategoryReq, category); Category categoryOld = categoryMapper.selectByName(addCategoryReq.getName()); if (categoryOld != null) { throw new MideaMallException(MideaMallExceptionEnum.NAME_EXIT); } int count = categoryMapper.insertSelective(category); if (count == 0) { throw new MideaMallException(MideaMallExceptionEnum.CREATE_FAILED); } } @Override public void update(Category updateCategory) { //如果更新的目录不为空 if (updateCategory.getName() != null) { Category oldCategory = categoryMapper.selectByName(updateCategory.getName()); //如果该目录存在,并且,id值不相同 if (oldCategory != null && !oldCategory.getId().equals(updateCategory.getId())) { throw new MideaMallException(MideaMallExceptionEnum.NAME_EXIT); } } int count = categoryMapper.updateByPrimaryKeySelective(updateCategory); if (count == 0) { throw new MideaMallException(MideaMallExceptionEnum.UPDATE_FAIL); } } @Override public void delete(Integer id) { Category oldCategory = categoryMapper.selectByPrimaryKey(id); if (oldCategory == null) { throw new MideaMallException(MideaMallExceptionEnum.DELETE_FAILED); } int count = categoryMapper.deleteByPrimaryKey(id); if (count == 0) { throw new MideaMallException(MideaMallExceptionEnum.DELETE_FAILED); } } @Override public PageInfo listForAdmin(@RequestParam Integer pageNum, @RequestParam Integer pageSize) { PageHelper.startPage(pageNum, pageSize, "type,order_num"); List<Category> categoryList = categoryMapper.selectList(); PageInfo pageInfo = new PageInfo<>(categoryList); return pageInfo; } @Override @Cacheable(value = "listCategoryForCustomer") public List<CategoryVO> listCategoryForCustomer() { List<CategoryVO> categoryVOList = new ArrayList<>(); recursivelyFindCategories(categoryVOList, 0); return categoryVOList; } @Override public List<CategoryVO> listCategoryForCustomer(Integer categoryId) { List<CategoryVO> categoryVOList = new ArrayList<>(); recursivelyFindCategories(categoryVOList, categoryId); return categoryVOList; } private void recursivelyFindCategories(List<CategoryVO> categoryVOList, Integer parentId) { //递归获取所有子类别,并组合成一个“目录树” List<Category> categoryList = categoryMapper.selectCategoriesByParentId(parentId); if (!CollectionUtils.isEmpty(categoryList)) { for (Category category : categoryList) { CategoryVO categoryVO = new CategoryVO(); BeanUtils.copyProperties(category, categoryVO); categoryVOList.add(categoryVO); recursivelyFindCategories(categoryVO.getChildCategory(), categoryVO.getId()); } } } }
4,187
0.700122
0.699145
112
35.5625
28.740458
97
false
false
0
0
0
0
0
0
0.517857
false
false
15
77195e6874cffd6b8e7748d7f67e420744eac78a
292,057,845,799
ba5da2e304d6eaefd5a9ab474d47768bb6ab0810
/admin/business/src/main/java/com/badminton/court/service/impl/CourtResourceServiceImpl.java
cc4f752cda3c6e48229a120b660423ad3fe28aba
[]
no_license
Luoqinbin/manager
https://github.com/Luoqinbin/manager
81580befc0cc19ec5d958c337ae1ae9c7a2eb9e0
a6ceaa590aa0a7b59f1f5cb46dc1a80298edc80b
refs/heads/master
2021-01-22T22:34:58.093000
2017-05-04T05:46:44
2017-05-04T05:46:44
85,555,363
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.badminton.court.service.impl; import com.badminton.court.service.CourtResourceService; import org.springframework.stereotype.Service; /** * Created by Luoqb on 2017/3/15. */ @Service("courtResourceService") public class CourtResourceServiceImpl implements CourtResourceService { }
UTF-8
Java
297
java
CourtResourceServiceImpl.java
Java
[ { "context": "ngframework.stereotype.Service;\n\n/**\n * Created by Luoqb on 2017/3/15.\n */\n@Service(\"courtResourceService\"", "end": 171, "score": 0.9996010661125183, "start": 166, "tag": "USERNAME", "value": "Luoqb" } ]
null
[]
package com.badminton.court.service.impl; import com.badminton.court.service.CourtResourceService; import org.springframework.stereotype.Service; /** * Created by Luoqb on 2017/3/15. */ @Service("courtResourceService") public class CourtResourceServiceImpl implements CourtResourceService { }
297
0.811448
0.787879
11
26
24.624453
71
false
false
0
0
0
0
0
0
0.272727
false
false
15
f4f61509f4504c1f890ebf9dc714acfc991b8d6b
2,001,454,762,986
874d46af3abe75fab154cc804153a20ba135d02c
/xyhmo-service/src/main/java/com/xyhmo/service/impl/UserInfoServiceImpl.java
b51f8469b68672c801365b034881dfc57f31f915
[]
no_license
2549566/xyhmo
https://github.com/2549566/xyhmo
39f9d237b628991f2348ef097745764d03a4eaf2
90dc5f3681741860e8f0f4734f3ed31eff83462f
refs/heads/master
2021-06-21T23:18:10.578000
2019-04-09T15:39:20
2019-04-09T15:39:20
156,717,880
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xyhmo.service.impl; import com.xyhmo.commom.enums.ParamEnum; import com.xyhmo.commom.service.Contants; import com.xyhmo.commom.service.RedisService; import com.xyhmo.commom.utils.ParamCheckUtil; import com.xyhmo.commom.utils.UniqueUtil; import com.xyhmo.dao.UserInfoDao; import com.xyhmo.domain.UserAuthInfo; import com.xyhmo.domain.UserInfo; import com.xyhmo.service.TokenService; import com.xyhmo.service.UserAuthInfoService; import com.xyhmo.service.UserInfoService; import com.xyhmo.vo.UserVo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.ArrayList; import java.util.List; @Service public class UserInfoServiceImpl implements UserInfoService{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private UserInfoDao userInfoDao; @Autowired private UserAuthInfoService userAuthInfoService; @Autowired private TokenService tokenService; @Autowired private RedisService redisService; @Override public Long save(String mobile) { logger.info("UserInfoServiceImpl save:mobile="+mobile); ParamCheckUtil.checkMobileNumber(mobile); UserInfo userInfo = new UserInfo(); userInfo.setMobileNumber(mobile); userInfo.setPin(UniqueUtil.genPin(mobile)); userInfo.setStatus(ParamEnum.PARAM_DATA_USED.getCode()); return userInfoDao.insert(userInfo); } @Override public UserInfo autuwaredUserInfo(String mobile) { return null; } @Override public UserInfo getUserInfoByMobile(String mobile) { return userInfoDao.selectUserInfoByMobile(mobile); } @Override public void EditUserInfo(UserVo vo) { if(vo==null || StringUtils.isEmpty(vo.getPin())){ return ; } UserInfo userInfo = userInfoDao.selectUserInfoByPin(vo.getPin()); if(userInfo==null){ return ; } userInfo.setUserType(vo.getUserType()); userInfoDao.updateUserInfo(userInfo); } @Override public UserVo autowaredToVo(UserInfo userInfo, UserAuthInfo userAuthInfo) { if(userInfo==null){ return null; } UserVo vo = new UserVo(); vo.setId(userInfo.getId()); vo.setPin(userInfo.getPin()); vo.setToken(userInfo.getToken()); vo.setMobileNumber(userInfo.getMobileNumber()); vo.setUserName(userInfo.getUserName()); vo.setUserType(userInfo.getUserType()); vo.setPassword(userInfo.getPassword()); vo.setBindVender(userInfo.getBindVender()); vo.setBindVenderProxy(userInfo.getBindVenderProxy()); vo.setIsAuth(userInfo.getIsAuth()); vo.setImageHearder(userInfo.getImageHearder()); vo.setCreated(userInfo.getCreated()); vo.setModified(userInfo.getModified()); vo.setScore(userInfo.getScore()); vo.setIsAcceptOrder(userInfo.getIsAcceptOrder()); if(null==userAuthInfo){ return vo; } vo.setRealName(userAuthInfo.getRealName()); vo.setImageCardFace(userAuthInfo.getImageCardFace()); vo.setImageCardBack(userAuthInfo.getImageCardBack()); vo.setImageCompanyQualiy(userAuthInfo.getImageCompanyQualiy()); vo.setCompanyName(userAuthInfo.getCompanyName()); vo.setAuthCreated(userAuthInfo.getCreated()); vo.setAuthModified(userAuthInfo.getModified()); return vo; } @Override public UserInfo getUserInfoByPin(String pin) { return userInfoDao.selectUserInfoByPin(pin); } @Override public UserVo getUserVoByToken(String token) { UserVo vo = tokenService.checkTokenExist(token); UserInfo userInfo = getUserInfoByPin(vo.getPin()); UserAuthInfo userAuthInfo = userAuthInfoService.getUserAuthInfoByPin(vo.getPin()); UserVo userVo = autowaredToVo(userInfo,userAuthInfo); redisService.set(Contants.REDIS_TOKEKN_BEFORE+token,userVo,Contants.TOKEN_OVER_TIME); return userVo; } @Override public List<UserInfo> getUserInfoByProxyPin(String pin) { return userInfoDao.selectUserInfoByProxyPin(pin); } @Override public List<UserVo> autowaredToVoList(List<UserInfo> userInfoList, List<UserAuthInfo> userAuthInfoList) { List<UserVo> userVoList = new ArrayList<>(); if(CollectionUtils.isEmpty(userInfoList)){ logger.error("UserInfoServiceImpl autowaredToVoList:userInfoList is empty"); return userVoList; } for(UserInfo userInfo:userInfoList){ if(StringUtils.isEmpty(userInfo.getPin())){ continue; } UserVo vo = new UserVo(); vo.setId(userInfo.getId()); vo.setPin(userInfo.getPin()); vo.setToken(userInfo.getToken()); vo.setMobileNumber(userInfo.getMobileNumber()); vo.setUserName(userInfo.getUserName()); vo.setUserType(userInfo.getUserType()); vo.setPassword(userInfo.getPassword()); vo.setBindVender(userInfo.getBindVender()); vo.setBindVenderProxy(userInfo.getBindVenderProxy()); vo.setIsAuth(userInfo.getIsAuth()); vo.setImageHearder(userInfo.getImageHearder()); vo.setCreated(userInfo.getCreated()); vo.setModified(userInfo.getModified()); vo.setScore(userInfo.getScore()); vo.setIsAcceptOrder(userInfo.getIsAcceptOrder()); for(UserAuthInfo userAuthInfo:userAuthInfoList){ if(userInfo.getPin().equals(userAuthInfo.getPin())){ vo.setRealName(userAuthInfo.getRealName()); vo.setImageCardFace(userAuthInfo.getImageCardFace()); vo.setImageCardBack(userAuthInfo.getImageCardBack()); vo.setImageCompanyQualiy(userAuthInfo.getImageCompanyQualiy()); vo.setCompanyName(userAuthInfo.getCompanyName()); vo.setAuthCreated(userAuthInfo.getCreated()); vo.setAuthModified(userAuthInfo.getModified()); break; } } userVoList.add(vo); } return userVoList; } @Override public List<UserInfo> getProxyListByVenderPin(String pin) { if(StringUtils.isEmpty(pin)){ logger.error("pin is empty"); return new ArrayList<>(); } return userInfoDao.selectProxyListByVenderPin(pin); } }
UTF-8
Java
6,744
java
UserInfoServiceImpl.java
Java
[ { "context": "e(userInfo.getUserType());\n vo.setPassword(userInfo.getPassword());\n vo.setBindVender(userInfo.getBindVend", "end": 2739, "score": 0.963339626789093, "start": 2719, "tag": "PASSWORD", "value": "userInfo.getPassword" }, { "context": "erInfo.getUserType())...
null
[]
package com.xyhmo.service.impl; import com.xyhmo.commom.enums.ParamEnum; import com.xyhmo.commom.service.Contants; import com.xyhmo.commom.service.RedisService; import com.xyhmo.commom.utils.ParamCheckUtil; import com.xyhmo.commom.utils.UniqueUtil; import com.xyhmo.dao.UserInfoDao; import com.xyhmo.domain.UserAuthInfo; import com.xyhmo.domain.UserInfo; import com.xyhmo.service.TokenService; import com.xyhmo.service.UserAuthInfoService; import com.xyhmo.service.UserInfoService; import com.xyhmo.vo.UserVo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.ArrayList; import java.util.List; @Service public class UserInfoServiceImpl implements UserInfoService{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private UserInfoDao userInfoDao; @Autowired private UserAuthInfoService userAuthInfoService; @Autowired private TokenService tokenService; @Autowired private RedisService redisService; @Override public Long save(String mobile) { logger.info("UserInfoServiceImpl save:mobile="+mobile); ParamCheckUtil.checkMobileNumber(mobile); UserInfo userInfo = new UserInfo(); userInfo.setMobileNumber(mobile); userInfo.setPin(UniqueUtil.genPin(mobile)); userInfo.setStatus(ParamEnum.PARAM_DATA_USED.getCode()); return userInfoDao.insert(userInfo); } @Override public UserInfo autuwaredUserInfo(String mobile) { return null; } @Override public UserInfo getUserInfoByMobile(String mobile) { return userInfoDao.selectUserInfoByMobile(mobile); } @Override public void EditUserInfo(UserVo vo) { if(vo==null || StringUtils.isEmpty(vo.getPin())){ return ; } UserInfo userInfo = userInfoDao.selectUserInfoByPin(vo.getPin()); if(userInfo==null){ return ; } userInfo.setUserType(vo.getUserType()); userInfoDao.updateUserInfo(userInfo); } @Override public UserVo autowaredToVo(UserInfo userInfo, UserAuthInfo userAuthInfo) { if(userInfo==null){ return null; } UserVo vo = new UserVo(); vo.setId(userInfo.getId()); vo.setPin(userInfo.getPin()); vo.setToken(userInfo.getToken()); vo.setMobileNumber(userInfo.getMobileNumber()); vo.setUserName(userInfo.getUserName()); vo.setUserType(userInfo.getUserType()); vo.setPassword(<PASSWORD>()); vo.setBindVender(userInfo.getBindVender()); vo.setBindVenderProxy(userInfo.getBindVenderProxy()); vo.setIsAuth(userInfo.getIsAuth()); vo.setImageHearder(userInfo.getImageHearder()); vo.setCreated(userInfo.getCreated()); vo.setModified(userInfo.getModified()); vo.setScore(userInfo.getScore()); vo.setIsAcceptOrder(userInfo.getIsAcceptOrder()); if(null==userAuthInfo){ return vo; } vo.setRealName(userAuthInfo.getRealName()); vo.setImageCardFace(userAuthInfo.getImageCardFace()); vo.setImageCardBack(userAuthInfo.getImageCardBack()); vo.setImageCompanyQualiy(userAuthInfo.getImageCompanyQualiy()); vo.setCompanyName(userAuthInfo.getCompanyName()); vo.setAuthCreated(userAuthInfo.getCreated()); vo.setAuthModified(userAuthInfo.getModified()); return vo; } @Override public UserInfo getUserInfoByPin(String pin) { return userInfoDao.selectUserInfoByPin(pin); } @Override public UserVo getUserVoByToken(String token) { UserVo vo = tokenService.checkTokenExist(token); UserInfo userInfo = getUserInfoByPin(vo.getPin()); UserAuthInfo userAuthInfo = userAuthInfoService.getUserAuthInfoByPin(vo.getPin()); UserVo userVo = autowaredToVo(userInfo,userAuthInfo); redisService.set(Contants.REDIS_TOKEKN_BEFORE+token,userVo,Contants.TOKEN_OVER_TIME); return userVo; } @Override public List<UserInfo> getUserInfoByProxyPin(String pin) { return userInfoDao.selectUserInfoByProxyPin(pin); } @Override public List<UserVo> autowaredToVoList(List<UserInfo> userInfoList, List<UserAuthInfo> userAuthInfoList) { List<UserVo> userVoList = new ArrayList<>(); if(CollectionUtils.isEmpty(userInfoList)){ logger.error("UserInfoServiceImpl autowaredToVoList:userInfoList is empty"); return userVoList; } for(UserInfo userInfo:userInfoList){ if(StringUtils.isEmpty(userInfo.getPin())){ continue; } UserVo vo = new UserVo(); vo.setId(userInfo.getId()); vo.setPin(userInfo.getPin()); vo.setToken(userInfo.getToken()); vo.setMobileNumber(userInfo.getMobileNumber()); vo.setUserName(userInfo.getUserName()); vo.setUserType(userInfo.getUserType()); vo.setPassword(<PASSWORD>.<PASSWORD>()); vo.setBindVender(userInfo.getBindVender()); vo.setBindVenderProxy(userInfo.getBindVenderProxy()); vo.setIsAuth(userInfo.getIsAuth()); vo.setImageHearder(userInfo.getImageHearder()); vo.setCreated(userInfo.getCreated()); vo.setModified(userInfo.getModified()); vo.setScore(userInfo.getScore()); vo.setIsAcceptOrder(userInfo.getIsAcceptOrder()); for(UserAuthInfo userAuthInfo:userAuthInfoList){ if(userInfo.getPin().equals(userAuthInfo.getPin())){ vo.setRealName(userAuthInfo.getRealName()); vo.setImageCardFace(userAuthInfo.getImageCardFace()); vo.setImageCardBack(userAuthInfo.getImageCardBack()); vo.setImageCompanyQualiy(userAuthInfo.getImageCompanyQualiy()); vo.setCompanyName(userAuthInfo.getCompanyName()); vo.setAuthCreated(userAuthInfo.getCreated()); vo.setAuthModified(userAuthInfo.getModified()); break; } } userVoList.add(vo); } return userVoList; } @Override public List<UserInfo> getProxyListByVenderPin(String pin) { if(StringUtils.isEmpty(pin)){ logger.error("pin is empty"); return new ArrayList<>(); } return userInfoDao.selectProxyListByVenderPin(pin); } }
6,735
0.668001
0.667705
180
36.466667
23.592466
109
false
false
0
0
0
0
0
0
0.633333
false
false
15
52eb29e3306a54de92ffb2d913ee01e4be0d6e44
1,992,864,896,668
b0e4c3f3fb97d687bf4d79685e90ff19a31a5696
/Project B/src/game/RoomManager.java
afc97a40f52ef4801ec00a87bc4204d85d21666a
[]
no_license
CCunningham0/training1
https://github.com/CCunningham0/training1
71dd2080bfb8127a904339730943ef968eebda85
4067bf65e6c5c70a1f7c7533dc9c7dd649034028
refs/heads/main
2023-07-02T05:28:21.198000
2021-07-23T18:45:57
2021-07-23T18:45:57
385,650,838
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package game; import fixtures.Room; /* * Class which loads rooms into memory */ public class RoomManager { Room startingRoom; public Room[] rooms; /* * Creates Room objects, links Rooms through exits, and designates * a starting room */ public void init() { rooms = new Room[8]; // Create Room objects Room foyer = new Room( "The Foyer", "A small foyer", "The small entryway of a neo-colonial house. A dining room is open to the West.\n" + "To the north is a medium-sized, tiled kitchen. " + "To the east, through a doorway, is a staircase which leads to the second floor.\n" + "To the west is a living room in which a sofa and a few chairs encircle a brick fireplace." ); rooms[0] = foyer; this.startingRoom = foyer; Room livingRoom = new Room( "The Living Room", "A cozy living room", "The living space for the residents of the home. It is dimly lit and a single book lies " + "on a side table next to the sofa.\n" + "To the north is the dining room with a large wooden table. " + "To the east is the foyer." ); this.rooms[1] = livingRoom; Room kitchen = new Room("The Kitchen", "A small open kitchen", "The kitchen has granite counter tops, a large white refridgerator, and the shelves are stocked" + "full of food,\n" + "as well as assorted kitchen utensils. To the east is a small bathroom with a single high window.\n" + "To the south is the foyer and entrance to the home. " + "To the west is the dining room with a clean dinner table." ); this.rooms[2] = kitchen; Room secondFloorHallway = new Room("The Second Floor", "A narrow hallway on the second floor", "The hallway on the second floor which leads to several upstairs rooms.\n" + "A few paintings of various landscapes hang on the eggshell colored walls.\n" + "To the north is a second bathroom with a bathtub and towel rack. " + "To the west down the hall is the master bedroom." ); this.rooms[3] = secondFloorHallway; Room diningRoom = new Room ("The Dining Room", "A square dining room", "The dining room of the household in which a large aged looking dinner table " + "stands taking up most the space\n" + "and under which cushioned wooden chairs sit. To the east is the kitchen. " + "To the south through an arch is the living room." ); this.rooms[4] = diningRoom; Room bathRoomFloor1 = new Room ("The 1st Floor Bathroom", "A small bathroom off of the kitchen", "The first floor bathroom who's doorway stands between the edge of the kitchen" + "counter top and the refridgerator.\n" + "Inside is a toilet, a sink, and small stained glass window near the ceiling. " + "To the west is the narrow doorway leading to the kitchen." ); this.rooms[5] = bathRoomFloor1; Room bathRoomFloor2 = new Room ("The 2nd Floor Bathroom", "A second bathroom upstairs", "The bathroom on the second floor which, somewhat larger than the one downstairs," + "holds a bathtub as well as a rack for towels.\n" + "Shades mask a window looking out over the lawn. " + "To the south is the exit onto the second floor hallway." ); this.rooms[6] = bathRoomFloor2; Room bedroom = new Room("The Master Bedroom", "A larger master bedroom", "The masterbedroom and where the building's owners sleep. Heavy curtains frame the windows\n" + "and a television hangs on the wall across from the bed, above an antique looking dresser.\n" + "To the east is the doorway to the hallway." ); this.rooms[7] = bedroom; // Set Room exits foyer.setExits(kitchen, secondFloorHallway, null, livingRoom); livingRoom.setExits(diningRoom, foyer, null, null); kitchen.setExits(null, bathRoomFloor1, foyer, diningRoom); secondFloorHallway.setExits(bathRoomFloor2, null, foyer, bedroom); diningRoom.setExits(null, kitchen, livingRoom, null); bathRoomFloor1.setExits(null, null, null, kitchen); bathRoomFloor2.setExits(null,null, secondFloorHallway, null); bedroom.setExits(null, secondFloorHallway, null, null); } }
UTF-8
Java
4,121
java
RoomManager.java
Java
[]
null
[]
package game; import fixtures.Room; /* * Class which loads rooms into memory */ public class RoomManager { Room startingRoom; public Room[] rooms; /* * Creates Room objects, links Rooms through exits, and designates * a starting room */ public void init() { rooms = new Room[8]; // Create Room objects Room foyer = new Room( "The Foyer", "A small foyer", "The small entryway of a neo-colonial house. A dining room is open to the West.\n" + "To the north is a medium-sized, tiled kitchen. " + "To the east, through a doorway, is a staircase which leads to the second floor.\n" + "To the west is a living room in which a sofa and a few chairs encircle a brick fireplace." ); rooms[0] = foyer; this.startingRoom = foyer; Room livingRoom = new Room( "The Living Room", "A cozy living room", "The living space for the residents of the home. It is dimly lit and a single book lies " + "on a side table next to the sofa.\n" + "To the north is the dining room with a large wooden table. " + "To the east is the foyer." ); this.rooms[1] = livingRoom; Room kitchen = new Room("The Kitchen", "A small open kitchen", "The kitchen has granite counter tops, a large white refridgerator, and the shelves are stocked" + "full of food,\n" + "as well as assorted kitchen utensils. To the east is a small bathroom with a single high window.\n" + "To the south is the foyer and entrance to the home. " + "To the west is the dining room with a clean dinner table." ); this.rooms[2] = kitchen; Room secondFloorHallway = new Room("The Second Floor", "A narrow hallway on the second floor", "The hallway on the second floor which leads to several upstairs rooms.\n" + "A few paintings of various landscapes hang on the eggshell colored walls.\n" + "To the north is a second bathroom with a bathtub and towel rack. " + "To the west down the hall is the master bedroom." ); this.rooms[3] = secondFloorHallway; Room diningRoom = new Room ("The Dining Room", "A square dining room", "The dining room of the household in which a large aged looking dinner table " + "stands taking up most the space\n" + "and under which cushioned wooden chairs sit. To the east is the kitchen. " + "To the south through an arch is the living room." ); this.rooms[4] = diningRoom; Room bathRoomFloor1 = new Room ("The 1st Floor Bathroom", "A small bathroom off of the kitchen", "The first floor bathroom who's doorway stands between the edge of the kitchen" + "counter top and the refridgerator.\n" + "Inside is a toilet, a sink, and small stained glass window near the ceiling. " + "To the west is the narrow doorway leading to the kitchen." ); this.rooms[5] = bathRoomFloor1; Room bathRoomFloor2 = new Room ("The 2nd Floor Bathroom", "A second bathroom upstairs", "The bathroom on the second floor which, somewhat larger than the one downstairs," + "holds a bathtub as well as a rack for towels.\n" + "Shades mask a window looking out over the lawn. " + "To the south is the exit onto the second floor hallway." ); this.rooms[6] = bathRoomFloor2; Room bedroom = new Room("The Master Bedroom", "A larger master bedroom", "The masterbedroom and where the building's owners sleep. Heavy curtains frame the windows\n" + "and a television hangs on the wall across from the bed, above an antique looking dresser.\n" + "To the east is the doorway to the hallway." ); this.rooms[7] = bedroom; // Set Room exits foyer.setExits(kitchen, secondFloorHallway, null, livingRoom); livingRoom.setExits(diningRoom, foyer, null, null); kitchen.setExits(null, bathRoomFloor1, foyer, diningRoom); secondFloorHallway.setExits(bathRoomFloor2, null, foyer, bedroom); diningRoom.setExits(null, kitchen, livingRoom, null); bathRoomFloor1.setExits(null, null, null, kitchen); bathRoomFloor2.setExits(null,null, secondFloorHallway, null); bedroom.setExits(null, secondFloorHallway, null, null); } }
4,121
0.690124
0.685513
107
37.514019
29.74828
106
false
false
0
0
0
0
0
0
3.308411
false
false
15
1af9ac4120274a06f83ce75b31d731c59698a9db
15,736,760,174,193
2d99a6840ce7fad264f8aeab632e726cb3cebc9a
/src/main/java/ch/codebulb/lombokvsgroovy/canonical/CanonicalLombok.java
7a61fa7d00d28870a87ee2ae6f2730df06bc2586
[ "BSD-3-Clause" ]
permissive
yaoReadingCode/lombokVsGroovy
https://github.com/yaoReadingCode/lombokVsGroovy
5cda26164e262c9441e8cbe88facc915e22600f9
dd07426d1b4da68124f658ab7c7b4c28d7f20f9d
refs/heads/master
2021-05-12T03:42:23.283000
2016-05-29T14:43:33
2016-05-29T14:43:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.codebulb.lombokvsgroovy.canonical; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class CanonicalLombok { private String name; private int age = 10; }
UTF-8
Java
264
java
CanonicalLombok.java
Java
[]
null
[]
package ch.codebulb.lombokvsgroovy.canonical; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class CanonicalLombok { private String name; private int age = 10; }
264
0.80303
0.795455
13
19.307692
13.769445
45
false
false
0
0
0
0
0
0
0.461538
false
false
15
877f48ad637e088a7f4e5371757fa9e78555f5b8
6,760,278,568,887
609b8741cbc32b103fa12b5697668496ff7cdce5
/src/main/java/com/chenjj/concurrent/utils/ReentrantLockTest4.java
faf3ecf3cd75065622c2ba758d11c3f88d86f8b2
[]
no_license
chenjunjiang/concurrent
https://github.com/chenjunjiang/concurrent
605edc063eb7e472943bbc9aa2500c271cb2e56a
a53365c57dca003ecb23cefe1053fde5ded8086d
refs/heads/master
2021-08-08T23:07:58.230000
2021-01-29T09:05:44
2021-01-29T09:05:44
42,591,587
0
0
null
false
2020-11-18T09:26:19
2015-09-16T14:16:48
2020-11-18T09:26:00
2020-11-18T09:26:18
561
0
0
2
Java
false
false
package com.chenjj.concurrent.utils; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * ReentrantLock VS. Synchronized * 多线程读操作性能对比 * Benchmark Mode Cnt Score Error Units * ReentrantLockTest4.base avgt 10 0.013 ± 0.002 us/op * ReentrantLockTest4.lock avgt 10 0.327 ± 0.008 us/op * ReentrantLockTest4.sync avgt 10 0.451 ± 0.041 us/op * 执行基准测试会发现在10个线程的情况下,显式锁Lock的性能要优于synchronized关键字。 */ @BenchmarkMode(Mode.AverageTime) @Measurement(iterations = 10) @Warmup(iterations = 10) @OutputTimeUnit(TimeUnit.MICROSECONDS) public class ReentrantLockTest4 { public static void main(String[] args) throws RunnerException { final Options options = new OptionsBuilder().include(ReentrantLockTest4.class.getSimpleName()) .forks(1) .build(); new Runner(options).run(); } @GroupThreads(10) @Group("base") @Benchmark public void testBaseMethod(Test test, Blackhole blackhole) { blackhole.consume(test.baseMethod()); } @GroupThreads(10) @Group("lock") @Benchmark public void testLockMethod(Test test, Blackhole blackhole) { blackhole.consume(test.lockMethod()); } @GroupThreads(10) @Group("sync") @Benchmark public void testSyncMethod(Test test, Blackhole blackhole) { blackhole.consume(test.syncMethod()); } @State(Scope.Group) public static class Test { private int x = 10; private final Lock lock = new ReentrantLock(); public int baseMethod() { return x; } public int lockMethod() { lock.lock(); try { return x; } finally { lock.unlock(); } } public int syncMethod() { synchronized (this) { return x; } } } }
UTF-8
Java
2,328
java
ReentrantLockTest4.java
Java
[]
null
[]
package com.chenjj.concurrent.utils; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * ReentrantLock VS. Synchronized * 多线程读操作性能对比 * Benchmark Mode Cnt Score Error Units * ReentrantLockTest4.base avgt 10 0.013 ± 0.002 us/op * ReentrantLockTest4.lock avgt 10 0.327 ± 0.008 us/op * ReentrantLockTest4.sync avgt 10 0.451 ± 0.041 us/op * 执行基准测试会发现在10个线程的情况下,显式锁Lock的性能要优于synchronized关键字。 */ @BenchmarkMode(Mode.AverageTime) @Measurement(iterations = 10) @Warmup(iterations = 10) @OutputTimeUnit(TimeUnit.MICROSECONDS) public class ReentrantLockTest4 { public static void main(String[] args) throws RunnerException { final Options options = new OptionsBuilder().include(ReentrantLockTest4.class.getSimpleName()) .forks(1) .build(); new Runner(options).run(); } @GroupThreads(10) @Group("base") @Benchmark public void testBaseMethod(Test test, Blackhole blackhole) { blackhole.consume(test.baseMethod()); } @GroupThreads(10) @Group("lock") @Benchmark public void testLockMethod(Test test, Blackhole blackhole) { blackhole.consume(test.lockMethod()); } @GroupThreads(10) @Group("sync") @Benchmark public void testSyncMethod(Test test, Blackhole blackhole) { blackhole.consume(test.syncMethod()); } @State(Scope.Group) public static class Test { private int x = 10; private final Lock lock = new ReentrantLock(); public int baseMethod() { return x; } public int lockMethod() { lock.lock(); try { return x; } finally { lock.unlock(); } } public int syncMethod() { synchronized (this) { return x; } } } }
2,328
0.636202
0.61391
80
27.0375
20.872496
102
false
false
0
0
0
0
0
0
0.3125
false
false
15
8c71b31786227f9695876ba89687b7bde84be254
6,760,278,568,973
8c7d6e3226dc369c4b82286ae3e5371440a8c130
/de.haase/src/main/java/java1618k1/GameOfLife.java
1ae8c0b01f38292b338728e1d6bfee2feb2ff233
[]
no_license
chrishaase/scrapbook
https://github.com/chrishaase/scrapbook
85a488f94fd8e69dadd415b3b4eea705b0c0fd8e
5f60144d9cfe47c6d10ebd0d5b471fd872671a34
refs/heads/master
2018-08-21T17:13:06.887000
2018-06-16T13:49:30
2018-06-16T13:49:30
130,110,136
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package java1618k1; public class GameOfLife { boolean[][] feld = { { false, false, false, false, false }, { false, false, true, false, false }, { false, false, true, false, false }, { false, false, true, false, false }, { false, false, false, false, false } }; boolean[][] feldTemp = new boolean[feld.length][]; int aliveCounter = 0; public static void main(String[] args) { GameOfLife myGame = new GameOfLife(); for (int i = 0; i < 10; i++) { myGame.print(); System.out.println(); myGame.nextGeneration(); } } void print() { for (int i = 0; i < feld.length; i++) { for (int j = 0; j < feld[i].length; j++) { if (feld[i][j] == true) { System.out.print("o "); } else { System.out.print(". "); } } System.out.println(); } } void nextGeneration() { // Create TemporaryField for (int i = 0; i < feld.length; i++) { int a = feld[i].length; feldTemp[i] = new boolean[a]; } // end for i // Copy Information in TemporaryField for (int i = 0; i < (feld.length); i++) { for (int j = 0; j < (feld[i].length); j++) { feldTemp[i][j] = feld[i][j]; } } // Loop through Zeilen 2 bis n-1 in Original (siehe oben) // Loop through Spalten 2 bis n-1 Original (siehe oben) for (int i = 1; i < (feld.length - 1); i++) { for (int j = 1; j < (feld[i].length - 1); j++) { // ---- check 8 neighbours on temporary field (das bleibt // erhalten) // - Loop through 9-Feld and count Neighbours dead alive aliveCounter = 0; for (int i2 = -1; i2 <= 1; i2++) { for (int j2 = -1; j2 <= 1; j2++) { if (feldTemp[i + i2][j + j2] == true) { // substract // Mittelpunkt // von Suchfeld // if necessary aliveCounter++; } // end if } // end j2 } // end i2 if (feldTemp[i][j] == true) { aliveCounter--; } // end if // if 3 neighbours alive and zelle dead then change to alive if (((aliveCounter == 3)) && (feldTemp[i][j] == false)) { feld[i][j] = true; } // if less than 2 or moren than three neighbours alive and zelle // alive // than set to dead if (((aliveCounter < 2) || (aliveCounter > 3)) && (feldTemp[i][j] == true)) { feld[i][j] = false; } } // end for i } // end for j } // end method nextgeneration } // end class
UTF-8
Java
2,588
java
GameOfLife.java
Java
[]
null
[]
package java1618k1; public class GameOfLife { boolean[][] feld = { { false, false, false, false, false }, { false, false, true, false, false }, { false, false, true, false, false }, { false, false, true, false, false }, { false, false, false, false, false } }; boolean[][] feldTemp = new boolean[feld.length][]; int aliveCounter = 0; public static void main(String[] args) { GameOfLife myGame = new GameOfLife(); for (int i = 0; i < 10; i++) { myGame.print(); System.out.println(); myGame.nextGeneration(); } } void print() { for (int i = 0; i < feld.length; i++) { for (int j = 0; j < feld[i].length; j++) { if (feld[i][j] == true) { System.out.print("o "); } else { System.out.print(". "); } } System.out.println(); } } void nextGeneration() { // Create TemporaryField for (int i = 0; i < feld.length; i++) { int a = feld[i].length; feldTemp[i] = new boolean[a]; } // end for i // Copy Information in TemporaryField for (int i = 0; i < (feld.length); i++) { for (int j = 0; j < (feld[i].length); j++) { feldTemp[i][j] = feld[i][j]; } } // Loop through Zeilen 2 bis n-1 in Original (siehe oben) // Loop through Spalten 2 bis n-1 Original (siehe oben) for (int i = 1; i < (feld.length - 1); i++) { for (int j = 1; j < (feld[i].length - 1); j++) { // ---- check 8 neighbours on temporary field (das bleibt // erhalten) // - Loop through 9-Feld and count Neighbours dead alive aliveCounter = 0; for (int i2 = -1; i2 <= 1; i2++) { for (int j2 = -1; j2 <= 1; j2++) { if (feldTemp[i + i2][j + j2] == true) { // substract // Mittelpunkt // von Suchfeld // if necessary aliveCounter++; } // end if } // end j2 } // end i2 if (feldTemp[i][j] == true) { aliveCounter--; } // end if // if 3 neighbours alive and zelle dead then change to alive if (((aliveCounter == 3)) && (feldTemp[i][j] == false)) { feld[i][j] = true; } // if less than 2 or moren than three neighbours alive and zelle // alive // than set to dead if (((aliveCounter < 2) || (aliveCounter > 3)) && (feldTemp[i][j] == true)) { feld[i][j] = false; } } // end for i } // end for j } // end method nextgeneration } // end class
2,588
0.491886
0.474884
95
25.242105
20.99309
81
false
false
0
0
0
0
0
0
3.126316
false
false
15
d37e68a7e71e9b60da15d8300094c1157a9eef3b
29,222,957,483,081
ffaf58e1641942c02fc8be0aa1ee2116215ed0be
/src/main/java/com/stusys/utils/TestCode.java
03ea840d619b51994d018d67845ab48e0d6a1654
[]
no_license
caoxingchi/StudentManager
https://github.com/caoxingchi/StudentManager
72bb3a43c7460aedece93aa0ada62abfa03b1cc5
f17cf92f2d4e4ee55dab08ebecabf289f696f400
refs/heads/master
2022-12-14T20:39:31.152000
2020-08-30T02:56:03
2020-08-30T02:56:03
291,375,850
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stusys.utils; import java.util.ArrayList; import java.util.List; public class TestCode { public static void main(String[] args) { List<Integer> ll=new ArrayList<>(); ll.add(231); ll.add(412); System.out.println(ll); } }
UTF-8
Java
274
java
TestCode.java
Java
[]
null
[]
package com.stusys.utils; import java.util.ArrayList; import java.util.List; public class TestCode { public static void main(String[] args) { List<Integer> ll=new ArrayList<>(); ll.add(231); ll.add(412); System.out.println(ll); } }
274
0.620438
0.59854
13
20.076923
14.40866
44
false
false
0
0
0
0
0
0
0.538462
false
false
15
79adcf6ff8acafc62b67d4a4af38fc68f05cae0e
29,214,367,617,462
01792e9d60f0e492af8604ca198d9d399dbd302c
/binary-tree-maximum-path-sum/Solution.java
1df51bf0ce91198fab12507a90e7578b09eb7ddb
[]
no_license
singh523/leetcode
https://github.com/singh523/leetcode
5de3bbe101b462a3416dc0cdbd020df055da1a15
bf286849508d32b35217d5684514d1a61fd1874a
refs/heads/master
2022-04-18T21:51:59.483000
2020-04-19T07:53:14
2020-04-19T07:53:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Definition for binary tree class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { int result = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { search(root); return result; } int search(TreeNode node) { if (node == null) { return 0; } int leftMaxPathSum = search(node.left); int rightMaxPathSum = search(node.right); result = Math.max(result, node.val + leftMaxPathSum + rightMaxPathSum); return Math .max(0, node.val + Math.max(leftMaxPathSum, rightMaxPathSum)); } }
UTF-8
Java
576
java
Solution.java
Java
[]
null
[]
// Definition for binary tree class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { int result = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { search(root); return result; } int search(TreeNode node) { if (node == null) { return 0; } int leftMaxPathSum = search(node.left); int rightMaxPathSum = search(node.right); result = Math.max(result, node.val + leftMaxPathSum + rightMaxPathSum); return Math .max(0, node.val + Math.max(leftMaxPathSum, rightMaxPathSum)); } }
576
0.682292
0.678819
30
18.200001
18.687607
73
false
false
0
0
0
0
0
0
1.666667
false
false
15
07db9c40738952aec1f40d52270edea6a217c37c
30,820,685,387,569
28565923384894839e99c61c8abf78cd2040c2fd
/Queues/RandomizedQueue.java
22187835a76927c9596b59144b27b2decda9d658
[]
no_license
ralucapelin/Algorithms-part-I
https://github.com/ralucapelin/Algorithms-part-I
fa7b5efa2c0da2c9b38d2182ade3f5558441f2ef
af136b187840daf4b2b6caecf5fc9a6a1a2acad7
refs/heads/main
2023-03-17T03:07:16.112000
2021-03-07T19:11:45
2021-03-07T19:11:45
345,419,566
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* ***************************************************************************** * Name: * Date: * Description: **************************************************************************** */ import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import java.util.Iterator; import java.util.NoSuchElementException; public class RandomizedQueue<Item> implements Iterable<Item> { private Item[] q; private int n; public RandomizedQueue() { q = (Item[]) new Object[1]; } private void resize(int capacity) { Item[] copy = (Item[]) new Object[capacity]; for (int i = 0; i < n; i++) copy[i] = q[i]; q = copy; } public boolean isEmpty() { return n == 0; } public int size() { return n; } public void enqueue(Item item) { if (item == null) throw new IllegalArgumentException("WRONG "); if (q.length == n) resize(2 * q.length); q[n++] = item; } public Item dequeue() { if (isEmpty()) throw new NoSuchElementException("WRONG "); int x = StdRandom.uniform(n); Item a = q[x]; q[x] = q[n - 1]; q[n - 1] = null; n--; if (n > 0 && n == q.length / 4) resize(q.length / 2); return a; } public Item sample() { if (isEmpty()) throw new NoSuchElementException("WRONG "); int x = StdRandom.uniform(n); return q[x]; } public Iterator<Item> iterator() { return new ListIterator(); } private class ListIterator implements Iterator<Item> { private int i = n; public boolean hasNext() { return i > 0; } public void remove() { throw new UnsupportedOperationException("WRONG "); } public Item next() { if (!hasNext()) throw new NoSuchElementException("WRONG "); return q[--i]; } } public static void main(String[] args) { RandomizedQueue<String> s = new RandomizedQueue<String>(); In in = new In(args[0]); while (!in.isEmpty()) { String i = in.readString(); s.enqueue(i); } Iterator<String> it = s.iterator(); while (it.hasNext()) { StdOut.println(it.next()); } StdOut.println("done "); StdOut.println(s.dequeue() + " OK "); Iterator<String> i = s.iterator(); while (i.hasNext()) { StdOut.println(i.next()); } } }
UTF-8
Java
2,664
java
RandomizedQueue.java
Java
[]
null
[]
/* ***************************************************************************** * Name: * Date: * Description: **************************************************************************** */ import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import java.util.Iterator; import java.util.NoSuchElementException; public class RandomizedQueue<Item> implements Iterable<Item> { private Item[] q; private int n; public RandomizedQueue() { q = (Item[]) new Object[1]; } private void resize(int capacity) { Item[] copy = (Item[]) new Object[capacity]; for (int i = 0; i < n; i++) copy[i] = q[i]; q = copy; } public boolean isEmpty() { return n == 0; } public int size() { return n; } public void enqueue(Item item) { if (item == null) throw new IllegalArgumentException("WRONG "); if (q.length == n) resize(2 * q.length); q[n++] = item; } public Item dequeue() { if (isEmpty()) throw new NoSuchElementException("WRONG "); int x = StdRandom.uniform(n); Item a = q[x]; q[x] = q[n - 1]; q[n - 1] = null; n--; if (n > 0 && n == q.length / 4) resize(q.length / 2); return a; } public Item sample() { if (isEmpty()) throw new NoSuchElementException("WRONG "); int x = StdRandom.uniform(n); return q[x]; } public Iterator<Item> iterator() { return new ListIterator(); } private class ListIterator implements Iterator<Item> { private int i = n; public boolean hasNext() { return i > 0; } public void remove() { throw new UnsupportedOperationException("WRONG "); } public Item next() { if (!hasNext()) throw new NoSuchElementException("WRONG "); return q[--i]; } } public static void main(String[] args) { RandomizedQueue<String> s = new RandomizedQueue<String>(); In in = new In(args[0]); while (!in.isEmpty()) { String i = in.readString(); s.enqueue(i); } Iterator<String> it = s.iterator(); while (it.hasNext()) { StdOut.println(it.next()); } StdOut.println("done "); StdOut.println(s.dequeue() + " OK "); Iterator<String> i = s.iterator(); while (i.hasNext()) { StdOut.println(i.next()); } } }
2,664
0.479354
0.474099
110
23.218182
19.194403
80
false
false
0
0
0
0
0
0
0.409091
false
false
15
8a0152aac1dba87cc74f5bcc28c97ea2c930662b
27,779,848,514,949
1e070336420255164df3cab3d070605af5b2c6dd
/src/InputAndOutputStream/ReaderAndWriterDemo.java
ff57e2aa130945371a3fa4d80e2c9bf457163d9a
[]
no_license
mengdeqian/java011
https://github.com/mengdeqian/java011
372958ab519fb0d56932de64c60822ce86032d89
bcb0989083b8ba20125ce6e42062097867d485d2
refs/heads/master
2020-07-06T10:06:42.490000
2019-08-18T08:55:43
2019-08-18T08:55:43
202,981,190
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package InputAndOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; /** * 字符流文件读写 * @author mdq * */ public class ReaderAndWriterDemo { private static final String FilePath1 = "E:/桌面文件/信息.txt"; private static final String FilePath2 = "E:/桌面文件/信息复制版1.txt"; public static void main(String [] args){ try { BufferedReader bReader = new BufferedReader(new FileReader(FilePath1)); //固定的读取格式 String line = null; while((line = bReader.readLine()) != null){ System.out.println(line); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String content = "团地点:山东省邹城市中心店中学"; BufferedWriter bWriter = null; try { bWriter = new BufferedWriter(new FileWriter(FilePath2)); bWriter.write(content); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { bWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
GB18030
Java
1,433
java
ReaderAndWriterDemo.java
Java
[ { "context": "ava.io.InputStream;\r\n\r\n/**\r\n * 字符流文件读写\r\n * @author mdq\r\n *\r\n */\r\npublic class ReaderAndWriterDemo {\r\n\tpr", "end": 283, "score": 0.9996408820152283, "start": 280, "tag": "USERNAME", "value": "mdq" } ]
null
[]
package InputAndOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; /** * 字符流文件读写 * @author mdq * */ public class ReaderAndWriterDemo { private static final String FilePath1 = "E:/桌面文件/信息.txt"; private static final String FilePath2 = "E:/桌面文件/信息复制版1.txt"; public static void main(String [] args){ try { BufferedReader bReader = new BufferedReader(new FileReader(FilePath1)); //固定的读取格式 String line = null; while((line = bReader.readLine()) != null){ System.out.println(line); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String content = "团地点:山东省邹城市中心店中学"; BufferedWriter bWriter = null; try { bWriter = new BufferedWriter(new FileWriter(FilePath2)); bWriter.write(content); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { bWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
1,433
0.663197
0.65948
55
22.454546
17.664364
74
false
false
0
0
0
0
0
0
2.127273
false
false
15
04b1c7decf36b8a8330a33e4c3e2f3fef2d97441
30,279,519,488,775
dd3eec242deb434f76d26b4dc0e3c9509c951ce7
/2018-work/jiuy-biz/jiuy-yjj-api/src/main/java/com/yujj/layimjavaclient/socket/A.java
3083d48ae982b783535f04c488d7a5f3a8b46fcc
[]
no_license
github4n/other_workplace
https://github.com/github4n/other_workplace
1091e6368abc51153b4c7ebbb3742c35fb6a0f4a
7c07e0d078518bb70399e50b35e9f9ca859ba2df
refs/heads/master
2020-05-31T10:12:37.160000
2019-05-25T15:48:54
2019-05-25T15:48:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yujj.layimjavaclient.socket; import org.apache.log4j.chainsaw.Main; import com.yujj.layimjavaclient.pojo.message.ToServerMessageMine; import com.yujj.layimjavaclient.pojo.message.ToServerMessageTo; import com.yujj.layimjavaclient.pojo.message.ToServerTextMessage; import com.yujj.layimjavaclient.socket.sender.MessageSender; import com.yujj.layimjavaclient.util.LayIMFactory; public class A { public static void main(String[] args) { ToServerTextMessage toServerTextMessage = new ToServerTextMessage();//LayIMFactory.createSerializer().toObject("",ToServerTextMessage.class); ToServerMessageMine mine = new ToServerMessageMine(); mine.setId(2); mine.setUsername("董仲"); mine.setContent("测试消息!!!"); mine.setAvatar(""); toServerTextMessage.setMine(mine); ToServerMessageTo to = new ToServerMessageTo(); to.setId(1); to.setName("赵兴林"); to.setSign("没有签名"); to.setType("friend"); to.setAvatar(""); toServerTextMessage.setTo(to); //得到接收的对象 MessageSender sender = new MessageSender(); sender.sendMessage(toServerTextMessage); } }
UTF-8
Java
1,134
java
A.java
Java
[ { "context": "ssageMine();\n\t\tmine.setId(2);\n\t\tmine.setUsername(\"董仲\");\n\t\tmine.setContent(\"测试消息!!!\");\n\t\tmine.setAvatar", "end": 689, "score": 0.9996852278709412, "start": 687, "tag": "USERNAME", "value": "董仲" }, { "context": "ToServerMessageTo();\n\t\tto.setId(1);\n\t\t...
null
[]
package com.yujj.layimjavaclient.socket; import org.apache.log4j.chainsaw.Main; import com.yujj.layimjavaclient.pojo.message.ToServerMessageMine; import com.yujj.layimjavaclient.pojo.message.ToServerMessageTo; import com.yujj.layimjavaclient.pojo.message.ToServerTextMessage; import com.yujj.layimjavaclient.socket.sender.MessageSender; import com.yujj.layimjavaclient.util.LayIMFactory; public class A { public static void main(String[] args) { ToServerTextMessage toServerTextMessage = new ToServerTextMessage();//LayIMFactory.createSerializer().toObject("",ToServerTextMessage.class); ToServerMessageMine mine = new ToServerMessageMine(); mine.setId(2); mine.setUsername("董仲"); mine.setContent("测试消息!!!"); mine.setAvatar(""); toServerTextMessage.setMine(mine); ToServerMessageTo to = new ToServerMessageTo(); to.setId(1); to.setName("赵兴林"); to.setSign("没有签名"); to.setType("friend"); to.setAvatar(""); toServerTextMessage.setTo(to); //得到接收的对象 MessageSender sender = new MessageSender(); sender.sendMessage(toServerTextMessage); } }
1,134
0.765625
0.762868
35
30.085714
28.605066
143
false
false
0
0
0
0
0
0
1.714286
false
false
15
31adfc10242b2ac7f6ed42ef42a18b47c68c67ac
19,705,309,967,497
607757d79701ebedbc081cfead0c1f0b33c5d18a
/src/main/java/com/example/demo/models/CustomerDTO.java
a29ac704bac84215eeb76deefda5d9e295997769
[]
no_license
Chaia81/NordicMotorhomeRental
https://github.com/Chaia81/NordicMotorhomeRental
25a12b3e6cff9395583efdccf790622c77447db2
cbda2821cbdd7e26c945795179dda38ce172de99
refs/heads/master
2022-07-29T08:06:59.761000
2020-05-25T12:12:01
2020-05-25T12:12:01
266,541,529
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.models; public class CustomerDTO { private int cusId; private String cusFirstName; private String cusLastName; private int cusPhone; private String cusAddress; private int cusZip; private String cusCity; private int cusDriversLicense; private String cusEmail; public CustomerDTO() { } public CustomerDTO(int cusId, String cusFirstName, String cusLastName, int cusPhone, String cusAddress, int cusZip, String cusCity, int cusDriversLicense, String cusEmail) { this.cusId = cusId; this.cusFirstName = cusFirstName; this.cusLastName = cusLastName; this.cusPhone = cusPhone; this.cusAddress = cusAddress; this.cusZip = cusZip; this.cusCity = cusCity; this.cusDriversLicense = cusDriversLicense; this.cusEmail = cusEmail; } public int getCusId() { return cusId; } public void setCusId(int cusId) { this.cusId = cusId; } public String getCusFirstName() { return cusFirstName; } public void setCusFirstName(String cusFirstName) { this.cusFirstName = cusFirstName; } public String getCusLastName() { return cusLastName; } public void setCusLastName(String cusLastName) { this.cusLastName = cusLastName; } public int getCusPhone() { return cusPhone; } public void setCusPhone(int cusPhone) { this.cusPhone = cusPhone; } public String getCusAddress() { return cusAddress; } public void setCusAddress(String cusAddress) { this.cusAddress = cusAddress; } public int getCusZip() { return cusZip; } public void setCusZip(int cusZip) { this.cusZip = cusZip; } public String getCusCity() { return cusCity; } public void setCusCity(String cusCity) { this.cusCity = cusCity; } public int getCusDriversLicense() { return cusDriversLicense; } public void setCusDriversLicense(int cusDriversLicense) { this.cusDriversLicense = cusDriversLicense; } public String getCusEmail() { return cusEmail; } public void setCusEmail(String cusEmail) { this.cusEmail = cusEmail; } @Override public String toString() { return "CustomerDTO{" + "cusId=" + cusId + ", cusFirstName='" + cusFirstName + '\'' + ", cusLastName='" + cusLastName + '\'' + ", cusPhone=" + cusPhone + ", cusAddress='" + cusAddress + '\'' + ", cusZip=" + cusZip + ", cusCity='" + cusCity + '\'' + ", cusDriversLicense=" + cusDriversLicense + ", cusEmail='" + cusEmail + '\'' + '}'; } }
UTF-8
Java
2,861
java
CustomerDTO.java
Java
[ { "context": " this.cusId = cusId;\n this.cusFirstName = cusFirstName;\n this.cusLastName = cusLastNam", "end": 593, "score": 0.6697766780853271, "start": 592, "tag": "NAME", "value": "c" }, { "context": "rstName = cusFirstName;\n this.cusLastName = cusLastName...
null
[]
package com.example.demo.models; public class CustomerDTO { private int cusId; private String cusFirstName; private String cusLastName; private int cusPhone; private String cusAddress; private int cusZip; private String cusCity; private int cusDriversLicense; private String cusEmail; public CustomerDTO() { } public CustomerDTO(int cusId, String cusFirstName, String cusLastName, int cusPhone, String cusAddress, int cusZip, String cusCity, int cusDriversLicense, String cusEmail) { this.cusId = cusId; this.cusFirstName = cusFirstName; this.cusLastName = cusLastName; this.cusPhone = cusPhone; this.cusAddress = cusAddress; this.cusZip = cusZip; this.cusCity = cusCity; this.cusDriversLicense = cusDriversLicense; this.cusEmail = cusEmail; } public int getCusId() { return cusId; } public void setCusId(int cusId) { this.cusId = cusId; } public String getCusFirstName() { return cusFirstName; } public void setCusFirstName(String cusFirstName) { this.cusFirstName = cusFirstName; } public String getCusLastName() { return cusLastName; } public void setCusLastName(String cusLastName) { this.cusLastName = cusLastName; } public int getCusPhone() { return cusPhone; } public void setCusPhone(int cusPhone) { this.cusPhone = cusPhone; } public String getCusAddress() { return cusAddress; } public void setCusAddress(String cusAddress) { this.cusAddress = cusAddress; } public int getCusZip() { return cusZip; } public void setCusZip(int cusZip) { this.cusZip = cusZip; } public String getCusCity() { return cusCity; } public void setCusCity(String cusCity) { this.cusCity = cusCity; } public int getCusDriversLicense() { return cusDriversLicense; } public void setCusDriversLicense(int cusDriversLicense) { this.cusDriversLicense = cusDriversLicense; } public String getCusEmail() { return cusEmail; } public void setCusEmail(String cusEmail) { this.cusEmail = cusEmail; } @Override public String toString() { return "CustomerDTO{" + "cusId=" + cusId + ", cusFirstName='" + cusFirstName + '\'' + ", cusLastName='" + cusLastName + '\'' + ", cusPhone=" + cusPhone + ", cusAddress='" + cusAddress + '\'' + ", cusZip=" + cusZip + ", cusCity='" + cusCity + '\'' + ", cusDriversLicense=" + cusDriversLicense + ", cusEmail='" + cusEmail + '\'' + '}'; } }
2,861
0.591052
0.591052
116
23.672413
22.978167
177
false
false
0
0
0
0
0
0
0.465517
false
false
15
e56f76ddfb592b7e3de66f0e9a41e1a0441701b1
32,993,938,815,185
b288bb367cf1d8c88dfada5db2cc189ac6df931b
/app/src/main/java/com/example/second/adapter/Adapters.java
a91ab7bc3fff31e28008093add21807ab5a192a9
[]
no_license
Zahar322/Second
https://github.com/Zahar322/Second
4bd6e40f194ee1775a397092118ca512203fc5a9
29581f9dfa2e005e0fc7279bbca7619eeb80569f
refs/heads/master
2023-02-18T19:11:02.782000
2021-01-17T13:23:44
2021-01-17T13:23:44
330,396,162
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.second.adapter; import android.app.Activity; import android.content.Context; import android.widget.ArrayAdapter; import com.example.second.R; import com.example.second.model.Coffee; import com.example.second.model.User; import java.util.List; public class Adapters { // public static ArrayAdapter<User> userAdapter(List<User> userList, Context context) { // return new UserAdapter(context, R.layout.listitem, userList); // } public static ArrayAdapter<User> userAdapter(List<User> userList, Context context) { return new UserAdapter(context, R.layout.coffee_item, userList); } public static ArrayAdapter<Coffee> coffeeAdapter(List<Coffee> coffees, Context context, Activity activity) { return new CoffeeAdapter(context, R.layout.coffee_item, coffees, activity); } public static ArrayAdapter<Integer> imageAdapter(Context context) { return new ImageAdapter(context, R.layout.image_item); } public static ArrayAdapter<User> postAdapter(List<User> userList, Context context) { return new PostAdapter(context, R.layout.post_item, userList); } }
UTF-8
Java
1,148
java
Adapters.java
Java
[]
null
[]
package com.example.second.adapter; import android.app.Activity; import android.content.Context; import android.widget.ArrayAdapter; import com.example.second.R; import com.example.second.model.Coffee; import com.example.second.model.User; import java.util.List; public class Adapters { // public static ArrayAdapter<User> userAdapter(List<User> userList, Context context) { // return new UserAdapter(context, R.layout.listitem, userList); // } public static ArrayAdapter<User> userAdapter(List<User> userList, Context context) { return new UserAdapter(context, R.layout.coffee_item, userList); } public static ArrayAdapter<Coffee> coffeeAdapter(List<Coffee> coffees, Context context, Activity activity) { return new CoffeeAdapter(context, R.layout.coffee_item, coffees, activity); } public static ArrayAdapter<Integer> imageAdapter(Context context) { return new ImageAdapter(context, R.layout.image_item); } public static ArrayAdapter<User> postAdapter(List<User> userList, Context context) { return new PostAdapter(context, R.layout.post_item, userList); } }
1,148
0.737805
0.737805
35
31.799999
34.087952
112
false
false
0
0
0
0
0
0
0.8
false
false
15
12dbff5a8053b6d2d8d19269033a1f41cf040633
32,993,938,811,308
3ee05452b1aab2995a9c4d963be453fbc2d2c5f0
/src/com/giraffects/notifymyway/EditVibrationPatternDialog.java
28184e1606d84fa4704122b24e5ea7089ebfa9c7
[]
no_license
JerichoJyant/NotifyMyWay
https://github.com/JerichoJyant/NotifyMyWay
741d75e2c778198dce32ebca0d86b966f78eb836
288c9ace8651325d1e4a58c59338be9d378efc68
refs/heads/master
2021-05-27T01:31:35.083000
2011-04-03T22:00:09
2011-04-03T22:00:09
1,192,034
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.giraffects.notifymyway; import android.app.Dialog; import android.database.Cursor; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class EditVibrationPatternDialog extends Dialog implements OnClickListener { public static final int TYPE_ADD = 1; public static final int TYPE_EDIT = 2; private int type; private SelectVibrationPattern context; // Effectively a context, however // additional methods needed private long id; public EditVibrationPatternDialog(SelectVibrationPattern context, int type) { // For adding super(context); this.type = type; this.context = context; setContentView(R.layout.edit_pattern_dialog); if (type == TYPE_EDIT) { setTitle("Edit Pattern"); } else if (type == TYPE_ADD) { setTitle("Add Pattern"); } Button save_button = (Button) findViewById(R.id.save_pattern_button); save_button.setOnClickListener(this); Button cancel_button = (Button) findViewById(R.id.cancel_pattern_button); cancel_button.setOnClickListener(this); } public EditVibrationPatternDialog(SelectVibrationPattern context, int type, long id) { // Editing super(context); this.type = type; this.context = context; this.id = id; setContentView(R.layout.edit_pattern_dialog); setTitle("Edit Pattern"); TextView vp_name = (TextView) findViewById(R.id.name); TextView vp_pattern = (TextView) findViewById(R.id.pattern); DatabaseManager db_manager = new DatabaseManager(context).open(); Cursor vp = db_manager.fetchVibrationPattern(id); vp_name.setText(vp.getString(vp .getColumnIndexOrThrow(DatabaseManager.VP_KEY_NAME))); vp_pattern.setText(vp.getString(vp .getColumnIndexOrThrow(DatabaseManager.VP_KEY_PATTERN))); db_manager.close(); Button save_button = (Button) findViewById(R.id.save_pattern_button); save_button.setOnClickListener(this); Button cancel_button = (Button) findViewById(R.id.cancel_pattern_button); cancel_button.setOnClickListener(this); } public void onClick(View v) { if (v.getId() == R.id.save_pattern_button) { // Very dense, but retrieves text values String vp_name = (String) ((TextView) findViewById(R.id.name)) .getText().toString(); String vp_pattern = ((TextView) findViewById(R.id.pattern)) .getText().toString(); if (vp_name == "") { // Name is blank // Notify user and cancel operation Toast toast = Toast .makeText( context, "The name of the pattern can not be blank, please try again.", Toast.LENGTH_SHORT); toast.show(); return; } if (vp_pattern == "") { // Pattern is blank // Notify user and cancel operation Toast toast = Toast.makeText(context, "The the pattern can not be blank, please try again.", Toast.LENGTH_SHORT); toast.show(); return; } DatabaseManager db_manager = new DatabaseManager(context).open(); if (type == TYPE_ADD) { StaticHelper.d("createVibrationPattern, name: " + vp_name + ", pattern:" + vp_pattern); long result = db_manager.createVibrationPattern(vp_name, vp_pattern); if (result == -1) { StaticHelper .e("Could not insert new row into database with values " + vp_name + ", " + vp_pattern + ". Contact developer"); CharSequence text = "Error inserting the new row into database"; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else { StaticHelper.d("Created database row id: " + result); } context.onChangeVibrationPatterns(); db_manager.close(); dismiss(); } else if (type == TYPE_EDIT) { if (db_manager.updateVibrationPattern(id, vp_name, vp_pattern)) { Toast toast = Toast.makeText(context, "Edited vibration pattern", Toast.LENGTH_SHORT); toast.show(); context.onChangeVibrationPatterns(); db_manager.close(); } else { StaticHelper.e("Could not edit vibration pattern"); Toast toast = Toast .makeText( context, "Failed to edit vibration pattern, contact developer", Toast.LENGTH_SHORT); toast.show(); } dismiss(); // onChangeVibrationPatterns(); } } else if (v.getId() == R.id.cancel_pattern_button) { StaticHelper.d("Dialog Canceled"); dismiss(); } } }
UTF-8
Java
4,453
java
EditVibrationPatternDialog.java
Java
[]
null
[]
package com.giraffects.notifymyway; import android.app.Dialog; import android.database.Cursor; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class EditVibrationPatternDialog extends Dialog implements OnClickListener { public static final int TYPE_ADD = 1; public static final int TYPE_EDIT = 2; private int type; private SelectVibrationPattern context; // Effectively a context, however // additional methods needed private long id; public EditVibrationPatternDialog(SelectVibrationPattern context, int type) { // For adding super(context); this.type = type; this.context = context; setContentView(R.layout.edit_pattern_dialog); if (type == TYPE_EDIT) { setTitle("Edit Pattern"); } else if (type == TYPE_ADD) { setTitle("Add Pattern"); } Button save_button = (Button) findViewById(R.id.save_pattern_button); save_button.setOnClickListener(this); Button cancel_button = (Button) findViewById(R.id.cancel_pattern_button); cancel_button.setOnClickListener(this); } public EditVibrationPatternDialog(SelectVibrationPattern context, int type, long id) { // Editing super(context); this.type = type; this.context = context; this.id = id; setContentView(R.layout.edit_pattern_dialog); setTitle("Edit Pattern"); TextView vp_name = (TextView) findViewById(R.id.name); TextView vp_pattern = (TextView) findViewById(R.id.pattern); DatabaseManager db_manager = new DatabaseManager(context).open(); Cursor vp = db_manager.fetchVibrationPattern(id); vp_name.setText(vp.getString(vp .getColumnIndexOrThrow(DatabaseManager.VP_KEY_NAME))); vp_pattern.setText(vp.getString(vp .getColumnIndexOrThrow(DatabaseManager.VP_KEY_PATTERN))); db_manager.close(); Button save_button = (Button) findViewById(R.id.save_pattern_button); save_button.setOnClickListener(this); Button cancel_button = (Button) findViewById(R.id.cancel_pattern_button); cancel_button.setOnClickListener(this); } public void onClick(View v) { if (v.getId() == R.id.save_pattern_button) { // Very dense, but retrieves text values String vp_name = (String) ((TextView) findViewById(R.id.name)) .getText().toString(); String vp_pattern = ((TextView) findViewById(R.id.pattern)) .getText().toString(); if (vp_name == "") { // Name is blank // Notify user and cancel operation Toast toast = Toast .makeText( context, "The name of the pattern can not be blank, please try again.", Toast.LENGTH_SHORT); toast.show(); return; } if (vp_pattern == "") { // Pattern is blank // Notify user and cancel operation Toast toast = Toast.makeText(context, "The the pattern can not be blank, please try again.", Toast.LENGTH_SHORT); toast.show(); return; } DatabaseManager db_manager = new DatabaseManager(context).open(); if (type == TYPE_ADD) { StaticHelper.d("createVibrationPattern, name: " + vp_name + ", pattern:" + vp_pattern); long result = db_manager.createVibrationPattern(vp_name, vp_pattern); if (result == -1) { StaticHelper .e("Could not insert new row into database with values " + vp_name + ", " + vp_pattern + ". Contact developer"); CharSequence text = "Error inserting the new row into database"; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else { StaticHelper.d("Created database row id: " + result); } context.onChangeVibrationPatterns(); db_manager.close(); dismiss(); } else if (type == TYPE_EDIT) { if (db_manager.updateVibrationPattern(id, vp_name, vp_pattern)) { Toast toast = Toast.makeText(context, "Edited vibration pattern", Toast.LENGTH_SHORT); toast.show(); context.onChangeVibrationPatterns(); db_manager.close(); } else { StaticHelper.e("Could not edit vibration pattern"); Toast toast = Toast .makeText( context, "Failed to edit vibration pattern, contact developer", Toast.LENGTH_SHORT); toast.show(); } dismiss(); // onChangeVibrationPatterns(); } } else if (v.getId() == R.id.cancel_pattern_button) { StaticHelper.d("Dialog Canceled"); dismiss(); } } }
4,453
0.677072
0.676398
142
30.359156
21.492004
78
false
false
0
0
0
0
0
0
3.774648
false
false
15
da27e035e35565564a0e800cc1eef183e2f95b50
23,201,413,355,956
182648f67859f181a5b4bcbff6abb9da38ab1eaf
/src/main/java/com/yzpt/config/exception/basic/RestException.java
cbf547ecf5b9d0087795556fad0f8b04b2bb8b95
[]
no_license
suikelei/yzpt
https://github.com/suikelei/yzpt
8d7af703d3b3b9def4003511b59f42cc02228a7e
efc6018249fdd68d0f0ba7b17779f4abf0dbca7b
refs/heads/master
2019-08-20T02:56:20.907000
2016-09-06T05:46:26
2016-09-06T05:46:26
67,336,204
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yzpt.config.exception.basic; /** * Created by suikelei on 15/12/24. */ public class RestException extends RuntimeException { private static final long serialVersionUID = -1137527703456674414L; private ErrorStatus status; public RestException(Throwable cause, ErrorStatus status) { super(status.getUserMessage(),cause); this.status = status; } public RestException(ErrorStatus status) { super(status.getUserMessage()); this.status = status; } public ErrorStatus getStatus() { return status; } }
UTF-8
Java
532
java
RestException.java
Java
[ { "context": "om.yzpt.config.exception.basic;\n\n/**\n * Created by suikelei on 15/12/24.\n */\npublic class RestException exten", "end": 68, "score": 0.9995245933532715, "start": 60, "tag": "USERNAME", "value": "suikelei" } ]
null
[]
package com.yzpt.config.exception.basic; /** * Created by suikelei on 15/12/24. */ public class RestException extends RuntimeException { private static final long serialVersionUID = -1137527703456674414L; private ErrorStatus status; public RestException(Throwable cause, ErrorStatus status) { super(status.getUserMessage(),cause); this.status = status; } public RestException(ErrorStatus status) { super(status.getUserMessage()); this.status = status; } public ErrorStatus getStatus() { return status; } }
532
0.75
0.703008
25
20.280001
21.21607
68
false
false
0
0
0
0
0
0
1.12
false
false
15
5bb666ff233d4361aa9b39137ffffb70e1f48d40
5,454,608,491,313
d4e7f138a2a53482d196b9a8c156a548ebd829cc
/app/src/main/java/com/stjepanmrganic/adoptr/ClickListener.java
69f8348bf5a0aaf937979076154e25b906a3016c
[]
no_license
smrganic/DogShelter
https://github.com/smrganic/DogShelter
3af97f79890d8060873447a6e2e0347acd5d304c
39027b15e865e4234cf90228b0c67032d8ddfb05
refs/heads/master
2021-01-01T07:24:06.927000
2020-02-08T17:01:26
2020-02-08T17:01:26
239,169,036
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stjepanmrganic.adoptr; public interface ClickListener { void onItemClick(int position); }
UTF-8
Java
107
java
ClickListener.java
Java
[]
null
[]
package com.stjepanmrganic.adoptr; public interface ClickListener { void onItemClick(int position); }
107
0.785047
0.785047
5
20.4
16.280048
35
false
false
0
0
0
0
0
0
0.4
false
false
15
0cd18ee8aa01dbeda5541962bd788f9663353c6e
19,361,712,589,374
f8676bfe1f51fc63f449a6e2b69aff0536b09cbd
/src/action/OutputFileAction.java
74693df3eea8f6e9cd0c61caa1efc0694372c615
[]
no_license
Wal8800/206-Project
https://github.com/Wal8800/206-Project
fb3b768cf6d5751e1a677ace41b5d2138e24f086
ac30f8735ff607187e43be51fb76fe4ef7e72b7c
refs/heads/master
2017-04-21T22:49:49.531000
2014-10-27T10:30:20
2014-10-27T10:30:20
24,632,157
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package action; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * Open a file chooser that allow the user to select or create file to save at * a particular directory. The class will automatically append the extension to the * file name defined by the sublcass if the file name doesn't have the extension. * Also ask for the user confirmation to over write the selected file * @author Ka Chun Law */ public abstract class OutputFileAction implements ActionListener { private String extension = ""; /** * Open up a save dialog which allows the user to the output file * and the directory. Attached extension to the file name if the extension * is not present in the file name and ask for confirmation for overwriting * file */ @Override public void actionPerformed(ActionEvent e) { extension = getExtension(); @SuppressWarnings("serial") JFileChooser mp3Chooser = new JFileChooser(){ @Override public void approveSelection() { File file = getSelectedFile(); //this is use to check if the file name that user want to save as //have extension in the end of file name. If not then attach it at the end Pattern pattern = Pattern.compile("." + extension+ "$"); Matcher matcher = pattern.matcher(file.getName()); if ( !matcher.find()) { String path = new StringBuilder(file.getAbsolutePath()).append("." +extension).toString(); file = new File (path); this.setSelectedFile(file); } //check if the file exist already and ask the user if they want to over write the file if(file.exists() && getDialogType() == SAVE_DIALOG){ int result = JOptionPane.showConfirmDialog(this, file.getName() + " already" + " exist. Do you want to overwrite ?","OverWrite ?",JOptionPane.YES_NO_OPTION); switch(result){ case JOptionPane.YES_OPTION: super.approveSelection(); return; case JOptionPane.NO_OPTION: return; case JOptionPane.CLOSED_OPTION: return; } } super.approveSelection(); } }; mp3Chooser.setSelectedFile(new File("Untitled." + extension)); int returnVal = mp3Chooser.showSaveDialog(null); //the user confirm the selected file, the file will pass onto outputFile ad //the name of the file will be shown on output filed text field if (returnVal == JFileChooser.APPROVE_OPTION) { File selectedFile = mp3Chooser.getSelectedFile(); processOutputFile(selectedFile); } } /** * This method will have to be implemented by subclass so * the output file will have extension the class want */ public abstract String getExtension(); /** * Intended to be override to have different way of processing output file * @param file */ public abstract void processOutputFile(File file); }
UTF-8
Java
3,146
java
OutputFileAction.java
Java
[ { "context": "rmation to over write the selected file\n * @author Ka Chun Law\n */\npublic abstract class OutputFileAction implem", "end": 585, "score": 0.9995306730270386, "start": 574, "tag": "NAME", "value": "Ka Chun Law" } ]
null
[]
package action; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * Open a file chooser that allow the user to select or create file to save at * a particular directory. The class will automatically append the extension to the * file name defined by the sublcass if the file name doesn't have the extension. * Also ask for the user confirmation to over write the selected file * @author <NAME> */ public abstract class OutputFileAction implements ActionListener { private String extension = ""; /** * Open up a save dialog which allows the user to the output file * and the directory. Attached extension to the file name if the extension * is not present in the file name and ask for confirmation for overwriting * file */ @Override public void actionPerformed(ActionEvent e) { extension = getExtension(); @SuppressWarnings("serial") JFileChooser mp3Chooser = new JFileChooser(){ @Override public void approveSelection() { File file = getSelectedFile(); //this is use to check if the file name that user want to save as //have extension in the end of file name. If not then attach it at the end Pattern pattern = Pattern.compile("." + extension+ "$"); Matcher matcher = pattern.matcher(file.getName()); if ( !matcher.find()) { String path = new StringBuilder(file.getAbsolutePath()).append("." +extension).toString(); file = new File (path); this.setSelectedFile(file); } //check if the file exist already and ask the user if they want to over write the file if(file.exists() && getDialogType() == SAVE_DIALOG){ int result = JOptionPane.showConfirmDialog(this, file.getName() + " already" + " exist. Do you want to overwrite ?","OverWrite ?",JOptionPane.YES_NO_OPTION); switch(result){ case JOptionPane.YES_OPTION: super.approveSelection(); return; case JOptionPane.NO_OPTION: return; case JOptionPane.CLOSED_OPTION: return; } } super.approveSelection(); } }; mp3Chooser.setSelectedFile(new File("Untitled." + extension)); int returnVal = mp3Chooser.showSaveDialog(null); //the user confirm the selected file, the file will pass onto outputFile ad //the name of the file will be shown on output filed text field if (returnVal == JFileChooser.APPROVE_OPTION) { File selectedFile = mp3Chooser.getSelectedFile(); processOutputFile(selectedFile); } } /** * This method will have to be implemented by subclass so * the output file will have extension the class want */ public abstract String getExtension(); /** * Intended to be override to have different way of processing output file * @param file */ public abstract void processOutputFile(File file); }
3,141
0.664971
0.6637
94
32.468086
28.263464
95
false
false
0
0
0
0
0
0
2.085106
false
false
15
99325ee55d0778655d09f6a77e4ce4f6fdbc2431
23,416,161,719,550
647508b7af8ef6b10573157841e73ccc7ee90b86
/Practice_Chap17(String클래스)/src/example02/CharAtex.java
623e18e9522009ad3d74929fe05ac2961dd8dde3
[]
no_license
kimlsy2444/JAVA-Study
https://github.com/kimlsy2444/JAVA-Study
f2fc8cd47879db1c84cd5ca0bf5572b58bebcc70
592d0d603f2ba6f953950189eb1c3151474490fd
refs/heads/main
2023-07-16T19:17:43.457000
2021-09-02T09:14:36
2021-09-02T09:14:36
402,355,464
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package example02; public class CharAtex { public static void main(String[] args) { String ssn = "980203-2234567"; // o // 특정문자를 받고자 할 때 charAt() 메서드 사용 char sex = ssn.charAt(7); if(sex == '1' || sex == '3') { System.out.println("남자 입니다."); } else if(sex == '2' || sex == '4'){ System.out.println("여자 입니다."); } else { System.out.println("사람이 아님"); } } }
UHC
Java
477
java
CharAtex.java
Java
[]
null
[]
package example02; public class CharAtex { public static void main(String[] args) { String ssn = "980203-2234567"; // o // 특정문자를 받고자 할 때 charAt() 메서드 사용 char sex = ssn.charAt(7); if(sex == '1' || sex == '3') { System.out.println("남자 입니다."); } else if(sex == '2' || sex == '4'){ System.out.println("여자 입니다."); } else { System.out.println("사람이 아님"); } } }
477
0.520384
0.472422
25
15.68
15.01125
41
false
false
0
0
0
0
0
0
1.84
false
false
15
ba081f28237d05731877cf1b09743ba81b081457
9,062,381,026,482
e247bc5b989085699d1330fd7c0afcc0d91866ff
/shipmentservice/src/main/java/com/kenyam/shipmentservice/ShipmentController.java
493989eee44a585cce79ab4417415f2fd66e9a1b
[]
no_license
kenyam1979/MS-sample
https://github.com/kenyam1979/MS-sample
24e141977765a2b7c5435057aab2e3913dba3763
2d617e51df949aa2f7b09b0c1886854d475086bd
refs/heads/main
2023-03-21T23:02:20.189000
2021-03-09T13:15:41
2021-03-09T13:15:41
331,948,458
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kenyam.shipmentservice; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/shipment") public class ShipmentController { @Autowired private ShipmentService shipmentService; @RequestMapping(method = RequestMethod.GET) public List<Shipment> getOrderAll () { return shipmentService.getShipmentAll(); } @RequestMapping(method = RequestMethod.GET, value = "{id}") public Shipment getShipmentById (@PathVariable("id") int id) { return shipmentService.getShipmentById(id); } @RequestMapping(method = RequestMethod.GET, value = "/order/{id}") public Shipment getShipmentByOrderId (@PathVariable("id") int id) { return shipmentService.getShipmentByOrderId(id); } @RequestMapping(method = RequestMethod.GET, value = "/dispatch/{id}") // Temporarily implemented with GET public Shipment dispatchShipmentById (@PathVariable("id") int id) { return shipmentService.dispatchShipment(id); } @RequestMapping(method = RequestMethod.GET, value = "/complete/{id}") // Temporarily implemented with GET public Shipment completeShipmentById (@PathVariable("id") int id) { return shipmentService.completeShipment(id); } }
UTF-8
Java
1,351
java
ShipmentController.java
Java
[]
null
[]
package com.kenyam.shipmentservice; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/shipment") public class ShipmentController { @Autowired private ShipmentService shipmentService; @RequestMapping(method = RequestMethod.GET) public List<Shipment> getOrderAll () { return shipmentService.getShipmentAll(); } @RequestMapping(method = RequestMethod.GET, value = "{id}") public Shipment getShipmentById (@PathVariable("id") int id) { return shipmentService.getShipmentById(id); } @RequestMapping(method = RequestMethod.GET, value = "/order/{id}") public Shipment getShipmentByOrderId (@PathVariable("id") int id) { return shipmentService.getShipmentByOrderId(id); } @RequestMapping(method = RequestMethod.GET, value = "/dispatch/{id}") // Temporarily implemented with GET public Shipment dispatchShipmentById (@PathVariable("id") int id) { return shipmentService.dispatchShipment(id); } @RequestMapping(method = RequestMethod.GET, value = "/complete/{id}") // Temporarily implemented with GET public Shipment completeShipmentById (@PathVariable("id") int id) { return shipmentService.completeShipment(id); } }
1,351
0.722428
0.722428
41
31.95122
31.322828
109
false
false
0
0
0
0
0
0
0.341463
false
false
15
875843506b07fd9c589e8ee0693b17abb437627d
7,103,875,938,351
9b9b414777271b90424c57a4fc451406eaa8bb65
/MyFirstApp/src/com/example/myfirstapp/Entry_point.java
2362dd4ef8a1babc0cff98ce8601a8e270734c5d
[]
no_license
danielyaory/cool-app
https://github.com/danielyaory/cool-app
772b4b87e3fe9b25a11244b6b1576910474575b1
e5b1b438efb15b077b12eb2224b96ee796eb68b9
refs/heads/master
2020-05-30T09:22:09.203000
2015-04-18T14:05:31
2015-04-18T14:05:31
23,629,200
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.myfirstapp; import android.app.Activity; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; public class Entry_point extends Activity { MediaPlayer ourSong; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.entry_screen); ourSong = MediaPlayer.create(this, R.raw.splash_sound); Thread timer=new Thread(){ public void run(){ try{ ourSong.start(); sleep(2000); } catch(InterruptedException e){ e.printStackTrace(); }finally{ Intent OpenMainActivity= new Intent("com.example.MyFirstApp.MainActivity"); startActivity(OpenMainActivity); } } }; timer.start(); } /* (non-Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { super.onPause(); ourSong.release(); finish(); } /* (non-Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } }
UTF-8
Java
1,238
java
Entry_point.java
Java
[]
null
[]
package com.example.myfirstapp; import android.app.Activity; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; public class Entry_point extends Activity { MediaPlayer ourSong; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.entry_screen); ourSong = MediaPlayer.create(this, R.raw.splash_sound); Thread timer=new Thread(){ public void run(){ try{ ourSong.start(); sleep(2000); } catch(InterruptedException e){ e.printStackTrace(); }finally{ Intent OpenMainActivity= new Intent("com.example.MyFirstApp.MainActivity"); startActivity(OpenMainActivity); } } }; timer.start(); } /* (non-Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { super.onPause(); ourSong.release(); finish(); } /* (non-Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } }
1,238
0.630856
0.627625
66
16.757576
16.885588
80
false
false
0
0
0
0
0
0
2.106061
false
false
15
7259bd11878d46f6964ff75f9ebc9defde012a3b
13,623,636,293,260
36431722fd181aae0686ebb41630dbba12fd5273
/AirTrafficControl/src/br/ufrgs/inf/ga/GeneticAlgorithm.java
78d3b99d2b24c28558507944a4e9ddcadaf947ff
[]
no_license
qusaida83/aircraft-traffic-control
https://github.com/qusaida83/aircraft-traffic-control
38a7a1bdac3071d92f8103b4bc269cf83cb3ef39
29dec6a9dc6e9fd107a71c225a203f32b5eef75f
refs/heads/master
2021-01-10T04:49:29.906000
2010-06-25T01:02:30
2010-06-25T01:02:30
53,085,745
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.ufrgs.inf.ga; import java.util.List; import br.ufrgs.inf.atc.model.AircraftStaticData; import br.ufrgs.inf.atc.model.LandingSequenceCreator; import br.ufrgs.inf.ga.exceptions.AlgorithmException; import br.ufrgs.inf.ga.model.Individual; import br.ufrgs.inf.ga.model.IndividualCreator; import br.ufrgs.inf.ga.model.Parents; import br.ufrgs.inf.ga.model.Population; import br.ufrgs.inf.ga.model.PopulationConfig; import br.ufrgs.inf.ga.model.Solution; import br.ufrgs.inf.ga.operators.CrossoverOperator; import br.ufrgs.inf.ga.operators.MutationOperator; import br.ufrgs.inf.ga.operators.SelectionOperator; /** * Genetic Algorithm Class. * * <p> * This class implements a genetic algorithm meta heuristic to solve the * Air Traffic Control Problem. Solve means, find the best solution based in * an evaluation function in a finite number of iterations. * </p> * * @author diego * */ public class GeneticAlgorithm { /** * Max number of generations that the algorithm will run until a valid solution is find. */ public final int maxGenerations; /** * Responsible for initialize the population object. * This class provide a set of initializers methods. */ private final PopulationInitializer populationInitializer; /** * Operator used to select parents to a reproduction process. */ private final SelectionOperator selectionOperator = new SelectionOperator(); /** * Executes the crossover operator in a reproduction process. */ private final CrossoverOperator crossoverOperator; /** * Executes a mutation operation. */ private final MutationOperator mutationOperator; /** * Population where each individual represents a solution for the problem that is been solved. */ private Population population; /** * Parents selected by the {@link SelectionOperator} for reproduction. */ private List<Parents> selectedParents; /** * The best individual found at the end of the algorithm execution. */ private Individual bestIndividual; /** * Counts how many generations that none best solution is found. */ private int generationsWithoutImprovement = 0; /** * Algorithm solution. */ private Solution solution; /** * Initializes the dependencies. * * @param populationConfig population configuration parameters. * @param maxGenerations max number of generations. * @param aircrafts aircrafts data loaded from an input file. */ public GeneticAlgorithm(PopulationConfig populationConfig, int maxGenerations, AircraftStaticData[] aircrafts) { this.maxGenerations = maxGenerations; // Schedules aircraft landing times for a specific landing sequence. LandingTimeScheduler scheduler = new LandingTimeScheduler(); // Provides methods to create landing sequences with different characteristics. LandingSequenceCreator landingSequenceCreator = new LandingSequenceCreator(aircrafts); // Calculator for the fitness value of an individual in the population. FitnessEvaluator fitnessEvaluator = new FitnessEvaluator(); // IndividualCreator individualCreator = new IndividualCreator(landingSequenceCreator, fitnessEvaluator, scheduler); this.populationInitializer = new PopulationInitializer(individualCreator, populationConfig); this.crossoverOperator = new CrossoverOperator(scheduler, fitnessEvaluator); this.mutationOperator = new MutationOperator(scheduler, fitnessEvaluator); } /** * Executes the algorithm. * @throws AlgorithmException thrown if anything bad happens. */ public void execute() throws AlgorithmException { try { initializePopulation(); // Initial generation value int generation = 1; // The algorithm stop condition while(!solutionFound() && generation < maxGenerations) { //System.out.println("### generation " + generation); // swap the global best individual so far for the best individual of the current // generation, if this last one is better! findTheBestIndividualInCurrentGeneration(); // generating the next generation selectParentsForReproduction(); reproduct(); mutate(); // next generation... generation++; } this.solution = new Solution(population, bestIndividual, maxGenerations, generation, generationsWithoutImprovement); } catch (Exception e) { throw new AlgorithmException("An exception has occured when the algorithm was running.", e); } } /** * Verify if the best individual in the current generation is better than the global one found so far. */ private void findTheBestIndividualInCurrentGeneration() { // The best individual found in this population. Individual generationBestIndividual = population.getMostAdaptedIndividual(); //System.out.println("#### generation best individual: " + generationBestIndividual); //System.out.println("#### global best individual: " + bestIndividual); // if the best individual in this generation is more adapted than the global best individual so far, // than, the best individual in this generation becomes the global best individual. if (this.bestIndividual == null) { this.bestIndividual = generationBestIndividual; } else if (!this.bestIndividual.isMoreAdaptedThan(generationBestIndividual)) { this.bestIndividual = generationBestIndividual; generationsWithoutImprovement = 0; } else { // counts how many generations none global best solution is found. generationsWithoutImprovement++; } } /** * initializes the population and make the first fitness evaluation. */ protected void initializePopulation() { this.population = populationInitializer.createPopulation(); } /** * Selects a list of parents to reproduction and generation of new individuals. */ protected void selectParentsForReproduction() { this.selectedParents = selectionOperator.selectParents(population); } /** * Execute the reproduction operation. * * This process generates a new individual for each parents reproduction. * This son can join the population just if he is more adapted than one of his parents. * If true, the less adapted parent is replaced by his son. */ protected void reproduct() { for (Parents parents : selectedParents) { Individual son = crossoverOperator.execute(parents); Individual lessAdaptedParent = parents.getLessAdaptedParent(); if (son.isMoreAdaptedThan(lessAdaptedParent)) { population.replace(son, lessAdaptedParent); } } } /** * Mutates a percentage of bad individuals in attempt to generate better solutions. * This is good for escaping from minimal local solutions. */ protected void mutate() { int n = (int)(population.getSize() * population.getMutationRate()); int mutationStartIndex = (int)(population.getSize() * 0.5f); // Executes n randomly mutations in individuals starting from the middle of the sorted population to the end. for (int i = 0; i < n; i++) { // generates a random index between mutationStartIndex and the size of the population. int individualToBeMutatedIndex = mutationStartIndex + (int) (Math.random() * (population.getSize() - mutationStartIndex)); Individual individualToBeMutated = population.get(individualToBeMutatedIndex); mutationOperator.execute(individualToBeMutated); } population.setSorted(false); population.sortByFitness(); } /** * Verify the stop condition of the algorithm. * * <p> * If has been a long time since the last solution improvement, probably no improvement at all will occur, so we choose to stop the algorithm. * </p> * * @return true if the stop condition is reached, false otherwise. */ protected boolean solutionFound() { if (generationsWithoutImprovement > this.maxGenerations * 2/3) { return true; } return false; } /** * Returns the solution founded by the algorithm. * @return the solution. */ public Solution getSolution() { return this.solution; } }
UTF-8
Java
7,940
java
GeneticAlgorithm.java
Java
[ { "context": "inite number of iterations.\n * </p>\n * \n * @author diego\n *\n */\npublic class GeneticAlgorithm {\n\t\n\t/**\n\t *", "end": 899, "score": 0.9954344034194946, "start": 894, "tag": "USERNAME", "value": "diego" } ]
null
[]
package br.ufrgs.inf.ga; import java.util.List; import br.ufrgs.inf.atc.model.AircraftStaticData; import br.ufrgs.inf.atc.model.LandingSequenceCreator; import br.ufrgs.inf.ga.exceptions.AlgorithmException; import br.ufrgs.inf.ga.model.Individual; import br.ufrgs.inf.ga.model.IndividualCreator; import br.ufrgs.inf.ga.model.Parents; import br.ufrgs.inf.ga.model.Population; import br.ufrgs.inf.ga.model.PopulationConfig; import br.ufrgs.inf.ga.model.Solution; import br.ufrgs.inf.ga.operators.CrossoverOperator; import br.ufrgs.inf.ga.operators.MutationOperator; import br.ufrgs.inf.ga.operators.SelectionOperator; /** * Genetic Algorithm Class. * * <p> * This class implements a genetic algorithm meta heuristic to solve the * Air Traffic Control Problem. Solve means, find the best solution based in * an evaluation function in a finite number of iterations. * </p> * * @author diego * */ public class GeneticAlgorithm { /** * Max number of generations that the algorithm will run until a valid solution is find. */ public final int maxGenerations; /** * Responsible for initialize the population object. * This class provide a set of initializers methods. */ private final PopulationInitializer populationInitializer; /** * Operator used to select parents to a reproduction process. */ private final SelectionOperator selectionOperator = new SelectionOperator(); /** * Executes the crossover operator in a reproduction process. */ private final CrossoverOperator crossoverOperator; /** * Executes a mutation operation. */ private final MutationOperator mutationOperator; /** * Population where each individual represents a solution for the problem that is been solved. */ private Population population; /** * Parents selected by the {@link SelectionOperator} for reproduction. */ private List<Parents> selectedParents; /** * The best individual found at the end of the algorithm execution. */ private Individual bestIndividual; /** * Counts how many generations that none best solution is found. */ private int generationsWithoutImprovement = 0; /** * Algorithm solution. */ private Solution solution; /** * Initializes the dependencies. * * @param populationConfig population configuration parameters. * @param maxGenerations max number of generations. * @param aircrafts aircrafts data loaded from an input file. */ public GeneticAlgorithm(PopulationConfig populationConfig, int maxGenerations, AircraftStaticData[] aircrafts) { this.maxGenerations = maxGenerations; // Schedules aircraft landing times for a specific landing sequence. LandingTimeScheduler scheduler = new LandingTimeScheduler(); // Provides methods to create landing sequences with different characteristics. LandingSequenceCreator landingSequenceCreator = new LandingSequenceCreator(aircrafts); // Calculator for the fitness value of an individual in the population. FitnessEvaluator fitnessEvaluator = new FitnessEvaluator(); // IndividualCreator individualCreator = new IndividualCreator(landingSequenceCreator, fitnessEvaluator, scheduler); this.populationInitializer = new PopulationInitializer(individualCreator, populationConfig); this.crossoverOperator = new CrossoverOperator(scheduler, fitnessEvaluator); this.mutationOperator = new MutationOperator(scheduler, fitnessEvaluator); } /** * Executes the algorithm. * @throws AlgorithmException thrown if anything bad happens. */ public void execute() throws AlgorithmException { try { initializePopulation(); // Initial generation value int generation = 1; // The algorithm stop condition while(!solutionFound() && generation < maxGenerations) { //System.out.println("### generation " + generation); // swap the global best individual so far for the best individual of the current // generation, if this last one is better! findTheBestIndividualInCurrentGeneration(); // generating the next generation selectParentsForReproduction(); reproduct(); mutate(); // next generation... generation++; } this.solution = new Solution(population, bestIndividual, maxGenerations, generation, generationsWithoutImprovement); } catch (Exception e) { throw new AlgorithmException("An exception has occured when the algorithm was running.", e); } } /** * Verify if the best individual in the current generation is better than the global one found so far. */ private void findTheBestIndividualInCurrentGeneration() { // The best individual found in this population. Individual generationBestIndividual = population.getMostAdaptedIndividual(); //System.out.println("#### generation best individual: " + generationBestIndividual); //System.out.println("#### global best individual: " + bestIndividual); // if the best individual in this generation is more adapted than the global best individual so far, // than, the best individual in this generation becomes the global best individual. if (this.bestIndividual == null) { this.bestIndividual = generationBestIndividual; } else if (!this.bestIndividual.isMoreAdaptedThan(generationBestIndividual)) { this.bestIndividual = generationBestIndividual; generationsWithoutImprovement = 0; } else { // counts how many generations none global best solution is found. generationsWithoutImprovement++; } } /** * initializes the population and make the first fitness evaluation. */ protected void initializePopulation() { this.population = populationInitializer.createPopulation(); } /** * Selects a list of parents to reproduction and generation of new individuals. */ protected void selectParentsForReproduction() { this.selectedParents = selectionOperator.selectParents(population); } /** * Execute the reproduction operation. * * This process generates a new individual for each parents reproduction. * This son can join the population just if he is more adapted than one of his parents. * If true, the less adapted parent is replaced by his son. */ protected void reproduct() { for (Parents parents : selectedParents) { Individual son = crossoverOperator.execute(parents); Individual lessAdaptedParent = parents.getLessAdaptedParent(); if (son.isMoreAdaptedThan(lessAdaptedParent)) { population.replace(son, lessAdaptedParent); } } } /** * Mutates a percentage of bad individuals in attempt to generate better solutions. * This is good for escaping from minimal local solutions. */ protected void mutate() { int n = (int)(population.getSize() * population.getMutationRate()); int mutationStartIndex = (int)(population.getSize() * 0.5f); // Executes n randomly mutations in individuals starting from the middle of the sorted population to the end. for (int i = 0; i < n; i++) { // generates a random index between mutationStartIndex and the size of the population. int individualToBeMutatedIndex = mutationStartIndex + (int) (Math.random() * (population.getSize() - mutationStartIndex)); Individual individualToBeMutated = population.get(individualToBeMutatedIndex); mutationOperator.execute(individualToBeMutated); } population.setSorted(false); population.sortByFitness(); } /** * Verify the stop condition of the algorithm. * * <p> * If has been a long time since the last solution improvement, probably no improvement at all will occur, so we choose to stop the algorithm. * </p> * * @return true if the stop condition is reached, false otherwise. */ protected boolean solutionFound() { if (generationsWithoutImprovement > this.maxGenerations * 2/3) { return true; } return false; } /** * Returns the solution founded by the algorithm. * @return the solution. */ public Solution getSolution() { return this.solution; } }
7,940
0.743073
0.742065
243
31.674896
32.251541
144
false
false
0
0
0
0
0
0
1.781893
false
false
15
3236c44b35fd3db22927bcc4661becbf96a8b18d
3,324,304,711,447
71c8eccf56a94168bbf9408894d64e6956724405
/src/main/java/org/farmer/query/GetOp.java
f46b4ac3a6e40d3f273a42db082f0bf06751031f
[ "Apache-2.0" ]
permissive
gzygzy/farmer
https://github.com/gzygzy/farmer
f499ebda9bd60ff75b68763a9d5d98d0fad05795
c5cdea4c31accd56db1ff2d2b1d4be20fe9a7cf4
refs/heads/master
2017-04-26T21:08:40.808000
2013-11-21T09:22:03
2013-11-21T09:22:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.farmer.query; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Result; /** * Created with IntelliJ IDEA. * User: mengxin * Date: 13-10-7 * Time: 下午5:22 * To change this template use File | Settings | File Templates. */ public class GetOp { private static Configuration conf = HBaseConfiguration.create(); private HTable table = null; public GetOp(String tableName) throws IOException{ table = new HTable(conf,tableName); } public String fetchOne(String rowkey,String family,String column) throws IOException{ Get get = new Get(Bytes.toBytes(rowkey)); get.addColumn(Bytes.toBytes(family),Bytes.toBytes(column)); Result result = table.get(get); byte[] val = result.getValue(Bytes.toBytes(family),Bytes.toBytes(column)); return Bytes.toString(val); } }
UTF-8
Java
1,095
java
GetOp.java
Java
[ { "context": "sult;\n\n/**\n * Created with IntelliJ IDEA.\n * User: mengxin\n * Date: 13-10-7\n * Time: 下午5:22\n * To change thi", "end": 381, "score": 0.9995168447494507, "start": 374, "tag": "USERNAME", "value": "mengxin" } ]
null
[]
package org.farmer.query; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Result; /** * Created with IntelliJ IDEA. * User: mengxin * Date: 13-10-7 * Time: 下午5:22 * To change this template use File | Settings | File Templates. */ public class GetOp { private static Configuration conf = HBaseConfiguration.create(); private HTable table = null; public GetOp(String tableName) throws IOException{ table = new HTable(conf,tableName); } public String fetchOne(String rowkey,String family,String column) throws IOException{ Get get = new Get(Bytes.toBytes(rowkey)); get.addColumn(Bytes.toBytes(family),Bytes.toBytes(column)); Result result = table.get(get); byte[] val = result.getValue(Bytes.toBytes(family),Bytes.toBytes(column)); return Bytes.toString(val); } }
1,095
0.721357
0.714024
34
31.088236
25.170441
89
false
false
0
0
0
0
0
0
0.676471
false
false
15
96710ee5acfa66ee1aaab355c97e14975a4c09cc
15,427,522,558,485
d6984494b9493f8aecebc89c2fd181816bf032fe
/query/src/main/java/com/lantanagroup/link/query/uscore/Query.java
1819d32da71ccfe86515b7cf41f29b341d80e7be
[ "Apache-2.0" ]
permissive
lantanagroup/nandina
https://github.com/lantanagroup/nandina
45698fcbe69f15f5d60d82428130cbaf4208609a
a888b63551a37ed966bfdea58622d243595f70c2
refs/heads/master
2023-04-06T07:30:02.211000
2023-04-05T18:30:05
2023-04-05T18:30:05
250,599,538
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lantanagroup.link.query.uscore; import com.lantanagroup.link.model.PatientOfInterestModel; import com.lantanagroup.link.model.ReportContext; import com.lantanagroup.link.model.ReportCriteria; import com.lantanagroup.link.query.BaseQuery; import com.lantanagroup.link.query.IQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.List; @Component public class Query extends BaseQuery implements IQuery { private static final Logger logger = LoggerFactory.getLogger(Query.class); @Override public void execute(ReportCriteria criteria, ReportContext context, List<PatientOfInterestModel> patientsOfInterest, String reportId, List<String> resourceTypes, List<String> measureIds) { if (patientsOfInterest == null) { throw new IllegalArgumentException("patientsOfInterest"); } if (measureIds == null) { throw new IllegalArgumentException("Measure IDs must be provided"); } if (patientsOfInterest.size() > 0) { try { PatientScoop scoop = this.applicationContext.getBean(PatientScoop.class); scoop.setFhirQueryServer(this.getFhirQueryClient()); scoop.execute(criteria, context, patientsOfInterest, reportId, resourceTypes, measureIds); } catch (Exception ex) { logger.error("Error scooping data for patients: " + ex.getMessage()); ex.printStackTrace(); } } } }
UTF-8
Java
1,448
java
Query.java
Java
[]
null
[]
package com.lantanagroup.link.query.uscore; import com.lantanagroup.link.model.PatientOfInterestModel; import com.lantanagroup.link.model.ReportContext; import com.lantanagroup.link.model.ReportCriteria; import com.lantanagroup.link.query.BaseQuery; import com.lantanagroup.link.query.IQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.List; @Component public class Query extends BaseQuery implements IQuery { private static final Logger logger = LoggerFactory.getLogger(Query.class); @Override public void execute(ReportCriteria criteria, ReportContext context, List<PatientOfInterestModel> patientsOfInterest, String reportId, List<String> resourceTypes, List<String> measureIds) { if (patientsOfInterest == null) { throw new IllegalArgumentException("patientsOfInterest"); } if (measureIds == null) { throw new IllegalArgumentException("Measure IDs must be provided"); } if (patientsOfInterest.size() > 0) { try { PatientScoop scoop = this.applicationContext.getBean(PatientScoop.class); scoop.setFhirQueryServer(this.getFhirQueryClient()); scoop.execute(criteria, context, patientsOfInterest, reportId, resourceTypes, measureIds); } catch (Exception ex) { logger.error("Error scooping data for patients: " + ex.getMessage()); ex.printStackTrace(); } } } }
1,448
0.751381
0.749309
39
36.128204
36.987301
190
false
false
0
0
0
0
0
0
0.717949
false
false
15
64a0e221f6d3944e3725dbb4bec424dd31d0cb55
17,678,085,420,621
ace0f3a4b0139a905751891428d7a209e1d93287
/AlarmProject/src/com/imp/alarm/Adapter.java
cdb8785c7d70ad8070e4f65aa2a1a5bba3ab7dff
[]
no_license
sadistka/Alarm
https://github.com/sadistka/Alarm
4c69cab0e0b385a03e97c0caa145ab1eb0dd2c3c
04b22c4a7146c200795d27e1a25d1c57471bd669
refs/heads/master
2016-09-06T17:33:14.903000
2014-03-02T08:54:50
2014-03-02T08:54:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.imp.alarm; import java.util.ArrayList; import java.util.List; import com.imp.alarm.ViewController.ControllerAdapterCallback; import com.imp.utils.Utils; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; public class Adapter<T> extends ArrayAdapter<T> { public static interface AdapterCallback<T> { void initItem(ViewController views, T itemData, int position); int layoutId(); } public static interface ListUpdater { void update(); } private final List<T> mData = new ArrayList<T>(); private final AdapterCallback<T> mAdapterCallback; private final ControllerAdapterCallback mControllerCallback; public Adapter(Context context, List<T> data, AdapterCallback<T> adapterCallback, ControllerAdapterCallback adapterController) { super(context, -1); mData.addAll(data); mAdapterCallback = adapterCallback; mControllerCallback = adapterController; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewController controller = mControllerCallback.getViews(mAdapterCallback.layoutId()); mAdapterCallback.initItem(controller, getItem(position), position); return controller.get(); } @Override public int getCount() { return mData.size(); } @Override public T getItem(int position) { return mData.get(position); } @Override public boolean isEmpty() { return Utils.empty(mData); } }
UTF-8
Java
1,597
java
Adapter.java
Java
[]
null
[]
package com.imp.alarm; import java.util.ArrayList; import java.util.List; import com.imp.alarm.ViewController.ControllerAdapterCallback; import com.imp.utils.Utils; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; public class Adapter<T> extends ArrayAdapter<T> { public static interface AdapterCallback<T> { void initItem(ViewController views, T itemData, int position); int layoutId(); } public static interface ListUpdater { void update(); } private final List<T> mData = new ArrayList<T>(); private final AdapterCallback<T> mAdapterCallback; private final ControllerAdapterCallback mControllerCallback; public Adapter(Context context, List<T> data, AdapterCallback<T> adapterCallback, ControllerAdapterCallback adapterController) { super(context, -1); mData.addAll(data); mAdapterCallback = adapterCallback; mControllerCallback = adapterController; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewController controller = mControllerCallback.getViews(mAdapterCallback.layoutId()); mAdapterCallback.initItem(controller, getItem(position), position); return controller.get(); } @Override public int getCount() { return mData.size(); } @Override public T getItem(int position) { return mData.get(position); } @Override public boolean isEmpty() { return Utils.empty(mData); } }
1,597
0.702567
0.701941
57
27.017544
27.014286
132
false
false
0
0
0
0
0
0
0.614035
false
false
15
e4ab66146fd05a83c8a1870e51c8aaae71e74dac
22,101,901,737,790
9515831ba6ad7face3309560e20f2f9da3aafffc
/gsalazar-core/src/main/java/ar/com/gsalazar/services/impl/ProyectoServiceImpl.java
5392fb102bf5ad90a2fba3704b3d3f9d4e641e99
[]
no_license
sunixi/gsalazar
https://github.com/sunixi/gsalazar
2879aa30676f9f8231295bce60b5e048da6b1903
c1130d45d6e5ee4e9ab21adea2dc3f98bad84024
refs/heads/master
2021-01-10T03:06:04.209000
2010-08-29T17:36:58
2010-08-29T17:36:58
44,815,057
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package ar.com.gsalazar.services.impl; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import ar.com.gsalazar.beans.Persona; import ar.com.gsalazar.beans.Proyecto; import ar.com.gsalazar.daos.ProyectoDAO; import ar.com.gsalazar.dtos.BusquedaInfo; import ar.com.gsalazar.services.ProyectoService; import com.angel.architecture.exceptions.NonBusinessException; import com.angel.architecture.persistence.beans.TagSearch; import com.angel.architecture.services.TagSearchService; import com.angel.architecture.services.impl.GenericServiceImpl; /** * @author Guillermo Salazar * */ public class ProyectoServiceImpl extends GenericServiceImpl implements ProyectoService{ @Autowired private TagSearchService tagSearchService; protected ProyectoDAO getProyectoDAO(){ return (ProyectoDAO) super.getGenericDAO(); } public List<Proyecto> buscarTodosPorCantidadDesarrolladores(int cantidad) { return this.getProyectoDAO().buscarTodosPorCantidadDesarrolladores(cantidad); } public List<Proyecto> buscarTodos() { //TODO Cambiar esto al objeto proyecto, y persona respectivamente. List<Proyecto> proyectos = (List<Proyecto>) this.getProyectoDAO().findAll(); try { for(Proyecto proyecto: proyectos){ if(proyecto.getImagen() != null){ proyecto.setImagenArray(proyecto.getImagen().getBytes(1L, (int) proyecto.getImagen().length())); } for(Persona desarrollador: proyecto.getDesarrolladores()){ if(desarrollador.getImagen() != null){ desarrollador.setImagenArray(desarrollador.getImagen().getBytes(1L, (int) desarrollador.getImagen().length())); } } } } catch (SQLException e) { throw new NonBusinessException("No se pudo cargar la imagen del proyecto o persona.", e); } return proyectos; } public List<Proyecto> buscarTodosPorTagsNames(List<String> tagsNames) { List<TagSearch> tagsSearch = this.getTagSearchService().buscarTodosPorLabels(tagsNames); return this.buscarTodosPorTagsSearch(tagsSearch); } public List<Proyecto> buscarTodosPorTagsSearch(List<TagSearch> tagsSearch) { return this.getProyectoDAO().buscarTodosPorTagsSearch(tagsSearch); } public List<Proyecto> buscarTodosPorBusquedaInfo(BusquedaInfo busquedaInfo) { return this.getProyectoDAO().buscarTodosPorBusquedaInfo(busquedaInfo); } public List<Proyecto> buscarTodosEnDesarrollo(int cantidadMaxima) { return this.getProyectoDAO().buscarTodosEnDesarrollo(cantidadMaxima); } /** * @return the tagSearchService */ public TagSearchService getTagSearchService() { return tagSearchService; } /** * @param tagSearchService the tagSearchService to set */ public void setTagSearchService(TagSearchService tagSearchService) { this.tagSearchService = tagSearchService; } }
UTF-8
Java
2,908
java
ProyectoServiceImpl.java
Java
[ { "context": "rvices.impl.GenericServiceImpl;\r\n\r\n/**\r\n * @author Guillermo Salazar\r\n *\r\n */\r\npublic class ProyectoServiceImpl extend", "end": 678, "score": 0.9997389912605286, "start": 661, "tag": "NAME", "value": "Guillermo Salazar" } ]
null
[]
/** * */ package ar.com.gsalazar.services.impl; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import ar.com.gsalazar.beans.Persona; import ar.com.gsalazar.beans.Proyecto; import ar.com.gsalazar.daos.ProyectoDAO; import ar.com.gsalazar.dtos.BusquedaInfo; import ar.com.gsalazar.services.ProyectoService; import com.angel.architecture.exceptions.NonBusinessException; import com.angel.architecture.persistence.beans.TagSearch; import com.angel.architecture.services.TagSearchService; import com.angel.architecture.services.impl.GenericServiceImpl; /** * @author <NAME> * */ public class ProyectoServiceImpl extends GenericServiceImpl implements ProyectoService{ @Autowired private TagSearchService tagSearchService; protected ProyectoDAO getProyectoDAO(){ return (ProyectoDAO) super.getGenericDAO(); } public List<Proyecto> buscarTodosPorCantidadDesarrolladores(int cantidad) { return this.getProyectoDAO().buscarTodosPorCantidadDesarrolladores(cantidad); } public List<Proyecto> buscarTodos() { //TODO Cambiar esto al objeto proyecto, y persona respectivamente. List<Proyecto> proyectos = (List<Proyecto>) this.getProyectoDAO().findAll(); try { for(Proyecto proyecto: proyectos){ if(proyecto.getImagen() != null){ proyecto.setImagenArray(proyecto.getImagen().getBytes(1L, (int) proyecto.getImagen().length())); } for(Persona desarrollador: proyecto.getDesarrolladores()){ if(desarrollador.getImagen() != null){ desarrollador.setImagenArray(desarrollador.getImagen().getBytes(1L, (int) desarrollador.getImagen().length())); } } } } catch (SQLException e) { throw new NonBusinessException("No se pudo cargar la imagen del proyecto o persona.", e); } return proyectos; } public List<Proyecto> buscarTodosPorTagsNames(List<String> tagsNames) { List<TagSearch> tagsSearch = this.getTagSearchService().buscarTodosPorLabels(tagsNames); return this.buscarTodosPorTagsSearch(tagsSearch); } public List<Proyecto> buscarTodosPorTagsSearch(List<TagSearch> tagsSearch) { return this.getProyectoDAO().buscarTodosPorTagsSearch(tagsSearch); } public List<Proyecto> buscarTodosPorBusquedaInfo(BusquedaInfo busquedaInfo) { return this.getProyectoDAO().buscarTodosPorBusquedaInfo(busquedaInfo); } public List<Proyecto> buscarTodosEnDesarrollo(int cantidadMaxima) { return this.getProyectoDAO().buscarTodosEnDesarrollo(cantidadMaxima); } /** * @return the tagSearchService */ public TagSearchService getTagSearchService() { return tagSearchService; } /** * @param tagSearchService the tagSearchService to set */ public void setTagSearchService(TagSearchService tagSearchService) { this.tagSearchService = tagSearchService; } }
2,897
0.753783
0.753095
89
30.674158
31.344328
117
false
false
0
0
0
0
0
0
1.550562
false
false
15
9a28f83441e34a5ef587d160e64ab0379045cdcc
8,839,042,731,120
a55f4eb9a9758480b2383f5bd21ba8733cacab68
/explainability/service/xai-poc-v3/m2x-api/src/main/java/org/kie/trusty/m2x/model/PredictionInput.java
c9d74e387493d457cf8b1878e648abeee168e4dc
[ "Apache-2.0" ]
permissive
r00ta/trusty-ai-sandbox
https://github.com/r00ta/trusty-ai-sandbox
be71cee9281af5818d4ce7621273c28d2a779015
1bd26e2b8781204f5196719e40f2b37e121922e0
refs/heads/master
2021-12-29T09:53:01.852000
2021-09-07T12:21:12
2021-09-07T12:21:12
251,612,974
0
0
Apache-2.0
true
2020-03-31T13:37:13
2020-03-31T13:37:12
2020-03-31T13:21:45
2020-03-31T13:21:42
5
0
0
0
null
false
false
package org.kie.trusty.m2x.model; import java.util.Collections; import java.util.List; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; /** * The input of a prediction */ @Schema(name = "PredictionInput") public class PredictionInput { private List<Feature> features; public PredictionInput() { this.features = Collections.emptyList(); } @JsonCreator public PredictionInput(@JsonProperty("features") List<Feature> features) { this.features = features; } public List<Feature> getFeatures() { return features; } public void setFeatures(List<Feature> features) { this.features = features; } @Override public String toString() { return "PredictionInput{" + "features=" + features + '}'; } }
UTF-8
Java
931
java
PredictionInput.java
Java
[]
null
[]
package org.kie.trusty.m2x.model; import java.util.Collections; import java.util.List; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; /** * The input of a prediction */ @Schema(name = "PredictionInput") public class PredictionInput { private List<Feature> features; public PredictionInput() { this.features = Collections.emptyList(); } @JsonCreator public PredictionInput(@JsonProperty("features") List<Feature> features) { this.features = features; } public List<Feature> getFeatures() { return features; } public void setFeatures(List<Feature> features) { this.features = features; } @Override public String toString() { return "PredictionInput{" + "features=" + features + '}'; } }
931
0.659506
0.657358
41
21.707317
19.908625
78
false
false
0
0
0
0
0
0
0.292683
false
false
15
59dec203c75e10a5bf9fb2289b07f9b345b12778
22,325,240,034,755
9db31a345980d4f73d777f66499623eaa6caa316
/src/TestPerson.java
e0acec2e32c2990c07b8ae2f9cb90167e0adb361
[]
no_license
pradhanamit-eng/Serialization
https://github.com/pradhanamit-eng/Serialization
68b842149ae9fe4d97d45810c0072d5d63df2924
60802f7c89cc22534f9895564d1075b4dc69f031
refs/heads/master
2020-08-29T22:04:46.703000
2019-10-29T02:14:46
2019-10-29T02:14:46
218,185,441
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class TestPerson { public static void main(String[] args) { // create object of person Person person = new Person(); // store the name of person using setter person.setName("Cute wale hasan"); // fetch name of person String pn = person.getName(); System.out.println("name of person is "+pn); } }
UTF-8
Java
340
java
TestPerson.java
Java
[ { "context": "the name of person using setter\r\n\tperson.setName(\"Cute wale hasan\");\r\n\t\r\n\t// fetch name of person\r\n\tString pn = per", "end": 217, "score": 0.9998285174369812, "start": 202, "tag": "NAME", "value": "Cute wale hasan" } ]
null
[]
public class TestPerson { public static void main(String[] args) { // create object of person Person person = new Person(); // store the name of person using setter person.setName("<NAME>"); // fetch name of person String pn = person.getName(); System.out.println("name of person is "+pn); } }
331
0.644118
0.644118
16
19.125
16.537363
45
false
false
0
0
0
0
0
0
1.125
false
false
15
de8333169336d5875bf0dc4c3b427a4ae9263900
18,588,618,508,332
b15b4f84271e15c87876c89cd2b9ec38646a07ff
/Annotations/src/Developer.java
520d04d2c5ef3429d21de335f51adc37efe4f8a1
[]
no_license
bennylinn/springProjects
https://github.com/bennylinn/springProjects
a1ac5f7cdcd1a0fe9f6b26978f26da2240fbf87b
ce1f27922602105594d8e01b9d026707e5e5781b
refs/heads/master
2023-01-22T11:48:53.466000
2020-11-30T02:39:59
2020-11-30T02:39:59
286,321,545
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Developer extends Human { @Deprecated public String getName(){ return "Developer!"; } }
UTF-8
Java
118
java
Developer.java
Java
[ { "context": "recated\n\tpublic String getName(){\n return \"Developer!\";\n }\n}\n", "end": 106, "score": 0.8847697973251343, "start": 97, "tag": "NAME", "value": "Developer" } ]
null
[]
public class Developer extends Human { @Deprecated public String getName(){ return "Developer!"; } }
118
0.644068
0.644068
7
15.714286
13.603721
38
false
false
0
0
0
0
0
0
0.571429
false
false
15
b56eb9ba29a011295b11adaa6dd1b67c8697bf81
24,275,155,206,998
93159d84b23c96e6c7d2aa60112cfc14ec84d3f6
/tax/src/com/tax/junit/ws1/CommonEventType.java
72aca035d2f3f5a6fefec1475e0018a47c338057
[]
no_license
lzp-aygx/MyDemo
https://github.com/lzp-aygx/MyDemo
353d3699bb8137eb3a724fe36d580019a79c2225
248bb75ed2898514d5f8651ec77bd0dafb09f4b9
refs/heads/master
2016-08-09T21:57:13.415000
2016-03-16T08:15:31
2016-03-16T08:15:31
52,426,879
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tax.junit.ws1; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for CommonEventType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CommonEventType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Header" type="{http://www.leemanpaper.com/schema/technology/framework/Common/v001}EventHeaderType"/> * &lt;element name="Body" type="{http://www.leemanpaper.com/schema/technology/framework/Common/v001}EventBodyType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CommonEventType", namespace = "http://www.leemanpaper.com/schema/technology/framework/Common/v001", propOrder = { "header", "body" }) public class CommonEventType { @XmlElement(name = "Header", required = true) protected EventHeaderType header; @XmlElement(name = "Body", required = true) protected EventBodyType body; /** * Gets the value of the header property. * * @return * possible object is * {@link EventHeaderType } * */ public EventHeaderType getHeader() { return header; } /** * Sets the value of the header property. * * @param value * allowed object is * {@link EventHeaderType } * */ public void setHeader(EventHeaderType value) { this.header = value; } /** * Gets the value of the body property. * * @return * possible object is * {@link EventBodyType } * */ public EventBodyType getBody() { return body; } /** * Sets the value of the body property. * * @param value * allowed object is * {@link EventBodyType } * */ public void setBody(EventBodyType value) { this.body = value; } }
UTF-8
Java
2,280
java
CommonEventType.java
Java
[]
null
[]
package com.tax.junit.ws1; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for CommonEventType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CommonEventType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Header" type="{http://www.leemanpaper.com/schema/technology/framework/Common/v001}EventHeaderType"/> * &lt;element name="Body" type="{http://www.leemanpaper.com/schema/technology/framework/Common/v001}EventBodyType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CommonEventType", namespace = "http://www.leemanpaper.com/schema/technology/framework/Common/v001", propOrder = { "header", "body" }) public class CommonEventType { @XmlElement(name = "Header", required = true) protected EventHeaderType header; @XmlElement(name = "Body", required = true) protected EventBodyType body; /** * Gets the value of the header property. * * @return * possible object is * {@link EventHeaderType } * */ public EventHeaderType getHeader() { return header; } /** * Sets the value of the header property. * * @param value * allowed object is * {@link EventHeaderType } * */ public void setHeader(EventHeaderType value) { this.header = value; } /** * Gets the value of the body property. * * @return * possible object is * {@link EventBodyType } * */ public EventBodyType getBody() { return body; } /** * Sets the value of the body property. * * @param value * allowed object is * {@link EventBodyType } * */ public void setBody(EventBodyType value) { this.body = value; } }
2,280
0.612719
0.60614
89
24.606741
26.694534
130
false
false
0
0
0
0
0
0
0.292135
false
false
15
4bf5841f15545cd10efe813aee5d357134b5baca
34,153,579,970,166
31ae3f1b0da6397815f62db1e8d68d4b847477dc
/DynamicProgramming/Subsequence.java
d7ce485f7e23fa925ba161edbb35725c5434c894
[]
no_license
Buvi14/Data_Structures_Problem_Solving_Using-_Java
https://github.com/Buvi14/Data_Structures_Problem_Solving_Using-_Java
a19bd6b8c2cbd4f2eaac13f65f4db2bc5243869f
0d5ca5b30e0ce36142904da78efc86d7ee0b365c
refs/heads/main
2023-07-03T18:47:12.566000
2021-08-14T03:07:42
2021-08-14T03:07:42
392,923,346
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DynamicProgramming; public class Subsequence { public static void main(String[] args) { System.out.println(isSubsequence("axc","ahbgdc")); } public static boolean isSubsequence(String s, String t) { int[][] st = new int[s.length()+1][t.length()+1]; for (int i = 0; i < s.length()+1; i++) { for (int j = 0; j < t.length()+1; j++) { if(i==0){ st[i][j] = 0; } else if(j==0){ st[i][j]=0; } else if(s.charAt(i-1)==t.charAt(j-1)){ st[i][j] = st[i-1][j-1]+1; } else{ st[i][j] = Math.max(st[i-1][j],st[i][j-1]); } } } // for (int i = 0; i < st.length; i++) { // for (int j = 0; j < st[0].length; j++) { // System.out.print(st[i][j]); // } // System.out.println(); // } if(s.length() == st[st.length-1][st[0].length-1]){ return true; } else{ return false; } } }
UTF-8
Java
1,165
java
Subsequence.java
Java
[]
null
[]
package DynamicProgramming; public class Subsequence { public static void main(String[] args) { System.out.println(isSubsequence("axc","ahbgdc")); } public static boolean isSubsequence(String s, String t) { int[][] st = new int[s.length()+1][t.length()+1]; for (int i = 0; i < s.length()+1; i++) { for (int j = 0; j < t.length()+1; j++) { if(i==0){ st[i][j] = 0; } else if(j==0){ st[i][j]=0; } else if(s.charAt(i-1)==t.charAt(j-1)){ st[i][j] = st[i-1][j-1]+1; } else{ st[i][j] = Math.max(st[i-1][j],st[i][j-1]); } } } // for (int i = 0; i < st.length; i++) { // for (int j = 0; j < st[0].length; j++) { // System.out.print(st[i][j]); // } // System.out.println(); // } if(s.length() == st[st.length-1][st[0].length-1]){ return true; } else{ return false; } } }
1,165
0.370815
0.351073
37
30.486486
18.603432
63
false
false
0
0
0
0
0
0
0.594595
false
false
15
fe179a60e048382c09609a3977e14fdcc616e4bb
27,453,431,019,271
0b4b7a9845135377bef160659f70e2e4af2ff592
/AndroidTodolistOnline1/app/src/main/java/com/example/dell/androidtodolistonline1/BillActivity.java
907a9a818823081294f5dce8b7905beb88ba36e3
[]
no_license
Monir-Hossan/BillBoxAAPP-Project
https://github.com/Monir-Hossan/BillBoxAAPP-Project
a5ca840a7cc0b20fca37170d937e6bbd4fe47bc1
48b59159b9646625b8affa2422f097bef9a049d3
refs/heads/master
2020-05-26T15:36:22.931000
2019-05-24T19:05:11
2019-05-24T19:05:11
188,288,943
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.dell.androidtodolistonline1; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.example.dell.androidtodolistonline1.api.ApiBill; import com.example.dell.androidtodolistonline1.api.ApiBillInterface; import com.example.dell.androidtodolistonline1.pojo.Bill; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class BillActivity extends AppCompatActivity { private ApiBillInterface apiBillInterface; Bill bill; TextView name, billingMonth,billNo,kwhConsumed, acno,energyCharge,others,total, dueBill,biilPayafterduedate,tansactionId,submittDate; @Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.activity_bill ); name =(TextView) findViewById ( R.id.name ); billingMonth =(TextView) findViewById ( R.id.billingMonth); billNo =(TextView) findViewById ( R.id.billNo); kwhConsumed =(TextView) findViewById ( R.id.kwhConsumed); acno =(TextView) findViewById ( R.id.accno ); energyCharge =(TextView) findViewById ( R.id.energyCharge); others =(TextView) findViewById ( R.id.others); total =(TextView) findViewById ( R.id.total); dueBill =(TextView) findViewById ( R.id.dueBill); biilPayafterduedate =(TextView) findViewById ( R.id.biilPayafterduedate); tansactionId =(TextView) findViewById ( R.id.tansactionId); submittDate =(TextView) findViewById ( R.id.submittDate); apiBillInterface = ApiBill.getApiBill ().create ( ApiBillInterface.class ); } @Override protected void onResume () { super.onResume ( ); this.callForData(); } public void makeToast( String message){ Toast.makeText ( BillActivity.this , message, Toast.LENGTH_LONG ).show (); } public void callForData ( ) { Bundle bundle = getIntent().getExtras (); String account_no = bundle.getString ( "account_no" ); makeToast ( "Working " + String.valueOf ( account_no )); Call<Bill> call = apiBillInterface.getByAccountNo (account_no); call.enqueue ( new Callback<Bill> ( ) { @Override public void onResponse ( Call <Bill> call, Response<Bill> response ) { bill = response.body (); setData ( bill ); } @Override public void onFailure ( Call <Bill> call, Throwable t ) { makeToast ( "Not Found "+t.toString ()); } } ); } public void setData(Bill bill){ name.setText ( bill.getNameAddress () ); billingMonth.setText ( bill.getBillingMonth () ); billNo.setText ( bill.getBillNo () ); acno.setText ( bill.getAccountNo () ); kwhConsumed.setText ( bill.getKwhConsumed () ); energyCharge.setText ( bill.getEnergyCharge () ); others.setText ( bill.getOthers () ); total.setText ( bill.getTotalBill () ); biilPayafterduedate.setText ( bill.getBiilPayafterduedate () ); dueBill.setText ( bill.getDueBill () ); tansactionId.setText ( bill.getTansactionId () ); submittDate.setText ( bill.getSubmittDate () ); } public void BankMenu ( View view ) { Intent intent = new Intent ( this,BankMenu.class ); startActivity ( intent ); } public void BillsActivity ( View view ) { Intent intent = new Intent ( this,BillsActivity.class ); startActivity ( intent ); } }
UTF-8
Java
3,738
java
BillActivity.java
Java
[]
null
[]
package com.example.dell.androidtodolistonline1; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.example.dell.androidtodolistonline1.api.ApiBill; import com.example.dell.androidtodolistonline1.api.ApiBillInterface; import com.example.dell.androidtodolistonline1.pojo.Bill; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class BillActivity extends AppCompatActivity { private ApiBillInterface apiBillInterface; Bill bill; TextView name, billingMonth,billNo,kwhConsumed, acno,energyCharge,others,total, dueBill,biilPayafterduedate,tansactionId,submittDate; @Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.activity_bill ); name =(TextView) findViewById ( R.id.name ); billingMonth =(TextView) findViewById ( R.id.billingMonth); billNo =(TextView) findViewById ( R.id.billNo); kwhConsumed =(TextView) findViewById ( R.id.kwhConsumed); acno =(TextView) findViewById ( R.id.accno ); energyCharge =(TextView) findViewById ( R.id.energyCharge); others =(TextView) findViewById ( R.id.others); total =(TextView) findViewById ( R.id.total); dueBill =(TextView) findViewById ( R.id.dueBill); biilPayafterduedate =(TextView) findViewById ( R.id.biilPayafterduedate); tansactionId =(TextView) findViewById ( R.id.tansactionId); submittDate =(TextView) findViewById ( R.id.submittDate); apiBillInterface = ApiBill.getApiBill ().create ( ApiBillInterface.class ); } @Override protected void onResume () { super.onResume ( ); this.callForData(); } public void makeToast( String message){ Toast.makeText ( BillActivity.this , message, Toast.LENGTH_LONG ).show (); } public void callForData ( ) { Bundle bundle = getIntent().getExtras (); String account_no = bundle.getString ( "account_no" ); makeToast ( "Working " + String.valueOf ( account_no )); Call<Bill> call = apiBillInterface.getByAccountNo (account_no); call.enqueue ( new Callback<Bill> ( ) { @Override public void onResponse ( Call <Bill> call, Response<Bill> response ) { bill = response.body (); setData ( bill ); } @Override public void onFailure ( Call <Bill> call, Throwable t ) { makeToast ( "Not Found "+t.toString ()); } } ); } public void setData(Bill bill){ name.setText ( bill.getNameAddress () ); billingMonth.setText ( bill.getBillingMonth () ); billNo.setText ( bill.getBillNo () ); acno.setText ( bill.getAccountNo () ); kwhConsumed.setText ( bill.getKwhConsumed () ); energyCharge.setText ( bill.getEnergyCharge () ); others.setText ( bill.getOthers () ); total.setText ( bill.getTotalBill () ); biilPayafterduedate.setText ( bill.getBiilPayafterduedate () ); dueBill.setText ( bill.getDueBill () ); tansactionId.setText ( bill.getTansactionId () ); submittDate.setText ( bill.getSubmittDate () ); } public void BankMenu ( View view ) { Intent intent = new Intent ( this,BankMenu.class ); startActivity ( intent ); } public void BillsActivity ( View view ) { Intent intent = new Intent ( this,BillsActivity.class ); startActivity ( intent ); } }
3,738
0.649813
0.647673
111
32.675674
26.466419
83
false
false
0
0
0
0
0
0
0.675676
false
false
15
48a4495599ef195b40bfb7599e9f08263d08fdcf
34,626,026,371,987
81719ea633603b090e720ea2c95b054054d1845e
/pjx-sga-jee/src/test/java/ar/com/sga/tests/PersonaServiceUTest.java
38f8b1a5d1c56e2719e1d7fb1c06279f0bcd7bcf
[]
no_license
reyduar/jee-archetype-webapp
https://github.com/reyduar/jee-archetype-webapp
de0dc21352e03f3f06ba43320bcf4289146d9929
36b17f4b6bcef0c28f0aa86528e5f24e72a473b6
refs/heads/master
2020-04-13T21:39:04.566000
2014-02-24T03:21:31
2014-02-24T03:21:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ar.com.sga.tests; import static org.junit.Assert.*; import java.util.List; import javax.ejb.embeddable.EJBContainer; import org.junit.Before; import org.junit.Test; import ar.com.sga.domain.Persona; import ar.com.sga.service.PersonaService; public class PersonaServiceUTest { private PersonaService personaService; @Before public void setUp() throws Exception { EJBContainer contenedor = EJBContainer.createEJBContainer(); personaService = (PersonaService) contenedor.getContext(). lookup("java:global/classes/PersonaServiceImp!ar.com.sga.service.PersonaService"); } @Test public void PersonaServiceEJBtest() { System.out.println("Ininciando test EJB PersonasSevice"); assertTrue(personaService!=null); assertEquals(2,personaService.listarPersonas().size()); System.out.println("Resultado esperado 2: El Nro de personas es :"+personaService.listarPersonas().size()); this.desplegarPersonas(personaService.listarPersonas()); System.out.println("Fin de EJB Test-------------------"); } private void desplegarPersonas(List<Persona> listarPersonas) { for (Persona persona : listarPersonas) { System.out.println(persona); } } }
UTF-8
Java
1,191
java
PersonaServiceUTest.java
Java
[]
null
[]
package ar.com.sga.tests; import static org.junit.Assert.*; import java.util.List; import javax.ejb.embeddable.EJBContainer; import org.junit.Before; import org.junit.Test; import ar.com.sga.domain.Persona; import ar.com.sga.service.PersonaService; public class PersonaServiceUTest { private PersonaService personaService; @Before public void setUp() throws Exception { EJBContainer contenedor = EJBContainer.createEJBContainer(); personaService = (PersonaService) contenedor.getContext(). lookup("java:global/classes/PersonaServiceImp!ar.com.sga.service.PersonaService"); } @Test public void PersonaServiceEJBtest() { System.out.println("Ininciando test EJB PersonasSevice"); assertTrue(personaService!=null); assertEquals(2,personaService.listarPersonas().size()); System.out.println("Resultado esperado 2: El Nro de personas es :"+personaService.listarPersonas().size()); this.desplegarPersonas(personaService.listarPersonas()); System.out.println("Fin de EJB Test-------------------"); } private void desplegarPersonas(List<Persona> listarPersonas) { for (Persona persona : listarPersonas) { System.out.println(persona); } } }
1,191
0.74895
0.747271
45
25.466667
26.373894
109
false
false
0
0
0
0
0
0
1.444444
false
false
15
9e7a9462b874587daaf50bf8de6678dcc751963a
36,077,725,299,711
507c3eeed7b78fba0757b228db3fb48d5947be9c
/WebMailApp/src/main/java/com/cfn/app/MailServlet.java
5d6ae847fc650c018199b84ab2f91e5cc3473c8c
[]
no_license
sangramayak/com.old.spring
https://github.com/sangramayak/com.old.spring
7ef7a798172d06700c84b8742ba9b38b416602ad
58525b4437b2fa35859a04f12f0b52696f9dbce7
refs/heads/master
2021-04-27T00:46:13.282000
2018-02-05T07:16:26
2018-02-05T07:16:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cfn.app; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Servlet implementation class MailServlet */ public class MailServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MailServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String to=request.getParameter("to"); String subject=request.getParameter("subject"); String content=request.getParameter("content"); ApplicationContext ctx= new ClassPathXmlApplicationContext("spring-config.xml"); MailSendBean bean= (MailSendBean)ctx.getBean("mailSendBean"); bean.sendMail(to, subject, content); request.setAttribute("msg", "Message sent succesfully to "+to); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
UTF-8
Java
1,611
java
MailServlet.java
Java
[]
null
[]
package com.cfn.app; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Servlet implementation class MailServlet */ public class MailServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MailServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String to=request.getParameter("to"); String subject=request.getParameter("subject"); String content=request.getParameter("content"); ApplicationContext ctx= new ClassPathXmlApplicationContext("spring-config.xml"); MailSendBean bean= (MailSendBean)ctx.getBean("mailSendBean"); bean.sendMail(to, subject, content); request.setAttribute("msg", "Message sent succesfully to "+to); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
1,611
0.744258
0.743638
49
30.87755
31.313837
119
false
false
0
0
0
0
0
0
1.163265
false
false
15
fc6ec661f04c8e91384be2e0f27200e35e1dc3aa
34,815,004,926,093
ce6c35bd0e6e21568dd7ff0511ed97ab90fb5b86
/src/Offers/OffersBean.java
eef4f097857260a353515cb4def9cc34502b6742
[]
no_license
UdayangaAri/Ceybank-new
https://github.com/UdayangaAri/Ceybank-new
bf2fbdfb0fa15f56a3ffc89d35df7da9366b44f9
ec5024951f4f51d296351a53958cf93667490f94
refs/heads/master
2022-12-25T09:25:02.725000
2020-10-09T08:58:31
2020-10-09T08:58:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Offers; import java.sql.Blob; import javax.servlet.http.Part; public class OffersBean { protected int id; protected int ImageID; protected String Status; protected Part image; protected String ImageDate; protected Blob Images; protected String exdate; public String getExdate() { return exdate; } public void setExdate(String exdate) { this.exdate = exdate; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getImageID() { return ImageID; } public void setImageID(int imageID) { ImageID = imageID; } public String getStatus() { return Status; } public void setStatus(String status) { Status = status; } public Part getImage() { return image; } public void setImage(Part image) { this.image = image; } public String getImageDate() { return ImageDate; } public void setImageDate(String imageDate) { ImageDate = imageDate; } public Blob getImages() { return Images; } public void setImages(Blob images) { Images = images; } }
UTF-8
Java
1,049
java
OffersBean.java
Java
[]
null
[]
package Offers; import java.sql.Blob; import javax.servlet.http.Part; public class OffersBean { protected int id; protected int ImageID; protected String Status; protected Part image; protected String ImageDate; protected Blob Images; protected String exdate; public String getExdate() { return exdate; } public void setExdate(String exdate) { this.exdate = exdate; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getImageID() { return ImageID; } public void setImageID(int imageID) { ImageID = imageID; } public String getStatus() { return Status; } public void setStatus(String status) { Status = status; } public Part getImage() { return image; } public void setImage(Part image) { this.image = image; } public String getImageDate() { return ImageDate; } public void setImageDate(String imageDate) { ImageDate = imageDate; } public Blob getImages() { return Images; } public void setImages(Blob images) { Images = images; } }
1,049
0.696854
0.696854
63
15.650794
12.739339
45
false
false
0
0
0
0
0
0
1.460317
false
false
15
c9ce325983b439270620b2f1be4cca7460df4a35
35,802,847,398,978
0b4d0c67d74b256e1befbaa1a2565f60a8072d00
/src/main/java/io/lovelacetech/server/command/company/SaveCompanyCommand.java
92a09b834888419b856e424a44f8dce2bff061a0
[]
no_license
JaceyPenny/lovelaceassetmanager-server-v2
https://github.com/JaceyPenny/lovelaceassetmanager-server-v2
fddd4e9d72faa1a4e7bea6f982d7454f4a55885e
425cac16cc8303f1cfb84027c319fa74ee784182
refs/heads/master
2020-05-18T15:15:41.003000
2018-04-08T06:21:53
2018-04-08T06:21:53
184,492,572
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.lovelacetech.server.command.company; import io.lovelacetech.server.model.Company; import io.lovelacetech.server.model.api.enums.AccessLevel; import io.lovelacetech.server.model.api.model.ApiCompany; import io.lovelacetech.server.model.api.model.ApiUser; import io.lovelacetech.server.model.api.response.company.CompanyApiResponse; import io.lovelacetech.server.repository.UserRepository; import io.lovelacetech.server.util.AuthenticationUtils; import io.lovelacetech.server.util.Messages; import io.lovelacetech.server.util.RepositoryUtils; import io.lovelacetech.server.util.UUIDUtils; import org.springframework.http.HttpStatus; public class SaveCompanyCommand extends CompanyCommand<SaveCompanyCommand> { private ApiCompany company; private ApiUser user; private UserRepository userRepository; public SaveCompanyCommand setCompany(ApiCompany company) { this.company = company; return this; } public SaveCompanyCommand setUser(ApiUser user) { this.user = user; return this; } public SaveCompanyCommand setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; return this; } @Override public boolean checkCommand() { return super.checkCommand() && this.company != null && ((user == null && userRepository == null) || (user != null && userRepository != null)); } @Override public CompanyApiResponse execute() { if (!checkCommand()) { return new CompanyApiResponse().setDefault(); } // Remembers if this is a new company being created boolean isNewCompany = false; // If the user supplied "id" with their request, fetch the existing Company // for that ID. Otherwise, throw "Not Found" Company companyUpdate = company.toDatabase(); if (companyUpdate.hasId()) { Company existingCompany = getCompanyRepository().findOne(companyUpdate.getId()); if (existingCompany == null) { return new CompanyApiResponse().setNotFound(); } if (!AuthenticationUtils.userIsAtLeast(user, AccessLevel.ADMIN) && !UUIDUtils.idsEqual(existingCompany.getId(), user.getCompanyId())) { return new CompanyApiResponse().setAccessDenied(); } existingCompany.applyUpdate(companyUpdate); companyUpdate = existingCompany; } else { isNewCompany = true; } // A Company cannot be added to the database if its name is taken by another company Company existingCompanyWithName = getCompanyRepository().findByName(company.getName()); if (existingCompanyWithName != null && RepositoryUtils.updateConflictsWithExistingRow(companyUpdate, existingCompanyWithName)) { return new CompanyApiResponse() .setStatus(HttpStatus.CONFLICT) .setMessage(Messages.COMPANY_CONFLICTING_NAME); } companyUpdate = getCompanyRepository().save(companyUpdate); if (isNewCompany && user != null) { user.setCompanyId(companyUpdate.getId()); user.setAccessLevel(AccessLevel.ADMIN); userRepository.save(user.toDatabase()); } return new CompanyApiResponse() .setSuccess() .setResponse(companyUpdate.toApi()); } }
UTF-8
Java
3,204
java
SaveCompanyCommand.java
Java
[]
null
[]
package io.lovelacetech.server.command.company; import io.lovelacetech.server.model.Company; import io.lovelacetech.server.model.api.enums.AccessLevel; import io.lovelacetech.server.model.api.model.ApiCompany; import io.lovelacetech.server.model.api.model.ApiUser; import io.lovelacetech.server.model.api.response.company.CompanyApiResponse; import io.lovelacetech.server.repository.UserRepository; import io.lovelacetech.server.util.AuthenticationUtils; import io.lovelacetech.server.util.Messages; import io.lovelacetech.server.util.RepositoryUtils; import io.lovelacetech.server.util.UUIDUtils; import org.springframework.http.HttpStatus; public class SaveCompanyCommand extends CompanyCommand<SaveCompanyCommand> { private ApiCompany company; private ApiUser user; private UserRepository userRepository; public SaveCompanyCommand setCompany(ApiCompany company) { this.company = company; return this; } public SaveCompanyCommand setUser(ApiUser user) { this.user = user; return this; } public SaveCompanyCommand setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; return this; } @Override public boolean checkCommand() { return super.checkCommand() && this.company != null && ((user == null && userRepository == null) || (user != null && userRepository != null)); } @Override public CompanyApiResponse execute() { if (!checkCommand()) { return new CompanyApiResponse().setDefault(); } // Remembers if this is a new company being created boolean isNewCompany = false; // If the user supplied "id" with their request, fetch the existing Company // for that ID. Otherwise, throw "Not Found" Company companyUpdate = company.toDatabase(); if (companyUpdate.hasId()) { Company existingCompany = getCompanyRepository().findOne(companyUpdate.getId()); if (existingCompany == null) { return new CompanyApiResponse().setNotFound(); } if (!AuthenticationUtils.userIsAtLeast(user, AccessLevel.ADMIN) && !UUIDUtils.idsEqual(existingCompany.getId(), user.getCompanyId())) { return new CompanyApiResponse().setAccessDenied(); } existingCompany.applyUpdate(companyUpdate); companyUpdate = existingCompany; } else { isNewCompany = true; } // A Company cannot be added to the database if its name is taken by another company Company existingCompanyWithName = getCompanyRepository().findByName(company.getName()); if (existingCompanyWithName != null && RepositoryUtils.updateConflictsWithExistingRow(companyUpdate, existingCompanyWithName)) { return new CompanyApiResponse() .setStatus(HttpStatus.CONFLICT) .setMessage(Messages.COMPANY_CONFLICTING_NAME); } companyUpdate = getCompanyRepository().save(companyUpdate); if (isNewCompany && user != null) { user.setCompanyId(companyUpdate.getId()); user.setAccessLevel(AccessLevel.ADMIN); userRepository.save(user.toDatabase()); } return new CompanyApiResponse() .setSuccess() .setResponse(companyUpdate.toApi()); } }
3,204
0.722846
0.722846
95
32.726315
26.551416
100
false
false
0
0
0
0
0
0
0.473684
false
false
15
e4fd2d631004381e0c5f5cb9345e7a612d56953d
6,184,752,969,004
b5f3a751db5e59115889868d1dc1370ac8962517
/src/com/vng/skygarden/game/Machine.java
9e3f99bfe5d801dd55c8123dc336301c7ab4826e
[]
no_license
lavaalone/cgm
https://github.com/lavaalone/cgm
85581968d7f4c5484098f346300e5c4bb54746b8
b8944284c55acbdf208586d17086f562f384bdc7
refs/heads/master
2021-01-10T20:40:06.767000
2015-04-22T05:32:05
2015-04-22T05:32:05
34,370,185
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vng.skygarden.game; import com.vng.netty.*; import com.vng.util.*; import com.vng.log.*; import com.vng.db.*; import java.util.*; public class Machine { private byte floor; private byte id; private short level; private int active_time; private byte status; private int start_time; private byte slot_max; private byte slot_cur; private byte product_count; private byte product_completed_num; ArrayList<String> item_drop_list; // type:id:num ArrayList<SlotMachine> slot; ArrayList<byte[]> stock; Decor decor = null; private boolean load_result = true; private boolean need_save = false; private boolean LOG_MACHINE = !true; public Machine(int floor) { this.floor = (byte)floor; this.id = Misc.getMachineID(floor); this.level = 0; this.active_time = 0; this.status = DatabaseID.MACHINE_LOCK; this.start_time = -1; this.slot_max = 2; this.slot_cur = 0; this.product_count = 0; product_completed_num = 0; item_drop_list = new ArrayList<String>(); slot = new ArrayList<SlotMachine>(); stock = new ArrayList<byte[]>(); decor = new Decor(); // LogHelper.Log("Init machine OK!"); } public Machine(byte[] machine_bin) { FBEncrypt machine = new FBEncrypt(machine_bin); this.id = machine.getByte(KeyID.KEY_MACHINE_ID); this.floor = machine.getByte(KeyID.KEY_MACHINE_FLOOR); this.level = machine.getShort(KeyID.KEY_MACHINE_LEVEL); this.active_time = machine.getInt(KeyID.KEY_MACHINE_ACTIVE_TIME); this.status = machine.getByte(KeyID.KEY_MACHINE_STATUS); this.start_time = machine.getInt(KeyID.KEY_MACHINE_START_TIME); this.slot_max = machine.getByte(KeyID.KEY_MACHINE_SLOT_MAX); this.slot_cur = machine.getByte(KeyID.KEY_MACHINE_SLOT_CUR); this.product_count = machine.getByte(KeyID.KEY_MACHINE_PRODUCT_COUNT); this.product_completed_num = 0; item_drop_list = new ArrayList<String>(); if (machine.hasKey(KeyID.KEY_MACHINE_ITEM_DROP_LIST)) { String drop_list = machine.getString(KeyID.KEY_MACHINE_ITEM_DROP_LIST); // LogHelper.Log("load machine " + id + ": _" + drop_list + "_"); if(!drop_list.equals("")) { if (drop_list.contains(":18:")) drop_list = drop_list.replace(":18:", ":1:8:"); String[] items = drop_list.split(":"); if (items.length % 3 == 0) { for (int d = 0; d < items.length; d += 3) // type:id:num { item_drop_list.add(items[d] + ":" + items[d+1] + ":" + items[d+2]); } } } } slot = new ArrayList<SlotMachine>(); stock = new ArrayList<byte[]>(); for (int i = 0; i < this.slot_cur; i++) { byte[] slot_data = machine.getBinary(KeyID.KEY_MACHINE_SLOT + i); if (slot_data == null || slot_data.length == 0) { LogHelper.Log("Cannot load product slot " + i); load_result = false; return; } SlotMachine _slot_machine = new SlotMachine(slot_data); if (_slot_machine.isLoadSuccess() == false) { load_result = false; return; } slot.add(_slot_machine); } for (int i = 0; i < this.product_count; i++) { byte[] prod_data = machine.getBinary(KeyID.KEY_MACHINE_PRODUCT + i); if (prod_data == null || prod_data.length == 0) { LogHelper.Log("Cannot load product data " + i); load_result = false; return; } stock.add(prod_data); } // check completed product in slot then move to stock if (this.slot_cur > 0) { while (this.slot_cur > 0 && getFirstSlotTime() < Misc.SECONDS()) { if (slot.size() > 0) { int prod_id = slot.get(0).getID(); removeFirstSlot(); addProductToStock(prod_id); product_completed_num++; need_save = true; } } } //load decor byte[] bdecor = machine.getBinary(KeyID.KEY_MACHINE_DECOR); if (bdecor == null || bdecor.length == 0) { LogHelper.Log("Machine.. can not load decor data."); load_result = false; return; } decor = new Decor(bdecor); if (decor.isLoadSuccess() == false) { load_result = false; return; } // LogHelper.Log("Load machine...OK!"); } public boolean isLoadSuccess() { return load_result; } public boolean isNeedSave() { boolean _need_save = need_save; if (need_save) { need_save = false; } return _need_save; } public byte getProductCompleteNum() { return product_completed_num; } public void resetProductCompleteNum() { product_completed_num = 0; } public void addDropItem(String item) { if (product_count > item_drop_list.size()) // make sure item_drop_count always <= product_count { item_drop_list.add(item); } } public void increaseSlot() { slot_max += 1; } public void addProduct(int product_id) { setSlotCur(slot_cur + 1); int product_time = 0; if (slot.size() > 0) { product_time = slot.get(slot.size() - 1).getProductTime() + getProductCompleteTime(product_id); } else { product_time = Misc.SECONDS() + getProductCompleteTime(product_id); } // byte reduce_time_persent = Byte.parseByte(Misc.PARSE_STRING(Server.s_globalDB[DatabaseID.SHEET_MACHINE_UNLOCK][this.id][getLevel()]).split(":")[DatabaseID.MACHINE_REDUCE_TIME]); byte reduce_time_percent = (byte)Server.s_globalMachineUnlockData[this.floor][this.level][DatabaseID.MACHINE_REDUCE_TIME]; if (reduce_time_percent > 0) { int time_bonus = (getProductCompleteTime(product_id) * reduce_time_percent / 100); product_time -= time_bonus; } String start_event_time = Misc.PARSE_STRING(Server.s_globalDB[DatabaseID.SHEET_EVENT_GLOBAL][10][DatabaseID.EVENT_GLOBAL_START_DATE]); String end_event_time = Misc.PARSE_STRING(Server.s_globalDB[DatabaseID.SHEET_EVENT_GLOBAL][10][DatabaseID.EVENT_GLOBAL_END_DATE]); if(Misc.InEvent(start_event_time, end_event_time)) { // get machine id int machine_id = (int)Misc.PARSE_LONG(Server.s_globalDB[DatabaseID.SHEET_EVENT_GLOBAL][10][DatabaseID.EVENT_GLOBAL_BONUS_GOLD_RATE]); LogHelper.LogHappy("Machine id := " + id); LogHelper.LogHappy("Event machine id := " + machine_id); if (id == machine_id || machine_id == -1) { // get reduce percent int reduce_percent = (int)Misc.PARSE_LONG(Server.s_globalDB[DatabaseID.SHEET_EVENT_GLOBAL][10][DatabaseID.EVENT_GLOBAL_BONUS_EXP_RATE]); LogHelper.LogHappy("Reduce time percent := " + reduce_percent); LogHelper.LogHappy("Product time before := " + product_time); int time_bonus = (getProductCompleteTime(product_id) * reduce_percent / 100); product_time -= time_bonus; LogHelper.LogHappy("Product time after := " + product_time); } } SlotMachine _slot_machine = new SlotMachine(product_id, product_time); if (_slot_machine.isLoadSuccess() == false) { load_result = false; LogHelper.Log("Can not add product!!!"); return; } slot.add(_slot_machine); } public void addProductToStock(int product_id) { try { FBEncrypt prod = new FBEncrypt(); prod.addByte(KeyID.KEY_STOCK_PRODUCT_INDEX, this.product_count); prod.addByte(KeyID.KEY_STOCK_PRODUCT_ID, product_id); // need re-check how to calc exp for product (before start product or when product complete) long exp = Misc.PARSE_LONG(Server.s_globalDB[DatabaseID.SHEET_PRODUCT][product_id][DatabaseID.PRODUCT_EXP_RECEIVE]); // byte exp_bonus = Byte.parseByte(Misc.PARSE_STRING(Server.s_globalDB[DatabaseID.SHEET_MACHINE_UNLOCK][this.id][getLevel()]).split(":")[DatabaseID.MACHINE_EXP_BONUS]); byte exp_bonus = (byte)Server.s_globalMachineUnlockData[this.floor][this.level][DatabaseID.MACHINE_EXP_BONUS]; long exp_receive = exp + (exp * exp_bonus / 100); prod.addLong(KeyID.KEY_STOCK_PRODUCT_EXP, exp_receive); this.product_count += 1; stock.add(prod.toByteArray()); } catch (Exception e) { LogHelper.LogException("Machine.addProductToStock", e); } } public boolean removeFirstProductInStock() { if (stock.size() <= 0 || this.product_count <= 0) { LogHelper.Log("Stock is empty. Server need check!!!"); return false; } stock.remove(0); setProductCount(this.product_count - 1); return true; } public int removeFirstDropItem() { int item_id = -1; int item_type = -1; try { if (item_drop_list != null) { if (item_drop_list.size() <= 0) { // LogHelper.Log("item_drop_list is empty. Server need check!!!"); return -1; } item_type = Integer.parseInt(item_drop_list.get(0).split(":")[0]); if (item_type == DatabaseID.IT_EVENT) item_id = -1; else item_id = Integer.parseInt(item_drop_list.get(0).split(":")[1]); item_drop_list.remove(0); } } catch (Exception e) { LogHelper.LogException("Machine.removeFirstDropItem", e); } return item_id; } public String GetFirstDropItem() { StringBuilder sb = new StringBuilder(); int item_id = -1; int item_type = -1; try { if (item_drop_list != null) { if (item_drop_list.size() <= 0) { return ""; } item_type = Integer.parseInt(item_drop_list.get(0).split(":")[0]); item_id = Integer.parseInt(item_drop_list.get(0).split(":")[1]); sb.append(item_type); sb.append(":").append(item_id); item_drop_list.remove(0); return sb.toString(); } } catch (Exception e) { LogHelper.LogException("Machine.removeFirstDropItem", e); } return ""; } public byte getFirstProductIDInstock() { if (stock.size() <= 0) { LogHelper.Log("Stock is empty. Server need check!!!"); return -1; } byte[] prod_data = stock.get(0); if (prod_data == null || prod_data.length == 0) { return -1; } FBEncrypt prod = new FBEncrypt(prod_data); return prod.getByte(KeyID.KEY_STOCK_PRODUCT_ID); } public long getFirstProductExpInstock() { if (stock.size() <= 0) { LogHelper.Log("Stock is empty. Server need check!!!"); return -1; } byte[] prod_data = stock.get(0); if (prod_data == null || prod_data.length == 0) { return -1; } FBEncrypt prod = new FBEncrypt(prod_data); return prod.getLong(KeyID.KEY_STOCK_PRODUCT_EXP); } public byte[] getData() { FBEncrypt machine = new FBEncrypt(); machine.addByte(KeyID.KEY_MACHINE_ID, id); machine.addByte(KeyID.KEY_MACHINE_FLOOR, floor); machine.addShort(KeyID.KEY_MACHINE_LEVEL, level); machine.addInt(KeyID.KEY_MACHINE_ACTIVE_TIME, active_time); machine.addByte(KeyID.KEY_MACHINE_STATUS, status); machine.addInt(KeyID.KEY_MACHINE_START_TIME, start_time); machine.addByte(KeyID.KEY_MACHINE_SLOT_MAX, slot_max); machine.addByte(KeyID.KEY_MACHINE_SLOT_CUR, slot_cur); machine.addByte(KeyID.KEY_MACHINE_PRODUCT_COUNT, product_count); int item_drop_count = item_drop_list.size(); // make sure item_drop_count always <= product_count if (product_count < item_drop_count) item_drop_count = product_count; // LogHelper.Log("machine getData -----------"); StringBuilder sb = new StringBuilder(""); for (int i = 0; i < item_drop_count; i++) { if (i > 0) { sb.append(":"); } String item = item_drop_list.get(i); sb.append(item); // LogHelper.Log(item); } // LogHelper.Log("------ _" + sb.toString() + "_"); machine.addStringANSI(KeyID.KEY_MACHINE_ITEM_DROP_LIST, sb.toString()); // LogHelper.Log("--------------------------"); for (int i = 0; i < slot_cur; i++) { machine.addBinary(KeyID.KEY_MACHINE_SLOT + i, slot.get(i).getData()); } for (int i = 0; i < product_count; i++) { machine.addBinary(KeyID.KEY_MACHINE_PRODUCT + i, stock.get(i)); } machine.addBinary(KeyID.KEY_MACHINE_DECOR, decor.getData(false)); if (LOG_MACHINE) { LogMachine(); } return machine.toByteArray(); } // private String[] toStringArray(ArrayList<String> list) // { // String[] ret = new String[list.size()]; // int i = 0; // for (String e : list) // ret[i++] = e; // return ret; // } public boolean isFull() { return (slot_cur >= slot_max) || (product_count >= (slot_max + DatabaseID.MACHINE_DEFAULT_STOCK_CAPACITY)); } public boolean isLimit() { return (slot_max >= DatabaseID.MACHINE_SLOT_MAX); } public int getTimeMax() { int time = 0; for (int i = 0; i < DatabaseID.MACHINE_SLOT_MAX; i++) { if (slot.get(i).getID() != -1) { time += slot.get(i).getProductTime(); } else { break; } } if (time <= 0) time = Misc.SECONDS(); return time; } public int getFirstSlotTime() { if (slot.size() <= 0) { LogHelper.Log("Slot is empty. Server need check!!!"); return -1; } return slot.get(0).getProductTime(); } public void removeFirstSlot() { if (this.slot_cur > 0) { setSlotCur(this.slot_cur - 1); slot.remove(0); } } public void updateProductListTime(int prod_time) { for (int i = 0; i < this.slot_cur; i++) { slot.get(i).setProductTime(slot.get(i).getProductTime() - prod_time); } } // ------------------------------------------------------------------------------------------------------------------ public byte getSlotCur() { return this.slot_cur; } public void setSlotCur(int slot_cur) { this.slot_cur = (byte)slot_cur; } public byte getSlotMax() { return this.slot_max; } public void setSlotMax(int slot_max) { this.slot_max = (byte)slot_max; } public byte getProductCount() { return this.product_count; } public void setProductCount(int product_count) { this.product_count = (byte)product_count; } public byte getStatus() { return this.status; } public void setStatus(int status) { this.status = (byte)status; } public int getStartTime() { return this.start_time; } public void setStartTime(int start_time) { this.start_time = start_time; } public short getLevel() { return this.level; } public void setLevel(int level) { this.level = (short)level; } public int getActiveTime() { return this.active_time; } public void setActiveTime(int active_time) { // will not increase active time when its already max // String[] value = Misc.PARSE_STRING(Server.s_globalDB[DatabaseID.SHEET_MACHINE_UNLOCK][floor][level+1]).split(":"); // int max_time = Integer.parseInt(value[0]); if (this.level + 1 < Server.s_globalDB[DatabaseID.SHEET_MACHINE_UNLOCK][floor].length) { int max_time = (int)Server.s_globalMachineUnlockData[this.floor][this.level + 1][DatabaseID.MACHINE_ACTIVE_TIME]; if (active_time > max_time) active_time = max_time; } this.active_time = active_time; } public int getProductCompleteTime(int product_id) { return (int)Misc.PARSE_LONG(Server.s_globalDB[DatabaseID.SHEET_PRODUCT][product_id][DatabaseID.PRODUCT_PRODUCTION_TIME]); } public int GetID() { return (int)this.id; } public int getFloor() { return (int)this.floor; } public ArrayList<SlotMachine> getSlot() { return slot; } public void displayDataPackage() { FBEncrypt machine = new FBEncrypt(getData()); LogHelper.Log(""); LogHelper.Log("id: " + machine.getByte(KeyID.KEY_MACHINE_ID)); LogHelper.Log("floor: " + machine.getByte(KeyID.KEY_MACHINE_FLOOR)); LogHelper.Log("level: " + machine.getShort(KeyID.KEY_MACHINE_LEVEL)); LogHelper.Log("active time: " + machine.getInt(KeyID.KEY_MACHINE_ACTIVE_TIME)); LogHelper.Log("status: " + machine.getByte(KeyID.KEY_MACHINE_STATUS)); LogHelper.Log("start time: " + machine.getInt(KeyID.KEY_MACHINE_START_TIME)); LogHelper.Log("slot max: " + machine.getByte(KeyID.KEY_MACHINE_SLOT_MAX)); LogHelper.Log("slot cur: " + machine.getByte(KeyID.KEY_MACHINE_SLOT_CUR)); LogHelper.Log("prod cur: " + machine.getByte(KeyID.KEY_MACHINE_PRODUCT_COUNT)); StringBuilder sb = new StringBuilder(""); for (int i = 0; i < item_drop_list.size(); i++) { if (i > 0) sb.append(":"); sb.append(item_drop_list.get(i)); } // LogHelper.Log("item_drop_list: " + sb.toString()); for (int i = 0; i < machine.getByte(KeyID.KEY_MACHINE_SLOT_CUR); i++) { LogHelper.Log("\nSLOT " + i + ":"); FBEncrypt slot_enc = new FBEncrypt(machine.getBinary(KeyID.KEY_MACHINE_SLOT + i)); slot_enc.displayDataPackage(); } for (int i = 0; i < machine.getByte(KeyID.KEY_MACHINE_PRODUCT_COUNT); i++) { LogHelper.Log("\nPROD " + i + ":"); FBEncrypt prod_enc = new FBEncrypt(machine.getBinary(KeyID.KEY_MACHINE_PRODUCT + i)); prod_enc.displayDataPackage(); } Decor _decor = new Decor(machine.getBinary(KeyID.KEY_MACHINE_DECOR)); _decor.displayDataPackage(); } public void LogMachine() { StringBuilder log = new StringBuilder(); log.append("machine"); log.append('\t').append(this.id); log.append('\t').append(this.floor); log.append('\t').append(this.level); log.append('\t').append(this.active_time); log.append('\t').append(this.status); log.append('\t').append(this.start_time); log.append('\t').append(this.slot_max); log.append('\t').append(this.slot_cur); log.append('\t').append(this.product_count); for (int i = 0; i < slot.size(); i++) { SlotMachine slot_machine = slot.get(i); log.append("\tslot" + i); log.append('\t').append(slot_machine.LogSlotMachine()); } for (int i = 0; i < stock.size(); i++) { FBEncrypt prod = new FBEncrypt(stock.get(i)); log.append("\tproduct" + i); log.append('\t').append(prod.getByte(KeyID.KEY_STOCK_PRODUCT_INDEX)); log.append('\t').append(prod.getByte(KeyID.KEY_STOCK_PRODUCT_ID)); log.append('\t').append(prod.getLong(KeyID.KEY_STOCK_PRODUCT_EXP)); } log.append("\tdecor\t").append(decor.getID()); LogHelper.Log(log.toString()); } public String LogProperties() { StringBuilder log = new StringBuilder(); log.append(this.id); log.append(':').append(this.floor); log.append(':').append(this.level); log.append(':').append(this.active_time); log.append(':').append(this.status); log.append(':').append(this.start_time); log.append(':').append(this.slot_max); log.append(':').append(this.slot_cur); log.append(':').append(this.product_count); return log.toString(); } }
UTF-8
Java
18,083
java
Machine.java
Java
[]
null
[]
package com.vng.skygarden.game; import com.vng.netty.*; import com.vng.util.*; import com.vng.log.*; import com.vng.db.*; import java.util.*; public class Machine { private byte floor; private byte id; private short level; private int active_time; private byte status; private int start_time; private byte slot_max; private byte slot_cur; private byte product_count; private byte product_completed_num; ArrayList<String> item_drop_list; // type:id:num ArrayList<SlotMachine> slot; ArrayList<byte[]> stock; Decor decor = null; private boolean load_result = true; private boolean need_save = false; private boolean LOG_MACHINE = !true; public Machine(int floor) { this.floor = (byte)floor; this.id = Misc.getMachineID(floor); this.level = 0; this.active_time = 0; this.status = DatabaseID.MACHINE_LOCK; this.start_time = -1; this.slot_max = 2; this.slot_cur = 0; this.product_count = 0; product_completed_num = 0; item_drop_list = new ArrayList<String>(); slot = new ArrayList<SlotMachine>(); stock = new ArrayList<byte[]>(); decor = new Decor(); // LogHelper.Log("Init machine OK!"); } public Machine(byte[] machine_bin) { FBEncrypt machine = new FBEncrypt(machine_bin); this.id = machine.getByte(KeyID.KEY_MACHINE_ID); this.floor = machine.getByte(KeyID.KEY_MACHINE_FLOOR); this.level = machine.getShort(KeyID.KEY_MACHINE_LEVEL); this.active_time = machine.getInt(KeyID.KEY_MACHINE_ACTIVE_TIME); this.status = machine.getByte(KeyID.KEY_MACHINE_STATUS); this.start_time = machine.getInt(KeyID.KEY_MACHINE_START_TIME); this.slot_max = machine.getByte(KeyID.KEY_MACHINE_SLOT_MAX); this.slot_cur = machine.getByte(KeyID.KEY_MACHINE_SLOT_CUR); this.product_count = machine.getByte(KeyID.KEY_MACHINE_PRODUCT_COUNT); this.product_completed_num = 0; item_drop_list = new ArrayList<String>(); if (machine.hasKey(KeyID.KEY_MACHINE_ITEM_DROP_LIST)) { String drop_list = machine.getString(KeyID.KEY_MACHINE_ITEM_DROP_LIST); // LogHelper.Log("load machine " + id + ": _" + drop_list + "_"); if(!drop_list.equals("")) { if (drop_list.contains(":18:")) drop_list = drop_list.replace(":18:", ":1:8:"); String[] items = drop_list.split(":"); if (items.length % 3 == 0) { for (int d = 0; d < items.length; d += 3) // type:id:num { item_drop_list.add(items[d] + ":" + items[d+1] + ":" + items[d+2]); } } } } slot = new ArrayList<SlotMachine>(); stock = new ArrayList<byte[]>(); for (int i = 0; i < this.slot_cur; i++) { byte[] slot_data = machine.getBinary(KeyID.KEY_MACHINE_SLOT + i); if (slot_data == null || slot_data.length == 0) { LogHelper.Log("Cannot load product slot " + i); load_result = false; return; } SlotMachine _slot_machine = new SlotMachine(slot_data); if (_slot_machine.isLoadSuccess() == false) { load_result = false; return; } slot.add(_slot_machine); } for (int i = 0; i < this.product_count; i++) { byte[] prod_data = machine.getBinary(KeyID.KEY_MACHINE_PRODUCT + i); if (prod_data == null || prod_data.length == 0) { LogHelper.Log("Cannot load product data " + i); load_result = false; return; } stock.add(prod_data); } // check completed product in slot then move to stock if (this.slot_cur > 0) { while (this.slot_cur > 0 && getFirstSlotTime() < Misc.SECONDS()) { if (slot.size() > 0) { int prod_id = slot.get(0).getID(); removeFirstSlot(); addProductToStock(prod_id); product_completed_num++; need_save = true; } } } //load decor byte[] bdecor = machine.getBinary(KeyID.KEY_MACHINE_DECOR); if (bdecor == null || bdecor.length == 0) { LogHelper.Log("Machine.. can not load decor data."); load_result = false; return; } decor = new Decor(bdecor); if (decor.isLoadSuccess() == false) { load_result = false; return; } // LogHelper.Log("Load machine...OK!"); } public boolean isLoadSuccess() { return load_result; } public boolean isNeedSave() { boolean _need_save = need_save; if (need_save) { need_save = false; } return _need_save; } public byte getProductCompleteNum() { return product_completed_num; } public void resetProductCompleteNum() { product_completed_num = 0; } public void addDropItem(String item) { if (product_count > item_drop_list.size()) // make sure item_drop_count always <= product_count { item_drop_list.add(item); } } public void increaseSlot() { slot_max += 1; } public void addProduct(int product_id) { setSlotCur(slot_cur + 1); int product_time = 0; if (slot.size() > 0) { product_time = slot.get(slot.size() - 1).getProductTime() + getProductCompleteTime(product_id); } else { product_time = Misc.SECONDS() + getProductCompleteTime(product_id); } // byte reduce_time_persent = Byte.parseByte(Misc.PARSE_STRING(Server.s_globalDB[DatabaseID.SHEET_MACHINE_UNLOCK][this.id][getLevel()]).split(":")[DatabaseID.MACHINE_REDUCE_TIME]); byte reduce_time_percent = (byte)Server.s_globalMachineUnlockData[this.floor][this.level][DatabaseID.MACHINE_REDUCE_TIME]; if (reduce_time_percent > 0) { int time_bonus = (getProductCompleteTime(product_id) * reduce_time_percent / 100); product_time -= time_bonus; } String start_event_time = Misc.PARSE_STRING(Server.s_globalDB[DatabaseID.SHEET_EVENT_GLOBAL][10][DatabaseID.EVENT_GLOBAL_START_DATE]); String end_event_time = Misc.PARSE_STRING(Server.s_globalDB[DatabaseID.SHEET_EVENT_GLOBAL][10][DatabaseID.EVENT_GLOBAL_END_DATE]); if(Misc.InEvent(start_event_time, end_event_time)) { // get machine id int machine_id = (int)Misc.PARSE_LONG(Server.s_globalDB[DatabaseID.SHEET_EVENT_GLOBAL][10][DatabaseID.EVENT_GLOBAL_BONUS_GOLD_RATE]); LogHelper.LogHappy("Machine id := " + id); LogHelper.LogHappy("Event machine id := " + machine_id); if (id == machine_id || machine_id == -1) { // get reduce percent int reduce_percent = (int)Misc.PARSE_LONG(Server.s_globalDB[DatabaseID.SHEET_EVENT_GLOBAL][10][DatabaseID.EVENT_GLOBAL_BONUS_EXP_RATE]); LogHelper.LogHappy("Reduce time percent := " + reduce_percent); LogHelper.LogHappy("Product time before := " + product_time); int time_bonus = (getProductCompleteTime(product_id) * reduce_percent / 100); product_time -= time_bonus; LogHelper.LogHappy("Product time after := " + product_time); } } SlotMachine _slot_machine = new SlotMachine(product_id, product_time); if (_slot_machine.isLoadSuccess() == false) { load_result = false; LogHelper.Log("Can not add product!!!"); return; } slot.add(_slot_machine); } public void addProductToStock(int product_id) { try { FBEncrypt prod = new FBEncrypt(); prod.addByte(KeyID.KEY_STOCK_PRODUCT_INDEX, this.product_count); prod.addByte(KeyID.KEY_STOCK_PRODUCT_ID, product_id); // need re-check how to calc exp for product (before start product or when product complete) long exp = Misc.PARSE_LONG(Server.s_globalDB[DatabaseID.SHEET_PRODUCT][product_id][DatabaseID.PRODUCT_EXP_RECEIVE]); // byte exp_bonus = Byte.parseByte(Misc.PARSE_STRING(Server.s_globalDB[DatabaseID.SHEET_MACHINE_UNLOCK][this.id][getLevel()]).split(":")[DatabaseID.MACHINE_EXP_BONUS]); byte exp_bonus = (byte)Server.s_globalMachineUnlockData[this.floor][this.level][DatabaseID.MACHINE_EXP_BONUS]; long exp_receive = exp + (exp * exp_bonus / 100); prod.addLong(KeyID.KEY_STOCK_PRODUCT_EXP, exp_receive); this.product_count += 1; stock.add(prod.toByteArray()); } catch (Exception e) { LogHelper.LogException("Machine.addProductToStock", e); } } public boolean removeFirstProductInStock() { if (stock.size() <= 0 || this.product_count <= 0) { LogHelper.Log("Stock is empty. Server need check!!!"); return false; } stock.remove(0); setProductCount(this.product_count - 1); return true; } public int removeFirstDropItem() { int item_id = -1; int item_type = -1; try { if (item_drop_list != null) { if (item_drop_list.size() <= 0) { // LogHelper.Log("item_drop_list is empty. Server need check!!!"); return -1; } item_type = Integer.parseInt(item_drop_list.get(0).split(":")[0]); if (item_type == DatabaseID.IT_EVENT) item_id = -1; else item_id = Integer.parseInt(item_drop_list.get(0).split(":")[1]); item_drop_list.remove(0); } } catch (Exception e) { LogHelper.LogException("Machine.removeFirstDropItem", e); } return item_id; } public String GetFirstDropItem() { StringBuilder sb = new StringBuilder(); int item_id = -1; int item_type = -1; try { if (item_drop_list != null) { if (item_drop_list.size() <= 0) { return ""; } item_type = Integer.parseInt(item_drop_list.get(0).split(":")[0]); item_id = Integer.parseInt(item_drop_list.get(0).split(":")[1]); sb.append(item_type); sb.append(":").append(item_id); item_drop_list.remove(0); return sb.toString(); } } catch (Exception e) { LogHelper.LogException("Machine.removeFirstDropItem", e); } return ""; } public byte getFirstProductIDInstock() { if (stock.size() <= 0) { LogHelper.Log("Stock is empty. Server need check!!!"); return -1; } byte[] prod_data = stock.get(0); if (prod_data == null || prod_data.length == 0) { return -1; } FBEncrypt prod = new FBEncrypt(prod_data); return prod.getByte(KeyID.KEY_STOCK_PRODUCT_ID); } public long getFirstProductExpInstock() { if (stock.size() <= 0) { LogHelper.Log("Stock is empty. Server need check!!!"); return -1; } byte[] prod_data = stock.get(0); if (prod_data == null || prod_data.length == 0) { return -1; } FBEncrypt prod = new FBEncrypt(prod_data); return prod.getLong(KeyID.KEY_STOCK_PRODUCT_EXP); } public byte[] getData() { FBEncrypt machine = new FBEncrypt(); machine.addByte(KeyID.KEY_MACHINE_ID, id); machine.addByte(KeyID.KEY_MACHINE_FLOOR, floor); machine.addShort(KeyID.KEY_MACHINE_LEVEL, level); machine.addInt(KeyID.KEY_MACHINE_ACTIVE_TIME, active_time); machine.addByte(KeyID.KEY_MACHINE_STATUS, status); machine.addInt(KeyID.KEY_MACHINE_START_TIME, start_time); machine.addByte(KeyID.KEY_MACHINE_SLOT_MAX, slot_max); machine.addByte(KeyID.KEY_MACHINE_SLOT_CUR, slot_cur); machine.addByte(KeyID.KEY_MACHINE_PRODUCT_COUNT, product_count); int item_drop_count = item_drop_list.size(); // make sure item_drop_count always <= product_count if (product_count < item_drop_count) item_drop_count = product_count; // LogHelper.Log("machine getData -----------"); StringBuilder sb = new StringBuilder(""); for (int i = 0; i < item_drop_count; i++) { if (i > 0) { sb.append(":"); } String item = item_drop_list.get(i); sb.append(item); // LogHelper.Log(item); } // LogHelper.Log("------ _" + sb.toString() + "_"); machine.addStringANSI(KeyID.KEY_MACHINE_ITEM_DROP_LIST, sb.toString()); // LogHelper.Log("--------------------------"); for (int i = 0; i < slot_cur; i++) { machine.addBinary(KeyID.KEY_MACHINE_SLOT + i, slot.get(i).getData()); } for (int i = 0; i < product_count; i++) { machine.addBinary(KeyID.KEY_MACHINE_PRODUCT + i, stock.get(i)); } machine.addBinary(KeyID.KEY_MACHINE_DECOR, decor.getData(false)); if (LOG_MACHINE) { LogMachine(); } return machine.toByteArray(); } // private String[] toStringArray(ArrayList<String> list) // { // String[] ret = new String[list.size()]; // int i = 0; // for (String e : list) // ret[i++] = e; // return ret; // } public boolean isFull() { return (slot_cur >= slot_max) || (product_count >= (slot_max + DatabaseID.MACHINE_DEFAULT_STOCK_CAPACITY)); } public boolean isLimit() { return (slot_max >= DatabaseID.MACHINE_SLOT_MAX); } public int getTimeMax() { int time = 0; for (int i = 0; i < DatabaseID.MACHINE_SLOT_MAX; i++) { if (slot.get(i).getID() != -1) { time += slot.get(i).getProductTime(); } else { break; } } if (time <= 0) time = Misc.SECONDS(); return time; } public int getFirstSlotTime() { if (slot.size() <= 0) { LogHelper.Log("Slot is empty. Server need check!!!"); return -1; } return slot.get(0).getProductTime(); } public void removeFirstSlot() { if (this.slot_cur > 0) { setSlotCur(this.slot_cur - 1); slot.remove(0); } } public void updateProductListTime(int prod_time) { for (int i = 0; i < this.slot_cur; i++) { slot.get(i).setProductTime(slot.get(i).getProductTime() - prod_time); } } // ------------------------------------------------------------------------------------------------------------------ public byte getSlotCur() { return this.slot_cur; } public void setSlotCur(int slot_cur) { this.slot_cur = (byte)slot_cur; } public byte getSlotMax() { return this.slot_max; } public void setSlotMax(int slot_max) { this.slot_max = (byte)slot_max; } public byte getProductCount() { return this.product_count; } public void setProductCount(int product_count) { this.product_count = (byte)product_count; } public byte getStatus() { return this.status; } public void setStatus(int status) { this.status = (byte)status; } public int getStartTime() { return this.start_time; } public void setStartTime(int start_time) { this.start_time = start_time; } public short getLevel() { return this.level; } public void setLevel(int level) { this.level = (short)level; } public int getActiveTime() { return this.active_time; } public void setActiveTime(int active_time) { // will not increase active time when its already max // String[] value = Misc.PARSE_STRING(Server.s_globalDB[DatabaseID.SHEET_MACHINE_UNLOCK][floor][level+1]).split(":"); // int max_time = Integer.parseInt(value[0]); if (this.level + 1 < Server.s_globalDB[DatabaseID.SHEET_MACHINE_UNLOCK][floor].length) { int max_time = (int)Server.s_globalMachineUnlockData[this.floor][this.level + 1][DatabaseID.MACHINE_ACTIVE_TIME]; if (active_time > max_time) active_time = max_time; } this.active_time = active_time; } public int getProductCompleteTime(int product_id) { return (int)Misc.PARSE_LONG(Server.s_globalDB[DatabaseID.SHEET_PRODUCT][product_id][DatabaseID.PRODUCT_PRODUCTION_TIME]); } public int GetID() { return (int)this.id; } public int getFloor() { return (int)this.floor; } public ArrayList<SlotMachine> getSlot() { return slot; } public void displayDataPackage() { FBEncrypt machine = new FBEncrypt(getData()); LogHelper.Log(""); LogHelper.Log("id: " + machine.getByte(KeyID.KEY_MACHINE_ID)); LogHelper.Log("floor: " + machine.getByte(KeyID.KEY_MACHINE_FLOOR)); LogHelper.Log("level: " + machine.getShort(KeyID.KEY_MACHINE_LEVEL)); LogHelper.Log("active time: " + machine.getInt(KeyID.KEY_MACHINE_ACTIVE_TIME)); LogHelper.Log("status: " + machine.getByte(KeyID.KEY_MACHINE_STATUS)); LogHelper.Log("start time: " + machine.getInt(KeyID.KEY_MACHINE_START_TIME)); LogHelper.Log("slot max: " + machine.getByte(KeyID.KEY_MACHINE_SLOT_MAX)); LogHelper.Log("slot cur: " + machine.getByte(KeyID.KEY_MACHINE_SLOT_CUR)); LogHelper.Log("prod cur: " + machine.getByte(KeyID.KEY_MACHINE_PRODUCT_COUNT)); StringBuilder sb = new StringBuilder(""); for (int i = 0; i < item_drop_list.size(); i++) { if (i > 0) sb.append(":"); sb.append(item_drop_list.get(i)); } // LogHelper.Log("item_drop_list: " + sb.toString()); for (int i = 0; i < machine.getByte(KeyID.KEY_MACHINE_SLOT_CUR); i++) { LogHelper.Log("\nSLOT " + i + ":"); FBEncrypt slot_enc = new FBEncrypt(machine.getBinary(KeyID.KEY_MACHINE_SLOT + i)); slot_enc.displayDataPackage(); } for (int i = 0; i < machine.getByte(KeyID.KEY_MACHINE_PRODUCT_COUNT); i++) { LogHelper.Log("\nPROD " + i + ":"); FBEncrypt prod_enc = new FBEncrypt(machine.getBinary(KeyID.KEY_MACHINE_PRODUCT + i)); prod_enc.displayDataPackage(); } Decor _decor = new Decor(machine.getBinary(KeyID.KEY_MACHINE_DECOR)); _decor.displayDataPackage(); } public void LogMachine() { StringBuilder log = new StringBuilder(); log.append("machine"); log.append('\t').append(this.id); log.append('\t').append(this.floor); log.append('\t').append(this.level); log.append('\t').append(this.active_time); log.append('\t').append(this.status); log.append('\t').append(this.start_time); log.append('\t').append(this.slot_max); log.append('\t').append(this.slot_cur); log.append('\t').append(this.product_count); for (int i = 0; i < slot.size(); i++) { SlotMachine slot_machine = slot.get(i); log.append("\tslot" + i); log.append('\t').append(slot_machine.LogSlotMachine()); } for (int i = 0; i < stock.size(); i++) { FBEncrypt prod = new FBEncrypt(stock.get(i)); log.append("\tproduct" + i); log.append('\t').append(prod.getByte(KeyID.KEY_STOCK_PRODUCT_INDEX)); log.append('\t').append(prod.getByte(KeyID.KEY_STOCK_PRODUCT_ID)); log.append('\t').append(prod.getLong(KeyID.KEY_STOCK_PRODUCT_EXP)); } log.append("\tdecor\t").append(decor.getID()); LogHelper.Log(log.toString()); } public String LogProperties() { StringBuilder log = new StringBuilder(); log.append(this.id); log.append(':').append(this.floor); log.append(':').append(this.level); log.append(':').append(this.active_time); log.append(':').append(this.status); log.append(':').append(this.start_time); log.append(':').append(this.slot_max); log.append(':').append(this.slot_cur); log.append(':').append(this.product_count); return log.toString(); } }
18,083
0.638721
0.632473
740
23.437838
27.172974
182
false
false
0
0
0
0
0
0
2.463514
false
false
15
d4cdec047de1606b88e1112e6b590b2506bbf21c
34,351,148,472,458
dfd7e70936b123ee98e8a2d34ef41e4260ec3ade
/analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/kr/co/popone/fitts/viewmodel/store/browser/StoreBrowserViewModel$checkProductLink$4.java
7efaf3e06e66a2af08e0467c455e1fbd5d54efd4
[ "Apache-2.0" ]
permissive
skkuse-adv/2019Fall_team2
https://github.com/skkuse-adv/2019Fall_team2
2d4f75bc793368faac4ca8a2916b081ad49b7283
3ea84c6be39855f54634a7f9b1093e80893886eb
refs/heads/master
2020-08-07T03:41:11.447000
2019-12-21T04:06:34
2019-12-21T04:06:34
213,271,174
5
5
Apache-2.0
false
2019-12-12T09:15:32
2019-10-07T01:18:59
2019-12-09T06:55:30
2019-12-12T09:15:32
84,382
3
4
0
Java
false
false
package kr.co.popone.fitts.viewmodel.store.browser; import io.reactivex.functions.Consumer; import kr.co.popone.fitts.model.product.AffiliatesProduct; final class StoreBrowserViewModel$checkProductLink$4<T> implements Consumer<AffiliatesProduct> { final /* synthetic */ StoreBrowserViewModel this$0; StoreBrowserViewModel$checkProductLink$4(StoreBrowserViewModel storeBrowserViewModel) { this.this$0 = storeBrowserViewModel; } public final void accept(AffiliatesProduct affiliatesProduct) { this.this$0.isProductSubject.onNext(affiliatesProduct); this.this$0.isPartnerSubject.onNext(Boolean.valueOf(affiliatesProduct.isProduct())); } }
UTF-8
Java
701
java
StoreBrowserViewModel$checkProductLink$4.java
Java
[]
null
[]
package kr.co.popone.fitts.viewmodel.store.browser; import io.reactivex.functions.Consumer; import kr.co.popone.fitts.model.product.AffiliatesProduct; final class StoreBrowserViewModel$checkProductLink$4<T> implements Consumer<AffiliatesProduct> { final /* synthetic */ StoreBrowserViewModel this$0; StoreBrowserViewModel$checkProductLink$4(StoreBrowserViewModel storeBrowserViewModel) { this.this$0 = storeBrowserViewModel; } public final void accept(AffiliatesProduct affiliatesProduct) { this.this$0.isProductSubject.onNext(affiliatesProduct); this.this$0.isPartnerSubject.onNext(Boolean.valueOf(affiliatesProduct.isProduct())); } }
701
0.763195
0.754636
17
39.235294
34.934441
96
false
false
0
0
0
0
0
0
0.411765
false
false
15
846aec23eb7746b6bde84f77768bf0800f9577a0
22,187,801,120,396
e8ce774f263ef434f724e5b9d940922c5aa433bc
/src/cellShapes/CellShape.java
4d6cfe14a3a04051e82ad8b57d15ff9274baae2a
[ "MIT" ]
permissive
as577/cell_society
https://github.com/as577/cell_society
e67983229aa260b58e15ed5d4ed3dd4a9f153bfa
0cc66cabf19fba36090b006f7ac1969041618b67
refs/heads/master
2021-01-10T13:57:49.373000
2016-02-14T18:26:06
2016-02-14T18:26:06
51,707,110
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cellShapes; /** * The Cell Shape Super-class in which to extend all shapes from. * @author Aditya Srinivasan, Harry Guo, and Michael Kuryshev */ import cellsociety_team25.SimulationView; import javafx.scene.shape.Shape; public abstract class CellShape { /** * Places and sets the parameters of the shape in the visual grid based on its location. * @param row * @param col * @param myView * @return */ public abstract Shape getShape(int row, int col, SimulationView myView); /** * Get location of the x-coordinate of the shape. * @return x val */ public abstract int getX(); /** * Get location of the y-coordinate of the shape. * @return y val */ public abstract int getY(); }
UTF-8
Java
728
java
CellShape.java
Java
[ { "context": "ass in which to extend all shapes from.\n * @author Aditya Srinivasan, Harry Guo, and Michael Kuryshev\n */\n\nimport cell", "end": 119, "score": 0.9998566508293152, "start": 102, "tag": "NAME", "value": "Aditya Srinivasan" }, { "context": "end all shapes from.\n * @aut...
null
[]
package cellShapes; /** * The Cell Shape Super-class in which to extend all shapes from. * @author <NAME>, <NAME>, and <NAME> */ import cellsociety_team25.SimulationView; import javafx.scene.shape.Shape; public abstract class CellShape { /** * Places and sets the parameters of the shape in the visual grid based on its location. * @param row * @param col * @param myView * @return */ public abstract Shape getShape(int row, int col, SimulationView myView); /** * Get location of the x-coordinate of the shape. * @return x val */ public abstract int getX(); /** * Get location of the y-coordinate of the shape. * @return y val */ public abstract int getY(); }
704
0.692308
0.68956
34
20.411764
23.795845
89
false
false
0
0
0
0
0
0
0.941176
false
false
15
22b1b0b4832cc5fe2427d88d0b6d2f3114f59678
3,229,815,430,650
06154f410c0382908ff074cea60434d4eccdc691
/Test.java
5d319eb66bb1a9334ed775f061262d2668b67d76
[]
no_license
akilynx/ToP4CAS
https://github.com/akilynx/ToP4CAS
e8f8bcecfe533e52ec34fa80974c887d206bc676
77978b12dc2f6cef240d31632281d8dd5b71c6d9
refs/heads/master
2021-01-02T08:47:01.231000
2014-12-16T12:04:11
2014-12-16T12:04:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jp.ac.nagoya_u.is.nakamura.testpackage; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import jp.ac.nagoya_u.is.nakamura.diffpackage.Extractor; import jp.ac.nagoya_u.is.nakamura.diffpackage.LatestData; import jp.ac.nagoya_u.is.nakamura.diffpackage.Result; import jp.ac.nagoya_u.is.nakamura.diffpackage.History; import jp.ac.nagoya_u.is.nakamura.diffpackage.Data; import jp.ac.nagoya_u.is.nakamura.diffpackage.InsertData; import jp.ac.nagoya_u.is.nakamura.diffpackage.DeleteData; import jp.ac.nagoya_u.is.nakamura.diffpackage.LeaveData; import jp.ac.nagoya_u.is.nakamura.diffpackage.RestoreData; import jp.ac.nagoya_u.is.nakamura.diffpackage.Term; public class Test { /** * main * @param args */ public static void main(String[] args) { Extractor extractor = new Extractor(); String article = "テスト記事"; List<History> histories = new ArrayList<>(); int thread = 8; String section = "-"; String text = "以下 、 テスト 記事 本文 。 \n"; for(int i = 0; i < 10; i++){ if(i == 6){ String[] vandalText = {"全消し"}; History history =new History("荒らし", vandalText); histories.add(history); }else{ String editor = "編集者" + i%6; if(i%4==0){ text += "\n "+section+" 節 "+i/4+" \n"; } text += "これは テスト" + i +" です 。 \n"; History history =new History(editor, text.split(" ")); histories.add(history); } } Result result = extractor.extract(article, histories, 0, new ArrayList<Data>(), thread, section, 20, 3, 3, 1, false, true, false); /* ------------------ 入出力の説明 ------------------ >入力 String article // 記事名 List<History> histories // 編集履歴データ int version // 初期版番号。標準は0。前のデータをもとにデータ抽出する場合は変更。(リアルタイム抽出用) List<Data> data // 初期の版データ。要素数0でよい。(リアルタイム抽出用) int thread // スレッド数 String section // 節の区切り(Wikipediaならば "==") int h // 参照する過去の版数を制限する閾値。推奨値は20 int k // シーケンスマッチングにおける最小連続単語数の閾値。推奨値は4 int l // 移動+復元とみなす最小連続単語数の閾値。推奨値は9。r<=l int r // 一が一致する復元とみなす最小連続単語数の閾値。推奨値は1 boolean comment // コメントを出力するかどうか boolean remove // 除去すべきデータ(残存後に同一人物によって削除されたときの残存データ、削除後に同一人物により復元されたときの削除データ)を除去するかどうか boolean self // 復元者=追加者のときに復元データを抽出するかどうか(true: する) >出力: Return String article; // 記事名 TreeMap<Integer, String> editorsData = new TreeMap<>(); // 版番号、編集者 HashMap<String, Integer> frequenciesData = new HashMap<>(); // 編集者、編集回数 List<InsertData> insertsData = new ArrayList<>(); // 追加データ List<DeleteData> deletesData = new ArrayList<>(); // 削除データ List<RestoreData> restoresData = new ArrayList<>(); // 復元データ List<LeaveData> leavesData = new ArrayList<>(); // 残存データ LatestData latestData; // 最終版のデータ HashMap<Integer, HashMap<String, Integer>> removeLeaveData = new HashMap<>(); // 削除すべき残存データ <version, <inserter, count>> HashMap<Integer, HashMap<String, List<String>>> removeDeleteData = new HashMap<>(); // 削除すべき削除データ <version, <inserter, terms>> */ System.out.println("\n■ 記事名:" + result.article); System.out.println("\n■ 編集者一覧"); for(Entry<Integer, String> editorData: result.editorsData.entrySet()){ System.out.println("版"+editorData.getKey()+": "+editorData.getValue()); } System.out.println("\n■ 編集回数一覧"); for(Entry<String, Integer> frequencyData: result.frequenciesData.entrySet()){ System.out.println(frequencyData.getKey()+": "+frequencyData.getValue()+"回"); } System.out.println("\n■ 最終版のデータ"); LatestData latestData = result.latestData; System.out.println("・本文(最終版:"+latestData.version+", 最終編集者:"+latestData.editor+")"); for(Term term: latestData.terms){ System.out.print(term.term); } System.out.println("\n・単語ごとのデータ"); for(Data data: latestData.data){ if(data.state){ //ON状態の単語だけを表示 System.out.print(data.term+"\t| 追加> 版"+data.version+":"+data.inserter+" "); // 単語と追加者 if(!data.leavers.isEmpty()){ System.out.print("| 残存> "); for(Entry<String, Integer> leaver: data.leavers.entrySet()){ System.out.print("版"+leaver.getValue()+":"+leaver.getKey()+" "); // 残存者 } } if(!data.deleters.isEmpty()){ System.out.print("| 削除> "); for(Entry<Integer, String> deleter: data.deleters.entrySet()){ System.out.print("版"+deleter.getKey()+":"+deleter.getValue()+" "); // 削除者 } } if(!data.restorers.isEmpty()){ System.out.print("| 復元> "); for(Entry<Integer, String> restorer: data.restorers.entrySet()){ System.out.print("版"+restorer.getKey()+":"+restorer.getValue()+" "); // 復元者 } } System.out.println(); } } int count = 0; System.out.println("\n■ 追加のデータ"); for(InsertData insertData: result.insertsData){ System.out.println("版"+insertData.version+": "+insertData.editor+" > "+insertData.term); count++; if(count >= 10){ count = 0; System.out.println("...略"); break; } } System.out.println("\n■ 残存のデータ"); for(LeaveData leaveData: result.leavesData){ System.out.println("版"+leaveData.version+": "+leaveData.editor+" > "+leaveData.inserter +" "+ leaveData.count + "単語"); count++; if(count >= 10){ count = 0; System.out.println("...略"); break; } } System.out.println("\n■ 削除のデータ"); for(DeleteData deleteData: result.deletesData){ System.out.println("版"+deleteData.version+": "+deleteData.editor+" > "+deleteData.inserter +" "+deleteData.term); count++; if(count >= 10){ count = 0; System.out.println("...略"); break; } } System.out.println("\n■ 復元のデータ"); for(RestoreData restoreData: result.restoresData){ System.out.println("版"+restoreData.version+": "+restoreData.editor+" > "+restoreData.inserter +" "+restoreData.term); count++; if(count >= 10){ count = 0; System.out.println("...略"); break; } } } }
UTF-8
Java
6,832
java
Test.java
Java
[]
null
[]
package jp.ac.nagoya_u.is.nakamura.testpackage; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import jp.ac.nagoya_u.is.nakamura.diffpackage.Extractor; import jp.ac.nagoya_u.is.nakamura.diffpackage.LatestData; import jp.ac.nagoya_u.is.nakamura.diffpackage.Result; import jp.ac.nagoya_u.is.nakamura.diffpackage.History; import jp.ac.nagoya_u.is.nakamura.diffpackage.Data; import jp.ac.nagoya_u.is.nakamura.diffpackage.InsertData; import jp.ac.nagoya_u.is.nakamura.diffpackage.DeleteData; import jp.ac.nagoya_u.is.nakamura.diffpackage.LeaveData; import jp.ac.nagoya_u.is.nakamura.diffpackage.RestoreData; import jp.ac.nagoya_u.is.nakamura.diffpackage.Term; public class Test { /** * main * @param args */ public static void main(String[] args) { Extractor extractor = new Extractor(); String article = "テスト記事"; List<History> histories = new ArrayList<>(); int thread = 8; String section = "-"; String text = "以下 、 テスト 記事 本文 。 \n"; for(int i = 0; i < 10; i++){ if(i == 6){ String[] vandalText = {"全消し"}; History history =new History("荒らし", vandalText); histories.add(history); }else{ String editor = "編集者" + i%6; if(i%4==0){ text += "\n "+section+" 節 "+i/4+" \n"; } text += "これは テスト" + i +" です 。 \n"; History history =new History(editor, text.split(" ")); histories.add(history); } } Result result = extractor.extract(article, histories, 0, new ArrayList<Data>(), thread, section, 20, 3, 3, 1, false, true, false); /* ------------------ 入出力の説明 ------------------ >入力 String article // 記事名 List<History> histories // 編集履歴データ int version // 初期版番号。標準は0。前のデータをもとにデータ抽出する場合は変更。(リアルタイム抽出用) List<Data> data // 初期の版データ。要素数0でよい。(リアルタイム抽出用) int thread // スレッド数 String section // 節の区切り(Wikipediaならば "==") int h // 参照する過去の版数を制限する閾値。推奨値は20 int k // シーケンスマッチングにおける最小連続単語数の閾値。推奨値は4 int l // 移動+復元とみなす最小連続単語数の閾値。推奨値は9。r<=l int r // 一が一致する復元とみなす最小連続単語数の閾値。推奨値は1 boolean comment // コメントを出力するかどうか boolean remove // 除去すべきデータ(残存後に同一人物によって削除されたときの残存データ、削除後に同一人物により復元されたときの削除データ)を除去するかどうか boolean self // 復元者=追加者のときに復元データを抽出するかどうか(true: する) >出力: Return String article; // 記事名 TreeMap<Integer, String> editorsData = new TreeMap<>(); // 版番号、編集者 HashMap<String, Integer> frequenciesData = new HashMap<>(); // 編集者、編集回数 List<InsertData> insertsData = new ArrayList<>(); // 追加データ List<DeleteData> deletesData = new ArrayList<>(); // 削除データ List<RestoreData> restoresData = new ArrayList<>(); // 復元データ List<LeaveData> leavesData = new ArrayList<>(); // 残存データ LatestData latestData; // 最終版のデータ HashMap<Integer, HashMap<String, Integer>> removeLeaveData = new HashMap<>(); // 削除すべき残存データ <version, <inserter, count>> HashMap<Integer, HashMap<String, List<String>>> removeDeleteData = new HashMap<>(); // 削除すべき削除データ <version, <inserter, terms>> */ System.out.println("\n■ 記事名:" + result.article); System.out.println("\n■ 編集者一覧"); for(Entry<Integer, String> editorData: result.editorsData.entrySet()){ System.out.println("版"+editorData.getKey()+": "+editorData.getValue()); } System.out.println("\n■ 編集回数一覧"); for(Entry<String, Integer> frequencyData: result.frequenciesData.entrySet()){ System.out.println(frequencyData.getKey()+": "+frequencyData.getValue()+"回"); } System.out.println("\n■ 最終版のデータ"); LatestData latestData = result.latestData; System.out.println("・本文(最終版:"+latestData.version+", 最終編集者:"+latestData.editor+")"); for(Term term: latestData.terms){ System.out.print(term.term); } System.out.println("\n・単語ごとのデータ"); for(Data data: latestData.data){ if(data.state){ //ON状態の単語だけを表示 System.out.print(data.term+"\t| 追加> 版"+data.version+":"+data.inserter+" "); // 単語と追加者 if(!data.leavers.isEmpty()){ System.out.print("| 残存> "); for(Entry<String, Integer> leaver: data.leavers.entrySet()){ System.out.print("版"+leaver.getValue()+":"+leaver.getKey()+" "); // 残存者 } } if(!data.deleters.isEmpty()){ System.out.print("| 削除> "); for(Entry<Integer, String> deleter: data.deleters.entrySet()){ System.out.print("版"+deleter.getKey()+":"+deleter.getValue()+" "); // 削除者 } } if(!data.restorers.isEmpty()){ System.out.print("| 復元> "); for(Entry<Integer, String> restorer: data.restorers.entrySet()){ System.out.print("版"+restorer.getKey()+":"+restorer.getValue()+" "); // 復元者 } } System.out.println(); } } int count = 0; System.out.println("\n■ 追加のデータ"); for(InsertData insertData: result.insertsData){ System.out.println("版"+insertData.version+": "+insertData.editor+" > "+insertData.term); count++; if(count >= 10){ count = 0; System.out.println("...略"); break; } } System.out.println("\n■ 残存のデータ"); for(LeaveData leaveData: result.leavesData){ System.out.println("版"+leaveData.version+": "+leaveData.editor+" > "+leaveData.inserter +" "+ leaveData.count + "単語"); count++; if(count >= 10){ count = 0; System.out.println("...略"); break; } } System.out.println("\n■ 削除のデータ"); for(DeleteData deleteData: result.deletesData){ System.out.println("版"+deleteData.version+": "+deleteData.editor+" > "+deleteData.inserter +" "+deleteData.term); count++; if(count >= 10){ count = 0; System.out.println("...略"); break; } } System.out.println("\n■ 復元のデータ"); for(RestoreData restoreData: result.restoresData){ System.out.println("版"+restoreData.version+": "+restoreData.editor+" > "+restoreData.inserter +" "+restoreData.term); count++; if(count >= 10){ count = 0; System.out.println("...略"); break; } } } }
6,832
0.650592
0.644499
174
32.011494
29.201635
132
false
false
0
0
0
0
0
0
3.178161
false
false
15
08abcb39caab191c12d33871766ee0e25f729f32
3,229,815,430,142
ba00a9202d33ff701f7c5dcf21f8aa155ce20c39
/src/fresh/ui/FrmChangpwd.java
3d1031041969b4406faf865d91223fe3903ebca3
[]
no_license
happily4399/SUPER_FRESH
https://github.com/happily4399/SUPER_FRESH
f097f8cccbd7dbf75a9345057427785826897455
ae65c1b5629062f47afee10ac41faf93562ba7ff
refs/heads/master
2022-11-15T16:58:06.359000
2020-07-13T14:38:18
2020-07-13T14:38:18
276,839,713
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fresh.ui; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import fresh.control.UserManager; public class FrmChangpwd extends JDialog implements ActionListener{ private JPanel toolBar = new JPanel(); private JPanel workPane = new JPanel(); private Button btnOk = new Button("确定"); private Button btnCancel = new Button("取消"); private JLabel labelPwdOld = new JLabel("原密码:"); private JLabel labelPwd = new JLabel("新密码:"); private JPasswordField edtPwdOld = new JPasswordField(20); private JPasswordField edtPwd = new JPasswordField(20); public FrmChangpwd(Frame f, String s, boolean b) { super(f,s,b); toolBar.setLayout(new FlowLayout(FlowLayout.RIGHT)); toolBar.add(this.btnOk); toolBar.add(btnCancel); this.getContentPane().add(toolBar, BorderLayout.SOUTH); workPane.add(labelPwdOld); workPane.add(edtPwdOld); workPane.add(labelPwd); workPane.add(edtPwd); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); int width = 300; int height = 150; this.setBounds((d.width - width)/2, (d.height-height)/2, width, height); this.getContentPane().add(workPane, BorderLayout.CENTER); this.setSize(300, 150); this.btnCancel.addActionListener(this); this.btnOk.addActionListener(this); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==this.btnCancel) this.setVisible(false); else if(e.getSource()==this.btnOk){ try { UserManager um = new UserManager(); um.Changpwd(fresh.model.BeanUser.currentloginUser.getUser_Pnum() , new String(edtPwdOld.getPassword()), new String(edtPwd.getPassword()));; this.setVisible(false); } catch (Exception e1) { JOptionPane.showMessageDialog(null,e1.getMessage(), "错误",JOptionPane.ERROR_MESSAGE); return; } } } }
GB18030
Java
2,231
java
FrmChangpwd.java
Java
[]
null
[]
package fresh.ui; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import fresh.control.UserManager; public class FrmChangpwd extends JDialog implements ActionListener{ private JPanel toolBar = new JPanel(); private JPanel workPane = new JPanel(); private Button btnOk = new Button("确定"); private Button btnCancel = new Button("取消"); private JLabel labelPwdOld = new JLabel("原密码:"); private JLabel labelPwd = new JLabel("新密码:"); private JPasswordField edtPwdOld = new JPasswordField(20); private JPasswordField edtPwd = new JPasswordField(20); public FrmChangpwd(Frame f, String s, boolean b) { super(f,s,b); toolBar.setLayout(new FlowLayout(FlowLayout.RIGHT)); toolBar.add(this.btnOk); toolBar.add(btnCancel); this.getContentPane().add(toolBar, BorderLayout.SOUTH); workPane.add(labelPwdOld); workPane.add(edtPwdOld); workPane.add(labelPwd); workPane.add(edtPwd); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); int width = 300; int height = 150; this.setBounds((d.width - width)/2, (d.height-height)/2, width, height); this.getContentPane().add(workPane, BorderLayout.CENTER); this.setSize(300, 150); this.btnCancel.addActionListener(this); this.btnOk.addActionListener(this); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==this.btnCancel) this.setVisible(false); else if(e.getSource()==this.btnOk){ try { UserManager um = new UserManager(); um.Changpwd(fresh.model.BeanUser.currentloginUser.getUser_Pnum() , new String(edtPwdOld.getPassword()), new String(edtPwd.getPassword()));; this.setVisible(false); } catch (Exception e1) { JOptionPane.showMessageDialog(null,e1.getMessage(), "错误",JOptionPane.ERROR_MESSAGE); return; } } } }
2,231
0.744893
0.735815
70
30.471428
20.601471
88
false
false
0
0
0
0
0
0
2.314286
false
false
15
90e3f6b0d7e4b6d76d04e9a3bf2806c8443f903b
30,416,958,416,550
173a7e3c1d4b34193aaee905beceee6e34450e35
/kmzyc-order/kmzyc-order-api/src/main/java/com/pltfm/app/entities/SettmentOperateStatement.java
30beb5a7e5f7216194fda09c76d4400068837665
[]
no_license
jjmnbv/km_dev
https://github.com/jjmnbv/km_dev
d4fc9ee59476248941a2bc99a42d57fe13ca1614
f05f4a61326957decc2fc0b8e06e7b106efc96d4
refs/heads/master
2020-03-31T20:03:47.655000
2017-05-26T10:01:56
2017-05-26T10:01:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pltfm.app.entities; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; /** * 结算单操作流水 * * @author weijl * */ public class SettmentOperateStatement implements Serializable { /** * */ private static final long serialVersionUID = 6036435782253836898L; /** * 结算单流水ID */ private Long statementId; /** * 结算单ID */ private String settmentNo; /** * 操作时间 */ private Date operateTime; /** * 操作人类型 */ private short operatorType; /** * 操作人 */ private String operator; /** * T操作类型 结算状态 */ private short operateType; /** * 操作描述 */ private String remark; @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(operateTime)); sb.append("] "); // 后台用户|前台用户|系统自动 if (1 == operatorType) { sb.append("后台用户 "); sb.append(operator); } else if (2 == operatorType) { sb.append("前台用户 "); sb.append(operator); } else { sb.append("系统自动 "); // sb.append(operator); } sb.append(" "); // /结算状态,1:未确认,2:商家已确认,3:运营已确认,4:财务审核通过,5:财务审核拒绝,5:已结出 switch (operateType) { case 1: sb.append("[生成] : 生成结算单;"); break; case 2: sb.append("[商家确认] : 商家已核对并反馈意见; "); break; case 3: sb.append("[运营确认] : 运营人员已核对并完成差异调整(将计入下期结算); "); break; case 4: sb.append("[财务审核] : 财务审核通过; "); break; case 5: sb.append("[财务审核] : 财务审核拒绝; "); break; case 6: sb.append("[财务结出 ] : 本期结算单处理完毕; "); break; default: break; } return sb.toString(); /** * [2014-05-20 01:00:00] 系统自动 [财务结出] :本期应结金额已经结出到商家账户余额,本期结算单处理完毕; * * [2014-05-20 01:00:00] 后台用户 Accountant [财务审核] :财务审核通过; * * [2014-05-20 01:00:00] 后台用户 Admin [运营确认] :运营人员已核对并完成差异调整(将计入下期结算); * * [2014-05-20 01:00:00] 后台用户 Accountant [财务审核] :财务审核拒绝; * * [2014-05-20 01:00:00] 后台用户 Admin [运营确认] :运营人员已核对并完成差异调整(将计入下期结算); * * [2014-05-20 08:10:00] 前台用户 TestUser [商家确认] :商家已核对并反馈意见; * * [2014-05-20 01:00:00] 系统自动 [生成] :生成结算单; */ } public SettmentOperateStatement() { super(); // TODO Auto-generated constructor stub } public Long getStatementId() { return statementId; } public void setStatementId(Long statementId) { this.statementId = statementId; } public String getSettmentNo() { return settmentNo; } public void setSettmentNo(String settmentNo) { this.settmentNo = settmentNo; } public Date getOperateTime() { return operateTime; } public void setOperateTime(Date operateTime) { this.operateTime = operateTime; } public short getOperatorType() { return operatorType; } public void setOperatorType(short operatorType) { this.operatorType = operatorType; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public short getOperateType() { return operateType; } public void setOperateType(short operateType) { this.operateType = operateType; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
UTF-8
Java
4,310
java
SettmentOperateStatement.java
Java
[ { "context": "ava.util.Date;\r\n\r\n/**\r\n * 结算单操作流水\r\n * \r\n * @author weijl\r\n * \r\n */\r\npublic class SettmentOperateStatement ", "end": 165, "score": 0.9995309710502625, "start": 160, "tag": "USERNAME", "value": "weijl" } ]
null
[]
package com.pltfm.app.entities; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; /** * 结算单操作流水 * * @author weijl * */ public class SettmentOperateStatement implements Serializable { /** * */ private static final long serialVersionUID = 6036435782253836898L; /** * 结算单流水ID */ private Long statementId; /** * 结算单ID */ private String settmentNo; /** * 操作时间 */ private Date operateTime; /** * 操作人类型 */ private short operatorType; /** * 操作人 */ private String operator; /** * T操作类型 结算状态 */ private short operateType; /** * 操作描述 */ private String remark; @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(operateTime)); sb.append("] "); // 后台用户|前台用户|系统自动 if (1 == operatorType) { sb.append("后台用户 "); sb.append(operator); } else if (2 == operatorType) { sb.append("前台用户 "); sb.append(operator); } else { sb.append("系统自动 "); // sb.append(operator); } sb.append(" "); // /结算状态,1:未确认,2:商家已确认,3:运营已确认,4:财务审核通过,5:财务审核拒绝,5:已结出 switch (operateType) { case 1: sb.append("[生成] : 生成结算单;"); break; case 2: sb.append("[商家确认] : 商家已核对并反馈意见; "); break; case 3: sb.append("[运营确认] : 运营人员已核对并完成差异调整(将计入下期结算); "); break; case 4: sb.append("[财务审核] : 财务审核通过; "); break; case 5: sb.append("[财务审核] : 财务审核拒绝; "); break; case 6: sb.append("[财务结出 ] : 本期结算单处理完毕; "); break; default: break; } return sb.toString(); /** * [2014-05-20 01:00:00] 系统自动 [财务结出] :本期应结金额已经结出到商家账户余额,本期结算单处理完毕; * * [2014-05-20 01:00:00] 后台用户 Accountant [财务审核] :财务审核通过; * * [2014-05-20 01:00:00] 后台用户 Admin [运营确认] :运营人员已核对并完成差异调整(将计入下期结算); * * [2014-05-20 01:00:00] 后台用户 Accountant [财务审核] :财务审核拒绝; * * [2014-05-20 01:00:00] 后台用户 Admin [运营确认] :运营人员已核对并完成差异调整(将计入下期结算); * * [2014-05-20 08:10:00] 前台用户 TestUser [商家确认] :商家已核对并反馈意见; * * [2014-05-20 01:00:00] 系统自动 [生成] :生成结算单; */ } public SettmentOperateStatement() { super(); // TODO Auto-generated constructor stub } public Long getStatementId() { return statementId; } public void setStatementId(Long statementId) { this.statementId = statementId; } public String getSettmentNo() { return settmentNo; } public void setSettmentNo(String settmentNo) { this.settmentNo = settmentNo; } public Date getOperateTime() { return operateTime; } public void setOperateTime(Date operateTime) { this.operateTime = operateTime; } public short getOperatorType() { return operatorType; } public void setOperatorType(short operatorType) { this.operatorType = operatorType; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public short getOperateType() { return operateType; } public void setOperateType(short operateType) { this.operateType = operateType; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
4,310
0.562361
0.526053
177
18.38418
18.524967
79
false
false
0
0
0
0
0
0
0.344633
false
false
15
8bf6a8f6236ebda534a4cffff92f6e1c8b0162fc
21,165,598,856,066
3024821986f6a48cf2ef9a2d23587a034a5a2604
/crmbase_fw/src/com/yuchengtech/bcrm/workreport/service/ReportAuthService.java
d9f58590821d4eec8cbfa09347ff863be3456cb2
[]
no_license
huangquanlong/ssm-crud
https://github.com/huangquanlong/ssm-crud
092ed6f93b05013a82e3be8b124317fcc7097ee6
e1151b724744e498feef311b4fd1442ab4cbe71f
refs/heads/master
2021-05-10T21:20:51.451000
2018-01-21T02:56:22
2018-01-21T02:56:22
118,224,732
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yuchengtech.bcrm.workreport.service; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import com.yuchengtech.bcrm.workreport.model.OcrmFSysReportAuth; import com.yuchengtech.bob.common.CommonService; import com.yuchengtech.bob.common.JPABaseDAO; import com.yuchengtech.crm.constance.SystemConstance; @Service public class ReportAuthService extends CommonService{ public ReportAuthService(){ JPABaseDAO<OcrmFSysReportAuth,Long> baseDao = new JPABaseDAO<OcrmFSysReportAuth,Long>(OcrmFSysReportAuth.class); super.setBaseDAO(baseDao); } public String insertOne(String roleCode,String reportCode){ //JPABaseDAO<OcrmFSysReportAuth, Long> cfgbaseDAO = new JPABaseDAO<OcrmFSysReportAuth, Long>(OcrmFSysReportAuth.class); OcrmFSysReportAuth cfg= new OcrmFSysReportAuth(); cfg.setAppId(SystemConstance.LOGIC_SYSTEM_APP_ID); cfg.setRoleCode(roleCode); cfg.setReportCode(reportCode); //cfg.setId(121212l); baseDAO.save(cfg); return "success"; } public String deleteOne(StringBuilder jql){ Map<String, Object> values = new HashMap<String, Object>(); baseDAO.batchExecuteWithNameParam(jql.toString(), values); return "success"; } }
UTF-8
Java
1,267
java
ReportAuthService.java
Java
[]
null
[]
package com.yuchengtech.bcrm.workreport.service; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import com.yuchengtech.bcrm.workreport.model.OcrmFSysReportAuth; import com.yuchengtech.bob.common.CommonService; import com.yuchengtech.bob.common.JPABaseDAO; import com.yuchengtech.crm.constance.SystemConstance; @Service public class ReportAuthService extends CommonService{ public ReportAuthService(){ JPABaseDAO<OcrmFSysReportAuth,Long> baseDao = new JPABaseDAO<OcrmFSysReportAuth,Long>(OcrmFSysReportAuth.class); super.setBaseDAO(baseDao); } public String insertOne(String roleCode,String reportCode){ //JPABaseDAO<OcrmFSysReportAuth, Long> cfgbaseDAO = new JPABaseDAO<OcrmFSysReportAuth, Long>(OcrmFSysReportAuth.class); OcrmFSysReportAuth cfg= new OcrmFSysReportAuth(); cfg.setAppId(SystemConstance.LOGIC_SYSTEM_APP_ID); cfg.setRoleCode(roleCode); cfg.setReportCode(reportCode); //cfg.setId(121212l); baseDAO.save(cfg); return "success"; } public String deleteOne(StringBuilder jql){ Map<String, Object> values = new HashMap<String, Object>(); baseDAO.batchExecuteWithNameParam(jql.toString(), values); return "success"; } }
1,267
0.765588
0.760852
41
28.902439
29.808989
122
false
false
0
0
0
0
0
0
1.634146
false
false
15
95f753ef47c35350885bb974ef8c9d402220ab85
9,483,287,825,331
03ebcc6fa1ca19c6a1a8d8c1ad172e76ac5140e5
/SparkBuilderGeneratorPlugin/src/com/helospark/spark/builder/handlers/codegenerator/component/helper/CamelCaseConverter.java
76b5a0d8e233bfcd44dac6725a3829b6f2b4264a
[ "MIT" ]
permissive
helospark/SparkBuilderGenerator
https://github.com/helospark/SparkBuilderGenerator
d7fb50ceac7f113ccfb6f66fdf4dbfcc78634169
86fe53ad2d55c77a2564b88161defd214852531c
refs/heads/master
2023-08-17T10:23:16.083000
2023-08-06T20:01:00
2023-08-06T20:01:00
69,391,337
35
10
MIT
false
2023-08-06T20:01:01
2016-09-27T19:29:59
2023-02-19T02:33:06
2023-08-06T20:01:00
3,051
35
11
3
Java
false
false
package com.helospark.spark.builder.handlers.codegenerator.component.helper; public class CamelCaseConverter { public String toUpperCamelCase(String variableName) { if (variableName == null || variableName.length() <= 1) { return variableName; } return String.valueOf(Character.toUpperCase(variableName.charAt(0))) + variableName.substring(1); } public String toLowerCamelCase(String variableName) { if (variableName == null || variableName.length() <= 1) { return variableName; } return String.valueOf(Character.toLowerCase(variableName.charAt(0))) + variableName.substring(1); } }
UTF-8
Java
674
java
CamelCaseConverter.java
Java
[]
null
[]
package com.helospark.spark.builder.handlers.codegenerator.component.helper; public class CamelCaseConverter { public String toUpperCamelCase(String variableName) { if (variableName == null || variableName.length() <= 1) { return variableName; } return String.valueOf(Character.toUpperCase(variableName.charAt(0))) + variableName.substring(1); } public String toLowerCamelCase(String variableName) { if (variableName == null || variableName.length() <= 1) { return variableName; } return String.valueOf(Character.toLowerCase(variableName.charAt(0))) + variableName.substring(1); } }
674
0.679525
0.670623
18
36.444443
35.131851
105
false
false
0
0
0
0
0
0
0.5
false
false
15
b1b88421e4a5997ed5259f089369aba63c7fa7b8
27,736,898,819,916
6554aa3c89985325d9f936dbb4eff9f4149668f8
/app/src/main/java/ar/edu/unq/cpi/geography/data/expanded/analyzer/ApiCountryDataAnalyzer.java
c7e7a7a41da83c4adc27ec2db22450513f6c8b99
[]
no_license
obj2-material/geography_android
https://github.com/obj2-material/geography_android
2c575d94ae070ca58a3ee0b81fd6f3a6d9d8758c
307ca2372d295dd8b5d4194fe4f5815fa5d32ef0
refs/heads/master
2021-05-07T04:15:12.532000
2018-05-16T23:16:25
2018-05-28T12:51:58
111,139,527
0
0
null
false
2018-05-28T12:52:00
2017-11-17T18:51:52
2018-05-17T18:15:13
2018-05-28T12:51:59
155
0
0
0
Java
false
null
package ar.edu.unq.cpi.geography.data.expanded.analyzer; import org.json.JSONException; import org.json.JSONObject; import ar.edu.unq.cpi.geography.data.expanded.CountryData; /** * Created by Carlos on 11/11/2017. */ public class ApiCountryDataAnalyzer { private JSONObject rawData; public ApiCountryDataAnalyzer(JSONObject _rawData) { super(); this.rawData = _rawData; } public boolean isOnTarget() throws JSONException { return this.getString("subregion").equals("South America") && !(this.getString("name").contains("Falkland") || this.getString("name").contains("South Georgia") ); } public String getString(String fieldName) throws JSONException { return this.rawData.getString(fieldName); } public CountryData buildCountryData() { try { String code = this.getString("alpha3Code"); // este tiene que estar String spanishName = ""; try { spanishName = this.rawData.getJSONObject("translations").getString("es"); } catch (JSONException e) { // nothing to do } long population = 0; try { population = this.rawData.getLong("population"); } catch (JSONException e) { // nothing to do } long area = 0; try { area = this.rawData.getLong("area"); } catch (JSONException e) { // nothing to do } return new CountryData(code, spanishName, population, area); } catch (JSONException e) { e.printStackTrace(); return null; } } }
UTF-8
Java
1,767
java
ApiCountryDataAnalyzer.java
Java
[ { "context": "aphy.data.expanded.CountryData;\n\n/**\n * Created by Carlos on 11/11/2017.\n */\n\npublic class ApiCountryDataAn", "end": 202, "score": 0.9965968132019043, "start": 196, "tag": "NAME", "value": "Carlos" } ]
null
[]
package ar.edu.unq.cpi.geography.data.expanded.analyzer; import org.json.JSONException; import org.json.JSONObject; import ar.edu.unq.cpi.geography.data.expanded.CountryData; /** * Created by Carlos on 11/11/2017. */ public class ApiCountryDataAnalyzer { private JSONObject rawData; public ApiCountryDataAnalyzer(JSONObject _rawData) { super(); this.rawData = _rawData; } public boolean isOnTarget() throws JSONException { return this.getString("subregion").equals("South America") && !(this.getString("name").contains("Falkland") || this.getString("name").contains("South Georgia") ); } public String getString(String fieldName) throws JSONException { return this.rawData.getString(fieldName); } public CountryData buildCountryData() { try { String code = this.getString("alpha3Code"); // este tiene que estar String spanishName = ""; try { spanishName = this.rawData.getJSONObject("translations").getString("es"); } catch (JSONException e) { // nothing to do } long population = 0; try { population = this.rawData.getLong("population"); } catch (JSONException e) { // nothing to do } long area = 0; try { area = this.rawData.getLong("area"); } catch (JSONException e) { // nothing to do } return new CountryData(code, spanishName, population, area); } catch (JSONException e) { e.printStackTrace(); return null; } } }
1,767
0.557442
0.551217
58
29.465517
24.021696
89
false
false
0
0
0
0
0
0
0.413793
false
false
15
225a2ffe594da3807532278a98a7e69f74a80aeb
32,229,434,613,546
9c003733223894c65aaf1f53f6b6c3fb28b0f0d6
/src/juxtanetwork/Compare.java
fa2b9bbb1e2edc56e59905eb0aeed2f100de3c41
[]
no_license
dkaratasos/Juxta
https://github.com/dkaratasos/Juxta
10a4c1b88c0902b866862bacdf49bc6d1aed2d76
bb7bde52d8ea5296e92946236a58848df8e90b77
refs/heads/master
2021-07-06T20:32:38.832000
2019-04-16T13:10:35
2019-04-16T13:10:35
148,795,781
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package juxtanetwork; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.JTextArea; import javax.swing.tree.DefaultMutableTreeNode; public class Compare { JComboBox<String> BaseNodesCombo; DefaultMutableTreeNode commsTreeModel; String fileSeperator = System.getProperty("file.separator"); private String LogsDirectory = "Data"; // private String timeStampBase = "2018-10-11_16_42_17"; // will be retrieved later // private String timeStampTarget = "2018-10-11_16_42_18"; // will be retrieved later ArrayList<String> TimeStampBase = new ArrayList<String>(); ArrayList<String> TimeStampTarget = new ArrayList<String>(); private ArrayList<String> selectedCommands = new ArrayList<String>(); private ArrayList<String> BaseNodes = new ArrayList<String>(); private ArrayList<String> TargetNodes = new ArrayList<String>(); //============ // Hash Maps to store Hieradically information // <BaseNode,<TargetNode,<CommandName,Command>>> private HashMap<String, HashMap<String, HashMap<String, Command>>> Structure = new HashMap<String, HashMap<String, HashMap<String, Command>>>(); //============ /** * IXGKOAG Compare Constructor * * @param BaseNodesCombo * @param commsTreeModel */ Compare(JComboBox<String> BaseNodesCombo, DefaultMutableTreeNode commsTreeModel) { this.BaseNodesCombo = BaseNodesCombo; this.commsTreeModel = commsTreeModel; } //Update Selected Commands ArrayList void updateSelectedCommands(JList<String> commList) { selectedCommands.clear(); //This item should be selected Last if ((this.BaseNodes.isEmpty()) || (this.TargetNodes.isEmpty())) { commList.clearSelection(); return; } int[] selectedIndex = commList.getSelectedIndices(); for (int i = 0; i < selectedIndex.length; i++) { selectedCommands.add(commList.getModel().getElementAt(selectedIndex[i])); } // System.out.println("Selected Commads : " + selectedCommands); prepareHashStructure(); } //Update BaseNodes ArrayList //Update to return the ArrayList to Mainframe ArrayList<String> updateBaseNodes(JList<String> compList1, ArrayList<String> TimeStampBase) { BaseNodes.clear(); for (int i = 0; i < compList1.getModel().getSize(); i++) { BaseNodes.add(compList1.getModel().getElementAt(i)); } this.TimeStampBase = TimeStampBase; prepareHashStructure(); return findCommonCommands(); } //Update TargetNodes ArrayList //Update to return the ArrayList to Mainframe ArrayList<String> updateTargetNodes(JList<String> compList2, ArrayList<String> TimeStampTarget) { TargetNodes.clear(); for (int i = 0; i < compList2.getModel().getSize(); i++) { TargetNodes.add(compList2.getModel().getElementAt(i)); } this.TimeStampTarget = TimeStampTarget; prepareHashStructure(); return findCommonCommands(); } //method for creating the overall common command list private ArrayList<String> findCommonCommands() { ArrayList<String> baseCommands = new ArrayList(); ArrayList<String> targetCommands = new ArrayList(); ArrayList<String> commands = new ArrayList(); int iBase = 0; // Create Base nodes common commands for (String baseNode : BaseNodes) { commands.clear(); // String basePath = getPath(baseNode, timeStampBase); String basePath = getPath(baseNode, TimeStampBase.get(iBase)); File base = new File(basePath); if (base.listFiles().length == 0) { return commands; } for (File f : base.listFiles()) { int pos = f.getName().lastIndexOf("."); if (pos > 0) { commands.add(f.getName().substring(0, pos)); } else { commands.add(f.getName()); } } baseCommands = compareCommands(baseCommands, commands); iBase++; } int iTarget = 0; // Create Target nodes common commands for (String targetNode : TargetNodes) { commands.clear(); // String targetPath = getPath(targetNode, timeStampTarget); String targetPath = getPath(targetNode, TimeStampTarget.get(iTarget)); File target = new File(targetPath); if (target.listFiles().length == 0) { return commands; } for (File f : target.listFiles()) { int pos = f.getName().lastIndexOf("."); if (pos > 0) { commands.add(f.getName().substring(0, pos)); } else { commands.add(f.getName()); } } targetCommands = compareCommands(targetCommands, commands); iTarget++; } // Return overall common command list return compareCommands(baseCommands, targetCommands); } //method for comparing two Command lists and return the common list private ArrayList<String> compareCommands(ArrayList<String> listOne, ArrayList<String> listTwo) { ArrayList<String> similar = new ArrayList<String>(); similar.clear(); if (listOne.isEmpty()) { if (!listTwo.isEmpty()) { similar.addAll(listTwo); } } else if (listTwo.isEmpty()) { similar.addAll(listOne); } else { listOne.retainAll(listTwo); similar = listOne; } return similar; } //Update timeStampBase String void updateTimeStampBase(JList<String> compList2) { // To be implemented when timestamp selection implemented } //Update timeStampBase String void updateTimeStampTarget(JList<String> compList2) { // To be implemented when timestamp selection implemented } //get Path to Files String getPath(String node, String time) { // check if node name contains / or slash or dash in case of cluster node, to be agreed String[] items = node.split("\\/"); String path = ""; if (items.length > 1) { path = LogsDirectory + fileSeperator + items[0] + fileSeperator + time + fileSeperator + items[1]; } else { path = LogsDirectory + fileSeperator + node + fileSeperator + time + fileSeperator; } return path; } void prepareHashStructure() { //======Check if all data exists, do something.. e.g. popup if (selectedCommands.size() == 0) { return; } if (BaseNodes.size() == 0) { return; } if (TargetNodes.size() == 0) { return; } // if (timeStampBase.equals("")) { if (TimeStampBase.size() == 0) { return; } // if (timeStampTarget.equals("")) { if (TimeStampTarget.size() == 0) { return; } //============================================= //Clear Structure HashMap Structure.clear(); //--- Create Structure HashMap with All needed info to // construct GUI items and Calculate Data int iBase = 0; for (String baseNode : BaseNodes) { // String BasePath = getPath(baseNode, timeStampBase); String BasePath = getPath(baseNode, TimeStampBase.get(iBase)); HashMap<String, HashMap<String, Command>> TargetCommands = new HashMap<String, HashMap<String, Command>>(); int iTarget = 0; for (String targetNode : TargetNodes) { // String TargetPath = getPath(targetNode, timeStampTarget); String TargetPath = getPath(targetNode, TimeStampTarget.get(iTarget)); HashMap<String, Command> Commands = new HashMap<String, Command>(); for (String command : selectedCommands) { String BaseFile = BasePath + fileSeperator + command; String TargetFile = TargetPath + fileSeperator + command; //=== If both Files exist File f1 = new File(BaseFile); File f2 = new File(TargetFile); if ((f1.exists() && f1.isFile()) && (f2.exists() && f2.isFile())) { //create CommandObject and appendit to the targetNode Commands Command CommandObject = new Command(command, f1, f2); // Perform Some Tasks in Command Object Commands.put(command, CommandObject); } } TargetCommands.put(targetNode, Commands); iTarget++; } Structure.put(baseNode, TargetCommands); iBase++; } //Hash prepared do additional Stuff updateBaseNodesCombo(); //updateTargetNodesTree(); } public void updateBaseNodesCombo() { this.BaseNodesCombo.removeAllItems(); for (String key : Structure.keySet()) { this.BaseNodesCombo.addItem(key); } // this.BaseNodesCombo.setSelectedIndex(0); } //public HashMap<String, HashMap<String, HashMap<String, Command>>> getStructure(){ // return Structure; //} public void updateTargetNodesTree(String selectedNode) { if (selectedNode.equals("")) { return; } //Clear tree view Model this.commsTreeModel.removeAllChildren(); // Get the CompareTo Target Nodes Based on User Selection HashMap<String, HashMap<String, Command>> TargetNodes = this.Structure.get(selectedNode); //treeview int currIndex1 = 0; int currIndex2 = 0; DefaultMutableTreeNode[] nodesTreeModel = new DefaultMutableTreeNode[100]; DefaultMutableTreeNode[] commandsTreeModel = new DefaultMutableTreeNode[100]; //For each Node for (String CompareNode : TargetNodes.keySet()) { //Append TargetNode Element nodesTreeModel[currIndex1] = new DefaultMutableTreeNode(CompareNode); this.commsTreeModel.add(nodesTreeModel[currIndex1]); //For each CompareTo Target Node get Commands HashMap<String, Command> TargetCommands = TargetNodes.get(CompareNode); for (String CommandOnNode : TargetCommands.keySet()) { commandsTreeModel[currIndex2] = new DefaultMutableTreeNode(CommandOnNode); nodesTreeModel[currIndex1].add(commandsTreeModel[currIndex2]); currIndex2++; } currIndex1++; } } public void nodeSelected(String base, String target, String comm, JTextArea po1TextArea, JTextArea po2TextArea) { // String test = Structure.get(base).get(target).get(comm).getName(); // System.out.println("command name= "+test); if (comm.isEmpty()) { return; } if (target.isEmpty()) { return; } if (base.isEmpty()) { return; } try { Command comm1 = Structure.get(base).get(target).get(comm); comm1.getPOtexts(); String po1 = comm1.getPrintOut(); String po2 = comm1.getPrintOut2(); po1TextArea.setText(po1); po2TextArea.setText(po2); } catch (Exception e) { System.out.println("No command selected"); } } public String[] nodeSelected(String base, String target, String comm) { // String test = Structure.get(base).get(target).get(comm).getName(); // System.out.println("command name= "+test); String[] pos = new String[2]; if (comm.isEmpty()) { return pos; } if (target.isEmpty()) { return pos; } if (base.isEmpty()) { return pos; } try { Command comm1 = Structure.get(base).get(target).get(comm); // comm1.getPOtexts(); Moved to prepareHashStructure() String po1 = comm1.getPrintOut(); String po2 = comm1.getPrintOut2(); pos[0] = po1; pos[1] = po2; } catch (Exception e) { System.out.println("No command selected"); } return pos; } // CHMA-GGEW-SOVL /** * Method for getting the paths where the command file for both base and * target node is located. * * @param base is the name of the base node * @param target is the name of the target node * @param command is the name of the command that is processed * * @return the paths where the command file for base and target node is * stored */ public String[] getCommandReferences(String base, String target, String command) { Command comm = Structure.get(base).get(target).get(command); String[] paths = new String[2]; paths[0] = comm.getBasePath(); paths[1] = comm.getTargetPath(); return paths; } }
UTF-8
Java
13,753
java
Compare.java
Java
[]
null
[]
package juxtanetwork; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.JTextArea; import javax.swing.tree.DefaultMutableTreeNode; public class Compare { JComboBox<String> BaseNodesCombo; DefaultMutableTreeNode commsTreeModel; String fileSeperator = System.getProperty("file.separator"); private String LogsDirectory = "Data"; // private String timeStampBase = "2018-10-11_16_42_17"; // will be retrieved later // private String timeStampTarget = "2018-10-11_16_42_18"; // will be retrieved later ArrayList<String> TimeStampBase = new ArrayList<String>(); ArrayList<String> TimeStampTarget = new ArrayList<String>(); private ArrayList<String> selectedCommands = new ArrayList<String>(); private ArrayList<String> BaseNodes = new ArrayList<String>(); private ArrayList<String> TargetNodes = new ArrayList<String>(); //============ // Hash Maps to store Hieradically information // <BaseNode,<TargetNode,<CommandName,Command>>> private HashMap<String, HashMap<String, HashMap<String, Command>>> Structure = new HashMap<String, HashMap<String, HashMap<String, Command>>>(); //============ /** * IXGKOAG Compare Constructor * * @param BaseNodesCombo * @param commsTreeModel */ Compare(JComboBox<String> BaseNodesCombo, DefaultMutableTreeNode commsTreeModel) { this.BaseNodesCombo = BaseNodesCombo; this.commsTreeModel = commsTreeModel; } //Update Selected Commands ArrayList void updateSelectedCommands(JList<String> commList) { selectedCommands.clear(); //This item should be selected Last if ((this.BaseNodes.isEmpty()) || (this.TargetNodes.isEmpty())) { commList.clearSelection(); return; } int[] selectedIndex = commList.getSelectedIndices(); for (int i = 0; i < selectedIndex.length; i++) { selectedCommands.add(commList.getModel().getElementAt(selectedIndex[i])); } // System.out.println("Selected Commads : " + selectedCommands); prepareHashStructure(); } //Update BaseNodes ArrayList //Update to return the ArrayList to Mainframe ArrayList<String> updateBaseNodes(JList<String> compList1, ArrayList<String> TimeStampBase) { BaseNodes.clear(); for (int i = 0; i < compList1.getModel().getSize(); i++) { BaseNodes.add(compList1.getModel().getElementAt(i)); } this.TimeStampBase = TimeStampBase; prepareHashStructure(); return findCommonCommands(); } //Update TargetNodes ArrayList //Update to return the ArrayList to Mainframe ArrayList<String> updateTargetNodes(JList<String> compList2, ArrayList<String> TimeStampTarget) { TargetNodes.clear(); for (int i = 0; i < compList2.getModel().getSize(); i++) { TargetNodes.add(compList2.getModel().getElementAt(i)); } this.TimeStampTarget = TimeStampTarget; prepareHashStructure(); return findCommonCommands(); } //method for creating the overall common command list private ArrayList<String> findCommonCommands() { ArrayList<String> baseCommands = new ArrayList(); ArrayList<String> targetCommands = new ArrayList(); ArrayList<String> commands = new ArrayList(); int iBase = 0; // Create Base nodes common commands for (String baseNode : BaseNodes) { commands.clear(); // String basePath = getPath(baseNode, timeStampBase); String basePath = getPath(baseNode, TimeStampBase.get(iBase)); File base = new File(basePath); if (base.listFiles().length == 0) { return commands; } for (File f : base.listFiles()) { int pos = f.getName().lastIndexOf("."); if (pos > 0) { commands.add(f.getName().substring(0, pos)); } else { commands.add(f.getName()); } } baseCommands = compareCommands(baseCommands, commands); iBase++; } int iTarget = 0; // Create Target nodes common commands for (String targetNode : TargetNodes) { commands.clear(); // String targetPath = getPath(targetNode, timeStampTarget); String targetPath = getPath(targetNode, TimeStampTarget.get(iTarget)); File target = new File(targetPath); if (target.listFiles().length == 0) { return commands; } for (File f : target.listFiles()) { int pos = f.getName().lastIndexOf("."); if (pos > 0) { commands.add(f.getName().substring(0, pos)); } else { commands.add(f.getName()); } } targetCommands = compareCommands(targetCommands, commands); iTarget++; } // Return overall common command list return compareCommands(baseCommands, targetCommands); } //method for comparing two Command lists and return the common list private ArrayList<String> compareCommands(ArrayList<String> listOne, ArrayList<String> listTwo) { ArrayList<String> similar = new ArrayList<String>(); similar.clear(); if (listOne.isEmpty()) { if (!listTwo.isEmpty()) { similar.addAll(listTwo); } } else if (listTwo.isEmpty()) { similar.addAll(listOne); } else { listOne.retainAll(listTwo); similar = listOne; } return similar; } //Update timeStampBase String void updateTimeStampBase(JList<String> compList2) { // To be implemented when timestamp selection implemented } //Update timeStampBase String void updateTimeStampTarget(JList<String> compList2) { // To be implemented when timestamp selection implemented } //get Path to Files String getPath(String node, String time) { // check if node name contains / or slash or dash in case of cluster node, to be agreed String[] items = node.split("\\/"); String path = ""; if (items.length > 1) { path = LogsDirectory + fileSeperator + items[0] + fileSeperator + time + fileSeperator + items[1]; } else { path = LogsDirectory + fileSeperator + node + fileSeperator + time + fileSeperator; } return path; } void prepareHashStructure() { //======Check if all data exists, do something.. e.g. popup if (selectedCommands.size() == 0) { return; } if (BaseNodes.size() == 0) { return; } if (TargetNodes.size() == 0) { return; } // if (timeStampBase.equals("")) { if (TimeStampBase.size() == 0) { return; } // if (timeStampTarget.equals("")) { if (TimeStampTarget.size() == 0) { return; } //============================================= //Clear Structure HashMap Structure.clear(); //--- Create Structure HashMap with All needed info to // construct GUI items and Calculate Data int iBase = 0; for (String baseNode : BaseNodes) { // String BasePath = getPath(baseNode, timeStampBase); String BasePath = getPath(baseNode, TimeStampBase.get(iBase)); HashMap<String, HashMap<String, Command>> TargetCommands = new HashMap<String, HashMap<String, Command>>(); int iTarget = 0; for (String targetNode : TargetNodes) { // String TargetPath = getPath(targetNode, timeStampTarget); String TargetPath = getPath(targetNode, TimeStampTarget.get(iTarget)); HashMap<String, Command> Commands = new HashMap<String, Command>(); for (String command : selectedCommands) { String BaseFile = BasePath + fileSeperator + command; String TargetFile = TargetPath + fileSeperator + command; //=== If both Files exist File f1 = new File(BaseFile); File f2 = new File(TargetFile); if ((f1.exists() && f1.isFile()) && (f2.exists() && f2.isFile())) { //create CommandObject and appendit to the targetNode Commands Command CommandObject = new Command(command, f1, f2); // Perform Some Tasks in Command Object Commands.put(command, CommandObject); } } TargetCommands.put(targetNode, Commands); iTarget++; } Structure.put(baseNode, TargetCommands); iBase++; } //Hash prepared do additional Stuff updateBaseNodesCombo(); //updateTargetNodesTree(); } public void updateBaseNodesCombo() { this.BaseNodesCombo.removeAllItems(); for (String key : Structure.keySet()) { this.BaseNodesCombo.addItem(key); } // this.BaseNodesCombo.setSelectedIndex(0); } //public HashMap<String, HashMap<String, HashMap<String, Command>>> getStructure(){ // return Structure; //} public void updateTargetNodesTree(String selectedNode) { if (selectedNode.equals("")) { return; } //Clear tree view Model this.commsTreeModel.removeAllChildren(); // Get the CompareTo Target Nodes Based on User Selection HashMap<String, HashMap<String, Command>> TargetNodes = this.Structure.get(selectedNode); //treeview int currIndex1 = 0; int currIndex2 = 0; DefaultMutableTreeNode[] nodesTreeModel = new DefaultMutableTreeNode[100]; DefaultMutableTreeNode[] commandsTreeModel = new DefaultMutableTreeNode[100]; //For each Node for (String CompareNode : TargetNodes.keySet()) { //Append TargetNode Element nodesTreeModel[currIndex1] = new DefaultMutableTreeNode(CompareNode); this.commsTreeModel.add(nodesTreeModel[currIndex1]); //For each CompareTo Target Node get Commands HashMap<String, Command> TargetCommands = TargetNodes.get(CompareNode); for (String CommandOnNode : TargetCommands.keySet()) { commandsTreeModel[currIndex2] = new DefaultMutableTreeNode(CommandOnNode); nodesTreeModel[currIndex1].add(commandsTreeModel[currIndex2]); currIndex2++; } currIndex1++; } } public void nodeSelected(String base, String target, String comm, JTextArea po1TextArea, JTextArea po2TextArea) { // String test = Structure.get(base).get(target).get(comm).getName(); // System.out.println("command name= "+test); if (comm.isEmpty()) { return; } if (target.isEmpty()) { return; } if (base.isEmpty()) { return; } try { Command comm1 = Structure.get(base).get(target).get(comm); comm1.getPOtexts(); String po1 = comm1.getPrintOut(); String po2 = comm1.getPrintOut2(); po1TextArea.setText(po1); po2TextArea.setText(po2); } catch (Exception e) { System.out.println("No command selected"); } } public String[] nodeSelected(String base, String target, String comm) { // String test = Structure.get(base).get(target).get(comm).getName(); // System.out.println("command name= "+test); String[] pos = new String[2]; if (comm.isEmpty()) { return pos; } if (target.isEmpty()) { return pos; } if (base.isEmpty()) { return pos; } try { Command comm1 = Structure.get(base).get(target).get(comm); // comm1.getPOtexts(); Moved to prepareHashStructure() String po1 = comm1.getPrintOut(); String po2 = comm1.getPrintOut2(); pos[0] = po1; pos[1] = po2; } catch (Exception e) { System.out.println("No command selected"); } return pos; } // CHMA-GGEW-SOVL /** * Method for getting the paths where the command file for both base and * target node is located. * * @param base is the name of the base node * @param target is the name of the target node * @param command is the name of the command that is processed * * @return the paths where the command file for base and target node is * stored */ public String[] getCommandReferences(String base, String target, String command) { Command comm = Structure.get(base).get(target).get(command); String[] paths = new String[2]; paths[0] = comm.getBasePath(); paths[1] = comm.getTargetPath(); return paths; } }
13,753
0.571512
0.563441
364
35.782967
27.207275
148
false
false
0
0
0
0
0
0
0.596154
false
false
15
cd54280f8b2dfbff712e20921d5b2d41e77ed9a6
13,228,499,298,996
a486e1a55142f7d4f97a54890ee7cfec9273f8ba
/Hand-In3/src/PassportController.java
b0e39d0768e6a2e869838b69a6dad4b4693ed7eb
[]
no_license
chavdarhristov/AppliedJavaProgramming
https://github.com/chavdarhristov/AppliedJavaProgramming
53abb54152e1490c4b6e4a8c3207be656bf37cb5
8208bbc73071571ba727a9e7380d54c18ed3269c
refs/heads/master
2020-12-21T08:44:58.837000
2020-01-26T21:18:01
2020-01-26T21:18:01
236,377,381
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class PassportController implements Runnable { private AirportQueue queue; public PassportController(AirportQueue queue) { this.queue = queue; } @Override public void run() { Passenger passenger = null; while(true) { try { passenger = queue.getNextPassenger(); Thread.sleep(2000); } catch(InterruptedException e) { // } System.out.println("Passenger checked with number " + passenger.getPassportNumber()); } } }
UTF-8
Java
520
java
PassportController.java
Java
[]
null
[]
public class PassportController implements Runnable { private AirportQueue queue; public PassportController(AirportQueue queue) { this.queue = queue; } @Override public void run() { Passenger passenger = null; while(true) { try { passenger = queue.getNextPassenger(); Thread.sleep(2000); } catch(InterruptedException e) { // } System.out.println("Passenger checked with number " + passenger.getPassportNumber()); } } }
520
0.615385
0.607692
33
13.69697
19.444536
88
false
false
0
0
0
0
0
0
1.909091
false
false
15
ba5a29ffd271c6d1f4b87cab188f5aa0dce2c691
11,390,253,300,828
ac04c7b60123ebdf2e7a9e163c19f53c107485a3
/app/src/main/java/cc/rome753/demo/onerecycler/OnCreateVHListener.java
b3c1ad06e6fea37b7c14b98915a0436b0ae2c68f
[ "Apache-2.0" ]
permissive
rome753/OneRecyclerView
https://github.com/rome753/OneRecyclerView
d5350241d984226a37de2ee0da30b3e7e0db153e
ce36443cb749edd098c3b1e0a475c5a47a8e5512
refs/heads/master
2021-09-19T10:35:29.415000
2018-07-27T03:35:56
2018-07-27T03:35:56
110,517,504
10
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package cc.rome753.demo.onerecycler; import android.view.ViewGroup; public interface OnCreateVHListener<S extends OneVH>{ /** * 创建ViewHolder * @param parent RecyclerView * @return S extends OneVH */ S onCreateHolder(ViewGroup parent); /** * 根据当前位置或数据判断是否创建S类型的ViewHolder * @param position * @param t * @return */ boolean isCreate(int position, Object t); }
UTF-8
Java
512
java
OnCreateVHListener.java
Java
[ { "context": "package cc.rome753.demo.onerecycler;\n\nimport android.view.ViewGroup;", "end": 18, "score": 0.9897247552871704, "start": 11, "tag": "USERNAME", "value": "rome753" } ]
null
[]
package cc.rome753.demo.onerecycler; import android.view.ViewGroup; public interface OnCreateVHListener<S extends OneVH>{ /** * 创建ViewHolder * @param parent RecyclerView * @return S extends OneVH */ S onCreateHolder(ViewGroup parent); /** * 根据当前位置或数据判断是否创建S类型的ViewHolder * @param position * @param t * @return */ boolean isCreate(int position, Object t); }
512
0.580508
0.574153
20
22.65
16.574905
53
false
false
0
0
0
0
0
0
0.25
false
false
15
5177d508bc7bffacc9620a021a9deee5eae7c18b
21,766,894,285,714
20ea74433a6b00806904435026c04b6d51650ff7
/multipledb/src/test/java/com/labi/multipledb/MultipleDataSourcesProductTests.java
fcfcdf71f765bcc1ee81e2ccc1b3e4260fa99a35
[]
no_license
mlabi/sample
https://github.com/mlabi/sample
c91145c9455c9fed301091dee7842c24cb41906a
b620471f1cafc5a6cbcc0b107c80d077f01fa466
refs/heads/master
2020-12-05T00:06:46.096000
2020-01-05T16:32:46
2020-01-05T16:32:46
231,945,323
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.labi.multipledb; import com.labi.multipledb.customer.model.CustomerModel; import com.labi.multipledb.customer.repo.CustomerRepository; import com.labi.multipledb.product.model.ProductModel; import com.labi.multipledb.product.repo.ProductRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull; @RunWith(SpringRunner.class) @SpringBootTest public class MultipleDataSourcesProductTests { @Autowired private ProductRepository productRepository; @Test @Transactional("productTransactionManager") public void create_check_product() { ProductModel product = new ProductModel("228781","Running Shoes", 20.0); product = productRepository.save(product); System.out.println("Product ID: " + product.getId()); // assertNotNull(productRepository.findById(product.getId())); } }
UTF-8
Java
1,254
java
MultipleDataSourcesProductTests.java
Java
[]
null
[]
package com.labi.multipledb; import com.labi.multipledb.customer.model.CustomerModel; import com.labi.multipledb.customer.repo.CustomerRepository; import com.labi.multipledb.product.model.ProductModel; import com.labi.multipledb.product.repo.ProductRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull; @RunWith(SpringRunner.class) @SpringBootTest public class MultipleDataSourcesProductTests { @Autowired private ProductRepository productRepository; @Test @Transactional("productTransactionManager") public void create_check_product() { ProductModel product = new ProductModel("228781","Running Shoes", 20.0); product = productRepository.save(product); System.out.println("Product ID: " + product.getId()); // assertNotNull(productRepository.findById(product.getId())); } }
1,254
0.793461
0.785486
35
34.828571
25.409206
80
false
false
0
0
0
0
0
0
0.6
false
false
15
d5fc4352b3370bd38b60f0fb4a88d888474ea0be
15,642,270,929,120
df8065f8487f16f90bb58ddabddda75c71159cd0
/src/main/java/com/anis/mongodbboot/service/UsersServices.java
295268ae8a3c2a8570a85f5b2bb1092abc14e42a
[]
no_license
Anis1988/mongo-k8s-docker
https://github.com/Anis1988/mongo-k8s-docker
aa65ad0999ff96f48cfde5ca72eb1f2c660b3962
e3918fb3c520817788bc3a36f7393263d3836409
refs/heads/main
2023-01-28T03:13:08.506000
2020-12-11T16:59:51
2020-12-11T16:59:51
320,632,347
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.anis.mongodbboot.service; import com.anis.mongodbboot.document.Address; import com.anis.mongodbboot.document.Reviews; import com.anis.mongodbboot.document.Users; import com.anis.mongodbboot.repository.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class UsersServices { private final UserRepository userRepository; public List<Users> getThem(){ return (List<Users>) userRepository.findAll(); } public Users getOne(String name){ Users byName = userRepository.findByName(name); if(byName == null) { Users users = new Users("XXXXXXX", "XXXXXXX", 0000000, Arrays.asList(new Reviews("XXXXXXX", 0000000, false)), new Address("XXXXXXX", "XXXXXXX")); users.setId("000000000"); return users; } return byName; } public void remove(String name){ Users name1 = userRepository.findByName(name); userRepository.delete(name1); } public Users add(Users users){ return userRepository.save(users); } public Users update(String name,Users users){ Users byName = userRepository.findByName(name); if(byName !=null){ byName.setAddress(users.getAddress()); byName.setName(users.getName()); byName.setReviews(users.getReviews()); byName.setSalary(users.getSalary()); byName.setTeamName(users.getTeamName()); userRepository.save(byName); return byName; } userRepository.save(users); return users; } public List<Users> getThemByTeamName(String teamName) { List<Users> userList = (List<Users>) userRepository.findAll(); if(teamName.isEmpty()){ return userList; } else { return userList.stream() .filter(users -> users.getTeamName().equals(teamName)) .collect(Collectors.toList()); } } }
UTF-8
Java
2,180
java
UsersServices.java
Java
[]
null
[]
package com.anis.mongodbboot.service; import com.anis.mongodbboot.document.Address; import com.anis.mongodbboot.document.Reviews; import com.anis.mongodbboot.document.Users; import com.anis.mongodbboot.repository.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class UsersServices { private final UserRepository userRepository; public List<Users> getThem(){ return (List<Users>) userRepository.findAll(); } public Users getOne(String name){ Users byName = userRepository.findByName(name); if(byName == null) { Users users = new Users("XXXXXXX", "XXXXXXX", 0000000, Arrays.asList(new Reviews("XXXXXXX", 0000000, false)), new Address("XXXXXXX", "XXXXXXX")); users.setId("000000000"); return users; } return byName; } public void remove(String name){ Users name1 = userRepository.findByName(name); userRepository.delete(name1); } public Users add(Users users){ return userRepository.save(users); } public Users update(String name,Users users){ Users byName = userRepository.findByName(name); if(byName !=null){ byName.setAddress(users.getAddress()); byName.setName(users.getName()); byName.setReviews(users.getReviews()); byName.setSalary(users.getSalary()); byName.setTeamName(users.getTeamName()); userRepository.save(byName); return byName; } userRepository.save(users); return users; } public List<Users> getThemByTeamName(String teamName) { List<Users> userList = (List<Users>) userRepository.findAll(); if(teamName.isEmpty()){ return userList; } else { return userList.stream() .filter(users -> users.getTeamName().equals(teamName)) .collect(Collectors.toList()); } } }
2,180
0.631193
0.619725
67
31.537313
20.585699
74
false
false
0
0
0
0
0
0
0.61194
false
false
15
cd4ff94c8340cf9654d7844fbc2f4c86dc663acc
1,090,921,730,312
33bb8fa2222254dcf0d52c92e461e85bb251bfb4
/src/game/risk/utils/GameInterface.java
db7c9f010da030ee4daf5a251c69e382e9a2b39b
[]
no_license
tushargupta98/appRiskGame
https://github.com/tushargupta98/appRiskGame
4afdce767adab56b90607bf1bcdce87ca6da058f
affd932a4ddab86c772babcefae4a3ee19464c5c
refs/heads/master
2021-05-01T21:23:41.210000
2018-02-10T02:40:20
2018-02-10T02:40:20
120,976,924
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package game.risk.utils; import java.awt.Color; /** * This Interface contains all the final values used by the Game GUIs. * * @author Tushar Gupta * @version 1.0.0 * @since 12-October-2017 * */ public interface GameInterface { /** * Name of the Game displayed on Frame. */ public final static String FRAME_TITLE = "Risk Game Application"; /** * Frame width */ public final static int FRAME_WIDTH = 1200; /** * Frame Height */ public final static int FRAME_HEIGHT = 700; /** * Label width */ public final static int LABEL_WIDTH = 252; /** * Label height */ public final static int LABEL_HEIGHT = 52; /** * Label Gap */ public final static int LABEL_GAP = 20; /** * Map Directory */ public final static String MAP_DIRECTORY = "Resources/Maps"; /** * Default image directory */ public final static String DEFAULT_IMAGE_FILE_PATH = "Resources/Image/default.bmp"; /** * Maximum number of players can play */ public final static int MAX_NO_OF_PLAYERS = 5; /** * Minimum number of players can play */ public final static int MIN_NO_OF_PLAYERS = 3; /** * Total number of units for each player with total 3 players */ public final static int TOTAL_NO_OF_UNIT_FOR_3_PLAYERS_EACH = 35; /** * Total number of units for each player with total 4 players */ public final static int TOTAL_NO_OF_UNIT_FOR_4_PLAYERS_EACH = 30; /** * Total number of units for each player with total 5 players */ public final static int TOTAL_NO_OF_UNIT_FOR_5_PLAYERS_EACH = 25; /** * Players' different colors */ public final static Color[] COLOR_ARRAY = {Color.BLUE, Color.RED, Color.GREEN, Color.ORANGE, Color.BLACK}; /** * Players' different color names */ public final static String[] COLOR_NAME_ARRAY = {"Blue", "Red", "Green", "Orange", "Black"}; /** * Different risk card names */ public final static String[] RISK_CARD_NAMES = {"Soldier", "Cavalry", "Canon"}; /** * Numbers in different Risk cards */ public final static int[] RISK_CARD_NO_OF_SOLDIER_ON_CARD_ARRAY = {1, 3, 5}; /** * Dice's Six Sides */ public final static String[] DICE_SIDES = {" *", " **", " ***", " ****", " *****", " ******"}; /** * Attacker Won Statement */ public final static String ATTACKER_WON_STATEMENT = "Attacker Won!"; /** * Attacker Lose StatEment */ public final static String ATTACKER_LOSE_STATEMENT = "Attacker Defeated!"; /** * Nobody Won */ public final static String NO_RESULT = "No Result!"; /** * File path for saved files */ public final static String FILE_PATH_SAVED = "Resources/Saved/"; }
UTF-8
Java
2,744
java
GameInterface.java
Java
[ { "context": "final values used by the Game GUIs.\n * \n * @author Tushar Gupta\n * @version 1.0.0\n * @since 12-October-2017\n *\n *", "end": 152, "score": 0.9998475909233093, "start": 140, "tag": "NAME", "value": "Tushar Gupta" } ]
null
[]
package game.risk.utils; import java.awt.Color; /** * This Interface contains all the final values used by the Game GUIs. * * @author <NAME> * @version 1.0.0 * @since 12-October-2017 * */ public interface GameInterface { /** * Name of the Game displayed on Frame. */ public final static String FRAME_TITLE = "Risk Game Application"; /** * Frame width */ public final static int FRAME_WIDTH = 1200; /** * Frame Height */ public final static int FRAME_HEIGHT = 700; /** * Label width */ public final static int LABEL_WIDTH = 252; /** * Label height */ public final static int LABEL_HEIGHT = 52; /** * Label Gap */ public final static int LABEL_GAP = 20; /** * Map Directory */ public final static String MAP_DIRECTORY = "Resources/Maps"; /** * Default image directory */ public final static String DEFAULT_IMAGE_FILE_PATH = "Resources/Image/default.bmp"; /** * Maximum number of players can play */ public final static int MAX_NO_OF_PLAYERS = 5; /** * Minimum number of players can play */ public final static int MIN_NO_OF_PLAYERS = 3; /** * Total number of units for each player with total 3 players */ public final static int TOTAL_NO_OF_UNIT_FOR_3_PLAYERS_EACH = 35; /** * Total number of units for each player with total 4 players */ public final static int TOTAL_NO_OF_UNIT_FOR_4_PLAYERS_EACH = 30; /** * Total number of units for each player with total 5 players */ public final static int TOTAL_NO_OF_UNIT_FOR_5_PLAYERS_EACH = 25; /** * Players' different colors */ public final static Color[] COLOR_ARRAY = {Color.BLUE, Color.RED, Color.GREEN, Color.ORANGE, Color.BLACK}; /** * Players' different color names */ public final static String[] COLOR_NAME_ARRAY = {"Blue", "Red", "Green", "Orange", "Black"}; /** * Different risk card names */ public final static String[] RISK_CARD_NAMES = {"Soldier", "Cavalry", "Canon"}; /** * Numbers in different Risk cards */ public final static int[] RISK_CARD_NO_OF_SOLDIER_ON_CARD_ARRAY = {1, 3, 5}; /** * Dice's Six Sides */ public final static String[] DICE_SIDES = {" *", " **", " ***", " ****", " *****", " ******"}; /** * Attacker Won Statement */ public final static String ATTACKER_WON_STATEMENT = "Attacker Won!"; /** * Attacker Lose StatEment */ public final static String ATTACKER_LOSE_STATEMENT = "Attacker Defeated!"; /** * Nobody Won */ public final static String NO_RESULT = "No Result!"; /** * File path for saved files */ public final static String FILE_PATH_SAVED = "Resources/Saved/"; }
2,738
0.617711
0.603134
126
20.777779
25.130419
94
false
false
0
0
0
0
0
0
0.325397
false
false
15
40153ced35f9fce79bb74035bd466a5fca7471a5
1,546,188,261,031
9fadea6359034e6d4cfeb56bc9a3dd826b59838d
/app/src/main/java/cz/pfservis/hosys/DiskCache.java
63a07aa1a75c343b6bbc3b10b250e034fc8e450f
[ "Apache-2.0" ]
permissive
petrf22/hosys
https://github.com/petrf22/hosys
e67ee0a08d90142e8aefeda004dc3151947b47e7
2d4ce2b29e2dbebad59eb9c8e3b39ca44ca87952
refs/heads/master
2021-10-10T18:36:31.191000
2019-01-14T05:46:11
2019-01-15T10:48:26
111,959,029
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.pfservis.hosys; import android.content.Context; import android.os.Environment; import android.util.Log; import org.apache.commons.io.IOUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import cz.pfservis.hosys.enums.HosysPage; import static android.os.Environment.isExternalStorageRemovable; import static cz.pfservis.hosys.HosysConfig.UTF8; public class DiskCache { public enum FileType {html, css}; public static boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } public static boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } public static File getDiskCacheFile(HosysPage hosysPage, FileType fileType, Context context) { final File cachePath = isExternalStorageWritable() || !isExternalStorageRemovable() ? context.getExternalCacheDir() : context.getCacheDir(); return new File(cachePath, hosysPage.toString() + "." + fileType.toString()); } public static String readCacheData(File cacheFile, Context context) { if (!cacheFile.exists()) { return null; } InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(cacheFile)); return IOUtils.toString(is, HosysConfig.UTF8); } catch (IOException e) { Log.e("Exception", "File read failed: " + e.toString()); return null; } finally { IOUtils.closeQuietly(is); } } public static String readCacheHtmlData(HosysPage hosysPage, Context context) { File cacheFile = getDiskCacheFile(hosysPage, FileType.html, context); return readCacheData(cacheFile, context); } public static String readCacheCssData(HosysPage hosysPage, Context context) { File cacheFile = getDiskCacheFile(hosysPage, FileType.css, context); return readCacheData(cacheFile, context); } public static void writeCacheData(String htmlData, File cacheFile, Context context) { if (cacheFile.exists()) { cacheFile.delete(); } try { OutputStream os = new BufferedOutputStream(new FileOutputStream(cacheFile)); IOUtils.write(htmlData, os, UTF8); IOUtils.closeQuietly(os); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } } public static void writeCacheHtmlData(String fileData, HosysPage hosysPage, Context context) { File cacheFile = getDiskCacheFile(hosysPage, FileType.html, context); writeCacheData(fileData, cacheFile, context); } public static void writeCacheCssData(String fileData, HosysPage hosysPage, Context context) { File cacheFile = getDiskCacheFile(hosysPage, FileType.css, context); writeCacheData(fileData, cacheFile, context); } }
UTF-8
Java
3,449
java
DiskCache.java
Java
[]
null
[]
package cz.pfservis.hosys; import android.content.Context; import android.os.Environment; import android.util.Log; import org.apache.commons.io.IOUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import cz.pfservis.hosys.enums.HosysPage; import static android.os.Environment.isExternalStorageRemovable; import static cz.pfservis.hosys.HosysConfig.UTF8; public class DiskCache { public enum FileType {html, css}; public static boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } public static boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } public static File getDiskCacheFile(HosysPage hosysPage, FileType fileType, Context context) { final File cachePath = isExternalStorageWritable() || !isExternalStorageRemovable() ? context.getExternalCacheDir() : context.getCacheDir(); return new File(cachePath, hosysPage.toString() + "." + fileType.toString()); } public static String readCacheData(File cacheFile, Context context) { if (!cacheFile.exists()) { return null; } InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(cacheFile)); return IOUtils.toString(is, HosysConfig.UTF8); } catch (IOException e) { Log.e("Exception", "File read failed: " + e.toString()); return null; } finally { IOUtils.closeQuietly(is); } } public static String readCacheHtmlData(HosysPage hosysPage, Context context) { File cacheFile = getDiskCacheFile(hosysPage, FileType.html, context); return readCacheData(cacheFile, context); } public static String readCacheCssData(HosysPage hosysPage, Context context) { File cacheFile = getDiskCacheFile(hosysPage, FileType.css, context); return readCacheData(cacheFile, context); } public static void writeCacheData(String htmlData, File cacheFile, Context context) { if (cacheFile.exists()) { cacheFile.delete(); } try { OutputStream os = new BufferedOutputStream(new FileOutputStream(cacheFile)); IOUtils.write(htmlData, os, UTF8); IOUtils.closeQuietly(os); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } } public static void writeCacheHtmlData(String fileData, HosysPage hosysPage, Context context) { File cacheFile = getDiskCacheFile(hosysPage, FileType.html, context); writeCacheData(fileData, cacheFile, context); } public static void writeCacheCssData(String fileData, HosysPage hosysPage, Context context) { File cacheFile = getDiskCacheFile(hosysPage, FileType.css, context); writeCacheData(fileData, cacheFile, context); } }
3,449
0.670629
0.669759
115
29
30.076714
107
false
false
0
0
0
0
0
0
0.704348
false
false
15
7499fc8d9863597cc894dc9451d540bd8d987696
7,103,875,942,640
c571c6c292f82f6d3588fb2440ed6638f3b3ed48
/IDEAProjects/JDBCTest/src/org/jdbc/test2/TestSelect.java
6cfec153be8a9439f9bde2e687d5843f37be9066
[]
no_license
ALEX-YU23/JavaStudyDemo
https://github.com/ALEX-YU23/JavaStudyDemo
53d2cfb1279b94abae0f2e07c87b0abd9f4bd466
68528bc9a3047e2ed8ab8f603f792c57f098d57c
refs/heads/main
2023-06-18T17:57:38.137000
2021-07-17T06:49:35
2021-07-17T06:49:35
372,350,695
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.jdbc.test2; import org.jdbc.test2.utils.JdbcUtils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * @author alex-ycp * @create 2021-06-09 17:29 */ public class TestSelect { public static void main(String[] args) { // 获取连接 Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = JdbcUtils.getConnection(); // 获取执行sql的对象 statement = connection.createStatement(); // SQL语句 String sql = "select * from users"; // 执行SQL语句 获取结果集对象 resultSet = statement.executeQuery(sql); while(resultSet.next()){ System.out.println("id=" + resultSet.getObject("id")); System.out.println("name=" + resultSet.getObject("NAME")); System.out.println("password=" + resultSet.getObject("PASSWORD")); System.out.println("email=" + resultSet.getObject("email")); System.out.println("brith=" + resultSet.getObject("birthday")); System.out.println("=========================="); } } catch (SQLException e) { e.printStackTrace(); } finally { // 关闭连接 JdbcUtils.release(connection,statement,resultSet); } } }
UTF-8
Java
1,480
java
TestSelect.java
Java
[ { "context": "eption;\nimport java.sql.Statement;\n\n/**\n * @author alex-ycp\n * @create 2021-06-09 17:29\n */\npublic class Test", "end": 201, "score": 0.9996897578239441, "start": 193, "tag": "USERNAME", "value": "alex-ycp" } ]
null
[]
package org.jdbc.test2; import org.jdbc.test2.utils.JdbcUtils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * @author alex-ycp * @create 2021-06-09 17:29 */ public class TestSelect { public static void main(String[] args) { // 获取连接 Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = JdbcUtils.getConnection(); // 获取执行sql的对象 statement = connection.createStatement(); // SQL语句 String sql = "select * from users"; // 执行SQL语句 获取结果集对象 resultSet = statement.executeQuery(sql); while(resultSet.next()){ System.out.println("id=" + resultSet.getObject("id")); System.out.println("name=" + resultSet.getObject("NAME")); System.out.println("password=" + resultSet.getObject("PASSWORD")); System.out.println("email=" + resultSet.getObject("email")); System.out.println("brith=" + resultSet.getObject("birthday")); System.out.println("=========================="); } } catch (SQLException e) { e.printStackTrace(); } finally { // 关闭连接 JdbcUtils.release(connection,statement,resultSet); } } }
1,480
0.558989
0.549157
44
31.363636
23.092789
82
false
false
0
0
0
0
0
0
0.522727
false
false
15
a00fb2ca79ae1adee071e99f966ece1b0fb495ee
27,281,632,300,275
8a3bb4e9918ae65509e81e650ff93bd779600368
/web-java/rvt-i/src/main/java/net/foreworld/rvt/mapper/TaskTakeMapper.java
c632095169a88949eb0798a4a1a31fac4a73bab5
[ "MIT" ]
permissive
zswhcb/rvt
https://github.com/zswhcb/rvt
2a1c67057a335d4fffe818adbeced9e712a9d6db
2fa54c6461d0924c4737aae9d498b45d72b33611
refs/heads/master
2021-01-10T01:50:37.968000
2016-03-29T01:59:31
2016-03-29T01:59:31
47,094,575
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.foreworld.rvt.mapper; import java.util.Date; import java.util.List; import net.foreworld.rvt.model.TaskTake; import net.foreworld.rvt.util.MyMapper; /** * * @author huangxin (3203317@qq.com) * @license LGPL (http://www.gnu.org/licenses/lgpl.html) * @copyright FOREWORLD.NET * */ public interface TaskTakeMapper extends MyMapper<TaskTake> { List<TaskTake> findByTaskId(String task_id); List<TaskTake> findByUserId(String user_id, Date create_time); }
UTF-8
Java
473
java
TaskTakeMapper.java
Java
[ { "context": "et.foreworld.rvt.util.MyMapper;\n\n/**\n *\n * @author huangxin (3203317@qq.com)\n * @license LGPL (http://www.gnu", "end": 190, "score": 0.9595234990119934, "start": 182, "tag": "USERNAME", "value": "huangxin" }, { "context": "d.rvt.util.MyMapper;\n\n/**\n *\n * @autho...
null
[]
package net.foreworld.rvt.mapper; import java.util.Date; import java.util.List; import net.foreworld.rvt.model.TaskTake; import net.foreworld.rvt.util.MyMapper; /** * * @author huangxin (<EMAIL>) * @license LGPL (http://www.gnu.org/licenses/lgpl.html) * @copyright FOREWORLD.NET * */ public interface TaskTakeMapper extends MyMapper<TaskTake> { List<TaskTake> findByTaskId(String task_id); List<TaskTake> findByUserId(String user_id, Date create_time); }
466
0.752643
0.737844
20
22.700001
21.970663
63
false
false
0
0
0
0
0
0
0.5
false
false
15
045418a23752ff7e9c4aad187ee77b014d7ffd4a
20,358,145,020,745
0a40bc16c018ac0664b928a48400e7135abf3f79
/DistributedCustomGIPC/src/serversAndClients/ANilsCustomCounterClient.java
0dd1eaf4748eebe8283762826c311ee641b05cad
[]
no_license
npersson001/Distributed-Systems
https://github.com/npersson001/Distributed-Systems
815231138647a78f64f20a90fcbbfa00bdd1893f
1685ccce29dd677be44511bb9f8d49544b0f6904
refs/heads/master
2020-03-25T05:53:10.941000
2018-08-03T21:01:01
2018-08-03T21:01:01
143,470,799
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package serversAndClients; import inputport.datacomm.duplex.object.DuplexObjectInputPortSelector; import inputport.datacomm.duplex.object.explicitreceive.ReceiveReturnMessage; import inputport.rpc.ACachingAbstractRPCProxyInvocationHandler; import inputport.rpc.GIPCLocateRegistry; import inputport.rpc.duplex.DuplexRPCClientInputPort; import inputport.rpc.duplex.DuplexReceivedCallInvokerSelector; import inputport.rpc.duplex.DuplexSentCallCompleterSelector; import inputport.rpc.duplex.SynchronousDuplexReceivedCallInvokerSelector; import main.ANilsCustomDuplexObjectInputPortFactory; import main.ANilsCustomDuplexReceivedCallInvokerFactory; import port.ATracingConnectionListener; import serialization.SerializerSelector; import util.trace.port.rpc.RPCTraceUtility; import java.util.Scanner; import examples.gipc.counter.customization.ACustomDuplexObjectInputPortFactory; import examples.gipc.counter.customization.ACustomDuplexReceivedCallInvokerFactory; import examples.gipc.counter.customization.ACustomSentCallCompleterFactory; import examples.gipc.counter.customization.ACustomSerializerFactory; import examples.gipc.counter.layers.AMultiLayerCounterClient; import examples.mvc.rmi.duplex.DistributedRMICounter; public class ANilsCustomCounterClient extends AMultiLayerCounterClient{ // protected static DuplexRPCClientInputPort duplexRPCClientInputPort; public static void setFactories() { DuplexReceivedCallInvokerSelector.setReceivedCallInvokerFactory( new ANilsCustomDuplexReceivedCallInvokerFactory()); // DuplexReceivedCallInvokerSelector.setReceivedCallInvokerFactory( // new AnAsynchronousCustomDuplexReceivedCallInvokerFactory()); DuplexSentCallCompleterSelector.setDuplexSentCallCompleterFactory( new ACustomSentCallCompleterFactory()); DuplexObjectInputPortSelector.setDuplexInputPortFactory( new ANilsCustomDuplexObjectInputPortFactory()); SerializerSelector.setSerializerFactory(new ACustomSerializerFactory()); } public static void main (String[] args) { // BufferTraceUtility.setTracing(); // RPCTraceUtility.setTracing(); Scanner sc = new Scanner(System.in); System.out.println("What is the name of your client?"); String clientName = sc.nextLine(); setFactories(); init(clientName); setPort(); while(true) { System.out.println("What do you want to send?"); String input = sc.nextLine(); if(input.equals("q")) { break; } duplexRPCClientInputPort.send(input); duplexRPCClientInputPort.receive("Server"); } // sendByteBuffers(); // sendObjects(); // doOperations(); // while (true) { // ReceiveReturnMessage aReceivedMessage = gipcRegistry.getRPCClientPort().receive(); // if (aReceivedMessage == null) { // break; // } // System.out.println("Received message:" + aReceivedMessage ); // } } }
UTF-8
Java
2,903
java
ANilsCustomCounterClient.java
Java
[]
null
[]
package serversAndClients; import inputport.datacomm.duplex.object.DuplexObjectInputPortSelector; import inputport.datacomm.duplex.object.explicitreceive.ReceiveReturnMessage; import inputport.rpc.ACachingAbstractRPCProxyInvocationHandler; import inputport.rpc.GIPCLocateRegistry; import inputport.rpc.duplex.DuplexRPCClientInputPort; import inputport.rpc.duplex.DuplexReceivedCallInvokerSelector; import inputport.rpc.duplex.DuplexSentCallCompleterSelector; import inputport.rpc.duplex.SynchronousDuplexReceivedCallInvokerSelector; import main.ANilsCustomDuplexObjectInputPortFactory; import main.ANilsCustomDuplexReceivedCallInvokerFactory; import port.ATracingConnectionListener; import serialization.SerializerSelector; import util.trace.port.rpc.RPCTraceUtility; import java.util.Scanner; import examples.gipc.counter.customization.ACustomDuplexObjectInputPortFactory; import examples.gipc.counter.customization.ACustomDuplexReceivedCallInvokerFactory; import examples.gipc.counter.customization.ACustomSentCallCompleterFactory; import examples.gipc.counter.customization.ACustomSerializerFactory; import examples.gipc.counter.layers.AMultiLayerCounterClient; import examples.mvc.rmi.duplex.DistributedRMICounter; public class ANilsCustomCounterClient extends AMultiLayerCounterClient{ // protected static DuplexRPCClientInputPort duplexRPCClientInputPort; public static void setFactories() { DuplexReceivedCallInvokerSelector.setReceivedCallInvokerFactory( new ANilsCustomDuplexReceivedCallInvokerFactory()); // DuplexReceivedCallInvokerSelector.setReceivedCallInvokerFactory( // new AnAsynchronousCustomDuplexReceivedCallInvokerFactory()); DuplexSentCallCompleterSelector.setDuplexSentCallCompleterFactory( new ACustomSentCallCompleterFactory()); DuplexObjectInputPortSelector.setDuplexInputPortFactory( new ANilsCustomDuplexObjectInputPortFactory()); SerializerSelector.setSerializerFactory(new ACustomSerializerFactory()); } public static void main (String[] args) { // BufferTraceUtility.setTracing(); // RPCTraceUtility.setTracing(); Scanner sc = new Scanner(System.in); System.out.println("What is the name of your client?"); String clientName = sc.nextLine(); setFactories(); init(clientName); setPort(); while(true) { System.out.println("What do you want to send?"); String input = sc.nextLine(); if(input.equals("q")) { break; } duplexRPCClientInputPort.send(input); duplexRPCClientInputPort.receive("Server"); } // sendByteBuffers(); // sendObjects(); // doOperations(); // while (true) { // ReceiveReturnMessage aReceivedMessage = gipcRegistry.getRPCClientPort().receive(); // if (aReceivedMessage == null) { // break; // } // System.out.println("Received message:" + aReceivedMessage ); // } } }
2,903
0.790217
0.790217
77
35.701298
26.889898
87
false
false
0
0
0
0
0
0
2.077922
false
false
15
52120e62e4aa4275e59acd6b14293e6575eab0e8
7,954,279,501,058
492ff5fb03dd6534f9e208a608c9f1878acec323
/core_java/src/com/nit/cj_multithreading/SubThread.java
aa5dfefebe70927d69f97a7d69dd1d72b779ab5d
[]
no_license
vikash011/core_java_codes
https://github.com/vikash011/core_java_codes
1c0641efce4f9619b1d9dd1688d6ff466c48786b
3718d1ab4e354e448bf133ccebcaca8a3bb0216e
refs/heads/master
2022-12-27T11:04:42.701000
2020-10-01T14:22:06
2020-10-01T14:22:06
299,359,166
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nit.cj_multithreading; public class SubThread extends Thread { int sub = 0; @Override public void run() { for (int i = 50; i >= 0; i--) { sub = sub - i; // sub -=i; System.out.println("The Substraction:" + sub); } } }
UTF-8
Java
269
java
SubThread.java
Java
[]
null
[]
package com.nit.cj_multithreading; public class SubThread extends Thread { int sub = 0; @Override public void run() { for (int i = 50; i >= 0; i--) { sub = sub - i; // sub -=i; System.out.println("The Substraction:" + sub); } } }
269
0.546468
0.531599
18
12.944445
16.115805
49
false
false
0
0
0
0
0
0
1.166667
false
false
15
ee4d6ddf2b1a1a82feb11aadc979543df5414de9
20,916,490,798,661
85df182f6062e16f103e55ce5f1307912abe92f6
/Source/Java/Expressive/src/main/java/com/bijington/expressive/expressions/FunctionExpression.java
4b08ea703f4629bd42eb8e114c67240bcaa509ca
[ "MIT" ]
permissive
denispakizh/expressive
https://github.com/denispakizh/expressive
1700b0360aef68edf0eb0b8d71edfd13856e7f20
8f5c85dda8a88a7eeb580c5c95edac67df80f956
refs/heads/master
2021-08-11T15:49:38.871000
2021-08-10T13:04:14
2021-08-10T13:04:14
235,360,539
0
0
MIT
true
2021-08-10T09:04:47
2020-01-21T14:23:19
2020-01-22T09:21:25
2021-08-10T09:03:15
3,648
0
0
0
C#
false
false
package com.bijington.expressive.expressions; import com.bijington.expressive.exceptions.ExpressiveException; import com.bijington.expressive.functions.IFunction; import java.util.Map; /** * Created by shaun on 30/06/2016. */ public class FunctionExpression implements IExpression { private final IFunction _function; private final String _name; private final IExpression[] _parameters; public FunctionExpression(String name, IFunction function, IExpression[] parameters) { _name = name; _function = function; _parameters = parameters; } @Override public Object evaluate(Map<String, Object> variables) throws ExpressiveException { _function.setVariables(variables); return _function.evaluate(_parameters); } }
UTF-8
Java
794
java
FunctionExpression.java
Java
[ { "context": "unction;\n\nimport java.util.Map;\n\n/**\n * Created by shaun on 30/06/2016.\n */\npublic class FunctionExpressio", "end": 211, "score": 0.980922520160675, "start": 206, "tag": "USERNAME", "value": "shaun" } ]
null
[]
package com.bijington.expressive.expressions; import com.bijington.expressive.exceptions.ExpressiveException; import com.bijington.expressive.functions.IFunction; import java.util.Map; /** * Created by shaun on 30/06/2016. */ public class FunctionExpression implements IExpression { private final IFunction _function; private final String _name; private final IExpression[] _parameters; public FunctionExpression(String name, IFunction function, IExpression[] parameters) { _name = name; _function = function; _parameters = parameters; } @Override public Object evaluate(Map<String, Object> variables) throws ExpressiveException { _function.setVariables(variables); return _function.evaluate(_parameters); } }
794
0.720403
0.710327
29
26.379311
25.823557
88
false
false
0
0
0
0
0
0
0.517241
false
false
15
45c81d698be11b43a1eb3bcd713212dae8ef9ec7
29,892,972,442,654
adbc37db1e24dcbef8f7cc7127319802f8b0826f
/server/src/com/example/udp_server/ServerListenThreadAllJoyn.java
241ac8a79b4d77bc371d3f3446d4e0d28c8dd264
[]
no_license
HangRuan/EffluxGuide
https://github.com/HangRuan/EffluxGuide
ff1d32a4176d6ac1792fad5af5080f355afc7f59
4321cde9947ec729b8a0d39f9138767dd90ee935
refs/heads/master
2016-09-06T15:42:07.710000
2015-04-23T08:20:27
2015-04-23T08:20:27
34,430,706
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.udp_server; import java.net.DatagramSocket; import org.alljoyn.bus.BusAttachment; import org.alljoyn.bus.BusListener; import org.alljoyn.bus.Mutable; import org.alljoyn.bus.SessionOpts; import org.alljoyn.bus.SessionPortListener; import org.alljoyn.bus.Status; import android.content.Context; import android.os.Handler; class ServerListenThreadAllJoyn extends Thread { private DatagramSocket sock = null; private boolean ListenRunning = false; private String buffstr = null; String SERVICE_NAME ;short CONTACT_PORT; SimpleService mSimpleService; BusAttachment mBus; Context context; Handler mhandle; public ServerListenThreadAllJoyn(Context context,Handler mhandle) { this.context=context; this.mhandle=mhandle; } public String getString() { return buffstr; } public void kill() { mBus.unregisterBusObject(mSimpleService); mBus.disconnect(); mBus.release(); mBus=null; } public boolean init(String name,short port) { SERVICE_NAME=name; CONTACT_PORT=port; mSimpleService=new SimpleService(mhandle); return true; } public void run() { org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(context); mBus = new BusAttachment(context.getPackageName(), BusAttachment.RemoteMessage.Receive); mBus.registerBusListener(new BusListener()); Status status = mBus.registerBusObject(mSimpleService, "/SimpleService"); if (status != Status.OK) { return; } status = mBus.connect(); if (status != Status.OK) { return; } Mutable.ShortValue contactPort = new Mutable.ShortValue(CONTACT_PORT); SessionOpts sessionOpts = new SessionOpts(); sessionOpts.traffic = SessionOpts.TRAFFIC_MESSAGES; sessionOpts.isMultipoint = false; sessionOpts.proximity = SessionOpts.PROXIMITY_ANY; sessionOpts.transports = SessionOpts.TRANSPORT_ANY + SessionOpts.TRANSPORT_WFD; status = mBus.bindSessionPort(contactPort, sessionOpts, new SessionPortListener() { @Override public boolean acceptSessionJoiner(short sessionPort, String joiner, SessionOpts sessionOpts) { if (sessionPort == CONTACT_PORT) { return true; } else { return false; } } }); if (status != Status.OK) { return; } /* * request a well-known name from the bus */ int flag = BusAttachment.ALLJOYN_REQUESTNAME_FLAG_REPLACE_EXISTING | BusAttachment.ALLJOYN_REQUESTNAME_FLAG_DO_NOT_QUEUE; status = mBus.requestName(SERVICE_NAME, flag); if (status == Status.OK) { /* * If we successfully obtain a well-known name from the bus * advertise the same well-known name */ status = mBus.advertiseName(SERVICE_NAME, sessionOpts.transports); if (status != Status.OK) { /* * If we are unable to advertise the name, release * the well-known name from the local bus. */ status = mBus.releaseName(SERVICE_NAME); return; } } } }
UTF-8
Java
3,757
java
ServerListenThreadAllJoyn.java
Java
[]
null
[]
package com.example.udp_server; import java.net.DatagramSocket; import org.alljoyn.bus.BusAttachment; import org.alljoyn.bus.BusListener; import org.alljoyn.bus.Mutable; import org.alljoyn.bus.SessionOpts; import org.alljoyn.bus.SessionPortListener; import org.alljoyn.bus.Status; import android.content.Context; import android.os.Handler; class ServerListenThreadAllJoyn extends Thread { private DatagramSocket sock = null; private boolean ListenRunning = false; private String buffstr = null; String SERVICE_NAME ;short CONTACT_PORT; SimpleService mSimpleService; BusAttachment mBus; Context context; Handler mhandle; public ServerListenThreadAllJoyn(Context context,Handler mhandle) { this.context=context; this.mhandle=mhandle; } public String getString() { return buffstr; } public void kill() { mBus.unregisterBusObject(mSimpleService); mBus.disconnect(); mBus.release(); mBus=null; } public boolean init(String name,short port) { SERVICE_NAME=name; CONTACT_PORT=port; mSimpleService=new SimpleService(mhandle); return true; } public void run() { org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(context); mBus = new BusAttachment(context.getPackageName(), BusAttachment.RemoteMessage.Receive); mBus.registerBusListener(new BusListener()); Status status = mBus.registerBusObject(mSimpleService, "/SimpleService"); if (status != Status.OK) { return; } status = mBus.connect(); if (status != Status.OK) { return; } Mutable.ShortValue contactPort = new Mutable.ShortValue(CONTACT_PORT); SessionOpts sessionOpts = new SessionOpts(); sessionOpts.traffic = SessionOpts.TRAFFIC_MESSAGES; sessionOpts.isMultipoint = false; sessionOpts.proximity = SessionOpts.PROXIMITY_ANY; sessionOpts.transports = SessionOpts.TRANSPORT_ANY + SessionOpts.TRANSPORT_WFD; status = mBus.bindSessionPort(contactPort, sessionOpts, new SessionPortListener() { @Override public boolean acceptSessionJoiner(short sessionPort, String joiner, SessionOpts sessionOpts) { if (sessionPort == CONTACT_PORT) { return true; } else { return false; } } }); if (status != Status.OK) { return; } /* * request a well-known name from the bus */ int flag = BusAttachment.ALLJOYN_REQUESTNAME_FLAG_REPLACE_EXISTING | BusAttachment.ALLJOYN_REQUESTNAME_FLAG_DO_NOT_QUEUE; status = mBus.requestName(SERVICE_NAME, flag); if (status == Status.OK) { /* * If we successfully obtain a well-known name from the bus * advertise the same well-known name */ status = mBus.advertiseName(SERVICE_NAME, sessionOpts.transports); if (status != Status.OK) { /* * If we are unable to advertise the name, release * the well-known name from the local bus. */ status = mBus.releaseName(SERVICE_NAME); return; } } } }
3,757
0.554166
0.554166
124
29.306452
26.243641
134
false
false
0
0
0
0
0
0
1.120968
false
false
15
8ec9973710949d6dd23e7e6d40518f6924403dd7
30,004,641,533,184
88f3832185ed92bc3ccf57a93cd8e0d089ca65ac
/Main.java
138cf124619e8e67a299542634c575e5c9192eda
[]
no_license
Christoffer-Nielsen-Cph/Week-3-tasks
https://github.com/Christoffer-Nielsen-Cph/Week-3-tasks
e0884924c278af1b12d04d74758a6968139a6c31
c1e8ba57b2ab3f8616afe16783f1cc5404f263bd
refs/heads/main
2023-08-17T22:50:46.603000
2021-09-30T11:24:19
2021-09-30T11:24:19
412,030,715
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Comparator; import java.util.Locale; import java.util.Scanner; public class Main { static Scanner scan; private static String[] text; private static char[] chars; private static char myChar; private static int timesFound; private static int maxNum; public static void main(String[] args) throws FileNotFoundException { File file = new File("data.txt"); scan = new Scanner(file); String inputFromFile = ""; while (scan.hasNextLine()) // checks if theres more lines in the file { inputFromFile += scan.nextLine(); // adds each line to the inputFromFile string. } text = inputFromFile.split(" "); String lowerCaseInput = inputFromFile.toLowerCase(); chars = lowerCaseInput.toCharArray(); // Creates and array of strings, where each element is a single word from the file. // System.out.println(text.length); // printWordsStartingWith("Ø"); // printWordsOfLength(3); //test dine metoder ved at kalde dem her: // printLongestWord(text); // printFirstHalfOfEachWord(text); printMostFrequentLetter(); printLessFrequentLetter(); } private static void printWordsOfLength(int l) { boolean wordisvalid = true; for (String s : text) { if (s.length() == l) { if (s.contains(",") || s.contains(".")) { wordisvalid = false; } if (wordisvalid) { System.out.println(s); } } } } private static void printWordsStartingWith(String pattern) { for (String s : text) // for each word in text { if (s.startsWith(pattern) || s.startsWith(pattern.toLowerCase())) { System.out.println(s); } } } //skriv dine metoder herunder: private static void printLongestWord(String[] text) { Arrays.sort(text, Comparator.comparing(String::length)); System.out.println(text[text.length - 1]); } private static void printFirstHalfOfEachWord(String[] text) { int beginIndex = 0; int endIndex; for (String s : text) { endIndex = s.length() / 2; System.out.println(s.substring(beginIndex, endIndex)); } } private static void printMostFrequentLetter() { for(int i=1;i<chars.length;i++){ timesFound = 0; for(int j=0;j<chars.length;j++){ if(chars[i] == chars [j]){ timesFound = timesFound + 1; } if(Character.isWhitespace(chars[i])){ timesFound = timesFound -1; } if(timesFound>maxNum){ maxNum = timesFound; myChar = chars[i]; } } } System.out.println("The most frequent letter is: "+myChar+" and it occurs "+maxNum+" times"); } private static void printLessFrequentLetter(){ for(int i=1;i<chars.length;i++){ timesFound = 0; for(int j=0;j<chars.length;j++){ if(chars[i] == chars [j]){ timesFound = timesFound + 1; } if(Character.isWhitespace(chars[i])){ timesFound = timesFound -1; } if(timesFound<maxNum&& maxNum>=1){ maxNum = timesFound; myChar = chars[i]; } } } System.out.println(maxNum); } }
UTF-8
Java
3,842
java
Main.java
Java
[]
null
[]
import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Comparator; import java.util.Locale; import java.util.Scanner; public class Main { static Scanner scan; private static String[] text; private static char[] chars; private static char myChar; private static int timesFound; private static int maxNum; public static void main(String[] args) throws FileNotFoundException { File file = new File("data.txt"); scan = new Scanner(file); String inputFromFile = ""; while (scan.hasNextLine()) // checks if theres more lines in the file { inputFromFile += scan.nextLine(); // adds each line to the inputFromFile string. } text = inputFromFile.split(" "); String lowerCaseInput = inputFromFile.toLowerCase(); chars = lowerCaseInput.toCharArray(); // Creates and array of strings, where each element is a single word from the file. // System.out.println(text.length); // printWordsStartingWith("Ø"); // printWordsOfLength(3); //test dine metoder ved at kalde dem her: // printLongestWord(text); // printFirstHalfOfEachWord(text); printMostFrequentLetter(); printLessFrequentLetter(); } private static void printWordsOfLength(int l) { boolean wordisvalid = true; for (String s : text) { if (s.length() == l) { if (s.contains(",") || s.contains(".")) { wordisvalid = false; } if (wordisvalid) { System.out.println(s); } } } } private static void printWordsStartingWith(String pattern) { for (String s : text) // for each word in text { if (s.startsWith(pattern) || s.startsWith(pattern.toLowerCase())) { System.out.println(s); } } } //skriv dine metoder herunder: private static void printLongestWord(String[] text) { Arrays.sort(text, Comparator.comparing(String::length)); System.out.println(text[text.length - 1]); } private static void printFirstHalfOfEachWord(String[] text) { int beginIndex = 0; int endIndex; for (String s : text) { endIndex = s.length() / 2; System.out.println(s.substring(beginIndex, endIndex)); } } private static void printMostFrequentLetter() { for(int i=1;i<chars.length;i++){ timesFound = 0; for(int j=0;j<chars.length;j++){ if(chars[i] == chars [j]){ timesFound = timesFound + 1; } if(Character.isWhitespace(chars[i])){ timesFound = timesFound -1; } if(timesFound>maxNum){ maxNum = timesFound; myChar = chars[i]; } } } System.out.println("The most frequent letter is: "+myChar+" and it occurs "+maxNum+" times"); } private static void printLessFrequentLetter(){ for(int i=1;i<chars.length;i++){ timesFound = 0; for(int j=0;j<chars.length;j++){ if(chars[i] == chars [j]){ timesFound = timesFound + 1; } if(Character.isWhitespace(chars[i])){ timesFound = timesFound -1; } if(timesFound<maxNum&& maxNum>=1){ maxNum = timesFound; myChar = chars[i]; } } } System.out.println(maxNum); } }
3,842
0.520958
0.517053
134
27.619404
24.072897
112
false
false
0
0
0
0
0
0
0.477612
false
false
15
1e5c634aba6271c16cd09bf776ad6d46686d6370
19,018,115,224,488
1e21f8adf6af9a27d03559a08ca12d7741ceefce
/app/src/main/java/javax/microedition/rms/impl/AndroidRecordStoreManager.java
fd02ada0207ba8908b38c59bf9308427a13b9b70
[ "Apache-2.0" ]
permissive
nikita36078/J2ME-Loader
https://github.com/nikita36078/J2ME-Loader
4d2298347b12b394904c336c7ea4e06cf1b935c3
c265feb3a74496493e6f01970772331d14d3716f
refs/heads/master
2023-08-24T23:01:13.247000
2023-08-16T14:34:46
2023-08-16T14:34:46
91,971,028
1,657
281
Apache-2.0
false
2023-08-16T14:34:47
2017-05-21T16:23:08
2023-08-16T06:31:38
2023-08-16T14:34:46
19,756
1,506
194
155
Java
false
false
/* * MicroEmulator * Copyright (C) 2008 Bartek Teodorczyk <barteo@barteo.net> * Copyright (C) 2017-2018 Nikita Shakarun * <p> * It is licensed under the following two licenses as alternatives: * 1. GNU Lesser General Public License (the "LGPL") version 2.1 or any newer version * 2. Apache License (the "AL") Version 2.0 * <p> * You may not use this file except in compliance with at least one of * the above two licenses. * <p> * You may obtain a copy of the LGPL at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt * <p> * You may obtain a copy of the AL at * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 LGPL or the AL for the specific language governing permissions and * limitations. * * @version $Id$ */ package javax.microedition.rms.impl; import android.util.Log; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.microedition.rms.InvalidRecordIDException; import javax.microedition.rms.RecordStore; import javax.microedition.rms.RecordStoreException; import javax.microedition.rms.RecordStoreNotFoundException; import javax.microedition.shell.AppClassLoader; import javax.microedition.util.ContextHolder; import ru.playsoftware.j2meloader.util.FileUtils; public class AndroidRecordStoreManager implements RecordStoreManager { private static final String TAG = "RecordStore"; private final static String RECORD_STORE_HEADER_SUFFIX = ".rsh"; private final static String RECORD_STORE_RECORD_SUFFIX = ".rsr"; private final static Object NULL_STORE = new Object(); private Map<String, Object> recordStores = null; @Override public String getName() { return "Android record store"; } private synchronized void initializeIfNecessary() { if (recordStores == null) { recordStores = new ConcurrentHashMap<>(); String[] list = new File(AppClassLoader.getDataDir()).list(); if (list != null) { for (String fileName : list) { if (fileName.endsWith(RECORD_STORE_HEADER_SUFFIX)) { recordStores.put(fileName.substring(0, fileName.length() - RECORD_STORE_HEADER_SUFFIX.length()), NULL_STORE); } } } } } @Override public void deleteRecordStore(String recordStoreName) throws RecordStoreException { initializeIfNecessary(); recordStoreName = recordStoreName.replaceAll(FileUtils.ILLEGAL_FILENAME_CHARS, ""); Object value = recordStores.get(recordStoreName); if (value == null) { throw new RecordStoreNotFoundException(recordStoreName); } if (value instanceof RecordStoreImpl && ((RecordStoreImpl) value).isOpen()) { throw new RecordStoreException(); } File dataDir = new File(AppClassLoader.getDataDir()); String prefix = recordStoreName + "."; String[] files = dataDir.list(); if (files != null) { for (String name : files) { int dot = name.indexOf('.', prefix.length() + 1); if ((dot == -1 || dot == name.lastIndexOf('.')) && name.startsWith(prefix)) { //noinspection ResultOfMethodCallIgnored new File(dataDir, name).delete(); } } } recordStores.remove(recordStoreName); Log.d(TAG, "RecordStore " + recordStoreName + " deleted"); } @Override public RecordStore openRecordStore(String recordStoreName, boolean createIfNecessary) throws RecordStoreException { initializeIfNecessary(); recordStoreName = recordStoreName.replaceAll(FileUtils.ILLEGAL_FILENAME_CHARS, ""); Object value = recordStores.get(recordStoreName); if (value instanceof RecordStoreImpl && ((RecordStoreImpl) value).isOpen()) { ((RecordStoreImpl) value).setOpen(); return (RecordStoreImpl) value; } RecordStoreImpl recordStoreImpl; String headerName = getHeaderFileName(recordStoreName); File headerFile = new File(AppClassLoader.getDataDir(), headerName); try (DataInputStream dis = new DataInputStream(new FileInputStream(headerFile))) { recordStoreImpl = new RecordStoreImpl(this); recordStoreImpl.readHeader(dis); recordStoreImpl.setOpen(); } catch (FileNotFoundException e) { if (!createIfNecessary) { throw new RecordStoreNotFoundException(recordStoreName); } recordStoreImpl = new RecordStoreImpl(this, recordStoreName); recordStoreImpl.setOpen(); saveToDisk(recordStoreImpl, -1); } catch (IOException e) { Log.w(TAG, "openRecordStore: broken header " + headerFile, e); recordStoreImpl = new RecordStoreImpl(this, recordStoreName); recordStoreImpl.setOpen(); saveToDisk(recordStoreImpl, -1); } recordStores.put(recordStoreName, recordStoreImpl); synchronized (recordStoreImpl.records) { File dataDir = new File(AppClassLoader.getDataDir()); String prefix = recordStoreName + "."; String[] files = dataDir.list(); if (files != null) { for (String name : files) { if (name.startsWith(prefix) && name.endsWith(RECORD_STORE_RECORD_SUFFIX)) { File file = new File(dataDir, name); try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) { recordStoreImpl.readRecord(dis); } catch (IOException e) { Log.w(TAG, "loadFromDisk: broken record " + file, e); int pLen = prefix.length(); int sLen = RECORD_STORE_RECORD_SUFFIX.length(); int nLen = name.length(); if (pLen + sLen < nLen) { try { int recordId = Integer.parseInt(name.substring(pLen, nLen - sLen)); recordStoreImpl.records.put(recordId, new byte[0]); } catch (NumberFormatException numberFormatException) { Log.w(TAG, "loadFromDisk: ERROR stubbing broken record " + file); } } } } } } } Log.d(TAG, "RecordStore " + recordStoreName + " opened"); return recordStoreImpl; } @Override public String[] listRecordStores() { initializeIfNecessary(); String[] result = recordStores.keySet().toArray(new String[0]); if (result.length > 0) { return result; } else { return null; } } @Override public void deleteRecord(RecordStoreImpl recordStoreImpl, int recordId) throws RecordStoreException { deleteFromDisk(recordStoreImpl, recordId); } @Override public void loadRecord(RecordStoreImpl recordStoreImpl, int recordId) throws RecordStoreException { String recordName = getRecordFileName(recordStoreImpl.getName(), recordId); try (DataInputStream dis = new DataInputStream(ContextHolder.openFileInput(recordName))) { recordStoreImpl.readRecord(dis); } catch (FileNotFoundException e) { throw new InvalidRecordIDException(); } catch (IOException e) { Log.e(TAG, "RecordStore.loadFromDisk: ERROR reading " + recordName, e); } } @Override public void saveRecord(RecordStoreImpl recordStoreImpl, int recordId) throws RecordStoreException { saveToDisk(recordStoreImpl, recordId); } private synchronized void deleteFromDisk(RecordStoreImpl recordStore, int recordId) throws RecordStoreException { String headerName = getHeaderFileName(recordStore.getName()); try (DataOutputStream dos = new DataOutputStream(ContextHolder.openFileOutput(headerName))) { recordStore.writeHeader(dos); } catch (IOException e) { Log.e(TAG, "RecordStore.saveToDisk: ERROR writing object to " + headerName, e); throw new RecordStoreException(e.getMessage()); } ContextHolder.deleteFile(getRecordFileName(recordStore.getName(), recordId)); } /** * @param recordId -1 for storing only header */ private synchronized void saveToDisk(RecordStoreImpl recordStore, int recordId) throws RecordStoreException { String headerName = getHeaderFileName(recordStore.getName()); try (DataOutputStream dos = new DataOutputStream(ContextHolder.openFileOutput(headerName))) { recordStore.writeHeader(dos); } catch (IOException e) { Log.e(TAG, "RecordStore.saveToDisk: ERROR writing object to " + headerName, e); throw new RecordStoreException(e.getMessage()); } if (recordId != -1) { String recordName = getRecordFileName(recordStore.getName(), recordId); try (DataOutputStream dos = new DataOutputStream(ContextHolder.openFileOutput(recordName))) { recordStore.writeRecord(dos, recordId); } catch (IOException e) { Log.e(TAG, "RecordStore.saveToDisk: ERROR writing object to " + recordName, e); throw new RecordStoreException(e.getMessage()); } } } @Override public int getSizeAvailable(RecordStoreImpl recordStoreImpl) { // TODO should return free space on device return 1024 * 1024; } private String getHeaderFileName(String recordStoreName) { return recordStoreName + RECORD_STORE_HEADER_SUFFIX; } private String getRecordFileName(String recordStoreName, int recordId) { return recordStoreName + "." + recordId + RECORD_STORE_RECORD_SUFFIX; } }
UTF-8
Java
9,061
java
AndroidRecordStoreManager.java
Java
[ { "context": "/*\n * MicroEmulator\n * Copyright (C) 2008 Bartek Teodorczyk <barteo@barteo.net>\n * Copyright (C) 2017-2018 Ni", "end": 59, "score": 0.9998522400856018, "start": 42, "tag": "NAME", "value": "Bartek Teodorczyk" }, { "context": "Emulator\n * Copyright (C) 2008 Bartek Te...
null
[]
/* * MicroEmulator * Copyright (C) 2008 <NAME> <<EMAIL>> * Copyright (C) 2017-2018 <NAME> * <p> * It is licensed under the following two licenses as alternatives: * 1. GNU Lesser General Public License (the "LGPL") version 2.1 or any newer version * 2. Apache License (the "AL") Version 2.0 * <p> * You may not use this file except in compliance with at least one of * the above two licenses. * <p> * You may obtain a copy of the LGPL at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt * <p> * You may obtain a copy of the AL at * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 LGPL or the AL for the specific language governing permissions and * limitations. * * @version $Id$ */ package javax.microedition.rms.impl; import android.util.Log; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.microedition.rms.InvalidRecordIDException; import javax.microedition.rms.RecordStore; import javax.microedition.rms.RecordStoreException; import javax.microedition.rms.RecordStoreNotFoundException; import javax.microedition.shell.AppClassLoader; import javax.microedition.util.ContextHolder; import ru.playsoftware.j2meloader.util.FileUtils; public class AndroidRecordStoreManager implements RecordStoreManager { private static final String TAG = "RecordStore"; private final static String RECORD_STORE_HEADER_SUFFIX = ".rsh"; private final static String RECORD_STORE_RECORD_SUFFIX = ".rsr"; private final static Object NULL_STORE = new Object(); private Map<String, Object> recordStores = null; @Override public String getName() { return "Android record store"; } private synchronized void initializeIfNecessary() { if (recordStores == null) { recordStores = new ConcurrentHashMap<>(); String[] list = new File(AppClassLoader.getDataDir()).list(); if (list != null) { for (String fileName : list) { if (fileName.endsWith(RECORD_STORE_HEADER_SUFFIX)) { recordStores.put(fileName.substring(0, fileName.length() - RECORD_STORE_HEADER_SUFFIX.length()), NULL_STORE); } } } } } @Override public void deleteRecordStore(String recordStoreName) throws RecordStoreException { initializeIfNecessary(); recordStoreName = recordStoreName.replaceAll(FileUtils.ILLEGAL_FILENAME_CHARS, ""); Object value = recordStores.get(recordStoreName); if (value == null) { throw new RecordStoreNotFoundException(recordStoreName); } if (value instanceof RecordStoreImpl && ((RecordStoreImpl) value).isOpen()) { throw new RecordStoreException(); } File dataDir = new File(AppClassLoader.getDataDir()); String prefix = recordStoreName + "."; String[] files = dataDir.list(); if (files != null) { for (String name : files) { int dot = name.indexOf('.', prefix.length() + 1); if ((dot == -1 || dot == name.lastIndexOf('.')) && name.startsWith(prefix)) { //noinspection ResultOfMethodCallIgnored new File(dataDir, name).delete(); } } } recordStores.remove(recordStoreName); Log.d(TAG, "RecordStore " + recordStoreName + " deleted"); } @Override public RecordStore openRecordStore(String recordStoreName, boolean createIfNecessary) throws RecordStoreException { initializeIfNecessary(); recordStoreName = recordStoreName.replaceAll(FileUtils.ILLEGAL_FILENAME_CHARS, ""); Object value = recordStores.get(recordStoreName); if (value instanceof RecordStoreImpl && ((RecordStoreImpl) value).isOpen()) { ((RecordStoreImpl) value).setOpen(); return (RecordStoreImpl) value; } RecordStoreImpl recordStoreImpl; String headerName = getHeaderFileName(recordStoreName); File headerFile = new File(AppClassLoader.getDataDir(), headerName); try (DataInputStream dis = new DataInputStream(new FileInputStream(headerFile))) { recordStoreImpl = new RecordStoreImpl(this); recordStoreImpl.readHeader(dis); recordStoreImpl.setOpen(); } catch (FileNotFoundException e) { if (!createIfNecessary) { throw new RecordStoreNotFoundException(recordStoreName); } recordStoreImpl = new RecordStoreImpl(this, recordStoreName); recordStoreImpl.setOpen(); saveToDisk(recordStoreImpl, -1); } catch (IOException e) { Log.w(TAG, "openRecordStore: broken header " + headerFile, e); recordStoreImpl = new RecordStoreImpl(this, recordStoreName); recordStoreImpl.setOpen(); saveToDisk(recordStoreImpl, -1); } recordStores.put(recordStoreName, recordStoreImpl); synchronized (recordStoreImpl.records) { File dataDir = new File(AppClassLoader.getDataDir()); String prefix = recordStoreName + "."; String[] files = dataDir.list(); if (files != null) { for (String name : files) { if (name.startsWith(prefix) && name.endsWith(RECORD_STORE_RECORD_SUFFIX)) { File file = new File(dataDir, name); try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) { recordStoreImpl.readRecord(dis); } catch (IOException e) { Log.w(TAG, "loadFromDisk: broken record " + file, e); int pLen = prefix.length(); int sLen = RECORD_STORE_RECORD_SUFFIX.length(); int nLen = name.length(); if (pLen + sLen < nLen) { try { int recordId = Integer.parseInt(name.substring(pLen, nLen - sLen)); recordStoreImpl.records.put(recordId, new byte[0]); } catch (NumberFormatException numberFormatException) { Log.w(TAG, "loadFromDisk: ERROR stubbing broken record " + file); } } } } } } } Log.d(TAG, "RecordStore " + recordStoreName + " opened"); return recordStoreImpl; } @Override public String[] listRecordStores() { initializeIfNecessary(); String[] result = recordStores.keySet().toArray(new String[0]); if (result.length > 0) { return result; } else { return null; } } @Override public void deleteRecord(RecordStoreImpl recordStoreImpl, int recordId) throws RecordStoreException { deleteFromDisk(recordStoreImpl, recordId); } @Override public void loadRecord(RecordStoreImpl recordStoreImpl, int recordId) throws RecordStoreException { String recordName = getRecordFileName(recordStoreImpl.getName(), recordId); try (DataInputStream dis = new DataInputStream(ContextHolder.openFileInput(recordName))) { recordStoreImpl.readRecord(dis); } catch (FileNotFoundException e) { throw new InvalidRecordIDException(); } catch (IOException e) { Log.e(TAG, "RecordStore.loadFromDisk: ERROR reading " + recordName, e); } } @Override public void saveRecord(RecordStoreImpl recordStoreImpl, int recordId) throws RecordStoreException { saveToDisk(recordStoreImpl, recordId); } private synchronized void deleteFromDisk(RecordStoreImpl recordStore, int recordId) throws RecordStoreException { String headerName = getHeaderFileName(recordStore.getName()); try (DataOutputStream dos = new DataOutputStream(ContextHolder.openFileOutput(headerName))) { recordStore.writeHeader(dos); } catch (IOException e) { Log.e(TAG, "RecordStore.saveToDisk: ERROR writing object to " + headerName, e); throw new RecordStoreException(e.getMessage()); } ContextHolder.deleteFile(getRecordFileName(recordStore.getName(), recordId)); } /** * @param recordId -1 for storing only header */ private synchronized void saveToDisk(RecordStoreImpl recordStore, int recordId) throws RecordStoreException { String headerName = getHeaderFileName(recordStore.getName()); try (DataOutputStream dos = new DataOutputStream(ContextHolder.openFileOutput(headerName))) { recordStore.writeHeader(dos); } catch (IOException e) { Log.e(TAG, "RecordStore.saveToDisk: ERROR writing object to " + headerName, e); throw new RecordStoreException(e.getMessage()); } if (recordId != -1) { String recordName = getRecordFileName(recordStore.getName(), recordId); try (DataOutputStream dos = new DataOutputStream(ContextHolder.openFileOutput(recordName))) { recordStore.writeRecord(dos, recordId); } catch (IOException e) { Log.e(TAG, "RecordStore.saveToDisk: ERROR writing object to " + recordName, e); throw new RecordStoreException(e.getMessage()); } } } @Override public int getSizeAvailable(RecordStoreImpl recordStoreImpl) { // TODO should return free space on device return 1024 * 1024; } private String getHeaderFileName(String recordStoreName) { return recordStoreName + RECORD_STORE_HEADER_SUFFIX; } private String getRecordFileName(String recordStoreName, int recordId) { return recordStoreName + "." + recordId + RECORD_STORE_RECORD_SUFFIX; } }
9,031
0.727182
0.722658
267
32.936329
27.583576
96
false
false
0
0
0
0
0
0
2.498127
false
false
15
445df5943e5a75d92566d0161d1dd0fd774310a3
21,784,074,150,786
a37a8e92ea0958fc15f4fa386c9f0e94c503961f
/Group1_Project_IS1220_part1_FearnleyMartin_SebastienBaur/src/Clients/CLUI.java
17d7220c3ff9a03188fb22b6a9c23d0c9600bff1
[]
no_license
fearnleymartin/Final-Project
https://github.com/fearnleymartin/Final-Project
a38bd34fba812f32d03a6223cadb55c1212fec20
90afac1285baee90ba717ca2f44f0fd47ef4d862
refs/heads/master
2021-01-01T16:12:41.764000
2016-11-18T20:11:13
2016-11-18T20:11:13
33,923,776
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Clients; import java.util.*; import treeImplementation.*; import dataTypes.*; public class CLUI { //list contents of directory public static void ls(String vfsname, String args, String pathname){ VdAndCurrentNode vdcn; try { vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); Node currentNode = vdcn.getCurrentNode(); //all files & folders if (pathname.equals("")){ switch(args){ case "": List<Node> succ; try { succ = vd.getAllSuccessors(vd.getPath(currentNode)); for (Node n : succ){ if (n instanceof Fichier){ System.out.println(n.getName()+" "+"f"); } else{ System.out.println(n.getName()+" "+"d"); } } break; } catch (NotInTreeException e) { System.out.println("The current node: "+ currentNode + " is irretrievable"); e.printStackTrace(); } //prints size too case "-l": List<Node> succ2; try { succ2 = vd.getAllSuccessors(vd.getPath(currentNode)); for (Node n : succ2){ if (n instanceof Fichier){ System.out.println(n.getName()+" "+((Fichier)n).getSize() + " "+"f"); } else{ Tree subTree = vd.getSubTree(vd.getPath(n)); long size = vd.getTotalFileSize(subTree); System.out.println(n.getName()+" "+ size+" "+"d"); } } break; } catch (NotInTreeException e) { System.out.println("The current node: "+ currentNode + " is irretrievable"); e.printStackTrace(); } } } //files & folders in pathname else{ switch(args){ case "": List<Node> succ; try { succ = vd.getAllSuccessors(pathname); for (Node n : succ){ if (n instanceof Fichier){ System.out.println(n.getName()+" "+"f"); } else{ System.out.println(n.getName()+" "+"d"); } } break; } catch (NotInTreeException e) { System.out.println("The current node: "+ currentNode + " is irretrievable"); e.printStackTrace(); } //prints size too case "-l": List<Node> succ2; try { succ2 = vd.getAllSuccessors(pathname); for (Node n : succ2){ // System.out.println(succ2); if (n instanceof Fichier){ System.out.println(n.getName()+" "+((Fichier)n).getSize() + " "+"f"); } else{ Tree subTree = vd.getSubTree(vd.getPath(n)); long size = vd.getTotalFileSize(subTree); System.out.println(n.getName()+" "+ size+" "+"d"); } } break; } catch (NotInTreeException e) { System.out.println("The current node: "+ currentNode + " is irretrievable"); e.printStackTrace(); } } } } catch (VirtualDiskDoesntExistException e) { System.out.print("No virtual disk called '" + vfsname + "' exists"); e.printStackTrace(); } } //returns vd and its current node object from the name of a vfs public static VdAndCurrentNode getVdACNFromVfsname(String vfsname) throws VirtualDiskDoesntExistException{ for (VdAndCurrentNode vdcn : VdcnManagement.getVdList()){ if(vdcn.getVd().getName().equals(vfsname)){ return vdcn; } } throw new VirtualDiskDoesntExistException("No virtual disk called '" + vfsname + "' exists"); } //add in the different cases //navigate to directory public static void cd(String vfsname, String pathname){ VdAndCurrentNode vdcn; try { vdcn = getVdACNFromVfsname(vfsname); Node nodeSpecified; try { nodeSpecified = vdcn.getVd().getNodeFromPath(pathname); vdcn.setCurrentNode(nodeSpecified); System.out.println("The current node is " + nodeSpecified); } catch (NotInTreeException e) { System.out.println(pathname + " not found"); e.printStackTrace(); } } catch (VirtualDiskDoesntExistException e) { System.out.println("No virtual disk called '" + vfsname + "' exists"); e.printStackTrace(); } } //to create a new virtual disk //what if vd already exists with this name ? //limit maximum size to stop user doing anything stupid public static void crvfs(String vfsname, int dim) { VirtualDisk vd = VirtualDisk.createVirtualDisk(vfsname, "Virtual Disks/"+ vfsname+ ".ser", dim); VdAndCurrentNode vdcn = new VdAndCurrentNode(vd); VdcnManagement.getVdList().add(vdcn); } //renames files/directory public static void mv (String vfsname, String oldpath, String newpath) { VdAndCurrentNode vdcn; try { vdcn = getVdACNFromVfsname(vfsname); String[] str= newpath.split("/"); String newName = str[str.length-1]; try { vdcn.getVd().rename(oldpath, newName); } catch (NotInTreeException e) { System.out.println(oldpath + " not found"); e.printStackTrace(); } } catch (VirtualDiskDoesntExistException e) { System.out.println("No virtual disk called '" + vfsname + "' exists"); e.printStackTrace(); } } //doesn't work correctly !!!!!!!!!! public static void cp(String vfsname, String sourcepath,String targetpath) throws VirtualDiskDoesntExistException, NotInTreeException, NotADirectoryException, NoAvailableSpaceException, ParentException{ VdAndCurrentNode vdcn= getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); //change targetpath into parent path String[] str= targetpath.split("/"); String parentPath = ""; for (int i=0; i<str.length-2;i++){ parentPath = parentPath+str[i]+"/"; } parentPath = parentPath+str[str.length-2]; System.out.println(parentPath); vd.copy(sourcepath, parentPath); } //import file structure into vd public static void impvfs(String hostpath,String vfsname, String vfspath){ VdAndCurrentNode vdcn = null; try { vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); try { vd.importFileStructure(hostpath, vfspath); System.out.println(hostpath + " imported into "+ vfsname); } catch (NoAvailableSpaceException e) { e.printStackTrace(); } catch (NotInTreeException e) { System.out.println(vfspath + " not found"); e.printStackTrace(); } catch (NotADirectoryException e) { System.out.println(vfspath + " is not a directory"); e.printStackTrace(); } catch (ParentException e) { System.out.println("parent exception: file system you are importing is corrupted"); e.printStackTrace(); } } catch (VirtualDiskDoesntExistException e) { System.out.println(vfsname +" doesn't exist"); } } //exports home aswell public static void expvfs(String vfsname, String hostpath){ VdAndCurrentNode vdcn = null; try { vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); try { vd.exportDirectory(hostpath, "Home"); } catch (NotInTreeException e) { System.out.println("Home directory has been deleted, cannot export the vfs as vfs is damaged"); e.printStackTrace(); } System.out.println(vfsname + " exported into "+ hostpath); } catch (VirtualDiskDoesntExistException e) { System.out.println(vfsname +" doesn't exist"); e.printStackTrace(); } } //queries free space on the vd public static void free(String vfsname){ try { VdAndCurrentNode vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); System.out.println(vd.queryFreeSpace()); } catch (VirtualDiskDoesntExistException e) { System.out.println(vfsname +" doesn't exist"); e.printStackTrace(); } } //remove a vd public static void rmvfs (String vfsname){ VdAndCurrentNode vdcn; try { vdcn = getVdACNFromVfsname(vfsname); vdcn.getVd().deleteVirtualDisk(); VdcnManagement.getVdList().remove(vdcn); } catch (VirtualDiskDoesntExistException e) { System.out.println("No virtual disk called '" + vfsname + "' exists"); e.printStackTrace(); } } //remove file/directory from vd public static void rm(String vfsname, String pathname){ VdAndCurrentNode vdcn; try { vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); try { vd.deleteAll(pathname); } catch (NotInTreeException e) { System.out.println(pathname + " not found in "+ vfsname); e.printStackTrace(); } } catch (VirtualDiskDoesntExistException e) { System.out.println(vfsname +" doesn't exist"); e.printStackTrace(); } } //unused public static String invertedCommaRemover(String str){ if ((str.startsWith("\""))&& (str.endsWith("\""))){ System.out.println("hey"); return str.replace("\"",""); } else{ return str; } } public static void find(String vfsname, String filename){ try { VdAndCurrentNode vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); List<Node> list = null; try { list = vd.search(filename); for (Node n : list){ try { System.out.println(vd.getPath(n)); } catch (NotInTreeException e) { System.out.println("Cannot get the path of " +n.getName()); e.printStackTrace(); } } } catch (NotInTreeException e) { System.out.println(filename + " cannot be found in "+vfsname); e.printStackTrace(); } } catch (VirtualDiskDoesntExistException e) { System.out.println(vfsname +" doesn't exist"); e.printStackTrace(); } } public static void help (String str){ switch (str){ case "ls": System.out.println("To list the information concerning files and directories contained in absolute position corresponding to pathname (if no pathname argument is given then the current position, i.e. the current directory, is listed) in a VFS named vfsname. The command ls should behave differently, depending on the optional argument arg:"); System.out.println("If args=\"\" (i.e. no args is given): in this case ls simply displays the list of names of files and directories contained in the current directory of the VFS."); System.out.println("In this case ls vfs1 -l displays the list of names and dimension of files and directories contained in the current directory of the VFS."); System.out.println("Syntax: ls <vfsname> <args> <pathname> "); break; case "crvfs": System.out.println("To create a new VFS with name vfsname and maximal dimension dim bytes"); System.out.println("Syntax: crvfs <vfsname> <dim>"); break; case "cd": System.out.println("Changes the current position in the VFS vfsname to the directory whose absolute name is <pathname>"); System.out.println("Notice that if pathname=. the current position is unchanged whether if pathname=..the current position becomes the parent directory of the current one. For example \"cd vfs1 /Pictures/London\" will set the current position of VFS called vfs1 to path \"/Pictures/London\", whereas \"cd vfs1 ..\" will set the current position to the parent directory of the current one hence to \"/Pictures\" if \"cd vfs1 ..\" is executed soon after \"cd vfs1 /Pictures/London\""); System.out.println("Syntax: cd <vfsname> <pathname>"); break; case "mv": System.out.println("To change the name of a file/directory with absolute name oldpath in the new absolute name newpath of the VFS named vfsname."); System.out.println("Syntax: mv <vfsname> <oldpath> <newpath>"); break; case "cp": System.out.println("To copy, within the VFS named vfsname, the content of a file/directory whose absolute name is source path into a target le/directory whose absolute name is targetpath."); System.out.println("cp <vfsname> <sourcepath> <targetpath>"); break; case "rm": System.out.println("To remove a file/directory with absolute name pathname from the VFS named vfsname."); System.out.println("Syntax: rm <vfsname> <pathname>"); break; case "rmvfs": System.out.println("To delete a VFS named vfsname"); System.out.println("Syntax: rmvfs <vfsname>"); break; case "impvfs": System.out.println("To import the content of the directory/file corresponding to absolute name hostpath on the host file system into the position vfspath on an existing VFS named vfsname."); System.out.println("Syntax: impvfs <hostpath> <vfsname> <vfspath>"); break; case "expvfs": System.out.println("To export an existing VFS named vfsname into the absolute path named hostpath of the host file system"); System.out.println("Syntax: expvfs <vfsname> <hostpath>"); break; case "free": System.out.println("To display the quantity of free/occupied space for VFS named vfsname"); System.out.println("Syntax: free <vfsname>"); break; case "find": System.out.println("To search if a file named filename is stored in the VFS named vfsname, shall return the absolute path of the sought le if it is present in the VFS, null otherwise"); System.out.println("Syntax: find <vfsname> <filename>"); break; case "help": System.out.println("To display an \"help message\" (similar to that of unix shell terminal) which gives information about how to use the command named command-name. If help is invoked without <command-name> argument then it should display a generic help message about how to use the CLUI (e.g. general syntax of a CLUI command, list of all CLUI commands name)."); System.out.println("help <command-name>"); case "gen": System.out.println("Generates a tree of the current file system"); System.out.println("Syntax gen <vfsname>"); break; default: System.out.println("The "+ str + "command doesn't exist"); } } public static void help(){ System.out.println("Commands take the following general syntax: command <arg1> <arg2> <arg3>"); System.out.println("The different commands are: ls, cd, mv, cp, rm, crvfs, rmvfs, impvfs, expvfs, free, find, help"); System.out.println("Type help <command> to find out more about a command"); } //cuts up the string argument received from the user input into an array of string arguments //if path name includes spaces, then the path name must be put inside inverted commas public static List<String> preTreatment(String str){ List<String> list = new ArrayList<String>(); int strLen = str.length(); //compteur to iterate through each character of the string int compteur = 0; //for remembering where the last space was encountered int lastSpace = 0; //for remembering where the last inverted comma was encountered int lastComma = 0; //is true if the compteur is between inverted commas boolean inInvertedCommas=false; //is true if the inverted commas have just been closed boolean precededByInvertedCommas=false; while (compteur < strLen){ //tests for a space followed by an inverted comma, i.e. the beginning of an argument in inverted commas if (Character.toString((str.charAt(compteur))).equals(" ")&&Character.toString((str.charAt(compteur+1))).equals("\"")){ // System.out.println("space comma"); if (!inInvertedCommas&&!precededByInvertedCommas){ // System.out.println(str.substring(lastSpace, compteur)); list.add(str.substring(lastSpace, compteur)); lastSpace = compteur+1; } lastComma=compteur+2; compteur=compteur+2; inInvertedCommas=true; precededByInvertedCommas=false; } //tests for the end of a string in inverted commas else if (Character.toString((str.charAt(compteur))).equals("\"")){ // System.out.println("comma"); list.add(str.substring(lastComma, compteur)); // System.out.println(str.substring(lastComma, compteur)); lastComma = compteur+1; lastSpace = compteur+2; compteur++; inInvertedCommas=false; precededByInvertedCommas=true; } //tests for a space, i.e. athe start of a new argument, unless in inverted commas else if(Character.toString((str.charAt(compteur))).equals(" ")){ if (!inInvertedCommas&&!precededByInvertedCommas){ // System.out.println(str.substring(lastSpace, compteur)); list.add(str.substring(lastSpace, compteur)); lastSpace = compteur+1; compteur++; precededByInvertedCommas=false; } else{ compteur ++; precededByInvertedCommas=false; } } //if reaches end of string else if(compteur == strLen-1){ // System.out.println(str.substring(lastSpace, compteur+1)); list.add(str.substring(lastSpace, compteur+1)); compteur++; } //if none of these characters are encountered, we continue to iterate through the string else{ compteur ++; } } return list; } //interprets the user input and calls the correct function (aftr pre treatment) public static void understand(String str) throws NumberFormatException, NotInTreeException, VirtualDiskDoesntExistException, NoAvailableSpaceException, NotADirectoryException, ParentException{ //pre-treat string List<String> strList = preTreatment(str); //create an array from list returned String[] strs = new String[strList.size()]; for (int i = 0; i<strList.size();i++){ strs[i]=strList.get(i); } //check for first argument switch (strs[0]){ case "ls": if (strs.length==2){ ls(strs[1],"",""); } else if(strs.length==3){ if(strs[2].equals("-1")){ ls(strs[1],"-1",""); } else{ls(strs[1],"",strs[2]); } } else{ ls(strs[1],strs[2],strs[3]); } break; case "crvfs": if (strs.length==3){ crvfs(strs[1],Integer.parseInt(strs[2])); } else { System.out.println("Invalid Command, refer to help to see syntax"); } break; case "cd": if (strs.length==3){ cd(strs[1],strs[2]); } else { System.out.println("Invalid Command, refer to help to see syntax"); } break; case "mv": if (strs.length==4){ mv(strs[1],strs[2],strs[3]); } else { System.out.println("Invalid Command, refer to help to see syntax"); } break; case "cp": if (strs.length==4){ cp(strs[1],strs[2],strs[3]); } else { System.out.println("Invalid Command, refer to help to see syntax"); } break; case "rmvfs": if (strs.length==2){ rmvfs(strs[1]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "rm": if (strs.length==3){ rm(strs[1],strs[2]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "impvfs": if (strs.length==4){ impvfs(strs[1],strs[2],strs[3]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "expvfs": if (strs.length==3){ expvfs(strs[1],strs[2]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "free": if (strs.length==2){ free(strs[1]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "find": if (strs.length==3){ find(strs[1],strs[2]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "help": if (strs.length==1){ help();} else if (strs.length==2&&(strs[1] instanceof String)){help(strs[1]);} else{System.out.println("Invalid command, refer to help to see syntax");} break; // case "gen": // if (strs.length==2){ // new GenerateTree(getVdACNFromVfsname(strs[1]).getVd()); // } // else { // System.out.println("Invalid command, refer to help to see syntax"); // } // break; default: System.out.println("Not a valid command, please type help for more information"); } } public static void main(String[] args) throws NotInTreeException, VirtualDiskDoesntExistException, NoAvailableSpaceException, NotADirectoryException, ParentException{ //create vfs1 crvfs("vfs1",1000); //create vfs2 // crvfs("vfs2",1000); // System.out.println(VdcnManagement.getVdList().get(0).getVd()); // System.out.println(VdcnManagement.getVdList().get(0).getCurrentNode()); //acces vfs1 and vfs2 // VdAndCurrentNode vfs1 = getVdACNFromVfsname("vfs1"); // VdAndCurrentNode vfs2 = getVdACNFromVfsname("vfs2"); // System.out.println(vfs1.toString()); //import level 1 impvfs("eval/Host/level 1","vfs1","Home"); // GenerateTree gt = new GenerateTree(getVdACNFromVfsname("vfs1").getVd()); // System.out.println(vfs1.getVd().getTree().getNodeList()); // //navigate to level 2 // cd("vfs1","Home/level 1/level 2"); // System.out.println(vfs1.getCurrentNode()); // ls("vfs1","-1",""); //rename level 1 to level 1 renamed // mv("vfs1","Home/level 1","Home/level 1 renamed"); // gt.UpdateTree(); // ls("vfs1","","Home"); // //put test text.txt in level 2 bis // cp("vfs1","Home/level 1 renamed/level 2/test text.txt","Home/level 1 renamed/level 2 bis/test text.txt"); // //display trees // GenerateTree gt = new GenerateTree(vfs1.getVd()); // new GenerateTree(vfs2.getVd()); expvfs("vfs1","eval/Host/moving test"); System.out.println("What would you like to do ? Type help to see the commands"); Scanner scan = new Scanner(System.in); while (true){ String str = scan.nextLine(); // List<String> tab = (preTreatment(str)); // for (String s : tab){System.out.println("element: " +s);} understand(str); } } }
UTF-8
Java
21,747
java
CLUI.java
Java
[]
null
[]
package Clients; import java.util.*; import treeImplementation.*; import dataTypes.*; public class CLUI { //list contents of directory public static void ls(String vfsname, String args, String pathname){ VdAndCurrentNode vdcn; try { vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); Node currentNode = vdcn.getCurrentNode(); //all files & folders if (pathname.equals("")){ switch(args){ case "": List<Node> succ; try { succ = vd.getAllSuccessors(vd.getPath(currentNode)); for (Node n : succ){ if (n instanceof Fichier){ System.out.println(n.getName()+" "+"f"); } else{ System.out.println(n.getName()+" "+"d"); } } break; } catch (NotInTreeException e) { System.out.println("The current node: "+ currentNode + " is irretrievable"); e.printStackTrace(); } //prints size too case "-l": List<Node> succ2; try { succ2 = vd.getAllSuccessors(vd.getPath(currentNode)); for (Node n : succ2){ if (n instanceof Fichier){ System.out.println(n.getName()+" "+((Fichier)n).getSize() + " "+"f"); } else{ Tree subTree = vd.getSubTree(vd.getPath(n)); long size = vd.getTotalFileSize(subTree); System.out.println(n.getName()+" "+ size+" "+"d"); } } break; } catch (NotInTreeException e) { System.out.println("The current node: "+ currentNode + " is irretrievable"); e.printStackTrace(); } } } //files & folders in pathname else{ switch(args){ case "": List<Node> succ; try { succ = vd.getAllSuccessors(pathname); for (Node n : succ){ if (n instanceof Fichier){ System.out.println(n.getName()+" "+"f"); } else{ System.out.println(n.getName()+" "+"d"); } } break; } catch (NotInTreeException e) { System.out.println("The current node: "+ currentNode + " is irretrievable"); e.printStackTrace(); } //prints size too case "-l": List<Node> succ2; try { succ2 = vd.getAllSuccessors(pathname); for (Node n : succ2){ // System.out.println(succ2); if (n instanceof Fichier){ System.out.println(n.getName()+" "+((Fichier)n).getSize() + " "+"f"); } else{ Tree subTree = vd.getSubTree(vd.getPath(n)); long size = vd.getTotalFileSize(subTree); System.out.println(n.getName()+" "+ size+" "+"d"); } } break; } catch (NotInTreeException e) { System.out.println("The current node: "+ currentNode + " is irretrievable"); e.printStackTrace(); } } } } catch (VirtualDiskDoesntExistException e) { System.out.print("No virtual disk called '" + vfsname + "' exists"); e.printStackTrace(); } } //returns vd and its current node object from the name of a vfs public static VdAndCurrentNode getVdACNFromVfsname(String vfsname) throws VirtualDiskDoesntExistException{ for (VdAndCurrentNode vdcn : VdcnManagement.getVdList()){ if(vdcn.getVd().getName().equals(vfsname)){ return vdcn; } } throw new VirtualDiskDoesntExistException("No virtual disk called '" + vfsname + "' exists"); } //add in the different cases //navigate to directory public static void cd(String vfsname, String pathname){ VdAndCurrentNode vdcn; try { vdcn = getVdACNFromVfsname(vfsname); Node nodeSpecified; try { nodeSpecified = vdcn.getVd().getNodeFromPath(pathname); vdcn.setCurrentNode(nodeSpecified); System.out.println("The current node is " + nodeSpecified); } catch (NotInTreeException e) { System.out.println(pathname + " not found"); e.printStackTrace(); } } catch (VirtualDiskDoesntExistException e) { System.out.println("No virtual disk called '" + vfsname + "' exists"); e.printStackTrace(); } } //to create a new virtual disk //what if vd already exists with this name ? //limit maximum size to stop user doing anything stupid public static void crvfs(String vfsname, int dim) { VirtualDisk vd = VirtualDisk.createVirtualDisk(vfsname, "Virtual Disks/"+ vfsname+ ".ser", dim); VdAndCurrentNode vdcn = new VdAndCurrentNode(vd); VdcnManagement.getVdList().add(vdcn); } //renames files/directory public static void mv (String vfsname, String oldpath, String newpath) { VdAndCurrentNode vdcn; try { vdcn = getVdACNFromVfsname(vfsname); String[] str= newpath.split("/"); String newName = str[str.length-1]; try { vdcn.getVd().rename(oldpath, newName); } catch (NotInTreeException e) { System.out.println(oldpath + " not found"); e.printStackTrace(); } } catch (VirtualDiskDoesntExistException e) { System.out.println("No virtual disk called '" + vfsname + "' exists"); e.printStackTrace(); } } //doesn't work correctly !!!!!!!!!! public static void cp(String vfsname, String sourcepath,String targetpath) throws VirtualDiskDoesntExistException, NotInTreeException, NotADirectoryException, NoAvailableSpaceException, ParentException{ VdAndCurrentNode vdcn= getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); //change targetpath into parent path String[] str= targetpath.split("/"); String parentPath = ""; for (int i=0; i<str.length-2;i++){ parentPath = parentPath+str[i]+"/"; } parentPath = parentPath+str[str.length-2]; System.out.println(parentPath); vd.copy(sourcepath, parentPath); } //import file structure into vd public static void impvfs(String hostpath,String vfsname, String vfspath){ VdAndCurrentNode vdcn = null; try { vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); try { vd.importFileStructure(hostpath, vfspath); System.out.println(hostpath + " imported into "+ vfsname); } catch (NoAvailableSpaceException e) { e.printStackTrace(); } catch (NotInTreeException e) { System.out.println(vfspath + " not found"); e.printStackTrace(); } catch (NotADirectoryException e) { System.out.println(vfspath + " is not a directory"); e.printStackTrace(); } catch (ParentException e) { System.out.println("parent exception: file system you are importing is corrupted"); e.printStackTrace(); } } catch (VirtualDiskDoesntExistException e) { System.out.println(vfsname +" doesn't exist"); } } //exports home aswell public static void expvfs(String vfsname, String hostpath){ VdAndCurrentNode vdcn = null; try { vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); try { vd.exportDirectory(hostpath, "Home"); } catch (NotInTreeException e) { System.out.println("Home directory has been deleted, cannot export the vfs as vfs is damaged"); e.printStackTrace(); } System.out.println(vfsname + " exported into "+ hostpath); } catch (VirtualDiskDoesntExistException e) { System.out.println(vfsname +" doesn't exist"); e.printStackTrace(); } } //queries free space on the vd public static void free(String vfsname){ try { VdAndCurrentNode vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); System.out.println(vd.queryFreeSpace()); } catch (VirtualDiskDoesntExistException e) { System.out.println(vfsname +" doesn't exist"); e.printStackTrace(); } } //remove a vd public static void rmvfs (String vfsname){ VdAndCurrentNode vdcn; try { vdcn = getVdACNFromVfsname(vfsname); vdcn.getVd().deleteVirtualDisk(); VdcnManagement.getVdList().remove(vdcn); } catch (VirtualDiskDoesntExistException e) { System.out.println("No virtual disk called '" + vfsname + "' exists"); e.printStackTrace(); } } //remove file/directory from vd public static void rm(String vfsname, String pathname){ VdAndCurrentNode vdcn; try { vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); try { vd.deleteAll(pathname); } catch (NotInTreeException e) { System.out.println(pathname + " not found in "+ vfsname); e.printStackTrace(); } } catch (VirtualDiskDoesntExistException e) { System.out.println(vfsname +" doesn't exist"); e.printStackTrace(); } } //unused public static String invertedCommaRemover(String str){ if ((str.startsWith("\""))&& (str.endsWith("\""))){ System.out.println("hey"); return str.replace("\"",""); } else{ return str; } } public static void find(String vfsname, String filename){ try { VdAndCurrentNode vdcn = getVdACNFromVfsname(vfsname); VirtualDisk vd = vdcn.getVd(); List<Node> list = null; try { list = vd.search(filename); for (Node n : list){ try { System.out.println(vd.getPath(n)); } catch (NotInTreeException e) { System.out.println("Cannot get the path of " +n.getName()); e.printStackTrace(); } } } catch (NotInTreeException e) { System.out.println(filename + " cannot be found in "+vfsname); e.printStackTrace(); } } catch (VirtualDiskDoesntExistException e) { System.out.println(vfsname +" doesn't exist"); e.printStackTrace(); } } public static void help (String str){ switch (str){ case "ls": System.out.println("To list the information concerning files and directories contained in absolute position corresponding to pathname (if no pathname argument is given then the current position, i.e. the current directory, is listed) in a VFS named vfsname. The command ls should behave differently, depending on the optional argument arg:"); System.out.println("If args=\"\" (i.e. no args is given): in this case ls simply displays the list of names of files and directories contained in the current directory of the VFS."); System.out.println("In this case ls vfs1 -l displays the list of names and dimension of files and directories contained in the current directory of the VFS."); System.out.println("Syntax: ls <vfsname> <args> <pathname> "); break; case "crvfs": System.out.println("To create a new VFS with name vfsname and maximal dimension dim bytes"); System.out.println("Syntax: crvfs <vfsname> <dim>"); break; case "cd": System.out.println("Changes the current position in the VFS vfsname to the directory whose absolute name is <pathname>"); System.out.println("Notice that if pathname=. the current position is unchanged whether if pathname=..the current position becomes the parent directory of the current one. For example \"cd vfs1 /Pictures/London\" will set the current position of VFS called vfs1 to path \"/Pictures/London\", whereas \"cd vfs1 ..\" will set the current position to the parent directory of the current one hence to \"/Pictures\" if \"cd vfs1 ..\" is executed soon after \"cd vfs1 /Pictures/London\""); System.out.println("Syntax: cd <vfsname> <pathname>"); break; case "mv": System.out.println("To change the name of a file/directory with absolute name oldpath in the new absolute name newpath of the VFS named vfsname."); System.out.println("Syntax: mv <vfsname> <oldpath> <newpath>"); break; case "cp": System.out.println("To copy, within the VFS named vfsname, the content of a file/directory whose absolute name is source path into a target le/directory whose absolute name is targetpath."); System.out.println("cp <vfsname> <sourcepath> <targetpath>"); break; case "rm": System.out.println("To remove a file/directory with absolute name pathname from the VFS named vfsname."); System.out.println("Syntax: rm <vfsname> <pathname>"); break; case "rmvfs": System.out.println("To delete a VFS named vfsname"); System.out.println("Syntax: rmvfs <vfsname>"); break; case "impvfs": System.out.println("To import the content of the directory/file corresponding to absolute name hostpath on the host file system into the position vfspath on an existing VFS named vfsname."); System.out.println("Syntax: impvfs <hostpath> <vfsname> <vfspath>"); break; case "expvfs": System.out.println("To export an existing VFS named vfsname into the absolute path named hostpath of the host file system"); System.out.println("Syntax: expvfs <vfsname> <hostpath>"); break; case "free": System.out.println("To display the quantity of free/occupied space for VFS named vfsname"); System.out.println("Syntax: free <vfsname>"); break; case "find": System.out.println("To search if a file named filename is stored in the VFS named vfsname, shall return the absolute path of the sought le if it is present in the VFS, null otherwise"); System.out.println("Syntax: find <vfsname> <filename>"); break; case "help": System.out.println("To display an \"help message\" (similar to that of unix shell terminal) which gives information about how to use the command named command-name. If help is invoked without <command-name> argument then it should display a generic help message about how to use the CLUI (e.g. general syntax of a CLUI command, list of all CLUI commands name)."); System.out.println("help <command-name>"); case "gen": System.out.println("Generates a tree of the current file system"); System.out.println("Syntax gen <vfsname>"); break; default: System.out.println("The "+ str + "command doesn't exist"); } } public static void help(){ System.out.println("Commands take the following general syntax: command <arg1> <arg2> <arg3>"); System.out.println("The different commands are: ls, cd, mv, cp, rm, crvfs, rmvfs, impvfs, expvfs, free, find, help"); System.out.println("Type help <command> to find out more about a command"); } //cuts up the string argument received from the user input into an array of string arguments //if path name includes spaces, then the path name must be put inside inverted commas public static List<String> preTreatment(String str){ List<String> list = new ArrayList<String>(); int strLen = str.length(); //compteur to iterate through each character of the string int compteur = 0; //for remembering where the last space was encountered int lastSpace = 0; //for remembering where the last inverted comma was encountered int lastComma = 0; //is true if the compteur is between inverted commas boolean inInvertedCommas=false; //is true if the inverted commas have just been closed boolean precededByInvertedCommas=false; while (compteur < strLen){ //tests for a space followed by an inverted comma, i.e. the beginning of an argument in inverted commas if (Character.toString((str.charAt(compteur))).equals(" ")&&Character.toString((str.charAt(compteur+1))).equals("\"")){ // System.out.println("space comma"); if (!inInvertedCommas&&!precededByInvertedCommas){ // System.out.println(str.substring(lastSpace, compteur)); list.add(str.substring(lastSpace, compteur)); lastSpace = compteur+1; } lastComma=compteur+2; compteur=compteur+2; inInvertedCommas=true; precededByInvertedCommas=false; } //tests for the end of a string in inverted commas else if (Character.toString((str.charAt(compteur))).equals("\"")){ // System.out.println("comma"); list.add(str.substring(lastComma, compteur)); // System.out.println(str.substring(lastComma, compteur)); lastComma = compteur+1; lastSpace = compteur+2; compteur++; inInvertedCommas=false; precededByInvertedCommas=true; } //tests for a space, i.e. athe start of a new argument, unless in inverted commas else if(Character.toString((str.charAt(compteur))).equals(" ")){ if (!inInvertedCommas&&!precededByInvertedCommas){ // System.out.println(str.substring(lastSpace, compteur)); list.add(str.substring(lastSpace, compteur)); lastSpace = compteur+1; compteur++; precededByInvertedCommas=false; } else{ compteur ++; precededByInvertedCommas=false; } } //if reaches end of string else if(compteur == strLen-1){ // System.out.println(str.substring(lastSpace, compteur+1)); list.add(str.substring(lastSpace, compteur+1)); compteur++; } //if none of these characters are encountered, we continue to iterate through the string else{ compteur ++; } } return list; } //interprets the user input and calls the correct function (aftr pre treatment) public static void understand(String str) throws NumberFormatException, NotInTreeException, VirtualDiskDoesntExistException, NoAvailableSpaceException, NotADirectoryException, ParentException{ //pre-treat string List<String> strList = preTreatment(str); //create an array from list returned String[] strs = new String[strList.size()]; for (int i = 0; i<strList.size();i++){ strs[i]=strList.get(i); } //check for first argument switch (strs[0]){ case "ls": if (strs.length==2){ ls(strs[1],"",""); } else if(strs.length==3){ if(strs[2].equals("-1")){ ls(strs[1],"-1",""); } else{ls(strs[1],"",strs[2]); } } else{ ls(strs[1],strs[2],strs[3]); } break; case "crvfs": if (strs.length==3){ crvfs(strs[1],Integer.parseInt(strs[2])); } else { System.out.println("Invalid Command, refer to help to see syntax"); } break; case "cd": if (strs.length==3){ cd(strs[1],strs[2]); } else { System.out.println("Invalid Command, refer to help to see syntax"); } break; case "mv": if (strs.length==4){ mv(strs[1],strs[2],strs[3]); } else { System.out.println("Invalid Command, refer to help to see syntax"); } break; case "cp": if (strs.length==4){ cp(strs[1],strs[2],strs[3]); } else { System.out.println("Invalid Command, refer to help to see syntax"); } break; case "rmvfs": if (strs.length==2){ rmvfs(strs[1]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "rm": if (strs.length==3){ rm(strs[1],strs[2]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "impvfs": if (strs.length==4){ impvfs(strs[1],strs[2],strs[3]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "expvfs": if (strs.length==3){ expvfs(strs[1],strs[2]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "free": if (strs.length==2){ free(strs[1]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "find": if (strs.length==3){ find(strs[1],strs[2]); } else { System.out.println("Invalid command, refer to help to see syntax"); } break; case "help": if (strs.length==1){ help();} else if (strs.length==2&&(strs[1] instanceof String)){help(strs[1]);} else{System.out.println("Invalid command, refer to help to see syntax");} break; // case "gen": // if (strs.length==2){ // new GenerateTree(getVdACNFromVfsname(strs[1]).getVd()); // } // else { // System.out.println("Invalid command, refer to help to see syntax"); // } // break; default: System.out.println("Not a valid command, please type help for more information"); } } public static void main(String[] args) throws NotInTreeException, VirtualDiskDoesntExistException, NoAvailableSpaceException, NotADirectoryException, ParentException{ //create vfs1 crvfs("vfs1",1000); //create vfs2 // crvfs("vfs2",1000); // System.out.println(VdcnManagement.getVdList().get(0).getVd()); // System.out.println(VdcnManagement.getVdList().get(0).getCurrentNode()); //acces vfs1 and vfs2 // VdAndCurrentNode vfs1 = getVdACNFromVfsname("vfs1"); // VdAndCurrentNode vfs2 = getVdACNFromVfsname("vfs2"); // System.out.println(vfs1.toString()); //import level 1 impvfs("eval/Host/level 1","vfs1","Home"); // GenerateTree gt = new GenerateTree(getVdACNFromVfsname("vfs1").getVd()); // System.out.println(vfs1.getVd().getTree().getNodeList()); // //navigate to level 2 // cd("vfs1","Home/level 1/level 2"); // System.out.println(vfs1.getCurrentNode()); // ls("vfs1","-1",""); //rename level 1 to level 1 renamed // mv("vfs1","Home/level 1","Home/level 1 renamed"); // gt.UpdateTree(); // ls("vfs1","","Home"); // //put test text.txt in level 2 bis // cp("vfs1","Home/level 1 renamed/level 2/test text.txt","Home/level 1 renamed/level 2 bis/test text.txt"); // //display trees // GenerateTree gt = new GenerateTree(vfs1.getVd()); // new GenerateTree(vfs2.getVd()); expvfs("vfs1","eval/Host/moving test"); System.out.println("What would you like to do ? Type help to see the commands"); Scanner scan = new Scanner(System.in); while (true){ String str = scan.nextLine(); // List<String> tab = (preTreatment(str)); // for (String s : tab){System.out.println("element: " +s);} understand(str); } } }
21,747
0.645698
0.639628
629
32.573925
39.73505
486
false
false
0
0
0
0
0
0
3.683625
false
false
15
3fc7dc92002d4ff955b749da48fbf9bd22c7b48c
6,416,681,154,262
2160d7150c58aba493af7c00ad2c1cbaf9983972
/app/src/main/java/com/jingye/coffeemac/service/bean/action/ExchangeCoffeeByCodeInfo.java
de506e29848b3d2739f8dcdbd3a0a44da52f9af9
[]
no_license
ailinghengshui/CoffeeMachine
https://github.com/ailinghengshui/CoffeeMachine
5fb963d1dc02fd3667162822697de3bd17e3cd31
139a5c8b84255767d56038f2ea0c5a6130a5d40f
refs/heads/master
2021-07-23T15:47:29.555000
2017-11-03T09:41:44
2017-11-03T09:41:44
109,377,882
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jingye.coffeemac.service.bean.action; import com.jingye.coffeemac.service.ITranCode; import com.jingye.coffeemac.service.bean.BeanAncestor; public class ExchangeCoffeeByCodeInfo extends BeanAncestor { private String uid; private String fetchCode; private long timestamp; @Override public int getWhat() { return ITranCode.ACT_COFFEE; } @Override public int getAction() { return ITranCode.ACT_COFFEE_EXCHANGE_COFFEE; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public String getFetchCode() { return fetchCode; } public void setFetchCode(String fetchCode) { this.fetchCode = fetchCode; } }
UTF-8
Java
822
java
ExchangeCoffeeByCodeInfo.java
Java
[]
null
[]
package com.jingye.coffeemac.service.bean.action; import com.jingye.coffeemac.service.ITranCode; import com.jingye.coffeemac.service.bean.BeanAncestor; public class ExchangeCoffeeByCodeInfo extends BeanAncestor { private String uid; private String fetchCode; private long timestamp; @Override public int getWhat() { return ITranCode.ACT_COFFEE; } @Override public int getAction() { return ITranCode.ACT_COFFEE_EXCHANGE_COFFEE; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public String getFetchCode() { return fetchCode; } public void setFetchCode(String fetchCode) { this.fetchCode = fetchCode; } }
822
0.738443
0.738443
47
16.510639
17.584898
60
false
false
0
0
0
0
0
0
1.170213
false
false
15
00cea062a28a7f3833f72f129b30783e6b627091
30,709,016,228,084
bd489ae159a58fe4ef2b48edd56239d650b68f1d
/game-resource/src/main/java/com/dkm/produce/service/impl/ProduceServiceImpl.java
fdfce6fc6a56a3ae9fad73f9c2d6b517b7fa4db1
[]
no_license
tax-project/dkm_game_project
https://github.com/tax-project/dkm_game_project
71c515c32249311d016d434151e46c74b4109865
248f6230fa19c2e1c7ef35658bbbd0736a095466
refs/heads/master
2022-12-26T17:51:36.773000
2020-10-14T08:04:58
2020-10-14T08:04:58
287,437,968
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dkm.produce.service.impl; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.dkm.attendant.dao.AttendantMapper; import com.dkm.attendant.dao.AttendantUserMapper; import com.dkm.attendant.entity.AttenDant; import com.dkm.attendant.entity.AttendantUser; import com.dkm.attendant.entity.bo.ProducePutBO; import com.dkm.attendant.entity.vo.AttUserAllInfoVo; import com.dkm.attendant.service.IAttendantService; import com.dkm.attendant.service.IAttendantUserService; import com.dkm.config.RedisConfig; import com.dkm.constanct.CodeType; import com.dkm.entity.websocket.MsgInfo; import com.dkm.exception.ApplicationException; import com.dkm.good.entity.Goods; import com.dkm.good.service.IGoodsService; import com.dkm.jwt.contain.LocalUser; import com.dkm.jwt.entity.UserLoginQuery; import com.dkm.plunder.entity.UserProduce; import com.dkm.plunder.service.IUserProduceService; import com.dkm.produce.dao.ProduceMapper; import com.dkm.produce.entity.Produce; import com.dkm.produce.entity.bo.ProduceBO; import com.dkm.produce.entity.vo.*; import com.dkm.produce.service.IProduceService; import com.dkm.utils.DateUtils; import com.dkm.utils.IdGenerator; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author 刘梦祺 * @PROJECT_NAME: game_project * @DESCRIPTION: * @DATE: 2020/5/19 21:26 */ @Service @Slf4j @Transactional(rollbackFor = Exception.class) public class ProduceServiceImpl extends ServiceImpl<ProduceMapper, Produce> implements IProduceService { @Autowired private IdGenerator idGenerator; @Autowired private LocalUser localUser; @Autowired private IGoodsService goodsService; @Autowired private IUserProduceService userProduceService; @Autowired private ProduceMapper produceMapper; @Autowired private AttendantMapper attendantMapper; @Autowired private IAttendantUserService attendantUserService; @Autowired private IAttendantService attendantService; @Autowired private RabbitTemplate rabbitTemplate; /** * 物品金币 */ private String GOOD_NAME = "金币"; @Override public Map<String,Object> insertProduce(Long attendantId, Long attUserId) { UserLoginQuery user = localUser.getUser(); //查询时间有没有过期 LocalDateTime now = LocalDateTime.now(); //用户跟班信息 AttendantUser attUser = attendantUserService.queryAttUser(attUserId); if (attUser == null) { throw new ApplicationException(CodeType.SERVICE_ERROR, "attUserId传错了..大哥"); } //得到结束时间 String endDate = attUser.getEndDate(); LocalDateTime time = DateUtils.parseDateTime(endDate); //时间差 long until = now.until(time, ChronoUnit.SECONDS); if (until <= 0) { throw new ApplicationException(CodeType.SERVICE_ERROR, "产出时间已过期"); } //随机返回物品 Goods goods = goodsService.queryRandomGoods(); //产出对象 Produce produce = new Produce(); Long produceId = idGenerator.getNumberId(); produce.setId(produceId); if (1L == attendantId || 2L == attendantId || 3L == attendantId) { //系统跟班 produce.setAttendantId(attendantId); } else { //用户跟班 produce.setAttendantId(0L); } produce.setAttUserId(attUserId); int number; //算出随机生成的数量 if (GOOD_NAME.equals(goods.getName())) { //随机生成1000-2000的金币 number = (int) (Math.random() * (2000 - 1000 + 1)) + 1000; } else { //随机生成2-6的随机数 number = (int) (Math.random() * (6 - 2 + 2)) + 2; } produce.setNumber(number); produce.setGoodId(goods.getId()); //默认0 produce.setStatus(0); int insert = baseMapper.insert(produce); if (insert <= 0) { log.info("添加产出有误"); throw new ApplicationException(CodeType.SERVICE_ERROR); } UserProduce userProduce = new UserProduce(); userProduce.setUserId(user.getId()); userProduce.setProduceId(produceId); //添加用户产出 userProduceService.insertProduce(userProduce); //增加产出次数 attendantService.updateMuch(attUserId, 0); //返回随机生成的物品给前端 Map<String, Object> map = new HashMap<>(2); map.put("goods", goods); map.put("number",number); //事件通知产出 MsgInfo msgInfo = new MsgInfo(); msgInfo.setMsg("跟班产出事件"); msgInfo.setType(8); msgInfo.setMsgType(1); msgInfo.setToId(user.getId()); log.info("发送事件通知..."); rabbitTemplate.convertAndSend("game_event_notice", JSON.toJSONString(msgInfo)); return map; } @Override public Map<String,Object> queryImgFood(Long userId) { Map<String,Object> map=new HashMap<>(16); //跟班 List<AttendantImgVo> attendantImg = new ArrayList<>(); //查询出所有用户跟班图片 List<AttendantImgVo> attendantGoods = produceMapper.queryImgFood(userId); if(attendantGoods.size()==0){ map.put("msg","暂无跟班 快去抓跟班吧"); map.put("status",2); return map; } if(attendantGoods.size()!=0){ for (int i = 0; i < attendantGoods.size(); i++) { //不等于0说明是系统跟班 随机查询出一个跟班 放入集合 if(attendantGoods.get(i).getAttendantId()!=0){ AttendantImgVo attendantImgVo=new AttendantImgVo(); //随机查询一个跟班 AttenDant attenDant = attendantService.queryAttendant(); //放入对象 attendantImgVo.setWeChatHeadImgUrl(attenDant.getAtImg()); attendantImg.add(attendantImgVo); } //等于0就是用户跟班 if(attendantGoods.get(i).getAttendantId()==0){ AttendantImgVo attendantImgVo=new AttendantImgVo(); attendantImgVo.setWeChatHeadImgUrl(attendantGoods.get(i).getWeChatHeadImgUrl()); attendantImg.add(attendantImgVo); } } } //统计出所有物品的数量 List<AttendantPutVo> attendantPutVos = produceMapper.queryOutput(userId); List<ImgNumVo> collect = attendantPutVos.stream() .collect(Collectors.groupingBy(AttendantPutVo::getImgUrl, Collectors.summingInt(AttendantPutVo::getNumber))) .entrySet().stream().map(a -> new ImgNumVo(a.getKey(), a.getValue())).collect(Collectors.toList()); //查询到所有用户跟班 List<AttUserAllInfoVo> list1 = attendantMapper.queryThreeAtt(userId, 1); map.put("Img",attendantGoods); if(attendantPutVos.size()==0){ //1代表没有 map.put("status",0); map.put("attendantPutVos","暂无产出,快去抓跟班吧"); }else{ //0代表有产出 map.put("status",1); map.put("attendantPutVos",collect); } return map; } @Override public List<AttendantPutVo> queryOutput(Long userId) { //查询所有要返回的跟班数据 return produceMapper.queryOutput(userId); } @Override public int deleteOutGoodNumber(Long id) { return produceMapper.deleteById(id); } @Override public void deletePut(Long userId, Long aId) { //先查询id集合 List<ProduceSelectVo> list = baseMapper.queryAllIdList(userId, aId); if (null == list || list.size() == 0) { return; } //删除产出表信息 Integer integer = baseMapper.deleteProduce(list); if (integer <= 0) { throw new ApplicationException(CodeType.SERVICE_ERROR, "删除出错"); } //删除产出 Integer integer1 = baseMapper.deleteProduceUser(list); if (integer1 <= 0) { throw new ApplicationException(CodeType.SERVICE_ERROR, "删除出错"); } } @Override public void getPut() { UserLoginQuery user = localUser.getUser(); int much = 12; //获取当前时间 LocalDateTime now = LocalDateTime.now(); List<AttendantUser> attendantUsers = attendantUserService.queryListByUserId(user.getId()); List<Produce> produceList = new ArrayList<>(); List<UserProduce> userProduceList = new ArrayList<>(); List<ProduceBO> atuIdList = new ArrayList<>(); for (AttendantUser attendantUser : attendantUsers) { ProduceBO bo = new ProduceBO(); if (attendantUser.getAttMuch() == null) { attendantUser.setAttMuch(0); } //跟班的最后时间 LocalDateTime time = DateUtils.parseDateTime(attendantUser.getEndDate()); int until = (int)now.until(time, ChronoUnit.HOURS); if (attendantUser.getAttMuch() == much) { //次数够了直接返回 return; } if (until <= 0) { //查看数据库之前产出的次数 for (int i = 0; i < much - attendantUser.getAttMuch(); i++) { ProducePutBO put = put(user.getId(), attendantUser.getAttendantId(), attendantUser.getAtuId()); Produce produce = put.getProduce(); UserProduce userProduce = put.getUserProduce(); produceList.add(produce); userProduceList.add(userProduce); } bo.setMuch(much); } if (until > 0) { for (int i = 0; i < much - attendantUser.getAttMuch() - until; i++) { //产出 ProducePutBO putBO = put(user.getId(), attendantUser.getAttendantId(), attendantUser.getAtuId()); Produce produce = putBO.getProduce(); UserProduce userProduce = putBO.getUserProduce(); produceList.add(produce); userProduceList.add(userProduce); } bo.setMuch(much - until); } bo.setAttId(attendantUser.getAtuId()); atuIdList.add(bo); } //批量增加到数据库 if (produceList.size() > 0) { Integer integer = baseMapper.allInsertProduce(produceList); if (integer <= 0) { log.info("上线时批量增加产量出错"); throw new ApplicationException(CodeType.SERVICE_ERROR, "添加出错"); } } //批量增加用户产量 if (userProduceList.size() > 0) { userProduceService.allInsertUserProduce(userProduceList); } attendantUserService.updateProduce(atuIdList); } public ProducePutBO put(Long userId, Long attendantId, Long attUserId) { Goods goods = goodsService.queryOne(); Produce produce = new Produce(); Long produceId = idGenerator.getNumberId(); produce.setId(produceId); if (1L == attendantId || 2L == attendantId || 3L == attendantId) { produce.setAttendantId(attendantId); } else { produce.setAttendantId(0L); } produce.setAttUserId(attUserId); int number; //算出随机生成的数量 if (GOOD_NAME.equals(goods.getName())) { //随机生成1000-2000的金币 number = (int) (Math.random() * (2000 - 1000 + 1)) + 1000; } else { //随机生成1-3的随机数 number = (int) (Math.random() * (3 - 1 + 1)) + 1; } produce.setNumber(number); produce.setGoodId(goods.getId()); //默认0 produce.setStatus(0); UserProduce userProduce = new UserProduce(); userProduce.setUserId(userId); userProduce.setProduceId(produceId); ProducePutBO producePutBO = new ProducePutBO(); producePutBO.setProduce(produce); producePutBO.setUserProduce(userProduce); return producePutBO; } }
UTF-8
Java
12,959
java
ProduceServiceImpl.java
Java
[ { "context": ";\nimport java.util.stream.Stream;\n\n/**\n * @author 刘梦祺\n * @PROJECT_NAME: game_project\n * @DESCRIPTION:\n ", "end": 1743, "score": 0.9998167157173157, "start": 1740, "tag": "NAME", "value": "刘梦祺" } ]
null
[]
package com.dkm.produce.service.impl; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.dkm.attendant.dao.AttendantMapper; import com.dkm.attendant.dao.AttendantUserMapper; import com.dkm.attendant.entity.AttenDant; import com.dkm.attendant.entity.AttendantUser; import com.dkm.attendant.entity.bo.ProducePutBO; import com.dkm.attendant.entity.vo.AttUserAllInfoVo; import com.dkm.attendant.service.IAttendantService; import com.dkm.attendant.service.IAttendantUserService; import com.dkm.config.RedisConfig; import com.dkm.constanct.CodeType; import com.dkm.entity.websocket.MsgInfo; import com.dkm.exception.ApplicationException; import com.dkm.good.entity.Goods; import com.dkm.good.service.IGoodsService; import com.dkm.jwt.contain.LocalUser; import com.dkm.jwt.entity.UserLoginQuery; import com.dkm.plunder.entity.UserProduce; import com.dkm.plunder.service.IUserProduceService; import com.dkm.produce.dao.ProduceMapper; import com.dkm.produce.entity.Produce; import com.dkm.produce.entity.bo.ProduceBO; import com.dkm.produce.entity.vo.*; import com.dkm.produce.service.IProduceService; import com.dkm.utils.DateUtils; import com.dkm.utils.IdGenerator; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author 刘梦祺 * @PROJECT_NAME: game_project * @DESCRIPTION: * @DATE: 2020/5/19 21:26 */ @Service @Slf4j @Transactional(rollbackFor = Exception.class) public class ProduceServiceImpl extends ServiceImpl<ProduceMapper, Produce> implements IProduceService { @Autowired private IdGenerator idGenerator; @Autowired private LocalUser localUser; @Autowired private IGoodsService goodsService; @Autowired private IUserProduceService userProduceService; @Autowired private ProduceMapper produceMapper; @Autowired private AttendantMapper attendantMapper; @Autowired private IAttendantUserService attendantUserService; @Autowired private IAttendantService attendantService; @Autowired private RabbitTemplate rabbitTemplate; /** * 物品金币 */ private String GOOD_NAME = "金币"; @Override public Map<String,Object> insertProduce(Long attendantId, Long attUserId) { UserLoginQuery user = localUser.getUser(); //查询时间有没有过期 LocalDateTime now = LocalDateTime.now(); //用户跟班信息 AttendantUser attUser = attendantUserService.queryAttUser(attUserId); if (attUser == null) { throw new ApplicationException(CodeType.SERVICE_ERROR, "attUserId传错了..大哥"); } //得到结束时间 String endDate = attUser.getEndDate(); LocalDateTime time = DateUtils.parseDateTime(endDate); //时间差 long until = now.until(time, ChronoUnit.SECONDS); if (until <= 0) { throw new ApplicationException(CodeType.SERVICE_ERROR, "产出时间已过期"); } //随机返回物品 Goods goods = goodsService.queryRandomGoods(); //产出对象 Produce produce = new Produce(); Long produceId = idGenerator.getNumberId(); produce.setId(produceId); if (1L == attendantId || 2L == attendantId || 3L == attendantId) { //系统跟班 produce.setAttendantId(attendantId); } else { //用户跟班 produce.setAttendantId(0L); } produce.setAttUserId(attUserId); int number; //算出随机生成的数量 if (GOOD_NAME.equals(goods.getName())) { //随机生成1000-2000的金币 number = (int) (Math.random() * (2000 - 1000 + 1)) + 1000; } else { //随机生成2-6的随机数 number = (int) (Math.random() * (6 - 2 + 2)) + 2; } produce.setNumber(number); produce.setGoodId(goods.getId()); //默认0 produce.setStatus(0); int insert = baseMapper.insert(produce); if (insert <= 0) { log.info("添加产出有误"); throw new ApplicationException(CodeType.SERVICE_ERROR); } UserProduce userProduce = new UserProduce(); userProduce.setUserId(user.getId()); userProduce.setProduceId(produceId); //添加用户产出 userProduceService.insertProduce(userProduce); //增加产出次数 attendantService.updateMuch(attUserId, 0); //返回随机生成的物品给前端 Map<String, Object> map = new HashMap<>(2); map.put("goods", goods); map.put("number",number); //事件通知产出 MsgInfo msgInfo = new MsgInfo(); msgInfo.setMsg("跟班产出事件"); msgInfo.setType(8); msgInfo.setMsgType(1); msgInfo.setToId(user.getId()); log.info("发送事件通知..."); rabbitTemplate.convertAndSend("game_event_notice", JSON.toJSONString(msgInfo)); return map; } @Override public Map<String,Object> queryImgFood(Long userId) { Map<String,Object> map=new HashMap<>(16); //跟班 List<AttendantImgVo> attendantImg = new ArrayList<>(); //查询出所有用户跟班图片 List<AttendantImgVo> attendantGoods = produceMapper.queryImgFood(userId); if(attendantGoods.size()==0){ map.put("msg","暂无跟班 快去抓跟班吧"); map.put("status",2); return map; } if(attendantGoods.size()!=0){ for (int i = 0; i < attendantGoods.size(); i++) { //不等于0说明是系统跟班 随机查询出一个跟班 放入集合 if(attendantGoods.get(i).getAttendantId()!=0){ AttendantImgVo attendantImgVo=new AttendantImgVo(); //随机查询一个跟班 AttenDant attenDant = attendantService.queryAttendant(); //放入对象 attendantImgVo.setWeChatHeadImgUrl(attenDant.getAtImg()); attendantImg.add(attendantImgVo); } //等于0就是用户跟班 if(attendantGoods.get(i).getAttendantId()==0){ AttendantImgVo attendantImgVo=new AttendantImgVo(); attendantImgVo.setWeChatHeadImgUrl(attendantGoods.get(i).getWeChatHeadImgUrl()); attendantImg.add(attendantImgVo); } } } //统计出所有物品的数量 List<AttendantPutVo> attendantPutVos = produceMapper.queryOutput(userId); List<ImgNumVo> collect = attendantPutVos.stream() .collect(Collectors.groupingBy(AttendantPutVo::getImgUrl, Collectors.summingInt(AttendantPutVo::getNumber))) .entrySet().stream().map(a -> new ImgNumVo(a.getKey(), a.getValue())).collect(Collectors.toList()); //查询到所有用户跟班 List<AttUserAllInfoVo> list1 = attendantMapper.queryThreeAtt(userId, 1); map.put("Img",attendantGoods); if(attendantPutVos.size()==0){ //1代表没有 map.put("status",0); map.put("attendantPutVos","暂无产出,快去抓跟班吧"); }else{ //0代表有产出 map.put("status",1); map.put("attendantPutVos",collect); } return map; } @Override public List<AttendantPutVo> queryOutput(Long userId) { //查询所有要返回的跟班数据 return produceMapper.queryOutput(userId); } @Override public int deleteOutGoodNumber(Long id) { return produceMapper.deleteById(id); } @Override public void deletePut(Long userId, Long aId) { //先查询id集合 List<ProduceSelectVo> list = baseMapper.queryAllIdList(userId, aId); if (null == list || list.size() == 0) { return; } //删除产出表信息 Integer integer = baseMapper.deleteProduce(list); if (integer <= 0) { throw new ApplicationException(CodeType.SERVICE_ERROR, "删除出错"); } //删除产出 Integer integer1 = baseMapper.deleteProduceUser(list); if (integer1 <= 0) { throw new ApplicationException(CodeType.SERVICE_ERROR, "删除出错"); } } @Override public void getPut() { UserLoginQuery user = localUser.getUser(); int much = 12; //获取当前时间 LocalDateTime now = LocalDateTime.now(); List<AttendantUser> attendantUsers = attendantUserService.queryListByUserId(user.getId()); List<Produce> produceList = new ArrayList<>(); List<UserProduce> userProduceList = new ArrayList<>(); List<ProduceBO> atuIdList = new ArrayList<>(); for (AttendantUser attendantUser : attendantUsers) { ProduceBO bo = new ProduceBO(); if (attendantUser.getAttMuch() == null) { attendantUser.setAttMuch(0); } //跟班的最后时间 LocalDateTime time = DateUtils.parseDateTime(attendantUser.getEndDate()); int until = (int)now.until(time, ChronoUnit.HOURS); if (attendantUser.getAttMuch() == much) { //次数够了直接返回 return; } if (until <= 0) { //查看数据库之前产出的次数 for (int i = 0; i < much - attendantUser.getAttMuch(); i++) { ProducePutBO put = put(user.getId(), attendantUser.getAttendantId(), attendantUser.getAtuId()); Produce produce = put.getProduce(); UserProduce userProduce = put.getUserProduce(); produceList.add(produce); userProduceList.add(userProduce); } bo.setMuch(much); } if (until > 0) { for (int i = 0; i < much - attendantUser.getAttMuch() - until; i++) { //产出 ProducePutBO putBO = put(user.getId(), attendantUser.getAttendantId(), attendantUser.getAtuId()); Produce produce = putBO.getProduce(); UserProduce userProduce = putBO.getUserProduce(); produceList.add(produce); userProduceList.add(userProduce); } bo.setMuch(much - until); } bo.setAttId(attendantUser.getAtuId()); atuIdList.add(bo); } //批量增加到数据库 if (produceList.size() > 0) { Integer integer = baseMapper.allInsertProduce(produceList); if (integer <= 0) { log.info("上线时批量增加产量出错"); throw new ApplicationException(CodeType.SERVICE_ERROR, "添加出错"); } } //批量增加用户产量 if (userProduceList.size() > 0) { userProduceService.allInsertUserProduce(userProduceList); } attendantUserService.updateProduce(atuIdList); } public ProducePutBO put(Long userId, Long attendantId, Long attUserId) { Goods goods = goodsService.queryOne(); Produce produce = new Produce(); Long produceId = idGenerator.getNumberId(); produce.setId(produceId); if (1L == attendantId || 2L == attendantId || 3L == attendantId) { produce.setAttendantId(attendantId); } else { produce.setAttendantId(0L); } produce.setAttUserId(attUserId); int number; //算出随机生成的数量 if (GOOD_NAME.equals(goods.getName())) { //随机生成1000-2000的金币 number = (int) (Math.random() * (2000 - 1000 + 1)) + 1000; } else { //随机生成1-3的随机数 number = (int) (Math.random() * (3 - 1 + 1)) + 1; } produce.setNumber(number); produce.setGoodId(goods.getId()); //默认0 produce.setStatus(0); UserProduce userProduce = new UserProduce(); userProduce.setUserId(userId); userProduce.setProduceId(produceId); ProducePutBO producePutBO = new ProducePutBO(); producePutBO.setProduce(produce); producePutBO.setUserProduce(userProduce); return producePutBO; } }
12,959
0.611261
0.601604
402
29.395523
25.75169
124
false
false
0
0
0
0
0
0
0.549751
false
false
15
ab8c1d68f039754a419839df577c5ad3f5d34e51
5,102,421,206,373
b25e11292088c3090b1cc49064abbb244b8fc879
/src/test/java/ru/appline/rencreditFramework/tests/ParametrizedDepositTest.java
38e6c233c55150009fcec581c893b927acfc4193
[]
no_license
toshkanchik/RenCredit
https://github.com/toshkanchik/RenCredit
f40151be511b9f5e84731ba39da1c13ad7ccc264
9609b8b9666d318224cfd219e652cddd09a39cc9
refs/heads/master
2023-03-13T05:15:47.779000
2021-02-18T21:33:09
2021-02-18T21:33:09
340,182,935
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.appline.rencreditFramework.tests; import org.junit.jupiter.api.Tag; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvFileSource; import ru.appline.rencreditFramework.baseClasses.BaseTestClass; import ru.appline.rencreditFramework.utils.Currencies; public class ParametrizedDepositTest extends BaseTestClass{ @Tag("DepositTest") @ParameterizedTest(name = "Тестирование вклада {0}") @CsvFileSource(delimiter='|', resources = "/TestsData.csv") public void startTest(Currencies curr, String summ, String monthly, int months, boolean capitalization, String earned, String Replanish, String main){ pages.getStartPage() .clickOnMainOption("Вклады"); pages.getDepositPage() .chooseCurrency(curr) .fillInTextField("Сумма вклада", summ) .fillInTextField("Ежемесячное пополнение", monthly) .fillInDropDownField("На срок", months) .clickCheckboxName("Ежемесячная капитализация", capitalization) .checkEarned(earned) .checkReplenish(Replanish) .checkMainResult(main) ; } }
UTF-8
Java
1,322
java
ParametrizedDepositTest.java
Java
[]
null
[]
package ru.appline.rencreditFramework.tests; import org.junit.jupiter.api.Tag; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvFileSource; import ru.appline.rencreditFramework.baseClasses.BaseTestClass; import ru.appline.rencreditFramework.utils.Currencies; public class ParametrizedDepositTest extends BaseTestClass{ @Tag("DepositTest") @ParameterizedTest(name = "Тестирование вклада {0}") @CsvFileSource(delimiter='|', resources = "/TestsData.csv") public void startTest(Currencies curr, String summ, String monthly, int months, boolean capitalization, String earned, String Replanish, String main){ pages.getStartPage() .clickOnMainOption("Вклады"); pages.getDepositPage() .chooseCurrency(curr) .fillInTextField("Сумма вклада", summ) .fillInTextField("Ежемесячное пополнение", monthly) .fillInDropDownField("На срок", months) .clickCheckboxName("Ежемесячная капитализация", capitalization) .checkEarned(earned) .checkReplenish(Replanish) .checkMainResult(main) ; } }
1,322
0.673139
0.67233
28
42.142857
30.99391
154
false
false
0
0
0
0
0
0
0.75
false
false
15
333dbcafb07afed8599d6fa04c29c5a2a1801a92
23,029,614,670,947
3b3c2a3ad7dc1f754950c6f868d30f01dac75e3a
/app/src/main/java/app/doctor/dmcx/app/da/project/doctorapp/Controller/PrescriptionController.java
ee9acf54d2438de764c99f6358bf1c37c6de78dd
[]
no_license
cmplxty/DoctorApp_Doctor
https://github.com/cmplxty/DoctorApp_Doctor
04c3489a609b4b139a9ad27d88921b33ec9d7b1b
241a895c0a6e2fe47d77e3680aab6125119f8a70
refs/heads/master
2020-04-02T00:40:43.629000
2018-12-11T05:47:08
2018-12-11T05:47:11
153,816,266
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package app.doctor.dmcx.app.da.project.doctorapp.Controller; import android.widget.Toast; import java.util.HashMap; import java.util.Map; import app.doctor.dmcx.app.da.project.doctorapp.Common.RefActivity; import app.doctor.dmcx.app.da.project.doctorapp.Firebase.AFModel; import app.doctor.dmcx.app.da.project.doctorapp.Interface.ICallback; import app.doctor.dmcx.app.da.project.doctorapp.Interface.IAction; import app.doctor.dmcx.app.da.project.doctorapp.Model.Prescription; import app.doctor.dmcx.app.da.project.doctorapp.Utility.LoadingDialog; import app.doctor.dmcx.app.da.project.doctorapp.Utility.LoadingText; import app.doctor.dmcx.app.da.project.doctorapp.Variables.Vars; public class PrescriptionController { public static void SendPrescription(final Prescription prescription) { Map<String, Object> prescriptionMap = new HashMap<>(); prescriptionMap.put(AFModel.prescription_variables.doctor_id, prescription.getDoctor_id()); prescriptionMap.put(AFModel.prescription_variables.patient_id, prescription.getPatient_id()); prescriptionMap.put(AFModel.prescription_variables.doctor_name, prescription.getDoctor_name()); prescriptionMap.put(AFModel.prescription_variables.patient_name, prescription.getPatient_name()); prescriptionMap.put(AFModel.prescription_variables.patient_phone, prescription.getPatient_phone()); prescriptionMap.put(AFModel.prescription_variables.patient_age, prescription.getPatient_age()); prescriptionMap.put(AFModel.prescription_variables.patient_address, prescription.getPatient_address()); prescriptionMap.put(AFModel.prescription_variables.date, prescription.getDate()); prescriptionMap.put(AFModel.prescription_variables.medicines, prescription.getMedicines()); prescriptionMap.put(AFModel.prescription_variables.timestamp, prescription.getTimestamp()); Map<String, Object> updateMap = new HashMap<>(); updateMap.put(prescription.getDoctor_id() + "/" + prescription.getPatient_id() + "/" + Vars.appFirebase.getPushId(), prescriptionMap); updateMap.put(prescription.getPatient_id() + "/" + Vars.appFirebase.getPushId(), prescriptionMap); Vars.appFirebase.savePrescription(updateMap, new ICallback() { @Override public void onCallback(boolean isSuccessful, Object object) { if (object instanceof String) Toast.makeText(RefActivity.refACActivity.get(), String.valueOf(object), Toast.LENGTH_SHORT).show(); if (isSuccessful) { MessageController.SendMessagePrescription(prescription.getPatient_id(), prescription.getTimestamp()); } } }); } public static void LoadSinglePrescription(String patientId, String timestamp, final IAction action) { LoadingDialog.start(LoadingText.PleaseWait); Vars.appFirebase.loadSpecificPrescription(patientId, timestamp, new ICallback() { @Override public void onCallback(boolean isSuccessful, Object object) { LoadingDialog.stop(); if (isSuccessful) { action.onCompleteAction(object); } else { if (object instanceof String) Toast.makeText(RefActivity.refACActivity.get(), String.valueOf(object), Toast.LENGTH_SHORT).show(); } } }); } public static void LoadAllPrescriptionPatients(final IAction action) { Vars.appFirebase.loadPrescriptionPatients(new ICallback() { @Override public void onCallback(boolean isSuccessful, Object object) { if (object instanceof String) { action.onCompleteAction(null); Toast.makeText(RefActivity.refACActivity.get(), String.valueOf(object), Toast.LENGTH_SHORT).show(); } else { action.onCompleteAction(object); } } }); } public static void LoadSinglePatientPrescriptions(String patientId, final IAction action) { Vars.appFirebase.loadSpecificPatientPrescriptions(patientId, new ICallback() { @Override public void onCallback(boolean isSuccessful, Object object) { action.onCompleteAction(object); } }); } }
UTF-8
Java
4,412
java
PrescriptionController.java
Java
[]
null
[]
package app.doctor.dmcx.app.da.project.doctorapp.Controller; import android.widget.Toast; import java.util.HashMap; import java.util.Map; import app.doctor.dmcx.app.da.project.doctorapp.Common.RefActivity; import app.doctor.dmcx.app.da.project.doctorapp.Firebase.AFModel; import app.doctor.dmcx.app.da.project.doctorapp.Interface.ICallback; import app.doctor.dmcx.app.da.project.doctorapp.Interface.IAction; import app.doctor.dmcx.app.da.project.doctorapp.Model.Prescription; import app.doctor.dmcx.app.da.project.doctorapp.Utility.LoadingDialog; import app.doctor.dmcx.app.da.project.doctorapp.Utility.LoadingText; import app.doctor.dmcx.app.da.project.doctorapp.Variables.Vars; public class PrescriptionController { public static void SendPrescription(final Prescription prescription) { Map<String, Object> prescriptionMap = new HashMap<>(); prescriptionMap.put(AFModel.prescription_variables.doctor_id, prescription.getDoctor_id()); prescriptionMap.put(AFModel.prescription_variables.patient_id, prescription.getPatient_id()); prescriptionMap.put(AFModel.prescription_variables.doctor_name, prescription.getDoctor_name()); prescriptionMap.put(AFModel.prescription_variables.patient_name, prescription.getPatient_name()); prescriptionMap.put(AFModel.prescription_variables.patient_phone, prescription.getPatient_phone()); prescriptionMap.put(AFModel.prescription_variables.patient_age, prescription.getPatient_age()); prescriptionMap.put(AFModel.prescription_variables.patient_address, prescription.getPatient_address()); prescriptionMap.put(AFModel.prescription_variables.date, prescription.getDate()); prescriptionMap.put(AFModel.prescription_variables.medicines, prescription.getMedicines()); prescriptionMap.put(AFModel.prescription_variables.timestamp, prescription.getTimestamp()); Map<String, Object> updateMap = new HashMap<>(); updateMap.put(prescription.getDoctor_id() + "/" + prescription.getPatient_id() + "/" + Vars.appFirebase.getPushId(), prescriptionMap); updateMap.put(prescription.getPatient_id() + "/" + Vars.appFirebase.getPushId(), prescriptionMap); Vars.appFirebase.savePrescription(updateMap, new ICallback() { @Override public void onCallback(boolean isSuccessful, Object object) { if (object instanceof String) Toast.makeText(RefActivity.refACActivity.get(), String.valueOf(object), Toast.LENGTH_SHORT).show(); if (isSuccessful) { MessageController.SendMessagePrescription(prescription.getPatient_id(), prescription.getTimestamp()); } } }); } public static void LoadSinglePrescription(String patientId, String timestamp, final IAction action) { LoadingDialog.start(LoadingText.PleaseWait); Vars.appFirebase.loadSpecificPrescription(patientId, timestamp, new ICallback() { @Override public void onCallback(boolean isSuccessful, Object object) { LoadingDialog.stop(); if (isSuccessful) { action.onCompleteAction(object); } else { if (object instanceof String) Toast.makeText(RefActivity.refACActivity.get(), String.valueOf(object), Toast.LENGTH_SHORT).show(); } } }); } public static void LoadAllPrescriptionPatients(final IAction action) { Vars.appFirebase.loadPrescriptionPatients(new ICallback() { @Override public void onCallback(boolean isSuccessful, Object object) { if (object instanceof String) { action.onCompleteAction(null); Toast.makeText(RefActivity.refACActivity.get(), String.valueOf(object), Toast.LENGTH_SHORT).show(); } else { action.onCompleteAction(object); } } }); } public static void LoadSinglePatientPrescriptions(String patientId, final IAction action) { Vars.appFirebase.loadSpecificPatientPrescriptions(patientId, new ICallback() { @Override public void onCallback(boolean isSuccessful, Object object) { action.onCompleteAction(object); } }); } }
4,412
0.682457
0.682457
89
48.573032
39.371719
142
false
false
0
0
0
0
0
0
0.808989
false
false
15
9738460c730125cfdd17798067340ab5fa72fa7d
21,148,419,000,584
6235d3b43a49a6d7fea4344300874e8e6853f020
/src/main/java/com/google/common/collect/ch.java
b9709b6055010acb339acdb54ae3a58b15514637
[]
no_license
junges521/src_awe
https://github.com/junges521/src_awe
a12bcfeb6c62bd55afba7147b83f4e3df8797019
cff4a5e230f3346f493df79744e6f2a6f20a47e2
refs/heads/master
2020-07-13T19:37:36.253000
2019-08-29T10:47:51
2019-08-29T10:47:51
205,140,726
0
0
null
true
2019-08-29T10:41:58
2019-08-29T10:41:58
2019-08-29T08:24:29
2019-08-23T11:31:27
177,015
0
0
0
null
false
false
package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.ListIterator; @GwtCompatible public abstract class ch<E> extends cg<E> implements ListIterator<E> { protected ch() { } @Deprecated public final void add(E e2) { throw new UnsupportedOperationException(); } @Deprecated public final void set(E e2) { throw new UnsupportedOperationException(); } }
UTF-8
Java
451
java
ch.java
Java
[]
null
[]
package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.ListIterator; @GwtCompatible public abstract class ch<E> extends cg<E> implements ListIterator<E> { protected ch() { } @Deprecated public final void add(E e2) { throw new UnsupportedOperationException(); } @Deprecated public final void set(E e2) { throw new UnsupportedOperationException(); } }
451
0.698448
0.694013
20
21.549999
20.698973
70
false
false
0
0
0
0
0
0
0.25
false
false
15