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
1a0874f11a93e64bfed348fc56692c9873e9d18b
39,427,799,791,941
97aeffaf9f475150ff48936c126bd3581b710872
/Algorithms/src/test/java/medium/s/SpiralMatrixTwoTest.java
cc16b642c3a712c31812c88c3478126e287fde89
[ "MIT" ]
permissive
jsong00505/LeetCode
https://github.com/jsong00505/LeetCode
c3c874ac6a115702912ba9871fcf818f22303782
7eae1df4dfa88de6e7435f6238199d92d42c7032
refs/heads/master
2021-01-13T08:54:05.363000
2019-05-06T06:09:24
2019-05-06T06:09:24
177,471,840
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package medium.s; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class SpiralMatrixTwoTest { private SpiralMatrixTwo spiralMatrixTwo; @Before public void setUp() { spiralMatrixTwo = new SpiralMatrixTwo(); } @Test public void generateMatrix() { // test input int n = 3; // set expected value int[][] expected = {{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}; // perform test int[][] actual = spiralMatrixTwo.generateMatrix(n); // assertion assertArrayEquals(expected, actual); } }
UTF-8
Java
568
java
SpiralMatrixTwoTest.java
Java
[]
null
[]
package medium.s; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class SpiralMatrixTwoTest { private SpiralMatrixTwo spiralMatrixTwo; @Before public void setUp() { spiralMatrixTwo = new SpiralMatrixTwo(); } @Test public void generateMatrix() { // test input int n = 3; // set expected value int[][] expected = {{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}; // perform test int[][] actual = spiralMatrixTwo.generateMatrix(n); // assertion assertArrayEquals(expected, actual); } }
568
0.646127
0.628521
31
17.32258
17.315641
57
false
false
0
0
0
0
0
0
0.612903
false
false
13
979e81f894f25fc797846c4a05427002052462f2
37,795,712,228,942
47e9dbaae1836ec92bec473fe54c576344446636
/amwayGo/core/src/main/java/com/_4csoft/aof/ui/univ/vo/UIUnivSurveyPaperElementVO.java
a73a0fd7cd0e2983d50b7a0f738910dc6a2204f1
[]
no_license
nhjmaster/aa
https://github.com/nhjmaster/aa
3973719f2f2d5a3ccd98a3b315490c83c87819a5
7368551361a12756a5cf8ad2af50760a8c67189f
refs/heads/master
2018-01-12T18:48:36.949000
2017-03-02T15:02:25
2017-03-02T15:02:25
83,664,424
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 1999 4CSoft Inc. All right reserved. * This software is the proprietary information of 4CSoft Inc. * */ package com._4csoft.aof.ui.univ.vo; import java.io.Serializable; import com._4csoft.aof.univ.vo.UnivSurveyPaperElementVO; /** * @Project : aof5-univ-ui-core * @Package : com._4csoft.aof.ui.univ.vo * @File : UIUnivSurveyPaperElementVO.java * @Title : {๊ฐ„๋‹จํ•œ ํ”„๋กœ๊ทธ๋žจ์˜ ๋ช…์นญ์„ ๊ธฐ๋ก} * @date : 2014. 2. 21. * @author : ์ดํ•œ๊ตฌ * @descrption : {์ƒ์„ธํ•œ ํ”„๋กœ๊ทธ๋žจ์˜ ์šฉ๋„๋ฅผ ๊ธฐ๋ก} */ public class UIUnivSurveyPaperElementVO extends UnivSurveyPaperElementVO implements Serializable { private static final long serialVersionUID = 1L; /** ๋ณต์ˆ˜ ์ €์žฅ ๋ฐ ์‚ญ์ œ์‹œ ์‚ฌ์šฉํ•  ๋ณ€์ˆ˜ */ private Long[] surveyPaperSeqs; /** ๋ณต์ˆ˜ ์ €์žฅ ๋ฐ ์‚ญ์ œ์‹œ ์‚ฌ์šฉํ•  ๋ณ€์ˆ˜ */ private Long[] surveySeqs; /** ๋ณต์ˆ˜ ์ €์žฅ ๋ฐ ์‚ญ์ œ์‹œ ์‚ฌ์šฉํ•  ๋ณ€์ˆ˜์ˆ˜ */ private Long[] sortOrders; public Long[] getSurveyPaperSeqs() { return surveyPaperSeqs; } public void setSurveyPaperSeqs(Long[] surveyPaperSeqs) { this.surveyPaperSeqs = surveyPaperSeqs; } public Long[] getSurveySeqs() { return surveySeqs; } public void setSurveySeqs(Long[] surveySeqs) { this.surveySeqs = surveySeqs; } public Long[] getSortOrders() { return sortOrders; } public void setSortOrders(Long[] sortOrders) { this.sortOrders = sortOrders; } }
UTF-8
Java
1,461
java
UIUnivSurveyPaperElementVO.java
Java
[ { "context": "๊ทธ๋žจ์˜ ๋ช…์นญ์„ ๊ธฐ๋ก}\r\n * @date : 2014. 2. 21.\r\n * @author : ์ดํ•œ๊ตฌ\r\n * @descrption : {์ƒ์„ธํ•œ ํ”„๋กœ๊ทธ๋žจ์˜ ์šฉ๋„๋ฅผ ๊ธฐ๋ก}\r\n */\r\npublic", "end": 460, "score": 0.99966961145401, "start": 457, "tag": "NAME", "value": "์ดํ•œ๊ตฌ" } ]
null
[]
/* * Copyright (c) 1999 4CSoft Inc. All right reserved. * This software is the proprietary information of 4CSoft Inc. * */ package com._4csoft.aof.ui.univ.vo; import java.io.Serializable; import com._4csoft.aof.univ.vo.UnivSurveyPaperElementVO; /** * @Project : aof5-univ-ui-core * @Package : com._4csoft.aof.ui.univ.vo * @File : UIUnivSurveyPaperElementVO.java * @Title : {๊ฐ„๋‹จํ•œ ํ”„๋กœ๊ทธ๋žจ์˜ ๋ช…์นญ์„ ๊ธฐ๋ก} * @date : 2014. 2. 21. * @author : ์ดํ•œ๊ตฌ * @descrption : {์ƒ์„ธํ•œ ํ”„๋กœ๊ทธ๋žจ์˜ ์šฉ๋„๋ฅผ ๊ธฐ๋ก} */ public class UIUnivSurveyPaperElementVO extends UnivSurveyPaperElementVO implements Serializable { private static final long serialVersionUID = 1L; /** ๋ณต์ˆ˜ ์ €์žฅ ๋ฐ ์‚ญ์ œ์‹œ ์‚ฌ์šฉํ•  ๋ณ€์ˆ˜ */ private Long[] surveyPaperSeqs; /** ๋ณต์ˆ˜ ์ €์žฅ ๋ฐ ์‚ญ์ œ์‹œ ์‚ฌ์šฉํ•  ๋ณ€์ˆ˜ */ private Long[] surveySeqs; /** ๋ณต์ˆ˜ ์ €์žฅ ๋ฐ ์‚ญ์ œ์‹œ ์‚ฌ์šฉํ•  ๋ณ€์ˆ˜์ˆ˜ */ private Long[] sortOrders; public Long[] getSurveyPaperSeqs() { return surveyPaperSeqs; } public void setSurveyPaperSeqs(Long[] surveyPaperSeqs) { this.surveyPaperSeqs = surveyPaperSeqs; } public Long[] getSurveySeqs() { return surveySeqs; } public void setSurveySeqs(Long[] surveySeqs) { this.surveySeqs = surveySeqs; } public Long[] getSortOrders() { return sortOrders; } public void setSortOrders(Long[] sortOrders) { this.sortOrders = sortOrders; } }
1,461
0.679516
0.665911
57
21.210526
21.410553
98
false
false
0
0
0
0
0
0
0.77193
false
false
13
480103391b8946973e9179a3c10309ddba20ffa7
36,627,481,136,066
f3108f73b2afda5a0046c36b604710482bec93e5
/High School/6-3/Test.java
5a7c086a716e1022d076231e0e0f28f0cdef9e16
[]
no_license
pwzzy6/java
https://github.com/pwzzy6/java
c5763a7da96d813e3dd7e07a424f6173b0de9b32
1944485013ff19e74591921d86b72a85b29cb568
refs/heads/master
2021-01-18T21:58:09.455000
2017-12-13T05:05:59
2017-12-13T05:05:59
41,615,753
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// ziyang zou // computer science project 6-3 // It's the main class for this project, it is used to test all the methods. public class Test{ public static void main(String [] args){ Fraction x = new Fraction(3, 4); Fraction y = new Fraction(5, 6); x.add(x, y); System.out.println(x.toString()); x.sub(x, y); System.out.println(x.toString()); x.mul(x, y); System.out.println(x.toString()); x.divide(x, y); System.out.println(x.toString()); } }
UTF-8
Java
495
java
Test.java
Java
[ { "context": "// ziyang zou\n// computer science project 6-3\n// It's the main ", "end": 13, "score": 0.9998418092727661, "start": 3, "tag": "NAME", "value": "ziyang zou" } ]
null
[]
// <NAME> // computer science project 6-3 // It's the main class for this project, it is used to test all the methods. public class Test{ public static void main(String [] args){ Fraction x = new Fraction(3, 4); Fraction y = new Fraction(5, 6); x.add(x, y); System.out.println(x.toString()); x.sub(x, y); System.out.println(x.toString()); x.mul(x, y); System.out.println(x.toString()); x.divide(x, y); System.out.println(x.toString()); } }
491
0.616162
0.60404
24
19.625
19.319275
76
false
false
0
0
0
0
0
0
0.708333
false
false
13
a9192c310a6adfa660532cb757413094d6ae6d69
9,904,194,648,116
94fbdbb5f17f5fba91fe81a19e02aafada47a41f
/src/main/java/servlets/MyOrders.java
4fd4de4fdbf5594146c28b78e6963eb5f0b901d1
[]
no_license
Solomka/test_library
https://github.com/Solomka/test_library
aa93e4aefd6d23f5d9abbdc6b34defb751930858
ee1f6860c2d2df77d33b011a66836db934c786bb
refs/heads/master
2021-01-25T10:57:43.007000
2017-06-09T22:45:55
2017-06-09T22:45:55
93,901,995
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package servlets; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.sun.org.apache.xalan.internal.xsltc.compiler.sym; import vo.Book; import vo.Order; import vo.User; import dao.BookDao; import dao.BookDaoImpl; import dao.OrderDao; import dao.OrderDaoImpl; /** * Servlet implementation class MyOrders */ public class MyOrders extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyOrders() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/jsp"); HttpSession session = request.getSession(false); User user = (User) session.getAttribute("user"); System.out.println("User id: "+ user.getId()); OrderDao orderDao = new OrderDaoImpl(); List<Order> orders = orderDao.getReaderOrders(user.getId()); System.out.println(orders.toString()); request.setAttribute("orders", orders); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/myOrders.jsp"); //redirect dispatcher.forward(request,response); } }
UTF-8
Java
1,639
java
MyOrders.java
Java
[]
null
[]
package servlets; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.sun.org.apache.xalan.internal.xsltc.compiler.sym; import vo.Book; import vo.Order; import vo.User; import dao.BookDao; import dao.BookDaoImpl; import dao.OrderDao; import dao.OrderDaoImpl; /** * Servlet implementation class MyOrders */ public class MyOrders extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyOrders() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/jsp"); HttpSession session = request.getSession(false); User user = (User) session.getAttribute("user"); System.out.println("User id: "+ user.getId()); OrderDao orderDao = new OrderDaoImpl(); List<Order> orders = orderDao.getReaderOrders(user.getId()); System.out.println(orders.toString()); request.setAttribute("orders", orders); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/myOrders.jsp"); //redirect dispatcher.forward(request,response); } }
1,639
0.744966
0.744356
60
26.316668
25.266903
118
false
false
0
0
0
0
0
0
1.2
false
false
13
6fee80fd2fc8f592200ce6c8a507b2e87bc7a4cc
38,594,576,146,462
3c5594f9028fa29eaeb3179bd3bbe61bda143866
/main.java
eaf3ef3e10d09349ce1104093a2e51d6c50bcbcf
[]
no_license
sachinprasad0011/LZWalgorithm
https://github.com/sachinprasad0011/LZWalgorithm
42635a28e9b83ef8997a3a5cc528cfb7c5fb5b10
d0ed7acc4bfd12d271ed451f202d0c33668a921b
refs/heads/master
2021-05-22T18:55:20.277000
2020-04-04T16:42:43
2020-04-04T16:42:43
253,048,331
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; public class main{ static Scanner sc=new Scanner(System.in); public static void main(String args[]) throws IOException{ while(true){ System.out.println("Which operation do you want to perform 1. Compression 2. Decompression "); int choice=sc.nextInt(); switch(choice){ case 1: try { LZWCompression lzw = new LZWCompression(); Scanner input = new Scanner(System.in); System.out.println("Enter the name of your (input.txt) file."); String str = input.nextLine(); File file = new File(str); Scanner fileScanner = new Scanner(file); String line = ""; long originalfileSize = file.length(); System.out.format("The size of the original file: %d bytes", originalfileSize); System.out.println(); int count=0; while(fileScanner.hasNext()){ fileScanner.next(); count++; } System.out.println("Number of words in the original file:"+count); while (fileScanner.hasNext()) { line = fileScanner.nextLine(); } long starttime=System.nanoTime(); lzw.compress(str); long stoptime=System.nanoTime(); long totaltime=(stoptime-starttime); System.out.println("\nCompression of your file is complete!"); System.out.println("Total time taken : "+totaltime/1000000000 + " seconds"); System.out.println("Your new file is named: " + str.concat(".lzw")); System.out.println(); break; } catch (FileNotFoundException e) { System.out.println("File was not found!"); } case 2: try { LZWDecompression lzw = new LZWDecompression(); Scanner input = new Scanner(System.in); System.out.println("Enter the name of your (input.txt.lzw) file."); String str = input.nextLine(); File file = new File(str); Scanner fileScanner = new Scanner(file); String line = ""; long compressedfileSize = file.length(); System.out.format("The size of the compressed file: %d bytes", compressedfileSize); System.out.println(); while (fileScanner.hasNext()) { line = fileScanner.nextLine(); System.out.println("Contents of your file being decompressed:\n"+ line); } long originalfilesize = file.length(); FileInputStream fis = new FileInputStream(file); byte[] byteArray = new byte[(int)file.length()]; fis.read(byteArray); String data = new String(byteArray); String[] stringArray = data.split("\r\n"); long stime=System.nanoTime(); lzw.LZW_Decompress(str); long sttime=System.nanoTime(); long tttime=(sttime-stime); System.out.println("Decompression of your file is complete!"); System.out.println("Total time take to Decompress : "+tttime/1000000000 +" seconds"); System.out.println("Your new file is named: "+ str.replace(".lzw", "")); System.out.println(); break; } catch (FileNotFoundException e) { System.out.println("File was not found!"); } } } } }
UTF-8
Java
3,697
java
main.java
Java
[]
null
[]
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; public class main{ static Scanner sc=new Scanner(System.in); public static void main(String args[]) throws IOException{ while(true){ System.out.println("Which operation do you want to perform 1. Compression 2. Decompression "); int choice=sc.nextInt(); switch(choice){ case 1: try { LZWCompression lzw = new LZWCompression(); Scanner input = new Scanner(System.in); System.out.println("Enter the name of your (input.txt) file."); String str = input.nextLine(); File file = new File(str); Scanner fileScanner = new Scanner(file); String line = ""; long originalfileSize = file.length(); System.out.format("The size of the original file: %d bytes", originalfileSize); System.out.println(); int count=0; while(fileScanner.hasNext()){ fileScanner.next(); count++; } System.out.println("Number of words in the original file:"+count); while (fileScanner.hasNext()) { line = fileScanner.nextLine(); } long starttime=System.nanoTime(); lzw.compress(str); long stoptime=System.nanoTime(); long totaltime=(stoptime-starttime); System.out.println("\nCompression of your file is complete!"); System.out.println("Total time taken : "+totaltime/1000000000 + " seconds"); System.out.println("Your new file is named: " + str.concat(".lzw")); System.out.println(); break; } catch (FileNotFoundException e) { System.out.println("File was not found!"); } case 2: try { LZWDecompression lzw = new LZWDecompression(); Scanner input = new Scanner(System.in); System.out.println("Enter the name of your (input.txt.lzw) file."); String str = input.nextLine(); File file = new File(str); Scanner fileScanner = new Scanner(file); String line = ""; long compressedfileSize = file.length(); System.out.format("The size of the compressed file: %d bytes", compressedfileSize); System.out.println(); while (fileScanner.hasNext()) { line = fileScanner.nextLine(); System.out.println("Contents of your file being decompressed:\n"+ line); } long originalfilesize = file.length(); FileInputStream fis = new FileInputStream(file); byte[] byteArray = new byte[(int)file.length()]; fis.read(byteArray); String data = new String(byteArray); String[] stringArray = data.split("\r\n"); long stime=System.nanoTime(); lzw.LZW_Decompress(str); long sttime=System.nanoTime(); long tttime=(sttime-stime); System.out.println("Decompression of your file is complete!"); System.out.println("Total time take to Decompress : "+tttime/1000000000 +" seconds"); System.out.println("Your new file is named: "+ str.replace(".lzw", "")); System.out.println(); break; } catch (FileNotFoundException e) { System.out.println("File was not found!"); } } } } }
3,697
0.549905
0.543143
100
34.970001
25.928152
102
false
false
0
0
0
0
0
0
0.64
false
false
13
327b9f54d18ba35ce89fa1f0f18e9b4d9ea1100a
39,290,360,866,246
ba81e1dc720ba8bfada8efc9eb95351ad2e0ea38
/livraria-core/src/livraria/core/IDAO.java
02dc4e51d4c60cff03f5bdf9cfd328108ebf352a
[]
no_license
edner-ferreira/les2019
https://github.com/edner-ferreira/les2019
c7e457485d6a50a7ae02e09bf032925cea5739c5
694e0ab62dfd7f75091f5efe37039cf52220b381
refs/heads/master
2021-01-04T00:41:02.296000
2020-02-13T16:59:15
2020-02-13T16:59:15
240,306,888
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package livraria.core; import ecommerce.dominio.EntidadeDominio; import livraria.core.aplicacao.Resultado; public interface IDAO { public Resultado inserir(EntidadeDominio entidade); public Resultado listar(EntidadeDominio entidade); public Resultado alterar(EntidadeDominio entidade); public Resultado desativar(EntidadeDominio entidade); public Resultado ativar(EntidadeDominio entidade); public Resultado consultar(EntidadeDominio entidade); }
UTF-8
Java
484
java
IDAO.java
Java
[]
null
[]
package livraria.core; import ecommerce.dominio.EntidadeDominio; import livraria.core.aplicacao.Resultado; public interface IDAO { public Resultado inserir(EntidadeDominio entidade); public Resultado listar(EntidadeDominio entidade); public Resultado alterar(EntidadeDominio entidade); public Resultado desativar(EntidadeDominio entidade); public Resultado ativar(EntidadeDominio entidade); public Resultado consultar(EntidadeDominio entidade); }
484
0.791322
0.791322
20
23.200001
24.502245
57
false
false
0
0
0
0
0
0
0.45
false
false
13
ddc01163355b20f078ddc137d30be320f7d27739
13,735,305,427,403
d19b06e9fc9cdbedd9616ebf31c4b84ad9519b40
/app/src/main/java/com/columbia/omnistore/bean/LiveScore/LiveDataBaseBean.java
9728e1cbcfc49cf372530e2dc3660d14adeb792f
[]
no_license
Britainnia/OmniStore
https://github.com/Britainnia/OmniStore
543f7d1ba0c49c38970e6d4408441f512819c2b9
0fc89cb017b68838c83dd6b913e1247232d0ec18
refs/heads/master
2018-12-25T05:08:52.175000
2018-10-18T10:12:15
2018-10-18T10:12:15
135,888,345
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.columbia.omnistore.bean.LiveScore; /** * LiveScoreๆŠฅ่กจๆ•ฐๆฎ็ฑป */ public class LiveDataBaseBean { public String id; public String storeID; public int target; public int sales; public double targetPer; public int lyActSales; public double lyActSalesPer; public int unitsSales; public int transactions; public int aur; public double upt; public int vpt; public int trafficTY; public int footFallsTY; public double captureRate; public double conversionRate; public String week; public String month; public String year; public String storeName; public double margin; @Override public String toString() { return "LiveDataBaseBean{" + "id='" + id + '\'' + ", storeID='" + storeID + '\'' + ", target='" + target + '\'' + ", sales='" + sales + '\'' + ", targetPer=" + targetPer + ", lyActSales='" + lyActSales + '\'' + ", lyActSalesPer=" + lyActSalesPer + ", unitsSales='" + unitsSales + '\'' + ", transactions='" + transactions + '\'' + ", aur='" + aur + '\'' + ", upt='" + upt + '\'' + ", vpt='" + vpt + '\'' + ", trafficTY='" + trafficTY + '\'' + ", footFallsTY='" + footFallsTY + '\'' + ", captureRate='" + captureRate + '\'' + ", conversionRate='" + conversionRate + '\'' + ", week='" + week + '\'' + ", month='" + month + '\'' + ", year='" + year + '\'' + ", storeName='" + storeName + '\'' + ", margin=" + margin + '}'; } }
UTF-8
Java
1,799
java
LiveDataBaseBean.java
Java
[]
null
[]
package com.columbia.omnistore.bean.LiveScore; /** * LiveScoreๆŠฅ่กจๆ•ฐๆฎ็ฑป */ public class LiveDataBaseBean { public String id; public String storeID; public int target; public int sales; public double targetPer; public int lyActSales; public double lyActSalesPer; public int unitsSales; public int transactions; public int aur; public double upt; public int vpt; public int trafficTY; public int footFallsTY; public double captureRate; public double conversionRate; public String week; public String month; public String year; public String storeName; public double margin; @Override public String toString() { return "LiveDataBaseBean{" + "id='" + id + '\'' + ", storeID='" + storeID + '\'' + ", target='" + target + '\'' + ", sales='" + sales + '\'' + ", targetPer=" + targetPer + ", lyActSales='" + lyActSales + '\'' + ", lyActSalesPer=" + lyActSalesPer + ", unitsSales='" + unitsSales + '\'' + ", transactions='" + transactions + '\'' + ", aur='" + aur + '\'' + ", upt='" + upt + '\'' + ", vpt='" + vpt + '\'' + ", trafficTY='" + trafficTY + '\'' + ", footFallsTY='" + footFallsTY + '\'' + ", captureRate='" + captureRate + '\'' + ", conversionRate='" + conversionRate + '\'' + ", week='" + week + '\'' + ", month='" + month + '\'' + ", year='" + year + '\'' + ", storeName='" + storeName + '\'' + ", margin=" + margin + '}'; } }
1,799
0.460593
0.460593
56
30.946428
16.280378
62
false
false
0
0
0
0
0
0
0.767857
false
false
13
42aead078e501ef8d6cccd0bcaeeff3fb4104627
31,241,592,116,706
11d2ecd283728b68fd30828e56e27ff58c1a3fcd
/Polynome/src/tpe/uib1/uebung1/PolynomTest.java
dce2a632b9ddc601c160f3cfb83d5e7b54472279
[]
no_license
myd-mannheim/try_git
https://github.com/myd-mannheim/try_git
79e5c5f3336c0ca8974cee88ebc137b54743a2eb
f5d573cc5ad48eca26facb6e54fa4a7fd99042d8
refs/heads/master
2016-08-04T12:14:15.197000
2013-05-15T16:10:18
2013-05-15T16:10:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tpe.uib1.uebung1; import static org.junit.Assert.*; import org.junit.Test; public class PolynomTest { @Test public void constructorTest(){ Polynom p1 = new Polynom(1.0, 1.0, 1.0); //TODO //fail( ); } @Test public void getGradTestGrad3(){ Polynom p1 = new Polynom(1.0, 0.0, 25.0, 300); assertEquals(3, p1.getGrad()); } @Test public void getGradTestGrad4(){ Polynom p1 = new Polynom(1.0, 0.0, 25.0, 300, 42.0); assertEquals(4, p1.getGrad()); } @Test public void differenziereTest(){ Polynom p1 = new Polynom(-10, 0.0, 0.5, -1, 2); Polynom p1_dif = p1.differenziere(); Polynom p1_ref = new Polynom(0.0, 1, -3, 8); assertEquals(p1_ref.toString(), p1_dif.toString()); } @Test public void integriereTest(){ Polynom p1 = new Polynom(0.0, 1, -3, 8); Polynom p1_int = p1.integriere(); Polynom p1_ref = new Polynom(0.0, 0.0, 0.5, -1, 2); assertEquals(p1_ref.toString(), p1_int.toString()); } @Test public void toStringTest(){ Polynom p1 = new Polynom(3.256, -2, 5, 0, -0.5, -4, 0, 0, -9); String ref = "Grad 8: -9x^8 -4x^5 -0.5x^4 + 5x^2 -2x + 3.26"; System.out.println(p1.toString()); assertEquals(ref, p1.toString()); } @Test public void equalsTest(){ Polynom p1 = new Polynom(3.0, -2, 5, 0, -0.5, -4, 0, 0, -9); Polynom p2 = new Polynom(3.0, -2, 5, 0, -0.5, -4, 0, 0, -9); assertTrue(p1.equals(p2)); } @Test public void berechneTest() { Polynom p1 = new Polynom(5, 0, -2, 0, 9.5, -8, 5); assertEquals(9.5, p1.berechne(1), 0); } @Test public void berechneArrayTest() { Polynom p1 = new Polynom(5, 0, -2, 0, 9.5, -8, 5); double[] results = {9.5, 25.5, 59017.5, 109017.5}; assertArrayEquals(results, p1.berechne(1, -1, 5, -5), 0); } @Test public void addiereTest(){ Polynom p1 = new Polynom(5, 4, -2, 3, 9.5, -8); Polynom p2 = new Polynom(3, 7, 6, -6, 0, 4, 7, 11); Polynom p1p2 = new Polynom(8, 11, 4, -3, 9.5, -4, 7, 11); assertEquals(p1p2.toString(), p1.addiere(p2).toString()); } @Test public void subtrahiereTest() { Polynom p1 = new Polynom(5, 4, -2, 3, 9.5, -8); Polynom p2 = new Polynom(3, 7, 6, -6, 0, 4, 7, 11); Polynom p1p2 = new Polynom(2, -3, -8, 9, 9.5, -12, -7, -11); assertEquals(p1p2.toString(), p1.subtrahiere(p2).toString()); } @Test public void subtrahiereTest2() { Polynom p1 = new Polynom(3, 7, 6, -6, 0, 4, 7, 11); Polynom p2 = new Polynom(5, 4, -2, 3, 9.5, -8); Polynom p1p2 = new Polynom(-2, +3, +8, -9, -9.5, +12, 7, 11); assertEquals(p1p2.toString(), p1.subtrahiere(p2).toString()); } }
UTF-8
Java
2,721
java
PolynomTest.java
Java
[]
null
[]
package tpe.uib1.uebung1; import static org.junit.Assert.*; import org.junit.Test; public class PolynomTest { @Test public void constructorTest(){ Polynom p1 = new Polynom(1.0, 1.0, 1.0); //TODO //fail( ); } @Test public void getGradTestGrad3(){ Polynom p1 = new Polynom(1.0, 0.0, 25.0, 300); assertEquals(3, p1.getGrad()); } @Test public void getGradTestGrad4(){ Polynom p1 = new Polynom(1.0, 0.0, 25.0, 300, 42.0); assertEquals(4, p1.getGrad()); } @Test public void differenziereTest(){ Polynom p1 = new Polynom(-10, 0.0, 0.5, -1, 2); Polynom p1_dif = p1.differenziere(); Polynom p1_ref = new Polynom(0.0, 1, -3, 8); assertEquals(p1_ref.toString(), p1_dif.toString()); } @Test public void integriereTest(){ Polynom p1 = new Polynom(0.0, 1, -3, 8); Polynom p1_int = p1.integriere(); Polynom p1_ref = new Polynom(0.0, 0.0, 0.5, -1, 2); assertEquals(p1_ref.toString(), p1_int.toString()); } @Test public void toStringTest(){ Polynom p1 = new Polynom(3.256, -2, 5, 0, -0.5, -4, 0, 0, -9); String ref = "Grad 8: -9x^8 -4x^5 -0.5x^4 + 5x^2 -2x + 3.26"; System.out.println(p1.toString()); assertEquals(ref, p1.toString()); } @Test public void equalsTest(){ Polynom p1 = new Polynom(3.0, -2, 5, 0, -0.5, -4, 0, 0, -9); Polynom p2 = new Polynom(3.0, -2, 5, 0, -0.5, -4, 0, 0, -9); assertTrue(p1.equals(p2)); } @Test public void berechneTest() { Polynom p1 = new Polynom(5, 0, -2, 0, 9.5, -8, 5); assertEquals(9.5, p1.berechne(1), 0); } @Test public void berechneArrayTest() { Polynom p1 = new Polynom(5, 0, -2, 0, 9.5, -8, 5); double[] results = {9.5, 25.5, 59017.5, 109017.5}; assertArrayEquals(results, p1.berechne(1, -1, 5, -5), 0); } @Test public void addiereTest(){ Polynom p1 = new Polynom(5, 4, -2, 3, 9.5, -8); Polynom p2 = new Polynom(3, 7, 6, -6, 0, 4, 7, 11); Polynom p1p2 = new Polynom(8, 11, 4, -3, 9.5, -4, 7, 11); assertEquals(p1p2.toString(), p1.addiere(p2).toString()); } @Test public void subtrahiereTest() { Polynom p1 = new Polynom(5, 4, -2, 3, 9.5, -8); Polynom p2 = new Polynom(3, 7, 6, -6, 0, 4, 7, 11); Polynom p1p2 = new Polynom(2, -3, -8, 9, 9.5, -12, -7, -11); assertEquals(p1p2.toString(), p1.subtrahiere(p2).toString()); } @Test public void subtrahiereTest2() { Polynom p1 = new Polynom(3, 7, 6, -6, 0, 4, 7, 11); Polynom p2 = new Polynom(5, 4, -2, 3, 9.5, -8); Polynom p1p2 = new Polynom(-2, +3, +8, -9, -9.5, +12, 7, 11); assertEquals(p1p2.toString(), p1.subtrahiere(p2).toString()); } }
2,721
0.565601
0.460125
102
24.67647
23.24514
66
false
false
0
0
0
0
0
0
2.862745
false
false
13
027331e3d13ea2afde8222a95270dd33223736d6
7,722,351,250,319
5def0e28122ac9312cb921afd28b7db2d26f8782
/src/pe/eth/Travisaapp/view/CategoriamanView.java
cf4397220b2103d3cc1d0741b811d3ade0213184
[]
no_license
canondegeminis/travisaApp
https://github.com/canondegeminis/travisaApp
b520ab1707bedd1edfd70b7e04490270c16619c2
1eff0677f3c9e0c036b03d7f1c15a3e2b7c345e7
refs/heads/master
2023-02-21T21:02:22.410000
2021-01-22T05:24:24
2021-01-22T05:24:24
331,845,578
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pe.eth.Travisaapp.view; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import pe.eth.Travisaapp.controller.CategoriaController; import pe.eth.Travisaapp.controller.ProductoController; import pe.eth.Travisaapp.domain.Categoria; import pe.eth.Travisaapp.domain.Producto; /** * * @author CARLOS */ public class CategoriamanView extends javax.swing.JInternalFrame { String col[]={"Id","Descripcion","Precio","Stock","Observacion"}; DefaultTableModel modelo=new DefaultTableModel(null,col); public void agregarCategorias(){ ArrayList<Categoria> listacate=CategoriaController.listarcategoria(); for (Categoria cat : listacate) { CBoCat.addItem(cat.getNombre()); } } //ArrayList<Categoria> lista=CategoriaServiceImpl.listar(); public void mensaje(String m){ JOptionPane.showMessageDialog(null, m); } public CategoriamanView() { initComponents(); agregarCategorias(); TablaCat.setModel(modelo); txtIdcat.setEnabled(false); // camposeditables(false); } public void limpiar() { while (TablaCat.getRowCount() > 0) { ((DefaultTableModel) TablaCat.getModel()).removeRow(0); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); TablaCat = new javax.swing.JTable(); CBoCat = new javax.swing.JComboBox<>(); Panelbotones = new javax.swing.JPanel(); BtnBuscar = new javax.swing.JButton(); BtnEditar = new javax.swing.JButton(); BtnAct = new javax.swing.JButton(); BtnEliminar = new javax.swing.JButton(); BtnSalir = new javax.swing.JButton(); txtcodProd = new javax.swing.JTextField(); txtDescr = new javax.swing.JTextField(); txtPv = new javax.swing.JTextField(); txtStock = new javax.swing.JTextField(); txtObs = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txtIdcat = new javax.swing.JTextField(); setTitle("Categoria "); TablaCat.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(TablaCat); Panelbotones.setLayout(new java.awt.GridLayout(1, 0)); BtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pe/eth/Travisaapp/img/buscar.png"))); // NOI18N BtnBuscar.setText("Listar"); BtnBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnBuscarActionPerformed(evt); } }); Panelbotones.add(BtnBuscar); BtnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pe/eth/Travisaapp/img/editar.png"))); // NOI18N BtnEditar.setText("Editar"); BtnEditar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnEditarActionPerformed(evt); } }); Panelbotones.add(BtnEditar); BtnAct.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pe/eth/Travisaapp/img/backup-restore.png"))); // NOI18N BtnAct.setText("Actualizar"); BtnAct.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnActActionPerformed(evt); } }); Panelbotones.add(BtnAct); BtnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pe/eth/Travisaapp/img/eliminar.png"))); // NOI18N BtnEliminar.setText("Eliminar"); BtnEliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnEliminarActionPerformed(evt); } }); Panelbotones.add(BtnEliminar); BtnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pe/eth/Travisaapp/img/salir.png"))); // NOI18N BtnSalir.setText("Salir"); BtnSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnSalirActionPerformed(evt); } }); Panelbotones.add(BtnSalir); jLabel1.setText("IdProducto"); jLabel2.setText("Descripcion"); jLabel3.setText("Precio Venta"); jLabel4.setText("Stock"); jLabel5.setText("Observacion"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addComponent(CBoCat, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(Panelbotones, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(58, 58, 58)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(35, 35, 35) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(txtcodProd)) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(txtDescr)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel3) .addGap(39, 39, 39)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(txtPv, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(txtStock, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtIdcat, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5) .addComponent(txtObs, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Panelbotones, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(CBoCat))) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtcodProd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtDescr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtObs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE) .addComponent(txtIdcat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(24, 24, 24)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void BtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnBuscarActionPerformed limpiar() ; String cat=CBoCat.getSelectedItem().toString(); // ArrayList<Categoria> lista=ArticuloDAO.articulosPorCategoria(cat); ArrayList<Producto> lista=ProductoController.listarProductoxcategoria(cat); for (Producto p : lista) { modelo.addRow(new Object[]{p.getIDPRODUCTO(), p.getDESCRIPCION(),p.getPRECIOVENTA(), p.getSTOCK(),p.getObservacion()}); } }//GEN-LAST:event_BtnBuscarActionPerformed private void BtnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnSalirActionPerformed this.dispose(); }//GEN-LAST:event_BtnSalirActionPerformed private void BtnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnEditarActionPerformed String v=JOptionPane.showInputDialog(null, "Ingrese cรณdigo"); if(!v.equals("")){ //int codigo=Integer.parseInt(v); // EmpleadoDAO e=new EmpleadoDAO(); Producto p=ProductoController.BuscarProducto(v); //buscare empleado //Empleado emp=e.get(codigo); if(p!=null){ //asignar datos del objeto empleado //a los cuadros de texto txtcodProd.setText(String.valueOf(p.getIDPRODUCTO())); txtDescr.setText(p.getDESCRIPCION()); txtPv.setText(String.valueOf(p.getPRECIOVENTA())); txtStock.setText(String.valueOf(p.getSTOCK())); txtObs.setText(p.getObservacion()); txtIdcat.setText(String.valueOf(p.getIDCATEGORIA())); }else{ mensaje("Codigo no existe...!!!"); } }else{ mensaje("No ha ingresado codigo..."); } }//GEN-LAST:event_BtnEditarActionPerformed private void BtnActActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnActActionPerformed ActualizarCategoria(); }//GEN-LAST:event_BtnActActionPerformed private void BtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnEliminarActionPerformed EliminarProducto(); }//GEN-LAST:event_BtnEliminarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BtnAct; private javax.swing.JButton BtnBuscar; private javax.swing.JButton BtnEditar; private javax.swing.JButton BtnEliminar; private javax.swing.JButton BtnSalir; private javax.swing.JComboBox<String> CBoCat; private javax.swing.JPanel Panelbotones; private javax.swing.JTable TablaCat; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField txtDescr; private javax.swing.JTextField txtIdcat; private javax.swing.JTextField txtObs; private javax.swing.JTextField txtPv; private javax.swing.JTextField txtStock; private javax.swing.JTextField txtcodProd; // End of variables declaration//GEN-END:variables private void ActualizarCategoria() { Producto pro= new Producto(); pro.setIDPRODUCTO(txtcodProd.getText()); pro.setDESCRIPCION(txtDescr.getText()); pro.setPRECIOVENTA(Double.parseDouble(txtPv.getText())); pro.setSTOCK(Integer.parseInt(txtStock.getText())); pro.setObservacion(txtObs.getText()); pro.setIDCATEGORIA(Integer.parseInt(txtIdcat.getText())); ProductoController.updateProducto(pro); limpiarcampos(); } private void limpiarcampos() { txtDescr.setText(""); txtPv.setText(""); txtStock.setText(""); txtcodProd.setText(""); txtObs.setText(""); txtIdcat.setText(""); } private void camposeditables(boolean v) { txtcodProd.setVisible(v); txtDescr.setVisible(v); txtPv.setVisible(v); txtStock.setVisible(v); txtObs.setVisible(v); } private void EliminarProducto() { String v=JOptionPane.showInputDialog(null, "Ingrese cรณdigo"); if(!v.equals("")){ Producto cod=ProductoController.buscarCodigo(v); if(cod!=null){ ProductoController.eliminar(v); // txtcodProd.setText(String.valueOf(p.getIDPRODUCTO())); // txtDescr.setText(p.getDESCRIPCION()); // txtPv.setText(String.valueOf(p.getPRECIOVENTA())); // txtStock.setText(String.valueOf(p.getSTOCK())); // txtObs.setText(p.getObservacion()); // txtIdcat.setText(String.valueOf(p.getIDCATEGORIA())); }else{ mensaje("Codigo no existe...!!!"); } }else{ mensaje("No ha ingresado codigo..."); } } private static void cuadromensaje(String rs) { JOptionPane.showMessageDialog(null,rs); } }
UTF-8
Java
15,945
java
CategoriamanView.java
Java
[ { "context": "eth.Travisaapp.domain.Producto;\n\n/**\n *\n * @author CARLOS\n */\npublic class CategoriamanView extends javax.s", "end": 360, "score": 0.8018519282341003, "start": 354, "tag": "USERNAME", "value": "CARLOS" } ]
null
[]
package pe.eth.Travisaapp.view; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import pe.eth.Travisaapp.controller.CategoriaController; import pe.eth.Travisaapp.controller.ProductoController; import pe.eth.Travisaapp.domain.Categoria; import pe.eth.Travisaapp.domain.Producto; /** * * @author CARLOS */ public class CategoriamanView extends javax.swing.JInternalFrame { String col[]={"Id","Descripcion","Precio","Stock","Observacion"}; DefaultTableModel modelo=new DefaultTableModel(null,col); public void agregarCategorias(){ ArrayList<Categoria> listacate=CategoriaController.listarcategoria(); for (Categoria cat : listacate) { CBoCat.addItem(cat.getNombre()); } } //ArrayList<Categoria> lista=CategoriaServiceImpl.listar(); public void mensaje(String m){ JOptionPane.showMessageDialog(null, m); } public CategoriamanView() { initComponents(); agregarCategorias(); TablaCat.setModel(modelo); txtIdcat.setEnabled(false); // camposeditables(false); } public void limpiar() { while (TablaCat.getRowCount() > 0) { ((DefaultTableModel) TablaCat.getModel()).removeRow(0); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); TablaCat = new javax.swing.JTable(); CBoCat = new javax.swing.JComboBox<>(); Panelbotones = new javax.swing.JPanel(); BtnBuscar = new javax.swing.JButton(); BtnEditar = new javax.swing.JButton(); BtnAct = new javax.swing.JButton(); BtnEliminar = new javax.swing.JButton(); BtnSalir = new javax.swing.JButton(); txtcodProd = new javax.swing.JTextField(); txtDescr = new javax.swing.JTextField(); txtPv = new javax.swing.JTextField(); txtStock = new javax.swing.JTextField(); txtObs = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txtIdcat = new javax.swing.JTextField(); setTitle("Categoria "); TablaCat.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(TablaCat); Panelbotones.setLayout(new java.awt.GridLayout(1, 0)); BtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pe/eth/Travisaapp/img/buscar.png"))); // NOI18N BtnBuscar.setText("Listar"); BtnBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnBuscarActionPerformed(evt); } }); Panelbotones.add(BtnBuscar); BtnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pe/eth/Travisaapp/img/editar.png"))); // NOI18N BtnEditar.setText("Editar"); BtnEditar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnEditarActionPerformed(evt); } }); Panelbotones.add(BtnEditar); BtnAct.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pe/eth/Travisaapp/img/backup-restore.png"))); // NOI18N BtnAct.setText("Actualizar"); BtnAct.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnActActionPerformed(evt); } }); Panelbotones.add(BtnAct); BtnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pe/eth/Travisaapp/img/eliminar.png"))); // NOI18N BtnEliminar.setText("Eliminar"); BtnEliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnEliminarActionPerformed(evt); } }); Panelbotones.add(BtnEliminar); BtnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pe/eth/Travisaapp/img/salir.png"))); // NOI18N BtnSalir.setText("Salir"); BtnSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnSalirActionPerformed(evt); } }); Panelbotones.add(BtnSalir); jLabel1.setText("IdProducto"); jLabel2.setText("Descripcion"); jLabel3.setText("Precio Venta"); jLabel4.setText("Stock"); jLabel5.setText("Observacion"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addComponent(CBoCat, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(Panelbotones, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(58, 58, 58)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(35, 35, 35) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(txtcodProd)) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(txtDescr)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel3) .addGap(39, 39, 39)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(txtPv, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(txtStock, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtIdcat, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5) .addComponent(txtObs, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Panelbotones, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(CBoCat))) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtcodProd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtDescr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtObs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE) .addComponent(txtIdcat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(24, 24, 24)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void BtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnBuscarActionPerformed limpiar() ; String cat=CBoCat.getSelectedItem().toString(); // ArrayList<Categoria> lista=ArticuloDAO.articulosPorCategoria(cat); ArrayList<Producto> lista=ProductoController.listarProductoxcategoria(cat); for (Producto p : lista) { modelo.addRow(new Object[]{p.getIDPRODUCTO(), p.getDESCRIPCION(),p.getPRECIOVENTA(), p.getSTOCK(),p.getObservacion()}); } }//GEN-LAST:event_BtnBuscarActionPerformed private void BtnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnSalirActionPerformed this.dispose(); }//GEN-LAST:event_BtnSalirActionPerformed private void BtnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnEditarActionPerformed String v=JOptionPane.showInputDialog(null, "Ingrese cรณdigo"); if(!v.equals("")){ //int codigo=Integer.parseInt(v); // EmpleadoDAO e=new EmpleadoDAO(); Producto p=ProductoController.BuscarProducto(v); //buscare empleado //Empleado emp=e.get(codigo); if(p!=null){ //asignar datos del objeto empleado //a los cuadros de texto txtcodProd.setText(String.valueOf(p.getIDPRODUCTO())); txtDescr.setText(p.getDESCRIPCION()); txtPv.setText(String.valueOf(p.getPRECIOVENTA())); txtStock.setText(String.valueOf(p.getSTOCK())); txtObs.setText(p.getObservacion()); txtIdcat.setText(String.valueOf(p.getIDCATEGORIA())); }else{ mensaje("Codigo no existe...!!!"); } }else{ mensaje("No ha ingresado codigo..."); } }//GEN-LAST:event_BtnEditarActionPerformed private void BtnActActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnActActionPerformed ActualizarCategoria(); }//GEN-LAST:event_BtnActActionPerformed private void BtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnEliminarActionPerformed EliminarProducto(); }//GEN-LAST:event_BtnEliminarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BtnAct; private javax.swing.JButton BtnBuscar; private javax.swing.JButton BtnEditar; private javax.swing.JButton BtnEliminar; private javax.swing.JButton BtnSalir; private javax.swing.JComboBox<String> CBoCat; private javax.swing.JPanel Panelbotones; private javax.swing.JTable TablaCat; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField txtDescr; private javax.swing.JTextField txtIdcat; private javax.swing.JTextField txtObs; private javax.swing.JTextField txtPv; private javax.swing.JTextField txtStock; private javax.swing.JTextField txtcodProd; // End of variables declaration//GEN-END:variables private void ActualizarCategoria() { Producto pro= new Producto(); pro.setIDPRODUCTO(txtcodProd.getText()); pro.setDESCRIPCION(txtDescr.getText()); pro.setPRECIOVENTA(Double.parseDouble(txtPv.getText())); pro.setSTOCK(Integer.parseInt(txtStock.getText())); pro.setObservacion(txtObs.getText()); pro.setIDCATEGORIA(Integer.parseInt(txtIdcat.getText())); ProductoController.updateProducto(pro); limpiarcampos(); } private void limpiarcampos() { txtDescr.setText(""); txtPv.setText(""); txtStock.setText(""); txtcodProd.setText(""); txtObs.setText(""); txtIdcat.setText(""); } private void camposeditables(boolean v) { txtcodProd.setVisible(v); txtDescr.setVisible(v); txtPv.setVisible(v); txtStock.setVisible(v); txtObs.setVisible(v); } private void EliminarProducto() { String v=JOptionPane.showInputDialog(null, "Ingrese cรณdigo"); if(!v.equals("")){ Producto cod=ProductoController.buscarCodigo(v); if(cod!=null){ ProductoController.eliminar(v); // txtcodProd.setText(String.valueOf(p.getIDPRODUCTO())); // txtDescr.setText(p.getDESCRIPCION()); // txtPv.setText(String.valueOf(p.getPRECIOVENTA())); // txtStock.setText(String.valueOf(p.getSTOCK())); // txtObs.setText(p.getObservacion()); // txtIdcat.setText(String.valueOf(p.getIDCATEGORIA())); }else{ mensaje("Codigo no existe...!!!"); } }else{ mensaje("No ha ingresado codigo..."); } } private static void cuadromensaje(String rs) { JOptionPane.showMessageDialog(null,rs); } }
15,945
0.644044
0.636455
352
44.289772
34.756149
163
false
false
0
0
0
0
0
0
0.730114
false
false
13
6dc7ebe932007ee3460a02ca89ee97e4a63ec88b
19,799,799,293,028
b469318e06dcc331fd670cf1914dfd3fe6360e5a
/dsp-commons/src/main/java/com/flipkart/dsp/dto/MultiDataStoreGetRequest.java
525bac7f29910724cbd5b7a96ac4bb20e6ed4d19
[]
no_license
isabella232/dsp
https://github.com/isabella232/dsp
6644b22ccbb5d5b5927ff7c5cbd590e53cdebbcc
b366851c3282587309b725ae95e25eb106752a09
refs/heads/master
2023-03-18T14:18:32.148000
2021-01-24T06:48:20
2021-01-24T06:48:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.flipkart.dsp.dto; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class MultiDataStoreGetRequest { private String payloadId; private MultiDataStoreStorageAdapter storageAdapter; private MultiDataStorePayloadFormat payloadFormat; private String payloadFileLocation; }
UTF-8
Java
336
java
MultiDataStoreGetRequest.java
Java
[]
null
[]
package com.flipkart.dsp.dto; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class MultiDataStoreGetRequest { private String payloadId; private MultiDataStoreStorageAdapter storageAdapter; private MultiDataStorePayloadFormat payloadFormat; private String payloadFileLocation; }
336
0.824405
0.824405
13
24.846153
18.785618
56
false
false
0
0
0
0
0
0
0.538462
false
false
13
a8f1bf0f4aae8ca35d2148adcb70b4b72330216b
2,405,181,750,821
29ef659d16b2aa5c426dd0828870eb0bd752b91c
/src/test/java/com/controlefinanceiro/Movimentacao/MovimentacaoTeste.java
b2a23faf2c1ec42a892b1a4d70683e25bf38f8bc
[]
no_license
kennedylima/ControleFinanceiroAPI
https://github.com/kennedylima/ControleFinanceiroAPI
e97ddf11e2f308a12e3049bf6124496afeb3bf92
d624355806e7aec70ce72ca36f2a3eb275f39184
refs/heads/master
2020-06-10T05:47:50.218000
2016-12-09T20:30:56
2016-12-09T20:30:56
76,068,029
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.controlefinanceiro.Movimentacao; import com.controlefinanceiro.Model.Categoria; import com.controlefinanceiro.Model.Movimentacao; import com.controlefinanceiro.Model.Tipo; import com.controlefinanceiro.Repository.CategoriaRepository; import com.controlefinanceiro.Repository.MovimentacaoRepository; import org.junit.Before; 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.cglib.core.Local; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringRunner; import sun.java2d.pipe.SpanShapeRenderer; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Collection; import java.util.Date; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest @TestPropertySource(locations="classpath:application-test.properties") public class MovimentacaoTeste extends AbstractTransactionalJUnit4SpringContextTests { @Autowired MovimentacaoRepository movimentacaoRepository; @Autowired CategoriaRepository categoriaRepository; private Movimentacao movimentacao; private String descricao; private Tipo tipo; private Categoria categoria; private Double valor; private Date data; @Before public void inicializar() throws ParseException { tipo = Tipo.DESPESA; descricao = "Sushi"; categoria = new Categoria("Comida"); categoriaRepository.salvar(categoria); valor = 100d; data = new Date(); movimentacao = new Movimentacao(tipo,data,descricao,categoria,valor); movimentacaoRepository.salvar(movimentacao); } @Test public void deve_salvar_uma_movimentacao(){ assertNotNull(movimentacaoRepository.buscarPelo(movimentacao.getId())); } @Test public void deve_alterar_uma_movimentacao(){ int idEsperado = movimentacao.getId(); data = new Date(); descricao = "Picadinho Lanches"; movimentacao.alterar(tipo,descricao,data,categoria,valor); movimentacaoRepository.salvar(movimentacao); assertEquals(idEsperado,movimentacao.getId()); assertEquals(descricao,movimentacao.getDescricao()); } @Test public void deve_buscar_todas_as_movimentacoes(){ int quantidadeEsperada = 1; Collection<Movimentacao> movimentacoes = movimentacaoRepository.buscarTodas(); assertEquals(quantidadeEsperada,movimentacoes.size()); } @Test public void deve_remover_uma_movimentacao(){ movimentacaoRepository.remover(movimentacao.getId()); Collection<Movimentacao> movimentacoes = movimentacaoRepository.buscarTodas(); assertThat(movimentacoes, not(hasItem(movimentacao))); } }
UTF-8
Java
3,228
java
MovimentacaoTeste.java
Java
[ { "context": ";\n data = new Date();\n descricao = \"Picadinho Lanches\";\n\n movimentacao.alterar(tipo,descricao,da", "end": 2440, "score": 0.9989423751831055, "start": 2423, "tag": "NAME", "value": "Picadinho Lanches" } ]
null
[]
package com.controlefinanceiro.Movimentacao; import com.controlefinanceiro.Model.Categoria; import com.controlefinanceiro.Model.Movimentacao; import com.controlefinanceiro.Model.Tipo; import com.controlefinanceiro.Repository.CategoriaRepository; import com.controlefinanceiro.Repository.MovimentacaoRepository; import org.junit.Before; 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.cglib.core.Local; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringRunner; import sun.java2d.pipe.SpanShapeRenderer; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Collection; import java.util.Date; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest @TestPropertySource(locations="classpath:application-test.properties") public class MovimentacaoTeste extends AbstractTransactionalJUnit4SpringContextTests { @Autowired MovimentacaoRepository movimentacaoRepository; @Autowired CategoriaRepository categoriaRepository; private Movimentacao movimentacao; private String descricao; private Tipo tipo; private Categoria categoria; private Double valor; private Date data; @Before public void inicializar() throws ParseException { tipo = Tipo.DESPESA; descricao = "Sushi"; categoria = new Categoria("Comida"); categoriaRepository.salvar(categoria); valor = 100d; data = new Date(); movimentacao = new Movimentacao(tipo,data,descricao,categoria,valor); movimentacaoRepository.salvar(movimentacao); } @Test public void deve_salvar_uma_movimentacao(){ assertNotNull(movimentacaoRepository.buscarPelo(movimentacao.getId())); } @Test public void deve_alterar_uma_movimentacao(){ int idEsperado = movimentacao.getId(); data = new Date(); descricao = "<NAME>"; movimentacao.alterar(tipo,descricao,data,categoria,valor); movimentacaoRepository.salvar(movimentacao); assertEquals(idEsperado,movimentacao.getId()); assertEquals(descricao,movimentacao.getDescricao()); } @Test public void deve_buscar_todas_as_movimentacoes(){ int quantidadeEsperada = 1; Collection<Movimentacao> movimentacoes = movimentacaoRepository.buscarTodas(); assertEquals(quantidadeEsperada,movimentacoes.size()); } @Test public void deve_remover_uma_movimentacao(){ movimentacaoRepository.remover(movimentacao.getId()); Collection<Movimentacao> movimentacoes = movimentacaoRepository.buscarTodas(); assertThat(movimentacoes, not(hasItem(movimentacao))); } }
3,217
0.762082
0.759294
98
31.938776
24.847624
93
false
false
0
0
0
0
0
0
0.714286
false
false
13
ccd924d21faa50bdca9530ebcbb47dbe9ef875b2
32,160,715,173,134
6f17db36491612209f7b6e49977656f1272e6e4d
/data/data-impl/data-impl-rdb/data-impl-rdb-mybatis/src/main/java/com/ls/fw/data/rdb/impl/mybatis/plugin/page/SimpleParser.java
8e1330060b32b5cdba7e9275ff90e94e48d0551d
[]
no_license
happy6eve/fw
https://github.com/happy6eve/fw
78fc9d888f064d1539138884a2c9b58ab8b36a43
3a03f4cba82ce419baa8ee7d1862f0ac4c1b250e
refs/heads/master
2017-11-13T14:55:45.094000
2016-04-06T07:20:44
2016-04-06T07:20:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ls.fw.data.rdb.impl.mybatis.plugin.page; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.reflection.MetaObject; import com.ls.fw.data.bean.SimplePage; import com.ls.fw.data.rdb.core.config.DBType; import com.ls.fw.data.rdb.core.jdbc.dialet.Dialect; public class SimpleParser implements Parser { protected Dialect dialect = null; public SimpleParser(Dialect dialect) { super(); this.dialect = dialect; } public static Parser newParser(Dialect dialect) { return new SimpleParser(dialect); } public void parser(Dialect dialect) { this.dialect = dialect; } public void isSupportedSql(String sql) { if (sql.trim().toUpperCase().endsWith("FOR UPDATE")) { throw new RuntimeException("ๅˆ†้กตๆ’ไปถไธๆ”ฏๆŒๅŒ…ๅซfor update็š„sql"); } } /** * ่Žทๅ–ๆ€ปๆ•ฐsql - ๅฆ‚ๆžœ่ฆๆ”ฏๆŒๅ…ถไป–ๆ•ฐๆฎๅบ“๏ผŒไฟฎๆ”น่ฟ™้‡Œๅฐฑๅฏไปฅ * * @param sql * ๅŽŸๆŸฅ่ฏขsql * @return ่ฟ”ๅ›žcountๆŸฅ่ฏขsql */ public String getCountSql(final String sql) { isSupportedSql(sql); return dialect.getCountString(sql); } /** * ่Žทๅ–ๅˆ†้กตsql - ๅฆ‚ๆžœ่ฆๆ”ฏๆŒๅ…ถไป–ๆ•ฐๆฎๅบ“๏ผŒไฟฎๆ”น่ฟ™้‡Œๅฐฑๅฏไปฅ * * @param sql * ๅŽŸๆŸฅ่ฏขsql * @return ่ฟ”ๅ›žๅˆ†้กตsql */ public String getPageSql(String sql) { return this.dialect.getLimitString(sql, 1, "?", 1, "?"); } public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, SimplePage page) { Map paramMap = null; if (parameterObject == null) { paramMap = new HashMap(); } else if (parameterObject instanceof Map) { paramMap = (Map) parameterObject; } else { paramMap = new HashMap(); // ๅŠจๆ€sqlๆ—ถ็š„ๅˆคๆ–ญๆกไปถไธไผšๅ‡บ็ŽฐๅœจParameterMappingไธญ๏ผŒไฝ†ๆ˜ฏๅฟ…้กปๆœ‰๏ผŒๆ‰€ไปฅ่ฟ™้‡Œ้œ€่ฆๆ”ถ้›†ๆ‰€ๆœ‰็š„getterๅฑžๆ€ง // TypeHandlerRegistryๅฏไปฅ็›ดๆŽฅๅค„็†็š„ไผšไฝœไธบไธ€ไธช็›ดๆŽฅไฝฟ็”จ็š„ๅฏน่ฑก่ฟ›่กŒๅค„็† boolean hasTypeHandler = ms.getConfiguration() .getTypeHandlerRegistry() .hasTypeHandler(parameterObject.getClass()); if (!hasTypeHandler) { MetaObject metaObject = PageUtil.forObject(parameterObject); for (String name : metaObject.getGetterNames()) { paramMap.put(name, metaObject.getValue(name)); } } // ไธ‹้ข่ฟ™ๆฎตๆ–นๆณ•๏ผŒไธป่ฆ่งฃๅ†ณไธ€ไธชๅธธ่ง็ฑปๅž‹็š„ๅ‚ๆ•ฐๆ—ถ็š„้—ฎ้ข˜ if (boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0) { for (ParameterMapping parameterMapping : boundSql .getParameterMappings()) { String name = parameterMapping.getProperty(); if (!name.equals(PAGEPARAMETER_FIRST) && !name.equals(PAGEPARAMETER_SECOND) && paramMap.get(name) == null) { if (hasTypeHandler || parameterMapping.getJavaType() .isAssignableFrom( parameterObject.getClass())) { paramMap.put(name, parameterObject); } } } } } this.handlPageParameter(paramMap, ms, parameterObject, boundSql, page); return paramMap; } private Map handlPageParameter(Map paramMap,MappedStatement ms, Object parameterObject, BoundSql boundSql, SimplePage page) { DBType type = DBType.get(this.dialect.getType()); switch(type){ case hsql: paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize()); paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); break; case oracle: paramMap.put(PAGEPARAMETER_FIRST, page.getEndRow()); paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); break; case postgresql: paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize()); paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); break; case db2: case derby: case h2: case sqlserver: case sqlserver2005: case sybase: case mysql: paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow()); paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize()); break; case unkown: break; default: break; } return paramMap; } }
UTF-8
Java
4,244
java
SimpleParser.java
Java
[]
null
[]
package com.ls.fw.data.rdb.impl.mybatis.plugin.page; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.reflection.MetaObject; import com.ls.fw.data.bean.SimplePage; import com.ls.fw.data.rdb.core.config.DBType; import com.ls.fw.data.rdb.core.jdbc.dialet.Dialect; public class SimpleParser implements Parser { protected Dialect dialect = null; public SimpleParser(Dialect dialect) { super(); this.dialect = dialect; } public static Parser newParser(Dialect dialect) { return new SimpleParser(dialect); } public void parser(Dialect dialect) { this.dialect = dialect; } public void isSupportedSql(String sql) { if (sql.trim().toUpperCase().endsWith("FOR UPDATE")) { throw new RuntimeException("ๅˆ†้กตๆ’ไปถไธๆ”ฏๆŒๅŒ…ๅซfor update็š„sql"); } } /** * ่Žทๅ–ๆ€ปๆ•ฐsql - ๅฆ‚ๆžœ่ฆๆ”ฏๆŒๅ…ถไป–ๆ•ฐๆฎๅบ“๏ผŒไฟฎๆ”น่ฟ™้‡Œๅฐฑๅฏไปฅ * * @param sql * ๅŽŸๆŸฅ่ฏขsql * @return ่ฟ”ๅ›žcountๆŸฅ่ฏขsql */ public String getCountSql(final String sql) { isSupportedSql(sql); return dialect.getCountString(sql); } /** * ่Žทๅ–ๅˆ†้กตsql - ๅฆ‚ๆžœ่ฆๆ”ฏๆŒๅ…ถไป–ๆ•ฐๆฎๅบ“๏ผŒไฟฎๆ”น่ฟ™้‡Œๅฐฑๅฏไปฅ * * @param sql * ๅŽŸๆŸฅ่ฏขsql * @return ่ฟ”ๅ›žๅˆ†้กตsql */ public String getPageSql(String sql) { return this.dialect.getLimitString(sql, 1, "?", 1, "?"); } public Map setPageParameter(MappedStatement ms, Object parameterObject, BoundSql boundSql, SimplePage page) { Map paramMap = null; if (parameterObject == null) { paramMap = new HashMap(); } else if (parameterObject instanceof Map) { paramMap = (Map) parameterObject; } else { paramMap = new HashMap(); // ๅŠจๆ€sqlๆ—ถ็š„ๅˆคๆ–ญๆกไปถไธไผšๅ‡บ็ŽฐๅœจParameterMappingไธญ๏ผŒไฝ†ๆ˜ฏๅฟ…้กปๆœ‰๏ผŒๆ‰€ไปฅ่ฟ™้‡Œ้œ€่ฆๆ”ถ้›†ๆ‰€ๆœ‰็š„getterๅฑžๆ€ง // TypeHandlerRegistryๅฏไปฅ็›ดๆŽฅๅค„็†็š„ไผšไฝœไธบไธ€ไธช็›ดๆŽฅไฝฟ็”จ็š„ๅฏน่ฑก่ฟ›่กŒๅค„็† boolean hasTypeHandler = ms.getConfiguration() .getTypeHandlerRegistry() .hasTypeHandler(parameterObject.getClass()); if (!hasTypeHandler) { MetaObject metaObject = PageUtil.forObject(parameterObject); for (String name : metaObject.getGetterNames()) { paramMap.put(name, metaObject.getValue(name)); } } // ไธ‹้ข่ฟ™ๆฎตๆ–นๆณ•๏ผŒไธป่ฆ่งฃๅ†ณไธ€ไธชๅธธ่ง็ฑปๅž‹็š„ๅ‚ๆ•ฐๆ—ถ็š„้—ฎ้ข˜ if (boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0) { for (ParameterMapping parameterMapping : boundSql .getParameterMappings()) { String name = parameterMapping.getProperty(); if (!name.equals(PAGEPARAMETER_FIRST) && !name.equals(PAGEPARAMETER_SECOND) && paramMap.get(name) == null) { if (hasTypeHandler || parameterMapping.getJavaType() .isAssignableFrom( parameterObject.getClass())) { paramMap.put(name, parameterObject); } } } } } this.handlPageParameter(paramMap, ms, parameterObject, boundSql, page); return paramMap; } private Map handlPageParameter(Map paramMap,MappedStatement ms, Object parameterObject, BoundSql boundSql, SimplePage page) { DBType type = DBType.get(this.dialect.getType()); switch(type){ case hsql: paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize()); paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); break; case oracle: paramMap.put(PAGEPARAMETER_FIRST, page.getEndRow()); paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); break; case postgresql: paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize()); paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); break; case db2: case derby: case h2: case sqlserver: case sqlserver2005: case sybase: case mysql: paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow()); paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize()); break; case unkown: break; default: break; } return paramMap; } }
4,244
0.67334
0.671059
137
26.802919
21.353077
88
false
false
0
0
0
0
0
0
2.941606
false
false
13
291f60470d38c5092d05310763be89467b23ade6
13,194,139,595,527
c8531c3e4c4f5e21e4d43f2b842d434c35cef1ca
/src/wagemgr/dao/PostDao.java
60a1bba37f62dbc97dab4f4306bd4e66857a170b
[]
no_license
raining07/WageMgr
https://github.com/raining07/WageMgr
85c62a14b69b4877af703cefe8ffb659ac052b7e
4f9cdd4a73cac2a37dc09fd53d6df99831cc5a33
refs/heads/master
2017-10-06T10:51:50.403000
2017-06-24T08:44:35
2017-06-24T08:44:35
95,002,187
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package wagemgr.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import core.dba.DBAccessor; import core.util.CollectionUtil; import core.util.Reflections; import core.util.StringUtil; import wagemgr.domain.Post; /** * ่ŒๅŠก.ๆ•ฐๆฎๅฑ‚ */ public class PostDao { private final String tablename = "POST"; public List<Post> findAll() throws Exception { List<Post> depts = new ArrayList<>(); List<Map<String, Object>> list = DBAccessor.queryForList("SELECT * FROM " + tablename); for (Map<String, Object> each : list) { Post dept = Reflections.map2Obj(each, Post.class); depts.add(dept); } return depts; } public void save(String deptId, String deptName) { Map<String, Object> valMap = new HashMap<>(); valMap.put("pos_id", deptId); valMap.put("pos_name", deptName); if (StringUtil.isEmpty(deptId)) { valMap.put("pos_id", StringUtil.get32UUID()); DBAccessor.mapInsert(valMap, tablename); } else { Map<String, Object> whereMap = new HashMap<>(); whereMap.put("pos_id", deptId); DBAccessor.mapUpdate(valMap, whereMap, tablename); } } public void delete(String pos_id) { DBAccessor.execute("DELETE FROM " + tablename + " WHERE pos_id='" + pos_id + "'"); } public Post findById(String deptId) throws Exception { List<Map<String, Object>> list = DBAccessor .queryForList("SELECT * FROM " + tablename + " WHERE pos_id='" + deptId + "'"); if (CollectionUtil.isEmpty(list)) { return null; } else { Post dept = Reflections.map2Obj(list.get(0), Post.class); return dept; } } }
UTF-8
Java
1,664
java
PostDao.java
Java
[]
null
[]
package wagemgr.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import core.dba.DBAccessor; import core.util.CollectionUtil; import core.util.Reflections; import core.util.StringUtil; import wagemgr.domain.Post; /** * ่ŒๅŠก.ๆ•ฐๆฎๅฑ‚ */ public class PostDao { private final String tablename = "POST"; public List<Post> findAll() throws Exception { List<Post> depts = new ArrayList<>(); List<Map<String, Object>> list = DBAccessor.queryForList("SELECT * FROM " + tablename); for (Map<String, Object> each : list) { Post dept = Reflections.map2Obj(each, Post.class); depts.add(dept); } return depts; } public void save(String deptId, String deptName) { Map<String, Object> valMap = new HashMap<>(); valMap.put("pos_id", deptId); valMap.put("pos_name", deptName); if (StringUtil.isEmpty(deptId)) { valMap.put("pos_id", StringUtil.get32UUID()); DBAccessor.mapInsert(valMap, tablename); } else { Map<String, Object> whereMap = new HashMap<>(); whereMap.put("pos_id", deptId); DBAccessor.mapUpdate(valMap, whereMap, tablename); } } public void delete(String pos_id) { DBAccessor.execute("DELETE FROM " + tablename + " WHERE pos_id='" + pos_id + "'"); } public Post findById(String deptId) throws Exception { List<Map<String, Object>> list = DBAccessor .queryForList("SELECT * FROM " + tablename + " WHERE pos_id='" + deptId + "'"); if (CollectionUtil.isEmpty(list)) { return null; } else { Post dept = Reflections.map2Obj(list.get(0), Post.class); return dept; } } }
1,664
0.659613
0.65659
60
25.566668
22.858526
89
false
false
0
0
0
0
0
0
1.983333
false
false
13
88b03cab0c26c9b2d169a3d2580774433ea46b81
2,869,038,208,234
954d8405694a9b38feaffa7e835151c168c0baa8
/src/main/java/org/example/algoritms/PrzestawienieMacierzowe1.java
e64af968480c602ed8768f4a76e67540c9e358e2
[]
no_license
krzysiek2468/BazyProjekt
https://github.com/krzysiek2468/BazyProjekt
f5052fbe027542bead26a91a76b03e5b061c25e4
5e9cf5fa0d87ff95b6b64cd9d87bb50dde67859d
refs/heads/master
2023-04-03T09:08:16.309000
2021-04-15T11:54:46
2021-04-15T11:54:46
342,946,412
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.example.algoritms; import java.util.ArrayList; import java.util.List; public class PrzestawienieMacierzowe1 { public List<String> encryption(List<String> lines , String path3){ List<String> lista = new ArrayList<>(); for (String line : lines) { lista.add(szyfruj(usunSpacje(line) , prepareString(path3))) ; } return lista; } public List<String> decryption(List<String> lines , String path3){ List<String> lista = new ArrayList<>(); for (String line : lines) { lista.add(odszyfruj(usunSpacje(line) , prepareString(path3))) ; } return lista; } public String encryptionText(String text , String path3){ //path3 to klucz //tutaj zakodowujemy lines return szyfruj(usunSpacje(text) , prepareString(path3)); } public boolean checkKey(String text){ int count = text.length(); if(count%2 == 0){ return false; } char[] list = text.toCharArray(); boolean[] numbers = new boolean[(count/2)+1]; for (boolean value:numbers) { value=false; } for(int number = 0; number<count ; number++){ if(number%2 == 0){ int checkedValue; try { checkedValue = Integer.parseInt(String.valueOf(list[number])); }catch (Exception e){ return false; } if(checkedValue<= numbers.length){ if(numbers[checkedValue -1] == true){ return false; }else { numbers[checkedValue -1] = true; } }else{ return false; } }else{ if(list[number] == '-'){ // pฤ™tla idzie dalej } else{ return false; } } } return true; } public String prepareString(String key){ String keyy = ""; for (int counter=0 ; counter<key.length();counter++){ if(counter%2==0){ keyy= keyy + key.charAt(counter); } } return keyy; } public String szyfruj(String text , String key){ int rows = text.length() / key.length(); if((text.length())%(key.length()) >0){ rows++; } int longs = key.length(); char[][] tab = new char[rows][longs]; int number1=0; int number2=0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ tab[number1][number2] = '.'; } } int m=0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ if(m<text.length()){ tab[number1][number2] = text.charAt(m); m++; } } } String returnText = ""; int position = 0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ int getValueFromString = key.charAt(position)-49; if(tab[number1][getValueFromString] != '.'){ returnText += tab[number1][getValueFromString]; } position++; } position = 0; } return returnText; } public String odszyfruj(String text , String key){ int rows = text.length() / key.length(); int numbersOfEmptyFiled =key.length() - text.length()%(key.length()); if((text.length())%(key.length()) >0){ rows++; } int longs = key.length(); char[][] tab = new char[rows][longs]; int number1=0; int number2=0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ tab[number1][number2] = '.'; } } int a=0; for(int z=0;z<numbersOfEmptyFiled;z++){ int number = key.length()-a; for(int i=0;i<key.length()-1;i++){ if(key.charAt(i) -48 ==number){ tab[rows-1][i]='='; } } a++; // int variable =key.charAt(key.length()-1-a)-48; // tab[rows-1][variable-1]='='; // System.out.println("DDDDDDDDDDDDDDDD"); // a++; } for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ System.out.println(tab[number1][number2]); } } int m=0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ if(tab[number1][number2]!='='){ if(m<text.length()){ tab[number1][number2] = text.charAt(m); m++; } }else{ tab[number1][number2] = '.'; } } } // odczzzytywanie z tablicy String returnText = ""; int position = 0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ for(int number3=0; number3<longs;number3++ ){ int getValueFromString = key.charAt(number3)-49; if(getValueFromString == number2){ if(tab[number1][number3] !='.'){ returnText += tab[number1][number3];} else{ } } } } } return returnText; } public String usunSpacje(String text){ String returnText = ""; for(int i=0;i<text.length();i++){ if(text.charAt(i) != ' '){ returnText+=text.charAt(i); } } return returnText; } }
UTF-8
Java
6,194
java
PrzestawienieMacierzowe1.java
Java
[]
null
[]
package org.example.algoritms; import java.util.ArrayList; import java.util.List; public class PrzestawienieMacierzowe1 { public List<String> encryption(List<String> lines , String path3){ List<String> lista = new ArrayList<>(); for (String line : lines) { lista.add(szyfruj(usunSpacje(line) , prepareString(path3))) ; } return lista; } public List<String> decryption(List<String> lines , String path3){ List<String> lista = new ArrayList<>(); for (String line : lines) { lista.add(odszyfruj(usunSpacje(line) , prepareString(path3))) ; } return lista; } public String encryptionText(String text , String path3){ //path3 to klucz //tutaj zakodowujemy lines return szyfruj(usunSpacje(text) , prepareString(path3)); } public boolean checkKey(String text){ int count = text.length(); if(count%2 == 0){ return false; } char[] list = text.toCharArray(); boolean[] numbers = new boolean[(count/2)+1]; for (boolean value:numbers) { value=false; } for(int number = 0; number<count ; number++){ if(number%2 == 0){ int checkedValue; try { checkedValue = Integer.parseInt(String.valueOf(list[number])); }catch (Exception e){ return false; } if(checkedValue<= numbers.length){ if(numbers[checkedValue -1] == true){ return false; }else { numbers[checkedValue -1] = true; } }else{ return false; } }else{ if(list[number] == '-'){ // pฤ™tla idzie dalej } else{ return false; } } } return true; } public String prepareString(String key){ String keyy = ""; for (int counter=0 ; counter<key.length();counter++){ if(counter%2==0){ keyy= keyy + key.charAt(counter); } } return keyy; } public String szyfruj(String text , String key){ int rows = text.length() / key.length(); if((text.length())%(key.length()) >0){ rows++; } int longs = key.length(); char[][] tab = new char[rows][longs]; int number1=0; int number2=0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ tab[number1][number2] = '.'; } } int m=0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ if(m<text.length()){ tab[number1][number2] = text.charAt(m); m++; } } } String returnText = ""; int position = 0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ int getValueFromString = key.charAt(position)-49; if(tab[number1][getValueFromString] != '.'){ returnText += tab[number1][getValueFromString]; } position++; } position = 0; } return returnText; } public String odszyfruj(String text , String key){ int rows = text.length() / key.length(); int numbersOfEmptyFiled =key.length() - text.length()%(key.length()); if((text.length())%(key.length()) >0){ rows++; } int longs = key.length(); char[][] tab = new char[rows][longs]; int number1=0; int number2=0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ tab[number1][number2] = '.'; } } int a=0; for(int z=0;z<numbersOfEmptyFiled;z++){ int number = key.length()-a; for(int i=0;i<key.length()-1;i++){ if(key.charAt(i) -48 ==number){ tab[rows-1][i]='='; } } a++; // int variable =key.charAt(key.length()-1-a)-48; // tab[rows-1][variable-1]='='; // System.out.println("DDDDDDDDDDDDDDDD"); // a++; } for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ System.out.println(tab[number1][number2]); } } int m=0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ if(tab[number1][number2]!='='){ if(m<text.length()){ tab[number1][number2] = text.charAt(m); m++; } }else{ tab[number1][number2] = '.'; } } } // odczzzytywanie z tablicy String returnText = ""; int position = 0; for(number1 = 0; number1<rows;number1++){ for(number2=0;number2<longs;number2++){ for(int number3=0; number3<longs;number3++ ){ int getValueFromString = key.charAt(number3)-49; if(getValueFromString == number2){ if(tab[number1][number3] !='.'){ returnText += tab[number1][number3];} else{ } } } } } return returnText; } public String usunSpacje(String text){ String returnText = ""; for(int i=0;i<text.length();i++){ if(text.charAt(i) != ' '){ returnText+=text.charAt(i); } } return returnText; } }
6,194
0.448248
0.426611
256
23.191406
21.451765
82
false
false
0
0
0
0
0
0
0.46875
false
false
13
d95abf096e69af57a16514da734e1ffff63cb7ba
7,241,314,869,873
9ba534d2c137c5d65aac108977809d8f6338576e
/src/com/devsmart/plotter/AxisFunction.java
5638730fe7f553e9c346ce8502fda0793fa54ef4
[]
no_license
SciAps/android-plotter
https://github.com/SciAps/android-plotter
c47b87037170bc7aed92b47f9b965b54d7e52295
66305ba3622cb58b56070b45a388abc27117ce33
refs/heads/master
2022-05-30T19:15:07.554000
2016-09-13T16:27:49
2016-09-13T16:27:49
13,326,782
1
1
null
true
2022-05-18T21:03:57
2013-10-04T14:50:22
2015-04-19T13:44:58
2022-05-18T21:03:57
600
1
1
1
Java
false
false
package com.devsmart.plotter; public interface AxisFunction { void interpolate(float[] x, float[] y); AxisFunction copy(); /** * translate screen coord --> graph coord * * @param x * @return */ float value(float x); /** * return the inverse function * * @return */ AxisFunction inverse(); }
UTF-8
Java
364
java
AxisFunction.java
Java
[]
null
[]
package com.devsmart.plotter; public interface AxisFunction { void interpolate(float[] x, float[] y); AxisFunction copy(); /** * translate screen coord --> graph coord * * @param x * @return */ float value(float x); /** * return the inverse function * * @return */ AxisFunction inverse(); }
364
0.554945
0.554945
23
14.869565
14.084541
45
false
false
0
0
0
0
0
0
0.26087
false
false
13
b99e7d4f62c26242f090a6ee28a2d9a3387bbf15
1,047,972,039,228
c4ee1e77025052d489612cff3d78a098b59f5a0b
/final-buscador-estudiante2.0/src/exactitudNombre/ExactitudNombre.java
3bfa41824b3a3ccb5d0c9c918c2e1aad81497109
[]
no_license
agustinaa235/FIUBA-Finales-Algo3
https://github.com/agustinaa235/FIUBA-Finales-Algo3
c170f43256b20d862c05b79fdb5e74ce803eac17
4a99ac489916a98fbf28d4c184bc17b7c666b5f7
refs/heads/master
2023-03-26T04:10:25.222000
2021-03-22T14:22:23
2021-03-22T14:22:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exactitudNombre; import java.util.List; public interface ExactitudNombre { boolean cumple(String nombre, String nombreBuscado); }
UTF-8
Java
146
java
ExactitudNombre.java
Java
[]
null
[]
package exactitudNombre; import java.util.List; public interface ExactitudNombre { boolean cumple(String nombre, String nombreBuscado); }
146
0.780822
0.780822
9
15.222222
19.054178
56
false
false
0
0
0
0
0
0
0.444444
false
false
13
f25258c675c7863da1f9ce0abb0f8fe39c3b3834
1,047,972,040,236
faf456296336a5bc0870e621ed86c140e3522b62
/Examples/Firebase/src/im/delight/android/ddp/firebase/examples/MainActivity.java
4a7423ec61cf4a0b33a2f513bd383650742dd7fa
[ "Apache-2.0" ]
permissive
cprakashagr/Android-DDP
https://github.com/cprakashagr/Android-DDP
11cd8e132eadce39b14af93a20016dbacd1e3fa8
3a249857843bc27bc66361d4f31e5f6baab3399f
refs/heads/master
2020-04-06T04:36:09.176000
2016-01-04T14:20:45
2016-01-04T14:20:45
46,703,068
1
0
null
true
2015-11-23T07:14:07
2015-11-23T07:14:07
2015-11-22T02:34:10
2015-10-15T06:47:38
3,554
0
0
0
null
null
null
package im.delight.android.ddp.firebase.examples; /** * Copyright 2014 www.delight.im <info@delight.im> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context; import im.delight.android.ddp.firebase.ServerValue; import im.delight.android.ddp.firebase.ChildEventListener; import im.delight.android.ddp.firebase.DataSnapshot; import im.delight.android.ddp.firebase.ValueEventListener; import java.util.Map; import java.util.HashMap; import android.widget.Toast; import im.delight.android.ddp.firebase.FirebaseError; import im.delight.android.ddp.firebase.Firebase.CompletionListener; import im.delight.android.ddp.firebase.Firebase; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { private static final String SERVER_URL = "ws://example.meteor.com/websocket"; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = getApplicationContext(); // set the Android context (which has no effect here and is only there for compatibility) Firebase.setAndroidContext(this); // create the first reference to the server's URL Firebase mainRef = new Firebase(SERVER_URL); // create another reference to a child node Firebase usersRef = mainRef.child("users"); // write data to a child node usersRef.child("jane_doe").setValue("Jane Doe", 2.5f); // access a location directly from URL and remove the value new Firebase(SERVER_URL+"/some/outdated/child").removeValue(); // watch the connection state Firebase connectedState = new Firebase(SERVER_URL+"/.info/connected"); connectedState.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { final boolean connected = snapshot.getValue(Boolean.class); final String status = connected ? "connected" : "disconnected"; Toast.makeText(context, "Connectivity changed: "+status, Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(FirebaseError error) { } }); // get the offset from local time to server time new Firebase(SERVER_URL+"/.info/serverTimeOffset").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { Toast.makeText(context, "Server time offset received: "+snapshot.getValue(Long.class), Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(FirebaseError error) { } }); // subscribe to updates in the `users` location usersRef.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot snapshot, String previousChildName) { Toast.makeText(context, "Child added on reference `"+snapshot.getKey()+"`", Toast.LENGTH_SHORT).show(); } @Override public void onChildChanged(DataSnapshot snapshot, String previousChildName) { Toast.makeText(context, "Child changed on reference `"+snapshot.getKey()+"`", Toast.LENGTH_SHORT).show(); } @Override public void onChildRemoved(DataSnapshot snapshot) { Toast.makeText(context, "Child removed on reference `"+snapshot.getKey()+"`", Toast.LENGTH_SHORT).show(); } @Override public void onChildMoved(DataSnapshot snapshot, String previousChildName) { Toast.makeText(context, "Child moved on reference `"+snapshot.getKey()+"`", Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(FirebaseError error) { } }); // write several children at once in a given location Map<String, Object> johnDoeData = new HashMap<String, Object>(); johnDoeData.put("score", 1024); johnDoeData.put("active", false); johnDoeData.put("last_online", ServerValue.TIMESTAMP); usersRef.child("john_doe").updateChildren(johnDoeData, new CompletionListener() { @Override public void onComplete(FirebaseError error, Firebase ref) { String response = "Listener on `"+ref.getKey()+"` completed "+(error != null ? "with an error" : "successfully"); Toast.makeText(context, response, Toast.LENGTH_SHORT).show(); } }); // write a node's priority only usersRef.child("john_doe").child("score").setPriority(500); // create an automatically named child with `push()` final Firebase pushedRef = usersRef.getParent().child("randomEntries").push(); // read a plain Java object (POJO) from storage pushedRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { PersonBean personBean = snapshot.getValue(PersonBean.class); Toast.makeText(context, "PersonBean received: "+personBean, Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(FirebaseError error) { } }); // write a plain Java object (POJO) to the storage that will be serialized automatically PersonBean personBean = new PersonBean(); personBean.name = "John Doe"; personBean.age = 42; personBean.location = "Example City"; pushedRef.setValue(personBean); } @Override public void onDestroy() { super.onDestroy(); // manually force the client to disconnect Firebase.goOffline(); } }
UTF-8
Java
5,719
java
MainActivity.java
Java
[ { "context": ".examples;\n\n/**\n * Copyright 2014 www.delight.im <info@delight.im>\n *\n * Licensed under the Apache License, Version", "end": 104, "score": 0.9999319911003113, "start": 89, "tag": "EMAIL", "value": "info@delight.im" }, { "context": "child node\n\t\tusersRef.child(\"jane_doe\").setValue(\"Jane Doe\", 2.5f);\n\n\t\t// access a location directly from UR", "end": 1966, "score": 0.9998617172241211, "start": 1958, "tag": "NAME", "value": "Jane Doe" }, { "context": "nline\", ServerValue.TIMESTAMP);\n\t\tusersRef.child(\"john_doe\").updateChildren(johnDoeData, new CompletionListe", "end": 4327, "score": 0.8522561192512512, "start": 4319, "tag": "USERNAME", "value": "john_doe" }, { "context": "// write a node's priority only\n\t\tusersRef.child(\"john_doe\").child(\"score\").setPriority(500);\n\n\t\t// create a", "end": 4719, "score": 0.8397705554962158, "start": 4711, "tag": "USERNAME", "value": "john_doe" }, { "context": "rsonBean = new PersonBean();\n\t\tpersonBean.name = \"John Doe\";\n\t\tpersonBean.age = 42;\n\t\tpersonBean.location = ", "end": 5480, "score": 0.9997966885566711, "start": 5472, "tag": "NAME", "value": "John Doe" } ]
null
[]
package im.delight.android.ddp.firebase.examples; /** * Copyright 2014 www.delight.im <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context; import im.delight.android.ddp.firebase.ServerValue; import im.delight.android.ddp.firebase.ChildEventListener; import im.delight.android.ddp.firebase.DataSnapshot; import im.delight.android.ddp.firebase.ValueEventListener; import java.util.Map; import java.util.HashMap; import android.widget.Toast; import im.delight.android.ddp.firebase.FirebaseError; import im.delight.android.ddp.firebase.Firebase.CompletionListener; import im.delight.android.ddp.firebase.Firebase; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { private static final String SERVER_URL = "ws://example.meteor.com/websocket"; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = getApplicationContext(); // set the Android context (which has no effect here and is only there for compatibility) Firebase.setAndroidContext(this); // create the first reference to the server's URL Firebase mainRef = new Firebase(SERVER_URL); // create another reference to a child node Firebase usersRef = mainRef.child("users"); // write data to a child node usersRef.child("jane_doe").setValue("<NAME>", 2.5f); // access a location directly from URL and remove the value new Firebase(SERVER_URL+"/some/outdated/child").removeValue(); // watch the connection state Firebase connectedState = new Firebase(SERVER_URL+"/.info/connected"); connectedState.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { final boolean connected = snapshot.getValue(Boolean.class); final String status = connected ? "connected" : "disconnected"; Toast.makeText(context, "Connectivity changed: "+status, Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(FirebaseError error) { } }); // get the offset from local time to server time new Firebase(SERVER_URL+"/.info/serverTimeOffset").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { Toast.makeText(context, "Server time offset received: "+snapshot.getValue(Long.class), Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(FirebaseError error) { } }); // subscribe to updates in the `users` location usersRef.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot snapshot, String previousChildName) { Toast.makeText(context, "Child added on reference `"+snapshot.getKey()+"`", Toast.LENGTH_SHORT).show(); } @Override public void onChildChanged(DataSnapshot snapshot, String previousChildName) { Toast.makeText(context, "Child changed on reference `"+snapshot.getKey()+"`", Toast.LENGTH_SHORT).show(); } @Override public void onChildRemoved(DataSnapshot snapshot) { Toast.makeText(context, "Child removed on reference `"+snapshot.getKey()+"`", Toast.LENGTH_SHORT).show(); } @Override public void onChildMoved(DataSnapshot snapshot, String previousChildName) { Toast.makeText(context, "Child moved on reference `"+snapshot.getKey()+"`", Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(FirebaseError error) { } }); // write several children at once in a given location Map<String, Object> johnDoeData = new HashMap<String, Object>(); johnDoeData.put("score", 1024); johnDoeData.put("active", false); johnDoeData.put("last_online", ServerValue.TIMESTAMP); usersRef.child("john_doe").updateChildren(johnDoeData, new CompletionListener() { @Override public void onComplete(FirebaseError error, Firebase ref) { String response = "Listener on `"+ref.getKey()+"` completed "+(error != null ? "with an error" : "successfully"); Toast.makeText(context, response, Toast.LENGTH_SHORT).show(); } }); // write a node's priority only usersRef.child("john_doe").child("score").setPriority(500); // create an automatically named child with `push()` final Firebase pushedRef = usersRef.getParent().child("randomEntries").push(); // read a plain Java object (POJO) from storage pushedRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { PersonBean personBean = snapshot.getValue(PersonBean.class); Toast.makeText(context, "PersonBean received: "+personBean, Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(FirebaseError error) { } }); // write a plain Java object (POJO) to the storage that will be serialized automatically PersonBean personBean = new PersonBean(); personBean.name = "<NAME>"; personBean.age = 42; personBean.location = "Example City"; pushedRef.setValue(personBean); } @Override public void onDestroy() { super.onDestroy(); // manually force the client to disconnect Firebase.goOffline(); } }
5,707
0.738416
0.735094
168
33.041668
31.64373
118
false
false
0
0
0
0
0
0
1.970238
false
false
13
5869d4df9b0770ec26d8a5790adf7cb7bee4d125
11,527,692,285,742
3bdc001eec515187c7e57af1fdbe03c11e41df90
/MPSimpleCRUD/src/itdc/adcootauco/routes/Update.java
6c57c7aa873342eeb32ebec8dc8204da0af200ae
[]
no_license
foncyc/MPSimpleCRUD
https://github.com/foncyc/MPSimpleCRUD
bec945a384f5c0e8c9137cf37715e0e282305f8e
d3b4d09bc71a650e1996b4048365ebcc00bd4575
refs/heads/master
2021-01-20T09:06:56.705000
2017-05-08T07:27:45
2017-05-08T07:27:45
90,222,074
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package itdc.adcootauco.routes; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import itdc.adcootauco.data.DataService; import itdc.adcootauco.model.Member; @WebServlet("/update") public class Update extends HttpServlet { private static final long serialVersionUID = 1L; public Update() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Member member = (Member) request.getAttribute("member"); System.out.println(member.getId()); System.out.println(member.getFirstName()); System.out.println(member.getLastName()); DataService service = new DataService(); service.updateMember(member); response.sendRedirect("index"); // RequestDispatcher rd = request.getRequestDispatcher("index"); // rd.forward(request, response); } }
UTF-8
Java
1,284
java
Update.java
Java
[]
null
[]
package itdc.adcootauco.routes; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import itdc.adcootauco.data.DataService; import itdc.adcootauco.model.Member; @WebServlet("/update") public class Update extends HttpServlet { private static final long serialVersionUID = 1L; public Update() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Member member = (Member) request.getAttribute("member"); System.out.println(member.getId()); System.out.println(member.getFirstName()); System.out.println(member.getLastName()); DataService service = new DataService(); service.updateMember(member); response.sendRedirect("index"); // RequestDispatcher rd = request.getRequestDispatcher("index"); // rd.forward(request, response); } }
1,284
0.753115
0.752336
47
25.319149
22.76906
80
false
false
0
0
0
0
0
0
1.425532
false
false
13
d86856c55d8814da24afc73043a530ee6487fea2
6,605,659,720,406
8bd969ca2f422151f9ac274ff3f86ec843cbd4d3
/project/mes-common-branch3/src/main/java/com/hp/message/vo/rcl/R117.java
21fc31bd2f8bbe1e774d6ca5cf2f2cfa8bde737e
[]
no_license
shijingyu/SGJT
https://github.com/shijingyu/SGJT
5cc173a2a8fa700e962077c81dea733b37664943
6932405fa2eb7903198b4b87bc0847e6c7b027f0
refs/heads/master
2019-01-28T14:02:55.329000
2017-10-26T05:33:51
2017-10-26T05:33:51
98,390,618
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hp.message.vo.rcl; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.builder.ToStringBuilder; import com.hp.common.util.ReflectUtil; import com.hp.message.vo.AbstractCglL2Message; import com.hp.message.vo.L2Messaging; import com.thoughtworks.xstream.annotations.XStreamAlias; /** * --------------------------------------------------------------------------------- Confidential and Proprietary Copyright 2008 By SGAI & Hewlett-Packard Development Company, L.P. All Rights Reserved Project Name : SGAI MES Class Name : R117.java Package : com.hp.message.vo.rcl @version $Id$ @author Yandong @since 2009-9-27 */ @XStreamAlias("R117") public class R117 extends AbstractCglL2Message implements L2Messaging { /** * */ private static final long serialVersionUID = 6903212334017886290L; /** * predefined message type id */ private static final String messageTypeId = "R117"; /** * it is blank when send */ @XStreamAlias("ENTRY_COIL_ID") private String entryCoilId; @XStreamAlias("LAST_PCOIL") private Integer lastPiece; @XStreamAlias("PCOIL_ID") private String productCoilId; @XStreamAlias("SHIFT") private String shiftId; @XStreamAlias("CREW") private String crewId; @XStreamAlias("PROD_END") private String timeEnd; @XStreamAlias("PROD_START") private String timeStart; @XStreamAlias("PROD_DURATION") private Double duration; @XStreamAlias("WEIGHT_SCALE") private Double weightMeasured; @XStreamAlias("WEIGHT_CALC") private Double weightCalc; @XStreamAlias("WIDTH") private Double tgtFmWidth; @XStreamAlias("THICKNESS") private Double tgtFmThk; @XStreamAlias("LENGTH") private Double coilLength; @XStreamAlias("DIAMETER_INSIDE") private Double diameterInner; @XStreamAlias("DIAMETER_OUTSIDE") private Double diameterOuter; @XStreamAlias("WINDING_MODE") private String windingMode; @XStreamAlias("ExitInspectionDefectsItem") public List<ExitInspectionDefects> exitInspectionDefectsItem; @XStreamAlias("AnalogQualityValuesItem") public List<AnalogQualityValues> analogQualityValuesItem; @XStreamAlias("CoilConsumptionDataItem") public List<CoilConsumptionData> coilConsumptionDataItem; public R117() { this.exitInspectionDefectsItem = new ArrayList<ExitInspectionDefects>(); this.analogQualityValuesItem = new ArrayList<AnalogQualityValues>(); this.coilConsumptionDataItem = new ArrayList<CoilConsumptionData>(); } public final void addExitInspectionDefectsItem( ExitInspectionDefects exitInspectionDefects) { this.exitInspectionDefectsItem.add(exitInspectionDefects); } public final void addAnalogQualityValuesItem( AnalogQualityValues analogQualityValues) { this.analogQualityValuesItem.add(analogQualityValues); } public void addAllExitInspectionDefectsItem( List<ExitInspectionDefects> exitInspectionDefectsItem) { this.exitInspectionDefectsItem.addAll(exitInspectionDefectsItem); } public void addAllAnalogQualityValuesItem( List<AnalogQualityValues> analogQualityValuesItem) { this.analogQualityValuesItem.addAll(analogQualityValuesItem); } public final int sizeExitInspectionDefectsItem() { return this.exitInspectionDefectsItem.size(); } public final int sizeAnalogQualityValuesItem() { return this.analogQualityValuesItem.size(); } public final Iterator<ExitInspectionDefects> iteratorExitInspectionDefectsItem() { return this.exitInspectionDefectsItem.iterator(); } public final Iterator<AnalogQualityValues> iteratorAnalogQualityValuesItem() { return this.analogQualityValuesItem.iterator(); } public final void addCoilConsumptionDataItem( CoilConsumptionData coilConsumptionData) { this.coilConsumptionDataItem.add(coilConsumptionData); } public void addAllCoilConsumptionDataItem( List<CoilConsumptionData> coilConsumptionDataItem) { this.coilConsumptionDataItem.addAll(coilConsumptionDataItem); } public final int sizeCoilConsumptionDataItem() { return this.coilConsumptionDataItem.size(); } public final Iterator<CoilConsumptionData> iteratorCoilConsumptionDataItem() { return this.coilConsumptionDataItem.iterator(); } @XStreamAlias("ExitInspectionDefects") public static final class ExitInspectionDefects { @XStreamAlias("POS_START") private String posStart; @XStreamAlias("POS_END") private String posEnd; @XStreamAlias("DEFECT_CODE") private String defectCode; @XStreamAlias("DEFECT_SIDE") private String defectSide; @XStreamAlias("INTENSITY") private String intensity; @XStreamAlias("DEFECT_POSITION") private String defectPosition; @XStreamAlias("DEFECT_COMMENT") private String defectComment; /** * @return the posStart */ public String getPosStart() { return posStart; } /** * @param posStart the posStart to set */ public void setPosStart(String posStart) { this.posStart = posStart; } /** * @return the posEnd */ public String getPosEnd() { return posEnd; } /** * @param posEnd the posEnd to set */ public void setPosEnd(String posEnd) { this.posEnd = posEnd; } /** * @return the defectCode */ public String getDefectCode() { return defectCode; } /** * @param defectCode the defectCode to set */ public void setDefectCode(String defectCode) { this.defectCode = defectCode; } /** * @return the defectSide */ public String getDefectSide() { return defectSide; } /** * @param defectSide the defectSide to set */ public void setDefectSide(String defectSide) { this.defectSide = defectSide; } /** * @return the intensity */ public String getIntensity() { return intensity; } /** * @param intensity the intensity to set */ public void setIntensity(String intensity) { this.intensity = intensity; } /** * @return the defectPosition */ public String getDefectPosition() { return defectPosition; } /** * @param defectPosition the defectPosition to set */ public void setDefectPosition(String defectPosition) { this.defectPosition = defectPosition; } /** * @return the defectComment */ public String getDefectComment() { return defectComment; } /** * @param defectComment the defectComment to set */ public void setDefectComment(String defectComment) { this.defectComment = defectComment; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((intensity == null) ? 0 : intensity.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof ExitInspectionDefects)) return false; final ExitInspectionDefects other = (ExitInspectionDefects) obj; if (intensity == null) { if (other.intensity != null) return false; } else if (!intensity.equals(other.intensity)) return false; return true; } public String toString() { return new ToStringBuilder(this).append(this.intensity).toString(); } } @XStreamAlias("AnalogQualityValues") public static final class AnalogQualityValues { @XStreamAlias("MIN") private Double min; @XStreamAlias("MAX") private Double max; @XStreamAlias("AVG") private Double avg; @XStreamAlias("STD_DEV") private Double stdDev; /** * @return the min */ public Double getMin() { return min; } /** * @param min the min to set */ public void setMin(Double min) { this.min = min; } /** * @return the max */ public Double getMax() { return max; } /** * @param max the max to set */ public void setMax(Double max) { this.max = max; } /** * @return the avg */ public Double getAvg() { return avg; } /** * @param avg the avg to set */ public void setAvg(Double avg) { this.avg = avg; } /** * @return the stdDev */ public Double getStdDev() { return stdDev; } /** * @param stdDev the stdDev to set */ public void setStdDev(Double stdDev) { this.stdDev = stdDev; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((min == null) ? 0 : min.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof AnalogQualityValues)) return false; final AnalogQualityValues other = (AnalogQualityValues) obj; if (min == null) { if (other.min != null) return false; } else if (!min.equals(other.min)) return false; return true; } public String toString() { return new ToStringBuilder(this).append(this.min).toString(); } } @XStreamAlias("CoilConsumptionData") public static final class CoilConsumptionData { @XStreamAlias("Value_NN") private Double valueNn; /** * @return the valueNn */ public Double getValueNn() { return valueNn; } /** * @param valueNn the valueNn to set */ public void setValueNn(Double valueNn) { this.valueNn = valueNn; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((valueNn == null) ? 0 : valueNn.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof CoilConsumptionData)) return false; final CoilConsumptionData other = (CoilConsumptionData) obj; if (valueNn == null) { if (other.valueNn != null) return false; } else if (!valueNn.equals(other.valueNn)) return false; return true; } } /** * @return the productCoilId */ public String getProductCoilId() { return productCoilId; } /** * @param productCoilId the productCoilId to set */ public void setProductCoilId(String productCoilId) { this.productCoilId = productCoilId; } /** * @return the shiftId */ public String getShiftId() { return shiftId; } /** * @param shiftId the shiftId to set */ public void setShiftId(String shiftId) { this.shiftId = shiftId; } /** * @return the crewId */ public String getCrewId() { return crewId; } /** * @param crewId the crewId to set */ public void setCrewId(String crewId) { this.crewId = crewId; } /** * @return the timeEnd */ public String getTimeEnd() { return timeEnd; } /** * @param timeEnd the timeEnd to set */ public void setTimeEnd(String timeEnd) { this.timeEnd = timeEnd; } /** * @return the timeStart */ public String getTimeStart() { return timeStart; } /** * @param timeStart the timeStart to set */ public void setTimeStart(String timeStart) { this.timeStart = timeStart; } /** * @return the duration */ public Double getDuration() { return duration; } /** * @param duration the duration to set */ public void setDuration(Double duration) { this.duration = duration; } /** * @return the weightMeasured */ public Double getWeightMeasured() { return weightMeasured; } /** * @param weightMeasured the weightMeasured to set */ public void setWeightMeasured(Double weightMeasured) { this.weightMeasured = weightMeasured; } /** * @return the weightCalc */ public Double getWeightCalc() { return weightCalc; } /** * @param weightCalc the weightCalc to set */ public void setWeightCalc(Double weightCalc) { this.weightCalc = weightCalc; } /** * @return the tgtFmWidth */ public Double getTgtFmWidth() { return tgtFmWidth; } /** * @param tgtFmWidth the tgtFmWidth to set */ public void setTgtFmWidth(Double tgtFmWidth) { this.tgtFmWidth = tgtFmWidth; } /** * @return the tgtFmThk */ public Double getTgtFmThk() { return tgtFmThk; } /** * @param tgtFmThk the tgtFmThk to set */ public void setTgtFmThk(Double tgtFmThk) { this.tgtFmThk = tgtFmThk; } /** * @return the length */ public Double getCoilLength() { return coilLength; } /** * @param length the length to set */ public void setCoilLength(Double coilLength) { this.coilLength = coilLength; } /** * @return the diameterInner */ public Double getDiameterInner() { return diameterInner; } /** * @param diameterInner the diameterInner to set */ public void setDiameterInner(Double diameterInner) { this.diameterInner = diameterInner; } /** * @return the diameterOuter */ public Double getDiameterOuter() { return diameterOuter; } /** * @param diameterOuter the diameterOuter to set */ public void setDiameterOuter(Double diameterOuter) { this.diameterOuter = diameterOuter; } /** * @return the windingMode */ public String getWindingMode() { return windingMode; } /** * @param windingMode the windingMode to set */ public void setWindingMode(String windingMode) { this.windingMode = windingMode; } // /** // * @return the lockCode // */ // public String getLockCode() { // return lockCode; // } // // /** // * @param lockCode the lockCode to set // */ // public void setLockCode(String lockCode) { // this.lockCode = lockCode; // } // // /** // * @return the lockReason // */ // public String getLockReason() { // return lockReason; // } // // /** // * @param lockReason the lockReason to set // */ // public void setLockReason(String lockReason) { // this.lockReason = lockReason; // } /** * @return the exitInspectionDefectsItem */ public List<ExitInspectionDefects> getExitInspectionDefectsItem() { return exitInspectionDefectsItem; } /** * @param exitInspectionDefectsItem the exitInspectionDefectsItem to set */ public void setExitInspectionDefectsItem( List<ExitInspectionDefects> exitInspectionDefectsItem) { this.exitInspectionDefectsItem = exitInspectionDefectsItem; } /** * @return the analogQualityValuesItem */ public List<AnalogQualityValues> getAnalogQualityValuesItem() { return analogQualityValuesItem; } /** * @param analogQualityValuesItem the analogQualityValuesItem to set */ public void setAnalogQualityValuesItem( List<AnalogQualityValues> analogQualityValuesItem) { this.analogQualityValuesItem = analogQualityValuesItem; } /** * @return the spmFlag */ // public String getSpmFlag() { // return spmFlag; // } // // /** // * @param spmFlag the spmFlag to set // */ // public void setSpmFlag(String spmFlag) { // this.spmFlag = spmFlag; // } // // /** // * @return the spmElong // */ // public Double getSpmElong() { // return spmElong; // } // // /** // * @param spmElong the spmElong to set // */ // public void setSpmElong(Double spmElong) { // this.spmElong = spmElong; // } // // // // /** // * @return the oilFlag // */ // public String getOilFlag() { // return oilFlag; // } /** * @param oilFlag the oilFlag to set */ // public void setOilFlag(String oilFlag) { // this.oilFlag = oilFlag; // } // /** * @return the lastPiece */ public Integer getLastPiece() { return lastPiece; } /** * @param lastPiece the lastPiece to set */ public void setLastPiece(Integer lastPiece) { this.lastPiece = lastPiece; } /** * @return the entryCoilId */ public String getEntryCoilId() { return entryCoilId; } /** * @param entryCoilId the entryCoilId to set */ public void setEntryCoilId(String entryCoilId) { this.entryCoilId = entryCoilId; } /** * @return the messageTypeId */ public String getMessageTypeId() { return messageTypeId; } public String toString() { return new ToStringBuilder(this).append(this.getMessageHeader()) .append(this.entryCoilId).append(this.crewId).toString(); } /** * ็”จReflectionๆœบๅˆถๅพ—ๅˆฐๆ‰€ๆœ‰ๅฑžๆ€ง็š„Mapๅฝขๅผ * @return * @author xiali2 * @since 2008-10-14 */ public Map<String, Object> getMapFieldData() { Map<String,Object> fielData= ReflectUtil.getMapFieldData(this); fielData.remove("exitInspectionDefectsItem"); fielData.remove("analogQualityValuesItem"); fielData.remove("coilConsumptionDataItem"); return fielData; } }
UTF-8
Java
19,897
java
R117.java
Java
[ { "context": " \n @author Yandong\n @since 2009-9-27 \n */\n@XStreamAlias(\"R117\")\npub", "end": 1219, "score": 0.9932036399841309, "start": 1212, "tag": "NAME", "value": "Yandong" }, { "context": "ectionๆœบๅˆถๅพ—ๅˆฐๆ‰€ๆœ‰ๅฑžๆ€ง็š„Mapๅฝขๅผ\n * @return\n * @author xiali2\n * @since 2008-10-14\n */\n public Map<", "end": 19523, "score": 0.9995395541191101, "start": 19517, "tag": "USERNAME", "value": "xiali2" } ]
null
[]
package com.hp.message.vo.rcl; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.builder.ToStringBuilder; import com.hp.common.util.ReflectUtil; import com.hp.message.vo.AbstractCglL2Message; import com.hp.message.vo.L2Messaging; import com.thoughtworks.xstream.annotations.XStreamAlias; /** * --------------------------------------------------------------------------------- Confidential and Proprietary Copyright 2008 By SGAI & Hewlett-Packard Development Company, L.P. All Rights Reserved Project Name : SGAI MES Class Name : R117.java Package : com.hp.message.vo.rcl @version $Id$ @author Yandong @since 2009-9-27 */ @XStreamAlias("R117") public class R117 extends AbstractCglL2Message implements L2Messaging { /** * */ private static final long serialVersionUID = 6903212334017886290L; /** * predefined message type id */ private static final String messageTypeId = "R117"; /** * it is blank when send */ @XStreamAlias("ENTRY_COIL_ID") private String entryCoilId; @XStreamAlias("LAST_PCOIL") private Integer lastPiece; @XStreamAlias("PCOIL_ID") private String productCoilId; @XStreamAlias("SHIFT") private String shiftId; @XStreamAlias("CREW") private String crewId; @XStreamAlias("PROD_END") private String timeEnd; @XStreamAlias("PROD_START") private String timeStart; @XStreamAlias("PROD_DURATION") private Double duration; @XStreamAlias("WEIGHT_SCALE") private Double weightMeasured; @XStreamAlias("WEIGHT_CALC") private Double weightCalc; @XStreamAlias("WIDTH") private Double tgtFmWidth; @XStreamAlias("THICKNESS") private Double tgtFmThk; @XStreamAlias("LENGTH") private Double coilLength; @XStreamAlias("DIAMETER_INSIDE") private Double diameterInner; @XStreamAlias("DIAMETER_OUTSIDE") private Double diameterOuter; @XStreamAlias("WINDING_MODE") private String windingMode; @XStreamAlias("ExitInspectionDefectsItem") public List<ExitInspectionDefects> exitInspectionDefectsItem; @XStreamAlias("AnalogQualityValuesItem") public List<AnalogQualityValues> analogQualityValuesItem; @XStreamAlias("CoilConsumptionDataItem") public List<CoilConsumptionData> coilConsumptionDataItem; public R117() { this.exitInspectionDefectsItem = new ArrayList<ExitInspectionDefects>(); this.analogQualityValuesItem = new ArrayList<AnalogQualityValues>(); this.coilConsumptionDataItem = new ArrayList<CoilConsumptionData>(); } public final void addExitInspectionDefectsItem( ExitInspectionDefects exitInspectionDefects) { this.exitInspectionDefectsItem.add(exitInspectionDefects); } public final void addAnalogQualityValuesItem( AnalogQualityValues analogQualityValues) { this.analogQualityValuesItem.add(analogQualityValues); } public void addAllExitInspectionDefectsItem( List<ExitInspectionDefects> exitInspectionDefectsItem) { this.exitInspectionDefectsItem.addAll(exitInspectionDefectsItem); } public void addAllAnalogQualityValuesItem( List<AnalogQualityValues> analogQualityValuesItem) { this.analogQualityValuesItem.addAll(analogQualityValuesItem); } public final int sizeExitInspectionDefectsItem() { return this.exitInspectionDefectsItem.size(); } public final int sizeAnalogQualityValuesItem() { return this.analogQualityValuesItem.size(); } public final Iterator<ExitInspectionDefects> iteratorExitInspectionDefectsItem() { return this.exitInspectionDefectsItem.iterator(); } public final Iterator<AnalogQualityValues> iteratorAnalogQualityValuesItem() { return this.analogQualityValuesItem.iterator(); } public final void addCoilConsumptionDataItem( CoilConsumptionData coilConsumptionData) { this.coilConsumptionDataItem.add(coilConsumptionData); } public void addAllCoilConsumptionDataItem( List<CoilConsumptionData> coilConsumptionDataItem) { this.coilConsumptionDataItem.addAll(coilConsumptionDataItem); } public final int sizeCoilConsumptionDataItem() { return this.coilConsumptionDataItem.size(); } public final Iterator<CoilConsumptionData> iteratorCoilConsumptionDataItem() { return this.coilConsumptionDataItem.iterator(); } @XStreamAlias("ExitInspectionDefects") public static final class ExitInspectionDefects { @XStreamAlias("POS_START") private String posStart; @XStreamAlias("POS_END") private String posEnd; @XStreamAlias("DEFECT_CODE") private String defectCode; @XStreamAlias("DEFECT_SIDE") private String defectSide; @XStreamAlias("INTENSITY") private String intensity; @XStreamAlias("DEFECT_POSITION") private String defectPosition; @XStreamAlias("DEFECT_COMMENT") private String defectComment; /** * @return the posStart */ public String getPosStart() { return posStart; } /** * @param posStart the posStart to set */ public void setPosStart(String posStart) { this.posStart = posStart; } /** * @return the posEnd */ public String getPosEnd() { return posEnd; } /** * @param posEnd the posEnd to set */ public void setPosEnd(String posEnd) { this.posEnd = posEnd; } /** * @return the defectCode */ public String getDefectCode() { return defectCode; } /** * @param defectCode the defectCode to set */ public void setDefectCode(String defectCode) { this.defectCode = defectCode; } /** * @return the defectSide */ public String getDefectSide() { return defectSide; } /** * @param defectSide the defectSide to set */ public void setDefectSide(String defectSide) { this.defectSide = defectSide; } /** * @return the intensity */ public String getIntensity() { return intensity; } /** * @param intensity the intensity to set */ public void setIntensity(String intensity) { this.intensity = intensity; } /** * @return the defectPosition */ public String getDefectPosition() { return defectPosition; } /** * @param defectPosition the defectPosition to set */ public void setDefectPosition(String defectPosition) { this.defectPosition = defectPosition; } /** * @return the defectComment */ public String getDefectComment() { return defectComment; } /** * @param defectComment the defectComment to set */ public void setDefectComment(String defectComment) { this.defectComment = defectComment; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((intensity == null) ? 0 : intensity.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof ExitInspectionDefects)) return false; final ExitInspectionDefects other = (ExitInspectionDefects) obj; if (intensity == null) { if (other.intensity != null) return false; } else if (!intensity.equals(other.intensity)) return false; return true; } public String toString() { return new ToStringBuilder(this).append(this.intensity).toString(); } } @XStreamAlias("AnalogQualityValues") public static final class AnalogQualityValues { @XStreamAlias("MIN") private Double min; @XStreamAlias("MAX") private Double max; @XStreamAlias("AVG") private Double avg; @XStreamAlias("STD_DEV") private Double stdDev; /** * @return the min */ public Double getMin() { return min; } /** * @param min the min to set */ public void setMin(Double min) { this.min = min; } /** * @return the max */ public Double getMax() { return max; } /** * @param max the max to set */ public void setMax(Double max) { this.max = max; } /** * @return the avg */ public Double getAvg() { return avg; } /** * @param avg the avg to set */ public void setAvg(Double avg) { this.avg = avg; } /** * @return the stdDev */ public Double getStdDev() { return stdDev; } /** * @param stdDev the stdDev to set */ public void setStdDev(Double stdDev) { this.stdDev = stdDev; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((min == null) ? 0 : min.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof AnalogQualityValues)) return false; final AnalogQualityValues other = (AnalogQualityValues) obj; if (min == null) { if (other.min != null) return false; } else if (!min.equals(other.min)) return false; return true; } public String toString() { return new ToStringBuilder(this).append(this.min).toString(); } } @XStreamAlias("CoilConsumptionData") public static final class CoilConsumptionData { @XStreamAlias("Value_NN") private Double valueNn; /** * @return the valueNn */ public Double getValueNn() { return valueNn; } /** * @param valueNn the valueNn to set */ public void setValueNn(Double valueNn) { this.valueNn = valueNn; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((valueNn == null) ? 0 : valueNn.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof CoilConsumptionData)) return false; final CoilConsumptionData other = (CoilConsumptionData) obj; if (valueNn == null) { if (other.valueNn != null) return false; } else if (!valueNn.equals(other.valueNn)) return false; return true; } } /** * @return the productCoilId */ public String getProductCoilId() { return productCoilId; } /** * @param productCoilId the productCoilId to set */ public void setProductCoilId(String productCoilId) { this.productCoilId = productCoilId; } /** * @return the shiftId */ public String getShiftId() { return shiftId; } /** * @param shiftId the shiftId to set */ public void setShiftId(String shiftId) { this.shiftId = shiftId; } /** * @return the crewId */ public String getCrewId() { return crewId; } /** * @param crewId the crewId to set */ public void setCrewId(String crewId) { this.crewId = crewId; } /** * @return the timeEnd */ public String getTimeEnd() { return timeEnd; } /** * @param timeEnd the timeEnd to set */ public void setTimeEnd(String timeEnd) { this.timeEnd = timeEnd; } /** * @return the timeStart */ public String getTimeStart() { return timeStart; } /** * @param timeStart the timeStart to set */ public void setTimeStart(String timeStart) { this.timeStart = timeStart; } /** * @return the duration */ public Double getDuration() { return duration; } /** * @param duration the duration to set */ public void setDuration(Double duration) { this.duration = duration; } /** * @return the weightMeasured */ public Double getWeightMeasured() { return weightMeasured; } /** * @param weightMeasured the weightMeasured to set */ public void setWeightMeasured(Double weightMeasured) { this.weightMeasured = weightMeasured; } /** * @return the weightCalc */ public Double getWeightCalc() { return weightCalc; } /** * @param weightCalc the weightCalc to set */ public void setWeightCalc(Double weightCalc) { this.weightCalc = weightCalc; } /** * @return the tgtFmWidth */ public Double getTgtFmWidth() { return tgtFmWidth; } /** * @param tgtFmWidth the tgtFmWidth to set */ public void setTgtFmWidth(Double tgtFmWidth) { this.tgtFmWidth = tgtFmWidth; } /** * @return the tgtFmThk */ public Double getTgtFmThk() { return tgtFmThk; } /** * @param tgtFmThk the tgtFmThk to set */ public void setTgtFmThk(Double tgtFmThk) { this.tgtFmThk = tgtFmThk; } /** * @return the length */ public Double getCoilLength() { return coilLength; } /** * @param length the length to set */ public void setCoilLength(Double coilLength) { this.coilLength = coilLength; } /** * @return the diameterInner */ public Double getDiameterInner() { return diameterInner; } /** * @param diameterInner the diameterInner to set */ public void setDiameterInner(Double diameterInner) { this.diameterInner = diameterInner; } /** * @return the diameterOuter */ public Double getDiameterOuter() { return diameterOuter; } /** * @param diameterOuter the diameterOuter to set */ public void setDiameterOuter(Double diameterOuter) { this.diameterOuter = diameterOuter; } /** * @return the windingMode */ public String getWindingMode() { return windingMode; } /** * @param windingMode the windingMode to set */ public void setWindingMode(String windingMode) { this.windingMode = windingMode; } // /** // * @return the lockCode // */ // public String getLockCode() { // return lockCode; // } // // /** // * @param lockCode the lockCode to set // */ // public void setLockCode(String lockCode) { // this.lockCode = lockCode; // } // // /** // * @return the lockReason // */ // public String getLockReason() { // return lockReason; // } // // /** // * @param lockReason the lockReason to set // */ // public void setLockReason(String lockReason) { // this.lockReason = lockReason; // } /** * @return the exitInspectionDefectsItem */ public List<ExitInspectionDefects> getExitInspectionDefectsItem() { return exitInspectionDefectsItem; } /** * @param exitInspectionDefectsItem the exitInspectionDefectsItem to set */ public void setExitInspectionDefectsItem( List<ExitInspectionDefects> exitInspectionDefectsItem) { this.exitInspectionDefectsItem = exitInspectionDefectsItem; } /** * @return the analogQualityValuesItem */ public List<AnalogQualityValues> getAnalogQualityValuesItem() { return analogQualityValuesItem; } /** * @param analogQualityValuesItem the analogQualityValuesItem to set */ public void setAnalogQualityValuesItem( List<AnalogQualityValues> analogQualityValuesItem) { this.analogQualityValuesItem = analogQualityValuesItem; } /** * @return the spmFlag */ // public String getSpmFlag() { // return spmFlag; // } // // /** // * @param spmFlag the spmFlag to set // */ // public void setSpmFlag(String spmFlag) { // this.spmFlag = spmFlag; // } // // /** // * @return the spmElong // */ // public Double getSpmElong() { // return spmElong; // } // // /** // * @param spmElong the spmElong to set // */ // public void setSpmElong(Double spmElong) { // this.spmElong = spmElong; // } // // // // /** // * @return the oilFlag // */ // public String getOilFlag() { // return oilFlag; // } /** * @param oilFlag the oilFlag to set */ // public void setOilFlag(String oilFlag) { // this.oilFlag = oilFlag; // } // /** * @return the lastPiece */ public Integer getLastPiece() { return lastPiece; } /** * @param lastPiece the lastPiece to set */ public void setLastPiece(Integer lastPiece) { this.lastPiece = lastPiece; } /** * @return the entryCoilId */ public String getEntryCoilId() { return entryCoilId; } /** * @param entryCoilId the entryCoilId to set */ public void setEntryCoilId(String entryCoilId) { this.entryCoilId = entryCoilId; } /** * @return the messageTypeId */ public String getMessageTypeId() { return messageTypeId; } public String toString() { return new ToStringBuilder(this).append(this.getMessageHeader()) .append(this.entryCoilId).append(this.crewId).toString(); } /** * ็”จReflectionๆœบๅˆถๅพ—ๅˆฐๆ‰€ๆœ‰ๅฑžๆ€ง็š„Mapๅฝขๅผ * @return * @author xiali2 * @since 2008-10-14 */ public Map<String, Object> getMapFieldData() { Map<String,Object> fielData= ReflectUtil.getMapFieldData(this); fielData.remove("exitInspectionDefectsItem"); fielData.remove("analogQualityValuesItem"); fielData.remove("coilConsumptionDataItem"); return fielData; } }
19,897
0.556735
0.553213
779
24.509628
21.367277
160
false
false
0
0
0
0
0
0
0.223363
false
false
13
9f9f90409e300fe5e431a5d97b3edfebff2bbc3f
6,605,659,719,347
4e0ce43c3bf0e2ca1e28c242a8c79e1017159746
/src/main/java/com/ovh/milestone/Util/ExchangeRateMapping.java
5dd0d21046916b2fe78de473ea385db2e49f4f87
[]
no_license
jlenotte/Milestone
https://github.com/jlenotte/Milestone
343913a03ae8ad9dcd8d6db78e7ed6763159801d
50eca437c0c11965f49466cb36ec9753fd151574
refs/heads/master
2021-01-19T15:22:58.128000
2017-12-30T01:58:57
2017-12-30T01:58:57
100,961,727
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ovh.milestone.Util; import com.opencsv.CSVReader; import com.ovh.milestone.Conversion.ForexRate; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import static org.junit.Assert.assertTrue; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * All currencies applied here are from EUR to USD The * * * Algorithm of the mapping is as follows : * * 1. Read the CSV file that contains the dates and FOREX rates 2. Check the quality of the CSV * file's data (date format & currency) 3. If the quality of the data is met, map the dates & * currencies as K, V * * Preferably, you might want to have a clean pre-processed CSV file, with dates formatted * like so : yyyy-MM-dd, sorted and without odd and special characters. */ public class ExchangeRateMapping { // This map will contain dates(Strings) as Key // and FOREX rates (Doubles) as Values private static final Logger LOG = LoggerFactory.getLogger(ExchangeRateMapping.class.getName()); public static final Map<String, Double> map = new TreeMap<>(); public Map<String, Double> csvToMap(String csvFile) throws IOException { Double lastKnownXRate = null; File f = new File("forex.csv"); try (BufferedWriter bw = new BufferedWriter(new FileWriter(f, false))) { // Read the CSV file try (CSVReader read = new CSVReader(new FileReader(csvFile), ',')) { String[] line; // Read every line as long as it is not null while ((line = read.readNext()) != null) { // Check that our line is splitted correctly if (line.length >= 2) { // Check that we have a correct K & V if (line[0] != null && isCorrectDate(line[0]) && isCorrectXRate(line[1])) { // If the Xrate is null, set the last known xrate if (line[1].isEmpty()) { // Add the values to the map map.put(line[0], lastKnownXRate); // Write to csv String date = line[0]; Double forex = lastKnownXRate; ForexRate fx = new ForexRate(date, forex); bw.write(fx.getDate() + "," + fx.getForex()); bw.newLine(); bw.flush(); } else { // If my K, V are ok, then I can put the info to the map map.put(line[0], Double.parseDouble(line[1])); // Add to temporary variable for off days // Set off days to previous known date lastKnownXRate = Double.parseDouble(line[1]); // Write to csv String date = line[0]; Double forex = lastKnownXRate; ForexRate fx = new ForexRate(date, forex); bw.write(fx.getDate() + "," + fx.getForex()); bw.newLine(); bw.flush(); } } } } } displayMap(map); } catch (Exception e) { LOG.error(e.getMessage()); } return map; } /** * display the map */ private void displayMap(final Map<String, Double> map) { for (Entry<String, Double> stringDoubleEntry : map.entrySet()) { LOG.debug(String.valueOf(stringDoubleEntry)); } } /** * Make sure that the date has a correct format */ private boolean isCorrectDate(String s) { // Check that the date contains 10 chars and matches the following regex : // "0000-00-00" aka yyyy/MM/dd if (s != null && s.trim().length() == 10 && "([0-9]{4})-([0-9]{2})-([0-9]{2})".matches(s)) { return true; } return false; } /** * Format date */ public String formatDate(String s) throws Exception { DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); DateFormat correctDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String newDate = null; // If the literal matches the variable, format the date if ("([0-9]{2})-([0-9]{2})-([0-9]{4})".matches(s)) { newDate = correctDateFormat.format(df.parse(s)); } return newDate; } /** * Make sure that the Xrate is not problematic /!\ this is very important as Xrates that are * equal to 0 will completely mess up the process and program /!\ */ private boolean isCorrectXRate(String s) throws Exception { Pattern pattern = Pattern.compile("[$&+,:;=?@#|'<>.-^*()%!]"); Matcher matcher = pattern.matcher("\\.[]{}()*+-?^$|"); try { // Check that that the line's length is > 0 if (s.trim().length() >= 1) { // if correct, return true return true; } } catch (Exception e) { LOG.error(e.getMessage()); } return true; } }
UTF-8
Java
5,771
java
ExchangeRateMapping.java
Java
[]
null
[]
package com.ovh.milestone.Util; import com.opencsv.CSVReader; import com.ovh.milestone.Conversion.ForexRate; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import static org.junit.Assert.assertTrue; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * All currencies applied here are from EUR to USD The * * * Algorithm of the mapping is as follows : * * 1. Read the CSV file that contains the dates and FOREX rates 2. Check the quality of the CSV * file's data (date format & currency) 3. If the quality of the data is met, map the dates & * currencies as K, V * * Preferably, you might want to have a clean pre-processed CSV file, with dates formatted * like so : yyyy-MM-dd, sorted and without odd and special characters. */ public class ExchangeRateMapping { // This map will contain dates(Strings) as Key // and FOREX rates (Doubles) as Values private static final Logger LOG = LoggerFactory.getLogger(ExchangeRateMapping.class.getName()); public static final Map<String, Double> map = new TreeMap<>(); public Map<String, Double> csvToMap(String csvFile) throws IOException { Double lastKnownXRate = null; File f = new File("forex.csv"); try (BufferedWriter bw = new BufferedWriter(new FileWriter(f, false))) { // Read the CSV file try (CSVReader read = new CSVReader(new FileReader(csvFile), ',')) { String[] line; // Read every line as long as it is not null while ((line = read.readNext()) != null) { // Check that our line is splitted correctly if (line.length >= 2) { // Check that we have a correct K & V if (line[0] != null && isCorrectDate(line[0]) && isCorrectXRate(line[1])) { // If the Xrate is null, set the last known xrate if (line[1].isEmpty()) { // Add the values to the map map.put(line[0], lastKnownXRate); // Write to csv String date = line[0]; Double forex = lastKnownXRate; ForexRate fx = new ForexRate(date, forex); bw.write(fx.getDate() + "," + fx.getForex()); bw.newLine(); bw.flush(); } else { // If my K, V are ok, then I can put the info to the map map.put(line[0], Double.parseDouble(line[1])); // Add to temporary variable for off days // Set off days to previous known date lastKnownXRate = Double.parseDouble(line[1]); // Write to csv String date = line[0]; Double forex = lastKnownXRate; ForexRate fx = new ForexRate(date, forex); bw.write(fx.getDate() + "," + fx.getForex()); bw.newLine(); bw.flush(); } } } } } displayMap(map); } catch (Exception e) { LOG.error(e.getMessage()); } return map; } /** * display the map */ private void displayMap(final Map<String, Double> map) { for (Entry<String, Double> stringDoubleEntry : map.entrySet()) { LOG.debug(String.valueOf(stringDoubleEntry)); } } /** * Make sure that the date has a correct format */ private boolean isCorrectDate(String s) { // Check that the date contains 10 chars and matches the following regex : // "0000-00-00" aka yyyy/MM/dd if (s != null && s.trim().length() == 10 && "([0-9]{4})-([0-9]{2})-([0-9]{2})".matches(s)) { return true; } return false; } /** * Format date */ public String formatDate(String s) throws Exception { DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); DateFormat correctDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String newDate = null; // If the literal matches the variable, format the date if ("([0-9]{2})-([0-9]{2})-([0-9]{4})".matches(s)) { newDate = correctDateFormat.format(df.parse(s)); } return newDate; } /** * Make sure that the Xrate is not problematic /!\ this is very important as Xrates that are * equal to 0 will completely mess up the process and program /!\ */ private boolean isCorrectXRate(String s) throws Exception { Pattern pattern = Pattern.compile("[$&+,:;=?@#|'<>.-^*()%!]"); Matcher matcher = pattern.matcher("\\.[]{}()*+-?^$|"); try { // Check that that the line's length is > 0 if (s.trim().length() >= 1) { // if correct, return true return true; } } catch (Exception e) { LOG.error(e.getMessage()); } return true; } }
5,771
0.513429
0.504938
185
30.194595
28.97184
100
false
false
0
0
0
0
0
0
0.437838
false
false
13
3955161d79271c71b43a69f186f05df68c7d81e4
6,605,659,717,438
fe301144704b0f3fb3f126feee5c432ddeed4d29
/app/src/main/java/tk/winpooh32/omxrpicontroller/SettingsActivity.java
3e0dedcbcb068a559a057ae19f90a2adc1b5a8ae
[ "MIT" ]
permissive
WinPooh32/OmxRPiController
https://github.com/WinPooh32/OmxRPiController
db7253b4ba62c9fde7d18a41927f2bf1cf978287
d5c034a1050f0876e8494425771e0fa5a75bdca9
refs/heads/master
2020-04-23T11:14:19.679000
2019-02-17T14:09:11
2019-02-17T14:09:11
171,129,273
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tk.winpooh32.omxrpicontroller; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_settings); //addPreferencesFromResource(R.xml.preferences); // Display the fragment as the main content. getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); setTitle("Settings"); } public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); final ControllerApp app = (ControllerApp) this.getActivity().getApplicationContext(); final Preference ip = findPreference("ip"); final Preference port = findPreference("port"); final Preference path = findPreference("path"); final Preference connections = findPreference("connections"); final Preference uploads = findPreference("uploads"); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(app); ip.setSummary(app.serverIp); port.setSummary(app.serverPort); path.setSummary(prefs.getString("path","")); connections.setSummary(prefs.getString("connections","")); uploads.setSummary(prefs.getString("uploads","")); prefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if(key.equals("ip")){ app.serverIp = app.settings.getIp(); ip.setSummary(app.serverIp); } else if(key.equals("port")){ app.serverPort = app.settings.getPort(); port.setSummary(app.serverPort); } else if(key.equals("connections")){ connections.setSummary(sharedPreferences.getString("connections","")); } else if(key.equals("uploads")){ uploads.setSummary(sharedPreferences.getString("uploads","")); } else if(key.equals("path")){ path.setSummary(sharedPreferences.getString("path","")); } } }); } } // public static class SettingsFragment extends PreferenceFragment { // // private void setPreferencesFromResource(int preferences, String rootKey) { // setPreferencesFromResource(R.xml.preferences, rootKey); // } // //// @Override //// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //// //// mListPreference = (ListPreference) getPreferenceManager().findPreference("preference_key"); //// mListPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { //// @Override //// public boolean onPreferenceChange(Preference preference, Object newValue) { //// // your code here //// } //// } //// //// return inflater.inflate(R.layout.fragment_settings, container, false); //// } // } }
UTF-8
Java
4,017
java
SettingsActivity.java
Java
[ { "context": "package tk.winpooh32.omxrpicontroller;\n\nimport android.content.SharedP", "end": 20, "score": 0.9663884043693542, "start": 14, "tag": "USERNAME", "value": "pooh32" } ]
null
[]
package tk.winpooh32.omxrpicontroller; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_settings); //addPreferencesFromResource(R.xml.preferences); // Display the fragment as the main content. getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); setTitle("Settings"); } public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); final ControllerApp app = (ControllerApp) this.getActivity().getApplicationContext(); final Preference ip = findPreference("ip"); final Preference port = findPreference("port"); final Preference path = findPreference("path"); final Preference connections = findPreference("connections"); final Preference uploads = findPreference("uploads"); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(app); ip.setSummary(app.serverIp); port.setSummary(app.serverPort); path.setSummary(prefs.getString("path","")); connections.setSummary(prefs.getString("connections","")); uploads.setSummary(prefs.getString("uploads","")); prefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if(key.equals("ip")){ app.serverIp = app.settings.getIp(); ip.setSummary(app.serverIp); } else if(key.equals("port")){ app.serverPort = app.settings.getPort(); port.setSummary(app.serverPort); } else if(key.equals("connections")){ connections.setSummary(sharedPreferences.getString("connections","")); } else if(key.equals("uploads")){ uploads.setSummary(sharedPreferences.getString("uploads","")); } else if(key.equals("path")){ path.setSummary(sharedPreferences.getString("path","")); } } }); } } // public static class SettingsFragment extends PreferenceFragment { // // private void setPreferencesFromResource(int preferences, String rootKey) { // setPreferencesFromResource(R.xml.preferences, rootKey); // } // //// @Override //// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //// //// mListPreference = (ListPreference) getPreferenceManager().findPreference("preference_key"); //// mListPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { //// @Override //// public boolean onPreferenceChange(Preference preference, Object newValue) { //// // your code here //// } //// } //// //// return inflater.inflate(R.layout.fragment_settings, container, false); //// } // } }
4,017
0.608165
0.607418
99
39.575756
31.896959
117
false
false
0
0
0
0
0
0
0.535354
false
false
13
908d7fd7d79a9f32cf24690ce6ca2de01042b65b
27,169,963,173,130
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
/com.tencent.mm/classes.jar/com/tencent/mm/boot/svg/code/drawable/icons_filled_scissor.java
82f9f196be6fd254b3894564345b0c9671085bd5
[]
no_license
tsuzcx/qq_apk
https://github.com/tsuzcx/qq_apk
0d5e792c3c7351ab781957bac465c55c505caf61
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
refs/heads/main
2022-07-02T10:32:11.651000
2022-02-01T12:41:38
2022-02-01T12:41:38
453,860,108
36
9
null
false
2022-01-31T09:46:26
2022-01-31T02:43:22
2022-01-31T06:56:43
2022-01-31T09:46:26
167,304
0
1
1
Java
false
false
package com.tencent.mm.boot.svg.code.drawable; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import android.os.Looper; import com.tencent.mm.svg.WeChatSVGRenderC2Java; import com.tencent.mm.svg.c; public class icons_filled_scissor extends c { private final int height = 72; private final int width = 72; public int doCommand(int paramInt, Object... paramVarArgs) { switch (paramInt) { } for (;;) { return 0; return 72; return 72; Canvas localCanvas = (Canvas)paramVarArgs[0]; paramVarArgs = (Looper)paramVarArgs[1]; Object localObject1 = c.instanceMatrix(paramVarArgs); Object localObject2 = c.instanceMatrixArray(paramVarArgs); Paint localPaint1 = c.instancePaint(paramVarArgs); localPaint1.setFlags(385); localPaint1.setStyle(Paint.Style.FILL); Paint localPaint2 = c.instancePaint(paramVarArgs); localPaint2.setFlags(385); localPaint2.setStyle(Paint.Style.STROKE); localPaint1.setColor(-16777216); localPaint2.setStrokeWidth(1.0F); localPaint2.setStrokeCap(Paint.Cap.BUTT); localPaint2.setStrokeJoin(Paint.Join.MITER); localPaint2.setStrokeMiter(4.0F); localPaint2.setPathEffect(null); c.instancePaint(localPaint2, paramVarArgs).setStrokeWidth(1.0F); localCanvas.save(); localPaint1 = c.instancePaint(localPaint1, paramVarArgs); localPaint1.setColor(-436207616); localObject2 = c.setMatrixFloatArray((float[])localObject2, 1.0F, 0.0F, 9.0F, 0.0F, 1.0F, 9.0F, 0.0F, 0.0F, 1.0F); ((Matrix)localObject1).reset(); ((Matrix)localObject1).setValues((float[])localObject2); localCanvas.concat((Matrix)localObject1); localCanvas.save(); localObject1 = c.instancePaint(localPaint1, paramVarArgs); localObject2 = c.instancePath(paramVarArgs); ((Path)localObject2).moveTo(12.176471F, 28.852942F); ((Path)localObject2).cubicTo(18.90135F, 28.852942F, 24.352942F, 34.304531F, 24.352942F, 41.029411F); ((Path)localObject2).cubicTo(24.352942F, 47.754292F, 18.90135F, 53.205883F, 12.176471F, 53.205883F); ((Path)localObject2).cubicTo(5.451592F, 53.205883F, 0.0F, 47.754292F, 0.0F, 41.029411F); ((Path)localObject2).cubicTo(0.0F, 34.304531F, 5.451592F, 28.852942F, 12.176471F, 28.852942F); ((Path)localObject2).close(); ((Path)localObject2).moveTo(41.823528F, 28.852942F); ((Path)localObject2).cubicTo(48.548409F, 28.852942F, 54.0F, 34.304531F, 54.0F, 41.029411F); ((Path)localObject2).cubicTo(54.0F, 47.754292F, 48.548409F, 53.205883F, 41.823528F, 53.205883F); ((Path)localObject2).cubicTo(35.098652F, 53.205883F, 29.647058F, 47.754292F, 29.647058F, 41.029411F); ((Path)localObject2).cubicTo(29.647058F, 34.304531F, 35.098652F, 28.852942F, 41.823528F, 28.852942F); ((Path)localObject2).close(); ((Path)localObject2).moveTo(12.176471F, 34.676472F); ((Path)localObject2).cubicTo(8.667838F, 34.676472F, 5.823529F, 37.520779F, 5.823529F, 41.029411F); ((Path)localObject2).cubicTo(5.823529F, 44.538044F, 8.667838F, 47.382355F, 12.176471F, 47.382355F); ((Path)localObject2).cubicTo(15.685103F, 47.382355F, 18.529411F, 44.538044F, 18.529411F, 41.029411F); ((Path)localObject2).cubicTo(18.529411F, 37.520779F, 15.685103F, 34.676472F, 12.176471F, 34.676472F); ((Path)localObject2).close(); ((Path)localObject2).moveTo(41.823528F, 34.676472F); ((Path)localObject2).cubicTo(38.314896F, 34.676472F, 35.470589F, 37.520779F, 35.470589F, 41.029411F); ((Path)localObject2).cubicTo(35.470589F, 44.538044F, 38.314896F, 47.382355F, 41.823528F, 47.382355F); ((Path)localObject2).cubicTo(45.332161F, 47.382355F, 48.176472F, 44.538044F, 48.176472F, 41.029411F); ((Path)localObject2).cubicTo(48.176472F, 37.520779F, 45.332161F, 34.676472F, 41.823528F, 34.676472F); ((Path)localObject2).close(); ((Path)localObject2).moveTo(46.466427F, 0.1372338F); ((Path)localObject2).lineTo(46.873055F, 0.5711756F); ((Path)localObject2).cubicTo(49.730167F, 3.826816F, 49.841122F, 8.65159F, 47.205925F, 12.029105F); ((Path)localObject2).lineTo(46.829556F, 12.480422F); ((Path)localObject2).lineTo(46.466427F, 12.865156F); ((Path)localObject2).lineTo(26.99898F, 32.330177F); ((Path)localObject2).lineTo(7.533961F, 12.865156F); ((Path)localObject2).lineTo(7.170833F, 12.480422F); ((Path)localObject2).cubicTo(4.154855F, 9.093448F, 4.140355F, 3.9748F, 7.127334F, 0.5711756F); ((Path)localObject2).lineTo(7.533961F, 0.1372338F); ((Path)localObject2).lineTo(26.998922F, 19.604235F); ((Path)localObject2).lineTo(46.466427F, 0.1372338F); ((Path)localObject2).close(); WeChatSVGRenderC2Java.setFillType((Path)localObject2, 2); localCanvas.drawPath((Path)localObject2, (Paint)localObject1); localCanvas.restore(); localCanvas.restore(); c.done(paramVarArgs); } } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes12.jar * Qualified Name: com.tencent.mm.boot.svg.code.drawable.icons_filled_scissor * JD-Core Version: 0.7.0.1 */
UTF-8
Java
5,472
java
icons_filled_scissor.java
Java
[]
null
[]
package com.tencent.mm.boot.svg.code.drawable; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import android.os.Looper; import com.tencent.mm.svg.WeChatSVGRenderC2Java; import com.tencent.mm.svg.c; public class icons_filled_scissor extends c { private final int height = 72; private final int width = 72; public int doCommand(int paramInt, Object... paramVarArgs) { switch (paramInt) { } for (;;) { return 0; return 72; return 72; Canvas localCanvas = (Canvas)paramVarArgs[0]; paramVarArgs = (Looper)paramVarArgs[1]; Object localObject1 = c.instanceMatrix(paramVarArgs); Object localObject2 = c.instanceMatrixArray(paramVarArgs); Paint localPaint1 = c.instancePaint(paramVarArgs); localPaint1.setFlags(385); localPaint1.setStyle(Paint.Style.FILL); Paint localPaint2 = c.instancePaint(paramVarArgs); localPaint2.setFlags(385); localPaint2.setStyle(Paint.Style.STROKE); localPaint1.setColor(-16777216); localPaint2.setStrokeWidth(1.0F); localPaint2.setStrokeCap(Paint.Cap.BUTT); localPaint2.setStrokeJoin(Paint.Join.MITER); localPaint2.setStrokeMiter(4.0F); localPaint2.setPathEffect(null); c.instancePaint(localPaint2, paramVarArgs).setStrokeWidth(1.0F); localCanvas.save(); localPaint1 = c.instancePaint(localPaint1, paramVarArgs); localPaint1.setColor(-436207616); localObject2 = c.setMatrixFloatArray((float[])localObject2, 1.0F, 0.0F, 9.0F, 0.0F, 1.0F, 9.0F, 0.0F, 0.0F, 1.0F); ((Matrix)localObject1).reset(); ((Matrix)localObject1).setValues((float[])localObject2); localCanvas.concat((Matrix)localObject1); localCanvas.save(); localObject1 = c.instancePaint(localPaint1, paramVarArgs); localObject2 = c.instancePath(paramVarArgs); ((Path)localObject2).moveTo(12.176471F, 28.852942F); ((Path)localObject2).cubicTo(18.90135F, 28.852942F, 24.352942F, 34.304531F, 24.352942F, 41.029411F); ((Path)localObject2).cubicTo(24.352942F, 47.754292F, 18.90135F, 53.205883F, 12.176471F, 53.205883F); ((Path)localObject2).cubicTo(5.451592F, 53.205883F, 0.0F, 47.754292F, 0.0F, 41.029411F); ((Path)localObject2).cubicTo(0.0F, 34.304531F, 5.451592F, 28.852942F, 12.176471F, 28.852942F); ((Path)localObject2).close(); ((Path)localObject2).moveTo(41.823528F, 28.852942F); ((Path)localObject2).cubicTo(48.548409F, 28.852942F, 54.0F, 34.304531F, 54.0F, 41.029411F); ((Path)localObject2).cubicTo(54.0F, 47.754292F, 48.548409F, 53.205883F, 41.823528F, 53.205883F); ((Path)localObject2).cubicTo(35.098652F, 53.205883F, 29.647058F, 47.754292F, 29.647058F, 41.029411F); ((Path)localObject2).cubicTo(29.647058F, 34.304531F, 35.098652F, 28.852942F, 41.823528F, 28.852942F); ((Path)localObject2).close(); ((Path)localObject2).moveTo(12.176471F, 34.676472F); ((Path)localObject2).cubicTo(8.667838F, 34.676472F, 5.823529F, 37.520779F, 5.823529F, 41.029411F); ((Path)localObject2).cubicTo(5.823529F, 44.538044F, 8.667838F, 47.382355F, 12.176471F, 47.382355F); ((Path)localObject2).cubicTo(15.685103F, 47.382355F, 18.529411F, 44.538044F, 18.529411F, 41.029411F); ((Path)localObject2).cubicTo(18.529411F, 37.520779F, 15.685103F, 34.676472F, 12.176471F, 34.676472F); ((Path)localObject2).close(); ((Path)localObject2).moveTo(41.823528F, 34.676472F); ((Path)localObject2).cubicTo(38.314896F, 34.676472F, 35.470589F, 37.520779F, 35.470589F, 41.029411F); ((Path)localObject2).cubicTo(35.470589F, 44.538044F, 38.314896F, 47.382355F, 41.823528F, 47.382355F); ((Path)localObject2).cubicTo(45.332161F, 47.382355F, 48.176472F, 44.538044F, 48.176472F, 41.029411F); ((Path)localObject2).cubicTo(48.176472F, 37.520779F, 45.332161F, 34.676472F, 41.823528F, 34.676472F); ((Path)localObject2).close(); ((Path)localObject2).moveTo(46.466427F, 0.1372338F); ((Path)localObject2).lineTo(46.873055F, 0.5711756F); ((Path)localObject2).cubicTo(49.730167F, 3.826816F, 49.841122F, 8.65159F, 47.205925F, 12.029105F); ((Path)localObject2).lineTo(46.829556F, 12.480422F); ((Path)localObject2).lineTo(46.466427F, 12.865156F); ((Path)localObject2).lineTo(26.99898F, 32.330177F); ((Path)localObject2).lineTo(7.533961F, 12.865156F); ((Path)localObject2).lineTo(7.170833F, 12.480422F); ((Path)localObject2).cubicTo(4.154855F, 9.093448F, 4.140355F, 3.9748F, 7.127334F, 0.5711756F); ((Path)localObject2).lineTo(7.533961F, 0.1372338F); ((Path)localObject2).lineTo(26.998922F, 19.604235F); ((Path)localObject2).lineTo(46.466427F, 0.1372338F); ((Path)localObject2).close(); WeChatSVGRenderC2Java.setFillType((Path)localObject2, 2); localCanvas.drawPath((Path)localObject2, (Paint)localObject1); localCanvas.restore(); localCanvas.restore(); c.done(paramVarArgs); } } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes12.jar * Qualified Name: com.tencent.mm.boot.svg.code.drawable.icons_filled_scissor * JD-Core Version: 0.7.0.1 */
5,472
0.682749
0.469664
111
47.351353
33.021599
120
false
false
0
0
0
0
0
0
1.855856
false
false
13
c1fced061ad3e2243891a3e2045c5555d3072a86
35,046,933,149,755
6d7416e5831c0a11f328c17996bdedc71c55cf03
/Android/LCTF2016/easy100/myapp/sources/android/support/v4/widget/aj.java
1bd1e0fd36fb4071e1fcf2414054005edb5f473e
[]
no_license
Vorblock/myCTF-Study
https://github.com/Vorblock/myCTF-Study
68d166f2170e6c50bd0ff8de5044a67a99b455a2
0add379618cbe67362fe1363142ebb1ad78d45c5
refs/heads/master
2020-03-28T05:36:31.893000
2018-09-19T02:10:57
2018-09-19T02:10:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package android.support.v4.widget; import android.view.View.OnTouchListener; import android.widget.PopupMenu; class aj { aj() { } public static OnTouchListener a(Object obj) { return ((PopupMenu) obj).getDragToOpenListener(); } }
UTF-8
Java
257
java
aj.java
Java
[]
null
[]
package android.support.v4.widget; import android.view.View.OnTouchListener; import android.widget.PopupMenu; class aj { aj() { } public static OnTouchListener a(Object obj) { return ((PopupMenu) obj).getDragToOpenListener(); } }
257
0.692607
0.688716
13
18.76923
19.965948
57
false
false
0
0
0
0
0
0
0.307692
false
false
13
cc5ba03684b3545ccdaae859e490b5a012cfec54
30,090,540,924,788
1e3610bb11c3214072646b341b3ab55f96494398
/base/src/main/java/me/anchore/io/wal/ListRow.java
ee320a0f49dd5d6d6a0294c151a35d7d97fe3193
[ "Apache-2.0" ]
permissive
rofinily/code-fragment
https://github.com/rofinily/code-fragment
2bfe042da0744d1db4b210e4ce796be39cb49d02
681b289afefff427d058e2b3c46d8e4bcd5a6c7f
refs/heads/master
2022-12-31T06:30:00.314000
2020-02-05T10:23:08
2020-02-05T10:23:08
103,257,049
1
1
Apache-2.0
false
2020-10-13T08:40:46
2017-09-12T10:30:34
2020-02-05T10:23:28
2020-10-13T08:40:45
267
0
0
1
Java
false
false
package me.anchore.io.wal; import java.util.Arrays; import java.util.List; public class ListRow implements Row { List<?> list; public ListRow(List<?> list) { this.list = list; } public ListRow(Object... objects) { this.list = Arrays.asList(objects); } @Override public <V> V get(int index) { return (V) list.get(index); } @Override public int size() { return list.size(); } }
UTF-8
Java
458
java
ListRow.java
Java
[]
null
[]
package me.anchore.io.wal; import java.util.Arrays; import java.util.List; public class ListRow implements Row { List<?> list; public ListRow(List<?> list) { this.list = list; } public ListRow(Object... objects) { this.list = Arrays.asList(objects); } @Override public <V> V get(int index) { return (V) list.get(index); } @Override public int size() { return list.size(); } }
458
0.578603
0.578603
26
16.615385
14.382353
43
false
false
0
0
0
0
0
0
0.307692
false
false
13
f3018836cefe05cbf6187527c04a54334c1347ad
10,041,633,603,690
f870a42c274883323ebfcc3f167f8fe36fe1e4a9
/src/com/layssilvestre/atendimento/ControleAtendimento.java
ce48fb9052a7aa8f1d3ef9beaebb7b94b548f27d
[]
no_license
hellraizen/lays
https://github.com/hellraizen/lays
ec5a661eef9a6b8019730a2963c818b72257b4f3
7f8540dcab51f0832c2f6e253140523f71c03524
refs/heads/master
2021-01-10T11:38:34.859000
2016-01-14T05:16:00
2016-01-14T05:16:00
49,623,086
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.layssilvestre.atendimento; import java.sql.SQLException; import java.util.ArrayList; public class ControleAtendimento { IRepositorioAtendimento repositorioAtendimento; public ControleAtendimento() throws ClassNotFoundException { //repositorioAtendimento = new RepositorioAtendimento(); repositorioAtendimento = new RepositorioAtendimentoJdbc(); } public void inserirAtendimento(Atendimento atendimento) throws SQLException { repositorioAtendimento.inserirAtendimento(atendimento); } public void alterarAtendimento(Atendimento atendimento) throws SQLException { repositorioAtendimento.alterarAtendimento(atendimento); } public void excluirAtendimento(int codigo) throws SQLException{ repositorioAtendimento.excluirAtendimento(codigo); } public Atendimento procurar(int codigo) throws SQLException{ return repositorioAtendimento.procurar(codigo); } public ArrayList<Atendimento> listar() throws SQLException{ return repositorioAtendimento.listaAtendimento(); } }
UTF-8
Java
1,055
java
ControleAtendimento.java
Java
[]
null
[]
package com.layssilvestre.atendimento; import java.sql.SQLException; import java.util.ArrayList; public class ControleAtendimento { IRepositorioAtendimento repositorioAtendimento; public ControleAtendimento() throws ClassNotFoundException { //repositorioAtendimento = new RepositorioAtendimento(); repositorioAtendimento = new RepositorioAtendimentoJdbc(); } public void inserirAtendimento(Atendimento atendimento) throws SQLException { repositorioAtendimento.inserirAtendimento(atendimento); } public void alterarAtendimento(Atendimento atendimento) throws SQLException { repositorioAtendimento.alterarAtendimento(atendimento); } public void excluirAtendimento(int codigo) throws SQLException{ repositorioAtendimento.excluirAtendimento(codigo); } public Atendimento procurar(int codigo) throws SQLException{ return repositorioAtendimento.procurar(codigo); } public ArrayList<Atendimento> listar() throws SQLException{ return repositorioAtendimento.listaAtendimento(); } }
1,055
0.791469
0.791469
36
27.305555
27.961103
78
false
false
0
0
0
0
0
0
1.277778
false
false
13
0c07f42209ce2a7048c02fe023080c275c21b54b
11,982,958,812,339
e139322041815e3fa8888dc53b6cc6f98e915cf6
/src/com/chapter7/InitArray2.java
76a6e41c054f85b74436a104c1b33ebd1d388f04
[]
no_license
18Code/git_demo
https://github.com/18Code/git_demo
062f02287e7c5abf40a7bc1bcc7328b12bf2bbf4
a6902922a3b7bafdbbcbaf8fd13d9767f90f20f5
refs/heads/master
2020-03-23T11:33:04.578000
2018-09-18T10:57:04
2018-09-18T10:57:04
141,509,769
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.chapter7; import javax.swing.JOptionPane; import javax.swing.JTextArea; public class InitArray2 { public static void main(String[] args) { // TODO Auto-generated method stub final int ARRAY_LENGTH = 10; //็”จfinalไฟฎ้ฅฐ็ฌฆๅฃฐๆ˜Žๅธธ้‡ARRAY_LENGTH๏ผŒ่ฏฅๅธธ้‡็š„ๅ€ผไธบ10 int array[]; array = new int[ARRAY_LENGTH]; //ๅˆ›ๅปบไธ€ไธชๅŒ…ๅซ10ไธชๅ…ƒ็ด ็š„ๆ•ฐ็ป„ for (int counter = 0; counter < array.length; counter++) { //forๅพช็Žฏ array[counter] = 2 + 2 * counter; //counter็š„ๅฝ“ๅ‰ๅ€ผไน˜ไปฅ2ๅ†ๅŠ ไธŠ2๏ผŒ็”Ÿๆˆๆฏไธชๆ•ฐ็ป„ๅ…ƒ็ด ็š„ๅ€ผ } String output = "Index\tValue\n"; //ๅฐ†็จ‹ๅบ่ฆๆ˜พ็คบ็š„ๅˆ—ๆ ‡้ข˜่ต‹็ป™output for (int counter = 0; counter < array.length; counter++) { //forๅพช็Žฏ๏ผŒcounterๅˆๅ€ผ0๏ผŒๆ•ฐ็ป„้•ฟๅบฆ10๏ผŒ็ดขๅผ•ๅ€ผไธบ0ๅˆฐ9 output += counter + "\t" + array[counter] + "\n"; //ๅฐ†็ดขๅผ•ๅบๅทcounterๅ’Œๆฏไธชๆ•ฐ็ป„ๅ…ƒ็ด ็š„ๅ€ผarray[counter]ๆทปๅŠ ๅˆฐoutputไธญ } JTextArea outputArea = new JTextArea(); //ๅˆ›ๅปบJTextArea outputArea.setText(output); //outputๆ˜พ็คบๅœจๆถˆๆฏๅฏน่ฏๆก†็š„JTextAreaไธญ JOptionPane.showMessageDialog(null, outputArea, "Initalizing to Even Numbers from 2 to 20", JOptionPane.INFORMATION_MESSAGE); //่พ“ๅ‡บoutputArea System.exit(0); } }
UTF-8
Java
1,289
java
InitArray2.java
Java
[]
null
[]
package com.chapter7; import javax.swing.JOptionPane; import javax.swing.JTextArea; public class InitArray2 { public static void main(String[] args) { // TODO Auto-generated method stub final int ARRAY_LENGTH = 10; //็”จfinalไฟฎ้ฅฐ็ฌฆๅฃฐๆ˜Žๅธธ้‡ARRAY_LENGTH๏ผŒ่ฏฅๅธธ้‡็š„ๅ€ผไธบ10 int array[]; array = new int[ARRAY_LENGTH]; //ๅˆ›ๅปบไธ€ไธชๅŒ…ๅซ10ไธชๅ…ƒ็ด ็š„ๆ•ฐ็ป„ for (int counter = 0; counter < array.length; counter++) { //forๅพช็Žฏ array[counter] = 2 + 2 * counter; //counter็š„ๅฝ“ๅ‰ๅ€ผไน˜ไปฅ2ๅ†ๅŠ ไธŠ2๏ผŒ็”Ÿๆˆๆฏไธชๆ•ฐ็ป„ๅ…ƒ็ด ็š„ๅ€ผ } String output = "Index\tValue\n"; //ๅฐ†็จ‹ๅบ่ฆๆ˜พ็คบ็š„ๅˆ—ๆ ‡้ข˜่ต‹็ป™output for (int counter = 0; counter < array.length; counter++) { //forๅพช็Žฏ๏ผŒcounterๅˆๅ€ผ0๏ผŒๆ•ฐ็ป„้•ฟๅบฆ10๏ผŒ็ดขๅผ•ๅ€ผไธบ0ๅˆฐ9 output += counter + "\t" + array[counter] + "\n"; //ๅฐ†็ดขๅผ•ๅบๅทcounterๅ’Œๆฏไธชๆ•ฐ็ป„ๅ…ƒ็ด ็š„ๅ€ผarray[counter]ๆทปๅŠ ๅˆฐoutputไธญ } JTextArea outputArea = new JTextArea(); //ๅˆ›ๅปบJTextArea outputArea.setText(output); //outputๆ˜พ็คบๅœจๆถˆๆฏๅฏน่ฏๆก†็š„JTextAreaไธญ JOptionPane.showMessageDialog(null, outputArea, "Initalizing to Even Numbers from 2 to 20", JOptionPane.INFORMATION_MESSAGE); //่พ“ๅ‡บoutputArea System.exit(0); } }
1,289
0.685341
0.663866
36
27.75
31.074619
100
false
false
0
0
0
0
0
0
2.333333
false
false
13
9fa26ee54bb065a172578244cad40ad86c567ab5
30,477,087,969,101
7ccadba02a976cefcc09b74bf6963e56f54a45f1
/src/main/java/com/redian/chat/service/PushInterface.java
702464972d9166b9bab1353c79ce63fea5f11d64
[]
no_license
chenfeiTest/yunfwq
https://github.com/chenfeiTest/yunfwq
b898c1958283e09609ef886a4f91a5eec55621a0
721d02d9572765abe0749e11dcbafc24b3b92db8
refs/heads/master
2020-09-03T16:48:42.843000
2020-03-25T12:09:48
2020-03-25T12:09:48
219,512,829
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.redian.chat.service; import com.redian.chat.domain.PushDTO; import com.redian.errorcommon.DTO.Template; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @FeignClient("base-service") public interface PushInterface { @PostMapping(value = "/wechat/push/") Template push(@RequestBody PushDTO pushDTO); }
UTF-8
Java
450
java
PushInterface.java
Java
[]
null
[]
package com.redian.chat.service; import com.redian.chat.domain.PushDTO; import com.redian.errorcommon.DTO.Template; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @FeignClient("base-service") public interface PushInterface { @PostMapping(value = "/wechat/push/") Template push(@RequestBody PushDTO pushDTO); }
450
0.804444
0.804444
14
31.142857
21.579941
59
false
false
0
0
0
0
0
0
0.5
false
false
13
ece8e5ab56cd04bb4558b4a9cf0358cc288c7877
30,477,087,970,512
20fa43a35e187af96e9bdcdee545c8e15ff2d617
/src/main/java/ru/yandex/money/common/dbqueue/api/impl/NoopPayloadTransformer.java
cfd75e043a0c6e78fcf0c03836274a08b0aa9fb6
[ "MIT" ]
permissive
bizzdesign/db-queue
https://github.com/bizzdesign/db-queue
142c7f5a81e09a12205b99972d87efd2151e3591
178b98b1e2f67f410ae29b17d950e2231319c818
refs/heads/master
2021-08-05T21:54:48.980000
2020-02-07T07:24:45
2020-02-07T07:24:45
220,307,120
0
0
MIT
true
2019-11-07T18:52:37
2019-11-07T18:52:36
2019-11-01T19:41:44
2019-10-28T06:18:47
884
0
0
0
null
false
false
package ru.yandex.money.common.dbqueue.api.impl; import ru.yandex.money.common.dbqueue.api.TaskPayloadTransformer; import javax.annotation.Nullable; /** * ะŸัƒัั‚ะพะน ะฟั€ะตะพะฑั€ะฐะทะพะฒะฐั‚ะตะปัŒ ะดะฐะฝะฝั‹ั… ะพั‡ะตั€ะตะดะธ. * <p> * ะ˜ัะฟะพะปัŒะทัƒะตั‚ัั ะฒ ัะปัƒั‡ะฐะต, ะบะพะณะดะฐ ะฟั€ะตะพะฑั€ะฐะทะพะฒะฐะฝะธะต ะดะฐะฝะฝั‹ั… ะฝะต ั‚ั€ะตะฑัƒะตั‚ัั. */ public final class NoopPayloadTransformer implements TaskPayloadTransformer<String> { private static final NoopPayloadTransformer INSTANCE = new NoopPayloadTransformer(); /** * ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝัั‚ะฐะฝั ะฟั€ะตะพะฑั€ะฐะทะพะฒะฐั‚ะตะปั. * * @return ะธะฝัั‚ะฐะฝั ะฟั€ะตะพะฑั€ะฐะทะพะฒะฐั‚ะตะปั. ะ’ะพะทะฒั€ะฐั‰ะฐะตั‚ัั ัะธะฝะณะปั‚ะพะฝ. */ public static NoopPayloadTransformer getInstance() { return INSTANCE; } private NoopPayloadTransformer() { } @Nullable @Override public String toObject(@Nullable String payload) { return payload; } @Nullable @Override public String fromObject(@Nullable String payload) { return payload; } }
UTF-8
Java
1,109
java
NoopPayloadTransformer.java
Java
[]
null
[]
package ru.yandex.money.common.dbqueue.api.impl; import ru.yandex.money.common.dbqueue.api.TaskPayloadTransformer; import javax.annotation.Nullable; /** * ะŸัƒัั‚ะพะน ะฟั€ะตะพะฑั€ะฐะทะพะฒะฐั‚ะตะปัŒ ะดะฐะฝะฝั‹ั… ะพั‡ะตั€ะตะดะธ. * <p> * ะ˜ัะฟะพะปัŒะทัƒะตั‚ัั ะฒ ัะปัƒั‡ะฐะต, ะบะพะณะดะฐ ะฟั€ะตะพะฑั€ะฐะทะพะฒะฐะฝะธะต ะดะฐะฝะฝั‹ั… ะฝะต ั‚ั€ะตะฑัƒะตั‚ัั. */ public final class NoopPayloadTransformer implements TaskPayloadTransformer<String> { private static final NoopPayloadTransformer INSTANCE = new NoopPayloadTransformer(); /** * ะŸะพะปัƒั‡ะธั‚ัŒ ะธะฝัั‚ะฐะฝั ะฟั€ะตะพะฑั€ะฐะทะพะฒะฐั‚ะตะปั. * * @return ะธะฝัั‚ะฐะฝั ะฟั€ะตะพะฑั€ะฐะทะพะฒะฐั‚ะตะปั. ะ’ะพะทะฒั€ะฐั‰ะฐะตั‚ัั ัะธะฝะณะปั‚ะพะฝ. */ public static NoopPayloadTransformer getInstance() { return INSTANCE; } private NoopPayloadTransformer() { } @Nullable @Override public String toObject(@Nullable String payload) { return payload; } @Nullable @Override public String fromObject(@Nullable String payload) { return payload; } }
1,109
0.709916
0.709916
40
22.700001
25.894207
88
false
false
0
0
0
0
0
0
0.2
false
false
13
7bfe66320dd75e3b7a027bb6b8ba381d2661326a
9,594,956,978,387
5ee60efbef384c3b38717f92843937eeb6bb81e0
/src/main/java/it/pipodi/naspi/orchestration/PicturesOrchestration.java
91b94555a4af37d0f32997d85d5af8013825b7d8
[]
no_license
Pipodi/NASPi
https://github.com/Pipodi/NASPi
fae7ef4ac7364cfab31cd972c1c62d0a6e35a5e7
77dbe38c55316d14d29f53a49b75c29304cee93f
refs/heads/master
2021-06-15T20:46:44.859000
2019-07-01T10:07:01
2019-07-01T10:07:01
186,705,760
1
0
null
false
2021-04-26T19:17:31
2019-05-14T21:51:52
2019-07-01T10:07:04
2021-04-26T19:17:30
81
0
0
2
Java
false
false
package it.pipodi.naspi.orchestration; import org.springframework.stereotype.Service; @Service public class PicturesOrchestration { }
UTF-8
Java
136
java
PicturesOrchestration.java
Java
[]
null
[]
package it.pipodi.naspi.orchestration; import org.springframework.stereotype.Service; @Service public class PicturesOrchestration { }
136
0.830882
0.830882
7
18.428572
19.062733
46
false
false
0
0
0
0
0
0
0.285714
false
false
13
e2ed0b11132792407692aab67bd0da0b4a051132
9,594,956,980,253
8906ec72f11e76f8c8cfcd012b5aa18633287526
/learn-netty/src/main/java/com/pureyang/netty/chapter02/aio/AcceptCompletionHandler.java
2ab6f17d7b06eb1ed86c58985a94091a868e1c66
[]
no_license
pureyang317/learn-pure
https://github.com/pureyang317/learn-pure
aae2602c37f2d4ffee9f2bf19838be67516a427c
fad1236fba4789e0d59815ab7c3cb5a178d11bb7
refs/heads/master
2020-05-15T22:01:53.046000
2019-10-23T14:52:44
2019-10-23T14:52:44
182,513,371
1
0
null
false
2021-01-28T16:37:47
2019-04-21T09:18:03
2021-01-28T16:37:20
2021-01-28T16:37:46
96,826
0
0
9
Java
false
false
package com.pureyang.netty.chapter02.aio; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; /** * @Author ๆจๆ’ * @Email baixue.yh@raycloud.com * @Date 2019-06-05 10:56 * @Description AcceptCompletionHandler */ public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler> { @Override public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) { attachment.asynchronousServerSocketChannel.accept(attachment, this); ByteBuffer buffer = ByteBuffer.allocate(1024); result.read(buffer, buffer, new ReadCompletionHandler(result)); } @Override public void failed(Throwable exc, AsyncTimeServerHandler attachment) { exc.printStackTrace(); attachment.latch.countDown(); } }
UTF-8
Java
901
java
AcceptCompletionHandler.java
Java
[ { "context": "a.nio.channels.CompletionHandler;\n\n/**\n * @Author ๆจๆ’\n * @Email baixue.yh@raycloud.com\n * @Date 2019-06", "end": 185, "score": 0.9995347261428833, "start": 183, "tag": "NAME", "value": "ๆจๆ’" }, { "context": "ls.CompletionHandler;\n\n/**\n * @Author ๆจๆ’\n * @Email baixue.yh@raycloud.com\n * @Date 2019-06-05 10:56\n * @Description AcceptC", "end": 218, "score": 0.9999319314956665, "start": 196, "tag": "EMAIL", "value": "baixue.yh@raycloud.com" } ]
null
[]
package com.pureyang.netty.chapter02.aio; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; /** * @Author ๆจๆ’ * @Email <EMAIL> * @Date 2019-06-05 10:56 * @Description AcceptCompletionHandler */ public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler> { @Override public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) { attachment.asynchronousServerSocketChannel.accept(attachment, this); ByteBuffer buffer = ByteBuffer.allocate(1024); result.read(buffer, buffer, new ReadCompletionHandler(result)); } @Override public void failed(Throwable exc, AsyncTimeServerHandler attachment) { exc.printStackTrace(); attachment.latch.countDown(); } }
886
0.761427
0.74136
27
32.222221
31.734236
118
false
false
0
0
0
0
0
0
0.555556
false
false
13
9db6cce333c62cac3bfbceb787acdaa691c2967a
21,543,555,997,687
353a17d83b6d2c1fb0f338c56ccf19064bdb31ba
/configurator/src/main/java/com/artkostm/configurator/util/ConfigurationUtils.java
1101d123260524fa13da678906bc8725fdf244fd
[]
no_license
artkostm/ERCP-7002
https://github.com/artkostm/ERCP-7002
2ed60a5f15a0dbc3f243df75664e0256101187f8
37cdb81d11b1e4beb8b9ac07556abd283a285dd2
refs/heads/master
2021-01-24T09:38:29.930000
2016-03-21T10:31:28
2016-03-21T10:31:28
41,972,342
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.artkostm.configurator.util; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * * @author Artsiom * */ public class ConfigurationUtils { /** * * @param fullMethodPath - example: com.full.package.path.ClassName.methodName, * where com.full.package.path.ClassName - full name of class * that contains public static void methodName() method * @return Method or null if cannot instantiate class instance */ public static Method tryToGetMethodByName(final String fullMethodPath) { if (fullMethodPath == null || fullMethodPath.isEmpty()) { return null; } final int ind = fullMethodPath.lastIndexOf('.'); final String className = fullMethodPath.substring(0, ind); final String methodName = fullMethodPath.substring(ind+1); try { final Class<?> cl = Class.forName(className); return cl.getMethod(methodName, new Class<?>[]{}); } catch (Exception e) { e.printStackTrace();//TODO: add logging here } return null; } /** * * @param fullMethodPathesList - a list of full method paths * @see {com.artkostm.configurator.util.ConfigurationUtils.tryToGetMethodByName(String)} * @return a list of Methods, the list do not contain null values */ public static List<Method> tryToGetListOfMethodsByNames(final List<String> fullMethodPathsList) { if (fullMethodPathsList == null || fullMethodPathsList.isEmpty()) { return Collections.emptyList(); } final List<Method> methods = new ArrayList<Method>(fullMethodPathsList.size()); for (String fullMethodPath : fullMethodPathsList) { final Method method = tryToGetMethodByName(fullMethodPath); if (method != null) { methods.add(method); } } return methods; } }
UTF-8
Java
2,131
java
ConfigurationUtils.java
Java
[ { "context": "s;\r\nimport java.util.List;\r\n\r\n/**\r\n * \r\n * @author Artsiom\r\n *\r\n */\r\npublic class ConfigurationUtils \r\n{\r\n ", "end": 191, "score": 0.9909763336181641, "start": 184, "tag": "NAME", "value": "Artsiom" } ]
null
[]
package com.artkostm.configurator.util; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * * @author Artsiom * */ public class ConfigurationUtils { /** * * @param fullMethodPath - example: com.full.package.path.ClassName.methodName, * where com.full.package.path.ClassName - full name of class * that contains public static void methodName() method * @return Method or null if cannot instantiate class instance */ public static Method tryToGetMethodByName(final String fullMethodPath) { if (fullMethodPath == null || fullMethodPath.isEmpty()) { return null; } final int ind = fullMethodPath.lastIndexOf('.'); final String className = fullMethodPath.substring(0, ind); final String methodName = fullMethodPath.substring(ind+1); try { final Class<?> cl = Class.forName(className); return cl.getMethod(methodName, new Class<?>[]{}); } catch (Exception e) { e.printStackTrace();//TODO: add logging here } return null; } /** * * @param fullMethodPathesList - a list of full method paths * @see {com.artkostm.configurator.util.ConfigurationUtils.tryToGetMethodByName(String)} * @return a list of Methods, the list do not contain null values */ public static List<Method> tryToGetListOfMethodsByNames(final List<String> fullMethodPathsList) { if (fullMethodPathsList == null || fullMethodPathsList.isEmpty()) { return Collections.emptyList(); } final List<Method> methods = new ArrayList<Method>(fullMethodPathsList.size()); for (String fullMethodPath : fullMethodPathsList) { final Method method = tryToGetMethodByName(fullMethodPath); if (method != null) { methods.add(method); } } return methods; } }
2,131
0.59878
0.597841
66
30.287878
28.247696
99
false
false
0
0
0
0
0
0
0.393939
false
false
13
f453776e8931f486f41190107b756dd06a25b796
17,506,286,738,372
6f4ab7364be09f0ad38764e802c96499381fa0a2
/Compilers-3/methodClass.java
5c1cfe24189eb4e397a9183a882dce6868be5a3e
[]
no_license
JoHNNyB92/Compilers
https://github.com/JoHNNyB92/Compilers
16292a76b129cc2df7dcf6f18a7457f9bb0da95e
eb9aa57c297a833f2f921c2027eae7972372b6ef
refs/heads/master
2020-07-03T11:49:36.101000
2019-09-25T12:03:10
2019-09-25T12:03:10
201,896,247
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.HashMap; import java.util.Map; public class methodClass { public Map<String,String> returnType; public Map<String,Integer> methods; public Map<String,Integer> methodParameters; //public String methodName; public methodClass(Map<String,String> _returnType,Map<String,Integer> _methods,Map<String,Integer> _methodParameters){ this.returnType=_returnType; this.methods=_methods; this.methodParameters=_methodParameters; //this.methodName=_methodName; } public methodClass(){ this.returnType=new HashMap<String,String>(); this.methods=new HashMap<String,Integer>(); this.methodParameters=new HashMap<String,Integer>(); //this.methodName=_methodName; } public void copy(methodClass another){ another.returnType=new HashMap<String,String>(this.returnType); another.methods=new HashMap<String,Integer>(this.methods); another.methodParameters=new HashMap<String,Integer>(this.methodParameters); } }
UTF-8
Java
947
java
methodClass.java
Java
[]
null
[]
import java.util.HashMap; import java.util.Map; public class methodClass { public Map<String,String> returnType; public Map<String,Integer> methods; public Map<String,Integer> methodParameters; //public String methodName; public methodClass(Map<String,String> _returnType,Map<String,Integer> _methods,Map<String,Integer> _methodParameters){ this.returnType=_returnType; this.methods=_methods; this.methodParameters=_methodParameters; //this.methodName=_methodName; } public methodClass(){ this.returnType=new HashMap<String,String>(); this.methods=new HashMap<String,Integer>(); this.methodParameters=new HashMap<String,Integer>(); //this.methodName=_methodName; } public void copy(methodClass another){ another.returnType=new HashMap<String,String>(this.returnType); another.methods=new HashMap<String,Integer>(this.methods); another.methodParameters=new HashMap<String,Integer>(this.methodParameters); } }
947
0.772967
0.772967
29
31.655172
26.834455
119
false
false
0
0
0
0
0
0
2.241379
false
false
13
43e5bb2a34186a8e7d391395328634a53b6d6e5b
14,980,845,983,476
35d797e6af85fbbc2af2d20d291be8c5d0b9d2b2
/src/main/java/com/web/template/validator/UserValidator.java
514c64d9ae03f9e4b9106f86a9575cb50bb50426
[]
no_license
everoad/webTemplate
https://github.com/everoad/webTemplate
d2b039d07b87088695682a3af8f1a1b5d7123f99
98b498abac7d9bddc4e1bb6a603fd072279f0310
refs/heads/master
2021-01-20T09:17:07.820000
2017-05-08T01:27:14
2017-05-08T01:27:14
90,234,583
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.web.template.validator; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.web.template.vo.UserVO; public class UserValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return UserVO.class.isAssignableFrom(clazz); } @Override public void validate(Object obj, Errors errors) { UserVO userVo = (UserVO) obj; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user_email", "required", "๋นˆ์นธ์ž…๋‹ˆ๋‹ค."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user_pwd", "required", "๋นˆ์นธ์ž…๋‹ˆ๋‹ค."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user_nick", "required", "๋นˆ์นธ์ž…๋‹ˆ๋‹ค."); } }
UTF-8
Java
777
java
UserValidator.java
Java
[]
null
[]
package com.web.template.validator; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.web.template.vo.UserVO; public class UserValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return UserVO.class.isAssignableFrom(clazz); } @Override public void validate(Object obj, Errors errors) { UserVO userVo = (UserVO) obj; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user_email", "required", "๋นˆ์นธ์ž…๋‹ˆ๋‹ค."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user_pwd", "required", "๋นˆ์นธ์ž…๋‹ˆ๋‹ค."); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "user_nick", "required", "๋นˆ์นธ์ž…๋‹ˆ๋‹ค."); } }
777
0.7751
0.7751
25
28.879999
29.28388
88
false
false
0
0
0
0
0
0
1.52
false
false
13
16f5d9258e6580c6e7b8827d297656b8ea922965
14,980,845,982,675
e77249913cf3545e1dfca623b742edcb2c971346
/Spring/stringIntro/src/module-info.java
ca4663c4a8b4b3d9c73bd0a45e0786612f1a7fda
[]
no_license
cihatdev/OOPwithJAVA
https://github.com/cihatdev/OOPwithJAVA
6143792e29c741ba0f1fa1f28d2daf3d9b790965
75987c4acee6d5fc62041047ab13c2a4d134f236
refs/heads/master
2022-12-04T12:40:26.145000
2020-08-29T15:46:08
2020-08-29T15:46:08
288,232,850
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
module stringIntro { }
UTF-8
Java
22
java
module-info.java
Java
[]
null
[]
module stringIntro { }
22
0.772727
0.772727
2
10.5
9.5
20
false
false
0
0
0
0
0
0
0
false
false
13
f072a508c0beda6b2c78bee496c5f0861a9f65d2
33,930,241,663,554
c9a41c16dda346aa88f6ace299dcd9caac902152
/starter-samples/log-record-starter/src/test/java/cn/monitor4all/logRecord/test/service/CustomFunctionService.java
6fe00f3674dd53993e0bb134bf548c7280954f63
[ "Apache-2.0" ]
permissive
dantefung/Macaroon-Spring-Family
https://github.com/dantefung/Macaroon-Spring-Family
99878cab918726c5726617c39ce4c10cc3028e7e
40d00955af0fd33f4b660f6ab7a9c1859d5f5456
refs/heads/master
2023-08-31T09:29:39.149000
2023-08-30T08:25:50
2023-08-30T08:25:50
219,237,782
4
0
null
false
2023-02-22T18:04:48
2019-11-03T01:48:31
2022-11-15T11:57:46
2023-02-22T18:04:48
242,582
3
0
71
HTML
false
false
package cn.monitor4all.logRecord.test.service; import cn.monitor4all.logRecord.annotation.LogRecordFunc; @LogRecordFunc("test") public class CustomFunctionService { @LogRecordFunc("testMethodWithCustomName") public static String testMethodWithCustomName(){ return "testMethodWithCustomName"; } @LogRecordFunc public static String testMethodWithoutCustomName(){ return "testMethodWithoutCustomName"; } }
UTF-8
Java
449
java
CustomFunctionService.java
Java
[]
null
[]
package cn.monitor4all.logRecord.test.service; import cn.monitor4all.logRecord.annotation.LogRecordFunc; @LogRecordFunc("test") public class CustomFunctionService { @LogRecordFunc("testMethodWithCustomName") public static String testMethodWithCustomName(){ return "testMethodWithCustomName"; } @LogRecordFunc public static String testMethodWithoutCustomName(){ return "testMethodWithoutCustomName"; } }
449
0.757238
0.752784
19
22.631578
22.269192
57
false
false
0
0
0
0
0
0
0.210526
false
false
13
5461b060d3f05b9b114bbc59c5b0dfa877219c2b
37,752,762,552,562
f36e253f42b971e02f8e16c1370fdf27116c4a29
/Example/src/Test.java
1c0fa831188f6aea853c8b52141bd9c1d952741b
[]
no_license
konggong/example
https://github.com/konggong/example
04324ef62d06040b9c4e7c97183689a02f9992c4
25a35a905e9fb9552f698a8f30981f168b837e8d
refs/heads/master
2021-01-10T08:27:57.715000
2020-10-08T07:36:34
2020-10-08T07:36:34
53,319,492
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Test { public static void main(String[] args) { //test01(); test02(); //test03(); } public static void test03() { String str = " "; System.out.println("str.length = "+str.length()); } public static void test02() { String str = "A"; System.out.println("str.length = " + nullToSpace(str,10).length()); } public static String nullToSpace(String str,int i) { if (str == null) str = " "; if (str.length() < i) str = nullToSpace(str+" ",i); return str; } public static void test01() { int a = 0; int b = 1; System.out.println("a = " + a); System.out.println("b = " + b); a = b++; System.out.println("a = b++"); System.out.println("a = " + a); System.out.println("b = " + b); a = ++b; System.out.println("a = ++b"); System.out.println("a = " + a); System.out.println("b = " + b); } }
UTF-8
Java
1,044
java
Test.java
Java
[]
null
[]
public class Test { public static void main(String[] args) { //test01(); test02(); //test03(); } public static void test03() { String str = " "; System.out.println("str.length = "+str.length()); } public static void test02() { String str = "A"; System.out.println("str.length = " + nullToSpace(str,10).length()); } public static String nullToSpace(String str,int i) { if (str == null) str = " "; if (str.length() < i) str = nullToSpace(str+" ",i); return str; } public static void test01() { int a = 0; int b = 1; System.out.println("a = " + a); System.out.println("b = " + b); a = b++; System.out.println("a = b++"); System.out.println("a = " + a); System.out.println("b = " + b); a = ++b; System.out.println("a = ++b"); System.out.println("a = " + a); System.out.println("b = " + b); } }
1,044
0.45977
0.444444
42
23.833334
18.549698
75
false
false
0
0
0
0
0
0
0.595238
false
false
13
d1f60babc920dcff5b954a3a22b178eef65fccb4
37,400,575,245,332
4eb7f6358a2d61d7149410160c8eff629fed7a53
/src/main/java/exnihilocreatio/registries/registries/HammerRegistry.java
020d094d006585359ea319840cface0b3efe5115
[ "CC-BY-NC-SA-3.0", "MIT", "CC-BY-NC-4.0" ]
permissive
BloodyMods/ExNihiloCreatio
https://github.com/BloodyMods/ExNihiloCreatio
0fa1aa137169b5d29c90bcca741d789ac35ef6d1
75f60692a4257a62ba9f6831866e456d8526ec9d
refs/heads/1.12
2021-06-05T07:57:11.810000
2019-10-27T19:02:53
2019-10-27T19:02:53
99,278,949
19
40
MIT
true
2021-01-05T22:10:21
2017-08-03T22:08:04
2020-08-03T01:04:33
2019-10-27T19:02:59
33,996
24
25
50
Java
false
false
package exnihilocreatio.registries.registries; import com.google.common.collect.Lists; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import exnihilocreatio.api.registries.IHammerRegistry; import exnihilocreatio.compatibility.jei.hammer.HammerRecipe; import exnihilocreatio.json.CustomHammerRewardJson; import exnihilocreatio.json.CustomIngredientJson; import exnihilocreatio.json.CustomItemStackJson; import exnihilocreatio.registries.ingredient.IngredientUtil; import exnihilocreatio.registries.ingredient.OreIngredientStoring; import exnihilocreatio.registries.manager.ExNihiloRegistryManager; import exnihilocreatio.registries.registries.prefab.BaseRegistryMap; import exnihilocreatio.registries.types.HammerReward; import exnihilocreatio.util.BlockInfo; import exnihilocreatio.util.ItemUtil; import exnihilocreatio.util.StackInfo; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.NonNullList; import net.minecraftforge.common.crafting.CraftingHelper; import org.jetbrains.annotations.NotNull; import java.io.FileReader; import java.util.*; import java.util.stream.Collectors; public class HammerRegistry extends BaseRegistryMap<Ingredient, List<HammerReward>> implements IHammerRegistry { public HammerRegistry() { super( new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(ItemStack.class, CustomItemStackJson.INSTANCE) .registerTypeAdapter(Ingredient.class, CustomIngredientJson.INSTANCE) .registerTypeAdapter(OreIngredientStoring.class, CustomIngredientJson.INSTANCE) .registerTypeAdapter(HammerReward.class, CustomHammerRewardJson.INSTANCE) .enableComplexMapKeySerialization() .create(), new com.google.gson.reflect.TypeToken<Map<Ingredient, List<HammerReward>>>() {}.getType(), ExNihiloRegistryManager.HAMMER_DEFAULT_REGISTRY_PROVIDERS ); } @Override public void registerEntriesFromJSON(FileReader fr) { HashMap<String, ArrayList<HammerReward>> gsonInput = gson.fromJson(fr, new TypeToken<HashMap<String, ArrayList<HammerReward>>>() { }.getType()); for (Map.Entry<String, ArrayList<HammerReward>> s : gsonInput.entrySet()) { Ingredient ingredient = IngredientUtil.parseFromString(s.getKey()); Ingredient search = registry.keySet().stream().filter(entry -> IngredientUtil.ingredientEquals(ingredient, entry)).findAny().orElse(null); if (search != null) { registry.get(search).addAll(s.getValue()); } else { NonNullList<HammerReward> drops = NonNullList.create(); drops.addAll(s.getValue()); registry.put(ingredient, drops); } } } /** * Adds a new Hammer recipe for use with Ex Nihilo hammers. * * @param state The blocks state to add * @param reward Reward * @param miningLevel Mining level of hammer. 0 = Wood/Gold, 1 = Stone, 2 = Iron, 3 = Diamond. Can be higher, but will need corresponding tool material. * @param chance Chance of drop * @param fortuneChance Chance of drop per level of fortune */ public void register(@NotNull IBlockState state, @NotNull ItemStack reward, int miningLevel, float chance, float fortuneChance) { register(new ItemStack(state.getBlock(), 1, state.getBlock().getMetaFromState(state)), new HammerReward(reward, miningLevel, chance, fortuneChance)); } public void register(@NotNull Block block, int meta, @NotNull ItemStack reward, int miningLevel, float chance, float fortuneChance) { register(new ItemStack(block, 1, meta), new HammerReward(reward, miningLevel, chance, fortuneChance)); } public void register(@NotNull StackInfo stackInfo, @NotNull ItemStack reward, int miningLevel, float chance, float fortuneChance) { register(stackInfo.getItemStack(), new HammerReward(reward, miningLevel, chance, fortuneChance)); } public void register(@NotNull ItemStack stack, @NotNull HammerReward reward) { if (stack.isEmpty()) return; Ingredient ingredient = CraftingHelper.getIngredient(stack); register(ingredient, reward); } public void register(@NotNull String name, @NotNull ItemStack reward, int miningLevel, float chance, float fortuneChance) { Ingredient ingredient = new OreIngredientStoring(name); register(ingredient, new HammerReward(reward, miningLevel, chance, fortuneChance)); } public void register(@NotNull Ingredient ingredient, @NotNull HammerReward reward) { Ingredient search = registry.keySet().stream().filter(entry -> IngredientUtil.ingredientEquals(ingredient, entry)).findAny().orElse(null); if (search != null) { registry.get(search).add(reward); } else { NonNullList<HammerReward> drops = NonNullList.create(); drops.add(reward); registry.put(ingredient, drops); } } @NotNull public NonNullList<ItemStack> getRewardDrops(@NotNull Random random, @NotNull IBlockState block, int miningLevel, int fortuneLevel) { NonNullList<ItemStack> rewards = NonNullList.create(); for (HammerReward reward : getRewards(block)) { if (miningLevel >= reward.getMiningLevel()) { if (random.nextFloat() <= reward.getChance() + (reward.getFortuneChance() * fortuneLevel)) { rewards.add(reward.getStack().copy()); } } } return rewards; } @NotNull public NonNullList<HammerReward> getRewards(@NotNull IBlockState block) { return getRewards(new BlockInfo(block)); } @NotNull public NonNullList<HammerReward> getRewards(@NotNull Block block, int meta) { return getRewards(new BlockInfo(block, meta)); } @NotNull public NonNullList<HammerReward> getRewards(@NotNull BlockInfo stackInfo) { NonNullList<HammerReward> drops = NonNullList.create(); if (stackInfo.isValid()) registry.entrySet().stream().filter(entry -> entry.getKey().test(stackInfo.getItemStack())).forEach(entry -> drops.addAll(entry.getValue())); return drops; } @NotNull public NonNullList<HammerReward> getRewards(@NotNull Ingredient ingredient) { NonNullList<HammerReward> drops = NonNullList.create(); registry.entrySet().stream().filter(entry -> entry.getKey() == ingredient).forEach(entry -> drops.addAll(entry.getValue())); return drops; } public boolean isRegistered(@NotNull IBlockState block) { return isRegistered(new BlockInfo(block)); } public boolean isRegistered(@NotNull Block block) { return isRegistered(new BlockInfo(block.getDefaultState())); } /** * Just so that tinkers complement doesn't crash */ @Deprecated public boolean registered(Block block) { return isRegistered(new BlockInfo(block.getDefaultState())); } public boolean isRegistered(@NotNull BlockInfo stackInfo) { return registry.keySet().stream().anyMatch(ingredient -> ingredient.test(stackInfo.getItemStack())); } // Legacy TODO: REMOVE if it works with ex compressum @Deprecated public List<HammerReward> getRewards(IBlockState state, int miningLevel) { NonNullList<HammerReward> drops = NonNullList.create(); BlockInfo block = new BlockInfo(state); registry.entrySet().stream().filter(entry -> entry.getKey().test(block.getItemStack())) .forEach(entry -> entry.getValue().stream().filter(value -> value.getMiningLevel() <= miningLevel).forEach(drops::add)); return drops; } @Override public List<HammerRecipe> getRecipeList() { List<HammerRecipe> hammerRecipes = Lists.newLinkedList(); for(Ingredient ingredient : getRegistry().keySet()){ if(ingredient == null) continue; List<ItemStack> rawOutputs = getRewards(ingredient).stream().map(HammerReward::getStack).collect(Collectors.toList()); List<ItemStack> allOutputs = new ArrayList<>(); for(ItemStack raw : rawOutputs){ boolean alreadyexists = false; for(ItemStack all : allOutputs){ if(ItemUtil.areStacksEquivalent(all, raw)){ alreadyexists = true; break; } } if(!alreadyexists) allOutputs.add(raw); } List<ItemStack> inputs = Arrays.asList(ingredient.getMatchingStacks()); for(int i = 0; i < allOutputs.size(); i+=21){ final List<ItemStack> outputs = allOutputs.subList(i, Math.min(i+21, allOutputs.size())); hammerRecipes.add(new HammerRecipe(inputs, outputs)); } } return hammerRecipes; } }
UTF-8
Java
9,281
java
HammerRegistry.java
Java
[]
null
[]
package exnihilocreatio.registries.registries; import com.google.common.collect.Lists; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import exnihilocreatio.api.registries.IHammerRegistry; import exnihilocreatio.compatibility.jei.hammer.HammerRecipe; import exnihilocreatio.json.CustomHammerRewardJson; import exnihilocreatio.json.CustomIngredientJson; import exnihilocreatio.json.CustomItemStackJson; import exnihilocreatio.registries.ingredient.IngredientUtil; import exnihilocreatio.registries.ingredient.OreIngredientStoring; import exnihilocreatio.registries.manager.ExNihiloRegistryManager; import exnihilocreatio.registries.registries.prefab.BaseRegistryMap; import exnihilocreatio.registries.types.HammerReward; import exnihilocreatio.util.BlockInfo; import exnihilocreatio.util.ItemUtil; import exnihilocreatio.util.StackInfo; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.util.NonNullList; import net.minecraftforge.common.crafting.CraftingHelper; import org.jetbrains.annotations.NotNull; import java.io.FileReader; import java.util.*; import java.util.stream.Collectors; public class HammerRegistry extends BaseRegistryMap<Ingredient, List<HammerReward>> implements IHammerRegistry { public HammerRegistry() { super( new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(ItemStack.class, CustomItemStackJson.INSTANCE) .registerTypeAdapter(Ingredient.class, CustomIngredientJson.INSTANCE) .registerTypeAdapter(OreIngredientStoring.class, CustomIngredientJson.INSTANCE) .registerTypeAdapter(HammerReward.class, CustomHammerRewardJson.INSTANCE) .enableComplexMapKeySerialization() .create(), new com.google.gson.reflect.TypeToken<Map<Ingredient, List<HammerReward>>>() {}.getType(), ExNihiloRegistryManager.HAMMER_DEFAULT_REGISTRY_PROVIDERS ); } @Override public void registerEntriesFromJSON(FileReader fr) { HashMap<String, ArrayList<HammerReward>> gsonInput = gson.fromJson(fr, new TypeToken<HashMap<String, ArrayList<HammerReward>>>() { }.getType()); for (Map.Entry<String, ArrayList<HammerReward>> s : gsonInput.entrySet()) { Ingredient ingredient = IngredientUtil.parseFromString(s.getKey()); Ingredient search = registry.keySet().stream().filter(entry -> IngredientUtil.ingredientEquals(ingredient, entry)).findAny().orElse(null); if (search != null) { registry.get(search).addAll(s.getValue()); } else { NonNullList<HammerReward> drops = NonNullList.create(); drops.addAll(s.getValue()); registry.put(ingredient, drops); } } } /** * Adds a new Hammer recipe for use with Ex Nihilo hammers. * * @param state The blocks state to add * @param reward Reward * @param miningLevel Mining level of hammer. 0 = Wood/Gold, 1 = Stone, 2 = Iron, 3 = Diamond. Can be higher, but will need corresponding tool material. * @param chance Chance of drop * @param fortuneChance Chance of drop per level of fortune */ public void register(@NotNull IBlockState state, @NotNull ItemStack reward, int miningLevel, float chance, float fortuneChance) { register(new ItemStack(state.getBlock(), 1, state.getBlock().getMetaFromState(state)), new HammerReward(reward, miningLevel, chance, fortuneChance)); } public void register(@NotNull Block block, int meta, @NotNull ItemStack reward, int miningLevel, float chance, float fortuneChance) { register(new ItemStack(block, 1, meta), new HammerReward(reward, miningLevel, chance, fortuneChance)); } public void register(@NotNull StackInfo stackInfo, @NotNull ItemStack reward, int miningLevel, float chance, float fortuneChance) { register(stackInfo.getItemStack(), new HammerReward(reward, miningLevel, chance, fortuneChance)); } public void register(@NotNull ItemStack stack, @NotNull HammerReward reward) { if (stack.isEmpty()) return; Ingredient ingredient = CraftingHelper.getIngredient(stack); register(ingredient, reward); } public void register(@NotNull String name, @NotNull ItemStack reward, int miningLevel, float chance, float fortuneChance) { Ingredient ingredient = new OreIngredientStoring(name); register(ingredient, new HammerReward(reward, miningLevel, chance, fortuneChance)); } public void register(@NotNull Ingredient ingredient, @NotNull HammerReward reward) { Ingredient search = registry.keySet().stream().filter(entry -> IngredientUtil.ingredientEquals(ingredient, entry)).findAny().orElse(null); if (search != null) { registry.get(search).add(reward); } else { NonNullList<HammerReward> drops = NonNullList.create(); drops.add(reward); registry.put(ingredient, drops); } } @NotNull public NonNullList<ItemStack> getRewardDrops(@NotNull Random random, @NotNull IBlockState block, int miningLevel, int fortuneLevel) { NonNullList<ItemStack> rewards = NonNullList.create(); for (HammerReward reward : getRewards(block)) { if (miningLevel >= reward.getMiningLevel()) { if (random.nextFloat() <= reward.getChance() + (reward.getFortuneChance() * fortuneLevel)) { rewards.add(reward.getStack().copy()); } } } return rewards; } @NotNull public NonNullList<HammerReward> getRewards(@NotNull IBlockState block) { return getRewards(new BlockInfo(block)); } @NotNull public NonNullList<HammerReward> getRewards(@NotNull Block block, int meta) { return getRewards(new BlockInfo(block, meta)); } @NotNull public NonNullList<HammerReward> getRewards(@NotNull BlockInfo stackInfo) { NonNullList<HammerReward> drops = NonNullList.create(); if (stackInfo.isValid()) registry.entrySet().stream().filter(entry -> entry.getKey().test(stackInfo.getItemStack())).forEach(entry -> drops.addAll(entry.getValue())); return drops; } @NotNull public NonNullList<HammerReward> getRewards(@NotNull Ingredient ingredient) { NonNullList<HammerReward> drops = NonNullList.create(); registry.entrySet().stream().filter(entry -> entry.getKey() == ingredient).forEach(entry -> drops.addAll(entry.getValue())); return drops; } public boolean isRegistered(@NotNull IBlockState block) { return isRegistered(new BlockInfo(block)); } public boolean isRegistered(@NotNull Block block) { return isRegistered(new BlockInfo(block.getDefaultState())); } /** * Just so that tinkers complement doesn't crash */ @Deprecated public boolean registered(Block block) { return isRegistered(new BlockInfo(block.getDefaultState())); } public boolean isRegistered(@NotNull BlockInfo stackInfo) { return registry.keySet().stream().anyMatch(ingredient -> ingredient.test(stackInfo.getItemStack())); } // Legacy TODO: REMOVE if it works with ex compressum @Deprecated public List<HammerReward> getRewards(IBlockState state, int miningLevel) { NonNullList<HammerReward> drops = NonNullList.create(); BlockInfo block = new BlockInfo(state); registry.entrySet().stream().filter(entry -> entry.getKey().test(block.getItemStack())) .forEach(entry -> entry.getValue().stream().filter(value -> value.getMiningLevel() <= miningLevel).forEach(drops::add)); return drops; } @Override public List<HammerRecipe> getRecipeList() { List<HammerRecipe> hammerRecipes = Lists.newLinkedList(); for(Ingredient ingredient : getRegistry().keySet()){ if(ingredient == null) continue; List<ItemStack> rawOutputs = getRewards(ingredient).stream().map(HammerReward::getStack).collect(Collectors.toList()); List<ItemStack> allOutputs = new ArrayList<>(); for(ItemStack raw : rawOutputs){ boolean alreadyexists = false; for(ItemStack all : allOutputs){ if(ItemUtil.areStacksEquivalent(all, raw)){ alreadyexists = true; break; } } if(!alreadyexists) allOutputs.add(raw); } List<ItemStack> inputs = Arrays.asList(ingredient.getMatchingStacks()); for(int i = 0; i < allOutputs.size(); i+=21){ final List<ItemStack> outputs = allOutputs.subList(i, Math.min(i+21, allOutputs.size())); hammerRecipes.add(new HammerRecipe(inputs, outputs)); } } return hammerRecipes; } }
9,281
0.668678
0.667493
212
42.778301
39.413303
158
false
false
0
0
0
0
0
0
0.712264
false
false
13
6481bde8542fa366d292a2ecb1c939dbc38c34b1
38,397,007,655,968
03676d0c538bab495bc35353d7b756b02902696c
/core/src/main/java/com/mobi/core/analysis/event/PushEvent.java
9808d8d65a5ecf0e17ac0b669ae7d408c06a6b92
[]
no_license
ZhouSilverBullet/MobiAggregateSdk
https://github.com/ZhouSilverBullet/MobiAggregateSdk
458705245ff4675fda2fb0a48d0c170dd98576d5
64d18ef3b342628485a76dca59dc3cf7293eb97b
refs/heads/master
2022-11-30T04:34:54.831000
2020-08-05T08:37:53
2020-08-05T08:37:53
268,796,028
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mobi.core.analysis.event; import android.text.TextUtils; import com.mobi.core.CoreSession; import com.mobi.core.utils.DateUtils; /** * @author zhousaito * @version 1.0 * @date 2020/6/18 20:39 * @Dec ็•ฅ */ public class PushEvent { // "event": 10, // "network":"tt", // "day":"2020-06-18", // "time":"2020-06-18 19:50", // "sort_type": "1", // "appid":"1112312xxx", // "bundle":"ๆœฌๅœฐๅฎ‰่ฃ…ๅบ”็”จ็š„ๅŒ…ๅ", // "posid":"2048001", //็ป™็”จๆˆท็š„ไฝฟ็”จ็š„ postId // "style_type":1, //ๆ’ๅฑ // "timestamp":1592465118652 //ๆ—ถ้—ดๆˆณ private int id; private int event; private String postId; private int styleType; private int sortType; private String network; /** * ็”จๆฅๅนฟๅ‘Šไธ€ๆก็บฟ่ฟฝ่ธช */ private String md5; /** * ไธŽ้”™่ฏฏ็›ธๅ…ณ็š„ๅฑžๆ€ง็ฑป */ private int type; private int code; private String message; private String debug; private String day; private String time; private long timestamp; private String bundle; private String appId; /** * 1.ๆˆๅŠŸ * 0.ๅคฑ่ดฅ */ private int isPushSuccess; public PushEvent(int event, int styleType, String postId, int sortType, String network, String md5) { this.event = event; this.styleType = styleType; this.postId = postId; this.sortType = sortType; this.network = network; this.md5 = md5; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getDebug() { return debug; } public void setDebug(String debug) { this.debug = debug; } public String getDay() { if (TextUtils.isEmpty(day)) { day = DateUtils.getStringDateDay(); } return day; } public String getTime() { if (TextUtils.isEmpty(time)) { time = DateUtils.getStringDateMin(); } return time; } public long getTimestamp() { if (timestamp == 0L) { timestamp = System.currentTimeMillis(); } return timestamp; } public String getAppId() { if (TextUtils.isEmpty(appId)) { if (CoreSession.get().getContext() != null) { appId = CoreSession.get().getAppId(); } } return appId; } public String getBundle() { if (TextUtils.isEmpty(bundle)) { if (CoreSession.get().getContext() != null) { bundle = CoreSession.get().getContext().getPackageName(); } } return bundle; } public int getSortType() { return sortType; } public int getEvent() { return event; } public int getStyleType() { return styleType; } public String getPostId() { return postId; } public String getNetwork() { return network; } public String getMd5() { return md5; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setDay(String day) { this.day = day; } public void setTime(String time) { this.time = time; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public void setBundle(String bundle) { this.bundle = bundle; } public void setAppId(String appId) { this.appId = appId; } public int getIsPushSuccess() { return isPushSuccess; } public void setIsPushSuccess(int isPushSuccess) { this.isPushSuccess = isPushSuccess; } @Override public String toString() { return "PushEvent{" + "id=" + id + ", event=" + event + ", postId='" + postId + '\'' + ", styleType=" + styleType + ", sortType=" + sortType + ", network='" + network + '\'' + ", md5='" + md5 + '\'' + ", type=" + type + ", code=" + code + ", message='" + message + '\'' + ", debug='" + debug + '\'' + ", day='" + day + '\'' + ", time='" + time + '\'' + ", timestamp=" + timestamp + ", bundle='" + bundle + '\'' + ", appId='" + appId + '\'' + ", isPushSuccess=" + isPushSuccess + '}'; } }
UTF-8
Java
5,043
java
PushEvent.java
Java
[ { "context": "ort com.mobi.core.utils.DateUtils;\n\n/**\n * @author zhousaito\n * @version 1.0\n * @date 2020/6/18 20:39\n * @Dec ", "end": 168, "score": 0.9996144771575928, "start": 159, "tag": "USERNAME", "value": "zhousaito" } ]
null
[]
package com.mobi.core.analysis.event; import android.text.TextUtils; import com.mobi.core.CoreSession; import com.mobi.core.utils.DateUtils; /** * @author zhousaito * @version 1.0 * @date 2020/6/18 20:39 * @Dec ็•ฅ */ public class PushEvent { // "event": 10, // "network":"tt", // "day":"2020-06-18", // "time":"2020-06-18 19:50", // "sort_type": "1", // "appid":"1112312xxx", // "bundle":"ๆœฌๅœฐๅฎ‰่ฃ…ๅบ”็”จ็š„ๅŒ…ๅ", // "posid":"2048001", //็ป™็”จๆˆท็š„ไฝฟ็”จ็š„ postId // "style_type":1, //ๆ’ๅฑ // "timestamp":1592465118652 //ๆ—ถ้—ดๆˆณ private int id; private int event; private String postId; private int styleType; private int sortType; private String network; /** * ็”จๆฅๅนฟๅ‘Šไธ€ๆก็บฟ่ฟฝ่ธช */ private String md5; /** * ไธŽ้”™่ฏฏ็›ธๅ…ณ็š„ๅฑžๆ€ง็ฑป */ private int type; private int code; private String message; private String debug; private String day; private String time; private long timestamp; private String bundle; private String appId; /** * 1.ๆˆๅŠŸ * 0.ๅคฑ่ดฅ */ private int isPushSuccess; public PushEvent(int event, int styleType, String postId, int sortType, String network, String md5) { this.event = event; this.styleType = styleType; this.postId = postId; this.sortType = sortType; this.network = network; this.md5 = md5; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getDebug() { return debug; } public void setDebug(String debug) { this.debug = debug; } public String getDay() { if (TextUtils.isEmpty(day)) { day = DateUtils.getStringDateDay(); } return day; } public String getTime() { if (TextUtils.isEmpty(time)) { time = DateUtils.getStringDateMin(); } return time; } public long getTimestamp() { if (timestamp == 0L) { timestamp = System.currentTimeMillis(); } return timestamp; } public String getAppId() { if (TextUtils.isEmpty(appId)) { if (CoreSession.get().getContext() != null) { appId = CoreSession.get().getAppId(); } } return appId; } public String getBundle() { if (TextUtils.isEmpty(bundle)) { if (CoreSession.get().getContext() != null) { bundle = CoreSession.get().getContext().getPackageName(); } } return bundle; } public int getSortType() { return sortType; } public int getEvent() { return event; } public int getStyleType() { return styleType; } public String getPostId() { return postId; } public String getNetwork() { return network; } public String getMd5() { return md5; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setDay(String day) { this.day = day; } public void setTime(String time) { this.time = time; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public void setBundle(String bundle) { this.bundle = bundle; } public void setAppId(String appId) { this.appId = appId; } public int getIsPushSuccess() { return isPushSuccess; } public void setIsPushSuccess(int isPushSuccess) { this.isPushSuccess = isPushSuccess; } @Override public String toString() { return "PushEvent{" + "id=" + id + ", event=" + event + ", postId='" + postId + '\'' + ", styleType=" + styleType + ", sortType=" + sortType + ", network='" + network + '\'' + ", md5='" + md5 + '\'' + ", type=" + type + ", code=" + code + ", message='" + message + '\'' + ", debug='" + debug + '\'' + ", day='" + day + '\'' + ", time='" + time + '\'' + ", timestamp=" + timestamp + ", bundle='" + bundle + '\'' + ", appId='" + appId + '\'' + ", isPushSuccess=" + isPushSuccess + '}'; } }
5,043
0.486781
0.471645
222
21.31982
16.155256
73
false
false
0
0
0
0
0
0
0.432432
false
false
13
a0ae610a8bbab6280da4fe18b79ad9448772bcb1
34,763,465,351,264
dc6b22a2fced33ebc32fb95bd5a382823a513d2d
/wicket-jquery-ui-samples/src/main/java/com/googlecode/wicket/jquery/ui/samples/kendoui/multiselect/RendererMultiSelectPage.java
1c44e90245aa1cc3d0c0b29decf0a133c52a8e07
[ "Apache-2.0" ]
permissive
sebfz1/wicket-jquery-ui
https://github.com/sebfz1/wicket-jquery-ui
5f09ffca6f60a305ee309e0d7af197b0135b35b2
b42ad542418bc7d98cb2b1cab9eb29d829894de7
refs/heads/wicket9.x
2023-08-14T10:22:39.888000
2023-03-25T05:20:32
2023-03-25T05:20:32
4,264,930
57
65
NOASSERTION
false
2023-09-07T07:53:47
2012-05-08T20:05:09
2023-05-14T18:48:36
2023-09-07T07:27:09
54,568
92
60
31
Java
false
false
package com.googlecode.wicket.jquery.ui.samples.kendoui.multiselect; import java.util.Collection; import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.model.Model; import org.apache.wicket.util.lang.Generics; import com.googlecode.wicket.jquery.ui.samples.data.bean.Genre; import com.googlecode.wicket.jquery.ui.samples.data.dao.GenresDAO; import com.googlecode.wicket.kendo.ui.form.button.AjaxButton; import com.googlecode.wicket.kendo.ui.form.button.Button; import com.googlecode.wicket.kendo.ui.form.multiselect.MultiSelect; import com.googlecode.wicket.kendo.ui.panel.KendoFeedbackPanel; public class RendererMultiSelectPage extends AbstractMultiSelectPage { private static final long serialVersionUID = 1L; public RendererMultiSelectPage() { Form<Void> form = new Form<Void>("form"); this.add(form); // FeedbackPanel // final KendoFeedbackPanel feedback = new KendoFeedbackPanel("feedback"); form.add(feedback); // MultiSelect // List<Genre> selected = Generics.newArrayList(); selected.add(GenresDAO.get(2)); selected.add(GenresDAO.get(4)); final MultiSelect<Genre> multiselect = new MultiSelect<Genre>("select", Model.ofList(selected), GenresDAO.all(), new ChoiceRenderer<Genre>("name", "id")); form.add(multiselect.setOutputMarkupId(true)); // Buttons // form.add(new Button("submit") { private static final long serialVersionUID = 1L; @Override public void onSubmit() { RendererMultiSelectPage.this.info(multiselect); } }); form.add(new AjaxButton("button") { private static final long serialVersionUID = 1L; @Override protected void onSubmit(AjaxRequestTarget target) { RendererMultiSelectPage.this.info(multiselect); target.add(feedback); } }); } private void info(MultiSelect<Genre> multiselect) { Collection<Genre> choice = multiselect.getModelObject(); this.info(choice != null ? choice.toString() : "no choice"); } }
UTF-8
Java
2,084
java
RendererMultiSelectPage.java
Java
[]
null
[]
package com.googlecode.wicket.jquery.ui.samples.kendoui.multiselect; import java.util.Collection; import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.model.Model; import org.apache.wicket.util.lang.Generics; import com.googlecode.wicket.jquery.ui.samples.data.bean.Genre; import com.googlecode.wicket.jquery.ui.samples.data.dao.GenresDAO; import com.googlecode.wicket.kendo.ui.form.button.AjaxButton; import com.googlecode.wicket.kendo.ui.form.button.Button; import com.googlecode.wicket.kendo.ui.form.multiselect.MultiSelect; import com.googlecode.wicket.kendo.ui.panel.KendoFeedbackPanel; public class RendererMultiSelectPage extends AbstractMultiSelectPage { private static final long serialVersionUID = 1L; public RendererMultiSelectPage() { Form<Void> form = new Form<Void>("form"); this.add(form); // FeedbackPanel // final KendoFeedbackPanel feedback = new KendoFeedbackPanel("feedback"); form.add(feedback); // MultiSelect // List<Genre> selected = Generics.newArrayList(); selected.add(GenresDAO.get(2)); selected.add(GenresDAO.get(4)); final MultiSelect<Genre> multiselect = new MultiSelect<Genre>("select", Model.ofList(selected), GenresDAO.all(), new ChoiceRenderer<Genre>("name", "id")); form.add(multiselect.setOutputMarkupId(true)); // Buttons // form.add(new Button("submit") { private static final long serialVersionUID = 1L; @Override public void onSubmit() { RendererMultiSelectPage.this.info(multiselect); } }); form.add(new AjaxButton("button") { private static final long serialVersionUID = 1L; @Override protected void onSubmit(AjaxRequestTarget target) { RendererMultiSelectPage.this.info(multiselect); target.add(feedback); } }); } private void info(MultiSelect<Genre> multiselect) { Collection<Genre> choice = multiselect.getModelObject(); this.info(choice != null ? choice.toString() : "no choice"); } }
2,084
0.754798
0.752399
71
28.352112
28.819056
156
false
false
0
0
0
0
0
0
1.71831
false
false
13
abf58164364cd79a784d810dbca80dc45f04266d
38,250,978,769,381
f7a88418fbba1deccce6a6c43bee2b3746442f42
/app/src/main/java/com/mall/dayi/net/api/CommunityService.java
58534d8e93b7bb6dad9f475060880cf4c8f2e7f2
[]
no_license
xiaorongkui/dayi_android_code
https://github.com/xiaorongkui/dayi_android_code
55a74b7f43e60e216d311a4b6c84919853e92adf
20fe6e338378c67f92ce18fb249a93827d537191
refs/heads/master
2020-03-20T09:28:53.548000
2018-06-24T12:38:56
2018-06-24T12:38:56
137,338,517
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mall.dayi.net.api; import com.mall.dayi.bean.response.BaseRes; import com.mall.dayi.common.AppNetConfig; import io.reactivex.Observable; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; /** * The interface Exchange service. */ public interface CommunityService { /** * ไบคๆ˜“ไธญๅฟƒๅธ็ง่Žทๅ– * * @return ExchangeCurrencyRes exchange currency */ @GET(AppNetConfig.urlPath + "wap/tradeCenter/currencyInfo") Observable<BaseRes<Object>> getExchangeCurrency(); /** * ไบคๆ˜“ไธญๅฟƒๆ•ฐๆฎ * * @param req the req * @return ExchangeCenterRes exchange center data */ @POST(AppNetConfig.urlPath + "wap/tradeCenter/getWapTradeCenterInfo") Observable<BaseRes<Object>> getExchangeCenterData(@Body Object req); }
UTF-8
Java
823
java
CommunityService.java
Java
[]
null
[]
package com.mall.dayi.net.api; import com.mall.dayi.bean.response.BaseRes; import com.mall.dayi.common.AppNetConfig; import io.reactivex.Observable; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; /** * The interface Exchange service. */ public interface CommunityService { /** * ไบคๆ˜“ไธญๅฟƒๅธ็ง่Žทๅ– * * @return ExchangeCurrencyRes exchange currency */ @GET(AppNetConfig.urlPath + "wap/tradeCenter/currencyInfo") Observable<BaseRes<Object>> getExchangeCurrency(); /** * ไบคๆ˜“ไธญๅฟƒๆ•ฐๆฎ * * @param req the req * @return ExchangeCenterRes exchange center data */ @POST(AppNetConfig.urlPath + "wap/tradeCenter/getWapTradeCenterInfo") Observable<BaseRes<Object>> getExchangeCenterData(@Body Object req); }
823
0.708176
0.704403
34
22.382353
22.419811
73
false
false
0
0
0
0
0
0
0.264706
false
false
13
eb0a79e268ee4aa6e85e6fe70e4028e90df46555
34,608,846,528,628
941f1e3ace71a88437614b23009c632bc193ee68
/app/src/main/java/app/absoftware/cementera/GraphicChart.java
9ddc96474aed9ad7a035dc8f15c1a620b6a6c678
[]
no_license
Andresbecerra72/cementeraApp_Android
https://github.com/Andresbecerra72/cementeraApp_Android
c75e7d5f69a8eeeb69187271ddaa70276ee42725
d3c63a1866ae28be1cc376d4919f670f8173d80e
refs/heads/master
2023-07-14T00:45:00.569000
2021-08-24T00:01:06
2021-08-24T00:01:06
399,280,443
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app.absoftware.cementera; import androidx.appcompat.app.AppCompatActivity; import app.absoftware.cementera.popups.PopupChart; import app.absoftware.cementera.service.Service; import app.absoftware.cementera.utility.VolleyCallback; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Paint; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.textfield.TextInputLayout; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class GraphicChart extends AppCompatActivity { // Elementos TextInputLayout selectInput; AutoCompleteTextView autoCompleteTxtView_reports; TextView tvWait, regresarText ; ProgressBar progressBar; Button getDataBtn; Service service = new Service(); // instancia la clase Service // -----------------------metodos-------------------------------- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_graphic_chart); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // conexion con elementos tvWait = findViewById(R.id.tvWait); selectInput = findViewById(R.id.selectInput); autoCompleteTxtView_reports = findViewById(R.id.autoCompleteTxtView_reports); regresarText = findViewById(R.id.regresarText); progressBar = findViewById(R.id.progress_graphic); getDataBtn = findViewById(R.id.getDataBtn); // underline textview regresarText.setPaintFlags(regresarText.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); // ---------------------------- // se deja solo visible mensaje cargando Informacion selectInput.setVisibility(View.INVISIBLE); // quita el Select getDataBtn.setVisibility(View.INVISIBLE); // quita el Button // para llenar el selec getChartData(); // llame el metodo para Obtener los datos de CHART des de el API // acciones del textView Inicio de sesion: NAVEGACION regresarText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), MenuMain.class); startActivity(intent); finish(); } }); // acciones del getDataBtn para Obtener datos del Chart desde el API getDataBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(String.valueOf(autoCompleteTxtView_reports.getText()).equals("")){ Toast.makeText(GraphicChart.this, "Seleccione una Opciรณn", Toast.LENGTH_LONG).show(); return; } // Linea para guardar la seleccion del Select service.saveLocalData(GraphicChart.this, "select_fuente", String.valueOf(autoCompleteTxtView_reports.getText())); Intent intent = new Intent(getApplicationContext(), PopupChart.class); startActivity(intent); } }); } //End OnCreate // ---------------------------------------------- // Metodo para obtener los datos desde BD: DISTINCT // ---------------------------------------------- // este metodo llena el select private void getChartData() { String url = getResources().getString(R.string.url) + "chart/distinct"; // llama la funcion DISTINCT del API service.getData(GraphicChart.this, url, new VolleyCallback() { // regresa la respuesta del API @Override public void onSuccessResponse(Object result) { // Log.d("Response", String.valueOf(result)); progressBar.setVisibility(View.INVISIBLE); // quita el Loading try { JSONObject data = new JSONObject(String.valueOf(result)); // convierte la repuesta en Objeto JSON // Log.d(" Data Message: ", String.valueOf(data.getString("message"))); if (!data.get("message").equals("Table Empty")){ // si hay Clients tvWait.setVisibility(View.INVISIBLE); // quita mensaje Cargando Informacion selectInput.setVisibility(View.VISIBLE); getDataBtn.setVisibility(View.VISIBLE); JSONArray jsonArray = data.getJSONArray("message"); // Solo la informacion del Menssage del API // JSONObject jsonObject = jsonArray.getJSONObject(0); // usado para cuando viene un registro por consulta de id o por nombre // Log.d(" Message Lenght: ", String.valueOf(jsonArray.length())); ArrayList<Object> listObject = new ArrayList<Object>(); // se crea un nueva lista de Objetos para almacenar los datos de Message for(int i = 0; i < jsonArray.length(); i++) // se extrae cada registro del JSONArray { listObject.add(i, jsonArray.get(i)); // se crea la lista de Objetos registros } List<String> items = new ArrayList<String>(); // lista para mostrar en el Select for (Object item :listObject) { // Foreach de la lista de Objetos JSONObject informsChart = new JSONObject(String.valueOf(item)); // Log.d(" Message Item: ", String.valueOf(informsChart)); // Log.d(" Message name: ", String.valueOf(informsChart.get("Table_Chart_name"))); items.add(String.valueOf(informsChart.get("Table_Chart_name"))); } ArrayAdapter<String> myAdapter_Q1 = new ArrayAdapter<String>(GraphicChart.this, R.layout.dropdown_item, items); autoCompleteTxtView_reports.setAdapter(myAdapter_Q1); // asigna el adaptador con los items al menu }else { // NO hay Charts Toast.makeText(getApplicationContext(),"NO hay Reportes Registrados", Toast.LENGTH_LONG).show(); tvWait.setText("No hay Reportes"); } } catch (JSONException e) { Log.i("MyTag JSONException", String.valueOf(e.getMessage())); } } @Override public void onErrorResponse(String error) { Log.d("Error", error); } }); } } // END class /* // Funcion Flecha Function<Double, String> func = x -> { if (x> 13) return "Muy Alto"; if (x >= 8 && x < 13) return "Alto"; if (x >= 4 && x < 8) return "Moderado"; if (x < 4) return "Bajo"; return "NA"; }; */ /* textItemF1 = findViewById(R.id.textItemF1); textItemF2 = findViewById(R.id.textItemF2); textItemF3 = findViewById(R.id.textItemF3); textItemF4 = findViewById(R.id.textItemF4); textItemF5 = findViewById(R.id.textItemF5); textItemF6 = findViewById(R.id.textItemF6); textItemF7 = findViewById(R.id.textItemF7); textItemF8 = findViewById(R.id.textItemF8); textItemF9 = findViewById(R.id.textItemF9); setTextInTV(i, String.valueOf(informsChart.get("Table_Chart_Label"))); private void setTextInTV(Integer index, String label) { Log.d(" TAG AQUI ", String.valueOf(i)); if (index == 1) textItemF1.setText(label); if (index == 2) textItemF2.setText(label); if (index == 3) textItemF3.setText(label); if (index == 4) textItemF4.setText(label); if (index == 5) textItemF5.setText(label); if (index == 6) textItemF6.setText(label); if (index == 7) textItemF7.setText(label); if (index == 8) textItemF8.setText(label); if (index == 9) textItemF9.setText(label); if (index > 9) i = 0; } */ /* for (int i = 0; i < 10; i++){ informeList.add(new Informe( i, "UNO", "DOS", "TRES", "CUATRO", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", true, true, false, true, false, false, false )); } */
UTF-8
Java
9,663
java
GraphicChart.java
Java
[]
null
[]
package app.absoftware.cementera; import androidx.appcompat.app.AppCompatActivity; import app.absoftware.cementera.popups.PopupChart; import app.absoftware.cementera.service.Service; import app.absoftware.cementera.utility.VolleyCallback; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Paint; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.textfield.TextInputLayout; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class GraphicChart extends AppCompatActivity { // Elementos TextInputLayout selectInput; AutoCompleteTextView autoCompleteTxtView_reports; TextView tvWait, regresarText ; ProgressBar progressBar; Button getDataBtn; Service service = new Service(); // instancia la clase Service // -----------------------metodos-------------------------------- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_graphic_chart); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // conexion con elementos tvWait = findViewById(R.id.tvWait); selectInput = findViewById(R.id.selectInput); autoCompleteTxtView_reports = findViewById(R.id.autoCompleteTxtView_reports); regresarText = findViewById(R.id.regresarText); progressBar = findViewById(R.id.progress_graphic); getDataBtn = findViewById(R.id.getDataBtn); // underline textview regresarText.setPaintFlags(regresarText.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); // ---------------------------- // se deja solo visible mensaje cargando Informacion selectInput.setVisibility(View.INVISIBLE); // quita el Select getDataBtn.setVisibility(View.INVISIBLE); // quita el Button // para llenar el selec getChartData(); // llame el metodo para Obtener los datos de CHART des de el API // acciones del textView Inicio de sesion: NAVEGACION regresarText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), MenuMain.class); startActivity(intent); finish(); } }); // acciones del getDataBtn para Obtener datos del Chart desde el API getDataBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(String.valueOf(autoCompleteTxtView_reports.getText()).equals("")){ Toast.makeText(GraphicChart.this, "Seleccione una Opciรณn", Toast.LENGTH_LONG).show(); return; } // Linea para guardar la seleccion del Select service.saveLocalData(GraphicChart.this, "select_fuente", String.valueOf(autoCompleteTxtView_reports.getText())); Intent intent = new Intent(getApplicationContext(), PopupChart.class); startActivity(intent); } }); } //End OnCreate // ---------------------------------------------- // Metodo para obtener los datos desde BD: DISTINCT // ---------------------------------------------- // este metodo llena el select private void getChartData() { String url = getResources().getString(R.string.url) + "chart/distinct"; // llama la funcion DISTINCT del API service.getData(GraphicChart.this, url, new VolleyCallback() { // regresa la respuesta del API @Override public void onSuccessResponse(Object result) { // Log.d("Response", String.valueOf(result)); progressBar.setVisibility(View.INVISIBLE); // quita el Loading try { JSONObject data = new JSONObject(String.valueOf(result)); // convierte la repuesta en Objeto JSON // Log.d(" Data Message: ", String.valueOf(data.getString("message"))); if (!data.get("message").equals("Table Empty")){ // si hay Clients tvWait.setVisibility(View.INVISIBLE); // quita mensaje Cargando Informacion selectInput.setVisibility(View.VISIBLE); getDataBtn.setVisibility(View.VISIBLE); JSONArray jsonArray = data.getJSONArray("message"); // Solo la informacion del Menssage del API // JSONObject jsonObject = jsonArray.getJSONObject(0); // usado para cuando viene un registro por consulta de id o por nombre // Log.d(" Message Lenght: ", String.valueOf(jsonArray.length())); ArrayList<Object> listObject = new ArrayList<Object>(); // se crea un nueva lista de Objetos para almacenar los datos de Message for(int i = 0; i < jsonArray.length(); i++) // se extrae cada registro del JSONArray { listObject.add(i, jsonArray.get(i)); // se crea la lista de Objetos registros } List<String> items = new ArrayList<String>(); // lista para mostrar en el Select for (Object item :listObject) { // Foreach de la lista de Objetos JSONObject informsChart = new JSONObject(String.valueOf(item)); // Log.d(" Message Item: ", String.valueOf(informsChart)); // Log.d(" Message name: ", String.valueOf(informsChart.get("Table_Chart_name"))); items.add(String.valueOf(informsChart.get("Table_Chart_name"))); } ArrayAdapter<String> myAdapter_Q1 = new ArrayAdapter<String>(GraphicChart.this, R.layout.dropdown_item, items); autoCompleteTxtView_reports.setAdapter(myAdapter_Q1); // asigna el adaptador con los items al menu }else { // NO hay Charts Toast.makeText(getApplicationContext(),"NO hay Reportes Registrados", Toast.LENGTH_LONG).show(); tvWait.setText("No hay Reportes"); } } catch (JSONException e) { Log.i("MyTag JSONException", String.valueOf(e.getMessage())); } } @Override public void onErrorResponse(String error) { Log.d("Error", error); } }); } } // END class /* // Funcion Flecha Function<Double, String> func = x -> { if (x> 13) return "Muy Alto"; if (x >= 8 && x < 13) return "Alto"; if (x >= 4 && x < 8) return "Moderado"; if (x < 4) return "Bajo"; return "NA"; }; */ /* textItemF1 = findViewById(R.id.textItemF1); textItemF2 = findViewById(R.id.textItemF2); textItemF3 = findViewById(R.id.textItemF3); textItemF4 = findViewById(R.id.textItemF4); textItemF5 = findViewById(R.id.textItemF5); textItemF6 = findViewById(R.id.textItemF6); textItemF7 = findViewById(R.id.textItemF7); textItemF8 = findViewById(R.id.textItemF8); textItemF9 = findViewById(R.id.textItemF9); setTextInTV(i, String.valueOf(informsChart.get("Table_Chart_Label"))); private void setTextInTV(Integer index, String label) { Log.d(" TAG AQUI ", String.valueOf(i)); if (index == 1) textItemF1.setText(label); if (index == 2) textItemF2.setText(label); if (index == 3) textItemF3.setText(label); if (index == 4) textItemF4.setText(label); if (index == 5) textItemF5.setText(label); if (index == 6) textItemF6.setText(label); if (index == 7) textItemF7.setText(label); if (index == 8) textItemF8.setText(label); if (index == 9) textItemF9.setText(label); if (index > 9) i = 0; } */ /* for (int i = 0; i < 10; i++){ informeList.add(new Informe( i, "UNO", "DOS", "TRES", "CUATRO", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", true, true, false, true, false, false, false )); } */
9,663
0.540261
0.534775
308
30.373377
31.954924
152
false
false
0
0
0
0
0
0
0.538961
false
false
13
798458783171968835dc441393d47aeb6f1774ec
4,629,974,750,857
3db3e36f1b5d9f15d5ae8dde03b5b2514dae717f
/aula/src/lista1/lista1Exercicio6.java
dd148e4906573a0ae1139358559d3206a4e0c981
[]
no_license
TiagointMartins/Turma14
https://github.com/TiagointMartins/Turma14
d0495833a03d5dc49969cd811667c8684b387e53
415d55b18bce48e18ff2c0a341c561bea9969d03
refs/heads/main
2023-03-12T15:30:58.648000
2020-12-18T17:57:41
2020-12-18T17:57:41
319,493,912
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lista1; import java.lang.Math; import java.util.Scanner; public class lista1Exercicio6 { public static void main(String[] args) { Scanner leia = new Scanner (System.in); double distancia, X1,X2, Y1, Y2, D, P1, P2; System.out.println("Informe o valor de X1: "); X1 = leia.nextDouble(); System.out.println("Informe o valor de Y1: "); Y1 = leia.nextDouble(); System.out.println("Informe o valor de X2: "); X2 = leia.nextDouble(); System.out.println("Informe o valor de Y2: "); Y2 = leia.nextDouble(); P1 = (X2 - X1)* (X2 - X1); P2 = (Y2 - Y1)* (Y2 - Y1); distancia = (P1 + P2) * (P1 + P2); System.out.println("O valor de distฤncia รฉ: "+distancia); } }
ISO-8859-13
Java
722
java
lista1Exercicio6.java
Java
[]
null
[]
package lista1; import java.lang.Math; import java.util.Scanner; public class lista1Exercicio6 { public static void main(String[] args) { Scanner leia = new Scanner (System.in); double distancia, X1,X2, Y1, Y2, D, P1, P2; System.out.println("Informe o valor de X1: "); X1 = leia.nextDouble(); System.out.println("Informe o valor de Y1: "); Y1 = leia.nextDouble(); System.out.println("Informe o valor de X2: "); X2 = leia.nextDouble(); System.out.println("Informe o valor de Y2: "); Y2 = leia.nextDouble(); P1 = (X2 - X1)* (X2 - X1); P2 = (Y2 - Y1)* (Y2 - Y1); distancia = (P1 + P2) * (P1 + P2); System.out.println("O valor de distฤncia รฉ: "+distancia); } }
722
0.613889
0.570833
33
20.818182
18.81562
59
false
false
0
0
0
0
0
0
2.151515
false
false
13
34ca3c06be55a36df3e5c22f7cc4a8c61e6777fd
15,401,752,786,309
ff46dec18352436820d41b1b5a0ea321b4d3a493
/src/org/buildndeploy/server/util/ChannelUtil.java
b19ea5c151a836049d8b403649911e6f1537e859
[]
no_license
WhileLoop/filesyncr-appengine
https://github.com/WhileLoop/filesyncr-appengine
9c6ccd2fa5a089ae1966313feb69de90d58c4a11
d57bac4639157224359d4d82ece601baa4807a75
refs/heads/master
2021-01-10T14:33:19.438000
2016-04-06T21:51:52
2016-04-06T21:51:52
55,632,473
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.buildndeploy.server.util; import java.io.IOException; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Date; import java.util.List; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import org.buildndeploy.server.model.ChannelConnection; import org.buildndeploy.shared.model.MessageType; import com.google.appengine.api.channel.ChannelMessage; import com.google.appengine.api.channel.ChannelPresence; import com.google.appengine.api.channel.ChannelService; import com.google.appengine.api.channel.ChannelServiceFactory; public class ChannelUtil { // 24 * 60 private static final int CHANNEL_TOKEN_TIMEOUT_MINUTES = 24 * 60 - 1; // One day is max private static final int CHANNEL_TOKEN_TIMEOUT_MILIS = CHANNEL_TOKEN_TIMEOUT_MINUTES * 60 * 1000; private static final long FIVE_MINUTES = 60 * 5 * 1000; private static SecureRandom rand = new SecureRandom(); private static Logger log = Logger.getLogger(ChannelUtil.class.getName()); // ========================================================================= // // CHANNEL MANAGMENT // // ========================================================================= // public static String proccesClientId(String username) { long now = new Date().getTime(); // Check for available channel log.info("begin query"); ChannelConnection availableChannel = ObjectifyUtil.ofy().load() .type(ChannelConnection.class) .filter("active", false) .filter("expires >", now + FIVE_MINUTES) .first().get(); if (availableChannel != null) { log.info("found available channel " + availableChannel.getChannelToken()); availableChannel.setUsername(username).save(); return availableChannel.getChannelToken(); } else { // Generate new client id log.info("gen rand"); String newClientId = new BigInteger(130, rand).toString(32); ChannelService channelService = ChannelServiceFactory.getChannelService(); // Open new channel log.info("duration minutes: " + CHANNEL_TOKEN_TIMEOUT_MINUTES); String newChannelToken = channelService.createChannel(newClientId, CHANNEL_TOKEN_TIMEOUT_MINUTES); // Save new entity long expires = new Date().getTime() + CHANNEL_TOKEN_TIMEOUT_MILIS; new ChannelConnection() .setClientId(newClientId) .setChannelToken(newChannelToken) .setExpires(expires) .setActive(false) .setUsername(username) .save(); log.info("created new channel " + newChannelToken); log.info("from client id " + newClientId); log.info("expires " + new Date(expires)); // Return token to client return newChannelToken; } } public static String parsePresence(HttpServletRequest req) throws IOException { ChannelService channelService = ChannelServiceFactory.getChannelService(); ChannelPresence presence = channelService.parsePresence(req); String clientId = presence.clientId(); return clientId; } // ========================================================================= // // PUSH MESSAGES // // ========================================================================= // public static void pushMessage(String payload, MessageType type) { ChannelService channelService = ChannelServiceFactory.getChannelService(); // Find all active channels List<ChannelConnection> activeChannels = ObjectifyUtil.ofy().load().type(ChannelConnection.class).filter("active", true).list(); for (ChannelConnection channel : activeChannels) { String clientId = channel.getClientId(); // Payloads are not logged log.info("Sending message to " + clientId + " of type " + type); ChannelMessage msg = createMessage(clientId, type, payload); channelService.sendMessage(msg); } } private static ChannelMessage createMessage(String id, MessageType type, String payload) { String typeOrdinal = type.ordinal() + ""; // Encode enum return new ChannelMessage(id, typeOrdinal + "|" + payload); // Append message type and delimiter } }
UTF-8
Java
4,110
java
ChannelUtil.java
Java
[ { "context": "expires)\r\n\t\t\t\t.setActive(false)\r\n\t\t\t\t.setUsername(username)\r\n\t\t\t\t.save();\r\n\t\t\tlog.info(\"created new channel ", "end": 2490, "score": 0.9983838796615601, "start": 2482, "tag": "USERNAME", "value": "username" } ]
null
[]
package org.buildndeploy.server.util; import java.io.IOException; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Date; import java.util.List; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import org.buildndeploy.server.model.ChannelConnection; import org.buildndeploy.shared.model.MessageType; import com.google.appengine.api.channel.ChannelMessage; import com.google.appengine.api.channel.ChannelPresence; import com.google.appengine.api.channel.ChannelService; import com.google.appengine.api.channel.ChannelServiceFactory; public class ChannelUtil { // 24 * 60 private static final int CHANNEL_TOKEN_TIMEOUT_MINUTES = 24 * 60 - 1; // One day is max private static final int CHANNEL_TOKEN_TIMEOUT_MILIS = CHANNEL_TOKEN_TIMEOUT_MINUTES * 60 * 1000; private static final long FIVE_MINUTES = 60 * 5 * 1000; private static SecureRandom rand = new SecureRandom(); private static Logger log = Logger.getLogger(ChannelUtil.class.getName()); // ========================================================================= // // CHANNEL MANAGMENT // // ========================================================================= // public static String proccesClientId(String username) { long now = new Date().getTime(); // Check for available channel log.info("begin query"); ChannelConnection availableChannel = ObjectifyUtil.ofy().load() .type(ChannelConnection.class) .filter("active", false) .filter("expires >", now + FIVE_MINUTES) .first().get(); if (availableChannel != null) { log.info("found available channel " + availableChannel.getChannelToken()); availableChannel.setUsername(username).save(); return availableChannel.getChannelToken(); } else { // Generate new client id log.info("gen rand"); String newClientId = new BigInteger(130, rand).toString(32); ChannelService channelService = ChannelServiceFactory.getChannelService(); // Open new channel log.info("duration minutes: " + CHANNEL_TOKEN_TIMEOUT_MINUTES); String newChannelToken = channelService.createChannel(newClientId, CHANNEL_TOKEN_TIMEOUT_MINUTES); // Save new entity long expires = new Date().getTime() + CHANNEL_TOKEN_TIMEOUT_MILIS; new ChannelConnection() .setClientId(newClientId) .setChannelToken(newChannelToken) .setExpires(expires) .setActive(false) .setUsername(username) .save(); log.info("created new channel " + newChannelToken); log.info("from client id " + newClientId); log.info("expires " + new Date(expires)); // Return token to client return newChannelToken; } } public static String parsePresence(HttpServletRequest req) throws IOException { ChannelService channelService = ChannelServiceFactory.getChannelService(); ChannelPresence presence = channelService.parsePresence(req); String clientId = presence.clientId(); return clientId; } // ========================================================================= // // PUSH MESSAGES // // ========================================================================= // public static void pushMessage(String payload, MessageType type) { ChannelService channelService = ChannelServiceFactory.getChannelService(); // Find all active channels List<ChannelConnection> activeChannels = ObjectifyUtil.ofy().load().type(ChannelConnection.class).filter("active", true).list(); for (ChannelConnection channel : activeChannels) { String clientId = channel.getClientId(); // Payloads are not logged log.info("Sending message to " + clientId + " of type " + type); ChannelMessage msg = createMessage(clientId, type, payload); channelService.sendMessage(msg); } } private static ChannelMessage createMessage(String id, MessageType type, String payload) { String typeOrdinal = type.ordinal() + ""; // Encode enum return new ChannelMessage(id, typeOrdinal + "|" + payload); // Append message type and delimiter } }
4,110
0.664963
0.658394
100
39.099998
29.114429
130
false
false
0
0
0
0
73
0.071046
2.59
false
false
13
a1c083aea3e50d3c19dfafce532bff31c4d9d10f
8,263,517,082,006
e5eb63f8e6db7bdc3bfd40259697c1d8a8762485
/src/service/WebServiceStub.java
dc6355a02ece3d67d2bd31ddbe0f4bffc79037a5
[]
no_license
Jisher/stock-trader-tdd
https://github.com/Jisher/stock-trader-tdd
3e953b95cf01627400b0cb12b889f5d8732abd08
6a67ddb07a751cd97af11e744685413a93a8fda0
refs/heads/master
2018-03-21T17:11:20.489000
2016-09-12T16:04:28
2016-09-12T16:04:28
66,707,508
0
0
null
false
2016-09-02T14:29:09
2016-08-27T09:47:17
2016-08-27T13:21:19
2016-09-02T14:29:09
3,571
0
0
0
Java
null
null
package service; import java.util.ArrayList; public class WebServiceStub implements Service { public boolean authenticate(int userID, String password) { boolean validID = validateID(userID); boolean validPass = validatePassword(password); if (validID == true && validPass == true) { return true; } return false; } public String getStockInfo(String symbol) throws Exception { String companyName = "ABC Inc"; int currentPrice = 1000; int numberOfSharesOutstanding = 4700; if (validSymbol(symbol) == true) { if (validNumber(currentPrice) == false || validNumber(numberOfSharesOutstanding) == false) { throw new Exception("Numbers cannot be less than zero"); } return String.format("%s, %s, %d, %s", companyName, symbol, currentPrice, numberOfSharesOutstanding); } else { return "No such symbol"; } } private boolean validateID(int userID) { int ID = userID; if (ID > 9999 || ID < 1) { return false; } return true; } private boolean validatePassword(String password) { String regex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$"; return password.matches(regex); } private boolean validSymbol(String symbol) { return true; } private boolean validNumber(int num) { if (num >= 0) { return true; } return false; } }
UTF-8
Java
1,322
java
WebServiceStub.java
Java
[]
null
[]
package service; import java.util.ArrayList; public class WebServiceStub implements Service { public boolean authenticate(int userID, String password) { boolean validID = validateID(userID); boolean validPass = validatePassword(password); if (validID == true && validPass == true) { return true; } return false; } public String getStockInfo(String symbol) throws Exception { String companyName = "ABC Inc"; int currentPrice = 1000; int numberOfSharesOutstanding = 4700; if (validSymbol(symbol) == true) { if (validNumber(currentPrice) == false || validNumber(numberOfSharesOutstanding) == false) { throw new Exception("Numbers cannot be less than zero"); } return String.format("%s, %s, %d, %s", companyName, symbol, currentPrice, numberOfSharesOutstanding); } else { return "No such symbol"; } } private boolean validateID(int userID) { int ID = userID; if (ID > 9999 || ID < 1) { return false; } return true; } private boolean validatePassword(String password) { String regex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$"; return password.matches(regex); } private boolean validSymbol(String symbol) { return true; } private boolean validNumber(int num) { if (num >= 0) { return true; } return false; } }
1,322
0.661876
0.649017
58
21.810345
25.246002
104
false
false
0
0
0
0
0
0
1.931034
false
false
13
1cab44433c748ba64edd0408a0dea48c941880a0
8,263,517,079,602
2e1a6cb585684494676e6dc7b72228a913ad0b2f
/app/src/main/java/com/XuanRan/GetClass/SignCheck.java
cb7c464fe68b97798418813bd44bda63857cdca0
[]
no_license
XuanRan0808/getclass
https://github.com/XuanRan0808/getclass
d477f06022d0f8f9e1d85d8a1360aab4a89aebe5
0b77b7fd124a39679b59ef57e6b978d11a5ae528
refs/heads/master
2020-12-04T09:11:00.030000
2020-01-17T15:09:09
2020-01-17T15:09:09
231,706,860
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.XuanRan.GetClass; /** * Create By XuanRan 2019/02/04 */ import android.content.*; import android.content.pm.*; import android.util.*; import dalvik.system.*; import java.io.*; import java.security.*; import java.security.cert.*; import java.util.*; import android.content.pm.Signature; import android.util.Base64; //็ญพๅ้ชŒ่ฏๅทฅๅ…ท public class SignCheck { private Context context; private String cer = null; /* * param 0:cc.binmt.signature.PmsHookApplication * param 1:cn.wjdiankong.hookpms.ServiceManagerWraper * */ private String bxHookClass[]={"Y2MuYmlubXQuc2lnbmF0dXJlLlBtc0hvb2tBcHBsaWNhdGlvbg==","Y24ud2pkaWFua29uZy5ob29rcG1zLlNlcnZpY2VNYW5hZ2VyV3JhcGVy",}; /* * param:็”จๆˆท่‡ชๅฎšไน‰็š„Hook็ฑป */ private String HookClass[]={"","","","","","","","","","","","","","","","","","","","","","","",""}; private List<String> hookclasslist; private String realCer = null; private static final String TAG = "SignCheck"; /* * Base64่ฝฌๆขString * Creat:XuanRan */ public String Base64ToString(String hi) { byte[] by=Base64.decode(hi, 0); String string=new String(by); return string; } /* * ๅฏปๆ‰พHook Class */ public void FindHookClass() { for (int xr=0;xr < hookclasslist.size();xr++) { // param ๆŸฅๆ‰พ็š„ๅŒ…ๅ่ทฏๅพ„ List<String >classNameList=getClassName(hookclasslist.get(xr), context); for (int i=0;i < classNameList.size();i++) { //้€š่ฟ‡ๅพช็Žฏๅฏนๆฏ”ๆ•ฐ็ป„ๆฅๆฃ€ๆŸฅๆ˜ฏๅฆๅญ˜ๅœจ if (hookclasslist.contains(classNameList.get(i))) { kill(); } } } } /* * ็ป“ๆŸ็จ‹ๅบ่ฟ›็จ‹ */ protected void kill() { Log.e(Base64ToString("WHVhblJhblJ1blRpbWVFeGNlcHRpb24="), Base64ToString("UHJvaGliaXRlZCBDbGFzczo=")); int ip=android.os.Process.myPid(); android.os.Process.killProcess(ip); } public SignCheck(Context context) { this.context = context; this.cer = getCertificateSHA1Fingerprint(); } public SignCheck(Context context, String realCer) { this.context = context; this.realCer = realCer; this.cer = getCertificateSHA1Fingerprint(); //ๆฃ€ๆŸฅๆ˜ฏๅฆๆ˜ฏ็ฌฌไธ€ๆฌกไฝฟ็”จ ๅ‡ๅฐ‘่ต„ๆบๆตช่ดน if (!isNotFirst("WHVhblJhbkNoZWNrU2lnblNoYXJlZEJvb2xlYW4")) { hookclasslist = new ArrayList<String >(); //ๅฟฝ็•ฅbxHookClassๆ•ฐ็ป„ไธญ็š„็ฉบ็™ฝๅ†…ๅฎน for (int xr=0;xr < bxHookClass.length;xr++) { if (!bxHookClass[xr].equals("")) { //่งฃๅฏ†bxhookclassๆ•ฐ็ป„ๅ†…ๅฎนๅนถๆทปๅŠ ๅˆฐhookclasslistไธญ hookclasslist.add(Base64ToString(bxHookClass[xr])); } } //็”จๆˆท่‡ชๅฎšไน‰้œ€่ฆๆฃ€ๆŸฅ็š„class๏ผŒๅฟฝ็•ฅhookClassไธญ็š„็ฉบ็™ฝๅ†…ๅฎน for (int xr=0;xr < HookClass.length;xr++) { //ๆฃ€ๆŸฅHookClassๆ•ฐ็ป„ไธญๆ˜ฏๅฆๅญ˜ๅœจ็ฉบๅ€ผ if (!HookClass[xr].equals("")) { //ๅฆ‚ๆžœไธๆ˜ฏ็ฉบๅ€ผๅˆ™ๆฃ€ๆŸฅhookclasslistๆ˜ฏๅฆๅทฒ็ปๅญ˜ๅœจ if (!hookclasslist.contains(HookClass[xr])) { //ๅฐ†้ž็ฉบๅ€ผๅ’Œๆœช้‡ๅค็š„ๆทปๅŠ ๅˆฐhookclasslistๆ•ฐ็ป„ใ€‚ hookclasslist.add(HookClass[xr]); } } } hookclasslist.add(context.getPackageName() + ".PmsHook"); //ๅฏปๆ‰พHookClassๅˆ—่กจ FindHookClass(); //ๅœจๅˆ›ๅปบๆž„้€ ๆ–นๆณ•ๆ—ถๅฐฑๅผ€ๅง‹ๆฃ€ๆŸฅ็ญพๅ if (!check()) { kill(); } } } public String getRealCer() { return realCer; } /** * ่ฎพ็ฝฎๆญฃ็กฎ็š„็ญพๅ * * @param realCer */ public void setRealCer(String realCer) { this.realCer = realCer; } /** * ่Žทๅ–ๅบ”็”จ็š„็ญพๅ * * @return */ public String getCertificateSHA1Fingerprint() { //่Žทๅ–ๅŒ…็ฎก็†ๅ™จ PackageManager pm = context.getPackageManager(); //่Žทๅ–ๅฝ“ๅ‰่ฆ่Žทๅ– SHA1 ๅ€ผ็š„ๅŒ…ๅ๏ผŒไนŸๅฏไปฅ็”จๅ…ถไป–็š„ๅŒ…ๅ๏ผŒไฝ†้œ€่ฆๆณจๆ„๏ผŒ //ๅœจ็”จๅ…ถไป–ๅŒ…ๅ็š„ๅ‰ๆๆ˜ฏ๏ผŒๆญคๆ–นๆณ•ไผ ้€’็š„ๅ‚ๆ•ฐ Context ๅบ”่ฏฅๆ˜ฏๅฏนๅบ”ๅŒ…็š„ไธŠไธ‹ๆ–‡ใ€‚ String packageName = context.getPackageName(); //่ฟ”ๅ›žๅŒ…ๆ‹ฌๅœจๅŒ…ไธญ็š„็ญพๅไฟกๆฏ int flags = PackageManager.GET_SIGNATURES; PackageInfo packageInfo = null; try { //่Žทๅพ—ๅŒ…็š„ๆ‰€ๆœ‰ๅ†…ๅฎนไฟกๆฏ็ฑป packageInfo = pm.getPackageInfo(packageName, flags); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } //็ญพๅไฟกๆฏ Signature[] signatures = packageInfo.signatures; byte[] cert = signatures[0].toByteArray(); //ๅฐ†็ญพๅ่ฝฌๆขไธบๅญ—่Š‚ๆ•ฐ็ป„ๆต InputStream input = new ByteArrayInputStream(cert); //่ฏไนฆๅทฅๅŽ‚็ฑป๏ผŒ่ฟ™ไธช็ฑปๅฎž็Žฐไบ†ๅ‡บๅŽ‚ๅˆๆ ผ่ฏ็ฎ—ๆณ•็š„ๅŠŸ่ƒฝ CertificateFactory cf = null; try { cf = CertificateFactory.getInstance("X509"); } catch (Exception e) { e.printStackTrace(); } //X509 ่ฏไนฆ๏ผŒX.509 ๆ˜ฏไธ€็ง้žๅธธ้€š็”จ็š„่ฏไนฆๆ ผๅผ X509Certificate c = null; try { c = (X509Certificate) cf.generateCertificate(input); } catch (Exception e) { e.printStackTrace(); } String hexString = null; try { //ๅŠ ๅฏ†็ฎ—ๆณ•็š„็ฑป๏ผŒ่ฟ™้‡Œ็š„ๅ‚ๆ•ฐๅฏไปฅไฝฟ MD4,MD5 ็ญ‰ๅŠ ๅฏ†็ฎ—ๆณ• MessageDigest md = MessageDigest.getInstance("SHA1"); //่Žทๅพ—ๅ…ฌ้’ฅ byte[] publicKey = md.digest(c.getEncoded()); //ๅญ—่Š‚ๅˆฐๅๅ…ญ่ฟ›ๅˆถ็š„ๆ ผๅผ่ฝฌๆข hexString = byte2HexFormatted(publicKey); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (CertificateEncodingException e) { e.printStackTrace(); } return hexString; } /* * ๆ ผๅผ่ฝฌๆข * Create:XuanRan * https://dwz.cn/QQ3135 * MT่ฎบๅ›๏ผšbbs.binmt.cc */ private String byte2HexFormatted(byte[] arr) { StringBuilder str = new StringBuilder(arr.length * 2); for (int i = 0; i < arr.length; i++) { String h = Integer.toHexString(arr[i]); int l =h.length(); if (l == 1) h = "0" + h; if (l > 2) h = h.substring(l - 2, l); str.append(h.toUpperCase()); if (i < (arr.length - 1)) str.append(':'); } return str.toString(); } /* * ่Žทๅ–็ฑป */ public List<String > getClassName(String packageName, Context context) { List<String >classNameList=new ArrayList<String >(); try { DexFile df = new DexFile(context.getPackageCodePath());//้€š่ฟ‡DexFileๆŸฅๆ‰พๅฝ“ๅ‰็š„APKไธญๅฏๆ‰ง่กŒๆ–‡ไปถ Enumeration<String> enumeration = df.entries();//่Žทๅ–dfไธญ็š„ๅ…ƒ็ด  ่ฟ™้‡ŒๅŒ…ๅซไบ†ๆ‰€ๆœ‰ๅฏๆ‰ง่กŒ็š„็ฑปๅ ่ฏฅ็ฑปๅๅŒ…ๅซไบ†ๅŒ…ๅ+็ฑปๅ็š„ๆ–นๅผ while (enumeration.hasMoreElements()) {//้ๅކ String className = (String) enumeration.nextElement(); if (className.contains(packageName)) {//ๅœจๅฝ“ๅ‰ๆ‰€ๆœ‰ๅฏๆ‰ง่กŒ็š„็ฑป้‡Œ้ขๆŸฅๆ‰พๅŒ…ๅซๆœ‰่ฏฅๅŒ…ๅ็š„ๆ‰€ๆœ‰็ฑป classNameList.add(className); } } } catch (Exception e) { e.printStackTrace(); } return classNameList; } /* * ๆฃ€ๆŸฅๆ˜ฏๅฆไธบ็ฌฌไธ€ๆฌกไฝฟ็”จ๏ผŒๅ‡ๅฐ‘็ณป็ปŸ่ต„ๆบๆตช่ดน * */ public boolean isNotFirst(String a) { SharedPreferences shared=context.getSharedPreferences(Base64ToString("WHVhblJhbkNoZWNrU2lnblNoYXJlZFBGaWxl"), Context.MODE_PRIVATE); return shared.getBoolean(Base64ToString(a), false); } public void putNotfirst() { SharedPreferences shared=context.getSharedPreferences(Base64ToString("WHVhblJhbkNoZWNrU2lnblNoYXJlZFBGaWxl"), Context.MODE_PRIVATE); SharedPreferences.Editor sharededit=shared.edit(); sharededit.putBoolean(Base64ToString("WHVhblJhbkNoZWNrU2lnblNoYXJlZEJvb2xlYW4="), true); sharededit.commit(); } /** * ๆฃ€ๆต‹็ญพๅๆ˜ฏๅฆๆญฃ็กฎ * @return true ็ญพๅๆญฃๅธธ false ็ญพๅไธๆญฃๅธธ */ public boolean check() { boolean reboln=false; boolean xuanranboolean=isNotFirst("WHVhblJhbkNoZWNrU2lnblNoYXJlZEJvb2xlYW4="); if (reboln) { kill(); } if (this.realCer != null) { cer = cer.trim(); realCer = realCer.trim(); if (this.cer.equals(this.realCer)) { reboln = true; if (!xuanranboolean) { putNotfirst(); } return reboln; } } else { Log.e(Base64ToString("WHVhblJhblJ1blRpbWVFeGNlcHRpb24="), Base64ToString("5pyq57uZ5a6a55yf5a6e55qE562+5ZCNIFNIQS0xIOWAvA==")); } return reboln; }}
UTF-8
Java
8,574
java
SignCheck.java
Java
[ { "context": "package com.XuanRan.GetClass;\n\n/**\n * Create By XuanRan 2019/02/04\n */\nimport android.content.*;\nimport a", "end": 55, "score": 0.9935849905014038, "start": 48, "tag": "NAME", "value": "XuanRan" }, { "context": "Wraper\n\t * \n\t */\n\tprivate String bxHookClass[]={\"Y2MuYmlubXQuc2lnbmF0dXJlLlBtc0hvb2tBcHBsaWNhdGlvbg==", "end": 576, "score": 0.5072861909866333, "start": 575, "tag": "KEY", "value": "2" }, { "context": "mlubXQuc2lnbmF0dXJlLlBtc0hvb2tBcHBsaWNhdGlvbg==\",\"Y24ud2pkaWFua29uZy5ob29rcG1zLlNlcnZpY2VNYW5hZ2VyV3JhcGVy\",};\n\t/*\n\t * param:็”จๆˆท่‡ชๅฎšไน‰็š„Hook็ฑป\n\t */\n\tprivate Strin", "end": 685, "score": 0.7684537172317505, "start": 629, "tag": "KEY", "value": "Y24ud2pkaWFua29uZy5ob29rcG1zLlNlcnZpY2VNYW5hZ2VyV3JhcGVy" }, { "context": "turn hexString;\n }\n\n /*\n\t * ๆ ผๅผ่ฝฌๆข\n\t * Create:XuanRan\n\t * https://dwz.cn/QQ3135\n\t * MT่ฎบๅ›๏ผšbbs.binmt.cc\n\t", "end": 5037, "score": 0.9698634743690491, "start": 5030, "tag": "NAME", "value": "XuanRan" } ]
null
[]
package com.XuanRan.GetClass; /** * Create By XuanRan 2019/02/04 */ import android.content.*; import android.content.pm.*; import android.util.*; import dalvik.system.*; import java.io.*; import java.security.*; import java.security.cert.*; import java.util.*; import android.content.pm.Signature; import android.util.Base64; //็ญพๅ้ชŒ่ฏๅทฅๅ…ท public class SignCheck { private Context context; private String cer = null; /* * param 0:cc.binmt.signature.PmsHookApplication * param 1:cn.wjdiankong.hookpms.ServiceManagerWraper * */ private String bxHookClass[]={"Y2MuYmlubXQuc2lnbmF0dXJlLlBtc0hvb2tBcHBsaWNhdGlvbg==","<KEY>",}; /* * param:็”จๆˆท่‡ชๅฎšไน‰็š„Hook็ฑป */ private String HookClass[]={"","","","","","","","","","","","","","","","","","","","","","","",""}; private List<String> hookclasslist; private String realCer = null; private static final String TAG = "SignCheck"; /* * Base64่ฝฌๆขString * Creat:XuanRan */ public String Base64ToString(String hi) { byte[] by=Base64.decode(hi, 0); String string=new String(by); return string; } /* * ๅฏปๆ‰พHook Class */ public void FindHookClass() { for (int xr=0;xr < hookclasslist.size();xr++) { // param ๆŸฅๆ‰พ็š„ๅŒ…ๅ่ทฏๅพ„ List<String >classNameList=getClassName(hookclasslist.get(xr), context); for (int i=0;i < classNameList.size();i++) { //้€š่ฟ‡ๅพช็Žฏๅฏนๆฏ”ๆ•ฐ็ป„ๆฅๆฃ€ๆŸฅๆ˜ฏๅฆๅญ˜ๅœจ if (hookclasslist.contains(classNameList.get(i))) { kill(); } } } } /* * ็ป“ๆŸ็จ‹ๅบ่ฟ›็จ‹ */ protected void kill() { Log.e(Base64ToString("WHVhblJhblJ1blRpbWVFeGNlcHRpb24="), Base64ToString("UHJvaGliaXRlZCBDbGFzczo=")); int ip=android.os.Process.myPid(); android.os.Process.killProcess(ip); } public SignCheck(Context context) { this.context = context; this.cer = getCertificateSHA1Fingerprint(); } public SignCheck(Context context, String realCer) { this.context = context; this.realCer = realCer; this.cer = getCertificateSHA1Fingerprint(); //ๆฃ€ๆŸฅๆ˜ฏๅฆๆ˜ฏ็ฌฌไธ€ๆฌกไฝฟ็”จ ๅ‡ๅฐ‘่ต„ๆบๆตช่ดน if (!isNotFirst("WHVhblJhbkNoZWNrU2lnblNoYXJlZEJvb2xlYW4")) { hookclasslist = new ArrayList<String >(); //ๅฟฝ็•ฅbxHookClassๆ•ฐ็ป„ไธญ็š„็ฉบ็™ฝๅ†…ๅฎน for (int xr=0;xr < bxHookClass.length;xr++) { if (!bxHookClass[xr].equals("")) { //่งฃๅฏ†bxhookclassๆ•ฐ็ป„ๅ†…ๅฎนๅนถๆทปๅŠ ๅˆฐhookclasslistไธญ hookclasslist.add(Base64ToString(bxHookClass[xr])); } } //็”จๆˆท่‡ชๅฎšไน‰้œ€่ฆๆฃ€ๆŸฅ็š„class๏ผŒๅฟฝ็•ฅhookClassไธญ็š„็ฉบ็™ฝๅ†…ๅฎน for (int xr=0;xr < HookClass.length;xr++) { //ๆฃ€ๆŸฅHookClassๆ•ฐ็ป„ไธญๆ˜ฏๅฆๅญ˜ๅœจ็ฉบๅ€ผ if (!HookClass[xr].equals("")) { //ๅฆ‚ๆžœไธๆ˜ฏ็ฉบๅ€ผๅˆ™ๆฃ€ๆŸฅhookclasslistๆ˜ฏๅฆๅทฒ็ปๅญ˜ๅœจ if (!hookclasslist.contains(HookClass[xr])) { //ๅฐ†้ž็ฉบๅ€ผๅ’Œๆœช้‡ๅค็š„ๆทปๅŠ ๅˆฐhookclasslistๆ•ฐ็ป„ใ€‚ hookclasslist.add(HookClass[xr]); } } } hookclasslist.add(context.getPackageName() + ".PmsHook"); //ๅฏปๆ‰พHookClassๅˆ—่กจ FindHookClass(); //ๅœจๅˆ›ๅปบๆž„้€ ๆ–นๆณ•ๆ—ถๅฐฑๅผ€ๅง‹ๆฃ€ๆŸฅ็ญพๅ if (!check()) { kill(); } } } public String getRealCer() { return realCer; } /** * ่ฎพ็ฝฎๆญฃ็กฎ็š„็ญพๅ * * @param realCer */ public void setRealCer(String realCer) { this.realCer = realCer; } /** * ่Žทๅ–ๅบ”็”จ็š„็ญพๅ * * @return */ public String getCertificateSHA1Fingerprint() { //่Žทๅ–ๅŒ…็ฎก็†ๅ™จ PackageManager pm = context.getPackageManager(); //่Žทๅ–ๅฝ“ๅ‰่ฆ่Žทๅ– SHA1 ๅ€ผ็š„ๅŒ…ๅ๏ผŒไนŸๅฏไปฅ็”จๅ…ถไป–็š„ๅŒ…ๅ๏ผŒไฝ†้œ€่ฆๆณจๆ„๏ผŒ //ๅœจ็”จๅ…ถไป–ๅŒ…ๅ็š„ๅ‰ๆๆ˜ฏ๏ผŒๆญคๆ–นๆณ•ไผ ้€’็š„ๅ‚ๆ•ฐ Context ๅบ”่ฏฅๆ˜ฏๅฏนๅบ”ๅŒ…็š„ไธŠไธ‹ๆ–‡ใ€‚ String packageName = context.getPackageName(); //่ฟ”ๅ›žๅŒ…ๆ‹ฌๅœจๅŒ…ไธญ็š„็ญพๅไฟกๆฏ int flags = PackageManager.GET_SIGNATURES; PackageInfo packageInfo = null; try { //่Žทๅพ—ๅŒ…็š„ๆ‰€ๆœ‰ๅ†…ๅฎนไฟกๆฏ็ฑป packageInfo = pm.getPackageInfo(packageName, flags); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } //็ญพๅไฟกๆฏ Signature[] signatures = packageInfo.signatures; byte[] cert = signatures[0].toByteArray(); //ๅฐ†็ญพๅ่ฝฌๆขไธบๅญ—่Š‚ๆ•ฐ็ป„ๆต InputStream input = new ByteArrayInputStream(cert); //่ฏไนฆๅทฅๅŽ‚็ฑป๏ผŒ่ฟ™ไธช็ฑปๅฎž็Žฐไบ†ๅ‡บๅŽ‚ๅˆๆ ผ่ฏ็ฎ—ๆณ•็š„ๅŠŸ่ƒฝ CertificateFactory cf = null; try { cf = CertificateFactory.getInstance("X509"); } catch (Exception e) { e.printStackTrace(); } //X509 ่ฏไนฆ๏ผŒX.509 ๆ˜ฏไธ€็ง้žๅธธ้€š็”จ็š„่ฏไนฆๆ ผๅผ X509Certificate c = null; try { c = (X509Certificate) cf.generateCertificate(input); } catch (Exception e) { e.printStackTrace(); } String hexString = null; try { //ๅŠ ๅฏ†็ฎ—ๆณ•็š„็ฑป๏ผŒ่ฟ™้‡Œ็š„ๅ‚ๆ•ฐๅฏไปฅไฝฟ MD4,MD5 ็ญ‰ๅŠ ๅฏ†็ฎ—ๆณ• MessageDigest md = MessageDigest.getInstance("SHA1"); //่Žทๅพ—ๅ…ฌ้’ฅ byte[] publicKey = md.digest(c.getEncoded()); //ๅญ—่Š‚ๅˆฐๅๅ…ญ่ฟ›ๅˆถ็š„ๆ ผๅผ่ฝฌๆข hexString = byte2HexFormatted(publicKey); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (CertificateEncodingException e) { e.printStackTrace(); } return hexString; } /* * ๆ ผๅผ่ฝฌๆข * Create:XuanRan * https://dwz.cn/QQ3135 * MT่ฎบๅ›๏ผšbbs.binmt.cc */ private String byte2HexFormatted(byte[] arr) { StringBuilder str = new StringBuilder(arr.length * 2); for (int i = 0; i < arr.length; i++) { String h = Integer.toHexString(arr[i]); int l =h.length(); if (l == 1) h = "0" + h; if (l > 2) h = h.substring(l - 2, l); str.append(h.toUpperCase()); if (i < (arr.length - 1)) str.append(':'); } return str.toString(); } /* * ่Žทๅ–็ฑป */ public List<String > getClassName(String packageName, Context context) { List<String >classNameList=new ArrayList<String >(); try { DexFile df = new DexFile(context.getPackageCodePath());//้€š่ฟ‡DexFileๆŸฅๆ‰พๅฝ“ๅ‰็š„APKไธญๅฏๆ‰ง่กŒๆ–‡ไปถ Enumeration<String> enumeration = df.entries();//่Žทๅ–dfไธญ็š„ๅ…ƒ็ด  ่ฟ™้‡ŒๅŒ…ๅซไบ†ๆ‰€ๆœ‰ๅฏๆ‰ง่กŒ็š„็ฑปๅ ่ฏฅ็ฑปๅๅŒ…ๅซไบ†ๅŒ…ๅ+็ฑปๅ็š„ๆ–นๅผ while (enumeration.hasMoreElements()) {//้ๅކ String className = (String) enumeration.nextElement(); if (className.contains(packageName)) {//ๅœจๅฝ“ๅ‰ๆ‰€ๆœ‰ๅฏๆ‰ง่กŒ็š„็ฑป้‡Œ้ขๆŸฅๆ‰พๅŒ…ๅซๆœ‰่ฏฅๅŒ…ๅ็š„ๆ‰€ๆœ‰็ฑป classNameList.add(className); } } } catch (Exception e) { e.printStackTrace(); } return classNameList; } /* * ๆฃ€ๆŸฅๆ˜ฏๅฆไธบ็ฌฌไธ€ๆฌกไฝฟ็”จ๏ผŒๅ‡ๅฐ‘็ณป็ปŸ่ต„ๆบๆตช่ดน * */ public boolean isNotFirst(String a) { SharedPreferences shared=context.getSharedPreferences(Base64ToString("WHVhblJhbkNoZWNrU2lnblNoYXJlZFBGaWxl"), Context.MODE_PRIVATE); return shared.getBoolean(Base64ToString(a), false); } public void putNotfirst() { SharedPreferences shared=context.getSharedPreferences(Base64ToString("WHVhblJhbkNoZWNrU2lnblNoYXJlZFBGaWxl"), Context.MODE_PRIVATE); SharedPreferences.Editor sharededit=shared.edit(); sharededit.putBoolean(Base64ToString("WHVhblJhbkNoZWNrU2lnblNoYXJlZEJvb2xlYW4="), true); sharededit.commit(); } /** * ๆฃ€ๆต‹็ญพๅๆ˜ฏๅฆๆญฃ็กฎ * @return true ็ญพๅๆญฃๅธธ false ็ญพๅไธๆญฃๅธธ */ public boolean check() { boolean reboln=false; boolean xuanranboolean=isNotFirst("WHVhblJhbkNoZWNrU2lnblNoYXJlZEJvb2xlYW4="); if (reboln) { kill(); } if (this.realCer != null) { cer = cer.trim(); realCer = realCer.trim(); if (this.cer.equals(this.realCer)) { reboln = true; if (!xuanranboolean) { putNotfirst(); } return reboln; } } else { Log.e(Base64ToString("WHVhblJhblJ1blRpbWVFeGNlcHRpb24="), Base64ToString("5pyq57uZ5a6a55yf5a6e55qE562+5ZCNIFNIQS0xIOWAvA==")); } return reboln; }}
8,523
0.608508
0.591492
331
22.081572
24.356541
147
false
false
0
0
0
0
0
0
1.549849
false
false
13
80fc56fe8d973d85bbe29d48cd9e8433bf233880
24,257,975,355,601
322b050f06906c1e53322b95d2b61982719c7156
/src/main/java/de/jos/tselicence/core/interfaces/repositories/ILogRepository.java
391ffc58b01005973a66a2a47724bb8c36e090d0
[]
no_license
fantasy2113/tse-app
https://github.com/fantasy2113/tse-app
1ab191ce280660bfbed5f4b30793847c32cdabc9
97d1ae24fbea4990a17e9500f503bb0bd6e47810
refs/heads/master
2023-04-11T01:44:38.662000
2020-06-14T16:54:19
2020-06-14T16:54:19
243,978,007
0
0
null
false
2021-04-26T20:23:07
2020-02-29T13:55:32
2020-06-14T16:55:23
2021-04-26T20:23:07
272
0
0
1
Java
false
false
package de.jos.tselicence.core.interfaces.repositories; import java.util.List; public interface ILogRepository { List<String> getLogs(); }
UTF-8
Java
145
java
ILogRepository.java
Java
[]
null
[]
package de.jos.tselicence.core.interfaces.repositories; import java.util.List; public interface ILogRepository { List<String> getLogs(); }
145
0.772414
0.772414
7
19.714285
19.299995
55
false
false
0
0
0
0
0
0
0.428571
false
false
13
72ffa79ab5b88d92710d63f3f02663986b401773
32,203,664,847,944
1ed5c16927e98d62a160cf52ef563cd4a45e2122
/Java/com/foretees/communication/.svn/text-base/CommunicationHelper.java.svn-base
b87d9714d64ae39d52f741d48f85d0134326aad6
[]
no_license
uksubs66/java-v2
https://github.com/uksubs66/java-v2
b1517d1866360ffca7356d61bb360233ea479f58
baba766e11ca8bb1930db5cb0d3b645ed9e7250c
refs/heads/master
2021-01-25T08:59:44.495000
2015-07-17T15:37:27
2015-07-17T15:37:27
39,220,401
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*************************************************************************************** * CommunicationHelper: This utility class contains methods to save and retrieve information for gathering * information necessary to create and edit distribution lists * * * created: 1/19/2004 jag * * * last updated: * * 12/10/09 Druid Hills - only allow members to have 12 entries in dist list (case 1754). * * *************************************************************************************** */ package com.foretees.communication; import java.io.*; import java.util.ArrayList; import java.sql.*; import javax.servlet.http.*; import com.foretees.client.action.Action; import com.foretees.client.action.ActionHelper; import com.foretees.client.action.ActionModel; import com.foretees.client.form.FormModel; import com.foretees.client.table.Cell; import com.foretees.client.table.RowModel; import com.foretees.client.table.TableModel; import com.foretees.common.FeedBack; import com.foretees.common.Labels; import com.foretees.common.ProcessConstants; import com.foretees.member.Member; import com.foretees.member.MemberHelper; /** *************************************************************************************** * * This helper class contains methods for commonly used functions related to * creating and editing members. * *************************************************************************************** **/ public class CommunicationHelper { //initialize the attributes private static String versionId = ProcessConstants.CODEBASE; /** *************************************************************************************** * * Validates whether the information provided in the request is valid for creating a new * distribution list. * * @param form that contains the information from the request * *************************************************************************************** **/ public static FeedBack validate(HttpServletRequest req, String theUserName, FormModel form, Connection con, HttpSession session, boolean isNew) { FeedBack feedback = new FeedBack(); //verify that the distribution list name does not already exist for this user String list_name = req.getParameter(DistributionList.LIST_NAME); String user = (String)session.getAttribute("user"); if (list_name == null || list_name.equals("")) { feedback = new FeedBack(); feedback.setPositive(false); feedback.addMessage("You must enter a name for the list. "); feedback.setAffectedField(DistributionList.LIST_NAME); } else { if (isNew) { feedback = DistributionList.listExists(list_name, user, con, session); } } return feedback; } /** *************************************************************************************** * * Adds a new distribution list to the database. The information should be validated * before calling this method. * * @param form that contains the information from the request * *************************************************************************************** **/ public static FeedBack persist(HttpServletRequest req, FormModel form, PrintWriter out, HttpSession session, Connection con) { int i = 0; int max_list_size = DistributionList.getMaxListSize(session); String table_name = DistributionList.getTableName(session); boolean isProshopUser = ProcessConstants.isProshopUser((String)session.getAttribute("user")); //get the table from the form and add the name in the list RowModel row = form.getRow(DistributionList.LIST_OF_NAMES); TableModel names = (TableModel)(((Cell)row.get(0)).getContent()); String[] all_names = new String[max_list_size]; for (i=0; i<max_list_size; i++) { all_names[i] = ""; // init array } for (i=0; i<names.size(); i++) { all_names[i] = (names.getRow(i)).getId(); // put usernames in array } //get the name for the distribution list String list_name = req.getParameter(DistributionList.LIST_NAME); // // get this user's user id // String user = (String)session.getAttribute("user"); // get username ('proshop' or member's username) // save the distribution list try { //build the correct statement using the appropriate database table based on the //type of the user String statement = "INSERT INTO " + table_name + " (name, owner"; for (int j=1; j<=max_list_size; j++) { statement = statement + ", user" + j; } statement = statement + ") VALUES (?,?,"; for (int k=0; k<max_list_size-1; k++) { statement = statement + "?,"; } statement = statement + "?)"; PreparedStatement pstmt = con.prepareStatement (statement); pstmt.clearParameters(); // clear the parms pstmt.setString(1, list_name); // put the parm in pstmt pstmt.setString(2, user); for (i=0; i<max_list_size; i++) { pstmt.setString(i+3, all_names[i]); } pstmt.executeUpdate(); // execute the prepared stmt pstmt.close(); // close the stmt } catch (Exception exc) { exc.printStackTrace(); } return new FeedBack(); } /** *************************************************************************************** * * Updates distribution list in the database. The information should be validated * before calling this method. * * @param form that contains the information from the request * *************************************************************************************** **/ public static FeedBack update(HttpServletRequest req, FormModel form, PrintWriter out, HttpSession session, Connection con) { int i = 0; int max_list_size = DistributionList.getMaxListSize(session); String table_name = DistributionList.getTableName(session); boolean isProshopUser = ProcessConstants.isProshopUser((String)session.getAttribute("user")); //get the table from the form and add the name in the list RowModel row = form.getRow(DistributionList.LIST_OF_NAMES); TableModel names = (TableModel)(((Cell)row.get(0)).getContent()); String[] all_names = new String[max_list_size]; for (i=0; i<max_list_size; i++) { all_names[i] = ""; // init array } for (i=0; i<names.size(); i++) { all_names[i] = (names.getRow(i)).getId(); // put usernames in array } //get the name for the distribution list String list_name = req.getParameter(DistributionList.LIST_NAME); String org_list_name = req.getParameter(DistributionList.ORIGINAL_LIST_NAME); // // get this user's user id // String user = (String)session.getAttribute("user"); // get username ('proshop' or member's username) // save the distribution list try { String statement = "UPDATE " + table_name + " SET name = ?"; for (int j=1; j<=max_list_size; j++) { statement = statement + ", user" + j + " = ?"; } statement = statement + " WHERE name = ? AND owner = ?"; PreparedStatement pstmt = con.prepareStatement (statement); //"UPDATE " + table_name + " SET name = ?, user1 = ?, user2 = ?, user3 = ?, user4 = ?, user5 = ?, user6 = ?, user7 = ?, user8 = ?, user9 = ?, user10 = ?, " + //"user11 = ?, user12 = ?, user13 = ?, user14 = ?, user15 = ?, user16 = ?, user17 = ?, user18 = ?, user19 = ?, user20 = ?, " + //"user21 = ?, user22 = ?, user23 = ?, user24 = ?, user25 = ?, user26 = ?, user27 = ?, user28 = ?, user29 = ?, user30 = ? WHERE name = ? AND owner = ?"); pstmt.clearParameters(); // clear the parms pstmt.setString(1, list_name); // put the parm in pstmt pstmt.setString(max_list_size + 2, org_list_name); pstmt.setString(max_list_size + 3, user); for (i=0; i<max_list_size; i++) { pstmt.setString(i+2, all_names[i]); } pstmt.executeUpdate(); // execute the prepared stmt pstmt.close(); // close the stmt } catch (Exception exc) { } return new FeedBack(); } /** *************************************************************************************** * * Deletes a distribution list in the database. * * @param form that contains the information from the request * *************************************************************************************** **/ public static FeedBack delete(HttpServletRequest req, FormModel form, PrintWriter out, HttpSession session, Connection con) { String list_name = req.getParameter(DistributionList.LIST_NAME); String user = (String)session.getAttribute("user"); boolean isProshopUser = ProcessConstants.isProshopUser(user); String table_name = DistributionList.getTableName(session); try { PreparedStatement stmt = con.prepareStatement ( "Delete FROM " + table_name + " WHERE name = ? AND owner = ?"); stmt.clearParameters(); // clear the parms stmt.setString(1, list_name); // put the parm in stmt stmt.setString(2, user); stmt.executeUpdate(); // execute the prepared stmt stmt.close(); } catch (Exception exc) { } return new FeedBack(); } public static FeedBack addToList(FormModel form, HttpSession session, HttpServletRequest req, HttpServletResponse res, Connection con, PrintWriter out) throws IOException { String items = req.getParameter(ActionHelper.SELECTED_ITEMS_STRING); FeedBack feedback = null; if (items != null && !(items.equals(""))) { ArrayList user_names = ActionHelper.getSelectedNames(items); //get the table from the form and add the name in the list RowModel row = form.getRow(DistributionList.LIST_OF_NAMES); TableModel names = (TableModel)(((Cell)row.get(0)).getContent()); int max = DistributionList.getMaxListSize(session); // get max members allowed in dist list String user = (String)session.getAttribute("user"); // get username ('proshop' or member's username) String club = (String)session.getAttribute("club"); // get club if (club.equals("dhgc") && !user.startsWith("proshop")) { // if Druid Hills and a member max = 12; // max of 12 entries allowed } for (int i=0; i<user_names.size(); i++) { if (names.size() < max) { //check to see if this name is already in the list String name_to_add = (String)(user_names.get(i)); RowModel nameRow = names.getRow(name_to_add); if (nameRow == null) { try { nameRow = new RowModel(); nameRow.setId(name_to_add); String displayName = ""; String search_type = (String)(req.getParameter(ActionHelper.SEARCH_TYPE)); if (search_type.equals(ActionHelper.SEARCH_MEMBERS)) { displayName = MemberHelper.getMemberDisplayName(con, name_to_add, out); } nameRow.add(displayName); ActionModel actions = new ActionModel(); String removeUrl = "javascript:removeNameFromList('" + versionId + "servlet/Edit_distributionlist', '" + ActionHelper.REMOVE_FROM_LIST + "', '" + name_to_add + "')"; Action removeAction = new Action(ActionHelper.REMOVE, Labels.REMOVE, "Remove this member from the list.", removeUrl); actions.add(removeAction); nameRow.add(actions); names.addRow(nameRow); } catch (SQLException sqle) { //what to do } } } else { feedback = new FeedBack(); feedback.setPositive(false); feedback.addMessage("The maximum number of members for a list is " + max + ". Some of the selected members may not have been added."); } } ActionModel model = names.getContextActions(); Action searchAction = (Action)(model.get(0)); if (names.size()<DistributionList.getMaxListSize(session)) { searchAction.setSelected(false); } else { searchAction.setSelected(true); } } return feedback; } public static void removeFromList(FormModel form, HttpSession session, HttpServletRequest req, HttpServletResponse res, Connection con, PrintWriter out) throws IOException { //the user has submitted a name to add to the list String name_to_remove = req.getParameter(Member.REQ_USER_NAME); if (name_to_remove != null && !(name_to_remove.equals(""))) { //get the table from the form and add the name in the list RowModel row = form.getRow(DistributionList.LIST_OF_NAMES); TableModel names = (TableModel)(((Cell)row.get(0)).getContent()); names.remove(name_to_remove); ActionModel model = names.getContextActions(); Action searchAction = (Action)(model.get(0)); if (names.size()<DistributionList.getMaxListSize(session)) { searchAction.setSelected(false); } else { searchAction.setSelected(true); } } } }
UTF-8
Java
13,988
CommunicationHelper.java.svn-base
Java
[ { "context": "tribution lists\r\n *\r\n *\r\n * created: 1/19/2004 jag\r\n *\r\n *\r\n * last updated:\r\n *\r\n * 12/10/09 ", "end": 318, "score": 0.6810060143470764, "start": 315, "tag": "NAME", "value": "jag" }, { "context": "\r\n *\r\n *\r\n * last updated:\r\n *\r\n * 12/10/09 Druid Hills - only allow members to have 12 entries in dist l", "end": 380, "score": 0.9970707297325134, "start": 369, "tag": "NAME", "value": "Druid Hills" }, { "context": "ssion.getAttribute(\"user\"); // get username ('proshop' or member's username)\r\n\r\n // save the distrib", "end": 4432, "score": 0.9984140396118164, "start": 4425, "tag": "USERNAME", "value": "proshop" }, { "context": "ssion.getAttribute(\"user\"); // get username ('proshop' or member's username)\r\n\r\n // save the distrib", "end": 7188, "score": 0.9991412162780762, "start": 7181, "tag": "USERNAME", "value": "proshop" }, { "context": "ssion.getAttribute(\"user\"); // get username ('proshop' or member's username)\r\n String club = (Stri", "end": 10676, "score": 0.9758228063583374, "start": 10669, "tag": "USERNAME", "value": "proshop" }, { "context": " if (club.equals(\"dhgc\") && !user.startsWith(\"proshop\")) { // if Druid Hills and a member\r\n ", "end": 10832, "score": 0.5355770587921143, "start": 10829, "tag": "USERNAME", "value": "pro" } ]
null
[]
/*************************************************************************************** * CommunicationHelper: This utility class contains methods to save and retrieve information for gathering * information necessary to create and edit distribution lists * * * created: 1/19/2004 jag * * * last updated: * * 12/10/09 <NAME> - only allow members to have 12 entries in dist list (case 1754). * * *************************************************************************************** */ package com.foretees.communication; import java.io.*; import java.util.ArrayList; import java.sql.*; import javax.servlet.http.*; import com.foretees.client.action.Action; import com.foretees.client.action.ActionHelper; import com.foretees.client.action.ActionModel; import com.foretees.client.form.FormModel; import com.foretees.client.table.Cell; import com.foretees.client.table.RowModel; import com.foretees.client.table.TableModel; import com.foretees.common.FeedBack; import com.foretees.common.Labels; import com.foretees.common.ProcessConstants; import com.foretees.member.Member; import com.foretees.member.MemberHelper; /** *************************************************************************************** * * This helper class contains methods for commonly used functions related to * creating and editing members. * *************************************************************************************** **/ public class CommunicationHelper { //initialize the attributes private static String versionId = ProcessConstants.CODEBASE; /** *************************************************************************************** * * Validates whether the information provided in the request is valid for creating a new * distribution list. * * @param form that contains the information from the request * *************************************************************************************** **/ public static FeedBack validate(HttpServletRequest req, String theUserName, FormModel form, Connection con, HttpSession session, boolean isNew) { FeedBack feedback = new FeedBack(); //verify that the distribution list name does not already exist for this user String list_name = req.getParameter(DistributionList.LIST_NAME); String user = (String)session.getAttribute("user"); if (list_name == null || list_name.equals("")) { feedback = new FeedBack(); feedback.setPositive(false); feedback.addMessage("You must enter a name for the list. "); feedback.setAffectedField(DistributionList.LIST_NAME); } else { if (isNew) { feedback = DistributionList.listExists(list_name, user, con, session); } } return feedback; } /** *************************************************************************************** * * Adds a new distribution list to the database. The information should be validated * before calling this method. * * @param form that contains the information from the request * *************************************************************************************** **/ public static FeedBack persist(HttpServletRequest req, FormModel form, PrintWriter out, HttpSession session, Connection con) { int i = 0; int max_list_size = DistributionList.getMaxListSize(session); String table_name = DistributionList.getTableName(session); boolean isProshopUser = ProcessConstants.isProshopUser((String)session.getAttribute("user")); //get the table from the form and add the name in the list RowModel row = form.getRow(DistributionList.LIST_OF_NAMES); TableModel names = (TableModel)(((Cell)row.get(0)).getContent()); String[] all_names = new String[max_list_size]; for (i=0; i<max_list_size; i++) { all_names[i] = ""; // init array } for (i=0; i<names.size(); i++) { all_names[i] = (names.getRow(i)).getId(); // put usernames in array } //get the name for the distribution list String list_name = req.getParameter(DistributionList.LIST_NAME); // // get this user's user id // String user = (String)session.getAttribute("user"); // get username ('proshop' or member's username) // save the distribution list try { //build the correct statement using the appropriate database table based on the //type of the user String statement = "INSERT INTO " + table_name + " (name, owner"; for (int j=1; j<=max_list_size; j++) { statement = statement + ", user" + j; } statement = statement + ") VALUES (?,?,"; for (int k=0; k<max_list_size-1; k++) { statement = statement + "?,"; } statement = statement + "?)"; PreparedStatement pstmt = con.prepareStatement (statement); pstmt.clearParameters(); // clear the parms pstmt.setString(1, list_name); // put the parm in pstmt pstmt.setString(2, user); for (i=0; i<max_list_size; i++) { pstmt.setString(i+3, all_names[i]); } pstmt.executeUpdate(); // execute the prepared stmt pstmt.close(); // close the stmt } catch (Exception exc) { exc.printStackTrace(); } return new FeedBack(); } /** *************************************************************************************** * * Updates distribution list in the database. The information should be validated * before calling this method. * * @param form that contains the information from the request * *************************************************************************************** **/ public static FeedBack update(HttpServletRequest req, FormModel form, PrintWriter out, HttpSession session, Connection con) { int i = 0; int max_list_size = DistributionList.getMaxListSize(session); String table_name = DistributionList.getTableName(session); boolean isProshopUser = ProcessConstants.isProshopUser((String)session.getAttribute("user")); //get the table from the form and add the name in the list RowModel row = form.getRow(DistributionList.LIST_OF_NAMES); TableModel names = (TableModel)(((Cell)row.get(0)).getContent()); String[] all_names = new String[max_list_size]; for (i=0; i<max_list_size; i++) { all_names[i] = ""; // init array } for (i=0; i<names.size(); i++) { all_names[i] = (names.getRow(i)).getId(); // put usernames in array } //get the name for the distribution list String list_name = req.getParameter(DistributionList.LIST_NAME); String org_list_name = req.getParameter(DistributionList.ORIGINAL_LIST_NAME); // // get this user's user id // String user = (String)session.getAttribute("user"); // get username ('proshop' or member's username) // save the distribution list try { String statement = "UPDATE " + table_name + " SET name = ?"; for (int j=1; j<=max_list_size; j++) { statement = statement + ", user" + j + " = ?"; } statement = statement + " WHERE name = ? AND owner = ?"; PreparedStatement pstmt = con.prepareStatement (statement); //"UPDATE " + table_name + " SET name = ?, user1 = ?, user2 = ?, user3 = ?, user4 = ?, user5 = ?, user6 = ?, user7 = ?, user8 = ?, user9 = ?, user10 = ?, " + //"user11 = ?, user12 = ?, user13 = ?, user14 = ?, user15 = ?, user16 = ?, user17 = ?, user18 = ?, user19 = ?, user20 = ?, " + //"user21 = ?, user22 = ?, user23 = ?, user24 = ?, user25 = ?, user26 = ?, user27 = ?, user28 = ?, user29 = ?, user30 = ? WHERE name = ? AND owner = ?"); pstmt.clearParameters(); // clear the parms pstmt.setString(1, list_name); // put the parm in pstmt pstmt.setString(max_list_size + 2, org_list_name); pstmt.setString(max_list_size + 3, user); for (i=0; i<max_list_size; i++) { pstmt.setString(i+2, all_names[i]); } pstmt.executeUpdate(); // execute the prepared stmt pstmt.close(); // close the stmt } catch (Exception exc) { } return new FeedBack(); } /** *************************************************************************************** * * Deletes a distribution list in the database. * * @param form that contains the information from the request * *************************************************************************************** **/ public static FeedBack delete(HttpServletRequest req, FormModel form, PrintWriter out, HttpSession session, Connection con) { String list_name = req.getParameter(DistributionList.LIST_NAME); String user = (String)session.getAttribute("user"); boolean isProshopUser = ProcessConstants.isProshopUser(user); String table_name = DistributionList.getTableName(session); try { PreparedStatement stmt = con.prepareStatement ( "Delete FROM " + table_name + " WHERE name = ? AND owner = ?"); stmt.clearParameters(); // clear the parms stmt.setString(1, list_name); // put the parm in stmt stmt.setString(2, user); stmt.executeUpdate(); // execute the prepared stmt stmt.close(); } catch (Exception exc) { } return new FeedBack(); } public static FeedBack addToList(FormModel form, HttpSession session, HttpServletRequest req, HttpServletResponse res, Connection con, PrintWriter out) throws IOException { String items = req.getParameter(ActionHelper.SELECTED_ITEMS_STRING); FeedBack feedback = null; if (items != null && !(items.equals(""))) { ArrayList user_names = ActionHelper.getSelectedNames(items); //get the table from the form and add the name in the list RowModel row = form.getRow(DistributionList.LIST_OF_NAMES); TableModel names = (TableModel)(((Cell)row.get(0)).getContent()); int max = DistributionList.getMaxListSize(session); // get max members allowed in dist list String user = (String)session.getAttribute("user"); // get username ('proshop' or member's username) String club = (String)session.getAttribute("club"); // get club if (club.equals("dhgc") && !user.startsWith("proshop")) { // if Druid Hills and a member max = 12; // max of 12 entries allowed } for (int i=0; i<user_names.size(); i++) { if (names.size() < max) { //check to see if this name is already in the list String name_to_add = (String)(user_names.get(i)); RowModel nameRow = names.getRow(name_to_add); if (nameRow == null) { try { nameRow = new RowModel(); nameRow.setId(name_to_add); String displayName = ""; String search_type = (String)(req.getParameter(ActionHelper.SEARCH_TYPE)); if (search_type.equals(ActionHelper.SEARCH_MEMBERS)) { displayName = MemberHelper.getMemberDisplayName(con, name_to_add, out); } nameRow.add(displayName); ActionModel actions = new ActionModel(); String removeUrl = "javascript:removeNameFromList('" + versionId + "servlet/Edit_distributionlist', '" + ActionHelper.REMOVE_FROM_LIST + "', '" + name_to_add + "')"; Action removeAction = new Action(ActionHelper.REMOVE, Labels.REMOVE, "Remove this member from the list.", removeUrl); actions.add(removeAction); nameRow.add(actions); names.addRow(nameRow); } catch (SQLException sqle) { //what to do } } } else { feedback = new FeedBack(); feedback.setPositive(false); feedback.addMessage("The maximum number of members for a list is " + max + ". Some of the selected members may not have been added."); } } ActionModel model = names.getContextActions(); Action searchAction = (Action)(model.get(0)); if (names.size()<DistributionList.getMaxListSize(session)) { searchAction.setSelected(false); } else { searchAction.setSelected(true); } } return feedback; } public static void removeFromList(FormModel form, HttpSession session, HttpServletRequest req, HttpServletResponse res, Connection con, PrintWriter out) throws IOException { //the user has submitted a name to add to the list String name_to_remove = req.getParameter(Member.REQ_USER_NAME); if (name_to_remove != null && !(name_to_remove.equals(""))) { //get the table from the form and add the name in the list RowModel row = form.getRow(DistributionList.LIST_OF_NAMES); TableModel names = (TableModel)(((Cell)row.get(0)).getContent()); names.remove(name_to_remove); ActionModel model = names.getContextActions(); Action searchAction = (Action)(model.get(0)); if (names.size()<DistributionList.getMaxListSize(session)) { searchAction.setSelected(false); } else { searchAction.setSelected(true); } } } }
13,983
0.552116
0.544824
425
30.912941
35.360455
179
false
false
0
0
0
0
0
0
0.543529
false
false
13
a304677a52cf42b8630e32dc104582854dd9de02
3,092,376,456,174
dc64c577f75050afed22c789b48cb3268978a407
/A2OJ/src/ladder/less1300/LittleElephantAndRozdil129A.java
4dc3b757eb918359c2bb5e418a7966befb063e72
[]
no_license
adiptabasu/A2OJ-Codes
https://github.com/adiptabasu/A2OJ-Codes
38c4c0bedd4eb3f27370ab1ed3c38c5131e57062
a5c123bbe245cba96396aaa70c8c88cd7c3ba8f0
refs/heads/main
2023-06-24T04:28:38.364000
2021-07-29T19:42:05
2021-07-29T19:42:05
384,558,145
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ladder.less1300; import java.util.Scanner; public class LittleElephantAndRozdil129A { public static void main(String[] args) { Scanner sc=new Scanner(System.in); long n=sc.nextLong(); boolean isDouble=false; long value=Long.MAX_VALUE,pos=0; for(long i=0;i<n;i++) { long temp=sc.nextLong(); if(temp<value) { value=temp; pos=i; isDouble=false; } else if(temp==value) { isDouble=true; } } if(isDouble) { System.out.println("Still Rozdil"); } else { System.out.println(pos+1); } sc.close(); } }
UTF-8
Java
576
java
LittleElephantAndRozdil129A.java
Java
[]
null
[]
package ladder.less1300; import java.util.Scanner; public class LittleElephantAndRozdil129A { public static void main(String[] args) { Scanner sc=new Scanner(System.in); long n=sc.nextLong(); boolean isDouble=false; long value=Long.MAX_VALUE,pos=0; for(long i=0;i<n;i++) { long temp=sc.nextLong(); if(temp<value) { value=temp; pos=i; isDouble=false; } else if(temp==value) { isDouble=true; } } if(isDouble) { System.out.println("Still Rozdil"); } else { System.out.println(pos+1); } sc.close(); } }
576
0.623264
0.605903
37
14.594595
12.847251
41
false
false
0
0
0
0
0
0
2.45946
false
false
13
d4356a46e0b990efd59e2ed057a498cf515af2dd
25,855,703,122,121
8d4bb09f8c18e2521bc195f7e95a144a0ccb21e3
/Intersection of Two Linked Lists/src/Node.java
58fa1e875d1315cdc379ebf5f70cb2eb9abb5e2d
[]
no_license
mjolewis/Leet-Code
https://github.com/mjolewis/Leet-Code
e6d84af2b27aa0647395045c80b654a0f539de68
a08912311ba3e56520c680143590480b569a059d
refs/heads/master
2020-07-04T08:45:08.569000
2019-09-12T14:10:01
2019-09-12T14:10:01
202,227,215
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Author: Michael Lewis Date: 9/9/19 */ import java.util.*; /** * Write a program to find the node at which the intersection of two singly linked lists begins. * Notes: If the two linked lists have no intersection at all, return null. The linked lists must retain their original * structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. * Your code should preferably run in O(n) time and use only O(1) memory. */ public class Node { private int data; private Node next; public Node(int data) { this.data = data; this.next = null; } public Node() {} // Default constructor public Node getIntersectionNode(Node headA, Node headB) { Set<Node> nodes = new HashSet<>(); Node currentNodeA = headA; while (currentNodeA != null) { nodes.add(currentNodeA); currentNodeA = currentNodeA.next; } if (nodes.isEmpty()) return null; Node currentNodeB = headB; while (currentNodeB != null) { if (nodes.contains(currentNodeB)) { return currentNodeB; } else { currentNodeB = currentNodeB.next; } } return null; } /** * Construct two Linked Lists and intersect the lists at the nth node * @param args */ public static void main(String[] args) { Node headA = new Node(4); Node nodeA1 = new Node(1); Node nodeA2 = new Node(8); Node nodeA3 = new Node(4); Node nodeA4 = new Node(5); Node headB = new Node(5); Node nodeB1 = new Node(0); Node nodeB2 = new Node(1); Node nodeB3 = new Node(8); Node nodeB4 = new Node(4); Node nodeB5 = new Node(5); headA.next = nodeA1; nodeA1.next = nodeA2; nodeA2.next = nodeA3; nodeA3.next = nodeA4; headB.next = nodeB1; nodeB1.next = nodeB2; nodeB2.next = nodeB3; nodeB3.next = nodeB4; nodeB4.next = nodeB5; headA.getIntersectionNode(headA, headB); } }
UTF-8
Java
2,144
java
Node.java
Java
[ { "context": "/*\nAuthor: Michael Lewis\nDate: 9/9/19\n */\n\nimport java.util.*;\n\n/**\n * Wri", "end": 24, "score": 0.9998525381088257, "start": 11, "tag": "NAME", "value": "Michael Lewis" } ]
null
[]
/* Author: <NAME> Date: 9/9/19 */ import java.util.*; /** * Write a program to find the node at which the intersection of two singly linked lists begins. * Notes: If the two linked lists have no intersection at all, return null. The linked lists must retain their original * structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. * Your code should preferably run in O(n) time and use only O(1) memory. */ public class Node { private int data; private Node next; public Node(int data) { this.data = data; this.next = null; } public Node() {} // Default constructor public Node getIntersectionNode(Node headA, Node headB) { Set<Node> nodes = new HashSet<>(); Node currentNodeA = headA; while (currentNodeA != null) { nodes.add(currentNodeA); currentNodeA = currentNodeA.next; } if (nodes.isEmpty()) return null; Node currentNodeB = headB; while (currentNodeB != null) { if (nodes.contains(currentNodeB)) { return currentNodeB; } else { currentNodeB = currentNodeB.next; } } return null; } /** * Construct two Linked Lists and intersect the lists at the nth node * @param args */ public static void main(String[] args) { Node headA = new Node(4); Node nodeA1 = new Node(1); Node nodeA2 = new Node(8); Node nodeA3 = new Node(4); Node nodeA4 = new Node(5); Node headB = new Node(5); Node nodeB1 = new Node(0); Node nodeB2 = new Node(1); Node nodeB3 = new Node(8); Node nodeB4 = new Node(4); Node nodeB5 = new Node(5); headA.next = nodeA1; nodeA1.next = nodeA2; nodeA2.next = nodeA3; nodeA3.next = nodeA4; headB.next = nodeB1; nodeB1.next = nodeB2; nodeB2.next = nodeB3; nodeB3.next = nodeB4; nodeB4.next = nodeB5; headA.getIntersectionNode(headA, headB); } }
2,137
0.58209
0.562966
78
26.487179
24.401945
119
false
false
0
0
0
0
0
0
0.487179
false
false
13
5416214c4a640a91681e1dcf7d9a2c5bcf521cfc
27,650,999,518,383
4207ae07ea686846a4805ce6137f30e233139674
/QAPORTALRest/src/main/java/com/alacriti/qaportal/resource/SearchResource.java
ae9eb23024354659b935b3aa1285d50549666af6
[]
no_license
mounikadacharla/qaportal
https://github.com/mounikadacharla/qaportal
c46a33af3115575c56766b6175111d7f907e741b
f0c60caf8149d5fe81c2187888dff464c6076dc2
refs/heads/master
2021-01-15T10:30:08.994000
2017-09-11T09:17:09
2017-09-22T07:31:46
99,583,717
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.alacriti.qaportal.resource; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; import com.alacriti.qaportal.bz.delegate.SearchDelegate; import com.alacriti.qaportal.model.vo.QuestionsModel; @Path("/") public class SearchResource { public static final Logger log= Logger.getLogger(SearchResource.class); @POST @Path("/search") @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.APPLICATION_JSON) public List<QuestionsModel> searchingForQuestions(String wordSearchingFor) { log.debug("SearchResource====>searchingForQuestions"); SearchDelegate searchDelegate = new SearchDelegate(); return searchDelegate.searchingForQuestions(wordSearchingFor); } }
UTF-8
Java
828
java
SearchResource.java
Java
[]
null
[]
package com.alacriti.qaportal.resource; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; import com.alacriti.qaportal.bz.delegate.SearchDelegate; import com.alacriti.qaportal.model.vo.QuestionsModel; @Path("/") public class SearchResource { public static final Logger log= Logger.getLogger(SearchResource.class); @POST @Path("/search") @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.APPLICATION_JSON) public List<QuestionsModel> searchingForQuestions(String wordSearchingFor) { log.debug("SearchResource====>searchingForQuestions"); SearchDelegate searchDelegate = new SearchDelegate(); return searchDelegate.searchingForQuestions(wordSearchingFor); } }
828
0.794686
0.793478
30
26.6
23.572018
77
false
false
0
0
0
0
0
0
0.9
false
false
13
321b491fe7d66ffe18aa1966f69e19932fd7d477
4,131,758,596,058
ba629834b7df4ddf2ca6667c5fefb91744ae914e
/.svn/pristine/a6/a6e58fc8abcaf33515cc67dae6854181c4bf227b.svn-base
171ed816e1451684bcb48ebdce757481d6d4bd28
[ "MIT" ]
permissive
skylergarrison/maze-game
https://github.com/skylergarrison/maze-game
68102d4b77afebb1ed39495fca65765a1561b936
2ac32804a979bac8f60463ff89c6f33d46d6a780
refs/heads/master
2020-03-26T18:04:22.219000
2018-08-24T04:19:01
2018-08-24T04:19:01
145,194,774
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package falstad; /** * This class provides an API for manual and automatic driving algorithms to allow for the navigation of a maze * as built by any of the Falstad MazeBuilders. Has a zero argument default constructor, a field for battery power, * a field for if the robot is out of power, and fields for if it has various sensors. The BasicRobot supports all * Robot functions: turning, moving, seeing the goal, seeing the distance to next obstacle, etc. * * This code implements the Robot interface by Peter Kemper. * @author William S. Garrison */ public class BasicRobot implements Robot { //instantiate necessary fields for battery and various sensors Maze maze; private float battery = 2500; private boolean isStopped = false; boolean rightSensor = true; boolean downSensor = true; boolean leftSensor = true; boolean upSensor = true; boolean roomSensor = true; @Override public void rotate(Turn turn) throws Exception { //rotate the robot in the maze: 1 for right, -1 for left, and 1 two times for turning around. //adjust battery accordingly try{ switch(turn){ case LEFT: maze.rotate(1); battery = battery - 3; break; case RIGHT: maze.rotate(-1); battery = battery - 3; break; case AROUND: maze.rotate(1); maze.rotate(1); battery = battery - 6; break; } } catch(Exception e){ } //always check for battery level after draining operations //if done, call the maze to finish by the batteryfinish method if(battery<=0){ isStopped = true; maze.batteryFinish(); } } @Override public void move(int distance) throws Exception { int count = 0; //walk forward as many steps as the passed integer requires try{ while(count<distance){ maze.walk(1); battery = battery - 5; count += 1; } } catch(Exception e){ } //always check for battery level after draining operations //if done, call the maze to finish by the batteryfinish method if(battery<=0){ isStopped = true; maze.batteryFinish(); } } @Override public int[] getCurrentPosition() throws Exception { //gets the current position from the maze in the form of an {x,y} two cell array try{ return maze.getCurrentPosition(); } catch(Exception e){ return null; } } @Override public void setMaze(Maze maze) { //sets the essential maze for the robot this.maze = maze; } @Override public boolean isAtGoal() { //checks if the robot is at its goal return maze.isMazeExit(); } @Override public boolean canSeeGoal(Direction direction) throws UnsupportedOperationException { //checks if the robot can see the goal square //always returns true if the robot is on its goal square boolean returnBool; if(this.distanceToObstacle(direction)==Integer.MAX_VALUE || maze.isMazeExit()){ returnBool = true; } else{ returnBool = false; } return returnBool; } @Override public boolean isInsideRoom() throws UnsupportedOperationException { //senses if the robot is in a room or not //if the bot has no room sensor, throw exception if(this.roomSensor==false){ throw new UnsupportedOperationException(); } return maze.isInRoom(); } @Override public boolean hasRoomSensor() { //checks if the robot has a room sensor return this.roomSensor; } @Override public int[] getCurrentDirection() { //gets the current direction of the robot as a 2 cell array of {dx,dy} format return maze.getCurrentDirection(); } @Override public float getBatteryLevel() { //returns the float of the battery level at the current time return battery; } @Override public void setBatteryLevel(float level) { //sets the battery level with float input from the user battery = level; if(battery==0){ this.isStopped=true; } } @Override public float getEnergyForFullRotation() { //returns the energy for a 360degree rotation from this robot return 12; } @Override public float getEnergyForStepForward() { //returns the energy for a step forward from this robot return 5; } @Override public boolean hasStopped() { //returns if the robot is stopped or not as a boolean return isStopped; } @Override public int distanceToObstacle(Direction direction) throws UnsupportedOperationException { int returnDistance = 0; //relative to the robot's current direction, calls on the maze to calculate the distance to the //nearest obstacle, and returns it as an integer. // //if the robot does not have this sensor, throws exception try{ switch(direction){ case FORWARD: if(this.upSensor==false){ throw new UnsupportedOperationException(); } returnDistance = maze.wallDistance(0); battery = battery - 1; break; case RIGHT: if(this.rightSensor==false){ throw new UnsupportedOperationException(); } returnDistance = maze.wallDistance(1); battery = battery - 1; break; case BACKWARD: if(this.downSensor==false){ throw new UnsupportedOperationException(); } returnDistance = maze.wallDistance(2); battery = battery - 1; break; case LEFT: if(this.leftSensor==false){ throw new UnsupportedOperationException(); } returnDistance = maze.wallDistance(3); battery = battery - 1; break; default: break; } } catch(UnsupportedOperationException e){ System.out.println("UnsupportedOperationException"); } //always check for battery level after draining operations //if done, call the maze to finish by the batteryfinish method if(battery<0){ isStopped = true; maze.batteryFinish(); } return returnDistance; } @Override public boolean hasDistanceSensor(Direction direction) { boolean returnBool = false; //returns true if the robot has the requested sensor switch(direction){ case FORWARD: returnBool = this.upSensor; break; case RIGHT: returnBool = this.rightSensor; break; case BACKWARD: returnBool = this.downSensor; break; case LEFT: returnBool = this.leftSensor; break; } return returnBool; } /** * Test method to set the robot to not have any sensors. */ public void setAllFalse(){ rightSensor = false; downSensor = false; leftSensor = false; upSensor = false; roomSensor = false; } }
UTF-8
Java
6,337
a6e58fc8abcaf33515cc67dae6854181c4bf227b.svn-base
Java
[ { "context": " * \n * This code implements the Robot interface by Peter Kemper.\n * @author William S. Garrison\n */\npublic class ", "end": 525, "score": 0.9998175501823425, "start": 513, "tag": "NAME", "value": "Peter Kemper" }, { "context": "ts the Robot interface by Peter Kemper.\n * @author William S. Garrison\n */\npublic class BasicRobot implements Robot {\n\t/", "end": 557, "score": 0.99988853931427, "start": 538, "tag": "NAME", "value": "William S. Garrison" } ]
null
[]
package falstad; /** * This class provides an API for manual and automatic driving algorithms to allow for the navigation of a maze * as built by any of the Falstad MazeBuilders. Has a zero argument default constructor, a field for battery power, * a field for if the robot is out of power, and fields for if it has various sensors. The BasicRobot supports all * Robot functions: turning, moving, seeing the goal, seeing the distance to next obstacle, etc. * * This code implements the Robot interface by <NAME>. * @author <NAME> */ public class BasicRobot implements Robot { //instantiate necessary fields for battery and various sensors Maze maze; private float battery = 2500; private boolean isStopped = false; boolean rightSensor = true; boolean downSensor = true; boolean leftSensor = true; boolean upSensor = true; boolean roomSensor = true; @Override public void rotate(Turn turn) throws Exception { //rotate the robot in the maze: 1 for right, -1 for left, and 1 two times for turning around. //adjust battery accordingly try{ switch(turn){ case LEFT: maze.rotate(1); battery = battery - 3; break; case RIGHT: maze.rotate(-1); battery = battery - 3; break; case AROUND: maze.rotate(1); maze.rotate(1); battery = battery - 6; break; } } catch(Exception e){ } //always check for battery level after draining operations //if done, call the maze to finish by the batteryfinish method if(battery<=0){ isStopped = true; maze.batteryFinish(); } } @Override public void move(int distance) throws Exception { int count = 0; //walk forward as many steps as the passed integer requires try{ while(count<distance){ maze.walk(1); battery = battery - 5; count += 1; } } catch(Exception e){ } //always check for battery level after draining operations //if done, call the maze to finish by the batteryfinish method if(battery<=0){ isStopped = true; maze.batteryFinish(); } } @Override public int[] getCurrentPosition() throws Exception { //gets the current position from the maze in the form of an {x,y} two cell array try{ return maze.getCurrentPosition(); } catch(Exception e){ return null; } } @Override public void setMaze(Maze maze) { //sets the essential maze for the robot this.maze = maze; } @Override public boolean isAtGoal() { //checks if the robot is at its goal return maze.isMazeExit(); } @Override public boolean canSeeGoal(Direction direction) throws UnsupportedOperationException { //checks if the robot can see the goal square //always returns true if the robot is on its goal square boolean returnBool; if(this.distanceToObstacle(direction)==Integer.MAX_VALUE || maze.isMazeExit()){ returnBool = true; } else{ returnBool = false; } return returnBool; } @Override public boolean isInsideRoom() throws UnsupportedOperationException { //senses if the robot is in a room or not //if the bot has no room sensor, throw exception if(this.roomSensor==false){ throw new UnsupportedOperationException(); } return maze.isInRoom(); } @Override public boolean hasRoomSensor() { //checks if the robot has a room sensor return this.roomSensor; } @Override public int[] getCurrentDirection() { //gets the current direction of the robot as a 2 cell array of {dx,dy} format return maze.getCurrentDirection(); } @Override public float getBatteryLevel() { //returns the float of the battery level at the current time return battery; } @Override public void setBatteryLevel(float level) { //sets the battery level with float input from the user battery = level; if(battery==0){ this.isStopped=true; } } @Override public float getEnergyForFullRotation() { //returns the energy for a 360degree rotation from this robot return 12; } @Override public float getEnergyForStepForward() { //returns the energy for a step forward from this robot return 5; } @Override public boolean hasStopped() { //returns if the robot is stopped or not as a boolean return isStopped; } @Override public int distanceToObstacle(Direction direction) throws UnsupportedOperationException { int returnDistance = 0; //relative to the robot's current direction, calls on the maze to calculate the distance to the //nearest obstacle, and returns it as an integer. // //if the robot does not have this sensor, throws exception try{ switch(direction){ case FORWARD: if(this.upSensor==false){ throw new UnsupportedOperationException(); } returnDistance = maze.wallDistance(0); battery = battery - 1; break; case RIGHT: if(this.rightSensor==false){ throw new UnsupportedOperationException(); } returnDistance = maze.wallDistance(1); battery = battery - 1; break; case BACKWARD: if(this.downSensor==false){ throw new UnsupportedOperationException(); } returnDistance = maze.wallDistance(2); battery = battery - 1; break; case LEFT: if(this.leftSensor==false){ throw new UnsupportedOperationException(); } returnDistance = maze.wallDistance(3); battery = battery - 1; break; default: break; } } catch(UnsupportedOperationException e){ System.out.println("UnsupportedOperationException"); } //always check for battery level after draining operations //if done, call the maze to finish by the batteryfinish method if(battery<0){ isStopped = true; maze.batteryFinish(); } return returnDistance; } @Override public boolean hasDistanceSensor(Direction direction) { boolean returnBool = false; //returns true if the robot has the requested sensor switch(direction){ case FORWARD: returnBool = this.upSensor; break; case RIGHT: returnBool = this.rightSensor; break; case BACKWARD: returnBool = this.downSensor; break; case LEFT: returnBool = this.leftSensor; break; } return returnBool; } /** * Test method to set the robot to not have any sensors. */ public void setAllFalse(){ rightSensor = false; downSensor = false; leftSensor = false; upSensor = false; roomSensor = false; } }
6,318
0.695124
0.689127
273
22.212454
23.294395
115
false
false
0
0
0
0
0
0
2.340659
false
false
13
bb6280b523c178e2e706e52f0f9c6b8d21a9f1b0
22,789,096,532,822
3cffb22c459d96825eabf42b78bed81015b8935d
/e-proc-ws/src/main/java/com/oracle/xmlns/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria/ObjectFactory.java
6cabe5b2283612d14bd8848c3481f522e5424cdd
[]
no_license
rezaact/eproc
https://github.com/rezaact/eproc
d39e7c34ecccabb1a9b83c7d5a518e91d27cb407
f43f1984420ca2550ffee418a410d0ff63190bc2
refs/heads/master
2021-01-11T01:35:07.641000
2015-11-01T15:28:32
2015-11-01T15:28:32
44,674,756
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.oracle.xmlns.pcbpel.adapter.db.sp.pkg_master_upd_ref_kriteria; import java.math.BigDecimal; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.oracle.xmlns.pcbpel.adapter.db.sp.pkg_master_upd_ref_kriteria package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _OPUpdRefKriteriaMSGERROR_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "MSGERROR"); private final static QName _OPUpdRefKriteriaOUTROWCOUNT_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "OUT_ROWCOUNT"); private final static QName _IPUpdRefKriteriaPUPDATEBY_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_UPDATE_BY"); private final static QName _IPUpdRefKriteriaPKATEGORIKRITERIA_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_KATEGORI_KRITERIA"); private final static QName _IPUpdRefKriteriaPIDKRITERIA_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_ID_KRITERIA"); private final static QName _IPUpdRefKriteriaPNAMA_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_NAMA"); private final static QName _IPUpdRefKriteriaPKETERANGAN_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_KETERANGAN"); private final static QName _IPUpdRefKriteriaPFLAGTAMPIL_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_FLAG_TAMPIL"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.oracle.xmlns.pcbpel.adapter.db.sp.pkg_master_upd_ref_kriteria * */ public ObjectFactory() { } /** * Create an instance of {@link IPUpdRefKriteria } * */ public IPUpdRefKriteria createIPUpdRefKriteria() { return new IPUpdRefKriteria(); } /** * Create an instance of {@link OPUpdRefKriteria } * */ public OPUpdRefKriteria createOPUpdRefKriteria() { return new OPUpdRefKriteria(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "MSGERROR", scope = OPUpdRefKriteria.class) public JAXBElement<String> createOPUpdRefKriteriaMSGERROR(String value) { return new JAXBElement<String>(_OPUpdRefKriteriaMSGERROR_QNAME, String.class, OPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "OUT_ROWCOUNT", scope = OPUpdRefKriteria.class) public JAXBElement<BigDecimal> createOPUpdRefKriteriaOUTROWCOUNT(BigDecimal value) { return new JAXBElement<BigDecimal>(_OPUpdRefKriteriaOUTROWCOUNT_QNAME, BigDecimal.class, OPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_UPDATE_BY", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPUPDATEBY(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPUPDATEBY_QNAME, String.class, IPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_KATEGORI_KRITERIA", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPKATEGORIKRITERIA(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPKATEGORIKRITERIA_QNAME, String.class, IPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_ID_KRITERIA", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPIDKRITERIA(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPIDKRITERIA_QNAME, String.class, IPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_NAMA", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPNAMA(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPNAMA_QNAME, String.class, IPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_KETERANGAN", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPKETERANGAN(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPKETERANGAN_QNAME, String.class, IPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_FLAG_TAMPIL", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPFLAGTAMPIL(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPFLAGTAMPIL_QNAME, String.class, IPUpdRefKriteria.class, value); } }
UTF-8
Java
6,735
java
ObjectFactory.java
Java
[]
null
[]
package com.oracle.xmlns.pcbpel.adapter.db.sp.pkg_master_upd_ref_kriteria; import java.math.BigDecimal; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.oracle.xmlns.pcbpel.adapter.db.sp.pkg_master_upd_ref_kriteria package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _OPUpdRefKriteriaMSGERROR_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "MSGERROR"); private final static QName _OPUpdRefKriteriaOUTROWCOUNT_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "OUT_ROWCOUNT"); private final static QName _IPUpdRefKriteriaPUPDATEBY_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_UPDATE_BY"); private final static QName _IPUpdRefKriteriaPKATEGORIKRITERIA_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_KATEGORI_KRITERIA"); private final static QName _IPUpdRefKriteriaPIDKRITERIA_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_ID_KRITERIA"); private final static QName _IPUpdRefKriteriaPNAMA_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_NAMA"); private final static QName _IPUpdRefKriteriaPKETERANGAN_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_KETERANGAN"); private final static QName _IPUpdRefKriteriaPFLAGTAMPIL_QNAME = new QName("http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", "P_FLAG_TAMPIL"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.oracle.xmlns.pcbpel.adapter.db.sp.pkg_master_upd_ref_kriteria * */ public ObjectFactory() { } /** * Create an instance of {@link IPUpdRefKriteria } * */ public IPUpdRefKriteria createIPUpdRefKriteria() { return new IPUpdRefKriteria(); } /** * Create an instance of {@link OPUpdRefKriteria } * */ public OPUpdRefKriteria createOPUpdRefKriteria() { return new OPUpdRefKriteria(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "MSGERROR", scope = OPUpdRefKriteria.class) public JAXBElement<String> createOPUpdRefKriteriaMSGERROR(String value) { return new JAXBElement<String>(_OPUpdRefKriteriaMSGERROR_QNAME, String.class, OPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "OUT_ROWCOUNT", scope = OPUpdRefKriteria.class) public JAXBElement<BigDecimal> createOPUpdRefKriteriaOUTROWCOUNT(BigDecimal value) { return new JAXBElement<BigDecimal>(_OPUpdRefKriteriaOUTROWCOUNT_QNAME, BigDecimal.class, OPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_UPDATE_BY", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPUPDATEBY(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPUPDATEBY_QNAME, String.class, IPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_KATEGORI_KRITERIA", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPKATEGORIKRITERIA(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPKATEGORIKRITERIA_QNAME, String.class, IPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_ID_KRITERIA", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPIDKRITERIA(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPIDKRITERIA_QNAME, String.class, IPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_NAMA", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPNAMA(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPNAMA_QNAME, String.class, IPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_KETERANGAN", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPKETERANGAN(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPKETERANGAN_QNAME, String.class, IPUpdRefKriteria.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://xmlns.oracle.com/pcbpel/adapter/db/sp/pkg_master_upd_ref_kriteria", name = "P_FLAG_TAMPIL", scope = IPUpdRefKriteria.class) public JAXBElement<String> createIPUpdRefKriteriaPFLAGTAMPIL(String value) { return new JAXBElement<String>(_IPUpdRefKriteriaPFLAGTAMPIL_QNAME, String.class, IPUpdRefKriteria.class, value); } }
6,735
0.716555
0.716555
131
50.404579
57.037121
183
false
false
0
0
0
0
0
0
0.557252
false
false
13
46c34c659a0f2b1dafa60c8eb2c0451c60512f1d
22,789,096,530,701
c018786a6c3a684f40ec93d042430a3e61e8779e
/service/src/main/java/cn/kgc/tangcco/tcbd1017/st/ShangJiaRuKuService.java
f48c31827135f56e5fba7aec0667f9c3f930796c
[]
no_license
tcbd1017/aitao
https://github.com/tcbd1017/aitao
26470ec3c6418c9741212e4a2ff947e991efb430
b1de77c9498850ad59eb7166c2b8fafaeb4efde4
refs/heads/hubin20191225hehehe
2022-12-18T14:24:09.475000
2019-12-25T14:30:53
2019-12-25T14:30:53
223,545,160
0
0
null
false
2022-12-06T00:43:54
2019-11-23T06:51:48
2019-12-24T14:39:34
2022-12-06T00:43:53
32,933
0
0
10
Java
false
false
package cn.kgc.tangcco.tcbd1017.st; import java.sql.SQLException; import java.util.Map; public interface ShangJiaRuKuService { /** * ๅ•†ๅฎถๆŸฅ็œ‹ ่‡ชๅฎถไป“ๅบ“็š„่ดง็‰ฉ GoodsDaoImpl selectgoods() */ public Map<String,Object> ChaKanGoods(Map<String,Object>map); /** * ๅผ€ๅง‹ๆฃ€ๆต‹ๅ…ฅๅบ“ ๆŠŠๆ‰€ๅกซไฟกๆฏ ๆทปๅŠ ๅˆฐ JianceDaoImpl่กจ insertChuKu insertJianCeBiao๏ผˆ๏ผ‰ * @param map * @return * @throws SQLException */ public Map<String, Object> KaiShiRuKu(Map<String,Object>map); /** * * @ๆ–นๆณ•ๅ๏ผšๆŸฅ่ฏขjiance่กจ * @param map * @return */ public Map<String, Object> ChaXunZhuCe(Map<String,Object>map); }
UTF-8
Java
728
java
ShangJiaRuKuService.java
Java
[]
null
[]
package cn.kgc.tangcco.tcbd1017.st; import java.sql.SQLException; import java.util.Map; public interface ShangJiaRuKuService { /** * ๅ•†ๅฎถๆŸฅ็œ‹ ่‡ชๅฎถไป“ๅบ“็š„่ดง็‰ฉ GoodsDaoImpl selectgoods() */ public Map<String,Object> ChaKanGoods(Map<String,Object>map); /** * ๅผ€ๅง‹ๆฃ€ๆต‹ๅ…ฅๅบ“ ๆŠŠๆ‰€ๅกซไฟกๆฏ ๆทปๅŠ ๅˆฐ JianceDaoImpl่กจ insertChuKu insertJianCeBiao๏ผˆ๏ผ‰ * @param map * @return * @throws SQLException */ public Map<String, Object> KaiShiRuKu(Map<String,Object>map); /** * * @ๆ–นๆณ•ๅ๏ผšๆŸฅ่ฏขjiance่กจ * @param map * @return */ public Map<String, Object> ChaXunZhuCe(Map<String,Object>map); }
728
0.609423
0.603343
30
19.966667
24.678577
92
false
false
0
0
0
0
0
0
1.133333
false
false
13
452301dfe6d3047261f556d7e95798dff8e3bea4
11,682,311,047,636
29d825e800322d26793d9f773f4a7902189e0001
/src/DBLayer/IFDBEmployee.java
e66b979e87ca16cc6f05b7d9f139c011908bcd17
[]
no_license
vicarmocanu/Hotel-Management---Java
https://github.com/vicarmocanu/Hotel-Management---Java
ca38625ef26790ed5ec0981f5e459e5c2841c12c
28c7c8141669c2b20bbad1cd2ad8bc8b3b86d609
refs/heads/master
2020-06-07T10:15:19.939000
2013-08-25T22:25:49
2013-08-25T22:25:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DBLayer; import java.util.LinkedList; import Model.Employee; public interface IFDBEmployee { public LinkedList<Employee> getAllEmployees(); public Employee getEmployeeById(int id); public int insertEmployee(Employee employeeObj) throws Exception; public int updateEmployee(Employee employeeObj); public int deleteEmployeeById(int id); }
UTF-8
Java
368
java
IFDBEmployee.java
Java
[]
null
[]
package DBLayer; import java.util.LinkedList; import Model.Employee; public interface IFDBEmployee { public LinkedList<Employee> getAllEmployees(); public Employee getEmployeeById(int id); public int insertEmployee(Employee employeeObj) throws Exception; public int updateEmployee(Employee employeeObj); public int deleteEmployeeById(int id); }
368
0.782609
0.782609
14
24.285715
21.399027
67
false
false
0
0
0
0
0
0
1
false
false
13
ccf91a5534a26a5c861fb2abe3c987111d60ff41
30,614,526,902,888
3d0d303c1b6ac8770dedd9d025977b1961d6ae57
/Big Data Engineering/ADBMS Assignments/Piyush_Saxena_Assignment_3/Assignment3_Part3/CombineFileInputFormat/Assignment3_Part3_CombineFileInput/src/inputFormat/MyCombineFileRecordReader.java
8ca1398152581d0ffb3228b84bfaae9d19fca81f
[]
no_license
piyushsaxena2910/acedemic_projects
https://github.com/piyushsaxena2910/acedemic_projects
eb724baf08366a648a08edc661d549c4416c74a0
2b5a582967c7d54739ade3e8a4f59a3c457134a5
refs/heads/master
2021-01-21T17:46:45.941000
2017-05-21T23:59:29
2017-05-21T23:59:29
91,986,966
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package inputFormat; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.input.LineRecordReader; public class MyCombineFileRecordReader extends RecordReader<LongWritable,Text>{ private LineRecordReader lineRecordReader = new LineRecordReader(); public MyCombineFileRecordReader(CombineFileSplit split, TaskAttemptContext context, Integer index) throws IOException{ FileSplit fileSplit = new FileSplit(split.getPath(index),split.getOffset(index), split.getLength(index), split.getLocations()); lineRecordReader.initialize(fileSplit, context); } @Override public void close() throws IOException { // TODO Auto-generated method stub lineRecordReader.close(); } @Override public LongWritable getCurrentKey() throws IOException, InterruptedException { // TODO Auto-generated method stub return lineRecordReader.getCurrentKey(); } @Override public Text getCurrentValue() throws IOException, InterruptedException { // TODO Auto-generated method stub return lineRecordReader.getCurrentValue(); } @Override public float getProgress() throws IOException, InterruptedException { // TODO Auto-generated method stub return lineRecordReader.getProgress(); } @Override public void initialize(InputSplit arg0, TaskAttemptContext arg1) throws IOException, InterruptedException { // TODO Auto-generated method stub } @Override public boolean nextKeyValue() throws IOException, InterruptedException { // TODO Auto-generated method stub return lineRecordReader.nextKeyValue(); } }
UTF-8
Java
1,946
java
MyCombineFileRecordReader.java
Java
[]
null
[]
package inputFormat; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.input.LineRecordReader; public class MyCombineFileRecordReader extends RecordReader<LongWritable,Text>{ private LineRecordReader lineRecordReader = new LineRecordReader(); public MyCombineFileRecordReader(CombineFileSplit split, TaskAttemptContext context, Integer index) throws IOException{ FileSplit fileSplit = new FileSplit(split.getPath(index),split.getOffset(index), split.getLength(index), split.getLocations()); lineRecordReader.initialize(fileSplit, context); } @Override public void close() throws IOException { // TODO Auto-generated method stub lineRecordReader.close(); } @Override public LongWritable getCurrentKey() throws IOException, InterruptedException { // TODO Auto-generated method stub return lineRecordReader.getCurrentKey(); } @Override public Text getCurrentValue() throws IOException, InterruptedException { // TODO Auto-generated method stub return lineRecordReader.getCurrentValue(); } @Override public float getProgress() throws IOException, InterruptedException { // TODO Auto-generated method stub return lineRecordReader.getProgress(); } @Override public void initialize(InputSplit arg0, TaskAttemptContext arg1) throws IOException, InterruptedException { // TODO Auto-generated method stub } @Override public boolean nextKeyValue() throws IOException, InterruptedException { // TODO Auto-generated method stub return lineRecordReader.nextKeyValue(); } }
1,946
0.777492
0.776465
61
30.90164
29.611532
108
false
false
0
0
0
0
0
0
1.262295
false
false
13
3d20231c24947d73de6c60d582ac4500eb818bc8
13,374,528,210,914
6f6e2a8fc8021759dc8689806fc6a4e8ff5cf887
/CodilocTest/src/net/tsc/codiloc/versionmanager/model/VersionManagerFacadeTest.java
364e7f29ab1a052700a4e169349f50e66b9db3e1
[ "Unlicense" ]
permissive
tscecos/codiloc
https://github.com/tscecos/codiloc
a56626b487d048e8ca3b036e46d2e5381854e9ba
8b92a17eb4a3ce350da0e5072ada5b13ae69267f
refs/heads/master
2016-09-06T19:52:56.207000
2014-05-11T03:35:24
2014-05-11T03:35:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.tsc.codiloc.versionmanager.model; import static org.junit.Assert.assertEquals; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.tsc.codiloc.filemanager.exception.FileManagerException; import net.tsc.codiloc.filemanager.model.FileManagerFacade; import net.tsc.codiloc.loccomparator.exception.ComparatorException; import net.tsc.codiloc.loccomparator.model.ComparatorFacade; import net.tsc.codiloc.loccomparator.model.ComparedLine; import net.tsc.codiloc.versionmanager.exception.VersionManagerException; import org.junit.Test; public class VersionManagerFacadeTest { private final File original = new File("..\\CodilocTest\\testFiles\\original\\ComparedLine.java"); private final File modified = new File("..\\CodilocTest\\testFiles\\modified\\ComparedLine.java"); @Test public void compareVersion() throws VersionManagerException { int addedLines = 0; int deletedLines = 0; int totalLines = 0; List<String> originalLines = null; List<String> modifiedLines = null; List<ComparedLine> addedLinesList = new ArrayList<>(); List<ComparedLine> deletedLinesList = new ArrayList<>(); VersionManagerFacade versionManager = VersionManagerFacade.getInstance(); ComparatorFacade comparator = ComparatorFacade.getInstance(); FileManagerFacade fileManager = FileManagerFacade.getInstance(); try { originalLines = fileManager.getLinesFromFile(original); modifiedLines = fileManager.getLinesFromFile(modified); } catch (FileManagerException e) { e.printStackTrace(); } try { addedLinesList = comparator.getAddedLOC(originalLines, modifiedLines); assertEquals(" private String addLine;", addedLinesList.get(0).getTextLine()); assertEquals(" private int addLineNumber;", addedLinesList.get(1).getTextLine()); deletedLinesList = comparator.getDeletedLOC(originalLines, modifiedLines); assertEquals(" public void setTextLineNumber(int textLineNumber) {", deletedLinesList.get(0).getTextLine()); assertEquals(" this.textLineNumber = textLineNumber;", deletedLinesList.get(1).getTextLine()); assertEquals(" }", deletedLinesList.get(2).getTextLine()); addedLines = versionManager.countComparedLOC(addedLinesList); assertEquals(2, addedLines); deletedLines = versionManager.countComparedLOC(deletedLinesList); assertEquals(3, deletedLines); for(String line : modifiedLines){ totalLines += versionManager.countLOC(line); } assertEquals(20, totalLines); } catch (ComparatorException e) { e.printStackTrace(); } } @Test public void loadBase() throws VersionManagerException { String fileName = "../files/ComparedLine.java"; VersionManagerFacade versionManager = VersionManagerFacade.getInstance(); List<String> baseLines = versionManager.loadBase(fileName); assertEquals(61, baseLines.size()); assertEquals("package net.tsc.codiloc.loccomparator.model;", baseLines.get(0)); assertEquals("}", baseLines.get(60)); } @Test public void loadHistory() throws VersionManagerException { String fileName = "../files/ComparedLine.java"; VersionManagerFacade versionManager = VersionManagerFacade.getInstance(); List<String> historyLines = versionManager.loadHistory(fileName); assertEquals(null, historyLines); } @Test public void addHeaderVer0() throws VersionManagerException { Map<String, String> header = null; List<String> historyLines = null; List<String> hResult = new ArrayList<String>(); VersionManagerFacade versionManager = VersionManagerFacade .getInstance(); try { versionManager.addHeader(header, historyLines); } catch (IllegalArgumentException e) { e.printStackTrace(); } historyLines = new ArrayList<String>(); historyLines.add("int edad = 22;"); historyLines.add("if(comparedText.equal(\"hola mundo\")){"); historyLines.add("int String = \"mi nombre es\";"); historyLines.add("int total = 1233;"); historyLines.add("bool flag = false;"); historyLines.add("int cost = 345;"); header = new HashMap<String, String>(); header.put("Autor", "Mauricio Torres"); header.put("Observaciones", "nueva clase que hace algo"); hResult.add("/*<<---HEADER--->>"); hResult.add("*<<VER:0>>"); hResult.add("*<<DATETIME:"); hResult.add("*<<Autor:Mauricio Torres>>"); hResult.add("*<<Observaciones:nueva clase que hace algo>>"); hResult.add("*<<---END HEADER--->>"); hResult.add("*/"); try { versionManager.addHeader(header, historyLines); List<String> hRes = versionManager.getHistoryLines(); for (Map.Entry<String, String> entry : header.entrySet()) { String line = "*<<" + entry.getKey() + ":" + entry.getValue() + ">>"; boolean res = hRes.contains(line); assertEquals(res, true); } for (String hLine : historyLines) { boolean res = hRes.contains(hLine); assertEquals(res, true); } } catch (VersionManagerException e) { e.printStackTrace(); } } @Test public void addHeaderVerX() throws VersionManagerException { Map<String, String> header = null; List<String> historyLines = null; List<String> hResult = new ArrayList<String>(); VersionManagerFacade versionManager = VersionManagerFacade .getInstance(); try { versionManager.addHeader(header, historyLines); } catch (IllegalArgumentException e) { e.printStackTrace(); } historyLines = new ArrayList<String>(); historyLines.add("/*<<---HEADER--->>"); historyLines.add("*<<VER:0>>"); historyLines.add("*<<DATETIME:10/05/14 10:32 AM>>"); historyLines.add("*<<Observaciones:nueva clase que hace algo>>"); historyLines.add("*<<Autor:Mauricio Torres>>"); historyLines.add("*<<---END HEADER--->>"); historyLines.add("*/"); historyLines.add("int edad = 22;"); historyLines.add("if(comparedText.equal(\"hola mundo\")){"); historyLines.add("int String = \"mi nombre es\";"); historyLines.add("int total = 1233;"); historyLines.add("bool flag = false;"); historyLines.add("int cost = 345;"); header = new HashMap<String, String>(); header.put("Autor", "Juan Perez"); header.put("Observaciones", "La misma clase que hace algo, ahora hace otra cosa"); hResult.add("/*<<---HEADER--->>"); hResult.add("*<<VER:1>>"); hResult.add("*<<DATETIME:"); hResult.add("*<<Autor:Juan Perez>>"); hResult.add("*<<Observaciones:La misma clase que hace algo, ahora hace otra cosa>>"); hResult.add("*<<---END HEADER--->>"); hResult.add("*/"); try { versionManager.addHeader(header, historyLines); List<String> hRes = versionManager.getHistoryLines(); for (Map.Entry<String, String> entry : header.entrySet()) { String line = "*<<" + entry.getKey() + ":" + entry.getValue() + ">>"; boolean res = hRes.contains(line); assertEquals(res, true); } for (String hLine : historyLines) { boolean res = hRes.contains(hLine); assertEquals(res, true); } } catch (VersionManagerException e) { e.printStackTrace(); } } @Test public void addTags() throws VersionManagerException { ComparedLine pushLine; List<ComparedLine> comparedLines = new ArrayList<>(); List<String> historyLines = new ArrayList<String>(); List<String> resultHistoryLines = new ArrayList<String>(); pushLine = new ComparedLine("int edad = 22;", 0); comparedLines.add(pushLine); pushLine = new ComparedLine("if(comparedText.equal(\"hola mundo\")){", 1); comparedLines.add(pushLine); pushLine = new ComparedLine("String name = \"mi nombre es\";", 2); comparedLines.add(pushLine); pushLine = new ComparedLine("int total = 1233;", 3); comparedLines.add(pushLine); pushLine = new ComparedLine("bool flag = false;", 4); comparedLines.add(pushLine); pushLine = new ComparedLine("int cost = 345;", 5); comparedLines.add(pushLine); historyLines.add("int edad = 22;"); historyLines.add("if(comparedText.equal(\"hola mundo\")){"); historyLines.add("String name = \"mi nombre es\";"); historyLines.add("int total = 1233;"); historyLines.add("bool flag = false;"); historyLines.add("int cost = 345;"); VersionManagerFacade versionManager = VersionManagerFacade.getInstance(); versionManager.addTags(comparedLines, historyLines, "1.0", "A"); resultHistoryLines = versionManager.getHistoryLines(); assertEquals("int edad = 22; //<<Versiรณn: 1.0 Lรญnea adicionada: int edad = 22;>>", resultHistoryLines.get(0)); assertEquals("if(comparedText.equal(\"hola mundo\")){ //<<Versiรณn: 1.0 Lรญnea adicionada: if(comparedText.equal(\"hola mundo\")){>>", resultHistoryLines.get(1)); assertEquals("String name = \"mi nombre es\"; //<<Versiรณn: 1.0 Lรญnea adicionada: String name = \"mi nombre es\";>>", resultHistoryLines.get(2)); assertEquals("int total = 1233; //<<Versiรณn: 1.0 Lรญnea adicionada: int total = 1233;>>", resultHistoryLines.get(3)); assertEquals("bool flag = false; //<<Versiรณn: 1.0 Lรญnea adicionada: bool flag = false;>>", resultHistoryLines.get(4)); assertEquals("int cost = 345; //<<Versiรณn: 1.0 Lรญnea adicionada: int cost = 345;>>", resultHistoryLines.get(5)); } @Test public void addTagsWithHeader() throws VersionManagerException { ComparedLine pushLine; List<ComparedLine> comparedLines = new ArrayList<>(); List<String> historyLines = new ArrayList<String>(); List<String> resultHistoryLines = new ArrayList<String>(); pushLine = new ComparedLine("int edad = 22;", 0); comparedLines.add(pushLine); pushLine = new ComparedLine("if(comparedText.equal(\"hola mundo\")){", 1); comparedLines.add(pushLine); pushLine = new ComparedLine("String name = \"mi nombre es\";", 2); comparedLines.add(pushLine); pushLine = new ComparedLine("int total = 1233;", 3); comparedLines.add(pushLine); pushLine = new ComparedLine("bool flag = false;", 4); comparedLines.add(pushLine); pushLine = new ComparedLine("int cost = 345;", 5); comparedLines.add(pushLine); historyLines.add("/*<<---HEADER--->>"); historyLines.add("*<<VER:0>>"); historyLines.add("*<<DATETIME:"); historyLines.add("*<<Autor:Mauricio Torres>>"); historyLines.add("*<<Observaciones:nueva clase que hace algo>>"); historyLines.add("*<<---END HEADER--->>"); historyLines.add("*/"); historyLines.add("int edad = 22;"); historyLines.add("if(comparedText.equal(\"hola mundo\")){"); historyLines.add("String name = \"mi nombre es\";"); historyLines.add("int total = 1233;"); historyLines.add("bool flag = false;"); historyLines.add("int cost = 345;"); VersionManagerFacade versionManager = VersionManagerFacade.getInstance(); versionManager.addTags(comparedLines, historyLines, "1.0", "D"); resultHistoryLines = versionManager.getHistoryLines(); assertEquals("int edad = 22; //<<Versiรณn: 1.0 Lรญnea eliminada: int edad = 22;>>", resultHistoryLines.get(7)); assertEquals("if(comparedText.equal(\"hola mundo\")){ //<<Versiรณn: 1.0 Lรญnea eliminada: if(comparedText.equal(\"hola mundo\")){>>", resultHistoryLines.get(8)); assertEquals("String name = \"mi nombre es\"; //<<Versiรณn: 1.0 Lรญnea eliminada: String name = \"mi nombre es\";>>", resultHistoryLines.get(9)); assertEquals("int total = 1233; //<<Versiรณn: 1.0 Lรญnea eliminada: int total = 1233;>>", resultHistoryLines.get(10)); assertEquals("bool flag = false; //<<Versiรณn: 1.0 Lรญnea eliminada: bool flag = false;>>", resultHistoryLines.get(11)); assertEquals("int cost = 345; //<<Versiรณn: 1.0 Lรญnea eliminada: int cost = 345;>>", resultHistoryLines.get(12)); } }
WINDOWS-1250
Java
11,867
java
VersionManagerFacadeTest.java
Java
[ { "context": "ashMap<String, String>();\r\n\t\theader.put(\"Autor\", \"Mauricio Torres\");\r\n\t\theader.put(\"Observaciones\", \"nueva clase qu", "end": 4313, "score": 0.9998887181282043, "start": 4298, "tag": "NAME", "value": "Mauricio Torres" }, { "context": "ult.add(\"*<<DATETIME:\");\r\n\t\thResult.add(\"*<<Autor:Mauricio Torres>>\");\r\n\t\thResult.add(\"*<<Observaciones:nueva clase", "end": 4520, "score": 0.9998879432678223, "start": 4505, "tag": "NAME", "value": "Mauricio Torres" }, { "context": " que hace algo>>\");\r\n\t\thistoryLines.add(\"*<<Autor:Mauricio Torres>>\");\r\n\t\thistoryLines.add(\"*<<---END HEADER--->>\")", "end": 5908, "score": 0.9998935461044312, "start": 5893, "tag": "NAME", "value": "Mauricio Torres" }, { "context": "ashMap<String, String>();\r\n\t\theader.put(\"Autor\", \"Juan Perez\");\r\n\t\theader.put(\"Observaciones\", \"La misma clase", "end": 6351, "score": 0.9998841285705566, "start": 6341, "tag": "NAME", "value": "Juan Perez" }, { "context": "ult.add(\"*<<DATETIME:\");\r\n\t\thResult.add(\"*<<Autor:Juan Perez>>\");\r\n\t\thResult.add(\"*<<Observaciones:La misma cl", "end": 6580, "score": 0.99970543384552, "start": 6570, "tag": "NAME", "value": "Juan Perez" }, { "context": "dd(\"*<<DATETIME:\");\r\n\t\thistoryLines.add(\"*<<Autor:Mauricio Torres>>\");\r\n\t\thistoryLines.add(\"*<<Observaciones:nueva ", "end": 10413, "score": 0.9998920559883118, "start": 10398, "tag": "NAME", "value": "Mauricio Torres" } ]
null
[]
package net.tsc.codiloc.versionmanager.model; import static org.junit.Assert.assertEquals; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.tsc.codiloc.filemanager.exception.FileManagerException; import net.tsc.codiloc.filemanager.model.FileManagerFacade; import net.tsc.codiloc.loccomparator.exception.ComparatorException; import net.tsc.codiloc.loccomparator.model.ComparatorFacade; import net.tsc.codiloc.loccomparator.model.ComparedLine; import net.tsc.codiloc.versionmanager.exception.VersionManagerException; import org.junit.Test; public class VersionManagerFacadeTest { private final File original = new File("..\\CodilocTest\\testFiles\\original\\ComparedLine.java"); private final File modified = new File("..\\CodilocTest\\testFiles\\modified\\ComparedLine.java"); @Test public void compareVersion() throws VersionManagerException { int addedLines = 0; int deletedLines = 0; int totalLines = 0; List<String> originalLines = null; List<String> modifiedLines = null; List<ComparedLine> addedLinesList = new ArrayList<>(); List<ComparedLine> deletedLinesList = new ArrayList<>(); VersionManagerFacade versionManager = VersionManagerFacade.getInstance(); ComparatorFacade comparator = ComparatorFacade.getInstance(); FileManagerFacade fileManager = FileManagerFacade.getInstance(); try { originalLines = fileManager.getLinesFromFile(original); modifiedLines = fileManager.getLinesFromFile(modified); } catch (FileManagerException e) { e.printStackTrace(); } try { addedLinesList = comparator.getAddedLOC(originalLines, modifiedLines); assertEquals(" private String addLine;", addedLinesList.get(0).getTextLine()); assertEquals(" private int addLineNumber;", addedLinesList.get(1).getTextLine()); deletedLinesList = comparator.getDeletedLOC(originalLines, modifiedLines); assertEquals(" public void setTextLineNumber(int textLineNumber) {", deletedLinesList.get(0).getTextLine()); assertEquals(" this.textLineNumber = textLineNumber;", deletedLinesList.get(1).getTextLine()); assertEquals(" }", deletedLinesList.get(2).getTextLine()); addedLines = versionManager.countComparedLOC(addedLinesList); assertEquals(2, addedLines); deletedLines = versionManager.countComparedLOC(deletedLinesList); assertEquals(3, deletedLines); for(String line : modifiedLines){ totalLines += versionManager.countLOC(line); } assertEquals(20, totalLines); } catch (ComparatorException e) { e.printStackTrace(); } } @Test public void loadBase() throws VersionManagerException { String fileName = "../files/ComparedLine.java"; VersionManagerFacade versionManager = VersionManagerFacade.getInstance(); List<String> baseLines = versionManager.loadBase(fileName); assertEquals(61, baseLines.size()); assertEquals("package net.tsc.codiloc.loccomparator.model;", baseLines.get(0)); assertEquals("}", baseLines.get(60)); } @Test public void loadHistory() throws VersionManagerException { String fileName = "../files/ComparedLine.java"; VersionManagerFacade versionManager = VersionManagerFacade.getInstance(); List<String> historyLines = versionManager.loadHistory(fileName); assertEquals(null, historyLines); } @Test public void addHeaderVer0() throws VersionManagerException { Map<String, String> header = null; List<String> historyLines = null; List<String> hResult = new ArrayList<String>(); VersionManagerFacade versionManager = VersionManagerFacade .getInstance(); try { versionManager.addHeader(header, historyLines); } catch (IllegalArgumentException e) { e.printStackTrace(); } historyLines = new ArrayList<String>(); historyLines.add("int edad = 22;"); historyLines.add("if(comparedText.equal(\"hola mundo\")){"); historyLines.add("int String = \"mi nombre es\";"); historyLines.add("int total = 1233;"); historyLines.add("bool flag = false;"); historyLines.add("int cost = 345;"); header = new HashMap<String, String>(); header.put("Autor", "<NAME>"); header.put("Observaciones", "nueva clase que hace algo"); hResult.add("/*<<---HEADER--->>"); hResult.add("*<<VER:0>>"); hResult.add("*<<DATETIME:"); hResult.add("*<<Autor:<NAME>>>"); hResult.add("*<<Observaciones:nueva clase que hace algo>>"); hResult.add("*<<---END HEADER--->>"); hResult.add("*/"); try { versionManager.addHeader(header, historyLines); List<String> hRes = versionManager.getHistoryLines(); for (Map.Entry<String, String> entry : header.entrySet()) { String line = "*<<" + entry.getKey() + ":" + entry.getValue() + ">>"; boolean res = hRes.contains(line); assertEquals(res, true); } for (String hLine : historyLines) { boolean res = hRes.contains(hLine); assertEquals(res, true); } } catch (VersionManagerException e) { e.printStackTrace(); } } @Test public void addHeaderVerX() throws VersionManagerException { Map<String, String> header = null; List<String> historyLines = null; List<String> hResult = new ArrayList<String>(); VersionManagerFacade versionManager = VersionManagerFacade .getInstance(); try { versionManager.addHeader(header, historyLines); } catch (IllegalArgumentException e) { e.printStackTrace(); } historyLines = new ArrayList<String>(); historyLines.add("/*<<---HEADER--->>"); historyLines.add("*<<VER:0>>"); historyLines.add("*<<DATETIME:10/05/14 10:32 AM>>"); historyLines.add("*<<Observaciones:nueva clase que hace algo>>"); historyLines.add("*<<Autor:<NAME>>>"); historyLines.add("*<<---END HEADER--->>"); historyLines.add("*/"); historyLines.add("int edad = 22;"); historyLines.add("if(comparedText.equal(\"hola mundo\")){"); historyLines.add("int String = \"mi nombre es\";"); historyLines.add("int total = 1233;"); historyLines.add("bool flag = false;"); historyLines.add("int cost = 345;"); header = new HashMap<String, String>(); header.put("Autor", "<NAME>"); header.put("Observaciones", "La misma clase que hace algo, ahora hace otra cosa"); hResult.add("/*<<---HEADER--->>"); hResult.add("*<<VER:1>>"); hResult.add("*<<DATETIME:"); hResult.add("*<<Autor:<NAME>>>"); hResult.add("*<<Observaciones:La misma clase que hace algo, ahora hace otra cosa>>"); hResult.add("*<<---END HEADER--->>"); hResult.add("*/"); try { versionManager.addHeader(header, historyLines); List<String> hRes = versionManager.getHistoryLines(); for (Map.Entry<String, String> entry : header.entrySet()) { String line = "*<<" + entry.getKey() + ":" + entry.getValue() + ">>"; boolean res = hRes.contains(line); assertEquals(res, true); } for (String hLine : historyLines) { boolean res = hRes.contains(hLine); assertEquals(res, true); } } catch (VersionManagerException e) { e.printStackTrace(); } } @Test public void addTags() throws VersionManagerException { ComparedLine pushLine; List<ComparedLine> comparedLines = new ArrayList<>(); List<String> historyLines = new ArrayList<String>(); List<String> resultHistoryLines = new ArrayList<String>(); pushLine = new ComparedLine("int edad = 22;", 0); comparedLines.add(pushLine); pushLine = new ComparedLine("if(comparedText.equal(\"hola mundo\")){", 1); comparedLines.add(pushLine); pushLine = new ComparedLine("String name = \"mi nombre es\";", 2); comparedLines.add(pushLine); pushLine = new ComparedLine("int total = 1233;", 3); comparedLines.add(pushLine); pushLine = new ComparedLine("bool flag = false;", 4); comparedLines.add(pushLine); pushLine = new ComparedLine("int cost = 345;", 5); comparedLines.add(pushLine); historyLines.add("int edad = 22;"); historyLines.add("if(comparedText.equal(\"hola mundo\")){"); historyLines.add("String name = \"mi nombre es\";"); historyLines.add("int total = 1233;"); historyLines.add("bool flag = false;"); historyLines.add("int cost = 345;"); VersionManagerFacade versionManager = VersionManagerFacade.getInstance(); versionManager.addTags(comparedLines, historyLines, "1.0", "A"); resultHistoryLines = versionManager.getHistoryLines(); assertEquals("int edad = 22; //<<Versiรณn: 1.0 Lรญnea adicionada: int edad = 22;>>", resultHistoryLines.get(0)); assertEquals("if(comparedText.equal(\"hola mundo\")){ //<<Versiรณn: 1.0 Lรญnea adicionada: if(comparedText.equal(\"hola mundo\")){>>", resultHistoryLines.get(1)); assertEquals("String name = \"mi nombre es\"; //<<Versiรณn: 1.0 Lรญnea adicionada: String name = \"mi nombre es\";>>", resultHistoryLines.get(2)); assertEquals("int total = 1233; //<<Versiรณn: 1.0 Lรญnea adicionada: int total = 1233;>>", resultHistoryLines.get(3)); assertEquals("bool flag = false; //<<Versiรณn: 1.0 Lรญnea adicionada: bool flag = false;>>", resultHistoryLines.get(4)); assertEquals("int cost = 345; //<<Versiรณn: 1.0 Lรญnea adicionada: int cost = 345;>>", resultHistoryLines.get(5)); } @Test public void addTagsWithHeader() throws VersionManagerException { ComparedLine pushLine; List<ComparedLine> comparedLines = new ArrayList<>(); List<String> historyLines = new ArrayList<String>(); List<String> resultHistoryLines = new ArrayList<String>(); pushLine = new ComparedLine("int edad = 22;", 0); comparedLines.add(pushLine); pushLine = new ComparedLine("if(comparedText.equal(\"hola mundo\")){", 1); comparedLines.add(pushLine); pushLine = new ComparedLine("String name = \"mi nombre es\";", 2); comparedLines.add(pushLine); pushLine = new ComparedLine("int total = 1233;", 3); comparedLines.add(pushLine); pushLine = new ComparedLine("bool flag = false;", 4); comparedLines.add(pushLine); pushLine = new ComparedLine("int cost = 345;", 5); comparedLines.add(pushLine); historyLines.add("/*<<---HEADER--->>"); historyLines.add("*<<VER:0>>"); historyLines.add("*<<DATETIME:"); historyLines.add("*<<Autor:<NAME>>>"); historyLines.add("*<<Observaciones:nueva clase que hace algo>>"); historyLines.add("*<<---END HEADER--->>"); historyLines.add("*/"); historyLines.add("int edad = 22;"); historyLines.add("if(comparedText.equal(\"hola mundo\")){"); historyLines.add("String name = \"mi nombre es\";"); historyLines.add("int total = 1233;"); historyLines.add("bool flag = false;"); historyLines.add("int cost = 345;"); VersionManagerFacade versionManager = VersionManagerFacade.getInstance(); versionManager.addTags(comparedLines, historyLines, "1.0", "D"); resultHistoryLines = versionManager.getHistoryLines(); assertEquals("int edad = 22; //<<Versiรณn: 1.0 Lรญnea eliminada: int edad = 22;>>", resultHistoryLines.get(7)); assertEquals("if(comparedText.equal(\"hola mundo\")){ //<<Versiรณn: 1.0 Lรญnea eliminada: if(comparedText.equal(\"hola mundo\")){>>", resultHistoryLines.get(8)); assertEquals("String name = \"mi nombre es\"; //<<Versiรณn: 1.0 Lรญnea eliminada: String name = \"mi nombre es\";>>", resultHistoryLines.get(9)); assertEquals("int total = 1233; //<<Versiรณn: 1.0 Lรญnea eliminada: int total = 1233;>>", resultHistoryLines.get(10)); assertEquals("bool flag = false; //<<Versiรณn: 1.0 Lรญnea eliminada: bool flag = false;>>", resultHistoryLines.get(11)); assertEquals("int cost = 345; //<<Versiรณn: 1.0 Lรญnea eliminada: int cost = 345;>>", resultHistoryLines.get(12)); } }
11,823
0.67998
0.665034
304
36.957237
31.373201
162
false
false
0
0
0
0
0
0
2.924342
false
false
13
3addb2b4715f699fcabbb0965cca5c766db9fd28
14,388,140,480,886
2ff8297cec805ab8c20a53bb0510ec6e675e5737
/SharesTools/src/com/mosorg/common/utils/file/PropertiesUtil.java
923e3c95da0c65628b33442da10c44ffced78119
[]
no_license
smile2015/JavaDemo
https://github.com/smile2015/JavaDemo
f6f10a9bc4efbb1cbe4700cab46ab5cc1d335e1c
36a48d2c69de86c08ebadc0c94b46dfda8ecb5cd
refs/heads/master
2022-12-26T02:20:53.698000
2019-09-09T02:55:49
2019-09-09T02:56:08
164,214,310
0
0
null
false
2022-12-16T00:37:14
2019-01-05T12:47:12
2019-09-09T02:56:22
2022-12-16T00:37:11
114,074
0
0
8
Java
false
false
package com.mosorg.common.utils.file; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * @author msmiles * */ public class PropertiesUtil { // ไฝฟ็”จProperties็ฑปๆฅๅŠ ่ฝฝๅฑžๆ€งๆ–‡ไปถ static Properties props = new Properties(); private static String filePath="config/web.properties"; static{ System.out.println("filePath: "+filePath); //InputStream ins=ClassLoader.getSystemResourceAsStream(filePath); InputStream ins=PropertiesUtil.class.getClassLoader().getResourceAsStream(filePath); try { props.load(ins); } catch (IOException e) { e.printStackTrace(); } } public static void loadProperties(String fpath){ if(null!=fpath && !"".equals(fpath)){ filePath=fpath; } try { InputStream ins=ClassLoader.getSystemResourceAsStream(filePath); props.load(ins); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /*** * * @param key * @return */ public static String getValue(String key){ return props.getProperty(key); } }
UTF-8
Java
1,162
java
PropertiesUtil.java
Java
[ { "context": "ream;\nimport java.util.Properties;\n\n/**\n * @author msmiles\n *\n */\npublic class PropertiesUtil {\n\t\n\t// ไฝฟ็”จProp", "end": 185, "score": 0.9995909929275513, "start": 178, "tag": "USERNAME", "value": "msmiles" } ]
null
[]
package com.mosorg.common.utils.file; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * @author msmiles * */ public class PropertiesUtil { // ไฝฟ็”จProperties็ฑปๆฅๅŠ ่ฝฝๅฑžๆ€งๆ–‡ไปถ static Properties props = new Properties(); private static String filePath="config/web.properties"; static{ System.out.println("filePath: "+filePath); //InputStream ins=ClassLoader.getSystemResourceAsStream(filePath); InputStream ins=PropertiesUtil.class.getClassLoader().getResourceAsStream(filePath); try { props.load(ins); } catch (IOException e) { e.printStackTrace(); } } public static void loadProperties(String fpath){ if(null!=fpath && !"".equals(fpath)){ filePath=fpath; } try { InputStream ins=ClassLoader.getSystemResourceAsStream(filePath); props.load(ins); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /*** * * @param key * @return */ public static String getValue(String key){ return props.getProperty(key); } }
1,162
0.690893
0.690893
54
20.166666
20.748716
89
false
false
0
0
0
0
0
0
1.407407
false
false
13
96dc531ed4c26661043a62ec4d04dda50a76f8c5
30,425,548,385,033
d139b49d5ad2b5146f61d83ced0b67b5f3b3ba22
/src/test/java/gr/jchrist/gitextender/GitExecutor.java
266a44d779c0cd0894237da489650c71c0e2ad07
[ "Apache-2.0" ]
permissive
JChrist/gitextender
https://github.com/JChrist/gitextender
b050920a403dbe356dfe6a6de887549111c0958e
10a370acc23e2bbd8e93c5e8bdf08da0c6ec597d
refs/heads/main
2023-03-04T22:27:01.112000
2022-08-25T11:16:25
2022-08-25T11:16:25
38,200,282
17
1
Apache-2.0
false
2023-02-10T21:56:58
2015-06-28T13:45:34
2022-01-05T08:02:13
2023-02-10T21:56:55
279
15
1
6
Java
false
false
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gr.jchrist.gitextender; import com.intellij.execution.process.CapturingProcessHandler; import com.intellij.execution.process.ProcessOutput; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class GitExecutor { protected static final Logger LOG = Logger.getInstance(GitExecutor.class); public static class ExecutionException extends RuntimeException { private final int myExitCode; @NotNull private final String myOutput; ExecutionException(int exitCode, @NotNull String output) { super("Failed with exit code " + exitCode+". Output: "+output); myExitCode = exitCode; myOutput = output; } public int getExitCode() { return myExitCode; } @NotNull public String getOutput() { return myOutput; } } private static String ourCurrentDir; private static void cdAbs(@NotNull String absolutePath) { ourCurrentDir = absolutePath; debug("# cd " + shortenPath(absolutePath)); } public static void debug(@NotNull String msg) { if (!StringUtil.isEmptyOrSpaces(msg)) { LOG.info(msg); } } private static void cdRel(@NotNull String relativePath) { cdAbs(ourCurrentDir + "/" + relativePath); } public static void cd(@NotNull String relativeOrAbsolutePath) { if (relativeOrAbsolutePath.startsWith("/") || relativeOrAbsolutePath.charAt(1) == ':') { cdAbs(relativeOrAbsolutePath); } else { cdRel(relativeOrAbsolutePath); } } @NotNull public static File touch(String filePath) { try { File file = child(filePath); assert !file.exists() : "File " + file + " shouldn't exist yet"; //noinspection ResultOfMethodCallIgnored new File(file.getParent()).mkdirs(); // ensure to create the directories boolean fileCreated = file.createNewFile(); assert fileCreated; debug("# touch " + filePath); return file; } catch (IOException e) { throw new RuntimeException(e); } } @NotNull public static File touch(@NotNull String fileName, @NotNull String content) { File filePath = touch(fileName); echo(fileName, content); return filePath; } public static void echo(@NotNull String fileName, @NotNull String content) { try { FileUtil.writeToFile(child(fileName), content.getBytes(), true); } catch (IOException e) { throw new RuntimeException(e); } } public static void append(@NotNull File file, @NotNull String content) throws IOException { FileUtil.writeToFile(file, content.getBytes(), true); } public static void append(@NotNull String fileName, @NotNull String content) throws IOException { append(child(fileName), content); } @NotNull protected static String run(@NotNull File workingDir, @NotNull List<String> params, boolean ignoreNonZeroExitCode) throws ExecutionException { final ProcessBuilder builder = new ProcessBuilder().command(params); builder.directory(workingDir); builder.redirectErrorStream(true); Process clientProcess; try { clientProcess = builder.start(); } catch (IOException e) { throw new RuntimeException(e); } String commandLine = StringUtil.join(params, " "); CapturingProcessHandler handler = new CapturingProcessHandler(clientProcess, CharsetToolkit.getDefaultSystemCharset(), commandLine); ProcessOutput result = handler.runProcess(30 * 1000); if (result.isTimeout()) { throw new RuntimeException("Timeout waiting for the command execution. Command: " + commandLine); } String stdout = result.getStdout().trim(); if (result.getExitCode() != 0) { if (ignoreNonZeroExitCode) { debug("{" + result.getExitCode() + "}"); } debug(stdout); if (!ignoreNonZeroExitCode) { throw new ExecutionException(result.getExitCode(), stdout); } } else { debug(stdout); } return stdout; } @NotNull public static List<String> splitCommandInParameters(@NotNull String command) { List<String> split = new ArrayList<>(); boolean insideParam = false; StringBuilder currentParam = new StringBuilder(); for (char c : command.toCharArray()) { boolean flush = false; if (insideParam) { if (c == '\'') { insideParam = false; flush = true; } else { currentParam.append(c); } } else if (c == '\'') { insideParam = true; } else if (c == ' ') { flush = true; } else { currentParam.append(c); } if (flush) { if (!StringUtil.isEmptyOrSpaces(currentParam.toString())) { split.add(currentParam.toString()); } currentParam = new StringBuilder(); } } // last flush if (!StringUtil.isEmptyOrSpaces(currentParam.toString())) { split.add(currentParam.toString()); } return split; } @NotNull private static String shortenPath(@NotNull String path) { String[] split = path.split("/"); if (split.length > 3) { // split[0] is empty, because the path starts from / return String.format("/%s/.../%s/%s", split[1], split[split.length - 2], split[split.length - 1]); } return path; } @NotNull protected static File child(@NotNull String fileName) { assert ourCurrentDir != null : "Current dir hasn't been initialized yet. Call cd at least once before any other command."; return new File(ourCurrentDir, fileName); } @NotNull protected static File ourCurrentDir() { assert ourCurrentDir != null : "Current dir hasn't been initialized yet. Call cd at least once before any other command."; return new File(ourCurrentDir); } private static final int MAX_RETRIES = 3; private static boolean myVersionPrinted; //using inner class to avoid extra work during class loading of unrelated tests public static class PathHolder { private static String GIT_EXECUTABLE = null; public static String getGitExecutable() { if (GIT_EXECUTABLE != null) { return GIT_EXECUTABLE; } if (System.getProperty("os.name").toLowerCase().contains("windows")) { GIT_EXECUTABLE = "git.exe"; } else { GIT_EXECUTABLE = "git"; } return GIT_EXECUTABLE; } } public static String git(String command) { return git(command, false); } public static String git(String command, boolean ignoreNonZeroExitCode) { printVersionTheFirstTime(); return doCallGit(command, ignoreNonZeroExitCode); } @NotNull private static String doCallGit(String command, boolean ignoreNonZeroExitCode) { List<String> split = splitCommandInParameters(command); split.add(0, PathHolder.getGitExecutable()); File workingDir = ourCurrentDir(); debug("[" + workingDir.getName() + "] # git " + command); for (int attempt = 0; attempt < MAX_RETRIES; attempt++) { String stdout; try { stdout = run(workingDir, split, ignoreNonZeroExitCode); if (!isIndexLockFileError(stdout)) { return stdout; } } catch (ExecutionException e) { stdout = e.getOutput(); if (!isIndexLockFileError(stdout)) { throw e; } } LOG.info("Index lock file error, attempt #" + attempt + ": " + stdout); } throw new RuntimeException("fatal error during execution of Git command: $command"); } private static boolean isIndexLockFileError(@NotNull String stdout) { return stdout.contains("fatal") && stdout.contains("Unable to create") && stdout.contains(".git/index.lock"); } public static void add() { add("."); } public static void add(@NotNull String path) { git("add --verbose " + path); } @NotNull public static String addCommit(@NotNull String message) { add(); return commit(message); } public static void checkout(@NotNull String... params) { git("checkout " + StringUtil.join(params, " ")); } public static String commit(@NotNull String message) { git("commit -m '" + message + "'"); return last(); } @NotNull public static String tac(@NotNull String file, @NotNull String content) { touch(file, content); return addCommit("touched " + file); } @NotNull public static String tac(@NotNull String file) { touch(file, "content" + Math.random()); return addCommit("touched " + file); } @NotNull public static String push() { return git("push"); } @NotNull public static String push(String remoteName, String branch) { return git("push -u " + remoteName + " " + branch); } @NotNull public static String last() { return git("log -1 --pretty=%H"); } private static void printVersionTheFirstTime() { if (!myVersionPrinted) { myVersionPrinted = true; doCallGit("version", false); } } }
UTF-8
Java
10,809
java
GitExecutor.java
Java
[]
null
[]
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gr.jchrist.gitextender; import com.intellij.execution.process.CapturingProcessHandler; import com.intellij.execution.process.ProcessOutput; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class GitExecutor { protected static final Logger LOG = Logger.getInstance(GitExecutor.class); public static class ExecutionException extends RuntimeException { private final int myExitCode; @NotNull private final String myOutput; ExecutionException(int exitCode, @NotNull String output) { super("Failed with exit code " + exitCode+". Output: "+output); myExitCode = exitCode; myOutput = output; } public int getExitCode() { return myExitCode; } @NotNull public String getOutput() { return myOutput; } } private static String ourCurrentDir; private static void cdAbs(@NotNull String absolutePath) { ourCurrentDir = absolutePath; debug("# cd " + shortenPath(absolutePath)); } public static void debug(@NotNull String msg) { if (!StringUtil.isEmptyOrSpaces(msg)) { LOG.info(msg); } } private static void cdRel(@NotNull String relativePath) { cdAbs(ourCurrentDir + "/" + relativePath); } public static void cd(@NotNull String relativeOrAbsolutePath) { if (relativeOrAbsolutePath.startsWith("/") || relativeOrAbsolutePath.charAt(1) == ':') { cdAbs(relativeOrAbsolutePath); } else { cdRel(relativeOrAbsolutePath); } } @NotNull public static File touch(String filePath) { try { File file = child(filePath); assert !file.exists() : "File " + file + " shouldn't exist yet"; //noinspection ResultOfMethodCallIgnored new File(file.getParent()).mkdirs(); // ensure to create the directories boolean fileCreated = file.createNewFile(); assert fileCreated; debug("# touch " + filePath); return file; } catch (IOException e) { throw new RuntimeException(e); } } @NotNull public static File touch(@NotNull String fileName, @NotNull String content) { File filePath = touch(fileName); echo(fileName, content); return filePath; } public static void echo(@NotNull String fileName, @NotNull String content) { try { FileUtil.writeToFile(child(fileName), content.getBytes(), true); } catch (IOException e) { throw new RuntimeException(e); } } public static void append(@NotNull File file, @NotNull String content) throws IOException { FileUtil.writeToFile(file, content.getBytes(), true); } public static void append(@NotNull String fileName, @NotNull String content) throws IOException { append(child(fileName), content); } @NotNull protected static String run(@NotNull File workingDir, @NotNull List<String> params, boolean ignoreNonZeroExitCode) throws ExecutionException { final ProcessBuilder builder = new ProcessBuilder().command(params); builder.directory(workingDir); builder.redirectErrorStream(true); Process clientProcess; try { clientProcess = builder.start(); } catch (IOException e) { throw new RuntimeException(e); } String commandLine = StringUtil.join(params, " "); CapturingProcessHandler handler = new CapturingProcessHandler(clientProcess, CharsetToolkit.getDefaultSystemCharset(), commandLine); ProcessOutput result = handler.runProcess(30 * 1000); if (result.isTimeout()) { throw new RuntimeException("Timeout waiting for the command execution. Command: " + commandLine); } String stdout = result.getStdout().trim(); if (result.getExitCode() != 0) { if (ignoreNonZeroExitCode) { debug("{" + result.getExitCode() + "}"); } debug(stdout); if (!ignoreNonZeroExitCode) { throw new ExecutionException(result.getExitCode(), stdout); } } else { debug(stdout); } return stdout; } @NotNull public static List<String> splitCommandInParameters(@NotNull String command) { List<String> split = new ArrayList<>(); boolean insideParam = false; StringBuilder currentParam = new StringBuilder(); for (char c : command.toCharArray()) { boolean flush = false; if (insideParam) { if (c == '\'') { insideParam = false; flush = true; } else { currentParam.append(c); } } else if (c == '\'') { insideParam = true; } else if (c == ' ') { flush = true; } else { currentParam.append(c); } if (flush) { if (!StringUtil.isEmptyOrSpaces(currentParam.toString())) { split.add(currentParam.toString()); } currentParam = new StringBuilder(); } } // last flush if (!StringUtil.isEmptyOrSpaces(currentParam.toString())) { split.add(currentParam.toString()); } return split; } @NotNull private static String shortenPath(@NotNull String path) { String[] split = path.split("/"); if (split.length > 3) { // split[0] is empty, because the path starts from / return String.format("/%s/.../%s/%s", split[1], split[split.length - 2], split[split.length - 1]); } return path; } @NotNull protected static File child(@NotNull String fileName) { assert ourCurrentDir != null : "Current dir hasn't been initialized yet. Call cd at least once before any other command."; return new File(ourCurrentDir, fileName); } @NotNull protected static File ourCurrentDir() { assert ourCurrentDir != null : "Current dir hasn't been initialized yet. Call cd at least once before any other command."; return new File(ourCurrentDir); } private static final int MAX_RETRIES = 3; private static boolean myVersionPrinted; //using inner class to avoid extra work during class loading of unrelated tests public static class PathHolder { private static String GIT_EXECUTABLE = null; public static String getGitExecutable() { if (GIT_EXECUTABLE != null) { return GIT_EXECUTABLE; } if (System.getProperty("os.name").toLowerCase().contains("windows")) { GIT_EXECUTABLE = "git.exe"; } else { GIT_EXECUTABLE = "git"; } return GIT_EXECUTABLE; } } public static String git(String command) { return git(command, false); } public static String git(String command, boolean ignoreNonZeroExitCode) { printVersionTheFirstTime(); return doCallGit(command, ignoreNonZeroExitCode); } @NotNull private static String doCallGit(String command, boolean ignoreNonZeroExitCode) { List<String> split = splitCommandInParameters(command); split.add(0, PathHolder.getGitExecutable()); File workingDir = ourCurrentDir(); debug("[" + workingDir.getName() + "] # git " + command); for (int attempt = 0; attempt < MAX_RETRIES; attempt++) { String stdout; try { stdout = run(workingDir, split, ignoreNonZeroExitCode); if (!isIndexLockFileError(stdout)) { return stdout; } } catch (ExecutionException e) { stdout = e.getOutput(); if (!isIndexLockFileError(stdout)) { throw e; } } LOG.info("Index lock file error, attempt #" + attempt + ": " + stdout); } throw new RuntimeException("fatal error during execution of Git command: $command"); } private static boolean isIndexLockFileError(@NotNull String stdout) { return stdout.contains("fatal") && stdout.contains("Unable to create") && stdout.contains(".git/index.lock"); } public static void add() { add("."); } public static void add(@NotNull String path) { git("add --verbose " + path); } @NotNull public static String addCommit(@NotNull String message) { add(); return commit(message); } public static void checkout(@NotNull String... params) { git("checkout " + StringUtil.join(params, " ")); } public static String commit(@NotNull String message) { git("commit -m '" + message + "'"); return last(); } @NotNull public static String tac(@NotNull String file, @NotNull String content) { touch(file, content); return addCommit("touched " + file); } @NotNull public static String tac(@NotNull String file) { touch(file, "content" + Math.random()); return addCommit("touched " + file); } @NotNull public static String push() { return git("push"); } @NotNull public static String push(String remoteName, String branch) { return git("push -u " + remoteName + " " + branch); } @NotNull public static String last() { return git("log -1 --pretty=%H"); } private static void printVersionTheFirstTime() { if (!myVersionPrinted) { myVersionPrinted = true; doCallGit("version", false); } } }
10,809
0.597188
0.594505
328
31.954268
27.970821
140
false
false
0
0
0
0
0
0
0.493902
false
false
13
bcdabefd7acc2e8c6da0d44572455f9a99705337
3,496,103,434,921
84306a2dc1be837134bca0c7bbbee00c51f6883f
/src/client/MRUNodes.java
bbb63264d3f12489133d90fbdf4feb2b05245692
[]
no_license
Rune-Status/ubhating-orion_applet
https://github.com/Rune-Status/ubhating-orion_applet
51935b7d9de0646720cb2eccec4130e1bfd72243
e636e8d3d5d0ae710cfbccedbb060c83bea14acd
refs/heads/master
2020-12-06T05:57:48.525000
2020-01-08T21:49:37
2020-01-08T21:49:37
232,365,957
0
0
null
true
2020-01-08T22:20:07
2020-01-07T16:23:08
2020-01-07T22:20:09
2020-01-08T22:20:05
2,542
0
0
0
Java
false
false
package client; public final class MRUNodes { private final NodeSub emptyNodeSub = new NodeSub(); private final int initialCount; private int spaceLeft; private final NodeCache nodeCache; private final Queue requests = new Queue(); public MRUNodes(int i) { this.initialCount = i; this.spaceLeft = i; this.nodeCache = new NodeCache(); } public NodeSub insertFromCache(long l) { NodeSub nodeSub = (NodeSub)this.nodeCache.findNodeByID(l); if(nodeSub != null) { this.requests.insert(nodeSub); } return nodeSub; } public void removeFromCache(NodeSub nodeSub, long l) { try { if(this.spaceLeft == 0) { NodeSub runtimeexception = this.requests.popTail(); runtimeexception.remove(); runtimeexception.unlinkSub(); if(runtimeexception == this.emptyNodeSub) { NodeSub nodeSub_2 = this.requests.popTail(); nodeSub_2.remove(); nodeSub_2.unlinkSub(); } } else { --this.spaceLeft; } this.nodeCache.removeFromCache(nodeSub, l); this.requests.insert(nodeSub); } catch (RuntimeException var6) { SignLink.reporterror("47547, " + nodeSub + ", " + l + ", " + 2 + ", " + var6.toString()); throw new RuntimeException(); } } public void unlinkAll() { while(true) { NodeSub nodeSub = this.requests.popTail(); if(nodeSub == null) { this.spaceLeft = this.initialCount; return; } nodeSub.remove(); nodeSub.unlinkSub(); } } }
UTF-8
Java
1,740
java
MRUNodes.java
Java
[]
null
[]
package client; public final class MRUNodes { private final NodeSub emptyNodeSub = new NodeSub(); private final int initialCount; private int spaceLeft; private final NodeCache nodeCache; private final Queue requests = new Queue(); public MRUNodes(int i) { this.initialCount = i; this.spaceLeft = i; this.nodeCache = new NodeCache(); } public NodeSub insertFromCache(long l) { NodeSub nodeSub = (NodeSub)this.nodeCache.findNodeByID(l); if(nodeSub != null) { this.requests.insert(nodeSub); } return nodeSub; } public void removeFromCache(NodeSub nodeSub, long l) { try { if(this.spaceLeft == 0) { NodeSub runtimeexception = this.requests.popTail(); runtimeexception.remove(); runtimeexception.unlinkSub(); if(runtimeexception == this.emptyNodeSub) { NodeSub nodeSub_2 = this.requests.popTail(); nodeSub_2.remove(); nodeSub_2.unlinkSub(); } } else { --this.spaceLeft; } this.nodeCache.removeFromCache(nodeSub, l); this.requests.insert(nodeSub); } catch (RuntimeException var6) { SignLink.reporterror("47547, " + nodeSub + ", " + l + ", " + 2 + ", " + var6.toString()); throw new RuntimeException(); } } public void unlinkAll() { while(true) { NodeSub nodeSub = this.requests.popTail(); if(nodeSub == null) { this.spaceLeft = this.initialCount; return; } nodeSub.remove(); nodeSub.unlinkSub(); } } }
1,740
0.547701
0.540805
63
25.619047
21.11302
98
false
false
0
0
0
0
0
0
0.539683
false
false
13
10b32ff2ac625b04a60a372aa9b8bf6f1c8a8944
3,195,455,702,395
d806c0bb7e117da62d8e6b75301bde8d799e2252
/IdeaProjects/untitled9/out/production/ProjetJavaFX/src/metier/Animation.java
851da4ab9cec69224dbcf4e35b17b74625723e07
[]
no_license
gulzhker/SpaceIn
https://github.com/gulzhker/SpaceIn
a821366c090dcebd44c4ad91f6ad0bb74ca7abc7
d389cf399ec3c4a4cb9a8ecc5780f86076a0b875
refs/heads/master
2020-03-12T11:49:21.914000
2018-04-22T21:34:02
2018-04-22T21:34:02
130,604,667
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package metier; import controller.ControllerJeu; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.scene.image.ImageView; import java.util.Random; public class Animation { static final String PATH_PLAYER = "/img/player.png"; static final String PATH_LINUX = "/img/linux.png"; static final String PATH_TIR = "/img/tir.png"; static final int DEBUT_FENETRE = 0; static final int LARGEUR = 5; static final int PDV = 10; static final int TAILLE = 50; static final int TEMPS_CREATION = 2000; static final int VITESSE_ENNEMI = 1; static final int VITESSE_TIR = 2; static final int VITESSE_PLAYER = 1; private Player player; private ControllerJeu jeu; private Ennemi ennemi; private Tir tir; Task<Void> creerEnnemi = new Task<Void>() { @Override public Void call() throws InterruptedException { Random random = new Random(); while(true){ ennemi = new Ennemi(TAILLE, VITESSE_ENNEMI, PDV, random.nextInt(LARGEUR), DEBUT_FENETRE, creerImage(PATH_LINUX)); Platform.runLater(() -> { jeu.addBlock(ennemi); }); new TaskBlock(ennemi, jeu); Thread.sleep(TEMPS_CREATION); } } }; public Animation(ControllerJeu jeu) { this.jeu = jeu; player = new Player(TAILLE, VITESSE_PLAYER, PDV, 2, 4, creerImage(PATH_PLAYER)); jeu.addBlock(player); } private ImageView creerImage(String source){ ImageView imageView = new ImageView(source); imageView.setFitHeight(TAILLE); imageView.setPreserveRatio(true); return imageView; } public void commencer(){ ( new Thread(creerEnnemi) ).start(); } public void addTir(){ tir = new Tir(TAILLE, VITESSE_TIR, PDV, player.getAbscisse(), player.getOrdonnee()-1, creerImage(PATH_TIR)); new TaskBlock(tir, jeu); jeu.addBlock(tir); } public void movePlayer(Deplacer d){ switch (d){ case GAUCHE: if ( player.getAbscisse() > DEBUT_FENETRE ) player.deplacer(d); break; case DROITE: if ( player.getAbscisse() < LARGEUR-1 ) player.deplacer(d); break; } jeu.showBlock(player); } }
UTF-8
Java
2,386
java
Animation.java
Java
[]
null
[]
package metier; import controller.ControllerJeu; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.scene.image.ImageView; import java.util.Random; public class Animation { static final String PATH_PLAYER = "/img/player.png"; static final String PATH_LINUX = "/img/linux.png"; static final String PATH_TIR = "/img/tir.png"; static final int DEBUT_FENETRE = 0; static final int LARGEUR = 5; static final int PDV = 10; static final int TAILLE = 50; static final int TEMPS_CREATION = 2000; static final int VITESSE_ENNEMI = 1; static final int VITESSE_TIR = 2; static final int VITESSE_PLAYER = 1; private Player player; private ControllerJeu jeu; private Ennemi ennemi; private Tir tir; Task<Void> creerEnnemi = new Task<Void>() { @Override public Void call() throws InterruptedException { Random random = new Random(); while(true){ ennemi = new Ennemi(TAILLE, VITESSE_ENNEMI, PDV, random.nextInt(LARGEUR), DEBUT_FENETRE, creerImage(PATH_LINUX)); Platform.runLater(() -> { jeu.addBlock(ennemi); }); new TaskBlock(ennemi, jeu); Thread.sleep(TEMPS_CREATION); } } }; public Animation(ControllerJeu jeu) { this.jeu = jeu; player = new Player(TAILLE, VITESSE_PLAYER, PDV, 2, 4, creerImage(PATH_PLAYER)); jeu.addBlock(player); } private ImageView creerImage(String source){ ImageView imageView = new ImageView(source); imageView.setFitHeight(TAILLE); imageView.setPreserveRatio(true); return imageView; } public void commencer(){ ( new Thread(creerEnnemi) ).start(); } public void addTir(){ tir = new Tir(TAILLE, VITESSE_TIR, PDV, player.getAbscisse(), player.getOrdonnee()-1, creerImage(PATH_TIR)); new TaskBlock(tir, jeu); jeu.addBlock(tir); } public void movePlayer(Deplacer d){ switch (d){ case GAUCHE: if ( player.getAbscisse() > DEBUT_FENETRE ) player.deplacer(d); break; case DROITE: if ( player.getAbscisse() < LARGEUR-1 ) player.deplacer(d); break; } jeu.showBlock(player); } }
2,386
0.601425
0.5943
82
28.109756
23.777426
125
false
false
0
0
0
0
0
0
0.743902
false
false
13
67c1af9b0b2be66bead76e9e640c2da7a3d019ce
8,495,445,314,855
7c646abb88e786356b2616e14b75940244e408a6
/src/org/cadbox/j2d/scale/core/unit/UnitTranslator.java
f5cece7ff50c1aff2af1d43803ae4925515833f3
[]
no_license
shaiknoorahamed/Psi-Cad
https://github.com/shaiknoorahamed/Psi-Cad
dbbc6d4dc57f835beddc563eb3a9164403edfe05
f62749a8a09d0d15f27dd5d035cc6fcc24a8383a
refs/heads/master
2016-09-01T20:25:22.194000
2014-04-16T01:07:53
2014-04-16T01:07:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* 1: */ package org.cadbox.j2d.scale.core.unit; /* 2: */ /* 3: */ import java.awt.Toolkit; /* 4: */ /* 5: */ public class UnitTranslator /* 6: */ { /* 7: */ public static final double oneInch = 2.54D; /* 8: */ /* 9: */ public static MmUnit inchToMilimetor(InchUnit unit) /* 10: */ { /* 11:41 */ return new MmUnit(unit.getValue() * 2.54D * 10.0D); /* 12: */ } /* 13: */ /* 14: */ public static InchUnit milimetorToInch(MmUnit unit) /* 15: */ { /* 16:45 */ double tmp = unit.getValue() / 25.399999999999999D; /* 17:46 */ tmp = Math.round(tmp * 1000.0D) / 1000.0D; /* 18:47 */ return new InchUnit(tmp); /* 19: */ } /* 20: */ /* 21: */ public static double milimetorToPixel(MmUnit unit) /* 22: */ { /* 23:51 */ int dpi = Toolkit.getDefaultToolkit().getScreenResolution(); /* 24:52 */ InchUnit inch = milimetorToInch(unit); /* 25:53 */ return inch.getValue() * dpi; /* 26: */ } /* 27: */ /* 28: */ public static InchUnit pixelToInch(double unit) /* 29: */ { /* 30:57 */ int dpi = Toolkit.getDefaultToolkit().getScreenResolution(); /* 31:58 */ return new InchUnit(unit / dpi); /* 32: */ } /* 33: */ /* 34: */ public static MmUnit pixelToMilemetor(double unit) /* 35: */ { /* 36:62 */ int dpi = Toolkit.getDefaultToolkit().getScreenResolution(); /* 37:63 */ return inchToMilimetor(new InchUnit(unit / dpi)); /* 38: */ } /* 39: */ /* 40: */ public static double inchToPixel(InchUnit unit) /* 41: */ { /* 42:67 */ int dpi = Toolkit.getDefaultToolkit().getScreenResolution(); /* 43:68 */ return unit.getValue() * dpi; /* 44: */ } /* 45: */ /* 46: */ public static double lengthUnitToPixel(LengthUnit unit) /* 47: */ { /* 48:72 */ if ((unit instanceof MmUnit)) { /* 49:73 */ return milimetorToPixel((MmUnit)unit); /* 50: */ } /* 51:75 */ if ((unit instanceof InchUnit)) { /* 52:76 */ return inchToPixel((InchUnit)unit); /* 53: */ } /* 54:78 */ throw new IllegalArgumentException("Only mm or inch available!!!"); /* 55: */ } /* 56: */ /* 57: */ public static void main(String[] args) {} /* 58: */ } /* Location: C:\Users\kul_mut\Downloads\CADBox.2D-1.0.0\CADBox.2D\CADBox.2D.jar * Qualified Name: org.cadbox.j2d.scale.core.unit.UnitTranslator * JD-Core Version: 0.7.0.1 */
UTF-8
Java
2,495
java
UnitTranslator.java
Java
[ { "context": " 58: */ }\r\n\r\n\r\r\n/* Location: C:\\Users\\kul_mut\\Downloads\\CADBox.2D-1.0.0\\CADBox.2D\\CADBox.2D.jar", "end": 2335, "score": 0.9993495345115662, "start": 2328, "tag": "USERNAME", "value": "kul_mut" } ]
null
[]
/* 1: */ package org.cadbox.j2d.scale.core.unit; /* 2: */ /* 3: */ import java.awt.Toolkit; /* 4: */ /* 5: */ public class UnitTranslator /* 6: */ { /* 7: */ public static final double oneInch = 2.54D; /* 8: */ /* 9: */ public static MmUnit inchToMilimetor(InchUnit unit) /* 10: */ { /* 11:41 */ return new MmUnit(unit.getValue() * 2.54D * 10.0D); /* 12: */ } /* 13: */ /* 14: */ public static InchUnit milimetorToInch(MmUnit unit) /* 15: */ { /* 16:45 */ double tmp = unit.getValue() / 25.399999999999999D; /* 17:46 */ tmp = Math.round(tmp * 1000.0D) / 1000.0D; /* 18:47 */ return new InchUnit(tmp); /* 19: */ } /* 20: */ /* 21: */ public static double milimetorToPixel(MmUnit unit) /* 22: */ { /* 23:51 */ int dpi = Toolkit.getDefaultToolkit().getScreenResolution(); /* 24:52 */ InchUnit inch = milimetorToInch(unit); /* 25:53 */ return inch.getValue() * dpi; /* 26: */ } /* 27: */ /* 28: */ public static InchUnit pixelToInch(double unit) /* 29: */ { /* 30:57 */ int dpi = Toolkit.getDefaultToolkit().getScreenResolution(); /* 31:58 */ return new InchUnit(unit / dpi); /* 32: */ } /* 33: */ /* 34: */ public static MmUnit pixelToMilemetor(double unit) /* 35: */ { /* 36:62 */ int dpi = Toolkit.getDefaultToolkit().getScreenResolution(); /* 37:63 */ return inchToMilimetor(new InchUnit(unit / dpi)); /* 38: */ } /* 39: */ /* 40: */ public static double inchToPixel(InchUnit unit) /* 41: */ { /* 42:67 */ int dpi = Toolkit.getDefaultToolkit().getScreenResolution(); /* 43:68 */ return unit.getValue() * dpi; /* 44: */ } /* 45: */ /* 46: */ public static double lengthUnitToPixel(LengthUnit unit) /* 47: */ { /* 48:72 */ if ((unit instanceof MmUnit)) { /* 49:73 */ return milimetorToPixel((MmUnit)unit); /* 50: */ } /* 51:75 */ if ((unit instanceof InchUnit)) { /* 52:76 */ return inchToPixel((InchUnit)unit); /* 53: */ } /* 54:78 */ throw new IllegalArgumentException("Only mm or inch available!!!"); /* 55: */ } /* 56: */ /* 57: */ public static void main(String[] args) {} /* 58: */ } /* Location: C:\Users\kul_mut\Downloads\CADBox.2D-1.0.0\CADBox.2D\CADBox.2D.jar * Qualified Name: org.cadbox.j2d.scale.core.unit.UnitTranslator * JD-Core Version: 0.7.0.1 */
2,495
0.534669
0.458116
68
34.779411
25.931383
89
false
false
0
0
0
0
0
0
0.279412
false
false
13
28a6fb498f2e332eceb5b3e51096025e3bdbe950
14,027,363,227,002
b810802c11b8b13596bcc38ebce43ab3803f0762
/dpcode_public/src/abstractfactory/ProductA3.java
50ee22480c683c6008e21123c3d1749cc115d8b5
[]
no_license
Ni2014/MyAndroid
https://github.com/Ni2014/MyAndroid
b034f5f035c2c816d6f79dd576e224a9901be818
4c9e64c0b67dcaac7b35169e297f31ca8058d55c
refs/heads/master
2023-03-08T02:27:06.863000
2023-02-28T15:49:24
2023-02-28T15:49:24
40,481,629
17
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package abstractfactory; /**ๆ‰ฉๅฑ•ๆ–ฐ็š„ไบงๅ“ๆ— 3็ณปๅˆ— A3 * Created by Administrator on 2017/4/26. */ public class ProductA3 implements IProductA { @Override public void demo() { System.out.println("A3"); } }
UTF-8
Java
235
java
ProductA3.java
Java
[ { "context": " abstractfactory;\n\n/**ๆ‰ฉๅฑ•ๆ–ฐ็š„ไบงๅ“ๆ— 3็ณปๅˆ— A3\n * Created by Administrator on 2017/4/26.\n */\npublic class ProductA3 implemen", "end": 71, "score": 0.44731444120407104, "start": 58, "tag": "USERNAME", "value": "Administrator" } ]
null
[]
package abstractfactory; /**ๆ‰ฉๅฑ•ๆ–ฐ็š„ไบงๅ“ๆ— 3็ณปๅˆ— A3 * Created by Administrator on 2017/4/26. */ public class ProductA3 implements IProductA { @Override public void demo() { System.out.println("A3"); } }
235
0.663594
0.612903
11
18.727272
15.321351
45
false
false
0
0
0
0
0
0
0.181818
false
false
13
4876ab9c23c24e4e0f6dddee7e00cc6b42a66db1
14,027,363,227,579
92fb24dc611ccaab1098d25343e3d1e9256045b8
/javase/src/main/java/com/xicheng/javase/annotation/controller/AnnotationController.java
803b2261a8082f6ac630384cb03dda171a1d4005
[]
no_license
xianhaiGitHub/woodencottage
https://github.com/xianhaiGitHub/woodencottage
23813b4d2f788b979d70464ca67ff08044b6d3c7
7059cbe208a05461a93aff69b2364cc3ac6afa6a
refs/heads/master
2020-06-05T16:31:46.521000
2019-05-09T05:06:59
2019-05-09T05:06:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xicheng.javase.annotation.controller; import com.xicheng.javase.annotation.common.MyAnnotation; import org.junit.Test; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * @author xichengxml * @date 2018/12/27 * @description */ public class AnnotationController { @Test public void test01() throws Exception{ Class<?> loadClass = AnnotationController.class.getClassLoader().loadClass("com.xicheng.javase.annotation.service.impl.AnnotationServiceImpl"); Method[] methods = loadClass.getMethods(); for (int i = 0; i < methods.length; i++) { Annotation[] declaredAnnotations = methods[i].getDeclaredAnnotations(); for (int j = 0; j < declaredAnnotations.length; j++) { System.out.println(declaredAnnotations); } if (methods[i].isAnnotationPresent(MyAnnotation.class)) { MyAnnotation annotation = methods[i].getAnnotation(MyAnnotation.class); int anInt = annotation.getInt(); String string = annotation.getString(); System.out.println(anInt + ":" + string); } } } }
UTF-8
Java
1,192
java
AnnotationController.java
Java
[ { "context": ";\nimport java.lang.reflect.Method;\n\n/**\n * @author xichengxml\n * @date 2018/12/27\n * @description\n */\npublic cl", "end": 232, "score": 0.9996777176856995, "start": 222, "tag": "USERNAME", "value": "xichengxml" } ]
null
[]
package com.xicheng.javase.annotation.controller; import com.xicheng.javase.annotation.common.MyAnnotation; import org.junit.Test; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * @author xichengxml * @date 2018/12/27 * @description */ public class AnnotationController { @Test public void test01() throws Exception{ Class<?> loadClass = AnnotationController.class.getClassLoader().loadClass("com.xicheng.javase.annotation.service.impl.AnnotationServiceImpl"); Method[] methods = loadClass.getMethods(); for (int i = 0; i < methods.length; i++) { Annotation[] declaredAnnotations = methods[i].getDeclaredAnnotations(); for (int j = 0; j < declaredAnnotations.length; j++) { System.out.println(declaredAnnotations); } if (methods[i].isAnnotationPresent(MyAnnotation.class)) { MyAnnotation annotation = methods[i].getAnnotation(MyAnnotation.class); int anInt = annotation.getInt(); String string = annotation.getString(); System.out.println(anInt + ":" + string); } } } }
1,192
0.645134
0.635067
33
35.121212
32.855751
151
false
false
0
0
0
0
0
0
0.515152
false
false
13
88fb7fac7c47e0ba54a86820dd0c3cad45f969b9
14,027,363,228,778
6c4faf2dc803629e77a94406e5da4cef9a62fb52
/Module1/src/Module1/IsoTriangle.java
eada629d7d5ce991b6d17c6c16b70f69576ab7c8
[]
no_license
bsmith3541/TW101
https://github.com/bsmith3541/TW101
f9d525589adc37225576641e5b4d820e950d8f27
f6a1fc5a979313e224e6c350e66154a81a87041a
refs/heads/master
2016-09-07T19:08:08.242000
2014-07-25T17:10:07
2014-07-25T17:10:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Module1; /** * Created by brandonsmith on 7/16/14. */ public class IsoTriangle { public void print_triangle(int base) { for(int i = 0; i < base; i++) { print_spaces(i+1, base); print_stars(i+1); print_spaces(i+1, base); System.out.println(); } } private void print_spaces(int line, int base) { // always print the base - line of spaces // e.g. line 1 of a base 3 has 2 spaces for(int i = 0; i < base - line; i++) { System.out.print(" "); } } private void print_stars(int line) { // always print 2 * line - 1 stars for (int i = 0; i < (2*line) -1; i++) { System.out.print("*"); } } public static void main(String[] args) { IsoTriangle triangle = new IsoTriangle(); triangle.print_triangle(3); } }
UTF-8
Java
902
java
IsoTriangle.java
Java
[ { "context": "package Module1;\n\n/**\n * Created by brandonsmith on 7/16/14.\n */\npublic class IsoTriangle {\n pu", "end": 48, "score": 0.9985677599906921, "start": 36, "tag": "USERNAME", "value": "brandonsmith" } ]
null
[]
package Module1; /** * Created by brandonsmith on 7/16/14. */ public class IsoTriangle { public void print_triangle(int base) { for(int i = 0; i < base; i++) { print_spaces(i+1, base); print_stars(i+1); print_spaces(i+1, base); System.out.println(); } } private void print_spaces(int line, int base) { // always print the base - line of spaces // e.g. line 1 of a base 3 has 2 spaces for(int i = 0; i < base - line; i++) { System.out.print(" "); } } private void print_stars(int line) { // always print 2 * line - 1 stars for (int i = 0; i < (2*line) -1; i++) { System.out.print("*"); } } public static void main(String[] args) { IsoTriangle triangle = new IsoTriangle(); triangle.print_triangle(3); } }
902
0.507761
0.485588
35
24.771429
18.394232
51
false
false
0
0
0
0
0
0
0.514286
false
false
13
046ae236031e0a5c37bdc39f5be47594b66fdd23
7,206,955,180,430
0bfb7489fbbf45362f89753666fd73be72011701
/src/main/java/com/ogbu/unprg/sisbu/dao/impl/RespuestaEvaluacion2DAOImpl.java
9494997efaf0225b0464608f4cdcd16e078d9de2
[]
no_license
jamescarrillo/sisbu-backend
https://github.com/jamescarrillo/sisbu-backend
ae935ab4ba3fac215a4411edd8bc460bec9adc37
d123da7721cbf3bed704dedf1a3b5a765124d7ce
refs/heads/master
2020-04-17T21:05:01.472000
2020-03-13T00:03:16
2020-03-13T00:03:16
166,933,515
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ogbu.unprg.sisbu.dao.impl; import com.ogbu.unprg.sisbu.dao.IRespuestaEvaluacion2DAO; import com.ogbu.unprg.sisbu.model.Alternativa; import com.ogbu.unprg.sisbu.model.AreaPsi; import com.ogbu.unprg.sisbu.model.Pregunta; import com.ogbu.unprg.sisbu.model.SubAreaPsi; import com.ogbu.unprg.sisbu.model.RespuestaEvaluacion2; import com.ogbu.unprg.sisbu.utilities.BeanPagination; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Logger; /** * * @author James Carrillo */ public class RespuestaEvaluacion2DAOImpl implements IRespuestaEvaluacion2DAO { private static final Logger LOG = Logger.getLogger(RespuestaEvaluacion2DAOImpl.class.getName()); public RespuestaEvaluacion2DAOImpl() { } @Override public String add(List<RespuestaEvaluacion2> list_respuestas, Long idevaluacion_atendido, Connection conn) throws SQLException { String res = ""; StringBuilder sSQL = new StringBuilder(); sSQL.append("INSERT INTO `respuesta_evaluacion2`("); sSQL.append("IDEVALUACION_ATENDIDO,"); sSQL.append("IDPREGUNTA,"); sSQL.append("IDALTERNATIVA,"); sSQL.append("TEXTO"); sSQL.append(")"); sSQL.append("VALUES(?,?,?,?)"); try (PreparedStatement pst = conn.prepareStatement(sSQL.toString())) { for (RespuestaEvaluacion2 re : list_respuestas) { pst.setLong(1, idevaluacion_atendido); pst.setInt(2, re.getPregunta().getIdpregunta()); if (re.getPregunta().getTipo_respuesta() == 1) { pst.setString(3, null); } else { pst.setLong(3, re.getAlternativa().getIdalternativa()); } pst.setString(4, re.getTexto()); pst.executeUpdate(); } res = "ok"; } catch (SQLException e) { throw e; } return res; } @Override public BeanPagination getPagination(HashMap<String, Object> parameters, Connection conn) throws SQLException { BeanPagination beanPagination = new BeanPagination(); List<RespuestaEvaluacion2> list = new ArrayList<>(); PreparedStatement pst; ResultSet rs; try { StringBuilder sSQL = new StringBuilder(); sSQL.append("SELECT COUNT(RES.IDRESPUESTA_EVALUACION2) AS COUNT FROM "); sSQL.append("`respuesta_evaluacion2` AS RES "); sSQL.append("LEFT JOIN `pregunta` AS PRE ON RES.IDPREGUNTA=PRE.IDPREGUNTA "); sSQL.append("LEFT JOIN `alternativa` AS ALT ON ALT.IDALTERNATIVA=RES.IDALTERNATIVA "); sSQL.append("WHERE "); sSQL.append("RES.IDEVALUACION_ATENDIDO = ? "); pst = conn.prepareStatement(sSQL.toString()); pst.setLong(1, Long.parseLong(String.valueOf(parameters.get("IDEVALUACION")))); LOG.info(pst.toString()); rs = pst.executeQuery(); while (rs.next()) { beanPagination.setCount_filter(rs.getLong("COUNT")); if (rs.getInt("COUNT") > 0) { sSQL.setLength(0); sSQL.append("SELECT al.IDALTERNATIVA, al.DESCRIPCION AS ALTER_DESCRIPCION,al.VALOR,"); sSQL.append("sub.*,area.nombre as areapsi,pre.enunciado,pre.IDPREGUNTA,pre.ITEM_NEGATIVO "); sSQL.append("FROM "); sSQL.append("`respuesta_evaluacion2` AS RES "); sSQL.append("LEFT JOIN `alternativa` AS al ON AL.IDALTERNATIVA=RES.IDALTERNATIVA "); sSQL.append("LEFT JOIN `pregunta` AS PRE ON RES.IDPREGUNTA=PRE.IDPREGUNTA "); sSQL.append("LEFT JOIN `subarea_psi` AS sub ON sub.idsubarea_psi=pre.idsubarea_psi "); sSQL.append("LEFT JOIN `area_psi` AS area ON area.idarea_psi=sub.idarea_psi "); sSQL.append("WHERE "); sSQL.append("RES.IDEVALUACION_ATENDIDO = ? "); sSQL.append(String.valueOf(parameters.get("SQL_ORDERS"))); pst = conn.prepareStatement(sSQL.toString()); pst.setLong(1, Long.parseLong(String.valueOf(parameters.get("IDEVALUACION")))); LOG.info(pst.toString()); rs = pst.executeQuery(); while (rs.next()) { RespuestaEvaluacion2 evaluacion = new RespuestaEvaluacion2(); Pregunta pregunta = new Pregunta(); pregunta.setIdpregunta(rs.getInt("IDPREGUNTA")); pregunta.setEnunciado(rs.getString("ENUNCIADO")); pregunta.setItem_negativo(rs.getString("ITEM_NEGATIVO")); SubAreaPsi subAreaPsi =new SubAreaPsi(); subAreaPsi.setIdsubarea_psi(rs.getInt("IDSUBAREA_PSI")); subAreaPsi.setNombre(rs.getString("NOMBRE")); subAreaPsi.setDescripcion(rs.getString("DESCRIPCION")); subAreaPsi.setAbreviatura(rs.getString("ABREVIATURA")); subAreaPsi.setPuntaje_minimo(rs.getInt("PUNTAJE_MINIMO")); subAreaPsi.setPuntaje_maximo(rs.getInt("PUNTAJE_MAXIMO")); subAreaPsi.setMedia(rs.getDouble("MEDIA")); subAreaPsi.setDs(rs.getDouble("DS")); AreaPsi areaPsi =new AreaPsi(); areaPsi.setIdarea_psi(rs.getInt("IDAREA_PSI")); areaPsi.setNombre(rs.getString("AREAPSI")); subAreaPsi.setArea_psi(areaPsi); pregunta.setSubarea_psi(subAreaPsi); evaluacion.setPregunta(pregunta); Alternativa alternativa = new Alternativa(); alternativa.setIdalternativa(rs.getLong("IDALTERNATIVA")); alternativa.setDescripcion(rs.getString("ALTER_DESCRIPCION")); alternativa.setValor(rs.getShort("VALOR")); evaluacion.setAlternativa(alternativa); list.add(evaluacion); } } } beanPagination.setList(list); rs.close(); pst.close(); } catch (SQLException ex) { throw ex; } return beanPagination; } @Override public String update(List<RespuestaEvaluacion2> list_respuestas, Connection conn) throws SQLException { String res = ""; StringBuilder sSQL = new StringBuilder(); sSQL.append("UPDATE `respuesta_evaluacion2` SET "); sSQL.append("IDPREGUNTA = ?,"); sSQL.append("IDALTERNATIVA = ?,"); sSQL.append("TEXTO = ? "); sSQL.append("WHERE IDRESPUESTA_EVALUACION2 = ? "); try (PreparedStatement pst = conn.prepareStatement(sSQL.toString())) { for (RespuestaEvaluacion2 re : list_respuestas) { pst.setInt(1, re.getPregunta().getIdpregunta()); if (re.getPregunta().getTipo_respuesta() == 1) { pst.setString(2, null); } else { pst.setLong(2, re.getAlternativa().getIdalternativa()); } pst.setString(3, re.getTexto()); pst.setLong(4, re.getIdrespuesta_evaluacion2()); pst.executeUpdate(); } res = "ok"; } catch (SQLException e) { throw e; } return res; } }
UTF-8
Java
8,129
java
RespuestaEvaluacion2DAOImpl.java
Java
[ { "context": "t java.util.logging.Logger;\r\n\r\n/**\r\n *\r\n * @author James Carrillo\r\n */\r\npublic class RespuestaEvaluacion2DAOImpl im", "end": 861, "score": 0.9997388124465942, "start": 847, "tag": "NAME", "value": "James Carrillo" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ogbu.unprg.sisbu.dao.impl; import com.ogbu.unprg.sisbu.dao.IRespuestaEvaluacion2DAO; import com.ogbu.unprg.sisbu.model.Alternativa; import com.ogbu.unprg.sisbu.model.AreaPsi; import com.ogbu.unprg.sisbu.model.Pregunta; import com.ogbu.unprg.sisbu.model.SubAreaPsi; import com.ogbu.unprg.sisbu.model.RespuestaEvaluacion2; import com.ogbu.unprg.sisbu.utilities.BeanPagination; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Logger; /** * * @author <NAME> */ public class RespuestaEvaluacion2DAOImpl implements IRespuestaEvaluacion2DAO { private static final Logger LOG = Logger.getLogger(RespuestaEvaluacion2DAOImpl.class.getName()); public RespuestaEvaluacion2DAOImpl() { } @Override public String add(List<RespuestaEvaluacion2> list_respuestas, Long idevaluacion_atendido, Connection conn) throws SQLException { String res = ""; StringBuilder sSQL = new StringBuilder(); sSQL.append("INSERT INTO `respuesta_evaluacion2`("); sSQL.append("IDEVALUACION_ATENDIDO,"); sSQL.append("IDPREGUNTA,"); sSQL.append("IDALTERNATIVA,"); sSQL.append("TEXTO"); sSQL.append(")"); sSQL.append("VALUES(?,?,?,?)"); try (PreparedStatement pst = conn.prepareStatement(sSQL.toString())) { for (RespuestaEvaluacion2 re : list_respuestas) { pst.setLong(1, idevaluacion_atendido); pst.setInt(2, re.getPregunta().getIdpregunta()); if (re.getPregunta().getTipo_respuesta() == 1) { pst.setString(3, null); } else { pst.setLong(3, re.getAlternativa().getIdalternativa()); } pst.setString(4, re.getTexto()); pst.executeUpdate(); } res = "ok"; } catch (SQLException e) { throw e; } return res; } @Override public BeanPagination getPagination(HashMap<String, Object> parameters, Connection conn) throws SQLException { BeanPagination beanPagination = new BeanPagination(); List<RespuestaEvaluacion2> list = new ArrayList<>(); PreparedStatement pst; ResultSet rs; try { StringBuilder sSQL = new StringBuilder(); sSQL.append("SELECT COUNT(RES.IDRESPUESTA_EVALUACION2) AS COUNT FROM "); sSQL.append("`respuesta_evaluacion2` AS RES "); sSQL.append("LEFT JOIN `pregunta` AS PRE ON RES.IDPREGUNTA=PRE.IDPREGUNTA "); sSQL.append("LEFT JOIN `alternativa` AS ALT ON ALT.IDALTERNATIVA=RES.IDALTERNATIVA "); sSQL.append("WHERE "); sSQL.append("RES.IDEVALUACION_ATENDIDO = ? "); pst = conn.prepareStatement(sSQL.toString()); pst.setLong(1, Long.parseLong(String.valueOf(parameters.get("IDEVALUACION")))); LOG.info(pst.toString()); rs = pst.executeQuery(); while (rs.next()) { beanPagination.setCount_filter(rs.getLong("COUNT")); if (rs.getInt("COUNT") > 0) { sSQL.setLength(0); sSQL.append("SELECT al.IDALTERNATIVA, al.DESCRIPCION AS ALTER_DESCRIPCION,al.VALOR,"); sSQL.append("sub.*,area.nombre as areapsi,pre.enunciado,pre.IDPREGUNTA,pre.ITEM_NEGATIVO "); sSQL.append("FROM "); sSQL.append("`respuesta_evaluacion2` AS RES "); sSQL.append("LEFT JOIN `alternativa` AS al ON AL.IDALTERNATIVA=RES.IDALTERNATIVA "); sSQL.append("LEFT JOIN `pregunta` AS PRE ON RES.IDPREGUNTA=PRE.IDPREGUNTA "); sSQL.append("LEFT JOIN `subarea_psi` AS sub ON sub.idsubarea_psi=pre.idsubarea_psi "); sSQL.append("LEFT JOIN `area_psi` AS area ON area.idarea_psi=sub.idarea_psi "); sSQL.append("WHERE "); sSQL.append("RES.IDEVALUACION_ATENDIDO = ? "); sSQL.append(String.valueOf(parameters.get("SQL_ORDERS"))); pst = conn.prepareStatement(sSQL.toString()); pst.setLong(1, Long.parseLong(String.valueOf(parameters.get("IDEVALUACION")))); LOG.info(pst.toString()); rs = pst.executeQuery(); while (rs.next()) { RespuestaEvaluacion2 evaluacion = new RespuestaEvaluacion2(); Pregunta pregunta = new Pregunta(); pregunta.setIdpregunta(rs.getInt("IDPREGUNTA")); pregunta.setEnunciado(rs.getString("ENUNCIADO")); pregunta.setItem_negativo(rs.getString("ITEM_NEGATIVO")); SubAreaPsi subAreaPsi =new SubAreaPsi(); subAreaPsi.setIdsubarea_psi(rs.getInt("IDSUBAREA_PSI")); subAreaPsi.setNombre(rs.getString("NOMBRE")); subAreaPsi.setDescripcion(rs.getString("DESCRIPCION")); subAreaPsi.setAbreviatura(rs.getString("ABREVIATURA")); subAreaPsi.setPuntaje_minimo(rs.getInt("PUNTAJE_MINIMO")); subAreaPsi.setPuntaje_maximo(rs.getInt("PUNTAJE_MAXIMO")); subAreaPsi.setMedia(rs.getDouble("MEDIA")); subAreaPsi.setDs(rs.getDouble("DS")); AreaPsi areaPsi =new AreaPsi(); areaPsi.setIdarea_psi(rs.getInt("IDAREA_PSI")); areaPsi.setNombre(rs.getString("AREAPSI")); subAreaPsi.setArea_psi(areaPsi); pregunta.setSubarea_psi(subAreaPsi); evaluacion.setPregunta(pregunta); Alternativa alternativa = new Alternativa(); alternativa.setIdalternativa(rs.getLong("IDALTERNATIVA")); alternativa.setDescripcion(rs.getString("ALTER_DESCRIPCION")); alternativa.setValor(rs.getShort("VALOR")); evaluacion.setAlternativa(alternativa); list.add(evaluacion); } } } beanPagination.setList(list); rs.close(); pst.close(); } catch (SQLException ex) { throw ex; } return beanPagination; } @Override public String update(List<RespuestaEvaluacion2> list_respuestas, Connection conn) throws SQLException { String res = ""; StringBuilder sSQL = new StringBuilder(); sSQL.append("UPDATE `respuesta_evaluacion2` SET "); sSQL.append("IDPREGUNTA = ?,"); sSQL.append("IDALTERNATIVA = ?,"); sSQL.append("TEXTO = ? "); sSQL.append("WHERE IDRESPUESTA_EVALUACION2 = ? "); try (PreparedStatement pst = conn.prepareStatement(sSQL.toString())) { for (RespuestaEvaluacion2 re : list_respuestas) { pst.setInt(1, re.getPregunta().getIdpregunta()); if (re.getPregunta().getTipo_respuesta() == 1) { pst.setString(2, null); } else { pst.setLong(2, re.getAlternativa().getIdalternativa()); } pst.setString(3, re.getTexto()); pst.setLong(4, re.getIdrespuesta_evaluacion2()); pst.executeUpdate(); } res = "ok"; } catch (SQLException e) { throw e; } return res; } }
8,121
0.563538
0.559109
170
45.817646
29.34033
132
false
false
0
0
0
0
0
0
0.876471
false
false
13
cafd5b5afdaa5551c1e1511c329eb61da0f00517
4,406,636,445,710
849805e8fa963de6c48b0292e822c1823d71ade3
/src/main/java/it/course/myblogc3/payload/response/PostResponseWithPreferredTags.java
875eb222c87076a9fbd8885b6a66d7753da158b0
[]
no_license
Monone96/Blog-Application
https://github.com/Monone96/Blog-Application
dd24fce1b2e380672786ce2e45bb48a64d979fff
f115bb32a174336f0a9265aa5dd1ec15616663ef
refs/heads/main
2023-01-14T13:22:46.960000
2020-11-18T14:20:39
2020-11-18T14:20:39
313,954,751
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.course.myblogc3.payload.response; import java.util.Date; import it.course.myblogc3.entity.Post; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class PostResponseWithPreferredTags { private Long id; private String title; private Long authorId; private String authorName; private Date updatedAt; private String[] tagNames; public static PostResponseWithPreferredTags createFromEntity(Post p) { return new PostResponseWithPreferredTags( p.getId(), p.getTitle(), p.getAuthor().getId(), p.getAuthor().getUsername(), p.getUpdatedAt(), p.getTags().stream().map(t -> t.getTagName()).toArray(String[]::new) ); } }
UTF-8
Java
758
java
PostResponseWithPreferredTags.java
Java
[]
null
[]
package it.course.myblogc3.payload.response; import java.util.Date; import it.course.myblogc3.entity.Post; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class PostResponseWithPreferredTags { private Long id; private String title; private Long authorId; private String authorName; private Date updatedAt; private String[] tagNames; public static PostResponseWithPreferredTags createFromEntity(Post p) { return new PostResponseWithPreferredTags( p.getId(), p.getTitle(), p.getAuthor().getId(), p.getAuthor().getUsername(), p.getUpdatedAt(), p.getTags().stream().map(t -> t.getTagName()).toArray(String[]::new) ); } }
758
0.745383
0.742744
33
21.969696
19.355501
72
false
false
0
0
0
0
0
0
1.818182
false
false
13
47cfe5c38a794fcdd85ce3bc7a78680d244c5b88
34,205,119,574,900
ed4c9d72d80a4df9f6dbe28262e935e6abfeee70
/designPattern/absfactory/AbsFactory.java
f198d412d2e87dbc6015619fe36ca0c31271fea0
[]
no_license
zdkswd/designPattern
https://github.com/zdkswd/designPattern
2d994d1540eab8826e5c072ba2ff8c171afde6a5
e59d73c7fb2418c5c146988d5e68668d4e4653cb
refs/heads/master
2020-07-07T12:43:42.847000
2019-08-20T11:23:25
2019-08-20T11:23:25
203,351,124
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package zdk.absfactory; //ๆŠฝ่ฑกๅทฅๅŽ‚ๆจกๅผ็š„ๆŠฝ่ฑกๅฑ‚๏ผˆๆŽฅๅฃ๏ผ‰ public interface AbsFactory { //่ฎฉไธ‹้ข็š„ๅทฅๅŽ‚ๅญ็ฑปๆฅๅ…ทไฝ“ๅฎž็Žฐ public Pizza createPizza(String pizzaType); }
UTF-8
Java
196
java
AbsFactory.java
Java
[]
null
[]
package zdk.absfactory; //ๆŠฝ่ฑกๅทฅๅŽ‚ๆจกๅผ็š„ๆŠฝ่ฑกๅฑ‚๏ผˆๆŽฅๅฃ๏ผ‰ public interface AbsFactory { //่ฎฉไธ‹้ข็š„ๅทฅๅŽ‚ๅญ็ฑปๆฅๅ…ทไฝ“ๅฎž็Žฐ public Pizza createPizza(String pizzaType); }
196
0.753521
0.753521
7
19.285715
15.0875
47
false
false
0
0
0
0
0
0
0.285714
false
false
13
39d35a9e631ea2eb5f578714b894c0929ad98aed
34,291,018,908,803
2fcf0343a436b1ff084d9ab3ee7b801ac9867919
/testrestapi/src/main/java/com/test/restservice/repo/TldRepository.java
081892ba09698702cb959510f447a6aabae7346c
[]
no_license
iryndin/misc
https://github.com/iryndin/misc
c26c567f7f4a5521bb16d299cc6f0da515c0e7fd
dfac1154900ff979bde7e738fb6735999f50b305
refs/heads/master
2022-12-23T17:33:07.613000
2020-02-05T01:23:05
2020-02-05T01:23:05
19,784,932
1
4
null
false
2022-12-14T20:29:28
2014-05-14T15:26:22
2020-02-05T01:23:13
2022-12-14T20:29:25
245
1
4
27
Java
false
false
package com.test.restservice.repo; import com.test.restservice.model.Tld; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface TldRepository extends AppBaseRepository<Tld, Long> { List<Tld> findAllByOrderByPriceAsc(); }
UTF-8
Java
276
java
TldRepository.java
Java
[]
null
[]
package com.test.restservice.repo; import com.test.restservice.model.Tld; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface TldRepository extends AppBaseRepository<Tld, Long> { List<Tld> findAllByOrderByPriceAsc(); }
276
0.807971
0.807971
11
24.09091
22.69343
69
false
false
0
0
0
0
0
0
0.545455
false
false
13
162ad820e13f362a1d9e158eb8878fa757e38ef1
18,451,179,555,015
e2f74fe1c50f0068d77bba2b913c34f98913f7d4
/src/main/java/com/github/microprograms/qipai_exchange_manager_api/public_api/User_QueryFollowerList_Api.java
cd59251b537ebdb5150fa47efbcef43cf503c4de
[]
no_license
187383327/qipai-exchange-manager-api
https://github.com/187383327/qipai-exchange-manager-api
ff3c7c7cdff93c1de50559f5e05810729585b608
42fe2f008893cee1de5e32bcda32671a59a9aadb
refs/heads/master
2021-05-14T14:57:45.276000
2018-01-02T04:14:51
2018-01-02T04:14:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.microprograms.qipai_exchange_manager_api.public_api; import java.sql.Connection; import java.sql.ResultSet; import com.github.microprograms.ignite_utils.IgniteUtils; import com.github.microprograms.ignite_utils.sql.dml.Condition; import com.github.microprograms.ignite_utils.sql.dml.PagerRequest; import com.github.microprograms.ignite_utils.sql.dml.PagerResponse; import com.github.microprograms.ignite_utils.sql.dml.SelectCountSql; import com.github.microprograms.ignite_utils.sql.dml.SelectSql; import com.github.microprograms.ignite_utils.sql.dml.Sort; import com.github.microprograms.ignite_utils.sql.dml.Where; import com.github.microprograms.micro_api_runtime.annotation.MicroApiAnnotation; import com.github.microprograms.micro_api_runtime.model.Request; import com.github.microprograms.micro_api_runtime.model.Response; import com.github.microprograms.micro_entity_definition_runtime.annotation.Comment; import com.github.microprograms.micro_entity_definition_runtime.annotation.Required; import com.github.microprograms.qipai_exchange_manager_api.utils.Consts; @Comment(value = "็”จๆˆท - ๆŸฅ่ฏขๆˆ‘็š„้‚€่ฏทๅˆ—่กจ") @MicroApiAnnotation(type = "read", version = "v1.0.65") public class User_QueryFollowerList_Api { public static Response execute(Request request) throws Exception { Req req = (Req) request; Resp resp = new Resp(); PagerRequest pagerRequest = new PagerRequest(req.getPageIndex(), req.getPageSize()); try (Connection conn = IgniteUtils.getConnection(Consts.jdbc_url)) { String finalCondition = buildFinalCondition(req); ResultSet selectRs = conn.createStatement().executeQuery(new SelectSql(User.class).where(finalCondition).pager(pagerRequest).sorts(Sort.desc("dtCreate")).build()); resp.setData(IgniteUtils.getJavaObjectList(selectRs, User.class)); ResultSet selectCountRs = conn.createStatement().executeQuery(new SelectCountSql(User.class).where(finalCondition).build()); resp.setPager(new PagerResponse(pagerRequest, IgniteUtils.getCount(selectCountRs))); } return resp; } private static String buildFinalCondition(Req req) { String userId = req.getUserId(); Condition myLeaderId = null; switch(req.getLevel()) { case 1: myLeaderId = Condition.build("myLeaderId=", userId); break; case 2: myLeaderId = Condition.build("myLeaderId1=", userId); break; case 3: myLeaderId = Condition.build("myLeaderId2=", userId); break; default: myLeaderId = Condition.build("myLeaderId=", userId); break; } return Where.and(myLeaderId).toString(); } public static class Req extends Request { @Comment(value = "Token") @Required(value = true) private String token; public String getToken() { return token; } public void setToken(String token) { this.token = token; } @Comment(value = "้กต็ (ไปŽ0ๅผ€ๅง‹)") @Required(value = true) private Integer pageIndex; public Integer getPageIndex() { return pageIndex; } public void setPageIndex(Integer pageIndex) { this.pageIndex = pageIndex; } @Comment(value = "้กตๅคงๅฐ") @Required(value = true) private Integer pageSize; public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } @Comment(value = "็”จๆˆทID") @Required(value = false) private String userId; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Comment(value = "็ญ‰็บง(1ไธ€็บง,2ไบŒ็บง,3ไธ‰็บง)") @Required(value = false) private Integer level; public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } } public static class Resp extends Response { @Comment(value = "ๆˆ‘็š„้‚€่ฏทๅˆ—่กจ") @Required(value = true) private java.util.List<User> data; public java.util.List<User> getData() { return data; } public void setData(java.util.List<User> data) { this.data = data; } @Comment(value = "ๅˆ†้กต") @Required(value = true) private com.github.microprograms.ignite_utils.sql.dml.PagerResponse pager; public com.github.microprograms.ignite_utils.sql.dml.PagerResponse getPager() { return pager; } public void setPager(com.github.microprograms.ignite_utils.sql.dml.PagerResponse pager) { this.pager = pager; } } }
UTF-8
Java
5,054
java
User_QueryFollowerList_Api.java
Java
[]
null
[]
package com.github.microprograms.qipai_exchange_manager_api.public_api; import java.sql.Connection; import java.sql.ResultSet; import com.github.microprograms.ignite_utils.IgniteUtils; import com.github.microprograms.ignite_utils.sql.dml.Condition; import com.github.microprograms.ignite_utils.sql.dml.PagerRequest; import com.github.microprograms.ignite_utils.sql.dml.PagerResponse; import com.github.microprograms.ignite_utils.sql.dml.SelectCountSql; import com.github.microprograms.ignite_utils.sql.dml.SelectSql; import com.github.microprograms.ignite_utils.sql.dml.Sort; import com.github.microprograms.ignite_utils.sql.dml.Where; import com.github.microprograms.micro_api_runtime.annotation.MicroApiAnnotation; import com.github.microprograms.micro_api_runtime.model.Request; import com.github.microprograms.micro_api_runtime.model.Response; import com.github.microprograms.micro_entity_definition_runtime.annotation.Comment; import com.github.microprograms.micro_entity_definition_runtime.annotation.Required; import com.github.microprograms.qipai_exchange_manager_api.utils.Consts; @Comment(value = "็”จๆˆท - ๆŸฅ่ฏขๆˆ‘็š„้‚€่ฏทๅˆ—่กจ") @MicroApiAnnotation(type = "read", version = "v1.0.65") public class User_QueryFollowerList_Api { public static Response execute(Request request) throws Exception { Req req = (Req) request; Resp resp = new Resp(); PagerRequest pagerRequest = new PagerRequest(req.getPageIndex(), req.getPageSize()); try (Connection conn = IgniteUtils.getConnection(Consts.jdbc_url)) { String finalCondition = buildFinalCondition(req); ResultSet selectRs = conn.createStatement().executeQuery(new SelectSql(User.class).where(finalCondition).pager(pagerRequest).sorts(Sort.desc("dtCreate")).build()); resp.setData(IgniteUtils.getJavaObjectList(selectRs, User.class)); ResultSet selectCountRs = conn.createStatement().executeQuery(new SelectCountSql(User.class).where(finalCondition).build()); resp.setPager(new PagerResponse(pagerRequest, IgniteUtils.getCount(selectCountRs))); } return resp; } private static String buildFinalCondition(Req req) { String userId = req.getUserId(); Condition myLeaderId = null; switch(req.getLevel()) { case 1: myLeaderId = Condition.build("myLeaderId=", userId); break; case 2: myLeaderId = Condition.build("myLeaderId1=", userId); break; case 3: myLeaderId = Condition.build("myLeaderId2=", userId); break; default: myLeaderId = Condition.build("myLeaderId=", userId); break; } return Where.and(myLeaderId).toString(); } public static class Req extends Request { @Comment(value = "Token") @Required(value = true) private String token; public String getToken() { return token; } public void setToken(String token) { this.token = token; } @Comment(value = "้กต็ (ไปŽ0ๅผ€ๅง‹)") @Required(value = true) private Integer pageIndex; public Integer getPageIndex() { return pageIndex; } public void setPageIndex(Integer pageIndex) { this.pageIndex = pageIndex; } @Comment(value = "้กตๅคงๅฐ") @Required(value = true) private Integer pageSize; public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } @Comment(value = "็”จๆˆทID") @Required(value = false) private String userId; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Comment(value = "็ญ‰็บง(1ไธ€็บง,2ไบŒ็บง,3ไธ‰็บง)") @Required(value = false) private Integer level; public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } } public static class Resp extends Response { @Comment(value = "ๆˆ‘็š„้‚€่ฏทๅˆ—่กจ") @Required(value = true) private java.util.List<User> data; public java.util.List<User> getData() { return data; } public void setData(java.util.List<User> data) { this.data = data; } @Comment(value = "ๅˆ†้กต") @Required(value = true) private com.github.microprograms.ignite_utils.sql.dml.PagerResponse pager; public com.github.microprograms.ignite_utils.sql.dml.PagerResponse getPager() { return pager; } public void setPager(com.github.microprograms.ignite_utils.sql.dml.PagerResponse pager) { this.pager = pager; } } }
5,054
0.636692
0.634083
147
32.891155
29.363806
175
false
false
0
0
0
0
0
0
0.462585
false
false
13
dd02f1216ea56b7a8e19c58b9d5d70780a386d9a
32,315,333,988,191
262e2472f53fd4ebc9e52092a20ead9e0c2ce6cd
/OODesign/src/java/main/parkinglot/ParkingLevel.java
e3df1a41fec9831e82b87eb4135e19413f95f963
[]
no_license
kurteck/justforfun
https://github.com/kurteck/justforfun
91dd77e67e1299331cedc83fd8d8a117bd299fcf
a552664ef53cf582ed76228e093a6e264c64d0ab
refs/heads/master
2020-06-03T18:32:15.842000
2013-08-20T23:31:00
2013-08-20T23:31:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package parkinglot; import java.util.ArrayList; import java.util.List; public class ParkingLevel { private String id; private int capacity; private ParkingLot lot; private List<AccessGate> gates; private List<ParkingSpace> spaces; public ParkingLevel(String id, int capacity, ParkingLot lot) { this.id = id; this.lot = lot; this.gates = new ArrayList<AccessGate>(); this.spaces = new ArrayList<ParkingSpace>(capacity); this.capacity = capacity; } public String getId() { return id; } public int getOccupancy() { int occupancy = 0; for (ParkingSpace spot : spaces) { occupancy += spot.isOccupied() ? 1 : 0; } return occupancy; } public int getCapacity() { return capacity; } public ParkingSpace getParkingSpace(int i) { if ((i < 0) || (i > spaces.size())) { return null; } return spaces.get(i); } public boolean isGated() { return gates != null && gates.size() > 0; } public boolean isFull() { return getOccupancy() >= capacity; } public void closeAndlockGates() { for (AccessGate gate : gates) { gate.close(); gate.lock(); } } public void unlockAndOpenGates() { for (AccessGate gate : gates) { gate.unlock(); gate.open(); } } public boolean isAnyGateOpen() { if (gates.size() == 0) { return true; } for (AccessGate gate : gates) { if (gate.isOpen()) { return true; } } return false; } /** * Returns true if the given vehicle was * successfully parked in this ParkingSpace. * * @param v * @return */ protected boolean acceptVehicle(Vehicle v) { return lot.acceptVehicle(v) && isAnyGateOpen(); } public void addParkingSpace(ParkingSpace ps) { if (spaces.size() < capacity) { spaces.add(ps); } } public void addAccessGate(AccessGate gate) { gates.add(gate); } }
UTF-8
Java
1,853
java
ParkingLevel.java
Java
[]
null
[]
package parkinglot; import java.util.ArrayList; import java.util.List; public class ParkingLevel { private String id; private int capacity; private ParkingLot lot; private List<AccessGate> gates; private List<ParkingSpace> spaces; public ParkingLevel(String id, int capacity, ParkingLot lot) { this.id = id; this.lot = lot; this.gates = new ArrayList<AccessGate>(); this.spaces = new ArrayList<ParkingSpace>(capacity); this.capacity = capacity; } public String getId() { return id; } public int getOccupancy() { int occupancy = 0; for (ParkingSpace spot : spaces) { occupancy += spot.isOccupied() ? 1 : 0; } return occupancy; } public int getCapacity() { return capacity; } public ParkingSpace getParkingSpace(int i) { if ((i < 0) || (i > spaces.size())) { return null; } return spaces.get(i); } public boolean isGated() { return gates != null && gates.size() > 0; } public boolean isFull() { return getOccupancy() >= capacity; } public void closeAndlockGates() { for (AccessGate gate : gates) { gate.close(); gate.lock(); } } public void unlockAndOpenGates() { for (AccessGate gate : gates) { gate.unlock(); gate.open(); } } public boolean isAnyGateOpen() { if (gates.size() == 0) { return true; } for (AccessGate gate : gates) { if (gate.isOpen()) { return true; } } return false; } /** * Returns true if the given vehicle was * successfully parked in this ParkingSpace. * * @param v * @return */ protected boolean acceptVehicle(Vehicle v) { return lot.acceptVehicle(v) && isAnyGateOpen(); } public void addParkingSpace(ParkingSpace ps) { if (spaces.size() < capacity) { spaces.add(ps); } } public void addAccessGate(AccessGate gate) { gates.add(gate); } }
1,853
0.638964
0.635726
115
15.121739
15.96635
64
false
false
0
0
0
0
0
0
1.66087
false
false
13
243d2f996da63ccf9324aabec51dde76fbda7205
3,100,966,426,018
d1c92da3f513efa54834cd674bcf97739707178a
/recommended-query-service/src/main/java/com/stackroute/recommendedqueryservice/domain/Skills.java
b736371394d2bcb4b1b63313ba2e1bf9526c1501
[]
no_license
adithyaGowda/latestSquad
https://github.com/adithyaGowda/latestSquad
4e5eb16879225f1f96e94cc46784e0d1cd7282b2
fe759ce9e17a8e45a352497b4ba96cb2676d4487
refs/heads/master
2023-01-12T07:43:10.641000
2019-09-30T12:25:29
2019-09-30T12:25:29
211,853,945
0
0
null
false
2023-01-07T10:14:19
2019-09-30T12:24:46
2019-09-30T12:26:13
2023-01-07T10:14:19
4,378
0
0
32
Java
false
false
package com.stackroute.recommendedqueryservice.domain; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import lombok.*; import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; import java.util.List; @JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id") @NodeEntity /**With @Data, Lombok will generate getter and setter methods, toString methods, Equal & Hashcode methods*/ @Data /**@AllArgsConstructor will generate constructor with all properties in the class*/ @AllArgsConstructor /**@NoArgsConstructor will generate constructor with no arguments*/ @NoArgsConstructor @Getter @Setter @ToString public class Skills { /** * Id annotation makes id variable as Primary key */ @Id private Long id; private String skillName; }
UTF-8
Java
883
java
Skills.java
Java
[]
null
[]
package com.stackroute.recommendedqueryservice.domain; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import lombok.*; import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; import java.util.List; @JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id") @NodeEntity /**With @Data, Lombok will generate getter and setter methods, toString methods, Equal & Hashcode methods*/ @Data /**@AllArgsConstructor will generate constructor with all properties in the class*/ @AllArgsConstructor /**@NoArgsConstructor will generate constructor with no arguments*/ @NoArgsConstructor @Getter @Setter @ToString public class Skills { /** * Id annotation makes id variable as Primary key */ @Id private Long id; private String skillName; }
883
0.783692
0.781427
32
26.59375
28.979366
107
false
false
0
0
0
0
0
0
0.40625
false
false
13
701039e2fabe4ed24f5f692910c47c837fd5f7be
3,100,966,427,424
ae894469897450511448c66f090dc423cbe2c3b9
/Gtu/src/controller/QuestionController.java
bf4347aaf628adce8d254f4e4e48241ea922004e
[]
no_license
zongog/VICS
https://github.com/zongog/VICS
d9119c245c40f47446e21940bddb12c40b05ec5d
22fabd7a3afdbe351e12a990084158c1ba7ef9aa
refs/heads/master
2021-05-02T14:41:04.486000
2018-02-14T01:22:11
2018-02-14T01:22:11
120,724,569
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controller; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import domain.Member; import domain.QuestionAnswerDTO; import domain.QuestionDTO; import service.Member_Service; import service.QuestionService; @Controller public class QuestionController { @Resource private QuestionService questionService; @Autowired private Member_Service memberService; /** * ๊ณต์ง€์‚ฌํ•ญ ๋ฆฌ์ŠคํŠธ ํ™”๋ฉด์œผ๋กœ ์ด๋™ * @return */ @RequestMapping(value = "notice.do") public String index() { return "noticAll.do"; } /** * ์งˆ์˜์„œ id๊ฐ’๊ณผ ์ œ๋ชฉ ๊ฐ’์„ ๊ฐ€์ ธ์™€ List๋ฅผ ์ถœ๋ ฅ * @return */ @RequestMapping(value = "questionList.do") public ModelAndView showJoincpa() { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/question_list.jsp"); List<QuestionDTO> questionList = questionService.selectQuestionList();//QuestionDTO ๋ฐ›์•„์˜ค๊ธฐ // JSONObject jObject = new JSONObject(); JSONArray jArray = new JSONArray(); for (QuestionDTO questionDTO : questionList) { JSONObject questionJSON = new JSONObject(); questionJSON.put("version_id", questionDTO.getVersion_id()); questionJSON.put("version_title", questionDTO.getVersion_title()); jArray.add(questionJSON); } // jObject.put("StudentList", jArray); mv.addObject("questionListJson", jArray); return mv; } //EA_list์— DB์— ์žˆ๋Š” ์งˆ์˜์„œ ๋‹ต๋ณ€ํ•ญ๋ชฉ๋“ค์„ ์ถœ๋ ฅ /*@RequestMapping(value = "getEAList.do") public ModelAndView showEAList() { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/question_list.jsp"); List<QuestionDTO> questionList = questionService.selectQuestionList();//QuestionDTO ๋ฐ›์•„์˜ค๊ธฐ JSONArray jArray = new JSONArray(); for (QuestionDTO questionDTO : questionList) { JSONObject questionJSON = new JSONObject(); questionJSON.put("version_id", questionDTO.getVersion_id()); questionJSON.put("version_title", questionDTO.getVersion_title()); jArray.add(questionJSON); } // jObject.put("StudentList", jArray); mv.addObject("EAListJson", jArray); return mv; }*/ /** * Admin ์งˆ์˜์„œ ์ž‘์„ฑ ํ™”๋ฉด์œผ๋กœ ์ด๋™ * @return */ @RequestMapping(value = "createQuestionPage.do") public String createQuestionPage() { return "/WEB-INF/views/question/adminpage.jsp"; } /** * Admin ์งˆ์˜์„œ ์ž‘์„ฑ ํ›„ List ํ™”๋ฉด์œผ๋กœ ์ด๋™ * @param data * @throws ParseException */ @RequestMapping(value = "createQuestion.do", method = RequestMethod.POST, produces = "application/text; charset=utf8") @ResponseBody public void createQuestion(@RequestBody String data) throws ParseException { JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(data); JSONArray jsonArray = (JSONArray) parser.parse((String)jsonObj.get("main")); String version_title = (String) jsonObj.get("version_title"); // ๊ฐ€์žฅ ์ตœ๊ทผ version_id๊ฐ’ ๊ฐ€์ ธ์˜ค๊ธฐ String version_id_s = questionService.selectRecentlyVersionId(); System.out.println("version_id_s: " + version_id_s); int version_id = 0; if(version_id_s == null) // ๊ฐ’์ด ์•„์˜ˆ ์—†์„ ๊ฒฝ์šฐ(์ฒซ insert) version_id = 1; else // ๊ฐ’์ด ์žˆ์„ ๊ฒฝ์šฐ ๊ทธ ๊ฐ’์˜ +1 version_id = Integer.parseInt(version_id_s) + 1; System.out.println("version_id: " + version_id); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); String q_number = (String) jsonObject.get("q_number"); String content = (String) jsonObject.get("content"); // .์„ ์ œ๊ฑฐํ•ด์ค€๋‹ค q_number = q_number.replaceAll("\\.", ""); // ์ƒˆ QuestionDTO ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค QuestionDTO questionDTO = new QuestionDTO(); questionDTO.setContent(content); questionDTO.setQ_number(q_number); questionDTO.setVersion_title(version_title); questionDTO.setVersion_id(version_id); questionService.createQuestion(questionDTO); } } /* * Admin ์งˆ์˜์„œ ๋””ํ…Œ์ผ ํŽ˜์ด์ง€ ์ด๋™ * @return */ @RequestMapping(value = "selectQuestionDetail.do") public ModelAndView selectQuestionDetail(String version_id) { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/admin_detail.jsp"); List<QuestionDTO> questionList = questionService.selectQuestionListById(Integer.parseInt(version_id)); mv.addObject("version_title", questionList.get(0).getVersion_title()); JSONArray jArray = new JSONArray(); for (QuestionDTO questionDTO : questionList) { JSONObject questionJSON = new JSONObject(); questionJSON.put("version_id", questionDTO.getVersion_id()); questionJSON.put("version_title", questionDTO.getVersion_title()); // q_number ์‚ฌ์ด์‚ฌ์ด์— .์ถ”๊ฐ€ String q_number = questionDTO.getQ_number(); StringBuffer sb = new StringBuffer(q_number); for (int i = 1; i < (q_number.length() * 2) - 2; i+=2) { sb.insert(i, "."); } questionJSON.put("q_number", sb.toString()); questionJSON.put("content", questionDTO.getContent()); jArray.add(questionJSON); } System.out.println(jArray.toString()); mv.addObject("questionListJson", jArray); return mv; } /*@RequestMapping(value = "/joincpa.do", method = RequestMethod.POST) public String showjoincpa(MemberDTO member) { boolean registered = service.register(member); if (!registered) { return "redirect:join.do"; } return "login.jsp"; }*/ /*======================================EA================================*/ /** * EA์งˆ์˜์„œ ๊ด€๋ฆฌ ๊ฒŒ์‹œํŒ ํ™”๋ฉด์œผ๋กœ ์ด๋™ * @return */ // @RequestMapping(value = "eaList.do") // public ModelAndView moveEaList(HttpSession session) { // ModelAndView mv = new ModelAndView("/WEB-INF/views/question/ea_list.jsp"); // // Member memberVO = (Member) session.getAttribute("loginedUser"); // int session_id = memberVO.getSerial_number(); // List<HashMap<String, String>> answerMapList = questionService.QuestionAnswerList(Integer.toString(session_id)); // // JSONArray jArray = new JSONArray(); // for (int i = 0; i < answerMapList.size(); i++) { // HashMap<String, String> answerHashMap = answerMapList.get(i); // JSONObject answerJSON = new JSONObject(); // answerJSON.putAll(answerHashMap); // jArray.add(answerJSON); // } // mv.addObject("questionAnswerListJson", jArray); // System.out.println("JARRAY : " + jArray); // return mv; // } @RequestMapping(value = "eaList.do") public ModelAndView moveEaList() { ModelAndView mv=new ModelAndView("/WEB-INF/views/question/ea_list.jsp"); List<QuestionAnswerDTO> questionAnswerList = questionService.QuestionAnswerList(); //System.out.println("version_title ์ถœ๋ ฅ ํ™•์ธ : " + questionDTO.getVersion_title()); JSONArray jArray = new JSONArray(); for(QuestionAnswerDTO questionAnswerDTO : questionAnswerList) { JSONObject questionJSON = new JSONObject(); questionJSON.put("version_id", questionAnswerDTO.getVersion_id()); questionJSON.put("interviewee_vt_id", questionAnswerDTO.getInterviewee_vt_id()); jArray.add(questionJSON); } System.out.println("jArray ์ถœ๋ ฅ : " + jArray); mv.addObject("questionAnswerListJson", jArray); return mv; } /** * EA์งˆ์˜์„œ ๊ด€๋ฆฌ ๊ฒŒ์‹œํŒ->์งˆ์˜์„œ ์ž‘์„ฑ ํ™”๋ฉด์œผ๋กœ ์ด๋™ * @return */ @RequestMapping(value = "ea.detail") public ModelAndView movetest() { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/ea_detail.jsp"); List<QuestionDTO> questionList = questionService.selectQuestionList(); mv.addObject("questionList", questionList); return mv; } @RequestMapping(value = "getReport.do", produces = "application/text; charset=utf8") @ResponseBody public String getReport(String title) { // ModelAndView mv = new ModelAndView("/WEB-INF/views/question/ea_detail.jsp"); List<QuestionDTO> questionList = questionService.selectQuestionListByTitle(title); JSONArray jArray = new JSONArray(); for (QuestionDTO questionDTO : questionList) { JSONObject questionJSON = new JSONObject(); questionJSON.put("version_id", questionDTO.getVersion_id()); questionJSON.put("version_title", questionDTO.getVersion_title()); // q_number ์‚ฌ์ด์‚ฌ์ด์— .์ถ”๊ฐ€ String q_number = questionDTO.getQ_number(); StringBuffer sb = new StringBuffer(q_number); for (int i = 1; i < (q_number.length() * 2) - 2; i+=2) { sb.insert(i, "."); } questionJSON.put("content", questionDTO.getContent()); questionJSON.put("q_number", sb.toString()); jArray.add(questionJSON); } // System.out.println(jArray.toString()); String a = jArray.toJSONString(); System.out.println(a); return a; } int veteran_answer_id=0;//์„œ๋ฒ„ ๋Œ๋ฆด ๋•Œ๋งˆ๋‹ค ์ดˆ๊ธฐํ™”ํ•ด์ค˜์•ผ PK ์ค‘๋ณต๋˜์ง€ ์•Š์Œ(ORA-00001 ๋ฌด๊ฒฐ์„ฑ์ œ์•ฝ์— ๊ฑธ๋ฆฌ์ง€ ์•Š์Œ) @RequestMapping(value = "saveEA.do" ,method = RequestMethod.POST, produces = "application/text; charset=utf8") @ResponseBody public void saveEa(@RequestBody String data) throws ParseException { JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(data); System.out.println("๋„˜์–ด์˜จ ๋ฐ์ดํ„ฐ1 : "+jsonObj.toJSONString()); JSONArray jsonArray = (JSONArray) parser.parse((String)jsonObj.get("main")); System.out.println("๋„˜์–ด์˜จ ๋ฐ์ดํ„ฐ2: "+jsonArray.toJSONString()); String ea_id = (String)jsonObj.get("EA"); String vt_id = (String)jsonObj.get("VETERAN"); int version_id = Integer.parseInt(jsonObj.get("version_id").toString()); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); String binary_answer=(String) jsonObject.get("key4"); String q_number = (String) jsonObject.get("head"); // .์„ ์ œ๊ฑฐํ•ด์ค€๋‹ค q_number = q_number.replaceAll("\\.", ""); // ์ƒˆ QuestionAnswerDTO ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค QuestionAnswerDTO questionAnswerDTO = new QuestionAnswerDTO(); questionAnswerDTO.setVeteran_answer_id(veteran_answer_id); veteran_answer_id++; questionAnswerDTO.setVersion_id(version_id); questionAnswerDTO.setQ_number(q_number); questionAnswerDTO.setBinary_answer(binary_answer); questionAnswerDTO.setInterviewee_vt_id(vt_id); questionAnswerDTO.setInterviewer_ea_id(ea_id); questionService.createEaList(questionAnswerDTO); } } /** * ์งˆ์˜์„œ id๊ฐ’๊ณผ ์ œ๋ชฉ ๊ฐ’์„ ๊ฐ€์ ธ์™€ List๋ฅผ ์ถœ๋ ฅ * @return */ /*======================================Veteran================================*/ /** * Veteran) ์ž๊ธฐ๊ฐ€ ์‘๋‹ตํ•œ ์งˆ์˜์„œ ๋ชฉ๋ก๋ณด๊ธฐ * @param session * @return */ @RequestMapping(value = "veteranList.do") public ModelAndView moveVeteranList(HttpSession session) { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/veteran_list.jsp"); Member memberVO = (Member) session.getAttribute("loginedUser"); int session_id = memberVO.getSerial_number(); List<HashMap<String, String>> answerMapList = questionService.selectQuestionAnswerList(Integer.toString(session_id)); JSONArray jArray = new JSONArray(); for (int i = 0; i < answerMapList.size(); i++) { HashMap<String, String> answerHashMap = answerMapList.get(i); JSONObject answerJSON = new JSONObject(); answerJSON.putAll(answerHashMap); jArray.add(answerJSON); } mv.addObject("answerdata", jArray); return mv; } /** * Veteran) ์ž๊ธฐ๊ฐ€ ์‘๋‹ตํ•œ ์งˆ์˜์„œ ์ƒ์„ธ์‚ฌํ•ญ ๋ณด๊ธฐ * @param version_id * @param session * @return */ @RequestMapping(value = "questionAnswerDetail.do") public ModelAndView questionAnswerDetail(String version_id, String interviewer_ea_id, HttpSession session) { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/veteran_detail.jsp"); Member memberVO = (Member) session.getAttribute("loginedUser"); int session_id = memberVO.getSerial_number(); List<QuestionDTO> questionDTOList = questionService.selectQuestionListById(Integer.parseInt(version_id)); List<QuestionAnswerDTO> answerDTOList = questionService.selectQuestionAnswer(Integer.toString(session_id), interviewer_ea_id, version_id); System.out.println(questionDTOList.toString()); System.out.println(answerDTOList.toString()); JSONArray jArray = new JSONArray(); for (int i = 0; i < questionDTOList.size(); i++) { QuestionDTO tempQuestionDTO = questionDTOList.get(i); QuestionAnswerDTO tempQuestionAnswerDTO = answerDTOList.get(i); JSONObject questionJSON = new JSONObject(); // q_number ์‚ฌ์ด์‚ฌ์ด์— .์ถ”๊ฐ€ StringBuffer sb = new StringBuffer(tempQuestionDTO.getQ_number()); for (int j = 1; j < (tempQuestionDTO.getQ_number().length() * 2) - 2; j+=2) { sb.insert(j, "."); } // jsonObject ์งˆ๋ฌธ๋ฒˆํ˜ธ(q_number) ์ถ”๊ฐ€ questionJSON.put("q_number", sb.toString()); // jsonObject ์งˆ๋ฌธํ•ญ๋ชฉ(content) ์ถ”๊ฐ€ questionJSON.put("content", tempQuestionDTO.getContent()); // jsonObject ์‘๋‹ต ๊ฐ’(binary_answer) ์ถ”๊ฐ€ questionJSON.put("binary_answer", tempQuestionAnswerDTO.getBinary_answer()); // jArray์— ์ถ”๊ฐ€ jArray.add(questionJSON); } mv.addObject("veteranAnswerJson", jArray); return mv; } }
UTF-8
Java
14,572
java
QuestionController.java
Java
[]
null
[]
package controller; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import domain.Member; import domain.QuestionAnswerDTO; import domain.QuestionDTO; import service.Member_Service; import service.QuestionService; @Controller public class QuestionController { @Resource private QuestionService questionService; @Autowired private Member_Service memberService; /** * ๊ณต์ง€์‚ฌํ•ญ ๋ฆฌ์ŠคํŠธ ํ™”๋ฉด์œผ๋กœ ์ด๋™ * @return */ @RequestMapping(value = "notice.do") public String index() { return "noticAll.do"; } /** * ์งˆ์˜์„œ id๊ฐ’๊ณผ ์ œ๋ชฉ ๊ฐ’์„ ๊ฐ€์ ธ์™€ List๋ฅผ ์ถœ๋ ฅ * @return */ @RequestMapping(value = "questionList.do") public ModelAndView showJoincpa() { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/question_list.jsp"); List<QuestionDTO> questionList = questionService.selectQuestionList();//QuestionDTO ๋ฐ›์•„์˜ค๊ธฐ // JSONObject jObject = new JSONObject(); JSONArray jArray = new JSONArray(); for (QuestionDTO questionDTO : questionList) { JSONObject questionJSON = new JSONObject(); questionJSON.put("version_id", questionDTO.getVersion_id()); questionJSON.put("version_title", questionDTO.getVersion_title()); jArray.add(questionJSON); } // jObject.put("StudentList", jArray); mv.addObject("questionListJson", jArray); return mv; } //EA_list์— DB์— ์žˆ๋Š” ์งˆ์˜์„œ ๋‹ต๋ณ€ํ•ญ๋ชฉ๋“ค์„ ์ถœ๋ ฅ /*@RequestMapping(value = "getEAList.do") public ModelAndView showEAList() { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/question_list.jsp"); List<QuestionDTO> questionList = questionService.selectQuestionList();//QuestionDTO ๋ฐ›์•„์˜ค๊ธฐ JSONArray jArray = new JSONArray(); for (QuestionDTO questionDTO : questionList) { JSONObject questionJSON = new JSONObject(); questionJSON.put("version_id", questionDTO.getVersion_id()); questionJSON.put("version_title", questionDTO.getVersion_title()); jArray.add(questionJSON); } // jObject.put("StudentList", jArray); mv.addObject("EAListJson", jArray); return mv; }*/ /** * Admin ์งˆ์˜์„œ ์ž‘์„ฑ ํ™”๋ฉด์œผ๋กœ ์ด๋™ * @return */ @RequestMapping(value = "createQuestionPage.do") public String createQuestionPage() { return "/WEB-INF/views/question/adminpage.jsp"; } /** * Admin ์งˆ์˜์„œ ์ž‘์„ฑ ํ›„ List ํ™”๋ฉด์œผ๋กœ ์ด๋™ * @param data * @throws ParseException */ @RequestMapping(value = "createQuestion.do", method = RequestMethod.POST, produces = "application/text; charset=utf8") @ResponseBody public void createQuestion(@RequestBody String data) throws ParseException { JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(data); JSONArray jsonArray = (JSONArray) parser.parse((String)jsonObj.get("main")); String version_title = (String) jsonObj.get("version_title"); // ๊ฐ€์žฅ ์ตœ๊ทผ version_id๊ฐ’ ๊ฐ€์ ธ์˜ค๊ธฐ String version_id_s = questionService.selectRecentlyVersionId(); System.out.println("version_id_s: " + version_id_s); int version_id = 0; if(version_id_s == null) // ๊ฐ’์ด ์•„์˜ˆ ์—†์„ ๊ฒฝ์šฐ(์ฒซ insert) version_id = 1; else // ๊ฐ’์ด ์žˆ์„ ๊ฒฝ์šฐ ๊ทธ ๊ฐ’์˜ +1 version_id = Integer.parseInt(version_id_s) + 1; System.out.println("version_id: " + version_id); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); String q_number = (String) jsonObject.get("q_number"); String content = (String) jsonObject.get("content"); // .์„ ์ œ๊ฑฐํ•ด์ค€๋‹ค q_number = q_number.replaceAll("\\.", ""); // ์ƒˆ QuestionDTO ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค QuestionDTO questionDTO = new QuestionDTO(); questionDTO.setContent(content); questionDTO.setQ_number(q_number); questionDTO.setVersion_title(version_title); questionDTO.setVersion_id(version_id); questionService.createQuestion(questionDTO); } } /* * Admin ์งˆ์˜์„œ ๋””ํ…Œ์ผ ํŽ˜์ด์ง€ ์ด๋™ * @return */ @RequestMapping(value = "selectQuestionDetail.do") public ModelAndView selectQuestionDetail(String version_id) { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/admin_detail.jsp"); List<QuestionDTO> questionList = questionService.selectQuestionListById(Integer.parseInt(version_id)); mv.addObject("version_title", questionList.get(0).getVersion_title()); JSONArray jArray = new JSONArray(); for (QuestionDTO questionDTO : questionList) { JSONObject questionJSON = new JSONObject(); questionJSON.put("version_id", questionDTO.getVersion_id()); questionJSON.put("version_title", questionDTO.getVersion_title()); // q_number ์‚ฌ์ด์‚ฌ์ด์— .์ถ”๊ฐ€ String q_number = questionDTO.getQ_number(); StringBuffer sb = new StringBuffer(q_number); for (int i = 1; i < (q_number.length() * 2) - 2; i+=2) { sb.insert(i, "."); } questionJSON.put("q_number", sb.toString()); questionJSON.put("content", questionDTO.getContent()); jArray.add(questionJSON); } System.out.println(jArray.toString()); mv.addObject("questionListJson", jArray); return mv; } /*@RequestMapping(value = "/joincpa.do", method = RequestMethod.POST) public String showjoincpa(MemberDTO member) { boolean registered = service.register(member); if (!registered) { return "redirect:join.do"; } return "login.jsp"; }*/ /*======================================EA================================*/ /** * EA์งˆ์˜์„œ ๊ด€๋ฆฌ ๊ฒŒ์‹œํŒ ํ™”๋ฉด์œผ๋กœ ์ด๋™ * @return */ // @RequestMapping(value = "eaList.do") // public ModelAndView moveEaList(HttpSession session) { // ModelAndView mv = new ModelAndView("/WEB-INF/views/question/ea_list.jsp"); // // Member memberVO = (Member) session.getAttribute("loginedUser"); // int session_id = memberVO.getSerial_number(); // List<HashMap<String, String>> answerMapList = questionService.QuestionAnswerList(Integer.toString(session_id)); // // JSONArray jArray = new JSONArray(); // for (int i = 0; i < answerMapList.size(); i++) { // HashMap<String, String> answerHashMap = answerMapList.get(i); // JSONObject answerJSON = new JSONObject(); // answerJSON.putAll(answerHashMap); // jArray.add(answerJSON); // } // mv.addObject("questionAnswerListJson", jArray); // System.out.println("JARRAY : " + jArray); // return mv; // } @RequestMapping(value = "eaList.do") public ModelAndView moveEaList() { ModelAndView mv=new ModelAndView("/WEB-INF/views/question/ea_list.jsp"); List<QuestionAnswerDTO> questionAnswerList = questionService.QuestionAnswerList(); //System.out.println("version_title ์ถœ๋ ฅ ํ™•์ธ : " + questionDTO.getVersion_title()); JSONArray jArray = new JSONArray(); for(QuestionAnswerDTO questionAnswerDTO : questionAnswerList) { JSONObject questionJSON = new JSONObject(); questionJSON.put("version_id", questionAnswerDTO.getVersion_id()); questionJSON.put("interviewee_vt_id", questionAnswerDTO.getInterviewee_vt_id()); jArray.add(questionJSON); } System.out.println("jArray ์ถœ๋ ฅ : " + jArray); mv.addObject("questionAnswerListJson", jArray); return mv; } /** * EA์งˆ์˜์„œ ๊ด€๋ฆฌ ๊ฒŒ์‹œํŒ->์งˆ์˜์„œ ์ž‘์„ฑ ํ™”๋ฉด์œผ๋กœ ์ด๋™ * @return */ @RequestMapping(value = "ea.detail") public ModelAndView movetest() { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/ea_detail.jsp"); List<QuestionDTO> questionList = questionService.selectQuestionList(); mv.addObject("questionList", questionList); return mv; } @RequestMapping(value = "getReport.do", produces = "application/text; charset=utf8") @ResponseBody public String getReport(String title) { // ModelAndView mv = new ModelAndView("/WEB-INF/views/question/ea_detail.jsp"); List<QuestionDTO> questionList = questionService.selectQuestionListByTitle(title); JSONArray jArray = new JSONArray(); for (QuestionDTO questionDTO : questionList) { JSONObject questionJSON = new JSONObject(); questionJSON.put("version_id", questionDTO.getVersion_id()); questionJSON.put("version_title", questionDTO.getVersion_title()); // q_number ์‚ฌ์ด์‚ฌ์ด์— .์ถ”๊ฐ€ String q_number = questionDTO.getQ_number(); StringBuffer sb = new StringBuffer(q_number); for (int i = 1; i < (q_number.length() * 2) - 2; i+=2) { sb.insert(i, "."); } questionJSON.put("content", questionDTO.getContent()); questionJSON.put("q_number", sb.toString()); jArray.add(questionJSON); } // System.out.println(jArray.toString()); String a = jArray.toJSONString(); System.out.println(a); return a; } int veteran_answer_id=0;//์„œ๋ฒ„ ๋Œ๋ฆด ๋•Œ๋งˆ๋‹ค ์ดˆ๊ธฐํ™”ํ•ด์ค˜์•ผ PK ์ค‘๋ณต๋˜์ง€ ์•Š์Œ(ORA-00001 ๋ฌด๊ฒฐ์„ฑ์ œ์•ฝ์— ๊ฑธ๋ฆฌ์ง€ ์•Š์Œ) @RequestMapping(value = "saveEA.do" ,method = RequestMethod.POST, produces = "application/text; charset=utf8") @ResponseBody public void saveEa(@RequestBody String data) throws ParseException { JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(data); System.out.println("๋„˜์–ด์˜จ ๋ฐ์ดํ„ฐ1 : "+jsonObj.toJSONString()); JSONArray jsonArray = (JSONArray) parser.parse((String)jsonObj.get("main")); System.out.println("๋„˜์–ด์˜จ ๋ฐ์ดํ„ฐ2: "+jsonArray.toJSONString()); String ea_id = (String)jsonObj.get("EA"); String vt_id = (String)jsonObj.get("VETERAN"); int version_id = Integer.parseInt(jsonObj.get("version_id").toString()); for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); String binary_answer=(String) jsonObject.get("key4"); String q_number = (String) jsonObject.get("head"); // .์„ ์ œ๊ฑฐํ•ด์ค€๋‹ค q_number = q_number.replaceAll("\\.", ""); // ์ƒˆ QuestionAnswerDTO ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ ๋‹ค QuestionAnswerDTO questionAnswerDTO = new QuestionAnswerDTO(); questionAnswerDTO.setVeteran_answer_id(veteran_answer_id); veteran_answer_id++; questionAnswerDTO.setVersion_id(version_id); questionAnswerDTO.setQ_number(q_number); questionAnswerDTO.setBinary_answer(binary_answer); questionAnswerDTO.setInterviewee_vt_id(vt_id); questionAnswerDTO.setInterviewer_ea_id(ea_id); questionService.createEaList(questionAnswerDTO); } } /** * ์งˆ์˜์„œ id๊ฐ’๊ณผ ์ œ๋ชฉ ๊ฐ’์„ ๊ฐ€์ ธ์™€ List๋ฅผ ์ถœ๋ ฅ * @return */ /*======================================Veteran================================*/ /** * Veteran) ์ž๊ธฐ๊ฐ€ ์‘๋‹ตํ•œ ์งˆ์˜์„œ ๋ชฉ๋ก๋ณด๊ธฐ * @param session * @return */ @RequestMapping(value = "veteranList.do") public ModelAndView moveVeteranList(HttpSession session) { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/veteran_list.jsp"); Member memberVO = (Member) session.getAttribute("loginedUser"); int session_id = memberVO.getSerial_number(); List<HashMap<String, String>> answerMapList = questionService.selectQuestionAnswerList(Integer.toString(session_id)); JSONArray jArray = new JSONArray(); for (int i = 0; i < answerMapList.size(); i++) { HashMap<String, String> answerHashMap = answerMapList.get(i); JSONObject answerJSON = new JSONObject(); answerJSON.putAll(answerHashMap); jArray.add(answerJSON); } mv.addObject("answerdata", jArray); return mv; } /** * Veteran) ์ž๊ธฐ๊ฐ€ ์‘๋‹ตํ•œ ์งˆ์˜์„œ ์ƒ์„ธ์‚ฌํ•ญ ๋ณด๊ธฐ * @param version_id * @param session * @return */ @RequestMapping(value = "questionAnswerDetail.do") public ModelAndView questionAnswerDetail(String version_id, String interviewer_ea_id, HttpSession session) { ModelAndView mv = new ModelAndView("/WEB-INF/views/question/veteran_detail.jsp"); Member memberVO = (Member) session.getAttribute("loginedUser"); int session_id = memberVO.getSerial_number(); List<QuestionDTO> questionDTOList = questionService.selectQuestionListById(Integer.parseInt(version_id)); List<QuestionAnswerDTO> answerDTOList = questionService.selectQuestionAnswer(Integer.toString(session_id), interviewer_ea_id, version_id); System.out.println(questionDTOList.toString()); System.out.println(answerDTOList.toString()); JSONArray jArray = new JSONArray(); for (int i = 0; i < questionDTOList.size(); i++) { QuestionDTO tempQuestionDTO = questionDTOList.get(i); QuestionAnswerDTO tempQuestionAnswerDTO = answerDTOList.get(i); JSONObject questionJSON = new JSONObject(); // q_number ์‚ฌ์ด์‚ฌ์ด์— .์ถ”๊ฐ€ StringBuffer sb = new StringBuffer(tempQuestionDTO.getQ_number()); for (int j = 1; j < (tempQuestionDTO.getQ_number().length() * 2) - 2; j+=2) { sb.insert(j, "."); } // jsonObject ์งˆ๋ฌธ๋ฒˆํ˜ธ(q_number) ์ถ”๊ฐ€ questionJSON.put("q_number", sb.toString()); // jsonObject ์งˆ๋ฌธํ•ญ๋ชฉ(content) ์ถ”๊ฐ€ questionJSON.put("content", tempQuestionDTO.getContent()); // jsonObject ์‘๋‹ต ๊ฐ’(binary_answer) ์ถ”๊ฐ€ questionJSON.put("binary_answer", tempQuestionAnswerDTO.getBinary_answer()); // jArray์— ์ถ”๊ฐ€ jArray.add(questionJSON); } mv.addObject("veteranAnswerJson", jArray); return mv; } }
14,572
0.662967
0.660533
395
34.35696
28.362066
140
false
false
0
0
0
0
77
0.010669
1.84557
false
false
13
0a1d0c693d7cec652b1d08d7c2d71611da33a9fe
2,894,807,957,672
45b655db2cf6b21ff5cb63f2fe1482db881c79a7
/company-service/src/main/java/com/example/demo/service/CompanyServiceImpl.java
3a34c99658233d7b26340bd5f75b25b84da00575
[]
no_license
rsagrawal2996/Stock-Market-Charting-New
https://github.com/rsagrawal2996/Stock-Market-Charting-New
1e2bce01a3ce6b4c4872ceb92809d607e2b57fef
08f186c4b85627c799b9cdd4aba0841813e34d7f
refs/heads/master
2022-12-15T07:01:56.023000
2020-09-09T14:39:32
2020-09-09T14:39:32
294,136,438
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.service; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.modelmapper.ModelMapper; import org.modelmapper.TypeToken; import org.modelmapper.convention.MatchingStrategies; import org.modelmapper.spi.MatchingStrategy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.example.demo.dao.CompanyCodeDao; import com.example.demo.dao.CompanyDao; import com.example.demo.dao.StockExchangeDao; import com.example.demo.entity.Company; import com.example.demo.entity.CompanyCode; import com.example.demo.entity.CompanyCodeId; import com.example.demo.entity.StockExchange; import com.example.demo.models.CompanyCodeModelForCompany; import com.example.demo.models.CompanyRequestModel; import com.example.demo.models.CompanyResponseModel; @Service public class CompanyServiceImpl implements CompanyService{ private CompanyDao companyDao; private CompanyCodeDao companyCodeDao; private StockExchangeDao stockExchangeDao; private ModelMapper modelMapper; public CompanyServiceImpl(CompanyDao companyDao, CompanyCodeDao companyCodeDao, StockExchangeDao stockExchangeDao, ModelMapper modelMapper) { super(); this.companyDao = companyDao; this.companyCodeDao = companyCodeDao; this.stockExchangeDao = stockExchangeDao; this.modelMapper = modelMapper; } @Override @Transactional public List<CompanyResponseModel> getAllCompanies() { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Type listType = new TypeToken<List<CompanyResponseModel>>() {}.getType(); return modelMapper.map(companyDao.findAll(), listType); } @Override @Transactional public CompanyResponseModel findCompanyById(Long companyId) { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Company company = companyDao.findById(companyId).orElse(null); if(company!=null) { return modelMapper.map(company, CompanyResponseModel.class); } return null; } @Override @Transactional public CompanyResponseModel findCompanyByCompanyName(String companyName) { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Company company = companyDao.findByCompanyName(companyName).orElse(null); if(company!=null) { return modelMapper.map(company, CompanyResponseModel.class); } return null; } @Override @Transactional public String deleteCompanyById(Long companyId) { // TODO Auto-generated method stub Optional<Company> company = companyDao.findById(companyId); if(company.isPresent()) { List<CompanyCode> companyCodes = companyCodeDao.findAllByCompanyId(companyId); if(!companyCodes.isEmpty()) { companyCodeDao.deleteByCompanyId(companyId); } companyDao.deleteById(companyId); return "Successfully Deleted"; } return "Not Found"; } @Override @Transactional public CompanyResponseModel addCompany(CompanyRequestModel companyRequest){ // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Company company = companyDao.findByCompanyName(companyRequest.getCompanyName()).orElse(null); if(company!=null) { return modelMapper.map(company, CompanyResponseModel.class); } company = new Company(); company.setCeo(companyRequest.getCeo()); company.setCompanyName(companyRequest.getCompanyName()); company.setWriteup(companyRequest.getWriteup()); company.setTurnover(companyRequest.getTurnover()); company.setSector(companyRequest.getSector()); company.setDirectors(companyRequest.getDirectors()); company = companyDao.save(company); List<CompanyCodeModelForCompany> companyCodes = companyRequest.getCompanyCodes(); for(CompanyCodeModelForCompany companyCode : companyCodes) { StockExchange stockExchange = stockExchangeDao.findByStockExchangeName(companyCode.getStockExchangeName()).orElse(null); if(stockExchange==null) { return null; } CompanyCodeId id = new CompanyCodeId(company.getCompanyId(), stockExchange.getStockExchangeId()); CompanyCode companyCode1 = new CompanyCode(id, companyCode.getCompanyCodeValue(), company.getCompanyName(), companyCode.getStockExchangeName(), companyCode.getStockPrice()); companyCodeDao.save(companyCode1); } //company = companyDao.save(company); CompanyResponseModel companyResponse = modelMapper.map(company, CompanyResponseModel.class); companyResponse.setCompanyCodes(companyCodes); return companyResponse; } @Override @Transactional public List<CompanyResponseModel> findCompanyByCompanyNameContaining(String name) { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); List<Company> companies = companyDao.findByCompanyNameContainingIgnoreCase(name); Type listType = new TypeToken<List<CompanyResponseModel>>(){}.getType(); return modelMapper.map(companies, listType); } @Override @Transactional public CompanyResponseModel updateCompany(Long companyId, CompanyRequestModel companyRequest) { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Company company = companyDao.findById(companyId).orElse(null); if(company==null) { return null; //return modelMapper.map(companyRequest, CompanyResponseModel.class); } company.setCeo(companyRequest.getCeo()); company.setCompanyName(companyRequest.getCompanyName()); company.setWriteup(companyRequest.getWriteup()); company.setTurnover(companyRequest.getTurnover()); company.setSector(companyRequest.getSector()); company.setDirectors(companyRequest.getDirectors()); company = companyDao.save(company); companyCodeDao.deleteByCompanyId(companyId); List<CompanyCodeModelForCompany> companyCodes = companyRequest.getCompanyCodes(); for(CompanyCodeModelForCompany companyCode : companyCodes) { StockExchange stockExchange = stockExchangeDao.findByStockExchangeName(companyCode.getStockExchangeName()).orElse(null); if(stockExchange==null) { return null; } CompanyCodeId id = new CompanyCodeId(company.getCompanyId(), stockExchange.getStockExchangeId()); CompanyCode companyCode1 = new CompanyCode(id, companyCode.getCompanyCodeValue(), company.getCompanyName(), companyCode.getStockExchangeName(), companyCode.getStockPrice()); companyCodeDao.save(companyCode1); } //return modelMapper.map(company, CompanyResponseModel.class); CompanyResponseModel companyResponse = modelMapper.map(company, CompanyResponseModel.class); companyResponse.setCompanyCodes(companyCodes); return companyResponse; } @Override @Transactional public List<CompanyResponseModel> findCompanyBySector(String sector) { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Type listType = new TypeToken<List<CompanyResponseModel>>() {}.getType(); return modelMapper.map(companyDao.findAllBySector(sector), listType); } @Override @Transactional public CompanyResponseModel findCompanyByCompanyCode(String companyCodeValue) { // TODO Auto-generated method stub CompanyCode companyCode = companyCodeDao.findByCompanyCodeValue(companyCodeValue).orElse(null); if(companyCode!=null) { Company company = companyDao.findByCompanyName(companyCode.getCompanyName()).orElse(null); if(company!=null) { return modelMapper.map(company, CompanyResponseModel.class); } } return null; } @Override @Transactional public List<CompanyResponseModel> findCompanyByStockExchangeName(String stockExchangeName) { // TODO Auto-generated method stub List<CompanyCode> companyCodes = companyCodeDao.findAllByStockExchangeNameContaining(stockExchangeName); List<Company> companies = new ArrayList<>(); if(!companyCodes.isEmpty()) { for(CompanyCode companyCode : companyCodes) { Company company = companyDao.findByCompanyName(companyCode.getCompanyName()).orElse(null); if(company!=null) { companies.add(company); } } Type listType = new TypeToken<List<CompanyResponseModel>>() {}.getType(); return modelMapper.map(companies, listType); } return null; } }
UTF-8
Java
8,685
java
CompanyServiceImpl.java
Java
[]
null
[]
package com.example.demo.service; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.modelmapper.ModelMapper; import org.modelmapper.TypeToken; import org.modelmapper.convention.MatchingStrategies; import org.modelmapper.spi.MatchingStrategy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.example.demo.dao.CompanyCodeDao; import com.example.demo.dao.CompanyDao; import com.example.demo.dao.StockExchangeDao; import com.example.demo.entity.Company; import com.example.demo.entity.CompanyCode; import com.example.demo.entity.CompanyCodeId; import com.example.demo.entity.StockExchange; import com.example.demo.models.CompanyCodeModelForCompany; import com.example.demo.models.CompanyRequestModel; import com.example.demo.models.CompanyResponseModel; @Service public class CompanyServiceImpl implements CompanyService{ private CompanyDao companyDao; private CompanyCodeDao companyCodeDao; private StockExchangeDao stockExchangeDao; private ModelMapper modelMapper; public CompanyServiceImpl(CompanyDao companyDao, CompanyCodeDao companyCodeDao, StockExchangeDao stockExchangeDao, ModelMapper modelMapper) { super(); this.companyDao = companyDao; this.companyCodeDao = companyCodeDao; this.stockExchangeDao = stockExchangeDao; this.modelMapper = modelMapper; } @Override @Transactional public List<CompanyResponseModel> getAllCompanies() { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Type listType = new TypeToken<List<CompanyResponseModel>>() {}.getType(); return modelMapper.map(companyDao.findAll(), listType); } @Override @Transactional public CompanyResponseModel findCompanyById(Long companyId) { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Company company = companyDao.findById(companyId).orElse(null); if(company!=null) { return modelMapper.map(company, CompanyResponseModel.class); } return null; } @Override @Transactional public CompanyResponseModel findCompanyByCompanyName(String companyName) { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Company company = companyDao.findByCompanyName(companyName).orElse(null); if(company!=null) { return modelMapper.map(company, CompanyResponseModel.class); } return null; } @Override @Transactional public String deleteCompanyById(Long companyId) { // TODO Auto-generated method stub Optional<Company> company = companyDao.findById(companyId); if(company.isPresent()) { List<CompanyCode> companyCodes = companyCodeDao.findAllByCompanyId(companyId); if(!companyCodes.isEmpty()) { companyCodeDao.deleteByCompanyId(companyId); } companyDao.deleteById(companyId); return "Successfully Deleted"; } return "Not Found"; } @Override @Transactional public CompanyResponseModel addCompany(CompanyRequestModel companyRequest){ // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Company company = companyDao.findByCompanyName(companyRequest.getCompanyName()).orElse(null); if(company!=null) { return modelMapper.map(company, CompanyResponseModel.class); } company = new Company(); company.setCeo(companyRequest.getCeo()); company.setCompanyName(companyRequest.getCompanyName()); company.setWriteup(companyRequest.getWriteup()); company.setTurnover(companyRequest.getTurnover()); company.setSector(companyRequest.getSector()); company.setDirectors(companyRequest.getDirectors()); company = companyDao.save(company); List<CompanyCodeModelForCompany> companyCodes = companyRequest.getCompanyCodes(); for(CompanyCodeModelForCompany companyCode : companyCodes) { StockExchange stockExchange = stockExchangeDao.findByStockExchangeName(companyCode.getStockExchangeName()).orElse(null); if(stockExchange==null) { return null; } CompanyCodeId id = new CompanyCodeId(company.getCompanyId(), stockExchange.getStockExchangeId()); CompanyCode companyCode1 = new CompanyCode(id, companyCode.getCompanyCodeValue(), company.getCompanyName(), companyCode.getStockExchangeName(), companyCode.getStockPrice()); companyCodeDao.save(companyCode1); } //company = companyDao.save(company); CompanyResponseModel companyResponse = modelMapper.map(company, CompanyResponseModel.class); companyResponse.setCompanyCodes(companyCodes); return companyResponse; } @Override @Transactional public List<CompanyResponseModel> findCompanyByCompanyNameContaining(String name) { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); List<Company> companies = companyDao.findByCompanyNameContainingIgnoreCase(name); Type listType = new TypeToken<List<CompanyResponseModel>>(){}.getType(); return modelMapper.map(companies, listType); } @Override @Transactional public CompanyResponseModel updateCompany(Long companyId, CompanyRequestModel companyRequest) { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Company company = companyDao.findById(companyId).orElse(null); if(company==null) { return null; //return modelMapper.map(companyRequest, CompanyResponseModel.class); } company.setCeo(companyRequest.getCeo()); company.setCompanyName(companyRequest.getCompanyName()); company.setWriteup(companyRequest.getWriteup()); company.setTurnover(companyRequest.getTurnover()); company.setSector(companyRequest.getSector()); company.setDirectors(companyRequest.getDirectors()); company = companyDao.save(company); companyCodeDao.deleteByCompanyId(companyId); List<CompanyCodeModelForCompany> companyCodes = companyRequest.getCompanyCodes(); for(CompanyCodeModelForCompany companyCode : companyCodes) { StockExchange stockExchange = stockExchangeDao.findByStockExchangeName(companyCode.getStockExchangeName()).orElse(null); if(stockExchange==null) { return null; } CompanyCodeId id = new CompanyCodeId(company.getCompanyId(), stockExchange.getStockExchangeId()); CompanyCode companyCode1 = new CompanyCode(id, companyCode.getCompanyCodeValue(), company.getCompanyName(), companyCode.getStockExchangeName(), companyCode.getStockPrice()); companyCodeDao.save(companyCode1); } //return modelMapper.map(company, CompanyResponseModel.class); CompanyResponseModel companyResponse = modelMapper.map(company, CompanyResponseModel.class); companyResponse.setCompanyCodes(companyCodes); return companyResponse; } @Override @Transactional public List<CompanyResponseModel> findCompanyBySector(String sector) { // TODO Auto-generated method stub modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Type listType = new TypeToken<List<CompanyResponseModel>>() {}.getType(); return modelMapper.map(companyDao.findAllBySector(sector), listType); } @Override @Transactional public CompanyResponseModel findCompanyByCompanyCode(String companyCodeValue) { // TODO Auto-generated method stub CompanyCode companyCode = companyCodeDao.findByCompanyCodeValue(companyCodeValue).orElse(null); if(companyCode!=null) { Company company = companyDao.findByCompanyName(companyCode.getCompanyName()).orElse(null); if(company!=null) { return modelMapper.map(company, CompanyResponseModel.class); } } return null; } @Override @Transactional public List<CompanyResponseModel> findCompanyByStockExchangeName(String stockExchangeName) { // TODO Auto-generated method stub List<CompanyCode> companyCodes = companyCodeDao.findAllByStockExchangeNameContaining(stockExchangeName); List<Company> companies = new ArrayList<>(); if(!companyCodes.isEmpty()) { for(CompanyCode companyCode : companyCodes) { Company company = companyDao.findByCompanyName(companyCode.getCompanyName()).orElse(null); if(company!=null) { companies.add(company); } } Type listType = new TypeToken<List<CompanyResponseModel>>() {}.getType(); return modelMapper.map(companies, listType); } return null; } }
8,685
0.769372
0.768912
229
35.925766
31.424112
142
false
false
0
0
0
0
0
0
2.310044
false
false
13
10ff79e96d742a1b097f7abb475995085df131bb
24,489,903,522,109
9e015ed5833b6cbe688891ac3d0f97d7b92c1a38
/app/src/main/java/com/danielebartorilla/worldclock/beans/City.java
f374a30838d6ac3bb3de11e0d0b5643e366aa0c2
[ "MIT" ]
permissive
danielebartorilla/WorldClock
https://github.com/danielebartorilla/WorldClock
f3520d0e0e7be861f562e837a8bc281d9736edb5
0cf77bde7fc575ab531157188bc2c44435d31505
refs/heads/master
2018-03-26T13:02:50.283000
2018-02-08T23:16:34
2018-02-08T23:16:34
87,121,675
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.danielebartorilla.worldclock.beans; public class City { private String name; private String country; private int id; private Double lat; private Double lng; private String timezoneId; public City(int id, String name, String country, Double lat, Double lng){ this.id = id; this.name = name; this.country = country; this.lat = lat; this.lng = lng; } public City(int id, String name, String country, String timezoneId, Double lat, Double lng){ this.id = id; this.name = name; this.country = country; this.lat = lat; this.lng = lng; this.timezoneId = timezoneId; } public int getId(){ return id; } public void setTimezoneId(String timezoneId) { this.timezoneId = timezoneId; } public String getName() { return name; } public String getTimezoneId() { return timezoneId; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public Double getLat() { return lat; } public Double getLng() { return lng; } public void setLat(Double lat) { this.lat = lat; } public void setLng(Double lng) { this.lng = lng; } }
UTF-8
Java
1,383
java
City.java
Java
[]
null
[]
package com.danielebartorilla.worldclock.beans; public class City { private String name; private String country; private int id; private Double lat; private Double lng; private String timezoneId; public City(int id, String name, String country, Double lat, Double lng){ this.id = id; this.name = name; this.country = country; this.lat = lat; this.lng = lng; } public City(int id, String name, String country, String timezoneId, Double lat, Double lng){ this.id = id; this.name = name; this.country = country; this.lat = lat; this.lng = lng; this.timezoneId = timezoneId; } public int getId(){ return id; } public void setTimezoneId(String timezoneId) { this.timezoneId = timezoneId; } public String getName() { return name; } public String getTimezoneId() { return timezoneId; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public Double getLat() { return lat; } public Double getLng() { return lng; } public void setLat(Double lat) { this.lat = lat; } public void setLng(Double lng) { this.lng = lng; } }
1,383
0.574114
0.574114
74
17.68919
18.112953
96
false
false
0
0
0
0
0
0
0.5
false
false
13
a032cf2b3a8e7136586106e56370daca00746597
13,812,614,847,092
26f331a3480959c7b3f4625d93f210bb6a676d13
/app/src/main/java/com/wusir/wuweather/MyApplication.java
6300bfd38daf5a910974865e32bac756d2d898c3
[]
no_license
wusir-china/WuWeather
https://github.com/wusir-china/WuWeather
0125e48a91426483cb86d534fa2c5ef78d2fe347
0475601fe4977176939b540ed4d9dd481d443e82
refs/heads/master
2021-05-14T18:43:38.540000
2018-04-16T03:37:11
2018-04-16T03:37:11
116,083,540
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wusir.wuweather; import android.app.Application; import android.content.Context; import com.lzy.okgo.OkGo; import com.squareup.leakcanary.LeakCanary; import org.litepal.LitePal; /** * Created by zy on 2017/5/26. */ public class MyApplication extends Application { public static Context AppContext; @Override public void onCreate() { super.onCreate(); AppContext=getApplicationContext(); OkGo.getInstance().init(this); //ๅ†…ๅญ˜ๆณ„ๆผๆฃ€ๆต‹ // if(LeakCanary.isInAnalyzerProcess(this)){ // return; // } // LeakCanary.install(this); LitePal.initialize(this); } }
UTF-8
Java
666
java
MyApplication.java
Java
[ { "context": "y;\n\nimport org.litepal.LitePal;\n\n/**\n * Created by zy on 2017/5/26.\n */\n\npublic class MyApplication ext", "end": 214, "score": 0.9993544816970825, "start": 212, "tag": "USERNAME", "value": "zy" } ]
null
[]
package com.wusir.wuweather; import android.app.Application; import android.content.Context; import com.lzy.okgo.OkGo; import com.squareup.leakcanary.LeakCanary; import org.litepal.LitePal; /** * Created by zy on 2017/5/26. */ public class MyApplication extends Application { public static Context AppContext; @Override public void onCreate() { super.onCreate(); AppContext=getApplicationContext(); OkGo.getInstance().init(this); //ๅ†…ๅญ˜ๆณ„ๆผๆฃ€ๆต‹ // if(LeakCanary.isInAnalyzerProcess(this)){ // return; // } // LeakCanary.install(this); LitePal.initialize(this); } }
666
0.659021
0.648318
29
21.551723
16.162081
51
false
false
0
0
0
0
0
0
0.448276
false
false
13
65d2fd1d2713a6c7db169aeb1392dc160cbd144e
7,146,825,626,310
3fb666795c2684ec3c3db860169a2c540f8f4a93
/basic-tutorial/src/main/java/com/softmax/design/visit/Candy.java
a004a9e3faed0dd677a817a4ccc3fb78435c4781
[ "Apache-2.0" ]
permissive
jarvisqi/java-tutorial
https://github.com/jarvisqi/java-tutorial
63880552cd7a8b64b79abae990e32c2553d0d470
e9fde2484dd5fd93d0938f3def579ff223e70c5b
refs/heads/master
2023-04-15T15:23:00.487000
2023-04-11T06:47:31
2023-04-11T06:47:31
138,869,198
20
12
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.softmax.design.visit; import java.time.LocalDate; /** * ็ณ–ๆžœ็ฑป * @author Jarvis */ public class Candy extends Product { public Candy(String name, LocalDate producedDate, float price) { super(name, producedDate, price); } }
UTF-8
Java
259
java
Candy.java
Java
[ { "context": "import java.time.LocalDate;\n\n/**\n * ็ณ–ๆžœ็ฑป\n * @author Jarvis\n */\npublic class Candy extends Product {\n publ", "end": 92, "score": 0.9996973872184753, "start": 86, "tag": "NAME", "value": "Jarvis" } ]
null
[]
package com.softmax.design.visit; import java.time.LocalDate; /** * ็ณ–ๆžœ็ฑป * @author Jarvis */ public class Candy extends Product { public Candy(String name, LocalDate producedDate, float price) { super(name, producedDate, price); } }
259
0.687747
0.687747
13
18.461538
20.300116
68
false
false
0
0
0
0
0
0
0.538462
false
false
13
cb1da74f442b3ed837b5d236ad737627057fec1a
27,358,941,712,096
a3fe2bbd7be76efd79b10ec2f4f9031fd8337632
/app/src/main/java/com/microple/jademall/bean/Note.java
36609b5603b618470600c9b8e32b830b770b27c1
[]
no_license
xgf666666/feicui
https://github.com/xgf666666/feicui
f2bb3882ee62eead9d0f827b77ed7f388a018e52
471acb64998388d9ac369e33772229704ed13a31
refs/heads/master
2020-04-11T20:14:12.067000
2018-12-17T07:52:29
2018-12-17T07:52:29
162,064,308
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.microple.jademall.bean; /** * author: xiaoguagnfei * date: 2018/9/4 * describe: */ public class Note { /** * enter_protocol : {"value":"ๅ•†ๅฎถๅ…ฅ้ฉปๆกไพ‹"} */ private EnterProtocolBean enter_protocol; public EnterProtocolBean getEnter_protocol() { return enter_protocol; } public void setEnter_protocol(EnterProtocolBean enter_protocol) { this.enter_protocol = enter_protocol; } public static class EnterProtocolBean { /** * value : ๅ•†ๅฎถๅ…ฅ้ฉปๆกไพ‹ */ private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
UTF-8
Java
757
java
Note.java
Java
[ { "context": "ackage com.microple.jademall.bean;\n\n/**\n * author: xiaoguagnfei\n * date: 2018/9/4\n * describe:\n */\npublic class N", "end": 64, "score": 0.9958834052085876, "start": 52, "tag": "USERNAME", "value": "xiaoguagnfei" } ]
null
[]
package com.microple.jademall.bean; /** * author: xiaoguagnfei * date: 2018/9/4 * describe: */ public class Note { /** * enter_protocol : {"value":"ๅ•†ๅฎถๅ…ฅ้ฉปๆกไพ‹"} */ private EnterProtocolBean enter_protocol; public EnterProtocolBean getEnter_protocol() { return enter_protocol; } public void setEnter_protocol(EnterProtocolBean enter_protocol) { this.enter_protocol = enter_protocol; } public static class EnterProtocolBean { /** * value : ๅ•†ๅฎถๅ…ฅ้ฉปๆกไพ‹ */ private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
757
0.57708
0.568895
39
17.794872
18.089775
69
false
false
0
0
0
0
0
0
0.179487
false
false
13
22cd52b3198054eafd82deac60a09f2bcb88d303
17,935,783,491,103
e0bf864da16ab12fdad5683b9435a0729f738677
/MTM/src/com/rockyniu/todolist/util/Utils.java
73e3d7cfbf09956e5b4993a41118d57c13833449
[ "Apache-2.0" ]
permissive
ManYang/ToDo
https://github.com/ManYang/ToDo
d6ac126a4777ba2a4b3974a5d8d67c212002391b
d4991c890f6c58f9f33c5435eb2a78200ec9c6b6
refs/heads/master
2021-01-16T18:52:23.289000
2014-06-17T12:34:09
2014-06-17T12:34:09
20,941,395
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rockyniu.todolist.util; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TimeZone; import android.accounts.OperationCanceledException; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.util.Log; import android.widget.Toast; import com.google.android.gms.auth.GoogleAuthException; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.util.DateTime; import com.google.api.services.tasks.model.Task; import com.rockyniu.todolist.R; import com.rockyniu.todolist.R.string; import com.rockyniu.todolist.database.model.ToDoItem; public class Utils { public static List<ToDoItem> convertTasksToToDoItems(String userId, List<Task> tasks) { if (tasks == null) { return null; } List<ToDoItem> items = new ArrayList<ToDoItem>(); for (int i = 0; i < tasks.size(); i++) { items.add(convertTaskToToDoItem(userId, tasks.get(i))); } return items; } public static List<Task> convertToDoItemsToTasks(List<ToDoItem> items) { if (items == null) { return null; } List<Task> tasks = new ArrayList<Task>(); for (int i = 0; i < items.size(); i++) { tasks.add(convertToDoItemToTask(items.get(i))); } return tasks; } public static ToDoItem convertTaskToToDoItem(String userId, Task task) { if (task == null) return null; ToDoItem item = new ToDoItem(); // set id item.setId(task.getId()); // set userId item.setUserId(userId); // set modifiedTime item.setModifiedTime(task.getUpdated().getValue()); // set title and priority String title = task.getTitle().trim(); if (title.endsWith("!!")) { title = title.substring(0, title.length() - 2); item.setPriority(2); } else if (title.endsWith("!")) { title = title.substring(0, title.length() - 1); item.setPriority(1); } else if (title.endsWith(".")) { title = title.substring(0, title.length() - 1); item.setPriority(0); } else { item.setPriority(1); // default } if (title.isEmpty()) { item.setTitle("To be done"); // default } else { item.setTitle(title); } // set completed and completedTime if (task.getStatus().equals("completed")) { item.setCompleted(true); long time = task.getCompleted().getValue(); // int offset = TimeZone.getDefault().getOffset(time); item.setCompletedTime(time); } else { item.setCompleted(false); item.setCompletedTime(null); } ; // set dueTime DateTime due = task.getDue(); String notes = task.getNotes(); if (due == null && notes == null) { item.setDueTime(null); } else if (notes != null && notes.matches("^Due .*")) { // set dueTime from notes notes = notes.replace("Due ", ""); long dueTime = DateTime.parseRfc3339(notes).getValue(); // int offset = TimeZone.getDefault().getOffset(dueTime); item.setDueTime(dueTime); } else { // set dueTime from due long time = due.getValue(); int offset = TimeZone.getDefault().getOffset(time); item.setDueTime(time - offset); } // set notes item.setNotes(""); // set deleted if (task.getDeleted() == null || !task.getDeleted()) { item.setDeleted(false); } else { item.setDeleted(true); } return item; } public static Task convertToDoItemToTask(ToDoItem item) { Task task = new Task(); if (item == null) return null; // set id task.setId(item.getId()); // set title String priority = ""; switch (item.getPriority()) { case 2: priority = "!!"; break; case 1: priority = "!"; break; case 0: priority = "."; break; default: priority = "!"; break; } task.setTitle(item.getTitle() + priority); // set notes and due if (item.getDueTime() == null) { task.setDue(null); task.setNotes(null); } else { long time = item.getDueTime(); // int offset = TimeZone.getDefault().getOffset(time); DateTime dueTime = new DateTime(time); task.setDue(dueTime); task.setNotes("Due " + dueTime.toStringRfc3339()); } // set status and completed if (item.isCompleted()) { task.setStatus("completed"); long time = item.getCompletedTime(); // int offset = TimeZone.getDefault().getOffset(time); DateTime completedTime = new DateTime(time); task.setCompleted(completedTime); } else { task.setStatus("needsAction"); task.setCompleted(null); } // set updated task.setUpdated(new DateTime(item.getModifiedTime())); // set deleted task.setDeleted(item.isDeleted()); return task; } /** * Logs the given throwable and shows an error alert dialog with its * message. * * @param activity * activity * @param tag * log tag to use * @param t * throwable to log and show */ public static void logAndShow(Activity activity, String tag, Throwable t) { Log.e(tag, "Error", t); String message = t.getMessage(); if (t instanceof GoogleJsonResponseException) { GoogleJsonError details = ((GoogleJsonResponseException) t) .getDetails(); if (details != null) { message = details.getMessage(); } } else if (t.getCause() instanceof OperationCanceledException) { message = ((OperationCanceledException) t.getCause()).getMessage(); } else if (t.getCause() instanceof GoogleAuthException) { message = ((GoogleAuthException) t.getCause()).getMessage(); } else if (t instanceof IOException) { if (t.getMessage() == null) { message = "IOException"; } } showErrorToast(activity, message); } /** * Shows an toast message with the given message. * * @param activity * activity * @param message * message to show or {@code null} for none */ public static void showErrorToast(Activity activity, String message) { String errorMessage = getErrorMessage(activity, message); showToastInternal(activity, errorMessage); } private static String getErrorMessage(Activity activity, String message) { Resources resources = activity.getResources(); if (message == null) { return resources.getString(R.string.error); } return resources.getString(R.string.error_format, message); } public static void showToastInternal(final Activity activity, final String toastMessage) { activity.runOnUiThread(new Runnable() { public void run() { Toast.makeText(activity, toastMessage, Toast.LENGTH_LONG) .show(); } }); } /** * Shows an alert dialog with the given message. click is need to dismiss * the message. * * @param activity * activity * @param message * message to show or {@code null} for none * @param title * title of dialog */ private static void showNeedClickDialog(Activity activity, String message, String title) { AlertDialog alertDialog; alertDialog = new AlertDialog.Builder(activity).create(); alertDialog.setTitle(title); alertDialog.setMessage(message); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); return; } // public static void showPastDueDialog(Activity activity, String message){ // showNeedClickDialog(activity, message, "Task Past Due!"); // } private static void showTaskCreationErrorDialog(Activity activity, String message) { showNeedClickDialog(activity, message, "Task Creation Error"); } public static void showItemNameIsEmptyDialog(Activity activity) { showTaskCreationErrorDialog(activity, "Task name cannot be empty."); } public static void showDueTimeIsEarlierDialog(Activity activity) { showTaskCreationErrorDialog(activity, "Due time cannot be earlier than now."); } }
UTF-8
Java
7,959
java
Utils.java
Java
[]
null
[]
package com.rockyniu.todolist.util; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TimeZone; import android.accounts.OperationCanceledException; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.util.Log; import android.widget.Toast; import com.google.android.gms.auth.GoogleAuthException; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.util.DateTime; import com.google.api.services.tasks.model.Task; import com.rockyniu.todolist.R; import com.rockyniu.todolist.R.string; import com.rockyniu.todolist.database.model.ToDoItem; public class Utils { public static List<ToDoItem> convertTasksToToDoItems(String userId, List<Task> tasks) { if (tasks == null) { return null; } List<ToDoItem> items = new ArrayList<ToDoItem>(); for (int i = 0; i < tasks.size(); i++) { items.add(convertTaskToToDoItem(userId, tasks.get(i))); } return items; } public static List<Task> convertToDoItemsToTasks(List<ToDoItem> items) { if (items == null) { return null; } List<Task> tasks = new ArrayList<Task>(); for (int i = 0; i < items.size(); i++) { tasks.add(convertToDoItemToTask(items.get(i))); } return tasks; } public static ToDoItem convertTaskToToDoItem(String userId, Task task) { if (task == null) return null; ToDoItem item = new ToDoItem(); // set id item.setId(task.getId()); // set userId item.setUserId(userId); // set modifiedTime item.setModifiedTime(task.getUpdated().getValue()); // set title and priority String title = task.getTitle().trim(); if (title.endsWith("!!")) { title = title.substring(0, title.length() - 2); item.setPriority(2); } else if (title.endsWith("!")) { title = title.substring(0, title.length() - 1); item.setPriority(1); } else if (title.endsWith(".")) { title = title.substring(0, title.length() - 1); item.setPriority(0); } else { item.setPriority(1); // default } if (title.isEmpty()) { item.setTitle("To be done"); // default } else { item.setTitle(title); } // set completed and completedTime if (task.getStatus().equals("completed")) { item.setCompleted(true); long time = task.getCompleted().getValue(); // int offset = TimeZone.getDefault().getOffset(time); item.setCompletedTime(time); } else { item.setCompleted(false); item.setCompletedTime(null); } ; // set dueTime DateTime due = task.getDue(); String notes = task.getNotes(); if (due == null && notes == null) { item.setDueTime(null); } else if (notes != null && notes.matches("^Due .*")) { // set dueTime from notes notes = notes.replace("Due ", ""); long dueTime = DateTime.parseRfc3339(notes).getValue(); // int offset = TimeZone.getDefault().getOffset(dueTime); item.setDueTime(dueTime); } else { // set dueTime from due long time = due.getValue(); int offset = TimeZone.getDefault().getOffset(time); item.setDueTime(time - offset); } // set notes item.setNotes(""); // set deleted if (task.getDeleted() == null || !task.getDeleted()) { item.setDeleted(false); } else { item.setDeleted(true); } return item; } public static Task convertToDoItemToTask(ToDoItem item) { Task task = new Task(); if (item == null) return null; // set id task.setId(item.getId()); // set title String priority = ""; switch (item.getPriority()) { case 2: priority = "!!"; break; case 1: priority = "!"; break; case 0: priority = "."; break; default: priority = "!"; break; } task.setTitle(item.getTitle() + priority); // set notes and due if (item.getDueTime() == null) { task.setDue(null); task.setNotes(null); } else { long time = item.getDueTime(); // int offset = TimeZone.getDefault().getOffset(time); DateTime dueTime = new DateTime(time); task.setDue(dueTime); task.setNotes("Due " + dueTime.toStringRfc3339()); } // set status and completed if (item.isCompleted()) { task.setStatus("completed"); long time = item.getCompletedTime(); // int offset = TimeZone.getDefault().getOffset(time); DateTime completedTime = new DateTime(time); task.setCompleted(completedTime); } else { task.setStatus("needsAction"); task.setCompleted(null); } // set updated task.setUpdated(new DateTime(item.getModifiedTime())); // set deleted task.setDeleted(item.isDeleted()); return task; } /** * Logs the given throwable and shows an error alert dialog with its * message. * * @param activity * activity * @param tag * log tag to use * @param t * throwable to log and show */ public static void logAndShow(Activity activity, String tag, Throwable t) { Log.e(tag, "Error", t); String message = t.getMessage(); if (t instanceof GoogleJsonResponseException) { GoogleJsonError details = ((GoogleJsonResponseException) t) .getDetails(); if (details != null) { message = details.getMessage(); } } else if (t.getCause() instanceof OperationCanceledException) { message = ((OperationCanceledException) t.getCause()).getMessage(); } else if (t.getCause() instanceof GoogleAuthException) { message = ((GoogleAuthException) t.getCause()).getMessage(); } else if (t instanceof IOException) { if (t.getMessage() == null) { message = "IOException"; } } showErrorToast(activity, message); } /** * Shows an toast message with the given message. * * @param activity * activity * @param message * message to show or {@code null} for none */ public static void showErrorToast(Activity activity, String message) { String errorMessage = getErrorMessage(activity, message); showToastInternal(activity, errorMessage); } private static String getErrorMessage(Activity activity, String message) { Resources resources = activity.getResources(); if (message == null) { return resources.getString(R.string.error); } return resources.getString(R.string.error_format, message); } public static void showToastInternal(final Activity activity, final String toastMessage) { activity.runOnUiThread(new Runnable() { public void run() { Toast.makeText(activity, toastMessage, Toast.LENGTH_LONG) .show(); } }); } /** * Shows an alert dialog with the given message. click is need to dismiss * the message. * * @param activity * activity * @param message * message to show or {@code null} for none * @param title * title of dialog */ private static void showNeedClickDialog(Activity activity, String message, String title) { AlertDialog alertDialog; alertDialog = new AlertDialog.Builder(activity).create(); alertDialog.setTitle(title); alertDialog.setMessage(message); alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); return; } // public static void showPastDueDialog(Activity activity, String message){ // showNeedClickDialog(activity, message, "Task Past Due!"); // } private static void showTaskCreationErrorDialog(Activity activity, String message) { showNeedClickDialog(activity, message, "Task Creation Error"); } public static void showItemNameIsEmptyDialog(Activity activity) { showTaskCreationErrorDialog(activity, "Task name cannot be empty."); } public static void showDueTimeIsEarlierDialog(Activity activity) { showTaskCreationErrorDialog(activity, "Due time cannot be earlier than now."); } }
7,959
0.679985
0.677095
295
25.983051
21.293821
76
false
false
0
0
0
0
0
0
2.315254
false
false
13
ec1948ade1d114ac755142de796b748b6da65676
4,011,499,497,860
caa06de4d227e20cbf52cb7fe83114e988e20a7f
/src/java/algorithms/t88/MergeSortedArray.java
0f233e500120ae40f5374a0e7f8372cb153d5b80
[ "MIT" ]
permissive
wodis/leecode-java
https://github.com/wodis/leecode-java
4b16acfbac1549bdfc3071de19ed0b15a407a989
ac470506c37c1b4cd83d60e9b8b8681679b25417
refs/heads/master
2021-01-22T01:05:38.872000
2016-09-24T04:00:00
2016-09-24T04:00:00
33,039,653
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package algorithms.t88; /** * Given two sorted integer arrays A and B, merge B into A as one sorted array. * <p/> * Note: * You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. * The number of elements initialized in A and B are m and n respectively. * Created by wudi on 15-4-16. */ public class MergeSortedArray { public void merge(int A[], int m, int B[], int n) { int pA = m - 1; int pB = n - 1; for (int i = m + n - 1; i >= 0; i--) { if (pA < 0 && pB >= 0) { A[i] = B[pB]; pB--; continue; } else if (pB < 0 && pA >= 0) { A[i] = A[pA]; pA--; continue; } if (A[pA] > B[pB]) { A[i] = A[pA]; pA--; } else if (A[pA] <= B[pB]) { A[i] = B[pB]; pB--; } } } }
UTF-8
Java
1,000
java
MergeSortedArray.java
Java
[ { "context": "in A and B are m and n respectively.\n * Created by wudi on 15-4-16.\n */\npublic class MergeSortedArray {\n ", "end": 338, "score": 0.9983029365539551, "start": 334, "tag": "USERNAME", "value": "wudi" } ]
null
[]
package algorithms.t88; /** * Given two sorted integer arrays A and B, merge B into A as one sorted array. * <p/> * Note: * You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. * The number of elements initialized in A and B are m and n respectively. * Created by wudi on 15-4-16. */ public class MergeSortedArray { public void merge(int A[], int m, int B[], int n) { int pA = m - 1; int pB = n - 1; for (int i = m + n - 1; i >= 0; i--) { if (pA < 0 && pB >= 0) { A[i] = B[pB]; pB--; continue; } else if (pB < 0 && pA >= 0) { A[i] = A[pA]; pA--; continue; } if (A[pA] > B[pB]) { A[i] = A[pA]; pA--; } else if (A[pA] <= B[pB]) { A[i] = B[pB]; pB--; } } } }
1,000
0.418
0.403
35
27.571428
24.110798
118
false
false
0
0
0
0
0
0
0.542857
false
false
13
3a7cb57d16cdfcfce50db8f3371a916c8b74813f
13,572,096,713,222
63f496891a5cfe7bb788f2e6690d727b107d5dee
/blytics-lib/src/main/java/com/baloota/blytics/platforms/FlurryPlatform.java
2c0c92de52281a47a6a3cda7ec661c0245a0e18e
[]
no_license
baloota/b-lytics
https://github.com/baloota/b-lytics
80f254de1471c5f5b1ab91d19be8e12be4c0624b
c32b73301f1ddaf2bb3c6cf0d755300ba9fa4dfd
refs/heads/master
2021-08-22T22:25:57.050000
2021-06-04T06:58:21
2021-06-04T06:58:21
132,894,505
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.baloota.blytics.platforms; import android.app.Application; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import com.baloota.blytics.AnalyticsPlatform; import com.baloota.blytics.model.Session; import com.flurry.android.FlurryAgent; public class FlurryPlatform extends AnalyticsPlatform { private Application application; @Override public String getName() { return "Flurry"; } @Override public boolean isEnabled(@NonNull Application application) { boolean enabled = false; try { enabled = Class.forName("com.flurry.android.FlurryAgent") != null; } catch (ClassNotFoundException ignored) { Log.i("FlurryPlatform", "FlurryAnalytics not found!"); } return enabled; } @Override public void initialize(@NonNull Application application, boolean debug) { super.initialize(application, debug); this.application = application; } @Override public void track(@NonNull String event, @NonNull Bundle params) { FlurryAgent.logEvent(event, asMap(ensureParamsLength(params, 100))); } @Override public void onSessionStart(Session session) { FlurryAgent.onStartSession(application); } @Override public void onSessionFinish(Session session) { FlurryAgent.onEndSession(application); } @Override public void setUserId(@NonNull String userId) { FlurryAgent.setUserId(userId); } @Override public void setUserProperty(String property, String value) { } }
UTF-8
Java
1,624
java
FlurryPlatform.java
Java
[]
null
[]
package com.baloota.blytics.platforms; import android.app.Application; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import com.baloota.blytics.AnalyticsPlatform; import com.baloota.blytics.model.Session; import com.flurry.android.FlurryAgent; public class FlurryPlatform extends AnalyticsPlatform { private Application application; @Override public String getName() { return "Flurry"; } @Override public boolean isEnabled(@NonNull Application application) { boolean enabled = false; try { enabled = Class.forName("com.flurry.android.FlurryAgent") != null; } catch (ClassNotFoundException ignored) { Log.i("FlurryPlatform", "FlurryAnalytics not found!"); } return enabled; } @Override public void initialize(@NonNull Application application, boolean debug) { super.initialize(application, debug); this.application = application; } @Override public void track(@NonNull String event, @NonNull Bundle params) { FlurryAgent.logEvent(event, asMap(ensureParamsLength(params, 100))); } @Override public void onSessionStart(Session session) { FlurryAgent.onStartSession(application); } @Override public void onSessionFinish(Session session) { FlurryAgent.onEndSession(application); } @Override public void setUserId(@NonNull String userId) { FlurryAgent.setUserId(userId); } @Override public void setUserProperty(String property, String value) { } }
1,624
0.687808
0.685961
63
24.777779
23.766352
78
false
false
0
0
0
0
0
0
0.428571
false
false
13
3e47da2bdb1d6c7680210ec907f7f8b0eb7c2482
884,763,321,265
0a443175b12eb68c24e1cf5f4f5a021455ac9eb4
/sos-client/src/sos/police_v2/base/worldModel/PoliceWorldModel.java
a9ca2cf292e6029fe1e5cfb6eba8f69ba45714a8
[ "MIT" ]
permissive
reyhanehpahlevan/SOS_rescue_agent
https://github.com/reyhanehpahlevan/SOS_rescue_agent
7b52302b14f9bd927f9f82f358439248f1c26303
4dafa5a6cb3ff5ef2b34abeafbd82fc78f8b79f8
refs/heads/main
2023-03-03T07:33:42.883000
2021-02-15T10:19:50
2021-02-15T10:19:50
304,570,285
0
0
MIT
false
2020-10-16T09:12:56
2020-10-16T08:46:36
2020-10-16T08:50:12
2020-10-16T09:12:55
0
0
0
0
null
false
false
package sos.police_v2.base.worldModel; import java.awt.Point; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Formatter; import java.util.HashSet; import java.util.PriorityQueue; import rescuecore2.geometry.Point2D; import rescuecore2.misc.Pair; import rescuecore2.worldmodel.EntityID; import sos.base.SOSAgent; import sos.base.SOSConstant; import sos.base.SOSWorldModel; import sos.base.entities.Area; import sos.base.entities.Blockade; import sos.base.entities.Building; import sos.base.entities.Human; import sos.base.entities.PoliceForce; import sos.base.entities.Road; import sos.base.entities.StandardEntity; import sos.base.sosFireZone.util.ConvexHull_arr_New; import sos.base.util.mapRecognition.MapRecognition.MapName; import sos.fire_v2.base.tools.BuildingBlock; import sos.fire_v2.base.worldmodel.FirePrecompute.Mode; import sos.police_v2.PoliceConstants; import sos.police_v2.PoliceForceAgent; import sos.police_v2.PoliceUtils; import sos.police_v2.state.preCompute.PoliceForceTask; import sos.search_v2.searchType.CommunicationlessSearch; import com.infomatiq.jsi.IntProcedure; import com.infomatiq.jsi.Rectangle; public class PoliceWorldModel extends SOSWorldModel { private ArrayList<PoliceForceTask> policeTasks = null; private PoliceForceTask meTask; private ArrayList<BuildingBlock> buildingBlocks = new ArrayList<BuildingBlock>(); private ArrayList<BuildingBlock> island = new ArrayList<BuildingBlock>(); // private ArrayList<PoliceBuilding> policeBuildings; private HashSet<Area> highways = new HashSet<Area>(); private HashSet<Area> junctionPoints; private ArrayList<PoliceForceTask> policeForSpecialTask = new ArrayList<PoliceForceTask>(); // private ConvexHull convexHull = new ConvexHull(); // private ArrayList<Point> convex = new ArrayList<Point>(); public PoliceWorldModel(SOSAgent<? extends StandardEntity> sosAgent) { super(sosAgent); } @Override public void precompute() { super.precompute(); setDefaultValueByScenarioCondition(); makePoliceTasks(); setSomePoliceForSpecialTasks(); } private void setDefaultValueByScenarioCondition() { if (PoliceConstants.STANDARD_OF_MAP < 3) { if (fireBrigades().size() < 11) PoliceConstants.Value.FireBrigade.setValue(8); else PoliceConstants.Value.FireBrigade.setValue(6); if (ambulanceTeams().size() < 11) PoliceConstants.Value.AmbulanceTeam.setValue(7); else PoliceConstants.Value.AmbulanceTeam.setValue(5); if (refuges().size() < 2) PoliceConstants.Value.Refuge.setValue(10); else PoliceConstants.Value.Refuge.setValue(5); } if (PoliceConstants.STANDARD_OF_MAP >= 3) { if (fireBrigades().size() < 15) PoliceConstants.Value.FireBrigade.setValue(8); else PoliceConstants.Value.FireBrigade.setValue(6); if (ambulanceTeams().size() < 15) PoliceConstants.Value.AmbulanceTeam.setValue(7); else PoliceConstants.Value.AmbulanceTeam.setValue(5); if (refuges().size() < 3) PoliceConstants.Value.Refuge.setValue(7); else PoliceConstants.Value.Refuge.setValue(4); } PoliceConstants.Value.PoliceForce.setValue(0); if (policeForces().size() < 9) PoliceConstants.Value.PoliceForceInBuilding.setValue(10); else PoliceConstants.Value.PoliceForceInBuilding.setValue(8); } public void makeHighways() { if (!(sosAgent().getMapInfo().getRealMapName() == MapName.Kobe || sosAgent().getMapInfo().getRealMapName() == MapName.VC)) return; ArrayList<ConvexHull_arr_New> convexes = new ArrayList<ConvexHull_arr_New>(); long t = System.currentTimeMillis(); for (BuildingBlock bblock : islands()) { convexes.add(new ConvexHull_arr_New(bblock.buildings())); } HashSet<Area> areahash = new HashSet<Area>(); ArrayList<Area> roadsInIlandsList = new ArrayList<Area>(); FOR: for (Road road : roads()) { for (ConvexHull_arr_New convexHullNew : convexes) { // if(convexHullNew.isInConvex(road.getApexList())) if ((road.isNeighbourWithBuilding() && road.getSOSGroundArea() < PoliceConstants.VERY_SMALL_ROAD_GROUND_IN_MM)) continue FOR; if (convexHullNew.contains(road.getX(), road.getY())) { roadsInIlandsList.add(road); continue FOR; } } areahash.add(road); } for (Area road : roadsInIlandsList) { int i = 0; for (Area neigh : road.getNeighbours()) { if (areahash.contains(neigh)) i++; } if (i >= 2) areahash.add(road); } ArrayList<Area> removeList = new ArrayList<Area>(); for (Area area : areahash) { int i = 0; for (Area neigh : area.getNeighbours()) { if (areahash.contains(neigh)) i++; } if (i < 2) removeList.add(area); } areahash.removeAll(removeList); highways = areahash; sosAgent().log.consoleInfo("highways got:" + (System.currentTimeMillis() - t) + "ms"); makeJunction(); } private void makeJunction() { long t = System.currentTimeMillis(); int LENGHT = 3; int VALIDCOUNT = 2; junctionPoints = new HashSet<Area>(); FOR: for (Area road : highways) { if (road.getNeighbours().size() >= 2) { int validCount = 0; ArrayList<Area> tmp = new ArrayList<Area>(); tmp.add(road); tmp.addAll(road.getNeighbours()); for (Area area : road.getNeighbours()) { if (!highways.contains(area)) continue FOR; if (getLenghtOfRoad(highways, tmp, area, LENGHT) >= LENGHT) validCount++; } if (validCount > VALIDCOUNT) { for (Area area : road.getNeighbours()) { if (junctionPoints.contains(area)) continue FOR; } junctionPoints.add(road); } } } /** * Filtering some junction becuase some of them is not correct and some near each other */ long avg = 0; short index = 0; Pair<Area, Long> select2 = null; for (Area select1 : junctionPoints) { select2 = getNearestJunction(select1); avg += select2.second(); index++; } if (index != 0) avg = avg / index; long limit = (long) (avg * (0.7f)); // System.err.println("avg=" + avg + " limit=" + limit); ArrayList<Area> removelist = new ArrayList<Area>(); for (Area select1 : junctionPoints) { select2 = getNearestJunction(select1); if (select2.second() < limit) { if (!removelist.contains(select1)) removelist.add(select1); if (!removelist.contains(select2.first())) removelist.add(select2.first()); } } junctionPoints.removeAll(removelist); /** * back some removed junctionpoint that remove wrong */ if (removelist.size() > 0) { ArrayList<Area> addlist = new ArrayList<Area>(); HashSet<Area> invalid = new HashSet<Area>(junctionPoints); for (Area n : junctionPoints) { Area neighbor = getHighwaysNeighbour(highways, removelist, invalid, n, n); if (neighbor != null) { // temp.add(neighbor); if (!addlist.contains(neighbor)) addlist.add(neighbor); } } junctionPoints.addAll(addlist); } sosAgent().log.consoleInfo("Junctions got:" + (System.currentTimeMillis() - t) + "ms"); } private Pair<Area, Long> getNearestJunction(Area start) { Area result = null; long minDis = Long.MAX_VALUE; for (Area select : junctionPoints) { if (result == null) { result = select; continue; } long temp = (long) Point.distance(start.getX(), start.getY(), select.getX(), select.getY()); if (temp == 0) continue; if (minDis > temp) { result = select; minDis = temp; } } return new Pair<Area, Long>(result, minDis); } private Area getHighwaysNeighbour(HashSet<Area> areahash, Collection<Area> junctionPoints2, HashSet<Area> OldPath, Area area, Area startTarget) { // System.out.println(OldPath); if (junctionPoints2.contains(area)) { return area; } int mindist = Integer.MAX_VALUE; Area result = null; for (Area area2 : area.getNeighbours()) { if (OldPath.contains(area2)) continue; if (area2.equals(startTarget)) continue; if (!areahash.contains(area2)) continue; HashSet<Area> newPath = OldPath; newPath.add(area2); Area a = getHighwaysNeighbour(areahash, junctionPoints2, newPath, area2, startTarget); if (a != null) { int min = PoliceUtils.getDistance(area, a); if (mindist > min) { result = a; mindist = min; } } } return result; } int getLenghtOfRoad(HashSet<Area> areahash, ArrayList<Area> OldPath, Area area, int max) { if (max == 0) return 0; int tmpmax = 0; for (Area area2 : area.getNeighbours()) { if (area2 instanceof Building) continue; if (!areahash.contains(area2)) continue; if (OldPath.contains(area2)) continue; // ArrayList<Area> newPath = new ArrayList<Area>(OldPath); ArrayList<Area> newPath = OldPath; newPath.add(area2); tmpmax = Math.max(tmpmax, getLenghtOfRoad(areahash, newPath, area2, max - 1)); } return tmpmax + 1; } public HashSet<Area> getJunctionPoints() { return junctionPoints; } public HashSet<Area> getHighways() { return highways; } private void makePoliceTasks() { policeTasks = new ArrayList<PoliceForceTask>(); short tmpindex = 0; for (PoliceForce policeForce : policeForces()) { PoliceForceTask task = new PoliceForceTask(policeForce, tmpindex++); task.setDefaultValue(); policeTasks.add(task); // policeForce.selfToTask = task; if (me().equals(policeForce)) meTask = task; } } private void setSomePoliceForSpecialTasks() { int num = 1; Human centeralMan = CommunicationlessSearch.selectCenteralMan(this); if (centeralMan instanceof PoliceForce && num > getPoliceForSpecialTask().size()) getPoliceForSpecialTask().add(getPoliceTasks((PoliceForce) centeralMan)); for (PoliceForceTask ptask : getPoliceTasks()) { if (getPoliceForSpecialTask().size() == num) return; if (ptask.getDefaultValue() == 0 && !getPoliceForSpecialTask().contains(ptask)) { getPoliceForSpecialTask().add(ptask); ptask.setDefaultValue(PoliceConstants.Value.PoliceForSpecialTasks.getValue()); ptask.setJobDone(10000, false); log().debug("SpecialPolice===>" + ptask); } } } public PoliceForceTask meTask() { return meTask; } public void makeIslands() { if (!(sosAgent().getMapInfo().getRealMapName() == MapName.Kobe || sosAgent().getMapInfo().getRealMapName() == MapName.VC )) return; long start = System.currentTimeMillis(); File islandFile = new File("SOSFiles/IslandsPolice/" + sosAgent().getMapInfo().getMapName() + ".txt"); try {// if file exists FileInputStream fstream = new FileInputStream(islandFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s = br.readLine(); int numberOfIslands = Integer.parseInt(s); for (int i = 0; i < numberOfIslands; i++) { sos.fire_v2.base.tools.BuildingBlock bb = new BuildingBlock(sosAgent().model()); s = br.readLine(); int numberOfIslandBuildings = Integer.parseInt(s); ArrayList<Building> buildings = new ArrayList<Building>(numberOfIslandBuildings); for (int j = 0; j < numberOfIslandBuildings; j++) { s = br.readLine(); int index = Integer.parseInt(s); buildings.add(sosAgent().model().buildings().get(index)); } bb.makeByDistance(Mode.ReadFromFile, buildings); islands().add(bb); } in.close(); for (BuildingBlock bb : islands()) { bb.setIslandNeighbors(); } } catch (Exception e) {// if file dose not exist ArrayList<Building> allBuildings = new ArrayList<Building>(sosAgent().model().buildings()); while (allBuildings.size() > 0) { BuildingBlock bb = new BuildingBlock(sosAgent().model()); allBuildings = bb.makeByDistance(Mode.Compute, allBuildings); if (bb.buildings().size() > 0) { islands().add(bb); } } makeIslandsFile(islandFile); } sosAgent().log.consoleInfo("Police Islands got:" + (System.currentTimeMillis() - start) + "ms"); } /** @author nima */ private void makeIslandsFile(File file) { if (SOSConstant.IS_CHALLENGE_RUNNING) return; try { file.getParentFile().mkdirs(); Formatter f = new Formatter(file); f.format("%d\n", islands().size()); for (BuildingBlock bb : islands()) { f.format("%d\n", bb.buildings().size()); for (Building b : bb.buildings()) f.format("%d\n", b.getBuildingIndex()); } f.flush(); f.close(); } catch (FileNotFoundException e) { log().error("Write Island File]" + e.getMessage()); // e.printStackTrace(); } } public Point2D getCeterOfMap() { int x = getWorldBounds().first().first() + getWorldBounds().second().first(); int y = getWorldBounds().first().second() + getWorldBounds().second().second(); return new Point2D(x, y); } public PriorityQueue<Blockade> getBlockadesInRange(int x, int y, int range) { if (!indexed) { index(); } final PriorityQueue<Blockade> result = new PriorityQueue<Blockade>(20, new DistanceComparator()); Rectangle r = new Rectangle(x - range, y - range, x + range, y + range); index.intersects(r, new IntProcedure() { @Override public boolean execute(int id) { StandardEntity e = getEntity(new EntityID(id)); if (e != null && e instanceof Road && ((Road) e).isBlockadesDefined()) { for (Blockade blockade : ((Road) e).getBlockades()) { if (PoliceUtils.isValid(blockade)) result.add(blockade); } } return true; } }); return result; } public ArrayList<BuildingBlock> buildingBlocks() { return buildingBlocks; } public void setBuildingBlocks(ArrayList<BuildingBlock> buildingBlocks) { this.buildingBlocks = buildingBlocks; } public ArrayList<BuildingBlock> islands() { return island; } public void setIsland(ArrayList<BuildingBlock> island) { this.island = island; } public ArrayList<PoliceForceTask> getPoliceTasks() { return policeTasks; } private class DistanceComparator implements java.util.Comparator<Blockade> { @Override public int compare(Blockade c1, Blockade c2) { return (int) (PoliceUtils.getBlockadeDistance(c1) - PoliceUtils.getBlockadeDistance(c2)); } } public PoliceForceTask getPoliceTasks(PoliceForce o1) {//TODO behine tar beshe for (PoliceForceTask iterable_element : policeTasks) { if (iterable_element.getRealEntity().equals(o1)) return iterable_element; } return null; } @Override public PoliceForceAgent sosAgent() { return (PoliceForceAgent) super.sosAgent(); } public ArrayList<PoliceForceTask> getPoliceForSpecialTask() { return policeForSpecialTask; } }
UTF-8
Java
15,160
java
PoliceWorldModel.java
Java
[ { "context": "TimeMillis() - start) + \"ms\");\r\n\t}\r\n\r\n\t/** @author nima */\r\n\tprivate void makeIslandsFile(File file) {\r\n\t", "end": 12481, "score": 0.9992327094078064, "start": 12477, "tag": "USERNAME", "value": "nima" } ]
null
[]
package sos.police_v2.base.worldModel; import java.awt.Point; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Formatter; import java.util.HashSet; import java.util.PriorityQueue; import rescuecore2.geometry.Point2D; import rescuecore2.misc.Pair; import rescuecore2.worldmodel.EntityID; import sos.base.SOSAgent; import sos.base.SOSConstant; import sos.base.SOSWorldModel; import sos.base.entities.Area; import sos.base.entities.Blockade; import sos.base.entities.Building; import sos.base.entities.Human; import sos.base.entities.PoliceForce; import sos.base.entities.Road; import sos.base.entities.StandardEntity; import sos.base.sosFireZone.util.ConvexHull_arr_New; import sos.base.util.mapRecognition.MapRecognition.MapName; import sos.fire_v2.base.tools.BuildingBlock; import sos.fire_v2.base.worldmodel.FirePrecompute.Mode; import sos.police_v2.PoliceConstants; import sos.police_v2.PoliceForceAgent; import sos.police_v2.PoliceUtils; import sos.police_v2.state.preCompute.PoliceForceTask; import sos.search_v2.searchType.CommunicationlessSearch; import com.infomatiq.jsi.IntProcedure; import com.infomatiq.jsi.Rectangle; public class PoliceWorldModel extends SOSWorldModel { private ArrayList<PoliceForceTask> policeTasks = null; private PoliceForceTask meTask; private ArrayList<BuildingBlock> buildingBlocks = new ArrayList<BuildingBlock>(); private ArrayList<BuildingBlock> island = new ArrayList<BuildingBlock>(); // private ArrayList<PoliceBuilding> policeBuildings; private HashSet<Area> highways = new HashSet<Area>(); private HashSet<Area> junctionPoints; private ArrayList<PoliceForceTask> policeForSpecialTask = new ArrayList<PoliceForceTask>(); // private ConvexHull convexHull = new ConvexHull(); // private ArrayList<Point> convex = new ArrayList<Point>(); public PoliceWorldModel(SOSAgent<? extends StandardEntity> sosAgent) { super(sosAgent); } @Override public void precompute() { super.precompute(); setDefaultValueByScenarioCondition(); makePoliceTasks(); setSomePoliceForSpecialTasks(); } private void setDefaultValueByScenarioCondition() { if (PoliceConstants.STANDARD_OF_MAP < 3) { if (fireBrigades().size() < 11) PoliceConstants.Value.FireBrigade.setValue(8); else PoliceConstants.Value.FireBrigade.setValue(6); if (ambulanceTeams().size() < 11) PoliceConstants.Value.AmbulanceTeam.setValue(7); else PoliceConstants.Value.AmbulanceTeam.setValue(5); if (refuges().size() < 2) PoliceConstants.Value.Refuge.setValue(10); else PoliceConstants.Value.Refuge.setValue(5); } if (PoliceConstants.STANDARD_OF_MAP >= 3) { if (fireBrigades().size() < 15) PoliceConstants.Value.FireBrigade.setValue(8); else PoliceConstants.Value.FireBrigade.setValue(6); if (ambulanceTeams().size() < 15) PoliceConstants.Value.AmbulanceTeam.setValue(7); else PoliceConstants.Value.AmbulanceTeam.setValue(5); if (refuges().size() < 3) PoliceConstants.Value.Refuge.setValue(7); else PoliceConstants.Value.Refuge.setValue(4); } PoliceConstants.Value.PoliceForce.setValue(0); if (policeForces().size() < 9) PoliceConstants.Value.PoliceForceInBuilding.setValue(10); else PoliceConstants.Value.PoliceForceInBuilding.setValue(8); } public void makeHighways() { if (!(sosAgent().getMapInfo().getRealMapName() == MapName.Kobe || sosAgent().getMapInfo().getRealMapName() == MapName.VC)) return; ArrayList<ConvexHull_arr_New> convexes = new ArrayList<ConvexHull_arr_New>(); long t = System.currentTimeMillis(); for (BuildingBlock bblock : islands()) { convexes.add(new ConvexHull_arr_New(bblock.buildings())); } HashSet<Area> areahash = new HashSet<Area>(); ArrayList<Area> roadsInIlandsList = new ArrayList<Area>(); FOR: for (Road road : roads()) { for (ConvexHull_arr_New convexHullNew : convexes) { // if(convexHullNew.isInConvex(road.getApexList())) if ((road.isNeighbourWithBuilding() && road.getSOSGroundArea() < PoliceConstants.VERY_SMALL_ROAD_GROUND_IN_MM)) continue FOR; if (convexHullNew.contains(road.getX(), road.getY())) { roadsInIlandsList.add(road); continue FOR; } } areahash.add(road); } for (Area road : roadsInIlandsList) { int i = 0; for (Area neigh : road.getNeighbours()) { if (areahash.contains(neigh)) i++; } if (i >= 2) areahash.add(road); } ArrayList<Area> removeList = new ArrayList<Area>(); for (Area area : areahash) { int i = 0; for (Area neigh : area.getNeighbours()) { if (areahash.contains(neigh)) i++; } if (i < 2) removeList.add(area); } areahash.removeAll(removeList); highways = areahash; sosAgent().log.consoleInfo("highways got:" + (System.currentTimeMillis() - t) + "ms"); makeJunction(); } private void makeJunction() { long t = System.currentTimeMillis(); int LENGHT = 3; int VALIDCOUNT = 2; junctionPoints = new HashSet<Area>(); FOR: for (Area road : highways) { if (road.getNeighbours().size() >= 2) { int validCount = 0; ArrayList<Area> tmp = new ArrayList<Area>(); tmp.add(road); tmp.addAll(road.getNeighbours()); for (Area area : road.getNeighbours()) { if (!highways.contains(area)) continue FOR; if (getLenghtOfRoad(highways, tmp, area, LENGHT) >= LENGHT) validCount++; } if (validCount > VALIDCOUNT) { for (Area area : road.getNeighbours()) { if (junctionPoints.contains(area)) continue FOR; } junctionPoints.add(road); } } } /** * Filtering some junction becuase some of them is not correct and some near each other */ long avg = 0; short index = 0; Pair<Area, Long> select2 = null; for (Area select1 : junctionPoints) { select2 = getNearestJunction(select1); avg += select2.second(); index++; } if (index != 0) avg = avg / index; long limit = (long) (avg * (0.7f)); // System.err.println("avg=" + avg + " limit=" + limit); ArrayList<Area> removelist = new ArrayList<Area>(); for (Area select1 : junctionPoints) { select2 = getNearestJunction(select1); if (select2.second() < limit) { if (!removelist.contains(select1)) removelist.add(select1); if (!removelist.contains(select2.first())) removelist.add(select2.first()); } } junctionPoints.removeAll(removelist); /** * back some removed junctionpoint that remove wrong */ if (removelist.size() > 0) { ArrayList<Area> addlist = new ArrayList<Area>(); HashSet<Area> invalid = new HashSet<Area>(junctionPoints); for (Area n : junctionPoints) { Area neighbor = getHighwaysNeighbour(highways, removelist, invalid, n, n); if (neighbor != null) { // temp.add(neighbor); if (!addlist.contains(neighbor)) addlist.add(neighbor); } } junctionPoints.addAll(addlist); } sosAgent().log.consoleInfo("Junctions got:" + (System.currentTimeMillis() - t) + "ms"); } private Pair<Area, Long> getNearestJunction(Area start) { Area result = null; long minDis = Long.MAX_VALUE; for (Area select : junctionPoints) { if (result == null) { result = select; continue; } long temp = (long) Point.distance(start.getX(), start.getY(), select.getX(), select.getY()); if (temp == 0) continue; if (minDis > temp) { result = select; minDis = temp; } } return new Pair<Area, Long>(result, minDis); } private Area getHighwaysNeighbour(HashSet<Area> areahash, Collection<Area> junctionPoints2, HashSet<Area> OldPath, Area area, Area startTarget) { // System.out.println(OldPath); if (junctionPoints2.contains(area)) { return area; } int mindist = Integer.MAX_VALUE; Area result = null; for (Area area2 : area.getNeighbours()) { if (OldPath.contains(area2)) continue; if (area2.equals(startTarget)) continue; if (!areahash.contains(area2)) continue; HashSet<Area> newPath = OldPath; newPath.add(area2); Area a = getHighwaysNeighbour(areahash, junctionPoints2, newPath, area2, startTarget); if (a != null) { int min = PoliceUtils.getDistance(area, a); if (mindist > min) { result = a; mindist = min; } } } return result; } int getLenghtOfRoad(HashSet<Area> areahash, ArrayList<Area> OldPath, Area area, int max) { if (max == 0) return 0; int tmpmax = 0; for (Area area2 : area.getNeighbours()) { if (area2 instanceof Building) continue; if (!areahash.contains(area2)) continue; if (OldPath.contains(area2)) continue; // ArrayList<Area> newPath = new ArrayList<Area>(OldPath); ArrayList<Area> newPath = OldPath; newPath.add(area2); tmpmax = Math.max(tmpmax, getLenghtOfRoad(areahash, newPath, area2, max - 1)); } return tmpmax + 1; } public HashSet<Area> getJunctionPoints() { return junctionPoints; } public HashSet<Area> getHighways() { return highways; } private void makePoliceTasks() { policeTasks = new ArrayList<PoliceForceTask>(); short tmpindex = 0; for (PoliceForce policeForce : policeForces()) { PoliceForceTask task = new PoliceForceTask(policeForce, tmpindex++); task.setDefaultValue(); policeTasks.add(task); // policeForce.selfToTask = task; if (me().equals(policeForce)) meTask = task; } } private void setSomePoliceForSpecialTasks() { int num = 1; Human centeralMan = CommunicationlessSearch.selectCenteralMan(this); if (centeralMan instanceof PoliceForce && num > getPoliceForSpecialTask().size()) getPoliceForSpecialTask().add(getPoliceTasks((PoliceForce) centeralMan)); for (PoliceForceTask ptask : getPoliceTasks()) { if (getPoliceForSpecialTask().size() == num) return; if (ptask.getDefaultValue() == 0 && !getPoliceForSpecialTask().contains(ptask)) { getPoliceForSpecialTask().add(ptask); ptask.setDefaultValue(PoliceConstants.Value.PoliceForSpecialTasks.getValue()); ptask.setJobDone(10000, false); log().debug("SpecialPolice===>" + ptask); } } } public PoliceForceTask meTask() { return meTask; } public void makeIslands() { if (!(sosAgent().getMapInfo().getRealMapName() == MapName.Kobe || sosAgent().getMapInfo().getRealMapName() == MapName.VC )) return; long start = System.currentTimeMillis(); File islandFile = new File("SOSFiles/IslandsPolice/" + sosAgent().getMapInfo().getMapName() + ".txt"); try {// if file exists FileInputStream fstream = new FileInputStream(islandFile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s = br.readLine(); int numberOfIslands = Integer.parseInt(s); for (int i = 0; i < numberOfIslands; i++) { sos.fire_v2.base.tools.BuildingBlock bb = new BuildingBlock(sosAgent().model()); s = br.readLine(); int numberOfIslandBuildings = Integer.parseInt(s); ArrayList<Building> buildings = new ArrayList<Building>(numberOfIslandBuildings); for (int j = 0; j < numberOfIslandBuildings; j++) { s = br.readLine(); int index = Integer.parseInt(s); buildings.add(sosAgent().model().buildings().get(index)); } bb.makeByDistance(Mode.ReadFromFile, buildings); islands().add(bb); } in.close(); for (BuildingBlock bb : islands()) { bb.setIslandNeighbors(); } } catch (Exception e) {// if file dose not exist ArrayList<Building> allBuildings = new ArrayList<Building>(sosAgent().model().buildings()); while (allBuildings.size() > 0) { BuildingBlock bb = new BuildingBlock(sosAgent().model()); allBuildings = bb.makeByDistance(Mode.Compute, allBuildings); if (bb.buildings().size() > 0) { islands().add(bb); } } makeIslandsFile(islandFile); } sosAgent().log.consoleInfo("Police Islands got:" + (System.currentTimeMillis() - start) + "ms"); } /** @author nima */ private void makeIslandsFile(File file) { if (SOSConstant.IS_CHALLENGE_RUNNING) return; try { file.getParentFile().mkdirs(); Formatter f = new Formatter(file); f.format("%d\n", islands().size()); for (BuildingBlock bb : islands()) { f.format("%d\n", bb.buildings().size()); for (Building b : bb.buildings()) f.format("%d\n", b.getBuildingIndex()); } f.flush(); f.close(); } catch (FileNotFoundException e) { log().error("Write Island File]" + e.getMessage()); // e.printStackTrace(); } } public Point2D getCeterOfMap() { int x = getWorldBounds().first().first() + getWorldBounds().second().first(); int y = getWorldBounds().first().second() + getWorldBounds().second().second(); return new Point2D(x, y); } public PriorityQueue<Blockade> getBlockadesInRange(int x, int y, int range) { if (!indexed) { index(); } final PriorityQueue<Blockade> result = new PriorityQueue<Blockade>(20, new DistanceComparator()); Rectangle r = new Rectangle(x - range, y - range, x + range, y + range); index.intersects(r, new IntProcedure() { @Override public boolean execute(int id) { StandardEntity e = getEntity(new EntityID(id)); if (e != null && e instanceof Road && ((Road) e).isBlockadesDefined()) { for (Blockade blockade : ((Road) e).getBlockades()) { if (PoliceUtils.isValid(blockade)) result.add(blockade); } } return true; } }); return result; } public ArrayList<BuildingBlock> buildingBlocks() { return buildingBlocks; } public void setBuildingBlocks(ArrayList<BuildingBlock> buildingBlocks) { this.buildingBlocks = buildingBlocks; } public ArrayList<BuildingBlock> islands() { return island; } public void setIsland(ArrayList<BuildingBlock> island) { this.island = island; } public ArrayList<PoliceForceTask> getPoliceTasks() { return policeTasks; } private class DistanceComparator implements java.util.Comparator<Blockade> { @Override public int compare(Blockade c1, Blockade c2) { return (int) (PoliceUtils.getBlockadeDistance(c1) - PoliceUtils.getBlockadeDistance(c2)); } } public PoliceForceTask getPoliceTasks(PoliceForce o1) {//TODO behine tar beshe for (PoliceForceTask iterable_element : policeTasks) { if (iterable_element.getRealEntity().equals(o1)) return iterable_element; } return null; } @Override public PoliceForceAgent sosAgent() { return (PoliceForceAgent) super.sosAgent(); } public ArrayList<PoliceForceTask> getPoliceForSpecialTask() { return policeForSpecialTask; } }
15,160
0.670646
0.663193
485
29.257732
25.387747
146
false
false
0
0
0
0
0
0
2.837113
false
false
13
f2796e60aa24abcca445fe018acb1f937a247e8e
20,641,612,834,601
efbd969e487a37482e4afb7c91ed16f04b856de2
/empire-db-codegen/src/test/java/org/apache/empire/db/codegen/WriterServiceTest.java
433f45ed4abcb5dbd2a16791036e90ca988c6caf
[ "Apache-2.0" ]
permissive
apache/empire-db
https://github.com/apache/empire-db
28bc21571142b07fd3f87f5aa1abcf31e6076e11
0bf99b95f086a5ebd82762a43457a7a3e2578e99
refs/heads/master
2023-09-04T01:24:24.916000
2023-08-04T10:01:42
2023-08-04T10:01:42
2,046,220
69
31
Apache-2.0
false
2023-09-07T10:34:41
2011-07-14T07:03:04
2023-07-25T13:43:09
2023-09-07T10:34:40
15,314
75
28
3
Java
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.empire.db.codegen; import static org.junit.Assert.assertEquals; import org.apache.empire.data.DataType; import org.apache.empire.db.DBTableColumn; import org.junit.Test; import org.mockito.Mockito; public class WriterServiceTest { @Test public void testGetTableClassName() { CodeGenConfig config = new CodeGenConfig(); WriterService service = new WriterService(config); assertEquals("TestTable", service.getTableClassName("test_table")); assertEquals("TestTable", service.getTableClassName("TEST_TABLE")); assertEquals("Testtable", service.getTableClassName("TESTTABLE")); /* * Hint: Camel casing can be disabled setting PreserverCharacterCase=true */ } @Test public void testGetAccessorName(){ CodeGenConfig config = new CodeGenConfig(); WriterService service = new WriterService(config); DBTableColumn col = Mockito.mock(DBTableColumn.class); Mockito.when(col.getDataType()).thenReturn(DataType.INTEGER); Mockito.when(col.getName()).thenReturn("name"); assertEquals("getName",service.getAccessorName(col)); DBTableColumn col2 = Mockito.mock(DBTableColumn.class); Mockito.when(col2.getDataType()).thenReturn(DataType.BOOL); Mockito.when(col2.getName()).thenReturn("name"); assertEquals("isName",service.getAccessorName(col2)); } @Test public void testGetMutatorName(){ CodeGenConfig config = new CodeGenConfig(); WriterService service = new WriterService(config); DBTableColumn col = Mockito.mock(DBTableColumn.class); Mockito.when(col.getDataType()).thenReturn(DataType.DECIMAL); Mockito.when(col.getName()).thenReturn("name"); assertEquals("setName", service.getMutatorName(col)); } }
UTF-8
Java
2,493
java
WriterServiceTest.java
Java
[]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.empire.db.codegen; import static org.junit.Assert.assertEquals; import org.apache.empire.data.DataType; import org.apache.empire.db.DBTableColumn; import org.junit.Test; import org.mockito.Mockito; public class WriterServiceTest { @Test public void testGetTableClassName() { CodeGenConfig config = new CodeGenConfig(); WriterService service = new WriterService(config); assertEquals("TestTable", service.getTableClassName("test_table")); assertEquals("TestTable", service.getTableClassName("TEST_TABLE")); assertEquals("Testtable", service.getTableClassName("TESTTABLE")); /* * Hint: Camel casing can be disabled setting PreserverCharacterCase=true */ } @Test public void testGetAccessorName(){ CodeGenConfig config = new CodeGenConfig(); WriterService service = new WriterService(config); DBTableColumn col = Mockito.mock(DBTableColumn.class); Mockito.when(col.getDataType()).thenReturn(DataType.INTEGER); Mockito.when(col.getName()).thenReturn("name"); assertEquals("getName",service.getAccessorName(col)); DBTableColumn col2 = Mockito.mock(DBTableColumn.class); Mockito.when(col2.getDataType()).thenReturn(DataType.BOOL); Mockito.when(col2.getName()).thenReturn("name"); assertEquals("isName",service.getAccessorName(col2)); } @Test public void testGetMutatorName(){ CodeGenConfig config = new CodeGenConfig(); WriterService service = new WriterService(config); DBTableColumn col = Mockito.mock(DBTableColumn.class); Mockito.when(col.getDataType()).thenReturn(DataType.DECIMAL); Mockito.when(col.getName()).thenReturn("name"); assertEquals("setName", service.getMutatorName(col)); } }
2,493
0.757722
0.754513
69
35.130436
25.383957
75
false
false
0
0
0
0
0
0
1.521739
false
false
13
acf31a454f755e9b5fb4d6b359b16f71579c65f6
14,173,392,131,927
eb39921675018e7801fbdcc30c3f832de0a24dd8
/src/n_aryTreeLevelOrderTraversal/Demo.java
d33ec24b6e80c6968c32f60990268906e02c27c0
[]
no_license
Reggiecril/Leetcode-practise
https://github.com/Reggiecril/Leetcode-practise
66997a4e257965bbcb40e2dabcd58faa7ad238b6
ca70abd16c912e4f3427886c3bf45a336d6ef383
refs/heads/master
2021-07-16T23:57:37.646000
2018-10-13T18:09:12
2018-10-13T18:09:12
135,281,439
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package n_aryTreeLevelOrderTraversal; import java.util.ArrayList; import java.util.List; public class Demo { // public List<List<Integer>> levelOrder(Node root) { // List<List<Integer>> list=new ArrayList<>(); // if(root==null){ // return list; // } // Queue<Node> queue=new LinkedList<Node>(); // ((LinkedList<Node>) queue).add(root); // while(!queue.isEmpty()){ // List<Integer> inList=new ArrayList<>(); // int length=queue.size(); // for(int i=0;i<length;i++){ // Node node=((LinkedList<Node>) queue).removeLast(); // inList.add(node.val); // if(node.children==null)continue; // for(Node x:node.children) // ((LinkedList<Node>) queue).addFirst(x); // } // list.add(inList); // } // return list; // } public List<List<Integer>> levelOrder(Node root){ List<List<Integer>> list=new ArrayList<>(); if(root==null) return list; levelOrderUtil(root,0,list); return list; } private void levelOrderUtil(Node node,int count,List<List<Integer>> list){ if(node ==null) return; if(list.size()==count) list.add(new ArrayList<>()); list.get(count).add(node.val); for(Node x:node.children) levelOrderUtil(x,count+1,list); } } class Node { public int val; public List<Node> children; public Node() {} public Node(int _val,List<Node> _children) { val = _val; children = _children; } };
UTF-8
Java
1,653
java
Demo.java
Java
[]
null
[]
package n_aryTreeLevelOrderTraversal; import java.util.ArrayList; import java.util.List; public class Demo { // public List<List<Integer>> levelOrder(Node root) { // List<List<Integer>> list=new ArrayList<>(); // if(root==null){ // return list; // } // Queue<Node> queue=new LinkedList<Node>(); // ((LinkedList<Node>) queue).add(root); // while(!queue.isEmpty()){ // List<Integer> inList=new ArrayList<>(); // int length=queue.size(); // for(int i=0;i<length;i++){ // Node node=((LinkedList<Node>) queue).removeLast(); // inList.add(node.val); // if(node.children==null)continue; // for(Node x:node.children) // ((LinkedList<Node>) queue).addFirst(x); // } // list.add(inList); // } // return list; // } public List<List<Integer>> levelOrder(Node root){ List<List<Integer>> list=new ArrayList<>(); if(root==null) return list; levelOrderUtil(root,0,list); return list; } private void levelOrderUtil(Node node,int count,List<List<Integer>> list){ if(node ==null) return; if(list.size()==count) list.add(new ArrayList<>()); list.get(count).add(node.val); for(Node x:node.children) levelOrderUtil(x,count+1,list); } } class Node { public int val; public List<Node> children; public Node() {} public Node(int _val,List<Node> _children) { val = _val; children = _children; } };
1,653
0.528736
0.526921
57
28
19.391624
78
false
false
0
0
0
0
0
0
0.649123
false
false
13
58009c7a6e1bad120ade12e2fbf28ce504f1c43f
33,114,197,913,407
cfc40d1c8b22d4f3c844458d03a6fbd2e6e60d0a
/src/tp2/ejercicio4.java
7179380a1e6fa2bf8abd62b30f061cc6532bfac5
[]
no_license
JorgeSerrano26/THP
https://github.com/JorgeSerrano26/THP
96802920e1fe699341b2af910e95d98cbd726e6d
0c55e9d5fb4fb221faf7a84216f1bba2fe869ef5
refs/heads/master
2021-04-24T04:58:41.693000
2020-05-30T21:00:28
2020-05-30T21:00:28
250,072,483
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tp2; import java.util.Scanner; public class ejercicio4 { static Scanner input; public static void main(String args[]) { /* * Realizar un programa en el cual se pida al usuario el ingreso de dos nรบmeros * enteros num1 y num2, cuya relaciรณn de valores es que el primero es menor o * igual al segundo y mostrar por pantalla la secuencia de nรบmeros que existe * entre ambos: * * a) Incluyรฉndolos; * b) Excluyรฉndolos. * * Obs: Validar que el primer nรบmero sea menor o igual al segundo. * Pedir el ingreso de ambos nรบmeros las * veces que sea necesario hasta que se cumpla dicha condiciรณn. * ยฟQuรฉ pasarรญa si * esta validaciรณn no la realizรกramos y el ingreso es incorrecto? * */ input = new Scanner(System.in); int num1,num2; do{ System.out.println("Ingrese el primer numero: "); num1 = input.nextInt(); System.out.println("Ingrese el segundo numero: "); num2 = input.nextInt(); }while(num1 > num2); input.close(); //Incluyendolos System.out.println("Incluyendolos: "); for(int i = num1; i <= num2; i++) { System.out.println(i); } //Exluyendolos System.out.println("Exluyendolos: "); for(int i = num1+1; i < num2; i++) { System.out.println(i); } } }
ISO-8859-1
Java
1,296
java
ejercicio4.java
Java
[]
null
[]
package tp2; import java.util.Scanner; public class ejercicio4 { static Scanner input; public static void main(String args[]) { /* * Realizar un programa en el cual se pida al usuario el ingreso de dos nรบmeros * enteros num1 y num2, cuya relaciรณn de valores es que el primero es menor o * igual al segundo y mostrar por pantalla la secuencia de nรบmeros que existe * entre ambos: * * a) Incluyรฉndolos; * b) Excluyรฉndolos. * * Obs: Validar que el primer nรบmero sea menor o igual al segundo. * Pedir el ingreso de ambos nรบmeros las * veces que sea necesario hasta que se cumpla dicha condiciรณn. * ยฟQuรฉ pasarรญa si * esta validaciรณn no la realizรกramos y el ingreso es incorrecto? * */ input = new Scanner(System.in); int num1,num2; do{ System.out.println("Ingrese el primer numero: "); num1 = input.nextInt(); System.out.println("Ingrese el segundo numero: "); num2 = input.nextInt(); }while(num1 > num2); input.close(); //Incluyendolos System.out.println("Incluyendolos: "); for(int i = num1; i <= num2; i++) { System.out.println(i); } //Exluyendolos System.out.println("Exluyendolos: "); for(int i = num1+1; i < num2; i++) { System.out.println(i); } } }
1,296
0.64926
0.637568
53
23.207546
23.211382
81
false
false
0
0
0
0
0
0
2.150943
false
false
13
ace87e5d1510644df31e9332a8886feac5f4252a
42,949,719,470
64d17a1fd8b94a76ce906ca702616d321f3aa93f
/src/main/java/fr/insee/stamina/utils/AccessSpecification.java
56c3c2911fe33a87529638c76588ceb906988037
[ "MIT" ]
permissive
FranckCo/Stamina
https://github.com/FranckCo/Stamina
bd32101ec19a6b9167dca5b86c459efac5e50ad8
20843a1e56d4e9512cbe0089b07af6dda7bb6af1
refs/heads/master
2022-12-01T02:29:32.287000
2022-08-21T10:41:24
2022-08-21T10:41:24
40,617,438
2
1
MIT
false
2022-11-16T03:18:05
2015-08-12T18:30:14
2022-08-21T10:40:05
2022-11-16T03:18:02
396
2
1
9
Java
false
false
package fr.insee.stamina.utils; import java.io.File; import java.util.HashMap; import java.util.Map; public class AccessSpecification { File accessFile; String tableName; Map<String, String> columns; public File getAccessFile() { return accessFile; } public String getTableName() { return tableName; } public Map<String, String> getColumns() { return columns; } @Override public String toString() { return "AccessSpecification{" + "accessFile=" + accessFile + ", tableName='" + tableName + '\'' + ", columns=" + columns + '}'; } public AccessSpecification(File accessFile, String tableName, Map<String, String> columns) { this.accessFile = accessFile; this.tableName = tableName; this.columns = columns; } public static void main(String... arg) { Map<String, String> cpc2Columns = new HashMap<String, String>() {{ put("code", "Code"); put("label", "Description"); put("note", "ExplanatoryNote"); }}; AccessSpecification cpc2AccessInfo = new AccessSpecification(new File("CPCv2_english.mdb"), "CPC2-structure", cpc2Columns); System.out.println(cpc2AccessInfo); } }
UTF-8
Java
1,325
java
AccessSpecification.java
Java
[]
null
[]
package fr.insee.stamina.utils; import java.io.File; import java.util.HashMap; import java.util.Map; public class AccessSpecification { File accessFile; String tableName; Map<String, String> columns; public File getAccessFile() { return accessFile; } public String getTableName() { return tableName; } public Map<String, String> getColumns() { return columns; } @Override public String toString() { return "AccessSpecification{" + "accessFile=" + accessFile + ", tableName='" + tableName + '\'' + ", columns=" + columns + '}'; } public AccessSpecification(File accessFile, String tableName, Map<String, String> columns) { this.accessFile = accessFile; this.tableName = tableName; this.columns = columns; } public static void main(String... arg) { Map<String, String> cpc2Columns = new HashMap<String, String>() {{ put("code", "Code"); put("label", "Description"); put("note", "ExplanatoryNote"); }}; AccessSpecification cpc2AccessInfo = new AccessSpecification(new File("CPCv2_english.mdb"), "CPC2-structure", cpc2Columns); System.out.println(cpc2AccessInfo); } }
1,325
0.594717
0.590189
49
26.040817
25.349766
131
false
false
0
0
0
0
0
0
0.693878
false
false
13
a6993ac2de38e0b35efb35f5db2ce778616bbacf
16,879,221,538,219
d66adbf32602270ab88edcef5497d86098fb33d6
/app/src/main/java/com/example/familymap/HelperClasses/Setting.java
a7cbc078519f8bd43cae87e0334713bdcbc9e9ec
[]
no_license
danielkeele/Family-Map
https://github.com/danielkeele/Family-Map
3b69d6dd461b6b85448e241faef74e7fa9748ee7
9909877b6d16a358993b5ecfa5093e7903af02b6
refs/heads/master
2020-07-07T17:46:31.232000
2019-08-20T17:55:13
2019-08-20T17:55:13
203,426,829
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.familymap.HelperClasses; import java.util.HashMap; import java.util.Map; public class Setting { private Boolean lifeStoryLines; private Boolean familyTreeLines; private Boolean spouseLines; private Map<String, String> lineColors; private Map<String, String> markerColors; private String mapType; private String[] colors; private int colorsIndex; public Setting(Boolean lifeStoryLines, Boolean familyTreeLines, Boolean spouseLines, String mapType) { this.lifeStoryLines = lifeStoryLines; this.familyTreeLines = familyTreeLines; this.spouseLines = spouseLines; this.mapType = mapType; lineColors = new HashMap<>(); markerColors = new HashMap<>(); InitializeColorsArray(); SetDefaultLineColors(); SetDefaultMarkerColors(); } private void InitializeColorsArray() { colors = new String[10]; colorsIndex = 0; colors[0] = "Red"; colors[1] = "Blue"; colors[2] = "Green"; colors[3] = "Purple"; colors[4] = "Rose"; colors[5] = "Orange"; colors[6] = "Cyan"; colors[7] = "Magenta"; colors[8] = "Yellow"; colors[9] = "Azure"; } public void SetLineColorInMap(String key, String value) { lineColors.put(key, value); } public String GetLineColorValueForKey(String key) { return lineColors.get(key); } public String GetMarkerColorValueForKey(String key) { String result = markerColors.get(key); if (result == null) { result = colors[colorsIndex]; markerColors.put(key, colors[colorsIndex]); colorsIndex++; if (colorsIndex == colors.length) { colorsIndex = 0; } } return result; } public void SetLifeStoryLines(Boolean lifeStoryLines) { this.lifeStoryLines = lifeStoryLines; } public void SetFamilyTreeLines(Boolean familyTreeLines) { this.familyTreeLines = familyTreeLines; } public void SetSpouseLines(Boolean spouseLines) { this.spouseLines = spouseLines; } public void SetMapType(String mapType) { this.mapType = mapType; } public Boolean GetLifeStoryLines() { return lifeStoryLines; } public Boolean GetFamilyTreeLines() { return familyTreeLines; } public Boolean GetSpouseLines() { return spouseLines; } public String GetMapType() { return mapType; } private void SetDefaultLineColors() { lineColors.put("lifeStory", "Red"); lineColors.put("familyTree", "Blue"); lineColors.put("spouse", "Green"); } private void SetDefaultMarkerColors() { markerColors.put("Birth", "Red"); markerColors.put("Baptism", "Blue"); markerColors.put("Marriage", "Green"); } }
UTF-8
Java
3,022
java
Setting.java
Java
[]
null
[]
package com.example.familymap.HelperClasses; import java.util.HashMap; import java.util.Map; public class Setting { private Boolean lifeStoryLines; private Boolean familyTreeLines; private Boolean spouseLines; private Map<String, String> lineColors; private Map<String, String> markerColors; private String mapType; private String[] colors; private int colorsIndex; public Setting(Boolean lifeStoryLines, Boolean familyTreeLines, Boolean spouseLines, String mapType) { this.lifeStoryLines = lifeStoryLines; this.familyTreeLines = familyTreeLines; this.spouseLines = spouseLines; this.mapType = mapType; lineColors = new HashMap<>(); markerColors = new HashMap<>(); InitializeColorsArray(); SetDefaultLineColors(); SetDefaultMarkerColors(); } private void InitializeColorsArray() { colors = new String[10]; colorsIndex = 0; colors[0] = "Red"; colors[1] = "Blue"; colors[2] = "Green"; colors[3] = "Purple"; colors[4] = "Rose"; colors[5] = "Orange"; colors[6] = "Cyan"; colors[7] = "Magenta"; colors[8] = "Yellow"; colors[9] = "Azure"; } public void SetLineColorInMap(String key, String value) { lineColors.put(key, value); } public String GetLineColorValueForKey(String key) { return lineColors.get(key); } public String GetMarkerColorValueForKey(String key) { String result = markerColors.get(key); if (result == null) { result = colors[colorsIndex]; markerColors.put(key, colors[colorsIndex]); colorsIndex++; if (colorsIndex == colors.length) { colorsIndex = 0; } } return result; } public void SetLifeStoryLines(Boolean lifeStoryLines) { this.lifeStoryLines = lifeStoryLines; } public void SetFamilyTreeLines(Boolean familyTreeLines) { this.familyTreeLines = familyTreeLines; } public void SetSpouseLines(Boolean spouseLines) { this.spouseLines = spouseLines; } public void SetMapType(String mapType) { this.mapType = mapType; } public Boolean GetLifeStoryLines() { return lifeStoryLines; } public Boolean GetFamilyTreeLines() { return familyTreeLines; } public Boolean GetSpouseLines() { return spouseLines; } public String GetMapType() { return mapType; } private void SetDefaultLineColors() { lineColors.put("lifeStory", "Red"); lineColors.put("familyTree", "Blue"); lineColors.put("spouse", "Green"); } private void SetDefaultMarkerColors() { markerColors.put("Birth", "Red"); markerColors.put("Baptism", "Blue"); markerColors.put("Marriage", "Green"); } }
3,022
0.597948
0.593316
132
21.89394
19.416588
104
false
false
0
0
0
0
0
0
0.515152
false
false
13
77d855dcef1b989e84b080169beb943daf7cedc9
31,284,541,833,555
eca963fa3b666daea5537b2768a8b7881d41f442
/haxby/image/jcodec/containers/mkv/demuxer/MKVDemuxer.java
ae46d371a3aa354db7fc74550ad71d7aeeb13713
[ "Apache-2.0" ]
permissive
iedadata/geomapapp
https://github.com/iedadata/geomapapp
1bee9fcbb686b9a932c467cb6d1e4511277d6a46
5368b21c425ff188a125939877f1db1eefb7ed9b
refs/heads/master
2023-08-17T08:47:13.342000
2023-08-15T20:20:25
2023-08-15T20:20:25
98,096,914
1
3
Apache-2.0
false
2023-08-15T20:20:27
2017-07-23T12:38:27
2023-06-28T23:00:26
2023-08-15T20:20:25
9,177
2
3
530
Java
false
false
package haxby.image.jcodec.containers.mkv.demuxer; import static haxby.image.jcodec.common.model.TapeTimecode.ZERO_TAPE_TIMECODE; import static haxby.image.jcodec.containers.mkv.MKVType.Audio; import static haxby.image.jcodec.containers.mkv.MKVType.Channels; import static haxby.image.jcodec.containers.mkv.MKVType.Cluster; import static haxby.image.jcodec.containers.mkv.MKVType.CodecPrivate; import static haxby.image.jcodec.containers.mkv.MKVType.DisplayHeight; import static haxby.image.jcodec.containers.mkv.MKVType.DisplayUnit; import static haxby.image.jcodec.containers.mkv.MKVType.DisplayWidth; import static haxby.image.jcodec.containers.mkv.MKVType.Info; import static haxby.image.jcodec.containers.mkv.MKVType.Language; import static haxby.image.jcodec.containers.mkv.MKVType.PixelHeight; import static haxby.image.jcodec.containers.mkv.MKVType.PixelWidth; import static haxby.image.jcodec.containers.mkv.MKVType.SamplingFrequency; import static haxby.image.jcodec.containers.mkv.MKVType.Segment; import static haxby.image.jcodec.containers.mkv.MKVType.TagLanguage; import static haxby.image.jcodec.containers.mkv.MKVType.Timecode; import static haxby.image.jcodec.containers.mkv.MKVType.TimecodeScale; import static haxby.image.jcodec.containers.mkv.MKVType.TrackEntry; import static haxby.image.jcodec.containers.mkv.MKVType.TrackNumber; import static haxby.image.jcodec.containers.mkv.MKVType.TrackType; import static haxby.image.jcodec.containers.mkv.MKVType.Tracks; import static haxby.image.jcodec.containers.mkv.MKVType.Video; import static haxby.image.jcodec.containers.mkv.MKVType.findFirst; import static haxby.image.jcodec.containers.mkv.MKVType.findList; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import haxby.image.jcodec.codecs.h264.H264Utils; import haxby.image.jcodec.codecs.h264.mp4.AvcCBox; import haxby.image.jcodec.common.AudioCodecMeta; import haxby.image.jcodec.common.Codec; import haxby.image.jcodec.common.Demuxer; import haxby.image.jcodec.common.DemuxerTrack; import haxby.image.jcodec.common.DemuxerTrackMeta; import haxby.image.jcodec.common.SeekableDemuxerTrack; import haxby.image.jcodec.common.TrackType; import haxby.image.jcodec.common.UsedViaReflection; import haxby.image.jcodec.common.VideoCodecMeta; import haxby.image.jcodec.common.io.SeekableByteChannel; import haxby.image.jcodec.common.model.ColorSpace; import haxby.image.jcodec.common.model.Label; import haxby.image.jcodec.common.model.Packet; import haxby.image.jcodec.common.model.Size; import haxby.image.jcodec.common.model.Packet.FrameType; import haxby.image.jcodec.containers.mkv.MKVParser; import haxby.image.jcodec.containers.mkv.MKVType; import haxby.image.jcodec.containers.mkv.boxes.EbmlBase; import haxby.image.jcodec.containers.mkv.boxes.EbmlBin; import haxby.image.jcodec.containers.mkv.boxes.EbmlFloat; import haxby.image.jcodec.containers.mkv.boxes.EbmlMaster; import haxby.image.jcodec.containers.mkv.boxes.EbmlString; import haxby.image.jcodec.containers.mkv.boxes.EbmlUint; import haxby.image.jcodec.containers.mkv.boxes.MkvBlock; import haxby.image.jcodec.containers.mkv.util.EbmlUtil; import haxby.image.jcodec.containers.mkv.util.EbmlUtil.VarIntDetail; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * @author The JCodec project * */ public final class MKVDemuxer implements Demuxer { private VideoTrack vTrack = null; private List<AudioTrack> aTracks; private List<SubtitlesTrack> subsTracks; private List<EbmlMaster> t; private SeekableByteChannel channel; int timescale = 1; int pictureWidth; int pictureHeight; private static Map<String, Codec> codecVideoMapping = new HashMap<String, Codec>(); static { codecVideoMapping.put("V_MS/VFW/FOURCC", null); codecVideoMapping.put("V_UNCOMPRESSED", null); codecVideoMapping.put("V_MPEG4/ISO/SP", null); codecVideoMapping.put("V_MPEG4/ISO/ASP", null); codecVideoMapping.put("V_MPEG4/ISO/AP", null); codecVideoMapping.put("V_MPEG4/MS/V3", Codec.MPEG4); codecVideoMapping.put("V_MPEG4/ISO/AVC", Codec.H264); codecVideoMapping.put("V_MPEGH/ISO/HEVC", Codec.H265); codecVideoMapping.put("V_MPEG1", null); codecVideoMapping.put("V_MPEG2", Codec.MPEG2); codecVideoMapping.put("V_REAL/RV10", null); codecVideoMapping.put("V_REAL/RV20", null); codecVideoMapping.put("V_REAL/RV30", null); codecVideoMapping.put("V_REAL/RV40", null); codecVideoMapping.put("V_QUICKTIME", null); codecVideoMapping.put("V_THEORA", null); codecVideoMapping.put("V_PRORES", null); codecVideoMapping.put("V_VP8", Codec.VP8); codecVideoMapping.put("V_VP9", Codec.VP9); codecVideoMapping.put("V_FFV1", null); } private static Map<String, Codec> codecAudioMapping = new HashMap<String, Codec>(); static { codecAudioMapping.put("A_MPEG/L3", Codec.MP3); codecAudioMapping.put("A_MPEG/L2", null); codecAudioMapping.put("A_MPEG/L1", null); codecAudioMapping.put("A_PCM/INT/BIG", null); codecAudioMapping.put("A_PCM/INT/LIT", null); codecAudioMapping.put("A_PCM/FLOAT/IEEE", null); codecAudioMapping.put("A_MPC", null); codecAudioMapping.put("A_AC3", Codec.AC3); codecAudioMapping.put("A_AC3/BSID9", Codec.AC3); codecAudioMapping.put("A_AC3/BSID10", Codec.AC3); codecAudioMapping.put("A_ALAC", null); codecAudioMapping.put("A_DTS", null); codecAudioMapping.put("A_DTS/EXPRESS", null); codecAudioMapping.put("A_DTS/LOSSLESS", null); codecAudioMapping.put("A_VORBIS", Codec.VORBIS); codecAudioMapping.put("A_FLAC", null); codecAudioMapping.put("A_REAL/14_4", null); codecAudioMapping.put("A_REAL/28_8", null); codecAudioMapping.put("A_REAL/COOK", null); codecAudioMapping.put("A_REAL/SIPR", null); codecAudioMapping.put("A_REAL/RALF", null); codecAudioMapping.put("A_REAL/ATRC", null); codecAudioMapping.put("A_MS/ACM", null); codecAudioMapping.put("A_AAC", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG2", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG2/MAIN", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG2/LC", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG2/LC/SBR", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG2/SSR", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4/MAIN", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4/LC", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4/LC/SBR", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4/SSR", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4/LTP", Codec.AAC); codecAudioMapping.put("A_QUICKTIME", null); codecAudioMapping.put("A_QUICKTIME/QDMC", null); codecAudioMapping.put("A_QUICKTIME/QDM2", null); codecAudioMapping.put("A_TTA1", null); codecAudioMapping.put("A_WAVPACK4", null); codecAudioMapping.put("A_OPUS", Codec.OPUS); } private static Map<String, Codec> codecSubtitleMapping = new HashMap<String, Codec>(); static { codecSubtitleMapping.put("S_TEXT/UTF8", Codec.UTF8); codecSubtitleMapping.put("S_TEXT/SSA", null); codecSubtitleMapping.put("S_TEXT/ASS", null); codecSubtitleMapping.put("S_TEXT/USF", null); codecSubtitleMapping.put("S_TEXT/WEBVTT", null); codecSubtitleMapping.put("S_IMAGE/BMP", null); codecSubtitleMapping.put("S_DVBSUB", null); codecSubtitleMapping.put("S_VOBSUB", null); codecSubtitleMapping.put("S_HDMV/PGS", null); codecSubtitleMapping.put("S_HDMV/TEXTST", null); codecSubtitleMapping.put("S_KATE", null); } public MKVDemuxer(SeekableByteChannel fileChannelWrapper) throws IOException { this.channel = fileChannelWrapper; this.aTracks = new ArrayList<AudioTrack>(); this.subsTracks = new ArrayList<SubtitlesTrack>(); MKVParser parser = new MKVParser(channel); this.t = parser.parse(); demux(); } private void demux() { MKVType[] path = { Segment, Info, TimecodeScale }; EbmlUint ts = MKVType.findFirstTree(t, path); if (ts != null) timescale = (int) ts.getUint(); MKVType[] path9 = { Segment, Tracks, TrackEntry }; for (EbmlMaster elemTrack : findList(t, EbmlMaster.class, path9)) { MKVType[] path1 = { TrackEntry, TrackType }; long type = ((EbmlUint) findFirst(elemTrack, path1)).getUint(); MKVType[] path2 = { TrackEntry, TrackNumber }; long id = ((EbmlUint) findFirst(elemTrack, path2)).getUint(); if (type == 1) { // Parse Video if (vTrack != null) throw new RuntimeException("More then 1 video track, can not compute..."); MKVType[] path3 = { TrackEntry, CodecPrivate }; MKVType[] path10 = { TrackEntry, MKVType.CodecID }; EbmlString codecId = (EbmlString) findFirst(elemTrack, path10); Codec codec = codecVideoMapping.get(codecId.getString()); if (codec == null) { System.out.println("Unknown video codec: '" + codecId.getString() + "'"); } EbmlBin videoCodecState = (EbmlBin) findFirst(elemTrack, path3); ByteBuffer state = null; if (videoCodecState != null) state = videoCodecState.data; MKVType[] path4 = { TrackEntry, Video, PixelWidth }; EbmlUint width = (EbmlUint) findFirst(elemTrack, path4); MKVType[] path5 = { TrackEntry, Video, PixelHeight }; EbmlUint height = (EbmlUint) findFirst(elemTrack, path5); MKVType[] path6 = { TrackEntry, Video, DisplayWidth }; EbmlUint dwidth = (EbmlUint) findFirst(elemTrack, path6); MKVType[] path7 = { TrackEntry, Video, DisplayHeight }; EbmlUint dheight = (EbmlUint) findFirst(elemTrack, path7); MKVType[] path8 = { TrackEntry, Video, DisplayUnit }; EbmlUint unit = (EbmlUint) findFirst(elemTrack, path8); if (width != null && height != null) { pictureWidth = (int) width.getUint(); pictureHeight = (int) height.getUint(); } else if (dwidth != null && dheight != null) { if (unit == null || unit.getUint() == 0) { pictureHeight = (int) dheight.getUint(); pictureWidth = (int) dwidth.getUint(); } else { throw new RuntimeException("DisplayUnits other then 0 are not implemented yet"); } } vTrack = new VideoTrack(this, (int) id, state, codec); } else if (type == 2) { // Parse Audio double sampleRate = 8000.0; long channelCount = 1; String language = "eng"; MKVType[] path10 = { TrackEntry, MKVType.CodecID }; EbmlString codecId = (EbmlString) findFirst(elemTrack, path10); Codec codec = codecAudioMapping.get(codecId.getString()); if (codec == null) { System.out.println("Unknown audio codec: '" + codecId.getString() + "'"); } MKVType[] path3 = { TrackEntry, Audio, SamplingFrequency }; EbmlFloat sf = (EbmlFloat) findFirst(elemTrack, path3); if (sf != null) { sampleRate = sf.getDouble(); } MKVType[] path4 = { TrackEntry, Audio, Channels }; EbmlUint channels = (EbmlUint) findFirst(elemTrack, path4); if (channels != null) { channelCount = channels.getUint(); } MKVType[] path5 = { TrackEntry, Language }; EbmlString tagLanguage = (EbmlString) findFirst(elemTrack, path5); if (tagLanguage != null) { language = tagLanguage.getString(); } aTracks.add(new AudioTrack(this, (int) id, codec, sampleRate, channelCount, language)); } else if (type == 3) { // Parse complex } else if (type == 16) { // Parse logo } else if (type == 17) { // Parse subtitle String language = "eng"; MKVType[] path10 = { TrackEntry, MKVType.CodecID }; EbmlString codecId = (EbmlString) findFirst(elemTrack, path10); Codec codec = codecSubtitleMapping.get(codecId.getString()); if (codec == null) { System.out.println("Unknown subtitle codec: '" + codecId.getString() + "'"); } MKVType[] path5 = { TrackEntry, Language }; EbmlString tagLanguage = (EbmlString) findFirst(elemTrack, path5); if (tagLanguage != null) { language = tagLanguage.getString(); } SubtitlesTrack subsTrack = new SubtitlesTrack(this, (int) id, codec, language); subsTracks.add(subsTrack); } else if (type == 18) { // Parse buttons } else if (type == 32) { // Parse control } else if (type == 33) { // Parse metadata } } MKVType[] path2 = { Segment, Cluster }; for (EbmlMaster aCluster : findList(t, EbmlMaster.class, path2)) { MKVType[] path1 = { Cluster, Timecode }; long baseTimecode = ((EbmlUint) findFirst(aCluster, path1)).getUint(); for (EbmlBase child : aCluster.children) if (MKVType.SimpleBlock.equals(child.type)) { MkvBlock b = (MkvBlock) child; b.absoluteTimecode = b.timecode + baseTimecode; putIntoRightBasket(b); } else if (MKVType.BlockGroup.equals(child.type)) { EbmlMaster group = (EbmlMaster) child; for (EbmlBase grandChild : group.children) { if (grandChild.type == MKVType.Block) { MkvBlock b = (MkvBlock) grandChild; b.absoluteTimecode = b.timecode + baseTimecode; putIntoRightBasket(b); } } } } } private void putIntoRightBasket(MkvBlock b) { if (b.trackNumber == vTrack.trackNo) { vTrack.blocks.add(b); } else { for (int i = 0; i < aTracks.size(); i++) { AudioTrack audio = (AudioTrack) aTracks.get(i); if (b.trackNumber == audio.trackNo) { audio.blocks.add(IndexedBlock.make(audio.framesCount, b)); audio.framesCount += b.frameSizes.length; } } for (int i = 0; i < subsTracks.size(); i++) { SubtitlesTrack subs = subsTracks.get(i); if (b.trackNumber == subs.trackNo) { subs.blocks.add(IndexedBlock.make(subs.framesCount, b)); subs.framesCount += b.frameSizes.length; } } } } public static class VideoTrack implements SeekableDemuxerTrack { private ByteBuffer state; public final int trackNo; private int frameIdx = 0; List<MkvBlock> blocks; private MKVDemuxer demuxer; private Codec codec; private AvcCBox avcC; public VideoTrack(MKVDemuxer demuxer, int trackNo, ByteBuffer state, Codec codec) { this.blocks = new ArrayList<MkvBlock>(); this.demuxer = demuxer; this.trackNo = trackNo; this.codec = codec; if (codec == Codec.H264) { avcC = H264Utils.parseAVCCFromBuffer(state); this.state = H264Utils.avcCToAnnexB(avcC); } else { this.state = state; } } @Override public Packet nextFrame() throws IOException { if (frameIdx >= blocks.size()) return null; MkvBlock b = blocks.get(frameIdx); if (b == null) throw new RuntimeException("Something somewhere went wrong."); frameIdx++; /** * This part could be moved withing yet-another inner class, say MKVPacket to * that channel is actually read only when Packet.getData() is executed. */ demuxer.channel.setPosition(b.dataOffset); ByteBuffer data = ByteBuffer.allocate(b.dataLen); demuxer.channel.read(data); data.flip(); b.readFrames(data.duplicate()); long duration = 1; if (frameIdx < blocks.size()) duration = blocks.get(frameIdx).absoluteTimecode - b.absoluteTimecode; ByteBuffer result = b.frames[0].duplicate(); if (codec == Codec.H264) { result = H264Utils.decodeMOVPacket(result, avcC); } return Packet.createPacket(result, b.absoluteTimecode, demuxer.timescale, duration, frameIdx - 1, b._keyFrame ? FrameType.KEY : FrameType.INTER, ZERO_TAPE_TIMECODE); } @Override public boolean gotoFrame(long i) { if (i > Integer.MAX_VALUE) return false; if (i > blocks.size()) return false; frameIdx = (int) i; return true; } @Override public long getCurFrame() { return frameIdx; } @Override public void seek(double second) { throw new RuntimeException("Not implemented yet"); } public int getFrameCount() { return blocks.size(); } public ByteBuffer getCodecState() { return state; } @Override public DemuxerTrackMeta getMeta() { return new DemuxerTrackMeta(haxby.image.jcodec.common.TrackType.VIDEO, codec, 0, null, 0, state, haxby.image.jcodec.common.VideoCodecMeta.createSimpleVideoCodecMeta( new Size(demuxer.pictureWidth, demuxer.pictureHeight), ColorSpace.YUV420), null); } @Override public boolean gotoSyncFrame(long i) { throw new RuntimeException("Unsupported"); } } public static class IndexedBlock { public int firstFrameNo; public MkvBlock block; public static IndexedBlock make(int no, MkvBlock b) { IndexedBlock ib = new IndexedBlock(); ib.firstFrameNo = no; ib.block = b; return ib; } } public static class SubtitlesTrack extends MkvTrack { private Codec codec = null; private String language = "eng"; SubtitlesTrack(MKVDemuxer demuxer, int trackNo, Codec codec, String language) { super(trackNo, demuxer); this.codec = codec; if (language != null) { this.language = language; } } @Override public DemuxerTrackMeta getMeta() { return new DemuxerTrackMeta(haxby.image.jcodec.common.TrackType.TEXT, this.codec, 0, null, 0, null, null, null); } public String getLanguage() { return language; } } private static class MkvBlockData { final MkvBlock block; final ByteBuffer data; final int count; MkvBlockData(MkvBlock block, ByteBuffer data, int count) { this.block = block; this.data = data; this.count = count; } } public static class MkvTrack implements SeekableDemuxerTrack { public final int trackNo; List<IndexedBlock> blocks; int framesCount = 0; private int frameIdx = 0; private int blockIdx = 0; private int frameInBlockIdx = 0; private MKVDemuxer demuxer; public MkvTrack(int trackNo, MKVDemuxer demuxer) { this.blocks = new ArrayList<IndexedBlock>(); this.trackNo = trackNo; this.demuxer = demuxer; } @Override public Packet nextFrame() throws IOException { MkvBlockData bd = nextBlock(); if (bd == null) return null; return Packet.createPacket(bd.data, bd.block.absoluteTimecode, demuxer.timescale, 1, frameIdx - 1, FrameType.KEY, ZERO_TAPE_TIMECODE); } protected MkvBlockData nextBlock() throws IOException { if (frameIdx >= blocks.size() || blockIdx >= blocks.size()) return null; MkvBlock b = blocks.get(blockIdx).block; if (b == null) throw new RuntimeException("Something somewhere went wrong."); if (b.frames == null || b.frames.length == 0) { /** * This part could be moved withing yet-another inner class, say MKVPacket to * that channel is actually rean only when Packet.getData() is executed. */ demuxer.channel.setPosition(b.dataOffset); ByteBuffer data = ByteBuffer.allocate(b.dataLen); demuxer.channel.read(data); b.readFrames(data); } ByteBuffer data = b.frames[frameInBlockIdx].duplicate(); frameInBlockIdx++; frameIdx++; if (frameInBlockIdx >= b.frames.length) { blockIdx++; frameInBlockIdx = 0; } return new MkvBlockData(b, data, 1); } @Override public boolean gotoFrame(long i) { if (i > Integer.MAX_VALUE) return false; if (i > this.framesCount) return false; int frameBlockIdx = findBlockIndex(i); if (frameBlockIdx == -1) return false; frameIdx = (int) i; blockIdx = frameBlockIdx; frameInBlockIdx = (int) i - blocks.get(blockIdx).firstFrameNo; return true; } private int findBlockIndex(long i) { for (int blockIndex = 0; blockIndex < blocks.size(); blockIndex++) { if (i < blocks.get(blockIndex).block.frameSizes.length) return blockIndex; i -= blocks.get(blockIndex).block.frameSizes.length; } return -1; } @Override public long getCurFrame() { return frameIdx; } @Override public void seek(double second) { throw new RuntimeException("Not implemented yet"); } /** * Get multiple frames * * @param count * @return */ public Packet getFrames(int count) { MkvBlockData frameBlock = getFrameBlock(count); if (frameBlock == null) return null; return Packet.createPacket(frameBlock.data, frameBlock.block.absoluteTimecode, demuxer.timescale, frameBlock.count, 0, FrameType.KEY, ZERO_TAPE_TIMECODE); } MkvBlockData getFrameBlock(int count) { if (count + frameIdx >= framesCount) return null; List<ByteBuffer> packetFrames = new ArrayList<ByteBuffer>(); MkvBlock firstBlockInAPacket = blocks.get(blockIdx).block; while (count > 0) { MkvBlock b = blocks.get(blockIdx).block; if (b.frames == null || b.frames.length == 0) { /** * This part could be moved withing yet-another inner class, say MKVPacket to * that channel is actually rean only when Packet.getData() is executed. */ try { demuxer.channel.setPosition(b.dataOffset); ByteBuffer data = ByteBuffer.allocate(b.dataLen); demuxer.channel.read(data); b.readFrames(data); } catch (IOException ioe) { throw new RuntimeException("while reading frames of a Block at offset 0x" + Long.toHexString(b.dataOffset).toUpperCase() + ")", ioe); } } packetFrames.add(b.frames[frameInBlockIdx].duplicate()); frameIdx++; frameInBlockIdx++; if (frameInBlockIdx >= b.frames.length) { frameInBlockIdx = 0; blockIdx++; } count--; } int size = 0; for (ByteBuffer aFrame : packetFrames) size += aFrame.limit(); ByteBuffer data = ByteBuffer.allocate(size); for (ByteBuffer aFrame : packetFrames) data.put(aFrame); return new MkvBlockData(firstBlockInAPacket, data, packetFrames.size()); } @Override public DemuxerTrackMeta getMeta() { return null; } @Override public boolean gotoSyncFrame(long frame) { return gotoFrame(frame); } } public static class AudioTrack extends MkvTrack { private double sampleRate = 8000; private String language = "eng"; private long channelCount = 1; private Codec codec = null; public AudioTrack(MKVDemuxer demuxer, int trackNo, Codec codec, double sampleRate, long channelCount, String language) { super(trackNo, demuxer); this.codec = codec; if (language != null) { this.language = language; } if (sampleRate > 0.0) { this.sampleRate = sampleRate; } if (channelCount > 0) { this.channelCount = channelCount; } } @Override public Packet nextFrame() throws IOException { MkvBlockData b = nextBlock(); if (b == null) return null; return Packet.createPacket(b.data, b.block.absoluteTimecode, (int) Math.round(sampleRate), 1, 0, FrameType.KEY, ZERO_TAPE_TIMECODE); } /** * Get multiple frames * * @param count * @return */ public Packet getFrames(int count) { MkvBlockData frameBlock = getFrameBlock(count); if (frameBlock == null) return null; return Packet.createPacket(frameBlock.data, frameBlock.block.absoluteTimecode, (int) Math.round(sampleRate), frameBlock.count, 0, FrameType.KEY, ZERO_TAPE_TIMECODE); } @Override public DemuxerTrackMeta getMeta() { boolean isPcm = false; if (this.codec != null) { isPcm = this.codec.isPcm(); } return new DemuxerTrackMeta(haxby.image.jcodec.common.TrackType.AUDIO, this.codec, 0, null, 0, null, null, AudioCodecMeta.createAudioCodecMeta("", 0, (int) this.channelCount, (int) this.sampleRate, ByteOrder.LITTLE_ENDIAN, isPcm, null, null)); } @Override public boolean gotoSyncFrame(long frame) { return gotoFrame(frame); } public String getLanguage() { return language; } public long getChannelCount() { return channelCount; } } public int getPictureWidth() { return pictureWidth; } public int getPictureHeight() { return pictureHeight; } @Override public List<DemuxerTrack> getAudioTracks() { return (List<DemuxerTrack>) (List) aTracks; } @Override public List<DemuxerTrack> getTracks() { ArrayList<DemuxerTrack> tracks = new ArrayList<DemuxerTrack>(aTracks); tracks.add(vTrack); tracks.addAll(subsTracks); return tracks; } @Override public List<DemuxerTrack> getVideoTracks() { ArrayList<DemuxerTrack> tracks = new ArrayList<DemuxerTrack>(); tracks.add(vTrack); return tracks; } public List<DemuxerTrack> getSubtitleTracks() { return (List<DemuxerTrack>) (List) subsTracks; } public List<? extends EbmlBase> getTree() { return t; } @Override public void close() throws IOException { channel.close(); } @UsedViaReflection public static int probe(final ByteBuffer b) { ByteBuffer fork = b.duplicate(); byte[] firstFour = new byte[4]; fork.get(firstFour); boolean hasEBMLHeader = Arrays.equals(firstFour, MKVType.EBML.id); if (hasEBMLHeader) { try { VarIntDetail headerLen = EbmlUtil.parseVarInt(fork); if (headerLen.value < 0 || headerLen.value > 1000) { // The EBML header has unusual size return 30; } byte[] allHeader = new byte[(int) headerLen.value]; fork.get(allHeader); byte[] docTypeID = MKVType.DocType.id; int currPos = 0; while (currPos < headerLen.value && allHeader[currPos++] != docTypeID[0] && allHeader[currPos++] != docTypeID[1]) { // Do nothing } if (currPos == headerLen.value) { // Could not find the doctype info return 45; } byte[] theTypeLen = new byte[8]; System.arraycopy(allHeader, currPos, theTypeLen, 0, 8); try { VarIntDetail typeLen = EbmlUtil.parseVarInt(ByteBuffer.wrap(theTypeLen)); if (typeLen.value < 0 || typeLen.value > 50) { // Unusual DocType length return 75; } byte[] theType = new byte[(int) typeLen.value]; System.arraycopy(allHeader, currPos + typeLen.length, theType, 0, (int) typeLen.value); String parsedType = new String(theType); final String[] acceptableDocTypes = { "matroska", "webm" }; for (String acceptableType : acceptableDocTypes) { if (acceptableType.equals(parsedType)) { // Header and type looks ok, we can definitely try to load this return 100; } } // Unknown type but might be good to go return 90; } catch (RuntimeException rex) { // Could not find the length of the type return 60; } } catch (RuntimeException rex) { // Could not find the length of the EBML header return 15; } } else { // Not even the EBML header is there return 0; } } }
UTF-8
Java
32,092
java
MKVDemuxer.java
Java
[]
null
[]
package haxby.image.jcodec.containers.mkv.demuxer; import static haxby.image.jcodec.common.model.TapeTimecode.ZERO_TAPE_TIMECODE; import static haxby.image.jcodec.containers.mkv.MKVType.Audio; import static haxby.image.jcodec.containers.mkv.MKVType.Channels; import static haxby.image.jcodec.containers.mkv.MKVType.Cluster; import static haxby.image.jcodec.containers.mkv.MKVType.CodecPrivate; import static haxby.image.jcodec.containers.mkv.MKVType.DisplayHeight; import static haxby.image.jcodec.containers.mkv.MKVType.DisplayUnit; import static haxby.image.jcodec.containers.mkv.MKVType.DisplayWidth; import static haxby.image.jcodec.containers.mkv.MKVType.Info; import static haxby.image.jcodec.containers.mkv.MKVType.Language; import static haxby.image.jcodec.containers.mkv.MKVType.PixelHeight; import static haxby.image.jcodec.containers.mkv.MKVType.PixelWidth; import static haxby.image.jcodec.containers.mkv.MKVType.SamplingFrequency; import static haxby.image.jcodec.containers.mkv.MKVType.Segment; import static haxby.image.jcodec.containers.mkv.MKVType.TagLanguage; import static haxby.image.jcodec.containers.mkv.MKVType.Timecode; import static haxby.image.jcodec.containers.mkv.MKVType.TimecodeScale; import static haxby.image.jcodec.containers.mkv.MKVType.TrackEntry; import static haxby.image.jcodec.containers.mkv.MKVType.TrackNumber; import static haxby.image.jcodec.containers.mkv.MKVType.TrackType; import static haxby.image.jcodec.containers.mkv.MKVType.Tracks; import static haxby.image.jcodec.containers.mkv.MKVType.Video; import static haxby.image.jcodec.containers.mkv.MKVType.findFirst; import static haxby.image.jcodec.containers.mkv.MKVType.findList; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import haxby.image.jcodec.codecs.h264.H264Utils; import haxby.image.jcodec.codecs.h264.mp4.AvcCBox; import haxby.image.jcodec.common.AudioCodecMeta; import haxby.image.jcodec.common.Codec; import haxby.image.jcodec.common.Demuxer; import haxby.image.jcodec.common.DemuxerTrack; import haxby.image.jcodec.common.DemuxerTrackMeta; import haxby.image.jcodec.common.SeekableDemuxerTrack; import haxby.image.jcodec.common.TrackType; import haxby.image.jcodec.common.UsedViaReflection; import haxby.image.jcodec.common.VideoCodecMeta; import haxby.image.jcodec.common.io.SeekableByteChannel; import haxby.image.jcodec.common.model.ColorSpace; import haxby.image.jcodec.common.model.Label; import haxby.image.jcodec.common.model.Packet; import haxby.image.jcodec.common.model.Size; import haxby.image.jcodec.common.model.Packet.FrameType; import haxby.image.jcodec.containers.mkv.MKVParser; import haxby.image.jcodec.containers.mkv.MKVType; import haxby.image.jcodec.containers.mkv.boxes.EbmlBase; import haxby.image.jcodec.containers.mkv.boxes.EbmlBin; import haxby.image.jcodec.containers.mkv.boxes.EbmlFloat; import haxby.image.jcodec.containers.mkv.boxes.EbmlMaster; import haxby.image.jcodec.containers.mkv.boxes.EbmlString; import haxby.image.jcodec.containers.mkv.boxes.EbmlUint; import haxby.image.jcodec.containers.mkv.boxes.MkvBlock; import haxby.image.jcodec.containers.mkv.util.EbmlUtil; import haxby.image.jcodec.containers.mkv.util.EbmlUtil.VarIntDetail; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * @author The JCodec project * */ public final class MKVDemuxer implements Demuxer { private VideoTrack vTrack = null; private List<AudioTrack> aTracks; private List<SubtitlesTrack> subsTracks; private List<EbmlMaster> t; private SeekableByteChannel channel; int timescale = 1; int pictureWidth; int pictureHeight; private static Map<String, Codec> codecVideoMapping = new HashMap<String, Codec>(); static { codecVideoMapping.put("V_MS/VFW/FOURCC", null); codecVideoMapping.put("V_UNCOMPRESSED", null); codecVideoMapping.put("V_MPEG4/ISO/SP", null); codecVideoMapping.put("V_MPEG4/ISO/ASP", null); codecVideoMapping.put("V_MPEG4/ISO/AP", null); codecVideoMapping.put("V_MPEG4/MS/V3", Codec.MPEG4); codecVideoMapping.put("V_MPEG4/ISO/AVC", Codec.H264); codecVideoMapping.put("V_MPEGH/ISO/HEVC", Codec.H265); codecVideoMapping.put("V_MPEG1", null); codecVideoMapping.put("V_MPEG2", Codec.MPEG2); codecVideoMapping.put("V_REAL/RV10", null); codecVideoMapping.put("V_REAL/RV20", null); codecVideoMapping.put("V_REAL/RV30", null); codecVideoMapping.put("V_REAL/RV40", null); codecVideoMapping.put("V_QUICKTIME", null); codecVideoMapping.put("V_THEORA", null); codecVideoMapping.put("V_PRORES", null); codecVideoMapping.put("V_VP8", Codec.VP8); codecVideoMapping.put("V_VP9", Codec.VP9); codecVideoMapping.put("V_FFV1", null); } private static Map<String, Codec> codecAudioMapping = new HashMap<String, Codec>(); static { codecAudioMapping.put("A_MPEG/L3", Codec.MP3); codecAudioMapping.put("A_MPEG/L2", null); codecAudioMapping.put("A_MPEG/L1", null); codecAudioMapping.put("A_PCM/INT/BIG", null); codecAudioMapping.put("A_PCM/INT/LIT", null); codecAudioMapping.put("A_PCM/FLOAT/IEEE", null); codecAudioMapping.put("A_MPC", null); codecAudioMapping.put("A_AC3", Codec.AC3); codecAudioMapping.put("A_AC3/BSID9", Codec.AC3); codecAudioMapping.put("A_AC3/BSID10", Codec.AC3); codecAudioMapping.put("A_ALAC", null); codecAudioMapping.put("A_DTS", null); codecAudioMapping.put("A_DTS/EXPRESS", null); codecAudioMapping.put("A_DTS/LOSSLESS", null); codecAudioMapping.put("A_VORBIS", Codec.VORBIS); codecAudioMapping.put("A_FLAC", null); codecAudioMapping.put("A_REAL/14_4", null); codecAudioMapping.put("A_REAL/28_8", null); codecAudioMapping.put("A_REAL/COOK", null); codecAudioMapping.put("A_REAL/SIPR", null); codecAudioMapping.put("A_REAL/RALF", null); codecAudioMapping.put("A_REAL/ATRC", null); codecAudioMapping.put("A_MS/ACM", null); codecAudioMapping.put("A_AAC", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG2", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG2/MAIN", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG2/LC", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG2/LC/SBR", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG2/SSR", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4/MAIN", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4/LC", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4/LC/SBR", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4/SSR", Codec.AAC); codecAudioMapping.put("A_AAC/MPEG4/LTP", Codec.AAC); codecAudioMapping.put("A_QUICKTIME", null); codecAudioMapping.put("A_QUICKTIME/QDMC", null); codecAudioMapping.put("A_QUICKTIME/QDM2", null); codecAudioMapping.put("A_TTA1", null); codecAudioMapping.put("A_WAVPACK4", null); codecAudioMapping.put("A_OPUS", Codec.OPUS); } private static Map<String, Codec> codecSubtitleMapping = new HashMap<String, Codec>(); static { codecSubtitleMapping.put("S_TEXT/UTF8", Codec.UTF8); codecSubtitleMapping.put("S_TEXT/SSA", null); codecSubtitleMapping.put("S_TEXT/ASS", null); codecSubtitleMapping.put("S_TEXT/USF", null); codecSubtitleMapping.put("S_TEXT/WEBVTT", null); codecSubtitleMapping.put("S_IMAGE/BMP", null); codecSubtitleMapping.put("S_DVBSUB", null); codecSubtitleMapping.put("S_VOBSUB", null); codecSubtitleMapping.put("S_HDMV/PGS", null); codecSubtitleMapping.put("S_HDMV/TEXTST", null); codecSubtitleMapping.put("S_KATE", null); } public MKVDemuxer(SeekableByteChannel fileChannelWrapper) throws IOException { this.channel = fileChannelWrapper; this.aTracks = new ArrayList<AudioTrack>(); this.subsTracks = new ArrayList<SubtitlesTrack>(); MKVParser parser = new MKVParser(channel); this.t = parser.parse(); demux(); } private void demux() { MKVType[] path = { Segment, Info, TimecodeScale }; EbmlUint ts = MKVType.findFirstTree(t, path); if (ts != null) timescale = (int) ts.getUint(); MKVType[] path9 = { Segment, Tracks, TrackEntry }; for (EbmlMaster elemTrack : findList(t, EbmlMaster.class, path9)) { MKVType[] path1 = { TrackEntry, TrackType }; long type = ((EbmlUint) findFirst(elemTrack, path1)).getUint(); MKVType[] path2 = { TrackEntry, TrackNumber }; long id = ((EbmlUint) findFirst(elemTrack, path2)).getUint(); if (type == 1) { // Parse Video if (vTrack != null) throw new RuntimeException("More then 1 video track, can not compute..."); MKVType[] path3 = { TrackEntry, CodecPrivate }; MKVType[] path10 = { TrackEntry, MKVType.CodecID }; EbmlString codecId = (EbmlString) findFirst(elemTrack, path10); Codec codec = codecVideoMapping.get(codecId.getString()); if (codec == null) { System.out.println("Unknown video codec: '" + codecId.getString() + "'"); } EbmlBin videoCodecState = (EbmlBin) findFirst(elemTrack, path3); ByteBuffer state = null; if (videoCodecState != null) state = videoCodecState.data; MKVType[] path4 = { TrackEntry, Video, PixelWidth }; EbmlUint width = (EbmlUint) findFirst(elemTrack, path4); MKVType[] path5 = { TrackEntry, Video, PixelHeight }; EbmlUint height = (EbmlUint) findFirst(elemTrack, path5); MKVType[] path6 = { TrackEntry, Video, DisplayWidth }; EbmlUint dwidth = (EbmlUint) findFirst(elemTrack, path6); MKVType[] path7 = { TrackEntry, Video, DisplayHeight }; EbmlUint dheight = (EbmlUint) findFirst(elemTrack, path7); MKVType[] path8 = { TrackEntry, Video, DisplayUnit }; EbmlUint unit = (EbmlUint) findFirst(elemTrack, path8); if (width != null && height != null) { pictureWidth = (int) width.getUint(); pictureHeight = (int) height.getUint(); } else if (dwidth != null && dheight != null) { if (unit == null || unit.getUint() == 0) { pictureHeight = (int) dheight.getUint(); pictureWidth = (int) dwidth.getUint(); } else { throw new RuntimeException("DisplayUnits other then 0 are not implemented yet"); } } vTrack = new VideoTrack(this, (int) id, state, codec); } else if (type == 2) { // Parse Audio double sampleRate = 8000.0; long channelCount = 1; String language = "eng"; MKVType[] path10 = { TrackEntry, MKVType.CodecID }; EbmlString codecId = (EbmlString) findFirst(elemTrack, path10); Codec codec = codecAudioMapping.get(codecId.getString()); if (codec == null) { System.out.println("Unknown audio codec: '" + codecId.getString() + "'"); } MKVType[] path3 = { TrackEntry, Audio, SamplingFrequency }; EbmlFloat sf = (EbmlFloat) findFirst(elemTrack, path3); if (sf != null) { sampleRate = sf.getDouble(); } MKVType[] path4 = { TrackEntry, Audio, Channels }; EbmlUint channels = (EbmlUint) findFirst(elemTrack, path4); if (channels != null) { channelCount = channels.getUint(); } MKVType[] path5 = { TrackEntry, Language }; EbmlString tagLanguage = (EbmlString) findFirst(elemTrack, path5); if (tagLanguage != null) { language = tagLanguage.getString(); } aTracks.add(new AudioTrack(this, (int) id, codec, sampleRate, channelCount, language)); } else if (type == 3) { // Parse complex } else if (type == 16) { // Parse logo } else if (type == 17) { // Parse subtitle String language = "eng"; MKVType[] path10 = { TrackEntry, MKVType.CodecID }; EbmlString codecId = (EbmlString) findFirst(elemTrack, path10); Codec codec = codecSubtitleMapping.get(codecId.getString()); if (codec == null) { System.out.println("Unknown subtitle codec: '" + codecId.getString() + "'"); } MKVType[] path5 = { TrackEntry, Language }; EbmlString tagLanguage = (EbmlString) findFirst(elemTrack, path5); if (tagLanguage != null) { language = tagLanguage.getString(); } SubtitlesTrack subsTrack = new SubtitlesTrack(this, (int) id, codec, language); subsTracks.add(subsTrack); } else if (type == 18) { // Parse buttons } else if (type == 32) { // Parse control } else if (type == 33) { // Parse metadata } } MKVType[] path2 = { Segment, Cluster }; for (EbmlMaster aCluster : findList(t, EbmlMaster.class, path2)) { MKVType[] path1 = { Cluster, Timecode }; long baseTimecode = ((EbmlUint) findFirst(aCluster, path1)).getUint(); for (EbmlBase child : aCluster.children) if (MKVType.SimpleBlock.equals(child.type)) { MkvBlock b = (MkvBlock) child; b.absoluteTimecode = b.timecode + baseTimecode; putIntoRightBasket(b); } else if (MKVType.BlockGroup.equals(child.type)) { EbmlMaster group = (EbmlMaster) child; for (EbmlBase grandChild : group.children) { if (grandChild.type == MKVType.Block) { MkvBlock b = (MkvBlock) grandChild; b.absoluteTimecode = b.timecode + baseTimecode; putIntoRightBasket(b); } } } } } private void putIntoRightBasket(MkvBlock b) { if (b.trackNumber == vTrack.trackNo) { vTrack.blocks.add(b); } else { for (int i = 0; i < aTracks.size(); i++) { AudioTrack audio = (AudioTrack) aTracks.get(i); if (b.trackNumber == audio.trackNo) { audio.blocks.add(IndexedBlock.make(audio.framesCount, b)); audio.framesCount += b.frameSizes.length; } } for (int i = 0; i < subsTracks.size(); i++) { SubtitlesTrack subs = subsTracks.get(i); if (b.trackNumber == subs.trackNo) { subs.blocks.add(IndexedBlock.make(subs.framesCount, b)); subs.framesCount += b.frameSizes.length; } } } } public static class VideoTrack implements SeekableDemuxerTrack { private ByteBuffer state; public final int trackNo; private int frameIdx = 0; List<MkvBlock> blocks; private MKVDemuxer demuxer; private Codec codec; private AvcCBox avcC; public VideoTrack(MKVDemuxer demuxer, int trackNo, ByteBuffer state, Codec codec) { this.blocks = new ArrayList<MkvBlock>(); this.demuxer = demuxer; this.trackNo = trackNo; this.codec = codec; if (codec == Codec.H264) { avcC = H264Utils.parseAVCCFromBuffer(state); this.state = H264Utils.avcCToAnnexB(avcC); } else { this.state = state; } } @Override public Packet nextFrame() throws IOException { if (frameIdx >= blocks.size()) return null; MkvBlock b = blocks.get(frameIdx); if (b == null) throw new RuntimeException("Something somewhere went wrong."); frameIdx++; /** * This part could be moved withing yet-another inner class, say MKVPacket to * that channel is actually read only when Packet.getData() is executed. */ demuxer.channel.setPosition(b.dataOffset); ByteBuffer data = ByteBuffer.allocate(b.dataLen); demuxer.channel.read(data); data.flip(); b.readFrames(data.duplicate()); long duration = 1; if (frameIdx < blocks.size()) duration = blocks.get(frameIdx).absoluteTimecode - b.absoluteTimecode; ByteBuffer result = b.frames[0].duplicate(); if (codec == Codec.H264) { result = H264Utils.decodeMOVPacket(result, avcC); } return Packet.createPacket(result, b.absoluteTimecode, demuxer.timescale, duration, frameIdx - 1, b._keyFrame ? FrameType.KEY : FrameType.INTER, ZERO_TAPE_TIMECODE); } @Override public boolean gotoFrame(long i) { if (i > Integer.MAX_VALUE) return false; if (i > blocks.size()) return false; frameIdx = (int) i; return true; } @Override public long getCurFrame() { return frameIdx; } @Override public void seek(double second) { throw new RuntimeException("Not implemented yet"); } public int getFrameCount() { return blocks.size(); } public ByteBuffer getCodecState() { return state; } @Override public DemuxerTrackMeta getMeta() { return new DemuxerTrackMeta(haxby.image.jcodec.common.TrackType.VIDEO, codec, 0, null, 0, state, haxby.image.jcodec.common.VideoCodecMeta.createSimpleVideoCodecMeta( new Size(demuxer.pictureWidth, demuxer.pictureHeight), ColorSpace.YUV420), null); } @Override public boolean gotoSyncFrame(long i) { throw new RuntimeException("Unsupported"); } } public static class IndexedBlock { public int firstFrameNo; public MkvBlock block; public static IndexedBlock make(int no, MkvBlock b) { IndexedBlock ib = new IndexedBlock(); ib.firstFrameNo = no; ib.block = b; return ib; } } public static class SubtitlesTrack extends MkvTrack { private Codec codec = null; private String language = "eng"; SubtitlesTrack(MKVDemuxer demuxer, int trackNo, Codec codec, String language) { super(trackNo, demuxer); this.codec = codec; if (language != null) { this.language = language; } } @Override public DemuxerTrackMeta getMeta() { return new DemuxerTrackMeta(haxby.image.jcodec.common.TrackType.TEXT, this.codec, 0, null, 0, null, null, null); } public String getLanguage() { return language; } } private static class MkvBlockData { final MkvBlock block; final ByteBuffer data; final int count; MkvBlockData(MkvBlock block, ByteBuffer data, int count) { this.block = block; this.data = data; this.count = count; } } public static class MkvTrack implements SeekableDemuxerTrack { public final int trackNo; List<IndexedBlock> blocks; int framesCount = 0; private int frameIdx = 0; private int blockIdx = 0; private int frameInBlockIdx = 0; private MKVDemuxer demuxer; public MkvTrack(int trackNo, MKVDemuxer demuxer) { this.blocks = new ArrayList<IndexedBlock>(); this.trackNo = trackNo; this.demuxer = demuxer; } @Override public Packet nextFrame() throws IOException { MkvBlockData bd = nextBlock(); if (bd == null) return null; return Packet.createPacket(bd.data, bd.block.absoluteTimecode, demuxer.timescale, 1, frameIdx - 1, FrameType.KEY, ZERO_TAPE_TIMECODE); } protected MkvBlockData nextBlock() throws IOException { if (frameIdx >= blocks.size() || blockIdx >= blocks.size()) return null; MkvBlock b = blocks.get(blockIdx).block; if (b == null) throw new RuntimeException("Something somewhere went wrong."); if (b.frames == null || b.frames.length == 0) { /** * This part could be moved withing yet-another inner class, say MKVPacket to * that channel is actually rean only when Packet.getData() is executed. */ demuxer.channel.setPosition(b.dataOffset); ByteBuffer data = ByteBuffer.allocate(b.dataLen); demuxer.channel.read(data); b.readFrames(data); } ByteBuffer data = b.frames[frameInBlockIdx].duplicate(); frameInBlockIdx++; frameIdx++; if (frameInBlockIdx >= b.frames.length) { blockIdx++; frameInBlockIdx = 0; } return new MkvBlockData(b, data, 1); } @Override public boolean gotoFrame(long i) { if (i > Integer.MAX_VALUE) return false; if (i > this.framesCount) return false; int frameBlockIdx = findBlockIndex(i); if (frameBlockIdx == -1) return false; frameIdx = (int) i; blockIdx = frameBlockIdx; frameInBlockIdx = (int) i - blocks.get(blockIdx).firstFrameNo; return true; } private int findBlockIndex(long i) { for (int blockIndex = 0; blockIndex < blocks.size(); blockIndex++) { if (i < blocks.get(blockIndex).block.frameSizes.length) return blockIndex; i -= blocks.get(blockIndex).block.frameSizes.length; } return -1; } @Override public long getCurFrame() { return frameIdx; } @Override public void seek(double second) { throw new RuntimeException("Not implemented yet"); } /** * Get multiple frames * * @param count * @return */ public Packet getFrames(int count) { MkvBlockData frameBlock = getFrameBlock(count); if (frameBlock == null) return null; return Packet.createPacket(frameBlock.data, frameBlock.block.absoluteTimecode, demuxer.timescale, frameBlock.count, 0, FrameType.KEY, ZERO_TAPE_TIMECODE); } MkvBlockData getFrameBlock(int count) { if (count + frameIdx >= framesCount) return null; List<ByteBuffer> packetFrames = new ArrayList<ByteBuffer>(); MkvBlock firstBlockInAPacket = blocks.get(blockIdx).block; while (count > 0) { MkvBlock b = blocks.get(blockIdx).block; if (b.frames == null || b.frames.length == 0) { /** * This part could be moved withing yet-another inner class, say MKVPacket to * that channel is actually rean only when Packet.getData() is executed. */ try { demuxer.channel.setPosition(b.dataOffset); ByteBuffer data = ByteBuffer.allocate(b.dataLen); demuxer.channel.read(data); b.readFrames(data); } catch (IOException ioe) { throw new RuntimeException("while reading frames of a Block at offset 0x" + Long.toHexString(b.dataOffset).toUpperCase() + ")", ioe); } } packetFrames.add(b.frames[frameInBlockIdx].duplicate()); frameIdx++; frameInBlockIdx++; if (frameInBlockIdx >= b.frames.length) { frameInBlockIdx = 0; blockIdx++; } count--; } int size = 0; for (ByteBuffer aFrame : packetFrames) size += aFrame.limit(); ByteBuffer data = ByteBuffer.allocate(size); for (ByteBuffer aFrame : packetFrames) data.put(aFrame); return new MkvBlockData(firstBlockInAPacket, data, packetFrames.size()); } @Override public DemuxerTrackMeta getMeta() { return null; } @Override public boolean gotoSyncFrame(long frame) { return gotoFrame(frame); } } public static class AudioTrack extends MkvTrack { private double sampleRate = 8000; private String language = "eng"; private long channelCount = 1; private Codec codec = null; public AudioTrack(MKVDemuxer demuxer, int trackNo, Codec codec, double sampleRate, long channelCount, String language) { super(trackNo, demuxer); this.codec = codec; if (language != null) { this.language = language; } if (sampleRate > 0.0) { this.sampleRate = sampleRate; } if (channelCount > 0) { this.channelCount = channelCount; } } @Override public Packet nextFrame() throws IOException { MkvBlockData b = nextBlock(); if (b == null) return null; return Packet.createPacket(b.data, b.block.absoluteTimecode, (int) Math.round(sampleRate), 1, 0, FrameType.KEY, ZERO_TAPE_TIMECODE); } /** * Get multiple frames * * @param count * @return */ public Packet getFrames(int count) { MkvBlockData frameBlock = getFrameBlock(count); if (frameBlock == null) return null; return Packet.createPacket(frameBlock.data, frameBlock.block.absoluteTimecode, (int) Math.round(sampleRate), frameBlock.count, 0, FrameType.KEY, ZERO_TAPE_TIMECODE); } @Override public DemuxerTrackMeta getMeta() { boolean isPcm = false; if (this.codec != null) { isPcm = this.codec.isPcm(); } return new DemuxerTrackMeta(haxby.image.jcodec.common.TrackType.AUDIO, this.codec, 0, null, 0, null, null, AudioCodecMeta.createAudioCodecMeta("", 0, (int) this.channelCount, (int) this.sampleRate, ByteOrder.LITTLE_ENDIAN, isPcm, null, null)); } @Override public boolean gotoSyncFrame(long frame) { return gotoFrame(frame); } public String getLanguage() { return language; } public long getChannelCount() { return channelCount; } } public int getPictureWidth() { return pictureWidth; } public int getPictureHeight() { return pictureHeight; } @Override public List<DemuxerTrack> getAudioTracks() { return (List<DemuxerTrack>) (List) aTracks; } @Override public List<DemuxerTrack> getTracks() { ArrayList<DemuxerTrack> tracks = new ArrayList<DemuxerTrack>(aTracks); tracks.add(vTrack); tracks.addAll(subsTracks); return tracks; } @Override public List<DemuxerTrack> getVideoTracks() { ArrayList<DemuxerTrack> tracks = new ArrayList<DemuxerTrack>(); tracks.add(vTrack); return tracks; } public List<DemuxerTrack> getSubtitleTracks() { return (List<DemuxerTrack>) (List) subsTracks; } public List<? extends EbmlBase> getTree() { return t; } @Override public void close() throws IOException { channel.close(); } @UsedViaReflection public static int probe(final ByteBuffer b) { ByteBuffer fork = b.duplicate(); byte[] firstFour = new byte[4]; fork.get(firstFour); boolean hasEBMLHeader = Arrays.equals(firstFour, MKVType.EBML.id); if (hasEBMLHeader) { try { VarIntDetail headerLen = EbmlUtil.parseVarInt(fork); if (headerLen.value < 0 || headerLen.value > 1000) { // The EBML header has unusual size return 30; } byte[] allHeader = new byte[(int) headerLen.value]; fork.get(allHeader); byte[] docTypeID = MKVType.DocType.id; int currPos = 0; while (currPos < headerLen.value && allHeader[currPos++] != docTypeID[0] && allHeader[currPos++] != docTypeID[1]) { // Do nothing } if (currPos == headerLen.value) { // Could not find the doctype info return 45; } byte[] theTypeLen = new byte[8]; System.arraycopy(allHeader, currPos, theTypeLen, 0, 8); try { VarIntDetail typeLen = EbmlUtil.parseVarInt(ByteBuffer.wrap(theTypeLen)); if (typeLen.value < 0 || typeLen.value > 50) { // Unusual DocType length return 75; } byte[] theType = new byte[(int) typeLen.value]; System.arraycopy(allHeader, currPos + typeLen.length, theType, 0, (int) typeLen.value); String parsedType = new String(theType); final String[] acceptableDocTypes = { "matroska", "webm" }; for (String acceptableType : acceptableDocTypes) { if (acceptableType.equals(parsedType)) { // Header and type looks ok, we can definitely try to load this return 100; } } // Unknown type but might be good to go return 90; } catch (RuntimeException rex) { // Could not find the length of the type return 60; } } catch (RuntimeException rex) { // Could not find the length of the EBML header return 15; } } else { // Not even the EBML header is there return 0; } } }
32,092
0.571264
0.564066
804
38.915424
25.977703
124
false
false
0
0
0
0
0
0
0.823383
false
false
13
fccd2eb5f2f0a1ccc35d680e96bb994cc1bb5881
27,376,121,591,768
2949d6e6f89ea8358e6c23654b2447990e9f92f0
/src/main/java/com/platforms/supplier/platform/controller/ProductController.java
ae9883458b5cef43d4ad4f202fe84871f9d4b73b
[]
no_license
daviddai/supplier-platform
https://github.com/daviddai/supplier-platform
36fb2cad7d9dd4c764fd533b1f6fb2060c01e179
7298f3201f342149353499c372de0cf99e125ea7
refs/heads/master
2023-01-24T17:10:54.770000
2020-02-01T22:54:34
2020-02-01T22:54:34
226,198,877
0
0
null
false
2023-01-07T13:13:39
2019-12-05T22:20:32
2020-02-01T22:54:45
2023-01-07T13:13:38
2,171
0
0
19
TypeScript
false
false
package com.platforms.supplier.platform.controller; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; @RestController public class ProductController { @GetMapping(value = "/addProduct", produces = MediaType.TEXT_HTML_VALUE) public void addProduct(HttpServletResponse response) { response.setContentType(MediaType.TEXT_HTML_VALUE); } }
UTF-8
Java
522
java
ProductController.java
Java
[]
null
[]
package com.platforms.supplier.platform.controller; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; @RestController public class ProductController { @GetMapping(value = "/addProduct", produces = MediaType.TEXT_HTML_VALUE) public void addProduct(HttpServletResponse response) { response.setContentType(MediaType.TEXT_HTML_VALUE); } }
522
0.798851
0.798851
17
29.705883
27.206757
76
false
false
0
0
0
0
0
0
0.411765
false
false
13
da2a06e67e8b27a31a86da41217d88bd323e4afd
35,046,933,173,946
3de7e11ba3548f4b099a0a184d4098350bf64cf2
/src/main/java/org/flow/pojo/Resource.java
1904d9c649d944277fa5a16708e5706cce8455d3
[]
no_license
agtiga/groot-umps
https://github.com/agtiga/groot-umps
3fed33a436c718d1f8af08dd4cd391e5fab17f9f
dbf46e33fd0896d4285a604076863c2c384e833e
refs/heads/master
2022-08-19T11:41:43.671000
2018-06-22T07:01:35
2018-06-22T07:01:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.flow.pojo; import java.io.Serializable; import java.util.Date; public class Resource implements Serializable { private static final long serialVersionUID = 945884462887672211L; private Long id; private Long resourceId; private String name; private String url; private String method; private Long parentId; private String parentIds; private String permission; private String dataTarget; private String icon; private String component; private Byte type; private Byte enabled; private Date createTime; private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getResourceId() { return resourceId; } public void setResourceId(Long resourceId) { this.resourceId = resourceId; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url == null ? null : url.trim(); } public String getMethod() { return method; } public void setMethod(String method) { this.method = method == null ? null : method.trim(); } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getParentIds() { return parentIds; } public void setParentIds(String parentIds) { this.parentIds = parentIds == null ? null : parentIds.trim(); } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission == null ? null : permission.trim(); } public String getDataTarget() { return dataTarget; } public void setDataTarget(String dataTarget) { this.dataTarget = dataTarget == null ? null : dataTarget.trim(); } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon == null ? null : icon.trim(); } public String getComponent() { return component; } public void setComponent(String component) { this.component = component == null ? null : component.trim(); } public Byte getType() { return type; } public void setType(Byte type) { this.type = type; } public Byte getEnabled() { return enabled; } public void setEnabled(Byte enabled) { this.enabled = enabled; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", resourceId=").append(resourceId); sb.append(", name=").append(name); sb.append(", url=").append(url); sb.append(", method=").append(method); sb.append(", parentId=").append(parentId); sb.append(", parentIds=").append(parentIds); sb.append(", permission=").append(permission); sb.append(", dataTarget=").append(dataTarget); sb.append(", icon=").append(icon); sb.append(", component=").append(component); sb.append(", type=").append(type); sb.append(", enabled=").append(enabled); sb.append(", createTime=").append(createTime); sb.append(", updateTime=").append(updateTime); sb.append("]"); return sb.toString(); } }
UTF-8
Java
4,082
java
Resource.java
Java
[]
null
[]
package org.flow.pojo; import java.io.Serializable; import java.util.Date; public class Resource implements Serializable { private static final long serialVersionUID = 945884462887672211L; private Long id; private Long resourceId; private String name; private String url; private String method; private Long parentId; private String parentIds; private String permission; private String dataTarget; private String icon; private String component; private Byte type; private Byte enabled; private Date createTime; private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getResourceId() { return resourceId; } public void setResourceId(Long resourceId) { this.resourceId = resourceId; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url == null ? null : url.trim(); } public String getMethod() { return method; } public void setMethod(String method) { this.method = method == null ? null : method.trim(); } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getParentIds() { return parentIds; } public void setParentIds(String parentIds) { this.parentIds = parentIds == null ? null : parentIds.trim(); } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission == null ? null : permission.trim(); } public String getDataTarget() { return dataTarget; } public void setDataTarget(String dataTarget) { this.dataTarget = dataTarget == null ? null : dataTarget.trim(); } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon == null ? null : icon.trim(); } public String getComponent() { return component; } public void setComponent(String component) { this.component = component == null ? null : component.trim(); } public Byte getType() { return type; } public void setType(Byte type) { this.type = type; } public Byte getEnabled() { return enabled; } public void setEnabled(Byte enabled) { this.enabled = enabled; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", resourceId=").append(resourceId); sb.append(", name=").append(name); sb.append(", url=").append(url); sb.append(", method=").append(method); sb.append(", parentId=").append(parentId); sb.append(", parentIds=").append(parentIds); sb.append(", permission=").append(permission); sb.append(", dataTarget=").append(dataTarget); sb.append(", icon=").append(icon); sb.append(", component=").append(component); sb.append(", type=").append(type); sb.append(", enabled=").append(enabled); sb.append(", createTime=").append(createTime); sb.append(", updateTime=").append(updateTime); sb.append("]"); return sb.toString(); } }
4,082
0.595786
0.591377
182
21.434067
19.828484
72
false
false
0
0
0
0
0
0
0.467033
false
false
13
c1fc120f4e1967e40d92c27b419d63af80dd8ee2
34,402,688,088,297
395eb34ef4efb30191403b913ebbcbdb780ce31f
/AMQ_FSW2/SY_CamelWebApp_vs_AMQ/amq-camel-syapp/src/main/java/com/example/switchyard/camel_syapp/GreeterBean.java
8e8acd51a2db44c3ceec95ec680c31187383955f
[]
no_license
RickJWagner/SOA_Samples
https://github.com/RickJWagner/SOA_Samples
7c6b3a22eca70a674c236f51303d3a9ff6ef5be8
6d52f64cc450bb15db3b2e69dfadc8cd374348a3
refs/heads/master
2020-05-22T01:17:04.031000
2018-05-16T18:32:41
2018-05-16T18:32:41
1,413,609
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.switchyard.camel_syapp; import org.switchyard.component.bean.Service; @Service(Greeter.class) public class GreeterBean implements Greeter { @Override public String greet(String msg) { System.out.println("GreeterBean runs!" + msg); return "Hello " + msg; } }
UTF-8
Java
289
java
GreeterBean.java
Java
[]
null
[]
package com.example.switchyard.camel_syapp; import org.switchyard.component.bean.Service; @Service(Greeter.class) public class GreeterBean implements Greeter { @Override public String greet(String msg) { System.out.println("GreeterBean runs!" + msg); return "Hello " + msg; } }
289
0.747405
0.747405
14
19.642857
19.21163
48
false
false
0
0
0
0
0
0
0.785714
false
false
13
74e07508060089192ae51f6cb5a343065359d3eb
22,016,002,417,778
66ac0f0289e1c2308463f0422a04e100a9a14d98
/server/modules/platform/internal/src/org/labkey/api/query/SimpleTableDomainKind.java
4c15394c637d57d0162d0897d71d0e024a5f24f7
[ "MIT" ]
permissive
praveenmunagapati/ms-registration-server
https://github.com/praveenmunagapati/ms-registration-server
b4f860978f4b371cfb1fcb3c794d1315298638c2
49a851285dfbccbd0dc667f4a5ba1fcdbb2f0665
refs/heads/master
2022-04-19T00:15:59.055000
2020-04-14T06:12:38
2020-04-14T06:12:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2012-2019 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.labkey.api.query; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import org.json.JSONObject; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerType; import org.labkey.api.data.SQLFragment; import org.labkey.api.data.TableInfo; import org.labkey.api.exp.Handler; import org.labkey.api.exp.Lsid; import org.labkey.api.exp.TemplateInfo; import org.labkey.api.exp.XarContext; import org.labkey.api.exp.XarFormatException; import org.labkey.api.exp.api.ExperimentUrls; import org.labkey.api.exp.property.BaseAbstractDomainKind; import org.labkey.api.exp.property.Domain; import org.labkey.api.exp.property.PropertyService; import org.labkey.api.exp.xar.LsidUtils; import org.labkey.api.gwt.client.model.GWTDomain; import org.labkey.api.module.SimpleModule; import org.labkey.api.security.User; import org.labkey.api.security.permissions.AdminPermission; import org.labkey.api.util.GUID; import org.labkey.api.util.PageFlowUtil; import org.labkey.api.view.ActionURL; import org.labkey.api.view.HttpView; import org.labkey.api.writer.ContainerUser; import java.util.Collections; import java.util.Set; /** * User: kevink * Date: Sep 22, 2010 * * A domain kind for {@link SimpleUserSchema.SimpleTable}s. */ public class SimpleTableDomainKind extends BaseAbstractDomainKind { private static String XAR_SUBSTITUTION_SCHEMA_NAME = "SchemaName"; private static String XAR_SUBSTITUTION_TABLE_NAME = "TableName"; private static String XAR_SUBSTITUTION_GUID = "GUID"; public SimpleTableDomainKind() { } // uck. To get from a Domain to the SimpleTable we need to parse the Domain's type uri. public SimpleUserSchema.SimpleTable getTable(Domain domain) { String domainURI = domain.getTypeURI(); if (domainURI == null) return null; Lsid lsid = new Lsid(domainURI); String prefix = lsid.getNamespacePrefix(); if (prefix.startsWith(SimpleModule.NAMESPACE_PREFIX)) { // XXX: need to unescape '-' (and '.' ?) in schema and table names String schemaName = prefix.substring(SimpleModule.NAMESPACE_PREFIX.length() + 1); String queryName = lsid.getObjectId(); // HACK: have to reach out to get the user User user = HttpView.currentContext().getUser(); UserSchema schema = QueryService.get().getUserSchema(user, domain.getContainer(), schemaName); if (schema != null) { TableInfo table = schema.getTable(queryName, true); if (table instanceof SimpleUserSchema.SimpleTable) return (SimpleUserSchema.SimpleTable)table; } } return null; } @Override public String getKindName() { return SimpleModule.NAMESPACE_PREFIX; } @Override public String getTypeLabel(Domain domain) { return "Extensible Table '" + domain.getName() + "'"; } @Override public Handler.Priority getPriority(String domainURI) { Lsid lsid = new Lsid(domainURI); return lsid.getNamespacePrefix() != null && lsid.getNamespacePrefix().startsWith(SimpleModule.NAMESPACE_PREFIX) ? Handler.Priority.MEDIUM : null; } @Override public String generateDomainURI(String schemaName, String tableName, Container c, User u) { return getDomainURI(schemaName, tableName, c, u); } public static String getDomainURI(String schemaName, String tableName, Container c, User u) { try { XarContext xc = getXarContext(schemaName, tableName, c.getContainerFor(ContainerType.DataType.domainDefinitions), u); return LsidUtils.resolveLsidFromTemplate(SimpleModule.DOMAIN_LSID_TEMPLATE, xc, SimpleModule.DOMAIN_NAMESPACE_PREFIX_TEMPLATE); } catch (XarFormatException xfe) { return null; } } public static String createPropertyURI(String schemaName, String tableName, Container c, User u) { try { XarContext xc = getXarContext(schemaName, tableName, c, u); xc.addSubstitution(XAR_SUBSTITUTION_GUID, GUID.makeGUID()); return LsidUtils.resolveLsidFromTemplate(SimpleModule.PROPERTY_LSID_TEMPLATE, xc, SimpleModule.PROPERTY_NAMESPACE_PREFIX_TEMPLATE); } catch (XarFormatException xfe) { return null; } } protected static XarContext getXarContext(String schemaName, String tableName, Container c, User u) { // XXX: need to escape '-' (and '.' ?) in the schema and table names XarContext xc = new XarContext("Domains", c, u); xc.addSubstitution(XAR_SUBSTITUTION_SCHEMA_NAME, schemaName); xc.addSubstitution(XAR_SUBSTITUTION_TABLE_NAME, tableName); return xc; } @Override public SQLFragment sqlObjectIdsInDomain(Domain domain) { SimpleUserSchema.SimpleTable table = getTable(domain); if (table != null) { ColumnInfo objectUriColumn = table.getObjectUriColumn(); if (objectUriColumn != null) { TableInfo schemaTable = table.getRealTable(); SQLFragment sql = new SQLFragment(); sql.append("SELECT o.ObjectId FROM " + schemaTable + " me, exp.object o WHERE me." + objectUriColumn.getSelectName() + " = o.ObjectURI AND me.Container = ?"); sql.add(domain.getContainer().getId()); return sql; } } return new SQLFragment("NULL"); } @Override public ActionURL urlShowData(Domain domain, ContainerUser containerUser) { SimpleUserSchema.SimpleTable table = getTable(domain); if (table == null) return null; // nasty QueryDefinition qdef = table._userSchema.getQueryDefForTable(table.getName()); if (qdef != null) return table._userSchema.urlFor(QueryAction.executeQuery, qdef); return null; } @Override public boolean allowAttachmentProperties() { return true; } @Override public boolean allowFileLinkProperties() { return true; } @Override public boolean showDefaultValueSettings() { return true; } @Override public ActionURL urlEditDefinition(Domain domain, ContainerUser containerUser) { if (!containerUser.getContainer().isContainerFor(ContainerType.DataType.domainDefinitions)) return null; return PageFlowUtil.urlProvider(ExperimentUrls.class).getDomainEditorURL(containerUser.getContainer(), domain); } @Override public ActionURL urlCreateDefinition(String schemaName, String queryName, Container container, User user) { return super.urlCreateDefinition(schemaName, queryName, container.getContainerFor(ContainerType.DataType.domainDefinitions), user); } @Override public boolean canCreateDefinition(User user, Container container) { return container.hasPermission(user, AdminPermission.class) && container.isContainerFor(ContainerType.DataType.domainDefinitions); } @Override public boolean canEditDefinition(User user, Domain domain) { return domain.getContainer().hasPermission(user, AdminPermission.class); } @Override public Set<String> getReservedPropertyNames(Domain domain) { SimpleUserSchema.SimpleTable table = getTable(domain); if (table != null) { // return the set of built-in column names. return Sets.newHashSet(Iterables.transform(table.getBuiltInColumns(), new Function<ColumnInfo, String>() { public String apply(ColumnInfo col) { return col.getName(); } } )); } return Collections.emptySet(); } @Override public Domain createDomain(GWTDomain domain, JSONObject arguments, Container container, User user, TemplateInfo templateInfo) { String schemaName = (String)arguments.get("schemaName"); String tableName = (String)arguments.get("tableName"); if (schemaName == null || tableName == null) throw new IllegalArgumentException("schemaName and tableName are required"); String domainURI = generateDomainURI(schemaName, tableName, container, user); return PropertyService.get().createDomain(container, domainURI, domain.getName(), templateInfo); } }
UTF-8
Java
9,333
java
SimpleTableDomainKind.java
Java
[ { "context": "l.Collections;\nimport java.util.Set;\n\n/**\n * User: kevink\n * Date: Sep 22, 2010\n *\n * A domain kind for {@l", "end": 1878, "score": 0.9996048808097839, "start": 1872, "tag": "USERNAME", "value": "kevink" } ]
null
[]
/* * Copyright (c) 2012-2019 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.labkey.api.query; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import org.json.JSONObject; import org.labkey.api.data.ColumnInfo; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerType; import org.labkey.api.data.SQLFragment; import org.labkey.api.data.TableInfo; import org.labkey.api.exp.Handler; import org.labkey.api.exp.Lsid; import org.labkey.api.exp.TemplateInfo; import org.labkey.api.exp.XarContext; import org.labkey.api.exp.XarFormatException; import org.labkey.api.exp.api.ExperimentUrls; import org.labkey.api.exp.property.BaseAbstractDomainKind; import org.labkey.api.exp.property.Domain; import org.labkey.api.exp.property.PropertyService; import org.labkey.api.exp.xar.LsidUtils; import org.labkey.api.gwt.client.model.GWTDomain; import org.labkey.api.module.SimpleModule; import org.labkey.api.security.User; import org.labkey.api.security.permissions.AdminPermission; import org.labkey.api.util.GUID; import org.labkey.api.util.PageFlowUtil; import org.labkey.api.view.ActionURL; import org.labkey.api.view.HttpView; import org.labkey.api.writer.ContainerUser; import java.util.Collections; import java.util.Set; /** * User: kevink * Date: Sep 22, 2010 * * A domain kind for {@link SimpleUserSchema.SimpleTable}s. */ public class SimpleTableDomainKind extends BaseAbstractDomainKind { private static String XAR_SUBSTITUTION_SCHEMA_NAME = "SchemaName"; private static String XAR_SUBSTITUTION_TABLE_NAME = "TableName"; private static String XAR_SUBSTITUTION_GUID = "GUID"; public SimpleTableDomainKind() { } // uck. To get from a Domain to the SimpleTable we need to parse the Domain's type uri. public SimpleUserSchema.SimpleTable getTable(Domain domain) { String domainURI = domain.getTypeURI(); if (domainURI == null) return null; Lsid lsid = new Lsid(domainURI); String prefix = lsid.getNamespacePrefix(); if (prefix.startsWith(SimpleModule.NAMESPACE_PREFIX)) { // XXX: need to unescape '-' (and '.' ?) in schema and table names String schemaName = prefix.substring(SimpleModule.NAMESPACE_PREFIX.length() + 1); String queryName = lsid.getObjectId(); // HACK: have to reach out to get the user User user = HttpView.currentContext().getUser(); UserSchema schema = QueryService.get().getUserSchema(user, domain.getContainer(), schemaName); if (schema != null) { TableInfo table = schema.getTable(queryName, true); if (table instanceof SimpleUserSchema.SimpleTable) return (SimpleUserSchema.SimpleTable)table; } } return null; } @Override public String getKindName() { return SimpleModule.NAMESPACE_PREFIX; } @Override public String getTypeLabel(Domain domain) { return "Extensible Table '" + domain.getName() + "'"; } @Override public Handler.Priority getPriority(String domainURI) { Lsid lsid = new Lsid(domainURI); return lsid.getNamespacePrefix() != null && lsid.getNamespacePrefix().startsWith(SimpleModule.NAMESPACE_PREFIX) ? Handler.Priority.MEDIUM : null; } @Override public String generateDomainURI(String schemaName, String tableName, Container c, User u) { return getDomainURI(schemaName, tableName, c, u); } public static String getDomainURI(String schemaName, String tableName, Container c, User u) { try { XarContext xc = getXarContext(schemaName, tableName, c.getContainerFor(ContainerType.DataType.domainDefinitions), u); return LsidUtils.resolveLsidFromTemplate(SimpleModule.DOMAIN_LSID_TEMPLATE, xc, SimpleModule.DOMAIN_NAMESPACE_PREFIX_TEMPLATE); } catch (XarFormatException xfe) { return null; } } public static String createPropertyURI(String schemaName, String tableName, Container c, User u) { try { XarContext xc = getXarContext(schemaName, tableName, c, u); xc.addSubstitution(XAR_SUBSTITUTION_GUID, GUID.makeGUID()); return LsidUtils.resolveLsidFromTemplate(SimpleModule.PROPERTY_LSID_TEMPLATE, xc, SimpleModule.PROPERTY_NAMESPACE_PREFIX_TEMPLATE); } catch (XarFormatException xfe) { return null; } } protected static XarContext getXarContext(String schemaName, String tableName, Container c, User u) { // XXX: need to escape '-' (and '.' ?) in the schema and table names XarContext xc = new XarContext("Domains", c, u); xc.addSubstitution(XAR_SUBSTITUTION_SCHEMA_NAME, schemaName); xc.addSubstitution(XAR_SUBSTITUTION_TABLE_NAME, tableName); return xc; } @Override public SQLFragment sqlObjectIdsInDomain(Domain domain) { SimpleUserSchema.SimpleTable table = getTable(domain); if (table != null) { ColumnInfo objectUriColumn = table.getObjectUriColumn(); if (objectUriColumn != null) { TableInfo schemaTable = table.getRealTable(); SQLFragment sql = new SQLFragment(); sql.append("SELECT o.ObjectId FROM " + schemaTable + " me, exp.object o WHERE me." + objectUriColumn.getSelectName() + " = o.ObjectURI AND me.Container = ?"); sql.add(domain.getContainer().getId()); return sql; } } return new SQLFragment("NULL"); } @Override public ActionURL urlShowData(Domain domain, ContainerUser containerUser) { SimpleUserSchema.SimpleTable table = getTable(domain); if (table == null) return null; // nasty QueryDefinition qdef = table._userSchema.getQueryDefForTable(table.getName()); if (qdef != null) return table._userSchema.urlFor(QueryAction.executeQuery, qdef); return null; } @Override public boolean allowAttachmentProperties() { return true; } @Override public boolean allowFileLinkProperties() { return true; } @Override public boolean showDefaultValueSettings() { return true; } @Override public ActionURL urlEditDefinition(Domain domain, ContainerUser containerUser) { if (!containerUser.getContainer().isContainerFor(ContainerType.DataType.domainDefinitions)) return null; return PageFlowUtil.urlProvider(ExperimentUrls.class).getDomainEditorURL(containerUser.getContainer(), domain); } @Override public ActionURL urlCreateDefinition(String schemaName, String queryName, Container container, User user) { return super.urlCreateDefinition(schemaName, queryName, container.getContainerFor(ContainerType.DataType.domainDefinitions), user); } @Override public boolean canCreateDefinition(User user, Container container) { return container.hasPermission(user, AdminPermission.class) && container.isContainerFor(ContainerType.DataType.domainDefinitions); } @Override public boolean canEditDefinition(User user, Domain domain) { return domain.getContainer().hasPermission(user, AdminPermission.class); } @Override public Set<String> getReservedPropertyNames(Domain domain) { SimpleUserSchema.SimpleTable table = getTable(domain); if (table != null) { // return the set of built-in column names. return Sets.newHashSet(Iterables.transform(table.getBuiltInColumns(), new Function<ColumnInfo, String>() { public String apply(ColumnInfo col) { return col.getName(); } } )); } return Collections.emptySet(); } @Override public Domain createDomain(GWTDomain domain, JSONObject arguments, Container container, User user, TemplateInfo templateInfo) { String schemaName = (String)arguments.get("schemaName"); String tableName = (String)arguments.get("tableName"); if (schemaName == null || tableName == null) throw new IllegalArgumentException("schemaName and tableName are required"); String domainURI = generateDomainURI(schemaName, tableName, container, user); return PropertyService.get().createDomain(container, domainURI, domain.getName(), templateInfo); } }
9,333
0.67031
0.668274
267
33.951309
34.253208
174
false
false
0
0
0
0
0
0
0.595506
false
false
13
642d6731d953ee0be4f9f395127f363e5a42a553
6,889,127,549,555
0d2d26716f3460db58f9169c1be309414a2c765c
/project/src/ru/rd/courier/scripting/dataaccess/streamed/DbfParser.java
5970eb171f1d4d4eba3cf801768de14262d54578
[ "BSD-2-Clause" ]
permissive
RD-Courier/Courier
https://github.com/RD-Courier/Courier
ec2e423c341143d14f0a4a3c85eaf22b125ce107
f33c5e82f1fb4ff46431c9a2aca3763e79d62422
refs/heads/master
2020-05-23T10:13:39.475000
2017-02-16T13:01:58
2017-02-16T13:01:58
80,405,276
0
1
null
false
2017-02-09T08:16:39
2017-01-30T08:42:45
2017-01-30T12:46:04
2017-02-09T08:16:39
48,776
0
1
0
Java
null
null
/* * Copyright 2005-2017 Courier AUTHORS: please see AUTHORS file. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package ru.rd.courier.scripting.dataaccess.streamed; import com.linuxense.javadbf.DBFException; import com.linuxense.javadbf.DBFField; import com.linuxense.javadbf.DBFReader; import ru.rd.courier.jdbc.objbuffer.*; import ru.rd.courier.utils.StringHelper; import ru.rd.courier.utils.StringSimpleParser; import java.io.IOException; import java.io.InputStream; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** * User: AStepochkin * Date: 22.07.2008 * Time: 19:22:46 */ public class DbfParser implements StreamParser { private String m_encoding; private boolean m_trim; public DbfParser(String encoding, boolean trim) { m_encoding = encoding; m_trim = trim; } public void parseProperties(StringSimpleParser p) { Properties props = p.getProperties(null, '\'', "|"); m_encoding = StringHelper.stringParam(props, "encoding", m_encoding); m_trim = !StringHelper.boolParam(props, "cancel-trim", !m_trim); } public ResultSet parse(InputStream is) throws IOException { return new DbfResultSet(is, m_encoding, m_trim); } public void cancel() {} private static class DbfResultSet extends ObjectsResultSet { private InputStream is; private DBFReader m_dbf; private boolean m_trim; private static ColumnInfo[] getColumns(DBFReader dbf) throws DBFException { ColumnInfo[] cols = new ColumnInfo[dbf.getFieldCount()]; for (int i = 0; i < cols.length; i++) { DBFField f = dbf.getField(i); ColumnInfo col; switch(f.getDataType()) { case DBFField.FIELD_TYPE_C: col = new StringInfo(f.getName(), f.getFieldLength()); break; case DBFField.FIELD_TYPE_D: col = new DateInfo(f.getName()); break; case DBFField.FIELD_TYPE_F: col = new FloatInfo(f.getName(), f.getFieldLength(), f.getDecimalCount()); break; case DBFField.FIELD_TYPE_L: col = new BooleanInfo(f.getName()); break; case DBFField.FIELD_TYPE_N: col = new NumericInfo(f.getName(), f.getFieldLength(), f.getDecimalCount()); break; default: throw new RuntimeException("Unknown field type '" + f.getDataType() + "'"); } cols[i] = col; } return cols; } private static DBFReader createReader(InputStream data, String encoding) throws DBFException { DBFReader dbfr = new DBFReader(data); if (encoding != null) { dbfr.setCharactersetName(encoding); } return dbfr; } public DbfResultSet(InputStream data, String encoding, boolean trim) throws DBFException { this(createReader(data, encoding), trim); is = data; } public DbfResultSet(DBFReader dbf, boolean trim) throws DBFException { super(null, getColumns(dbf)); m_dbf = dbf; m_trim = trim; } protected boolean getRecord() throws SQLException { try { Object[] rec = m_dbf.nextRecord(); if (rec == null) return false; if (m_trim) { for (int i = 0; i < rec.length; i++) { Object obj = rec[i]; if (obj instanceof String) { rec[i] = ((String)obj).trim(); } } } setData(rec); return true; } catch (DBFException e) { throw new RuntimeException(e); } } protected int skipRecords(int count) throws SQLException { try{ int i; for (i = 0; i < count; i++) { if(m_dbf.nextRecord() == null) break; } return i; } catch (DBFException e) { throw new RuntimeException(e); } } @Override public void close() throws SQLException { try { if (is != null) { is.close(); } } catch (IOException e) { throw new RuntimeException(e); } super.close(); } } }
UTF-8
Java
6,215
java
DbfParser.java
Java
[ { "context": "on;\r\nimport java.util.Properties;\r\n\r\n/**\r\n * User: AStepochkin\r\n * Date: 22.07.2008\r\n * Time: 19:22:46\r\n */\r\npub", "end": 1887, "score": 0.9737750291824341, "start": 1876, "tag": "USERNAME", "value": "AStepochkin" } ]
null
[]
/* * Copyright 2005-2017 Courier AUTHORS: please see AUTHORS file. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package ru.rd.courier.scripting.dataaccess.streamed; import com.linuxense.javadbf.DBFException; import com.linuxense.javadbf.DBFField; import com.linuxense.javadbf.DBFReader; import ru.rd.courier.jdbc.objbuffer.*; import ru.rd.courier.utils.StringHelper; import ru.rd.courier.utils.StringSimpleParser; import java.io.IOException; import java.io.InputStream; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** * User: AStepochkin * Date: 22.07.2008 * Time: 19:22:46 */ public class DbfParser implements StreamParser { private String m_encoding; private boolean m_trim; public DbfParser(String encoding, boolean trim) { m_encoding = encoding; m_trim = trim; } public void parseProperties(StringSimpleParser p) { Properties props = p.getProperties(null, '\'', "|"); m_encoding = StringHelper.stringParam(props, "encoding", m_encoding); m_trim = !StringHelper.boolParam(props, "cancel-trim", !m_trim); } public ResultSet parse(InputStream is) throws IOException { return new DbfResultSet(is, m_encoding, m_trim); } public void cancel() {} private static class DbfResultSet extends ObjectsResultSet { private InputStream is; private DBFReader m_dbf; private boolean m_trim; private static ColumnInfo[] getColumns(DBFReader dbf) throws DBFException { ColumnInfo[] cols = new ColumnInfo[dbf.getFieldCount()]; for (int i = 0; i < cols.length; i++) { DBFField f = dbf.getField(i); ColumnInfo col; switch(f.getDataType()) { case DBFField.FIELD_TYPE_C: col = new StringInfo(f.getName(), f.getFieldLength()); break; case DBFField.FIELD_TYPE_D: col = new DateInfo(f.getName()); break; case DBFField.FIELD_TYPE_F: col = new FloatInfo(f.getName(), f.getFieldLength(), f.getDecimalCount()); break; case DBFField.FIELD_TYPE_L: col = new BooleanInfo(f.getName()); break; case DBFField.FIELD_TYPE_N: col = new NumericInfo(f.getName(), f.getFieldLength(), f.getDecimalCount()); break; default: throw new RuntimeException("Unknown field type '" + f.getDataType() + "'"); } cols[i] = col; } return cols; } private static DBFReader createReader(InputStream data, String encoding) throws DBFException { DBFReader dbfr = new DBFReader(data); if (encoding != null) { dbfr.setCharactersetName(encoding); } return dbfr; } public DbfResultSet(InputStream data, String encoding, boolean trim) throws DBFException { this(createReader(data, encoding), trim); is = data; } public DbfResultSet(DBFReader dbf, boolean trim) throws DBFException { super(null, getColumns(dbf)); m_dbf = dbf; m_trim = trim; } protected boolean getRecord() throws SQLException { try { Object[] rec = m_dbf.nextRecord(); if (rec == null) return false; if (m_trim) { for (int i = 0; i < rec.length; i++) { Object obj = rec[i]; if (obj instanceof String) { rec[i] = ((String)obj).trim(); } } } setData(rec); return true; } catch (DBFException e) { throw new RuntimeException(e); } } protected int skipRecords(int count) throws SQLException { try{ int i; for (i = 0; i < count; i++) { if(m_dbf.nextRecord() == null) break; } return i; } catch (DBFException e) { throw new RuntimeException(e); } } @Override public void close() throws SQLException { try { if (is != null) { is.close(); } } catch (IOException e) { throw new RuntimeException(e); } super.close(); } } }
6,215
0.551247
0.546903
168
34.994049
24.611868
102
false
false
0
0
0
0
0
0
0.660714
false
false
13
1912af73b6a96f4fc879927371af858fe53eabd1
16,767,552,340,811
98f4178dafbdf40f64bc1cba98debbcfab14c3bc
/app/src/main/java/com/xixicm/ca/domain/usecase/DefaultUCCallback.java
bde39473f92d0530b9fd179f29e4e23436e782bd
[ "Apache-2.0" ]
permissive
enuoCM/CA2
https://github.com/enuoCM/CA2
914b2316702a644b9c105d3a367f3367c67afabd
112d08951a84b309f847b01852160bf34178f0e3
refs/heads/master
2022-11-26T18:50:28.269000
2022-11-07T14:43:03
2022-11-07T14:44:33
193,346,807
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xixicm.ca.domain.usecase; /** * Created by mc on 2018/4/9. */ public class DefaultUCCallback<Request, Response> implements UseCase.UseCaseCallback<Request, Response> { @Override public void onSuccess(Request request) { } @Override public void onError(Response response) { } }
UTF-8
Java
319
java
DefaultUCCallback.java
Java
[ { "context": "e com.xixicm.ca.domain.usecase;\n\n/**\n * Created by mc on 2018/4/9.\n */\n\npublic class DefaultUCCallback<", "end": 59, "score": 0.994574248790741, "start": 57, "tag": "USERNAME", "value": "mc" } ]
null
[]
package com.xixicm.ca.domain.usecase; /** * Created by mc on 2018/4/9. */ public class DefaultUCCallback<Request, Response> implements UseCase.UseCaseCallback<Request, Response> { @Override public void onSuccess(Request request) { } @Override public void onError(Response response) { } }
319
0.695925
0.677116
18
16.777779
26.296505
105
false
false
0
0
0
0
0
0
0.166667
false
false
13
00e98f9bf0ee168aa33b0a354104b75bf6a18123
12,558,484,383,588
1234fff6ffd4f4cca1ab9d170a6cae519f5e987e
/src/gestorAsistenteVAC/util/StackU.java
e3b404ec89be2e5eeb8a97bc074eb745477296f0
[]
no_license
dafty-punky-boy/GestorAsistenteVAC
https://github.com/dafty-punky-boy/GestorAsistenteVAC
b9663c1429b15f5c54df2351088b7c9cd86b722f
c99e0abf1f3702a123b8f059970587ee7585aae2
refs/heads/main
2023-07-16T12:57:19.898000
2021-08-01T05:19:25
2021-08-01T05:19:25
356,980,945
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gestorAsistenteVAC.util; /** * Clase generica Pila. Deinida como una Subclase de LinkedList. * @author Dafty-Punky-Boy * @version 1.0, 22/04/21 * */ public class StackU<T> extends LinkedListU<T>{ /** * Crea una pila vacรญa. */ public StackU(){ super(); } /** * Agrega un nodo almacenando un dato de tipo T en la pila. * @param key EL dato de tipo T que se quiere almacenar. */ public void push(T key) { super.addBack(key); } /** * Extrae el dato de tipo T del utlimo nodo de la pila. * @return El ultimo dato de tipo T aรฑadido. */ public T pop() { if(isEmpty()) { return null; } T key = tail.getKey(); tail = tail.getPrev(); if(tail != null) { tail.setNext(null); } return key; } /** * Consulta el dato de tipo T del utlimo nodo de la pila. * @return El ultimo dato de tipo T aรฑadido. */ public T peek() { if(isEmpty()) { return null; } return tail.getKey(); } }
ISO-8859-1
Java
973
java
StackU.java
Java
[ { "context": "einida como una Subclase de LinkedList.\n * @author Dafty-Punky-Boy\n * @version 1.0, 22/04/21\n * \n */\npublic class St", "end": 129, "score": 0.9998855590820312, "start": 114, "tag": "NAME", "value": "Dafty-Punky-Boy" } ]
null
[]
package gestorAsistenteVAC.util; /** * Clase generica Pila. Deinida como una Subclase de LinkedList. * @author Dafty-Punky-Boy * @version 1.0, 22/04/21 * */ public class StackU<T> extends LinkedListU<T>{ /** * Crea una pila vacรญa. */ public StackU(){ super(); } /** * Agrega un nodo almacenando un dato de tipo T en la pila. * @param key EL dato de tipo T que se quiere almacenar. */ public void push(T key) { super.addBack(key); } /** * Extrae el dato de tipo T del utlimo nodo de la pila. * @return El ultimo dato de tipo T aรฑadido. */ public T pop() { if(isEmpty()) { return null; } T key = tail.getKey(); tail = tail.getPrev(); if(tail != null) { tail.setNext(null); } return key; } /** * Consulta el dato de tipo T del utlimo nodo de la pila. * @return El ultimo dato de tipo T aรฑadido. */ public T peek() { if(isEmpty()) { return null; } return tail.getKey(); } }
973
0.604124
0.595876
57
16.017544
17.909609
64
false
false
0
0
0
0
0
0
1.438596
false
false
13
dd04801f2c9ffa42015feba9b692c47e7ba7c514
29,085,518,558,926
61824a4ae9e4bba692a58ea5e732f77cf8ce8a76
/code/src/com/haibison/android/anhuu/providers/localfile/LocalFileContract.java
c034e551c8cfb9f857c21eed8a1c3e4216473f16
[ "Apache-2.0", "MIT" ]
permissive
Darknutrino/an-huu
https://github.com/Darknutrino/an-huu
3bbaf563a4caeace53724047256afdfa1dfea33d
9be113aacd119c518af4dad4283920747e0fb586
refs/heads/master
2021-01-10T18:02:12.640000
2014-07-24T11:17:52
2014-07-24T11:17:52
44,823,525
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2012 Hai Bison * * See the file LICENSE at the root directory of this project for copying * permission. */ package com.haibison.android.anhuu.providers.localfile; import android.content.Context; import com.haibison.android.anhuu.utils.Sys; /** * Contract for local file. * * @author Hai Bison * @since v5.1 beta */ public class LocalFileContract { /** * The raw authority of this provider. */ private static final String AUTHORITY = Sys.LIB_CODE_NAME + ".localfile"; /** * Gets the authority of this provider. * * @param context * the context. * @return the authority. */ public static final String getAuthority(Context context) { return context.getPackageName() + "." + AUTHORITY; }// getAuthority() /** * The unique ID of this provider. */ public static final String _ID = "7dab9818-0a8b-47ef-88cc-10fe538bfaf7"; }
UTF-8
Java
962
java
LocalFileContract.java
Java
[ { "context": "/*\n * Copyright (c) 2012 Hai Bison\n *\n * See the file LICENSE at the root directo", "end": 37, "score": 0.9998729228973389, "start": 28, "tag": "NAME", "value": "Hai Bison" }, { "context": "s;\n\n/**\n * Contract for local file.\n * \n * @author Hai Bison\n * @since v5.1 beta\n */\npublic class LocalFileCon", "end": 333, "score": 0.9998714327812195, "start": 324, "tag": "NAME", "value": "Hai Bison" } ]
null
[]
/* * Copyright (c) 2012 <NAME> * * See the file LICENSE at the root directory of this project for copying * permission. */ package com.haibison.android.anhuu.providers.localfile; import android.content.Context; import com.haibison.android.anhuu.utils.Sys; /** * Contract for local file. * * @author <NAME> * @since v5.1 beta */ public class LocalFileContract { /** * The raw authority of this provider. */ private static final String AUTHORITY = Sys.LIB_CODE_NAME + ".localfile"; /** * Gets the authority of this provider. * * @param context * the context. * @return the authority. */ public static final String getAuthority(Context context) { return context.getPackageName() + "." + AUTHORITY; }// getAuthority() /** * The unique ID of this provider. */ public static final String _ID = "7dab9818-0a8b-47ef-88cc-10fe538bfaf7"; }
956
0.634096
0.610187
43
21.372093
23.147678
77
false
false
0
0
0
0
0
0
0.139535
false
false
13
689c44f796733260e5a84a471896c25e5e89201a
1,717,986,978,905
995f73d30450a6dce6bc7145d89344b4ad6e0622
/Mate20-9.0/src/main/java/com/android/internal/os/CpuPowerCalculator.java
e0c853a928b05232e5004bd4ec16f4d8cd073e47
[]
no_license
morningblu/HWFramework
https://github.com/morningblu/HWFramework
0ceb02cbe42585d0169d9b6c4964a41b436039f5
672bb34094b8780806a10ba9b1d21036fd808b8e
refs/heads/master
2023-07-29T05:26:14.603000
2021-09-03T05:23:34
2021-09-03T05:23:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.internal.os; import android.os.BatteryStats; import android.util.ArrayMap; import android.util.Log; import com.android.internal.telephony.PhoneConstants; public class CpuPowerCalculator extends PowerCalculator { private static final boolean DEBUG = false; private static final long MICROSEC_IN_HR = 3600000000L; private static final String TAG = "CpuPowerCalculator"; private final PowerProfile mProfile; public CpuPowerCalculator(PowerProfile profile) { this.mProfile = profile; } public void calculateApp(BatterySipper app, BatteryStats.Uid u, long rawRealtimeUs, long rawUptimeUs, int statsType) { double highestDrain; BatterySipper batterySipper = app; BatteryStats.Uid uid = u; int i = statsType; batterySipper.cpuTimeMs = (uid.getUserCpuTimeUs(i) + uid.getSystemCpuTimeUs(i)) / 1000; int numClusters = this.mProfile.getNumCpuClusters(); double cpuPowerMaUs = 0.0d; int cluster = 0; while (cluster < numClusters) { int speedsForCluster = this.mProfile.getNumSpeedStepsInCpuCluster(cluster); double cpuPowerMaUs2 = cpuPowerMaUs; for (int speed = 0; speed < speedsForCluster; speed++) { cpuPowerMaUs2 += ((double) uid.getTimeAtCpuSpeed(cluster, speed, i)) * this.mProfile.getAveragePowerForCpuCore(cluster, speed); } cluster++; cpuPowerMaUs = cpuPowerMaUs2; } double cpuPowerMaUs3 = cpuPowerMaUs + (((double) (u.getCpuActiveTime() * 1000)) * this.mProfile.getAveragePower(PowerProfile.POWER_CPU_ACTIVE)); long[] cpuClusterTimes = u.getCpuClusterTimes(); if (cpuClusterTimes != null) { if (cpuClusterTimes.length == numClusters) { for (int i2 = 0; i2 < numClusters; i2++) { cpuPowerMaUs3 += ((double) (cpuClusterTimes[i2] * 1000)) * this.mProfile.getAveragePowerForCpuCluster(i2); } } else { Log.w(TAG, "UID " + u.getUid() + " CPU cluster # mismatch: Power Profile # " + numClusters + " actual # " + cpuClusterTimes.length); } } batterySipper.cpuPowerMah = cpuPowerMaUs3 / 3.6E9d; double highestDrain2 = 0.0d; batterySipper.cpuFgTimeMs = 0; ArrayMap<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats(); int processStatsCount = processStats.size(); int i3 = 0; while (true) { int i4 = i3; if (i4 >= processStatsCount) { break; } BatteryStats.Uid.Proc ps = (BatteryStats.Uid.Proc) processStats.valueAt(i4); String processName = processStats.keyAt(i4); int numClusters2 = numClusters; long[] cpuClusterTimes2 = cpuClusterTimes; batterySipper.cpuFgTimeMs += ps.getForegroundTime(i); long costValue = ps.getUserTime(i) + ps.getSystemTime(i) + ps.getForegroundTime(i); if (batterySipper.packageWithHighestDrain == null || batterySipper.packageWithHighestDrain.startsWith(PhoneConstants.APN_TYPE_ALL)) { highestDrain = (double) costValue; batterySipper.packageWithHighestDrain = processName; } else { if (highestDrain2 < ((double) costValue) && !processName.startsWith(PhoneConstants.APN_TYPE_ALL)) { highestDrain = (double) costValue; batterySipper.packageWithHighestDrain = processName; } i3 = i4 + 1; numClusters = numClusters2; cpuClusterTimes = cpuClusterTimes2; BatteryStats.Uid uid2 = u; i = statsType; } highestDrain2 = highestDrain; i3 = i4 + 1; numClusters = numClusters2; cpuClusterTimes = cpuClusterTimes2; BatteryStats.Uid uid22 = u; i = statsType; } long[] jArr = cpuClusterTimes; if (batterySipper.cpuFgTimeMs > batterySipper.cpuTimeMs) { batterySipper.cpuTimeMs = batterySipper.cpuFgTimeMs; } } }
UTF-8
Java
4,216
java
CpuPowerCalculator.java
Java
[]
null
[]
package com.android.internal.os; import android.os.BatteryStats; import android.util.ArrayMap; import android.util.Log; import com.android.internal.telephony.PhoneConstants; public class CpuPowerCalculator extends PowerCalculator { private static final boolean DEBUG = false; private static final long MICROSEC_IN_HR = 3600000000L; private static final String TAG = "CpuPowerCalculator"; private final PowerProfile mProfile; public CpuPowerCalculator(PowerProfile profile) { this.mProfile = profile; } public void calculateApp(BatterySipper app, BatteryStats.Uid u, long rawRealtimeUs, long rawUptimeUs, int statsType) { double highestDrain; BatterySipper batterySipper = app; BatteryStats.Uid uid = u; int i = statsType; batterySipper.cpuTimeMs = (uid.getUserCpuTimeUs(i) + uid.getSystemCpuTimeUs(i)) / 1000; int numClusters = this.mProfile.getNumCpuClusters(); double cpuPowerMaUs = 0.0d; int cluster = 0; while (cluster < numClusters) { int speedsForCluster = this.mProfile.getNumSpeedStepsInCpuCluster(cluster); double cpuPowerMaUs2 = cpuPowerMaUs; for (int speed = 0; speed < speedsForCluster; speed++) { cpuPowerMaUs2 += ((double) uid.getTimeAtCpuSpeed(cluster, speed, i)) * this.mProfile.getAveragePowerForCpuCore(cluster, speed); } cluster++; cpuPowerMaUs = cpuPowerMaUs2; } double cpuPowerMaUs3 = cpuPowerMaUs + (((double) (u.getCpuActiveTime() * 1000)) * this.mProfile.getAveragePower(PowerProfile.POWER_CPU_ACTIVE)); long[] cpuClusterTimes = u.getCpuClusterTimes(); if (cpuClusterTimes != null) { if (cpuClusterTimes.length == numClusters) { for (int i2 = 0; i2 < numClusters; i2++) { cpuPowerMaUs3 += ((double) (cpuClusterTimes[i2] * 1000)) * this.mProfile.getAveragePowerForCpuCluster(i2); } } else { Log.w(TAG, "UID " + u.getUid() + " CPU cluster # mismatch: Power Profile # " + numClusters + " actual # " + cpuClusterTimes.length); } } batterySipper.cpuPowerMah = cpuPowerMaUs3 / 3.6E9d; double highestDrain2 = 0.0d; batterySipper.cpuFgTimeMs = 0; ArrayMap<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats(); int processStatsCount = processStats.size(); int i3 = 0; while (true) { int i4 = i3; if (i4 >= processStatsCount) { break; } BatteryStats.Uid.Proc ps = (BatteryStats.Uid.Proc) processStats.valueAt(i4); String processName = processStats.keyAt(i4); int numClusters2 = numClusters; long[] cpuClusterTimes2 = cpuClusterTimes; batterySipper.cpuFgTimeMs += ps.getForegroundTime(i); long costValue = ps.getUserTime(i) + ps.getSystemTime(i) + ps.getForegroundTime(i); if (batterySipper.packageWithHighestDrain == null || batterySipper.packageWithHighestDrain.startsWith(PhoneConstants.APN_TYPE_ALL)) { highestDrain = (double) costValue; batterySipper.packageWithHighestDrain = processName; } else { if (highestDrain2 < ((double) costValue) && !processName.startsWith(PhoneConstants.APN_TYPE_ALL)) { highestDrain = (double) costValue; batterySipper.packageWithHighestDrain = processName; } i3 = i4 + 1; numClusters = numClusters2; cpuClusterTimes = cpuClusterTimes2; BatteryStats.Uid uid2 = u; i = statsType; } highestDrain2 = highestDrain; i3 = i4 + 1; numClusters = numClusters2; cpuClusterTimes = cpuClusterTimes2; BatteryStats.Uid uid22 = u; i = statsType; } long[] jArr = cpuClusterTimes; if (batterySipper.cpuFgTimeMs > batterySipper.cpuTimeMs) { batterySipper.cpuTimeMs = batterySipper.cpuFgTimeMs; } } }
4,216
0.614801
0.598435
90
45.844444
34.504078
152
false
false
0
0
0
0
0
0
0.811111
false
false
13
0d9bdb5dc04e8f26d548edbc4be2f1c6e51ed412
6,021,544,218,397
0a0e4e54e668d715c5b4399daca0037d87b254b1
/src/com/olms/dao/SelectQuestionDaoImpl.java
7dfa80b239cd6af64a22fbea0cc5c3096e1f08dc
[]
no_license
qhtml5/OLMS
https://github.com/qhtml5/OLMS
25044c8f6ca292d18901007945e4c0db91cfc01b
d421cfd82c033931c72c39f83db0f878e6dfd0df
refs/heads/master
2020-03-25T04:05:24.577000
2013-06-04T08:33:21
2013-06-04T08:33:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.olms.dao; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.olms.model.SelectQuestion; import com.olms.model.TestPaper; public class SelectQuestionDaoImpl extends HibernateDaoSupport implements SelectQuestionDao { @Override public void add(SelectQuestion selectQuestion) { getHibernateTemplate().save(selectQuestion); } @Override public void delete(SelectQuestion selectQuestion) { getHibernateTemplate().delete(selectQuestion); } @Override public void update(SelectQuestion selectQuestion) { getHibernateTemplate().update(selectQuestion); } @SuppressWarnings("unchecked") @Override public List<SelectQuestion> list() { return (List<SelectQuestion>)getHibernateTemplate().find("from SelectQuestion"); } @Override public SelectQuestion getSelectQuestionByID(Integer selectQuestionID) { return getHibernateTemplate().get(SelectQuestion.class, selectQuestionID); } @Override public List<SelectQuestion> listByTestPaperID(Integer testPaperID) { // TODO Auto-generated method stub return (List<SelectQuestion>) getHibernateTemplate().get(TestPaper.class, testPaperID); } }
UTF-8
Java
1,223
java
SelectQuestionDaoImpl.java
Java
[]
null
[]
package com.olms.dao; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.olms.model.SelectQuestion; import com.olms.model.TestPaper; public class SelectQuestionDaoImpl extends HibernateDaoSupport implements SelectQuestionDao { @Override public void add(SelectQuestion selectQuestion) { getHibernateTemplate().save(selectQuestion); } @Override public void delete(SelectQuestion selectQuestion) { getHibernateTemplate().delete(selectQuestion); } @Override public void update(SelectQuestion selectQuestion) { getHibernateTemplate().update(selectQuestion); } @SuppressWarnings("unchecked") @Override public List<SelectQuestion> list() { return (List<SelectQuestion>)getHibernateTemplate().find("from SelectQuestion"); } @Override public SelectQuestion getSelectQuestionByID(Integer selectQuestionID) { return getHibernateTemplate().get(SelectQuestion.class, selectQuestionID); } @Override public List<SelectQuestion> listByTestPaperID(Integer testPaperID) { // TODO Auto-generated method stub return (List<SelectQuestion>) getHibernateTemplate().get(TestPaper.class, testPaperID); } }
1,223
0.770237
0.769419
44
25.795454
28.896036
93
false
false
0
0
0
0
0
0
1.045455
false
false
13
0b2db35bab1964924f1a80619eab4819df66f294
11,948,599,082,965
b7565796f4ce75de1f7db4a7a0dbc9fb6ca1b53f
/src/test/java/com/lumatax/salesanalyzer/model/ValidTransactionsSummaryTest.java
3c6ba9396ff41d4c459332468b498fdef945dc04
[]
no_license
michaelmills/lumatax-server
https://github.com/michaelmills/lumatax-server
0921d4b93e04186afce931177b6e4e07c274e570
825ad8497e0f27b494175eefb2ef9034b19d9845
refs/heads/main
2023-08-24T19:21:19.936000
2021-11-04T17:19:52
2021-11-04T17:19:52
422,806,015
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lumatax.salesanalyzer.model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import java.math.BigDecimal; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @RunWith(MockitoJUnitRunner.class) class ValidTransactionsSummaryTest { private ValidTransactionsSummary summary; @BeforeEach void setUp() { summary = new ValidTransactionsSummary(); } @Test void addSale() { assertEquals(0, summary.getTotalSales().intValue()); summary.addSale(new BigDecimal(100)); summary.addSale(new BigDecimal(500)); summary.addTax(null); assertEquals(600, summary.getTotalSales().intValue()); } @Test void addTax() { assertEquals(0, summary.getTotalTax().intValue()); summary.addTax(new BigDecimal(200)); summary.addTax(new BigDecimal(500)); summary.addTax(null); assertEquals(700, summary.getTotalTax().intValue()); } @Test void addDate() { assertNull(summary.getStartDate()); assertNull(summary.getEndDate()); LocalDate end = LocalDate.of(2020, 10, 20); LocalDate middle = LocalDate.of(1990, 1, 2); LocalDate start = LocalDate.of(1700, 5, 11); summary.addDate(end); summary.addDate(start); summary.addDate(middle); assertEquals(start, summary.getStartDate()); assertEquals(end, summary.getEndDate()); } @Test void addDate_SameDates() { assertNull(summary.getStartDate()); assertNull(summary.getEndDate()); LocalDate date = LocalDate.of(2020, 10, 20); LocalDate date1 = LocalDate.of(2020, 10, 20); LocalDate date2 = LocalDate.of(2020, 10, 20); summary.addDate(date); summary.addDate(date2); summary.addDate(date1); summary.addDate(null); assertEquals(date, summary.getStartDate()); assertEquals(date, summary.getEndDate()); } }
UTF-8
Java
1,921
java
ValidTransactionsSummaryTest.java
Java
[]
null
[]
package com.lumatax.salesanalyzer.model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import java.math.BigDecimal; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @RunWith(MockitoJUnitRunner.class) class ValidTransactionsSummaryTest { private ValidTransactionsSummary summary; @BeforeEach void setUp() { summary = new ValidTransactionsSummary(); } @Test void addSale() { assertEquals(0, summary.getTotalSales().intValue()); summary.addSale(new BigDecimal(100)); summary.addSale(new BigDecimal(500)); summary.addTax(null); assertEquals(600, summary.getTotalSales().intValue()); } @Test void addTax() { assertEquals(0, summary.getTotalTax().intValue()); summary.addTax(new BigDecimal(200)); summary.addTax(new BigDecimal(500)); summary.addTax(null); assertEquals(700, summary.getTotalTax().intValue()); } @Test void addDate() { assertNull(summary.getStartDate()); assertNull(summary.getEndDate()); LocalDate end = LocalDate.of(2020, 10, 20); LocalDate middle = LocalDate.of(1990, 1, 2); LocalDate start = LocalDate.of(1700, 5, 11); summary.addDate(end); summary.addDate(start); summary.addDate(middle); assertEquals(start, summary.getStartDate()); assertEquals(end, summary.getEndDate()); } @Test void addDate_SameDates() { assertNull(summary.getStartDate()); assertNull(summary.getEndDate()); LocalDate date = LocalDate.of(2020, 10, 20); LocalDate date1 = LocalDate.of(2020, 10, 20); LocalDate date2 = LocalDate.of(2020, 10, 20); summary.addDate(date); summary.addDate(date2); summary.addDate(date1); summary.addDate(null); assertEquals(date, summary.getStartDate()); assertEquals(date, summary.getEndDate()); } }
1,921
0.739719
0.7038
80
23.025
19.419046
60
false
false
0
0
0
0
0
0
1.775
false
false
13
d3c59612a24556b63840a8d3db2260565eadf22c
38,285,338,509,574
7bac258a6a9122e7f5f8c5c2cfa70c428e55aca9
/src/problem_115/Solution.java
671fd597cb6eb341852a7c28137d60961b79d2a1
[]
no_license
lindanpeng/leetcode
https://github.com/lindanpeng/leetcode
bc886690ed6ee68bb21a0e05e680eca52abde859
a7ec3698193649d16857c4d0c486657c8469754e
refs/heads/master
2020-04-07T01:58:32.305000
2018-11-17T07:19:08
2018-11-17T07:19:08
157,959,323
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package problem_115; public class Solution { // public int numDistinct(String s, String t) { // numDistinct(s,t,0,0); // } // private int[][] sign=new int[1000][1000]; // private int numDistinct(String s,String t,int cur,int k ){ // if (sign[cur][k]!=-1){ // return sign[cur][k]; // } // if (k>=t.length()){ // sign[cur][k]=1; // for (int i=cur;i<s.length();i++) // return 1; // } // int cnt=0; // for (int i=cur;i<s.length();i++){ // if (s.charAt(i)==t.charAt(k)){ // cnt+=numDistinct(s,t,i+1,k+1); // } // } // return cnt; // } // // public static void main(String[] args) { // int n=new Solution().numDistinct("rabbbit","rabbit"); // System.out.println(n); // } }
UTF-8
Java
851
java
Solution.java
Java
[]
null
[]
package problem_115; public class Solution { // public int numDistinct(String s, String t) { // numDistinct(s,t,0,0); // } // private int[][] sign=new int[1000][1000]; // private int numDistinct(String s,String t,int cur,int k ){ // if (sign[cur][k]!=-1){ // return sign[cur][k]; // } // if (k>=t.length()){ // sign[cur][k]=1; // for (int i=cur;i<s.length();i++) // return 1; // } // int cnt=0; // for (int i=cur;i<s.length();i++){ // if (s.charAt(i)==t.charAt(k)){ // cnt+=numDistinct(s,t,i+1,k+1); // } // } // return cnt; // } // // public static void main(String[] args) { // int n=new Solution().numDistinct("rabbbit","rabbit"); // System.out.println(n); // } }
851
0.454759
0.432432
30
27.366667
18.05267
64
false
false
0
0
0
0
0
0
0.866667
false
false
13
53554dcead2803e715a30c3c8d2a281ae089ee15
9,388,798,539,076
dc32c176c3d970daf097aa5556ece94463bfdcdb
/gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/MatchStepTest.java
9b204cf28574c083178c08afdabfa3168c77601c
[ "Apache-2.0", "MIT" ]
permissive
apache/tinkerpop
https://github.com/apache/tinkerpop
6469dba91aaef87695f12b4a23b89afdc0021320
397eff08f73ae555bd3aab87498b9ff131792741
refs/heads/master
2023-09-05T13:29:53.428000
2023-08-31T21:13:43
2023-08-31T21:13:43
30,449,481
1,758
851
Apache-2.0
false
2023-09-13T14:46:55
2015-02-07T08:00:05
2023-09-12T09:02:15
2023-09-13T14:46:47
208,769
1,819
771
27
Java
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop.gremlin.process.traversal.step.map; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.process.traversal.step.StepTest; import org.apache.tinkerpop.gremlin.process.traversal.step.filter.CoinStep; import org.apache.tinkerpop.gremlin.process.traversal.step.filter.ConnectiveStep; import org.apache.tinkerpop.gremlin.process.traversal.step.filter.WherePredicateStep; import org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTraversalStep; import org.apache.tinkerpop.gremlin.process.traversal.step.util.EmptyStep; import org.apache.tinkerpop.gremlin.process.traversal.traverser.B_LP_O_P_S_SE_SL_TraverserGenerator; import org.apache.tinkerpop.gremlin.process.traversal.traverser.util.EmptyTraverser; import org.apache.tinkerpop.gremlin.structure.T; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.function.Consumer; import static org.apache.tinkerpop.gremlin.process.traversal.P.eq; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.and; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.as; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.in; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.match; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.or; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.out; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.where; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class MatchStepTest extends StepTest { @Override protected List<Traversal> getTraversals() { return Arrays.asList( __.match(as("a").out("knows").as("b")), __.match(as("a").out().as("b")), //// __.match(where(as("a").out("knows").as("b"))), __.match(as("a").where(out().as("b"))), /// match(__.as("a").out().as("b"), __.as("b").out().as("c")), match(__.as("b").out().as("c"), __.as("a").out().as("d")) ); } @Test public void testPreCompilationOfStartAndEnds() { final Traversal.Admin<?, ?> traversal = __.match(as("a").out().as("b"), as("c").path().as("d")).asAdmin(); final MatchStep<?, ?> matchStep = (MatchStep<?, ?>) traversal.getStartStep(); assertEquals(MatchStep.class, traversal.getStartStep().getClass()); assertEquals(2, matchStep.getGlobalChildren().size()); Traversal.Admin<Object, Object> pattern = matchStep.getGlobalChildren().get(0); assertEquals("a", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(VertexStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("b", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); // pattern = matchStep.getGlobalChildren().get(1); assertEquals("c", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(PathStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("d", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); } @Test public void testPreCompilationOfOr() { final List<Traversal.Admin<?, ?>> traversals = Arrays.asList( __.match(as("a").out().as("b"), or(as("c").path().as("d"), as("e").coin(0.5).as("f"))).asAdmin(), __.match(as("a").out().as("b"), as("c").path().as("d").or().as("e").coin(0.5).as("f")).asAdmin()); assertEquals(1, new HashSet<>(traversals).size()); // the two patterns should pre-compile to the same traversal traversals.forEach(traversal -> { final MatchStep<?, ?> matchStep = (MatchStep<?, ?>) traversal.getStartStep(); assertEquals(2, matchStep.getGlobalChildren().size()); Traversal.Admin<Object, Object> pattern = matchStep.getGlobalChildren().get(0); assertEquals("a", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(VertexStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("b", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); // pattern = matchStep.getGlobalChildren().get(1); assertEquals(MatchStep.class, pattern.getStartStep().getClass()); assertEquals(ConnectiveStep.Connective.OR, ((MatchStep<?, ?>) pattern.getStartStep()).getConnective()); assertEquals("c", ((MatchStep.MatchStartStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getStartStep()).getSelectKey().get()); assertEquals(PathStep.class, ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getStartStep().getNextStep().getClass()); assertEquals("d", ((MatchStep.MatchEndStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getEndStep()).getMatchKey().get()); assertEquals("e", ((MatchStep.MatchStartStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getStartStep()).getSelectKey().get()); assertEquals(CoinStep.class, ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getStartStep().getNextStep().getClass()); assertEquals("f", ((MatchStep.MatchEndStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getEndStep()).getMatchKey().get()); }); } @Test public void testPreCompilationOfAnd() { final List<Traversal.Admin<?, ?>> traversals = Arrays.asList( __.match(as("a").out().as("b"), and(as("c").path().as("d"), as("e").barrier())).asAdmin(), __.match(as("a").out().as("b"), as("c").path().as("d").and().as("e").barrier()).asAdmin()); assertEquals(1, new HashSet<>(traversals).size()); // the two patterns should pre-compile to the same traversal traversals.forEach(traversal -> { final MatchStep<?, ?> matchStep = (MatchStep<?, ?>) traversal.getStartStep(); assertEquals(2, matchStep.getGlobalChildren().size()); Traversal.Admin<Object, Object> pattern = matchStep.getGlobalChildren().get(0); assertEquals("a", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(VertexStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("b", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); // pattern = matchStep.getGlobalChildren().get(1); assertEquals(MatchStep.class, pattern.getStartStep().getClass()); assertEquals(ConnectiveStep.Connective.AND, ((MatchStep<?, ?>) pattern.getStartStep()).getConnective()); assertEquals("c", ((MatchStep.MatchStartStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getStartStep()).getSelectKey().get()); assertEquals(PathStep.class, ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getStartStep().getNextStep().getClass()); assertEquals("d", ((MatchStep.MatchEndStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getEndStep()).getMatchKey().get()); assertEquals("e", ((MatchStep.MatchStartStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getStartStep()).getSelectKey().get()); assertEquals(NoOpBarrierStep.class, ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getStartStep().getNextStep().getClass()); assertFalse(((MatchStep.MatchEndStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getEndStep()).getMatchKey().isPresent()); }); } @Test public void testPreCompilationOfWhereTraversal() { final List<Traversal.Admin<?, ?>> traversals = Arrays.asList( __.match(as("a").out().as("b"), as("c").where(in().as("d"))).asAdmin(), __.match(as("a").out().as("b"), where(as("c").in().as("d"))).asAdmin()); assertEquals(1, new HashSet<>(traversals).size()); // the two patterns should pre-compile to the same traversal traversals.forEach(traversal -> { final MatchStep<?, ?> matchStep = (MatchStep<?, ?>) traversal.getStartStep(); //assertFalse(matchStep.getStartLabel().isPresent()); assertEquals(2, matchStep.getGlobalChildren().size()); Traversal.Admin<Object, Object> pattern = matchStep.getGlobalChildren().get(0); assertEquals("a", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(VertexStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("b", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); // pattern = matchStep.getGlobalChildren().get(1); assertEquals(MatchStep.MatchStartStep.class, pattern.getStartStep().getClass()); assertEquals("c", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(WhereTraversalStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals(MatchStep.MatchEndStep.class, pattern.getStartStep().getNextStep().getNextStep().getClass()); assertEquals(1, ((WhereTraversalStep<?>) pattern.getStartStep().getNextStep()).getLocalChildren().size()); Traversal.Admin<?, ?> whereTraversal = ((WhereTraversalStep<?>) pattern.getStartStep().getNextStep()).getLocalChildren().get(0); assertEquals(WhereTraversalStep.WhereStartStep.class, whereTraversal.getStartStep().getClass()); assertTrue(((WhereTraversalStep.WhereStartStep) whereTraversal.getStartStep()).getScopeKeys().isEmpty()); assertEquals(VertexStep.class, whereTraversal.getStartStep().getNextStep().getClass()); assertEquals(WhereTraversalStep.WhereEndStep.class, whereTraversal.getStartStep().getNextStep().getNextStep().getClass()); assertEquals(1, ((WhereTraversalStep.WhereEndStep) whereTraversal.getStartStep().getNextStep().getNextStep()).getScopeKeys().size()); assertEquals("d", ((WhereTraversalStep.WhereEndStep) whereTraversal.getStartStep().getNextStep().getNextStep()).getScopeKeys().iterator().next()); }); } @Test public void testPreCompilationOfWherePredicate() { final List<Traversal.Admin<?, ?>> traversals = Arrays.asList( __.match(as("a").out().as("b"), as("c").where(P.neq("d"))).asAdmin(), __.match(as("a").out().as("b"), where("c", P.neq("d"))).asAdmin()); assertEquals(1, new HashSet<>(traversals).size()); // the two patterns should pre-compile to the same traversal traversals.forEach(traversal -> { final MatchStep<?, ?> matchStep = (MatchStep<?, ?>) traversal.getStartStep(); //assertFalse(matchStep.getStartLabel().isPresent()); assertEquals(2, matchStep.getGlobalChildren().size()); Traversal.Admin<Object, Object> pattern = matchStep.getGlobalChildren().get(0); assertEquals("a", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(VertexStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("b", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); // pattern = matchStep.getGlobalChildren().get(1); assertEquals(MatchStep.MatchStartStep.class, pattern.getStartStep().getClass()); assertEquals("c", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(WherePredicateStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals(MatchStep.MatchEndStep.class, pattern.getStartStep().getNextStep().getNextStep().getClass()); assertFalse(((WherePredicateStep<?>) pattern.getStartStep().getNextStep()).getStartKey().isPresent()); assertEquals("d", ((WherePredicateStep<?>) pattern.getStartStep().getNextStep()).getPredicate().get().getOriginalValue()); }); } @Test public void testCountMatchAlgorithm() { // MAKE SURE THE SORT ORDER CHANGES AS MORE RESULTS ARE RETURNED BY ONE OR THE OTHER TRAVERSAL Traversal.Admin<?, ?> traversal = __.match(as("a").out().as("b"), as("c").in().as("d")).asAdmin(); MatchStep.CountMatchAlgorithm countMatchAlgorithm = new MatchStep.CountMatchAlgorithm(); countMatchAlgorithm.initialize(false, ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren()); Traversal.Admin<Object, Object> firstPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(0); Traversal.Admin<Object, Object> secondPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(1); // assertEquals(2, countMatchAlgorithm.bundles.size()); countMatchAlgorithm.bundles.stream().forEach(bundle -> assertEquals(0.0d, bundle.multiplicity, 0.0d)); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), firstPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), firstPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(firstPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(secondPattern).traversalType); assertEquals(2l, countMatchAlgorithm.getBundle(firstPattern).startsCount); assertEquals(3l, countMatchAlgorithm.getBundle(secondPattern).startsCount); assertEquals(0l, countMatchAlgorithm.getBundle(firstPattern).endsCount); assertEquals(0l, countMatchAlgorithm.getBundle(secondPattern).endsCount); //// countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), firstPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); assertEquals(2l, countMatchAlgorithm.getBundle(firstPattern).startsCount); assertEquals(3l, countMatchAlgorithm.getBundle(secondPattern).startsCount); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).endsCount); assertEquals(3l, countMatchAlgorithm.getBundle(secondPattern).endsCount); assertEquals(0.5d, countMatchAlgorithm.getBundle(firstPattern).multiplicity, 0.01d); assertEquals(1.0d, countMatchAlgorithm.getBundle(secondPattern).multiplicity, 0.01d); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); // CHECK RE-SORTING AS MORE DATA COMES IN countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), firstPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), firstPattern); assertEquals(1.5d, countMatchAlgorithm.getBundle(firstPattern).multiplicity, 0.01d); assertEquals(1.0d, countMatchAlgorithm.getBundle(secondPattern).multiplicity, 0.01d); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(1).traversal); /////// MAKE SURE WHERE PREDICATE TRAVERSALS ARE ALWAYS FIRST AS THEY ARE SIMPLY .hasNext() CHECKS traversal = __.match(as("a").out().as("b"), as("c").in().as("d"), where("a", P.eq("b"))).asAdmin(); countMatchAlgorithm = new MatchStep.CountMatchAlgorithm(); countMatchAlgorithm.initialize(false, ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren()); assertEquals(3, countMatchAlgorithm.bundles.size()); firstPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(0); secondPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(1); Traversal.Admin<Object, Object> thirdPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(2); /// countMatchAlgorithm.bundles.stream().forEach(bundle -> assertEquals(0.0d, bundle.multiplicity, 0.0d)); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(firstPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(secondPattern).traversalType); assertEquals(MatchStep.TraversalType.WHERE_PREDICATE, countMatchAlgorithm.getBundle(thirdPattern).traversalType); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(thirdPattern, countMatchAlgorithm.bundles.get(2).traversal); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), firstPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), firstPattern); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).startsCount); assertEquals(0l, countMatchAlgorithm.getBundle(secondPattern).startsCount); assertEquals(0l, countMatchAlgorithm.getBundle(thirdPattern).startsCount); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).endsCount); assertEquals(0l, countMatchAlgorithm.getBundle(secondPattern).endsCount); assertEquals(0l, countMatchAlgorithm.getBundle(thirdPattern).endsCount); assertEquals(1.0d, countMatchAlgorithm.getBundle(firstPattern).multiplicity, 0.01d); assertEquals(0.0d, countMatchAlgorithm.getBundle(secondPattern).multiplicity, 0.01d); assertEquals(0.0d, countMatchAlgorithm.getBundle(thirdPattern).multiplicity, 0.01d); assertEquals(thirdPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(2).traversal); // countMatchAlgorithm.recordStart(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).startsCount); assertEquals(0l, countMatchAlgorithm.getBundle(secondPattern).startsCount); assertEquals(3l, countMatchAlgorithm.getBundle(thirdPattern).startsCount); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).endsCount); assertEquals(0l, countMatchAlgorithm.getBundle(secondPattern).endsCount); assertEquals(6l, countMatchAlgorithm.getBundle(thirdPattern).endsCount); assertEquals(1.0d, countMatchAlgorithm.getBundle(firstPattern).multiplicity, 0.01d); assertEquals(0.0d, countMatchAlgorithm.getBundle(secondPattern).multiplicity, 0.01d); assertEquals(2.0d, countMatchAlgorithm.getBundle(thirdPattern).multiplicity, 0.01d); assertEquals(thirdPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(2).traversal); // countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).startsCount); assertEquals(4l, countMatchAlgorithm.getBundle(secondPattern).startsCount); assertEquals(3l, countMatchAlgorithm.getBundle(thirdPattern).startsCount); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).endsCount); assertEquals(6l, countMatchAlgorithm.getBundle(secondPattern).endsCount); assertEquals(6l, countMatchAlgorithm.getBundle(thirdPattern).endsCount); assertEquals(1.0d, countMatchAlgorithm.getBundle(firstPattern).multiplicity, 0.01d); assertEquals(1.5d, countMatchAlgorithm.getBundle(secondPattern).multiplicity, 0.01d); assertEquals(2.0d, countMatchAlgorithm.getBundle(thirdPattern).multiplicity, 0.01d); assertEquals(thirdPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(2).traversal); } @Test public void testComputerAwareCountMatchAlgorithm() { // MAKE SURE OLAP JOBS ARE BIASED TOWARDS STAR GRAPH DATA final Consumer doNothing = s -> { }; final Traversal.Admin<?, ?> traversal = __.match( as("a").sideEffect(doNothing).as("b"), // 1 as("b").sideEffect(doNothing).as("c"), // 2 as("a").sideEffect(doNothing).as("d"), // 5 as("c").sideEffect(doNothing).as("e"), // 4 as("c").sideEffect(doNothing).as("f")) // 3 .asAdmin(); traversal.applyStrategies(); // necessary to enure step ids are unique final MatchStep.CountMatchAlgorithm countMatchAlgorithm = new MatchStep.CountMatchAlgorithm(); countMatchAlgorithm.initialize(true, ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren()); Traversal.Admin<Object, Object> firstPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(0); Traversal.Admin<Object, Object> secondPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(1); Traversal.Admin<Object, Object> thirdPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(2); Traversal.Admin<Object, Object> forthPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(3); Traversal.Admin<Object, Object> fifthPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(4); countMatchAlgorithm.bundles.stream().forEach(bundle -> assertEquals(0.0d, bundle.multiplicity, 0.0d)); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(firstPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(secondPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(thirdPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(forthPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(fifthPattern).traversalType); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(thirdPattern, countMatchAlgorithm.bundles.get(2).traversal); assertEquals(forthPattern, countMatchAlgorithm.bundles.get(3).traversal); assertEquals(fifthPattern, countMatchAlgorithm.bundles.get(4).traversal); // MAKE THE SECOND PATTERN EXPENSIVE countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); // MAKE THE THIRD PATTERN MORE EXPENSIVE THAN FORTH countMatchAlgorithm.recordStart(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); // MAKE THE FORTH PATTERN EXPENSIVE countMatchAlgorithm.recordStart(EmptyTraverser.instance(), forthPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), forthPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), forthPattern); // Traverser.Admin traverser = B_LP_O_P_S_SE_SL_TraverserGenerator.instance().generate(1, EmptyStep.instance(), 1l); traverser.addLabels(Collections.singleton("a")); assertEquals(firstPattern, countMatchAlgorithm.apply(traverser)); traverser = traverser.split(1, EmptyStep.instance()); traverser.getTags().add(firstPattern.getStartStep().getId()); traverser.addLabels(Collections.singleton("b")); // assertEquals(secondPattern, countMatchAlgorithm.apply(traverser)); traverser = traverser.split(1, EmptyStep.instance()); traverser.getTags().add(secondPattern.getStartStep().getId()); traverser.addLabels(Collections.singleton("c")); // assertEquals(fifthPattern, countMatchAlgorithm.apply(traverser)); traverser = traverser.split(1, EmptyStep.instance()); traverser.getTags().add(fifthPattern.getStartStep().getId()); traverser.addLabels(Collections.singleton("f")); // assertEquals(forthPattern, countMatchAlgorithm.apply(traverser)); traverser = traverser.split(1, EmptyStep.instance()); traverser.getTags().add(forthPattern.getStartStep().getId()); traverser.addLabels(Collections.singleton("e")); // assertEquals(thirdPattern, countMatchAlgorithm.apply(traverser)); traverser = traverser.split(1, EmptyStep.instance()); traverser.getTags().add(thirdPattern.getStartStep().getId()); traverser.addLabels(Collections.singleton("d")); } @Test public void shouldCalculateStartLabelCorrectly() { Traversal.Admin<?, ?> traversal = match( where(and( as("a").out("created").as("b"), as("b").in("created").count().is(eq(3)))), as("a").both().as("b"), where(as("b").in())).asAdmin(); assertEquals("a", MatchStep.Helper.computeStartLabel(((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren())); ///// traversal = match( where("a", P.neq("c")), as("a").out("created").as("b"), or( as("a").out("knows").has("name", "vadas"), as("a").in("knows").and().as("a").has(T.label, "person") ), as("b").in("created").as("c"), as("b").in("created").count().is(P.gt(1))).asAdmin(); assertEquals("a", MatchStep.Helper.computeStartLabel(((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren())); } }
UTF-8
Java
30,291
java
MatchStepTest.java
Java
[ { "context": "tatic org.junit.Assert.assertTrue;\n\n/**\n * @author Marko A. Rodriguez (http://markorodriguez.com)\n */\npublic class Matc", "end": 2788, "score": 0.9998774528503418, "start": 2770, "tag": "NAME", "value": "Marko A. Rodriguez" }, { "context": " as(\"a\").out(\"knows\").has(\"name\", \"vadas\"),\n as(\"a\").in(\"knows\").an", "end": 29932, "score": 0.9995070099830627, "start": 29927, "tag": "NAME", "value": "vadas" } ]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop.gremlin.process.traversal.step.map; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.process.traversal.step.StepTest; import org.apache.tinkerpop.gremlin.process.traversal.step.filter.CoinStep; import org.apache.tinkerpop.gremlin.process.traversal.step.filter.ConnectiveStep; import org.apache.tinkerpop.gremlin.process.traversal.step.filter.WherePredicateStep; import org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTraversalStep; import org.apache.tinkerpop.gremlin.process.traversal.step.util.EmptyStep; import org.apache.tinkerpop.gremlin.process.traversal.traverser.B_LP_O_P_S_SE_SL_TraverserGenerator; import org.apache.tinkerpop.gremlin.process.traversal.traverser.util.EmptyTraverser; import org.apache.tinkerpop.gremlin.structure.T; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.function.Consumer; import static org.apache.tinkerpop.gremlin.process.traversal.P.eq; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.and; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.as; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.in; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.match; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.or; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.out; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.where; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author <NAME> (http://markorodriguez.com) */ public class MatchStepTest extends StepTest { @Override protected List<Traversal> getTraversals() { return Arrays.asList( __.match(as("a").out("knows").as("b")), __.match(as("a").out().as("b")), //// __.match(where(as("a").out("knows").as("b"))), __.match(as("a").where(out().as("b"))), /// match(__.as("a").out().as("b"), __.as("b").out().as("c")), match(__.as("b").out().as("c"), __.as("a").out().as("d")) ); } @Test public void testPreCompilationOfStartAndEnds() { final Traversal.Admin<?, ?> traversal = __.match(as("a").out().as("b"), as("c").path().as("d")).asAdmin(); final MatchStep<?, ?> matchStep = (MatchStep<?, ?>) traversal.getStartStep(); assertEquals(MatchStep.class, traversal.getStartStep().getClass()); assertEquals(2, matchStep.getGlobalChildren().size()); Traversal.Admin<Object, Object> pattern = matchStep.getGlobalChildren().get(0); assertEquals("a", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(VertexStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("b", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); // pattern = matchStep.getGlobalChildren().get(1); assertEquals("c", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(PathStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("d", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); } @Test public void testPreCompilationOfOr() { final List<Traversal.Admin<?, ?>> traversals = Arrays.asList( __.match(as("a").out().as("b"), or(as("c").path().as("d"), as("e").coin(0.5).as("f"))).asAdmin(), __.match(as("a").out().as("b"), as("c").path().as("d").or().as("e").coin(0.5).as("f")).asAdmin()); assertEquals(1, new HashSet<>(traversals).size()); // the two patterns should pre-compile to the same traversal traversals.forEach(traversal -> { final MatchStep<?, ?> matchStep = (MatchStep<?, ?>) traversal.getStartStep(); assertEquals(2, matchStep.getGlobalChildren().size()); Traversal.Admin<Object, Object> pattern = matchStep.getGlobalChildren().get(0); assertEquals("a", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(VertexStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("b", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); // pattern = matchStep.getGlobalChildren().get(1); assertEquals(MatchStep.class, pattern.getStartStep().getClass()); assertEquals(ConnectiveStep.Connective.OR, ((MatchStep<?, ?>) pattern.getStartStep()).getConnective()); assertEquals("c", ((MatchStep.MatchStartStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getStartStep()).getSelectKey().get()); assertEquals(PathStep.class, ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getStartStep().getNextStep().getClass()); assertEquals("d", ((MatchStep.MatchEndStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getEndStep()).getMatchKey().get()); assertEquals("e", ((MatchStep.MatchStartStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getStartStep()).getSelectKey().get()); assertEquals(CoinStep.class, ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getStartStep().getNextStep().getClass()); assertEquals("f", ((MatchStep.MatchEndStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getEndStep()).getMatchKey().get()); }); } @Test public void testPreCompilationOfAnd() { final List<Traversal.Admin<?, ?>> traversals = Arrays.asList( __.match(as("a").out().as("b"), and(as("c").path().as("d"), as("e").barrier())).asAdmin(), __.match(as("a").out().as("b"), as("c").path().as("d").and().as("e").barrier()).asAdmin()); assertEquals(1, new HashSet<>(traversals).size()); // the two patterns should pre-compile to the same traversal traversals.forEach(traversal -> { final MatchStep<?, ?> matchStep = (MatchStep<?, ?>) traversal.getStartStep(); assertEquals(2, matchStep.getGlobalChildren().size()); Traversal.Admin<Object, Object> pattern = matchStep.getGlobalChildren().get(0); assertEquals("a", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(VertexStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("b", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); // pattern = matchStep.getGlobalChildren().get(1); assertEquals(MatchStep.class, pattern.getStartStep().getClass()); assertEquals(ConnectiveStep.Connective.AND, ((MatchStep<?, ?>) pattern.getStartStep()).getConnective()); assertEquals("c", ((MatchStep.MatchStartStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getStartStep()).getSelectKey().get()); assertEquals(PathStep.class, ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getStartStep().getNextStep().getClass()); assertEquals("d", ((MatchStep.MatchEndStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(0).getEndStep()).getMatchKey().get()); assertEquals("e", ((MatchStep.MatchStartStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getStartStep()).getSelectKey().get()); assertEquals(NoOpBarrierStep.class, ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getStartStep().getNextStep().getClass()); assertFalse(((MatchStep.MatchEndStep) ((MatchStep<?, ?>) pattern.getStartStep()).getGlobalChildren().get(1).getEndStep()).getMatchKey().isPresent()); }); } @Test public void testPreCompilationOfWhereTraversal() { final List<Traversal.Admin<?, ?>> traversals = Arrays.asList( __.match(as("a").out().as("b"), as("c").where(in().as("d"))).asAdmin(), __.match(as("a").out().as("b"), where(as("c").in().as("d"))).asAdmin()); assertEquals(1, new HashSet<>(traversals).size()); // the two patterns should pre-compile to the same traversal traversals.forEach(traversal -> { final MatchStep<?, ?> matchStep = (MatchStep<?, ?>) traversal.getStartStep(); //assertFalse(matchStep.getStartLabel().isPresent()); assertEquals(2, matchStep.getGlobalChildren().size()); Traversal.Admin<Object, Object> pattern = matchStep.getGlobalChildren().get(0); assertEquals("a", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(VertexStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("b", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); // pattern = matchStep.getGlobalChildren().get(1); assertEquals(MatchStep.MatchStartStep.class, pattern.getStartStep().getClass()); assertEquals("c", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(WhereTraversalStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals(MatchStep.MatchEndStep.class, pattern.getStartStep().getNextStep().getNextStep().getClass()); assertEquals(1, ((WhereTraversalStep<?>) pattern.getStartStep().getNextStep()).getLocalChildren().size()); Traversal.Admin<?, ?> whereTraversal = ((WhereTraversalStep<?>) pattern.getStartStep().getNextStep()).getLocalChildren().get(0); assertEquals(WhereTraversalStep.WhereStartStep.class, whereTraversal.getStartStep().getClass()); assertTrue(((WhereTraversalStep.WhereStartStep) whereTraversal.getStartStep()).getScopeKeys().isEmpty()); assertEquals(VertexStep.class, whereTraversal.getStartStep().getNextStep().getClass()); assertEquals(WhereTraversalStep.WhereEndStep.class, whereTraversal.getStartStep().getNextStep().getNextStep().getClass()); assertEquals(1, ((WhereTraversalStep.WhereEndStep) whereTraversal.getStartStep().getNextStep().getNextStep()).getScopeKeys().size()); assertEquals("d", ((WhereTraversalStep.WhereEndStep) whereTraversal.getStartStep().getNextStep().getNextStep()).getScopeKeys().iterator().next()); }); } @Test public void testPreCompilationOfWherePredicate() { final List<Traversal.Admin<?, ?>> traversals = Arrays.asList( __.match(as("a").out().as("b"), as("c").where(P.neq("d"))).asAdmin(), __.match(as("a").out().as("b"), where("c", P.neq("d"))).asAdmin()); assertEquals(1, new HashSet<>(traversals).size()); // the two patterns should pre-compile to the same traversal traversals.forEach(traversal -> { final MatchStep<?, ?> matchStep = (MatchStep<?, ?>) traversal.getStartStep(); //assertFalse(matchStep.getStartLabel().isPresent()); assertEquals(2, matchStep.getGlobalChildren().size()); Traversal.Admin<Object, Object> pattern = matchStep.getGlobalChildren().get(0); assertEquals("a", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(VertexStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals("b", ((MatchStep.MatchEndStep) pattern.getEndStep()).getMatchKey().get()); // pattern = matchStep.getGlobalChildren().get(1); assertEquals(MatchStep.MatchStartStep.class, pattern.getStartStep().getClass()); assertEquals("c", ((MatchStep.MatchStartStep) pattern.getStartStep()).getSelectKey().get()); assertEquals(WherePredicateStep.class, pattern.getStartStep().getNextStep().getClass()); assertEquals(MatchStep.MatchEndStep.class, pattern.getStartStep().getNextStep().getNextStep().getClass()); assertFalse(((WherePredicateStep<?>) pattern.getStartStep().getNextStep()).getStartKey().isPresent()); assertEquals("d", ((WherePredicateStep<?>) pattern.getStartStep().getNextStep()).getPredicate().get().getOriginalValue()); }); } @Test public void testCountMatchAlgorithm() { // MAKE SURE THE SORT ORDER CHANGES AS MORE RESULTS ARE RETURNED BY ONE OR THE OTHER TRAVERSAL Traversal.Admin<?, ?> traversal = __.match(as("a").out().as("b"), as("c").in().as("d")).asAdmin(); MatchStep.CountMatchAlgorithm countMatchAlgorithm = new MatchStep.CountMatchAlgorithm(); countMatchAlgorithm.initialize(false, ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren()); Traversal.Admin<Object, Object> firstPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(0); Traversal.Admin<Object, Object> secondPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(1); // assertEquals(2, countMatchAlgorithm.bundles.size()); countMatchAlgorithm.bundles.stream().forEach(bundle -> assertEquals(0.0d, bundle.multiplicity, 0.0d)); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), firstPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), firstPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(firstPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(secondPattern).traversalType); assertEquals(2l, countMatchAlgorithm.getBundle(firstPattern).startsCount); assertEquals(3l, countMatchAlgorithm.getBundle(secondPattern).startsCount); assertEquals(0l, countMatchAlgorithm.getBundle(firstPattern).endsCount); assertEquals(0l, countMatchAlgorithm.getBundle(secondPattern).endsCount); //// countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), firstPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); assertEquals(2l, countMatchAlgorithm.getBundle(firstPattern).startsCount); assertEquals(3l, countMatchAlgorithm.getBundle(secondPattern).startsCount); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).endsCount); assertEquals(3l, countMatchAlgorithm.getBundle(secondPattern).endsCount); assertEquals(0.5d, countMatchAlgorithm.getBundle(firstPattern).multiplicity, 0.01d); assertEquals(1.0d, countMatchAlgorithm.getBundle(secondPattern).multiplicity, 0.01d); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); // CHECK RE-SORTING AS MORE DATA COMES IN countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), firstPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), firstPattern); assertEquals(1.5d, countMatchAlgorithm.getBundle(firstPattern).multiplicity, 0.01d); assertEquals(1.0d, countMatchAlgorithm.getBundle(secondPattern).multiplicity, 0.01d); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(1).traversal); /////// MAKE SURE WHERE PREDICATE TRAVERSALS ARE ALWAYS FIRST AS THEY ARE SIMPLY .hasNext() CHECKS traversal = __.match(as("a").out().as("b"), as("c").in().as("d"), where("a", P.eq("b"))).asAdmin(); countMatchAlgorithm = new MatchStep.CountMatchAlgorithm(); countMatchAlgorithm.initialize(false, ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren()); assertEquals(3, countMatchAlgorithm.bundles.size()); firstPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(0); secondPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(1); Traversal.Admin<Object, Object> thirdPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(2); /// countMatchAlgorithm.bundles.stream().forEach(bundle -> assertEquals(0.0d, bundle.multiplicity, 0.0d)); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(firstPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(secondPattern).traversalType); assertEquals(MatchStep.TraversalType.WHERE_PREDICATE, countMatchAlgorithm.getBundle(thirdPattern).traversalType); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(thirdPattern, countMatchAlgorithm.bundles.get(2).traversal); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), firstPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), firstPattern); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).startsCount); assertEquals(0l, countMatchAlgorithm.getBundle(secondPattern).startsCount); assertEquals(0l, countMatchAlgorithm.getBundle(thirdPattern).startsCount); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).endsCount); assertEquals(0l, countMatchAlgorithm.getBundle(secondPattern).endsCount); assertEquals(0l, countMatchAlgorithm.getBundle(thirdPattern).endsCount); assertEquals(1.0d, countMatchAlgorithm.getBundle(firstPattern).multiplicity, 0.01d); assertEquals(0.0d, countMatchAlgorithm.getBundle(secondPattern).multiplicity, 0.01d); assertEquals(0.0d, countMatchAlgorithm.getBundle(thirdPattern).multiplicity, 0.01d); assertEquals(thirdPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(2).traversal); // countMatchAlgorithm.recordStart(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).startsCount); assertEquals(0l, countMatchAlgorithm.getBundle(secondPattern).startsCount); assertEquals(3l, countMatchAlgorithm.getBundle(thirdPattern).startsCount); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).endsCount); assertEquals(0l, countMatchAlgorithm.getBundle(secondPattern).endsCount); assertEquals(6l, countMatchAlgorithm.getBundle(thirdPattern).endsCount); assertEquals(1.0d, countMatchAlgorithm.getBundle(firstPattern).multiplicity, 0.01d); assertEquals(0.0d, countMatchAlgorithm.getBundle(secondPattern).multiplicity, 0.01d); assertEquals(2.0d, countMatchAlgorithm.getBundle(thirdPattern).multiplicity, 0.01d); assertEquals(thirdPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(2).traversal); // countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).startsCount); assertEquals(4l, countMatchAlgorithm.getBundle(secondPattern).startsCount); assertEquals(3l, countMatchAlgorithm.getBundle(thirdPattern).startsCount); assertEquals(1l, countMatchAlgorithm.getBundle(firstPattern).endsCount); assertEquals(6l, countMatchAlgorithm.getBundle(secondPattern).endsCount); assertEquals(6l, countMatchAlgorithm.getBundle(thirdPattern).endsCount); assertEquals(1.0d, countMatchAlgorithm.getBundle(firstPattern).multiplicity, 0.01d); assertEquals(1.5d, countMatchAlgorithm.getBundle(secondPattern).multiplicity, 0.01d); assertEquals(2.0d, countMatchAlgorithm.getBundle(thirdPattern).multiplicity, 0.01d); assertEquals(thirdPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(2).traversal); } @Test public void testComputerAwareCountMatchAlgorithm() { // MAKE SURE OLAP JOBS ARE BIASED TOWARDS STAR GRAPH DATA final Consumer doNothing = s -> { }; final Traversal.Admin<?, ?> traversal = __.match( as("a").sideEffect(doNothing).as("b"), // 1 as("b").sideEffect(doNothing).as("c"), // 2 as("a").sideEffect(doNothing).as("d"), // 5 as("c").sideEffect(doNothing).as("e"), // 4 as("c").sideEffect(doNothing).as("f")) // 3 .asAdmin(); traversal.applyStrategies(); // necessary to enure step ids are unique final MatchStep.CountMatchAlgorithm countMatchAlgorithm = new MatchStep.CountMatchAlgorithm(); countMatchAlgorithm.initialize(true, ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren()); Traversal.Admin<Object, Object> firstPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(0); Traversal.Admin<Object, Object> secondPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(1); Traversal.Admin<Object, Object> thirdPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(2); Traversal.Admin<Object, Object> forthPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(3); Traversal.Admin<Object, Object> fifthPattern = ((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren().get(4); countMatchAlgorithm.bundles.stream().forEach(bundle -> assertEquals(0.0d, bundle.multiplicity, 0.0d)); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(firstPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(secondPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(thirdPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(forthPattern).traversalType); assertEquals(MatchStep.TraversalType.MATCH_TRAVERSAL, countMatchAlgorithm.getBundle(fifthPattern).traversalType); assertEquals(firstPattern, countMatchAlgorithm.bundles.get(0).traversal); assertEquals(secondPattern, countMatchAlgorithm.bundles.get(1).traversal); assertEquals(thirdPattern, countMatchAlgorithm.bundles.get(2).traversal); assertEquals(forthPattern, countMatchAlgorithm.bundles.get(3).traversal); assertEquals(fifthPattern, countMatchAlgorithm.bundles.get(4).traversal); // MAKE THE SECOND PATTERN EXPENSIVE countMatchAlgorithm.recordStart(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), secondPattern); // MAKE THE THIRD PATTERN MORE EXPENSIVE THAN FORTH countMatchAlgorithm.recordStart(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), thirdPattern); // MAKE THE FORTH PATTERN EXPENSIVE countMatchAlgorithm.recordStart(EmptyTraverser.instance(), forthPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), forthPattern); countMatchAlgorithm.recordEnd(EmptyTraverser.instance(), forthPattern); // Traverser.Admin traverser = B_LP_O_P_S_SE_SL_TraverserGenerator.instance().generate(1, EmptyStep.instance(), 1l); traverser.addLabels(Collections.singleton("a")); assertEquals(firstPattern, countMatchAlgorithm.apply(traverser)); traverser = traverser.split(1, EmptyStep.instance()); traverser.getTags().add(firstPattern.getStartStep().getId()); traverser.addLabels(Collections.singleton("b")); // assertEquals(secondPattern, countMatchAlgorithm.apply(traverser)); traverser = traverser.split(1, EmptyStep.instance()); traverser.getTags().add(secondPattern.getStartStep().getId()); traverser.addLabels(Collections.singleton("c")); // assertEquals(fifthPattern, countMatchAlgorithm.apply(traverser)); traverser = traverser.split(1, EmptyStep.instance()); traverser.getTags().add(fifthPattern.getStartStep().getId()); traverser.addLabels(Collections.singleton("f")); // assertEquals(forthPattern, countMatchAlgorithm.apply(traverser)); traverser = traverser.split(1, EmptyStep.instance()); traverser.getTags().add(forthPattern.getStartStep().getId()); traverser.addLabels(Collections.singleton("e")); // assertEquals(thirdPattern, countMatchAlgorithm.apply(traverser)); traverser = traverser.split(1, EmptyStep.instance()); traverser.getTags().add(thirdPattern.getStartStep().getId()); traverser.addLabels(Collections.singleton("d")); } @Test public void shouldCalculateStartLabelCorrectly() { Traversal.Admin<?, ?> traversal = match( where(and( as("a").out("created").as("b"), as("b").in("created").count().is(eq(3)))), as("a").both().as("b"), where(as("b").in())).asAdmin(); assertEquals("a", MatchStep.Helper.computeStartLabel(((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren())); ///// traversal = match( where("a", P.neq("c")), as("a").out("created").as("b"), or( as("a").out("knows").has("name", "vadas"), as("a").in("knows").and().as("a").has(T.label, "person") ), as("b").in("created").as("c"), as("b").in("created").count().is(P.gt(1))).asAdmin(); assertEquals("a", MatchStep.Helper.computeStartLabel(((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren())); } }
30,279
0.69727
0.690799
421
70.950119
37.528957
166
false
false
0
0
0
0
0
0
1.463183
false
false
13