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
891679e57e30e99f28736fb78b002d2f912df536
35,450,660,085,936
a41fcc03b42ac43b3e48181e67d9226190d56b64
/3118005319/SEPersonalProjectCZL/src/main/java/com/czl/DissertationCheckerImpl.java
406d243d49db7d379a30d2b65ad00ffdd07bc9ba
[]
no_license
Leung45/Leung45
https://github.com/Leung45/Leung45
8922eb5c713b343297a56aa6d6f779cbacd88daa
5a29ccce40be7e2d080e33fdc5b1a40bbb35338e
refs/heads/master
2022-12-26T15:05:30.688000
2020-10-06T12:48:36
2020-10-06T12:48:36
293,559,693
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.czl; import java.io.*; import java.math.BigDecimal; import java.util.*; import org.wltea.analyzer.core.IKSegmenter; import org.wltea.analyzer.core.Lexeme; /** * @author CZL * @date 2020 09 22 */ public class DissertationCheckerImpl implements DissertationChecker{ /** * 获取查重结果 * @param file1 * @param file2 * @return 查重率 * @throws IOException */ @Override public double getCheckedResult(File file1,File file2) throws IOException{ //读取文件内容到StringBuilder StringBuilder strBuilder1 = new StringBuilder(); StringBuilder strBuilder2 = new StringBuilder(); //读取文件内容 strBuilder1 = readFileData(strBuilder1,file1); strBuilder2 = readFileData(strBuilder2,file2); //切词,获得切词后的List List<String> list1 = divideText(strBuilder1); List<String> list2 = divideText(strBuilder2); //调用余弦算法查重 return cosAlgoCheck(list1,list2); } /** * 读取文件内容 * @param strBuilder * @param file * @return 存储文件内容的StringBuilder */ public static StringBuilder readFileData(StringBuilder strBuilder,File file){ //使用BufferedReader提高读取效率 BufferedReader buffReader = null; try{ buffReader = new BufferedReader(new FileReader(file)); String str = null; //逐行读取 while((str = buffReader.readLine())!=null){ strBuilder.append(System.lineSeparator()+str); } }catch(Exception e){ e.printStackTrace(); }finally { //必须释放资源 if(buffReader!=null){ try { buffReader.close(); } catch (IOException e) { e.printStackTrace(); } } } return strBuilder; } /** * 切词方法--IK切词 * @param strBuilder * @return 分词的集合 * @throws IOException */ public static List<String> divideText(StringBuilder strBuilder) throws IOException{ //转为StringReader处理 String totalStr = strBuilder.toString(); StringReader strReader = new StringReader(totalStr); //分词结果存储在List中 List<String> list = new ArrayList<>(); //使用IK切词,true代表使用智能分词 IKSegmenter ikSegmenter = new IKSegmenter(strReader,true); Lexeme lexeme = null; while ((lexeme = ikSegmenter.next())!=null){ String dividedStr = lexeme.getLexemeText(); list.add(dividedStr); } return list; } /** * 余弦算法 * @param list1 文件 * @param list2 文件 * @return 查重率 */ public static double cosAlgoCheck(List<String> list1, List<String> list2) { //非空判断 if ( list1==null || list2==null || list1.size()==0 || list2.size()==0 ) { return 0; } //计算出切词后的每个词在各自所在文章中的频数 Map<String, Integer> map1 = calSegFreq(list1); Map<String, Integer> map2 = calSegFreq(list2); //利用Set的特点存取两个文章中所有词语 Set<String> segmentSet = new HashSet<>(); segmentSet.addAll(list1); segmentSet.addAll(list2); //A·A Integer AA = 0; //B·B Integer BB = 0; //A·B Integer AB = 0; for (String segment : segmentSet) { //计算出Set中每个词分别在两个文章切词集合中的频数 Integer temp1 = map1.get(segment); int freq1 = 0; if (null != temp1) { freq1 = temp1.intValue(); } Integer temp2 = map2.get(segment); int freq2 = 0; if (null != temp2) { freq2 = temp2.intValue(); } //A·A AA = AA + freq1 * freq1; //B·B BB = BB + freq2 * freq2; //A·B AB = AB + freq1 * freq2; } //|A| = sqrt(A·A) double absA = Math.sqrt(AA.doubleValue()); //|B| = sqrt(B·B) double absB = Math.sqrt(BB.doubleValue()); //|A|*|B| BigDecimal absAB = BigDecimal.valueOf(absA).multiply(BigDecimal.valueOf(absB)); //cosθ = (A·B)/(|A|*|B|),结果保留小数点后两位 double cos = BigDecimal.valueOf(AB).divide(absAB, 2, BigDecimal.ROUND_FLOOR).doubleValue(); return cos; } /** * 计算分词的频数 * @param list * @return 分词及其频数的键值对集合 */ private static Map<String, Integer> calSegFreq(List<String> list) { Map<String, Integer> segFreq = new HashMap<>(); for (String segment : list) { Integer integer = segFreq.get(segment); if (null == integer) { //无则新建 Integer integerNew = 0; segFreq.put(segment, integerNew+1); }else { //有则加一 segFreq.put(segment,integer+1); } } return segFreq; } }
UTF-8
Java
5,338
java
DissertationCheckerImpl.java
Java
[ { "context": "rt org.wltea.analyzer.core.Lexeme;\n\n/**\n * @author CZL\n * @date 2020 09 22\n */\npublic class Dissertation", "end": 187, "score": 0.9996242523193359, "start": 184, "tag": "USERNAME", "value": "CZL" } ]
null
[]
package com.czl; import java.io.*; import java.math.BigDecimal; import java.util.*; import org.wltea.analyzer.core.IKSegmenter; import org.wltea.analyzer.core.Lexeme; /** * @author CZL * @date 2020 09 22 */ public class DissertationCheckerImpl implements DissertationChecker{ /** * 获取查重结果 * @param file1 * @param file2 * @return 查重率 * @throws IOException */ @Override public double getCheckedResult(File file1,File file2) throws IOException{ //读取文件内容到StringBuilder StringBuilder strBuilder1 = new StringBuilder(); StringBuilder strBuilder2 = new StringBuilder(); //读取文件内容 strBuilder1 = readFileData(strBuilder1,file1); strBuilder2 = readFileData(strBuilder2,file2); //切词,获得切词后的List List<String> list1 = divideText(strBuilder1); List<String> list2 = divideText(strBuilder2); //调用余弦算法查重 return cosAlgoCheck(list1,list2); } /** * 读取文件内容 * @param strBuilder * @param file * @return 存储文件内容的StringBuilder */ public static StringBuilder readFileData(StringBuilder strBuilder,File file){ //使用BufferedReader提高读取效率 BufferedReader buffReader = null; try{ buffReader = new BufferedReader(new FileReader(file)); String str = null; //逐行读取 while((str = buffReader.readLine())!=null){ strBuilder.append(System.lineSeparator()+str); } }catch(Exception e){ e.printStackTrace(); }finally { //必须释放资源 if(buffReader!=null){ try { buffReader.close(); } catch (IOException e) { e.printStackTrace(); } } } return strBuilder; } /** * 切词方法--IK切词 * @param strBuilder * @return 分词的集合 * @throws IOException */ public static List<String> divideText(StringBuilder strBuilder) throws IOException{ //转为StringReader处理 String totalStr = strBuilder.toString(); StringReader strReader = new StringReader(totalStr); //分词结果存储在List中 List<String> list = new ArrayList<>(); //使用IK切词,true代表使用智能分词 IKSegmenter ikSegmenter = new IKSegmenter(strReader,true); Lexeme lexeme = null; while ((lexeme = ikSegmenter.next())!=null){ String dividedStr = lexeme.getLexemeText(); list.add(dividedStr); } return list; } /** * 余弦算法 * @param list1 文件 * @param list2 文件 * @return 查重率 */ public static double cosAlgoCheck(List<String> list1, List<String> list2) { //非空判断 if ( list1==null || list2==null || list1.size()==0 || list2.size()==0 ) { return 0; } //计算出切词后的每个词在各自所在文章中的频数 Map<String, Integer> map1 = calSegFreq(list1); Map<String, Integer> map2 = calSegFreq(list2); //利用Set的特点存取两个文章中所有词语 Set<String> segmentSet = new HashSet<>(); segmentSet.addAll(list1); segmentSet.addAll(list2); //A·A Integer AA = 0; //B·B Integer BB = 0; //A·B Integer AB = 0; for (String segment : segmentSet) { //计算出Set中每个词分别在两个文章切词集合中的频数 Integer temp1 = map1.get(segment); int freq1 = 0; if (null != temp1) { freq1 = temp1.intValue(); } Integer temp2 = map2.get(segment); int freq2 = 0; if (null != temp2) { freq2 = temp2.intValue(); } //A·A AA = AA + freq1 * freq1; //B·B BB = BB + freq2 * freq2; //A·B AB = AB + freq1 * freq2; } //|A| = sqrt(A·A) double absA = Math.sqrt(AA.doubleValue()); //|B| = sqrt(B·B) double absB = Math.sqrt(BB.doubleValue()); //|A|*|B| BigDecimal absAB = BigDecimal.valueOf(absA).multiply(BigDecimal.valueOf(absB)); //cosθ = (A·B)/(|A|*|B|),结果保留小数点后两位 double cos = BigDecimal.valueOf(AB).divide(absAB, 2, BigDecimal.ROUND_FLOOR).doubleValue(); return cos; } /** * 计算分词的频数 * @param list * @return 分词及其频数的键值对集合 */ private static Map<String, Integer> calSegFreq(List<String> list) { Map<String, Integer> segFreq = new HashMap<>(); for (String segment : list) { Integer integer = segFreq.get(segment); if (null == integer) { //无则新建 Integer integerNew = 0; segFreq.put(segment, integerNew+1); }else { //有则加一 segFreq.put(segment,integer+1); } } return segFreq; } }
5,338
0.534955
0.520646
182
25.879122
21.292486
99
false
false
0
0
0
0
0
0
0.5
false
false
4
46a2e0b5a94078b5ac9273a1ec5a6921fbb0bb67
19,576,460,969,748
97f2b4aae15dd76a1c4d368bb4b8b79d0eaf401d
/Snake/Snake.java
f904ae5774bb12564f0cda349eb86efb5916c48e
[]
no_license
mariagil12/sad
https://github.com/mariagil12/sad
4e0a70406ada84f5e2b3d35f0164433fbbe79956
47d6edc43f3b7ec7c733e308fb5aa537b6f9e255
refs/heads/main
2023-05-19T17:57:31.183000
2021-06-13T15:59:55
2021-06-13T15:59:55
339,968,866
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sad_Snake; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.util.ArrayList; public class Snake { public static final int BLACK=0; public static final int GRAY=1; public static final int PINK=2; public static final int BLUE=3; public static final int GREEN=4; public static final int RED=5; public static final int CYAN=6; public static final int MAGENTA=7; public static final int WHITE=8; public static final int DARKGRAY=9; public static final int ORANGE=10; public static final int YELLOW=11; public static final int INITIALX=400; public static final int INITIALY=300; private ArrayList<Point> snake = new ArrayList<Point>(); private int newX; private int newY; private int oldX; private int oldY; private Point lastPos; private Point aux = new Point(); public boolean pause = false; public int color; public Snake(int c) { this.snake.add(new Point(INITIALX,INITIALY)); this.color=c; } public ArrayList<Point> getSnake() { return snake; } public void drawSnake(Graphics g, int color) { switch(color) { case BLACK: g.setColor(Color.BLACK); break; case GRAY: g.setColor(Color.GRAY); break; case PINK: g.setColor(Color.PINK); break; case BLUE: g.setColor(Color.BLUE); break; case GREEN: g.setColor(Color.GREEN); break; case RED: g.setColor(Color.RED); break; case CYAN: g.setColor(Color.CYAN); break; case MAGENTA: g.setColor(Color.MAGENTA); break; case WHITE: g.setColor(Color.WHITE); break; case DARKGRAY: g.setColor(Color.DARK_GRAY); break; case ORANGE: g.setColor(Color.ORANGE); break; case YELLOW: g.setColor(Color.YELLOW); break; } for(int n = 0; n < snake.size(); n++) { g.fillRect(snake.get(n).x, snake.get(n).y, 10, 10); } } public boolean allowMove() { aux.x = snake.get(0).x + newX; aux.y = snake.get(0).y + newY; if(snake.size()>1 && snake.get(1).equals(aux)) { return false; } else { return true; } } public void moveSnake() { if(pause == false) { lastPos=snake.get(snake.size()-1); if(allowMove()) { for(int n=snake.size()-1; n>0; n--) { snake.get(n).setLocation(snake.get(n-1)); } snake.get(0).setLocation(aux); } else { for(int n=snake.size()-1; n>0; n--) { snake.get(n).setLocation(snake.get(n-1)); } Point newPoint = new Point(); newPoint.x=snake.get(0).x+oldX; newPoint.y=snake.get(0).y+oldY; snake.get(0).setLocation(newPoint); } } else { return; } } public void direction(String d) { oldX=newX; oldY=newY; switch(d) { case "UP": newX = 0; newY=(-10); break; case "DOWN": newX=0; newY=10; break; case "RIGTH": newX=10; newY=0; break; case "LEFT": newX=(-10); newY=0; break; } } public void grow() { snake.add(new Point(lastPos.x,lastPos.y)); } }
UTF-8
Java
2,928
java
Snake.java
Java
[]
null
[]
package sad_Snake; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.util.ArrayList; public class Snake { public static final int BLACK=0; public static final int GRAY=1; public static final int PINK=2; public static final int BLUE=3; public static final int GREEN=4; public static final int RED=5; public static final int CYAN=6; public static final int MAGENTA=7; public static final int WHITE=8; public static final int DARKGRAY=9; public static final int ORANGE=10; public static final int YELLOW=11; public static final int INITIALX=400; public static final int INITIALY=300; private ArrayList<Point> snake = new ArrayList<Point>(); private int newX; private int newY; private int oldX; private int oldY; private Point lastPos; private Point aux = new Point(); public boolean pause = false; public int color; public Snake(int c) { this.snake.add(new Point(INITIALX,INITIALY)); this.color=c; } public ArrayList<Point> getSnake() { return snake; } public void drawSnake(Graphics g, int color) { switch(color) { case BLACK: g.setColor(Color.BLACK); break; case GRAY: g.setColor(Color.GRAY); break; case PINK: g.setColor(Color.PINK); break; case BLUE: g.setColor(Color.BLUE); break; case GREEN: g.setColor(Color.GREEN); break; case RED: g.setColor(Color.RED); break; case CYAN: g.setColor(Color.CYAN); break; case MAGENTA: g.setColor(Color.MAGENTA); break; case WHITE: g.setColor(Color.WHITE); break; case DARKGRAY: g.setColor(Color.DARK_GRAY); break; case ORANGE: g.setColor(Color.ORANGE); break; case YELLOW: g.setColor(Color.YELLOW); break; } for(int n = 0; n < snake.size(); n++) { g.fillRect(snake.get(n).x, snake.get(n).y, 10, 10); } } public boolean allowMove() { aux.x = snake.get(0).x + newX; aux.y = snake.get(0).y + newY; if(snake.size()>1 && snake.get(1).equals(aux)) { return false; } else { return true; } } public void moveSnake() { if(pause == false) { lastPos=snake.get(snake.size()-1); if(allowMove()) { for(int n=snake.size()-1; n>0; n--) { snake.get(n).setLocation(snake.get(n-1)); } snake.get(0).setLocation(aux); } else { for(int n=snake.size()-1; n>0; n--) { snake.get(n).setLocation(snake.get(n-1)); } Point newPoint = new Point(); newPoint.x=snake.get(0).x+oldX; newPoint.y=snake.get(0).y+oldY; snake.get(0).setLocation(newPoint); } } else { return; } } public void direction(String d) { oldX=newX; oldY=newY; switch(d) { case "UP": newX = 0; newY=(-10); break; case "DOWN": newX=0; newY=10; break; case "RIGTH": newX=10; newY=0; break; case "LEFT": newX=(-10); newY=0; break; } } public void grow() { snake.add(new Point(lastPos.x,lastPos.y)); } }
2,928
0.636954
0.619194
148
18.783783
13.580361
57
false
false
0
0
0
0
0
0
2.675676
false
false
4
df653adbfc6977e4dc16551925344f73e68a0e1d
14,156,212,227,484
905855685ecd7809b5980c5468090f7a1407ff95
/ccc13j2.java
733e4e921eaa4e2d9e39aeda38d649642e4e1ff3
[]
no_license
potatoeggy/competitive
https://github.com/potatoeggy/competitive
2ce23f51284aa39db89bf7f958261abb13d6359d
354d99c277f974db93d2dd2902c03fa2be998344
refs/heads/master
2023-02-14T05:31:27.213000
2021-01-03T23:09:55
2021-01-03T23:09:55
268,399,853
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; class ccc13j2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); String user = input.nextLine(); boolean failed = false; for (char chara : user.toCharArray()) { if (chara != 'I' && chara != 'O' && chara != 'S' && chara != 'H' && chara != 'Z' && chara != 'X' && chara != 'N') { failed = true; break; } } if (failed) { System.out.println("NO"); } else { System.out.println("YES"); } } }
UTF-8
Java
491
java
ccc13j2.java
Java
[]
null
[]
import java.util.Scanner; class ccc13j2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); String user = input.nextLine(); boolean failed = false; for (char chara : user.toCharArray()) { if (chara != 'I' && chara != 'O' && chara != 'S' && chara != 'H' && chara != 'Z' && chara != 'X' && chara != 'N') { failed = true; break; } } if (failed) { System.out.println("NO"); } else { System.out.println("YES"); } } }
491
0.547862
0.541752
23
20.347826
25.050573
118
false
false
0
0
0
0
0
0
2.26087
false
false
4
4ed13991958ac554ed91429e4bd1c581334c4b50
28,381,143,900,973
007db6a36ac288421ac2cdea3f95f409e48c6c0f
/src/kin/dao/customer/AttachmentManagerIMP.java
2d009b74f3e866d3636f8cc70e31b31e4680ac4e
[]
no_license
eric-kin/core
https://github.com/eric-kin/core
9c157d383165176ce69d61ca5b78b2a999765fb4
90bd52e99fe4dd3bfcbfeb2007befe38462046a8
refs/heads/master
2016-08-11T07:37:51.396000
2015-07-01T10:11:54
2015-07-01T10:11:54
36,277,165
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kin.dao.customer; import org.springframework.stereotype.Component; import kin.bean.customer.Attachment; import kin.dao.system.BaseManagerIMP; import kin.manager.customer.AttachmentManager; @Component public class AttachmentManagerIMP extends BaseManagerIMP<Attachment> implements AttachmentManager { }
UTF-8
Java
330
java
AttachmentManagerIMP.java
Java
[]
null
[]
package kin.dao.customer; import org.springframework.stereotype.Component; import kin.bean.customer.Attachment; import kin.dao.system.BaseManagerIMP; import kin.manager.customer.AttachmentManager; @Component public class AttachmentManagerIMP extends BaseManagerIMP<Attachment> implements AttachmentManager { }
330
0.806061
0.806061
13
23.23077
28.549967
99
false
false
0
0
0
0
0
0
0.384615
false
false
4
01700b5936582d109b85d138c463bb12ca5dfe0f
31,327,491,512,681
676205704317e7891ef07aa18f05683e6eff2d23
/src/main/java/com/ragu/concurrency/core/MyApp.java
d5c8ac4be8079fe896ceb9b90eb7e27cd32d002b
[]
no_license
regunath/core-java
https://github.com/regunath/core-java
4702630b58d8416530e62d19f8c153a9280274bd
c470443b349535c1a0aa5c9ee961fb045c72152c
refs/heads/master
2021-01-09T20:21:28.303000
2016-07-28T15:24:06
2016-07-28T15:24:06
64,404,761
0
1
null
false
2016-07-28T15:35:40
2016-07-28T15:01:05
2016-07-28T15:08:23
2016-07-28T15:35:07
0
0
0
1
Java
null
null
package com.ragu.concurrency.core; public class MyApp { public static void main(String[] args) { MySyncService s = new MySyncService(); Thread t = new MyThread(s); t.setName("Thread---1"); Thread intt = new Thread(new MyIntThread(s)); intt.setName("Thread--2"); t.start(); intt.start(); } }
UTF-8
Java
314
java
MyApp.java
Java
[]
null
[]
package com.ragu.concurrency.core; public class MyApp { public static void main(String[] args) { MySyncService s = new MySyncService(); Thread t = new MyThread(s); t.setName("Thread---1"); Thread intt = new Thread(new MyIntThread(s)); intt.setName("Thread--2"); t.start(); intt.start(); } }
314
0.656051
0.649682
17
17.470589
16.335157
47
false
false
0
0
0
0
0
0
1.529412
false
false
4
6a44c9fe608768ab9aa3fa4d58ee30398af17680
11,630,771,457,532
301df37c25780842f11c8ac8373cdbd96f1d3656
/api/src/main/java/me/apjung/backend/domain/User/User.java
a8f562b2bde88875fb4ee51d57fae52cf5c2671b
[ "MIT" ]
permissive
gatsjy/apjung-backend
https://github.com/gatsjy/apjung-backend
b4fb01493549c5d9ecc7f65283feaa4161458902
f31f60f39aa64461df490d025bac366646a0bc15
refs/heads/master
2023-03-17T19:42:03.529000
2020-10-16T05:48:45
2020-10-16T05:48:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.apjung.backend.domain.User; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; @NoArgsConstructor @Setter @Getter @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "USER_ID") private Long id; private String email; private String password; private String name; private String mobile; private boolean isEmailAuth; private String emailAuthToken; @Builder public User(String email, String password, String name, String mobile, boolean isEmailAuth, String emailAuthToken) { this.email = email; this.password = password; this.name = name; this.mobile = mobile; this.isEmailAuth = isEmailAuth; this.emailAuthToken = emailAuthToken; } }
UTF-8
Java
868
java
User.java
Java
[ { "context": " this.email = email;\n this.password = password;\n this.name = name;\n this.mobile = ", "end": 716, "score": 0.998884379863739, "start": 708, "tag": "PASSWORD", "value": "password" } ]
null
[]
package me.apjung.backend.domain.User; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; @NoArgsConstructor @Setter @Getter @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "USER_ID") private Long id; private String email; private String password; private String name; private String mobile; private boolean isEmailAuth; private String emailAuthToken; @Builder public User(String email, String password, String name, String mobile, boolean isEmailAuth, String emailAuthToken) { this.email = email; this.password = <PASSWORD>; this.name = name; this.mobile = mobile; this.isEmailAuth = isEmailAuth; this.emailAuthToken = emailAuthToken; } }
870
0.705069
0.705069
36
23.111111
21.813322
120
false
false
0
0
0
0
0
0
0.666667
false
false
4
b8d53fbc9e8cbd35fdbdddfb4798746feaec81e8
11,630,771,459,039
5ffabe17f00d210eb8d0d087d09b06a52dcb35b7
/ic-se-storm/src/main/java/thu/instcloud/app/se/storm/icLauncher/ICSETopologyBuilder.java
d5f748bef06d67fe029fef3b77abc3b9184b5794
[ "Apache-2.0" ]
permissive
applyhhj/state-estimation-storm
https://github.com/applyhhj/state-estimation-storm
3e4c3a7b73e701c9fd8a2021327feb97b596378d
74ab07f2ec29aa50378dfaba7581197acee6141a
refs/heads/master
2018-12-31T19:14:06.169000
2016-05-31T07:50:14
2016-05-31T07:50:14
49,451,025
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package thu.instcloud.app.se.storm.icLauncher; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.StormSubmitter; import backtype.storm.topology.TopologyBuilder; import thu.instcloud.app.se.storm.common.SeUtils; import thu.instcloud.app.se.storm.estimator.*; import thu.instcloud.app.se.storm.measure.ExtractMeasureBolt; import thu.instcloud.app.se.storm.measure.StoreMeasureRBolt; import thu.instcloud.app.se.storm.splitter.ICSplitSystemRBolt; import thu.instcloud.app.se.storm.splitter.InitializerRBolt; import thu.instcloud.app.se.storm.splitter.PrepareRBolt; import thu.instcloud.common.ICUtils; import thu.instcloud.storm.api.core.ICStormComponentBuilder; import thu.instcloud.storm.api.core.ICStormComponents; import java.util.Map; /** * Created by hjh on 16-1-12. */ public class ICSETopologyBuilder { private Config config; private TopologyBuilder builder; private LocalCluster cluster; private String topologyName; private long runningTime; private String confFile; private String redisip; private String pass; private int paraEst; private int paraBad; private int paraMeaExtract; public ICSETopologyBuilder(String configFile) { this.confFile = configFile; importOtherConfig(); this.builder = new TopologyBuilder(); this.config = new Config(); this.runningTime = 1800; } private void importOtherConfig() { Map config; if (this.confFile == null) { config = ICUtils.Common.readICStormConfigFile(); } else { config = ICUtils.Common.readConfigFile(this.confFile); } this.redisip = (String) config.get(SeUtils.CONSTANTS.CFG_KEY_REDIS_SERVER); this.pass = (String) config.get(SeUtils.CONSTANTS.CFG_KEY_REDIS_PASS); this.paraBad = Integer.parseInt((String) config.get(SeUtils.CONSTANTS.CFG_KEY_PARA_BAD)); this.paraEst = Integer.parseInt((String) config.get(SeUtils.CONSTANTS.CFG_KEY_PARA_EST)); this.paraMeaExtract = Integer.parseInt((String) config.get(SeUtils.CONSTANTS.CFG_KEY_PARA_MEAEXTRACT)); } public void composeTopology() { ICStormComponentBuilder icStormComponentBuilder = new ICStormComponentBuilder(confFile); ICStormComponents components = icStormComponentBuilder.build(); // system split part builder.setSpout(SeUtils.STORM.COMPONENT.COMP_IC_CASE_RAWDATA_SPOUT, components.getSpouts().get(SeUtils.STORM.COMPONENT.COMP_IC_CASE_RAWDATA_SPOUT), 1); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_SPLIT_SPLITTER_BOLT, new ICSplitSystemRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_IC_CASE_RAWDATA_SPOUT); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_SPLIT_INITIALIZER_BOLT, new InitializerRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_SPLIT_SPLITTER_BOLT); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_SPLIT_PREPARE_BOLT, new PrepareRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_SPLIT_INITIALIZER_BOLT); // measurement system builder.setSpout(SeUtils.STORM.COMPONENT.COMP_IC_MEASURE_SPOUT, components.getSpouts().get(SeUtils.STORM.COMPONENT.COMP_IC_MEASURE_SPOUT), 1); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_MEAS_EXTRACT_BOLT, new ExtractMeasureBolt(), paraMeaExtract) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_IC_MEASURE_SPOUT); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_MEAS_STORE_BOLT, new StoreMeasureRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_MEAS_EXTRACT_BOLT); // estimator part // ic spout builder.setSpout(SeUtils.STORM.COMPONENT.COMP_IC_TRIGGER_SPOUT, components.getSpouts().get(SeUtils.STORM.COMPONENT.COMP_IC_TRIGGER_SPOUT), 1); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_TRIGGER_BOLT, new ICTriggerRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_IC_TRIGGER_SPOUT); builder.setSpout(SeUtils.STORM.COMPONENT.COMP_EST_TRIGGER_CANDI_SPOUT, new TriggerForCandidateRSpout(redisip, pass), 1); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_FIRSTEST, new FirstEstimationRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_TRIGGER_BOLT) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_TRIGGER_CANDI_SPOUT); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_REDUCEMAT, new ReduceMatrixRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_FIRSTEST, SeUtils.STORM.STREAM.STREAM_ESTIMATE) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_CHECKAFTERBADRECOG, SeUtils.STORM.STREAM.STREAM_ESTIMATE); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_ESTONCE, new EstimateOnceRBolt(redisip, pass), paraEst) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_REDUCEMAT) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_CHECKCONV, SeUtils.STORM.STREAM.STREAM_ESTIMATE); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_CHECKCONV, new CheckConvergeRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_ESTONCE); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_BADRECOG, new BadDataRecognitionRBolt(redisip, pass), paraBad) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_CHECKCONV, SeUtils.STORM.STREAM.STREAM_BAD_RECOG); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_CHECKAFTERBADRECOG, new CheckAfterBadRecogRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_BADRECOG); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_OUTPUT, new ICOutputBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_CHECKAFTERBADRECOG, SeUtils.STORM.STREAM.STREAM_OUTPUT) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_FIRSTEST, SeUtils.STORM.STREAM.STREAM_OUTPUT); // ic bolt for output builder.setBolt(SeUtils.STORM.COMPONENT.COMP_IC_OUTPUT_BOLT, components.getBolts().get(SeUtils.STORM.COMPONENT.COMP_IC_OUTPUT_BOLT)) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_OUTPUT); } private void runLocal() { if (cluster == null) { cluster = new LocalCluster(); } if (topologyName == null) { topologyName = "default"; } cluster.submitTopology(topologyName, config, builder.createTopology()); backtype.storm.utils.Utils.sleep(runningTime * 1000); cluster.killTopology(topologyName); cluster.shutdown(); } public void run(String[] args) throws Exception { if (args == null || args.length == 0) { topologyName = "estimator"; } else if (args.length == 4) { paraEst = Integer.parseInt(args[2]); paraBad = Integer.parseInt(args[3]); } composeTopology(); if (args == null || args.length == 0) { runLocal(); } else { int nWorkers = 3; if (args.length > 1) { // the second arg is the number of workers nWorkers = Integer.parseInt(args[1]); } // we need to set this number otherwise storm will set a acker for each worker, so the total number of executors // will be larger than the sum of parallelism hint of all bolts and spouts config.setNumAckers(3); // in se we can not set n task, as each task will spawn a matlab worker, then it will confuse us about the // processing capacity of the topology and matlab workers. And the capacity, especially of the estimation // components, is determined by the number of matlab workers, that is the number of tasks, not the number of // storm executors. config.setNumWorkers(nWorkers); // about topology rebalance // You always need to have more (or equal number of) tasks than executors. As the number of tasks is fixed, // you need to set a larger initial number than initial executors in order to be able to scale up the number of executors // during runtime. You can see the number of tasks, as maximum number of executors: // #executors <= #numTasks // by default if the number of executors(ne) is smaller than the number of workers then storm will only assign // ne workers StormSubmitter.submitTopologyWithProgressBar(args[0], config, builder.createTopology()); } } }
UTF-8
Java
8,800
java
ICSETopologyBuilder.java
Java
[ { "context": "ponents;\n\nimport java.util.Map;\n\n/**\n * Created by hjh on 16-1-12.\n */\npublic class ICSETopologyBuilder ", "end": 799, "score": 0.9996820688247681, "start": 796, "tag": "USERNAME", "value": "hjh" } ]
null
[]
package thu.instcloud.app.se.storm.icLauncher; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.StormSubmitter; import backtype.storm.topology.TopologyBuilder; import thu.instcloud.app.se.storm.common.SeUtils; import thu.instcloud.app.se.storm.estimator.*; import thu.instcloud.app.se.storm.measure.ExtractMeasureBolt; import thu.instcloud.app.se.storm.measure.StoreMeasureRBolt; import thu.instcloud.app.se.storm.splitter.ICSplitSystemRBolt; import thu.instcloud.app.se.storm.splitter.InitializerRBolt; import thu.instcloud.app.se.storm.splitter.PrepareRBolt; import thu.instcloud.common.ICUtils; import thu.instcloud.storm.api.core.ICStormComponentBuilder; import thu.instcloud.storm.api.core.ICStormComponents; import java.util.Map; /** * Created by hjh on 16-1-12. */ public class ICSETopologyBuilder { private Config config; private TopologyBuilder builder; private LocalCluster cluster; private String topologyName; private long runningTime; private String confFile; private String redisip; private String pass; private int paraEst; private int paraBad; private int paraMeaExtract; public ICSETopologyBuilder(String configFile) { this.confFile = configFile; importOtherConfig(); this.builder = new TopologyBuilder(); this.config = new Config(); this.runningTime = 1800; } private void importOtherConfig() { Map config; if (this.confFile == null) { config = ICUtils.Common.readICStormConfigFile(); } else { config = ICUtils.Common.readConfigFile(this.confFile); } this.redisip = (String) config.get(SeUtils.CONSTANTS.CFG_KEY_REDIS_SERVER); this.pass = (String) config.get(SeUtils.CONSTANTS.CFG_KEY_REDIS_PASS); this.paraBad = Integer.parseInt((String) config.get(SeUtils.CONSTANTS.CFG_KEY_PARA_BAD)); this.paraEst = Integer.parseInt((String) config.get(SeUtils.CONSTANTS.CFG_KEY_PARA_EST)); this.paraMeaExtract = Integer.parseInt((String) config.get(SeUtils.CONSTANTS.CFG_KEY_PARA_MEAEXTRACT)); } public void composeTopology() { ICStormComponentBuilder icStormComponentBuilder = new ICStormComponentBuilder(confFile); ICStormComponents components = icStormComponentBuilder.build(); // system split part builder.setSpout(SeUtils.STORM.COMPONENT.COMP_IC_CASE_RAWDATA_SPOUT, components.getSpouts().get(SeUtils.STORM.COMPONENT.COMP_IC_CASE_RAWDATA_SPOUT), 1); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_SPLIT_SPLITTER_BOLT, new ICSplitSystemRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_IC_CASE_RAWDATA_SPOUT); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_SPLIT_INITIALIZER_BOLT, new InitializerRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_SPLIT_SPLITTER_BOLT); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_SPLIT_PREPARE_BOLT, new PrepareRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_SPLIT_INITIALIZER_BOLT); // measurement system builder.setSpout(SeUtils.STORM.COMPONENT.COMP_IC_MEASURE_SPOUT, components.getSpouts().get(SeUtils.STORM.COMPONENT.COMP_IC_MEASURE_SPOUT), 1); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_MEAS_EXTRACT_BOLT, new ExtractMeasureBolt(), paraMeaExtract) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_IC_MEASURE_SPOUT); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_MEAS_STORE_BOLT, new StoreMeasureRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_MEAS_EXTRACT_BOLT); // estimator part // ic spout builder.setSpout(SeUtils.STORM.COMPONENT.COMP_IC_TRIGGER_SPOUT, components.getSpouts().get(SeUtils.STORM.COMPONENT.COMP_IC_TRIGGER_SPOUT), 1); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_TRIGGER_BOLT, new ICTriggerRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_IC_TRIGGER_SPOUT); builder.setSpout(SeUtils.STORM.COMPONENT.COMP_EST_TRIGGER_CANDI_SPOUT, new TriggerForCandidateRSpout(redisip, pass), 1); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_FIRSTEST, new FirstEstimationRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_TRIGGER_BOLT) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_TRIGGER_CANDI_SPOUT); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_REDUCEMAT, new ReduceMatrixRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_FIRSTEST, SeUtils.STORM.STREAM.STREAM_ESTIMATE) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_CHECKAFTERBADRECOG, SeUtils.STORM.STREAM.STREAM_ESTIMATE); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_ESTONCE, new EstimateOnceRBolt(redisip, pass), paraEst) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_REDUCEMAT) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_CHECKCONV, SeUtils.STORM.STREAM.STREAM_ESTIMATE); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_CHECKCONV, new CheckConvergeRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_ESTONCE); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_BADRECOG, new BadDataRecognitionRBolt(redisip, pass), paraBad) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_CHECKCONV, SeUtils.STORM.STREAM.STREAM_BAD_RECOG); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_CHECKAFTERBADRECOG, new CheckAfterBadRecogRBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_BADRECOG); builder.setBolt(SeUtils.STORM.COMPONENT.COMP_EST_OUTPUT, new ICOutputBolt(redisip, pass), 1) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_CHECKAFTERBADRECOG, SeUtils.STORM.STREAM.STREAM_OUTPUT) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_FIRSTEST, SeUtils.STORM.STREAM.STREAM_OUTPUT); // ic bolt for output builder.setBolt(SeUtils.STORM.COMPONENT.COMP_IC_OUTPUT_BOLT, components.getBolts().get(SeUtils.STORM.COMPONENT.COMP_IC_OUTPUT_BOLT)) .shuffleGrouping(SeUtils.STORM.COMPONENT.COMP_EST_OUTPUT); } private void runLocal() { if (cluster == null) { cluster = new LocalCluster(); } if (topologyName == null) { topologyName = "default"; } cluster.submitTopology(topologyName, config, builder.createTopology()); backtype.storm.utils.Utils.sleep(runningTime * 1000); cluster.killTopology(topologyName); cluster.shutdown(); } public void run(String[] args) throws Exception { if (args == null || args.length == 0) { topologyName = "estimator"; } else if (args.length == 4) { paraEst = Integer.parseInt(args[2]); paraBad = Integer.parseInt(args[3]); } composeTopology(); if (args == null || args.length == 0) { runLocal(); } else { int nWorkers = 3; if (args.length > 1) { // the second arg is the number of workers nWorkers = Integer.parseInt(args[1]); } // we need to set this number otherwise storm will set a acker for each worker, so the total number of executors // will be larger than the sum of parallelism hint of all bolts and spouts config.setNumAckers(3); // in se we can not set n task, as each task will spawn a matlab worker, then it will confuse us about the // processing capacity of the topology and matlab workers. And the capacity, especially of the estimation // components, is determined by the number of matlab workers, that is the number of tasks, not the number of // storm executors. config.setNumWorkers(nWorkers); // about topology rebalance // You always need to have more (or equal number of) tasks than executors. As the number of tasks is fixed, // you need to set a larger initial number than initial executors in order to be able to scale up the number of executors // during runtime. You can see the number of tasks, as maximum number of executors: // #executors <= #numTasks // by default if the number of executors(ne) is smaller than the number of workers then storm will only assign // ne workers StormSubmitter.submitTopologyWithProgressBar(args[0], config, builder.createTopology()); } } }
8,800
0.69125
0.687045
179
48.16201
39.774666
128
false
false
0
0
0
0
0
0
0.821229
false
false
4
06af83cac2ec846daef48d0a4024506a065a1201
34,059,090,658,137
b5a8576ff793c8af77e43ef205b6849963d80de7
/MyApplication3/app/src/main/java/com/example/myapplication/Settings.java
6f18ad35660ec73a6c272c5a2650bd54f5fa9197
[]
no_license
angelicaengstrom/IPP
https://github.com/angelicaengstrom/IPP
4fc0c3f750ae717e9321cd568b6c97995ea5840a
2562fe21f6b98ff44b849a225f45072805255918
refs/heads/main
2023-05-06T12:36:37.704000
2022-01-19T16:03:54
2022-01-19T16:03:54
337,354,061
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.myapplication; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.provider.MediaStore; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class Settings extends AppCompatActivity { private FirebaseUser user; private DatabaseReference reference; private String userID; private Button logout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); logout = (Button) findViewById(R.id.logoutbtn); Intent intent = new Intent(this, MainActivity.class); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v){ FirebaseAuth.getInstance().signOut(); finish(); startActivity(intent); } }); user = FirebaseAuth.getInstance().getCurrentUser(); reference = FirebaseDatabase.getInstance().getReference("Users"); userID = user.getUid(); final TextView fullNameTextView = (TextView) findViewById(R.id.ViewFullname); final TextView emailTextView = (TextView) findViewById(R.id.ViewEmail); final TextView ageTextView = (TextView) findViewById(R.id.ageTextView); final TextView genderTextView = (TextView) findViewById(R.id.genderTextView); reference.child(userID).addListenerForSingleValueEvent(new ValueEventListener(){ @Override public void onDataChange(@NonNull DataSnapshot snapshot){ user userProfile = snapshot.getValue(user.class); if(userProfile != null){ String fullName = userProfile.fullName; String email = userProfile.Email; String age = userProfile.age; String gender = userProfile.Gender; fullNameTextView.setText(fullName); emailTextView.setText(email); ageTextView.setText(age); genderTextView.setText(gender); } } @Override public void onCancelled(@NonNull DatabaseError error){ Toast.makeText(Settings.this, "Ett fel har inträffat!", Toast.LENGTH_LONG).show(); } }); if(FirebaseAuth.getInstance().getCurrentUser() == null){ startActivity(new Intent(this, MainActivity.class)); this.finish(); } BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation); bottomNavigationView.setSelectedItemId(R.id.settings); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch(item.getItemId()){ case R.id.note: startActivity(new Intent(getApplicationContext(), Add.class)); overridePendingTransition(0,0); return true; case R.id.calender: startActivity(new Intent(getApplicationContext(), Calender.class)); overridePendingTransition(0,0); return true; case R.id.graph: startActivity(new Intent(getApplicationContext(), Graph.class)); overridePendingTransition(0,0); return true; case R.id.settings: return true; } return false; } }); } }
UTF-8
Java
4,586
java
Settings.java
Java
[]
null
[]
package com.example.myapplication; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.provider.MediaStore; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class Settings extends AppCompatActivity { private FirebaseUser user; private DatabaseReference reference; private String userID; private Button logout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); logout = (Button) findViewById(R.id.logoutbtn); Intent intent = new Intent(this, MainActivity.class); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v){ FirebaseAuth.getInstance().signOut(); finish(); startActivity(intent); } }); user = FirebaseAuth.getInstance().getCurrentUser(); reference = FirebaseDatabase.getInstance().getReference("Users"); userID = user.getUid(); final TextView fullNameTextView = (TextView) findViewById(R.id.ViewFullname); final TextView emailTextView = (TextView) findViewById(R.id.ViewEmail); final TextView ageTextView = (TextView) findViewById(R.id.ageTextView); final TextView genderTextView = (TextView) findViewById(R.id.genderTextView); reference.child(userID).addListenerForSingleValueEvent(new ValueEventListener(){ @Override public void onDataChange(@NonNull DataSnapshot snapshot){ user userProfile = snapshot.getValue(user.class); if(userProfile != null){ String fullName = userProfile.fullName; String email = userProfile.Email; String age = userProfile.age; String gender = userProfile.Gender; fullNameTextView.setText(fullName); emailTextView.setText(email); ageTextView.setText(age); genderTextView.setText(gender); } } @Override public void onCancelled(@NonNull DatabaseError error){ Toast.makeText(Settings.this, "Ett fel har inträffat!", Toast.LENGTH_LONG).show(); } }); if(FirebaseAuth.getInstance().getCurrentUser() == null){ startActivity(new Intent(this, MainActivity.class)); this.finish(); } BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation); bottomNavigationView.setSelectedItemId(R.id.settings); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch(item.getItemId()){ case R.id.note: startActivity(new Intent(getApplicationContext(), Add.class)); overridePendingTransition(0,0); return true; case R.id.calender: startActivity(new Intent(getApplicationContext(), Calender.class)); overridePendingTransition(0,0); return true; case R.id.graph: startActivity(new Intent(getApplicationContext(), Graph.class)); overridePendingTransition(0,0); return true; case R.id.settings: return true; } return false; } }); } }
4,586
0.637732
0.636423
118
37.864407
26.849838
126
false
false
0
0
0
0
0
0
0.677966
false
false
4
8faf89f4a7b48e6364a397ea467ce132f8f53796
26,989,574,530,756
86c0bb90197752165b121ffc5600654d9dbea7cb
/Assignment 2/CAB302 Inventory Management Project/src/Items/ItemTemp.java
9efebff0cdc7038ea571c9072a35f1cf96971438
[]
no_license
jaylayson/java-proj
https://github.com/jaylayson/java-proj
8aa09e712f54a916316e119e4bf6266080d5512b
4c6e88ec562a000e8b951794064f2cf1845d0e7e
refs/heads/master
2020-04-27T00:00:24.222000
2019-06-06T06:17:22
2019-06-06T06:17:22
173,921,046
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * */ package Items; /** * @author John Layson * An item has a name, cost, price, reorder point and reorder amount * but may also have a temperature */ public abstract class ItemTemp implements ItemInterface{ public ItemTemp(String name, int cost, int price, int reorderP, int reorderA) { } /** * @return item's temperature */ public abstract int temperature(); }
UTF-8
Java
387
java
ItemTemp.java
Java
[ { "context": "/*\n * \n */\npackage Items;\n\n/**\n * @author John Layson\n * An item has a name, cost, price, reorder point", "end": 53, "score": 0.9994991421699524, "start": 42, "tag": "NAME", "value": "John Layson" } ]
null
[]
/* * */ package Items; /** * @author <NAME> * An item has a name, cost, price, reorder point and reorder amount * but may also have a temperature */ public abstract class ItemTemp implements ItemInterface{ public ItemTemp(String name, int cost, int price, int reorderP, int reorderA) { } /** * @return item's temperature */ public abstract int temperature(); }
382
0.687339
0.687339
22
16.59091
23.49402
80
false
false
0
0
0
0
0
0
0.727273
false
false
4
3d4bb5f43a9bc576bc5fa0541bf34b937f685275
30,382,598,665,650
1b02929bffa91aaa3c17a3a2430abacc558250f5
/DesignPatterns-Iterator/src/main/java/headfirst/Iterator/MenuIterator.java
ee98e276637fe263797b8359f3271b02a3cd0c14
[ "MIT" ]
permissive
wangchunfan/DesignPatterns
https://github.com/wangchunfan/DesignPatterns
1a4947d7e897412242ce7a71163d3b37eda71eb0
a8c4688e273c588355df17e16d8bf145619dc23a
refs/heads/master
2020-10-02T06:52:04.948000
2020-03-07T12:15:48
2020-03-07T12:15:48
227,726,052
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package headfirst.Iterator; /** * 菜单迭代器接口 */ public interface MenuIterator { Object next(); boolean hasNext(); }
UTF-8
Java
139
java
MenuIterator.java
Java
[]
null
[]
package headfirst.Iterator; /** * 菜单迭代器接口 */ public interface MenuIterator { Object next(); boolean hasNext(); }
139
0.656
0.656
10
11.5
11.377609
31
false
false
0
0
0
0
0
0
0.3
false
false
4
5c88539ffba66ce857a05d699867ff42c437193e
4,063,039,082,258
62fc323a19529dd95f57c14001cc26833845de57
/src/main/java/com/barclayscard/interview/inventorysystem/transactions/Transactions.java
03ea30473d398675d3441667d88e2bba3dc6354e
[]
no_license
josh66in/inventoryManagementSystem
https://github.com/josh66in/inventoryManagementSystem
47ea3ec77999eb504abbae212ed3a082b4df72e5
f14fa2531b0f75f55dc35abe31ca8000e93a925a
refs/heads/master
2021-04-27T00:15:43.666000
2018-06-29T01:03:52
2018-06-29T01:03:52
123,781,063
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.barclayscard.interview.inventorysystem.transactions; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import com.barclayscard.interview.inventorysystem.core.DatabaseDao; public class Transactions { DatabaseDao db = new DatabaseDao(); //parses each command and directs appropriate action. public void parse(String str) { StringTokenizer stkr = new StringTokenizer(str); while(stkr.hasMoreTokens()) { String st = stkr.nextToken(); switch(st) { case "create": String itemName = stkr.nextToken(); Float costPrice = Float.parseFloat(stkr.nextToken()); Float sellingPrice = Float.parseFloat(stkr.nextToken()); db.create(itemName, costPrice, sellingPrice); break; case "delete": String itemName1 = stkr.nextToken(); db.delete(itemName1); break; case "updateBuy": String itemName2 = stkr.nextToken(); Integer quantity = Integer.parseInt(stkr.nextToken()); db.updateBuy(itemName2, quantity); break; case "updateSell": String itemName3 = stkr.nextToken(); Integer quantity1 = Integer.parseInt(stkr.nextToken()); db.updateSell(itemName3, quantity1); break; case "report": db.report(); break; case "updateSellPrice": String itemName4 = stkr.nextToken(); Float newSellPrice = Float.parseFloat(stkr.nextToken()); db.updateSellPrice(itemName4, newSellPrice); break; default: System.out.println("Cannot locate this case. Ignoring."); break; } } } public DatabaseDao getDb() { return db; } public static void main(String[] args) { Transactions txn = new Transactions(); String str = new String(); while(!str.equalsIgnoreCase("EOF")) { try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } txn.parse(str); } } }
UTF-8
Java
2,133
java
Transactions.java
Java
[]
null
[]
package com.barclayscard.interview.inventorysystem.transactions; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import com.barclayscard.interview.inventorysystem.core.DatabaseDao; public class Transactions { DatabaseDao db = new DatabaseDao(); //parses each command and directs appropriate action. public void parse(String str) { StringTokenizer stkr = new StringTokenizer(str); while(stkr.hasMoreTokens()) { String st = stkr.nextToken(); switch(st) { case "create": String itemName = stkr.nextToken(); Float costPrice = Float.parseFloat(stkr.nextToken()); Float sellingPrice = Float.parseFloat(stkr.nextToken()); db.create(itemName, costPrice, sellingPrice); break; case "delete": String itemName1 = stkr.nextToken(); db.delete(itemName1); break; case "updateBuy": String itemName2 = stkr.nextToken(); Integer quantity = Integer.parseInt(stkr.nextToken()); db.updateBuy(itemName2, quantity); break; case "updateSell": String itemName3 = stkr.nextToken(); Integer quantity1 = Integer.parseInt(stkr.nextToken()); db.updateSell(itemName3, quantity1); break; case "report": db.report(); break; case "updateSellPrice": String itemName4 = stkr.nextToken(); Float newSellPrice = Float.parseFloat(stkr.nextToken()); db.updateSellPrice(itemName4, newSellPrice); break; default: System.out.println("Cannot locate this case. Ignoring."); break; } } } public DatabaseDao getDb() { return db; } public static void main(String[] args) { Transactions txn = new Transactions(); String str = new String(); while(!str.equalsIgnoreCase("EOF")) { try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } txn.parse(str); } } }
2,133
0.64135
0.636662
80
24.6625
20.938566
83
false
false
0
0
0
0
0
0
3.75
false
false
4
20198ea1947e6154f7ee9825b24dd0d597ef2e23
4,063,039,081,154
4d5d1d5ca54a333be0073da34db7e6b9afe0efdb
/JavaCodes/src/OOP/Super_3.java
c1ec34ec19575f5781235cd4abfe50f642802f79
[]
no_license
SeasunAmin/Java_codes
https://github.com/SeasunAmin/Java_codes
f2f8713a7d499aeefb7d63b57e00f2dfdc159766
49cbb9f3fefb68f8c6b7c8c87c787cbf88900dc9
refs/heads/main
2023-08-12T00:43:37.054000
2021-10-03T17:53:15
2021-10-03T17:53:15
413,154,586
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package OOP; public class Super_3 { String color; double wight; Super_3(String c, double w) { color = c; wight = w; } void display() { System.out.println("Color : "+color); System.out.println("Wight : " +wight); } static public class Super_3_Test extends Super_3 { int gear; Super_3_Test(String c, double w, int g) { super(c,w); gear = g; } void display() { super.display(); System.out.println("Gear : "+gear); } } public static void main(String[] args) { Super_3_Test ob = new Super_3_Test("Black",350,5); ob.display(); } }
UTF-8
Java
755
java
Super_3.java
Java
[]
null
[]
package OOP; public class Super_3 { String color; double wight; Super_3(String c, double w) { color = c; wight = w; } void display() { System.out.println("Color : "+color); System.out.println("Wight : " +wight); } static public class Super_3_Test extends Super_3 { int gear; Super_3_Test(String c, double w, int g) { super(c,w); gear = g; } void display() { super.display(); System.out.println("Gear : "+gear); } } public static void main(String[] args) { Super_3_Test ob = new Super_3_Test("Black",350,5); ob.display(); } }
755
0.464901
0.450331
44
16.136364
15.862464
58
false
false
0
0
0
0
0
0
0.454545
false
false
4
63ad702eb1fdd4864793f37a061ddf1a44306e60
25,529,285,658,881
f04a6fdbf1992459493421a627279cfacd24634e
/src/main/java/DandQ/LongestPalindromicSubstring.java
7a30f240aa6370be5ecb2068c5721e6a0d1a734e
[]
no_license
apurva165/dataStructures
https://github.com/apurva165/dataStructures
c7911e28162e3a855bac690aa2330812a523bfea
8ab149968f432e52fec7a966d851179184e44292
refs/heads/master
2020-08-13T21:57:25.476000
2020-04-24T11:51:50
2020-04-24T11:51:50
215,044,095
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DandQ; public class LongestPalindromicSubstring { public static void main(String[] args) { String string = "sadfnsdloiewasdf"; lpsSubString(string, 0, string.length() - 1); } public static int lpsSubString(String str, int startInd, int endInd) { int c1 = 0; if (str.charAt(startInd) == str.charAt(endInd)) { c1 = 1 + lpsSubString(str, startInd + 1, endInd - 1); } int c2 = lpsSubString(str, startInd + 1, endInd); int c3 = lpsSubString(str, startInd, endInd - 1); return Math.max(c1, Math.max(c2, c3)); } }
UTF-8
Java
614
java
LongestPalindromicSubstring.java
Java
[]
null
[]
package DandQ; public class LongestPalindromicSubstring { public static void main(String[] args) { String string = "sadfnsdloiewasdf"; lpsSubString(string, 0, string.length() - 1); } public static int lpsSubString(String str, int startInd, int endInd) { int c1 = 0; if (str.charAt(startInd) == str.charAt(endInd)) { c1 = 1 + lpsSubString(str, startInd + 1, endInd - 1); } int c2 = lpsSubString(str, startInd + 1, endInd); int c3 = lpsSubString(str, startInd, endInd - 1); return Math.max(c1, Math.max(c2, c3)); } }
614
0.596091
0.571661
22
26.863636
25.879608
74
false
false
0
0
0
0
0
0
0.909091
false
false
4
811a36c43d01142b3a5b550827ee91100e1a15c8
9,320,079,068,667
444a65f44f466e27c24661129d3b9cbb1f269181
/lottery-microservice/src/main/java/com/sirmam/lottery/service/StandardLotteryService.java
886314c84fcac471a1a6122b3a8f348252a8019e
[ "MIT" ]
permissive
ismailsirma/MicroserviceDemo
https://github.com/ismailsirma/MicroserviceDemo
c47e4222df88e5b03dcafba5cdce952b9c845a39
82e816aac05446a20cbe8c85f4797c95eb11d64f
refs/heads/main
2023-07-03T07:09:44.962000
2021-08-08T21:40:54
2021-08-08T21:40:54
387,355,745
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sirmam.lottery.service; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Service; @Service @RefreshScope public class StandardLotteryService implements LotteryService { @Value("${lottery.max}") // Application.properties içindeki adı SpELL : Spring Execution LANGUAGE private int lotteryMax; @Value("${lottery.size}") private int lotterySize; @Override public List<Integer> draw() { return ThreadLocalRandom.current().ints(1,lotteryMax).distinct().limit(lotterySize).sorted().boxed() .collect(Collectors.toList()); } }
UTF-8
Java
811
java
StandardLotteryService.java
Java
[]
null
[]
package com.sirmam.lottery.service; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Service; @Service @RefreshScope public class StandardLotteryService implements LotteryService { @Value("${lottery.max}") // Application.properties içindeki adı SpELL : Spring Execution LANGUAGE private int lotteryMax; @Value("${lottery.size}") private int lotterySize; @Override public List<Integer> draw() { return ThreadLocalRandom.current().ints(1,lotteryMax).distinct().limit(lotterySize).sorted().boxed() .collect(Collectors.toList()); } }
811
0.760198
0.758962
27
27.962963
29.220087
102
false
false
0
0
0
0
0
0
1.037037
false
false
4
28fc78151a7cdbbc04018228b6d98e8a714b24b2
10,651,518,917,904
d2cd049cfbe4989eea413ba983661b7be5f53288
/src/main/java/nl/han/ica/ap/purify/module/java/duplicatecode/DuplicatedCodeDetectorVisitor.java
a80db7ef5cf0531ecf3fad9403faecb22dc02f17
[ "MIT" ]
permissive
ArjanO/Purify
https://github.com/ArjanO/Purify
e6baf052bd016698001a4adb5d4c503757a631d2
26b84b46b369055a55041b407371c0656c054f9c
refs/heads/master
2016-09-10T19:18:07.353000
2013-05-29T12:36:16
2013-05-29T12:36:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright (c) 2013 HAN University of Applied Sciences * Arjan Oortgiese * Boyd Hofman * Joëll Portier * Michiel Westerbeek * Tim Waalewijn * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package nl.han.ica.ap.purify.module.java.duplicatecode; import java.util.TreeSet; import org.antlr.v4.runtime.tree.ParseTree; import nl.han.ica.ap.purify.language.java.JavaBaseVisitor; import nl.han.ica.ap.purify.language.java.JavaParser.MemberDeclContext; import nl.han.ica.ap.purify.language.java.JavaParser.MethodBodyContext; import nl.han.ica.ap.purify.language.java.util.MethodUtil; import nl.han.ica.ap.purify.modles.SourceFile; /** * Detect duplicated code. A visitor is used because the visit is handled * self for a method's body. * * @author Arjan */ class DuplicatedCodeDetectorVisitor extends JavaBaseVisitor<Void> { private static final int MassThreshold = 15; private static final float SimilarityThreshold = 0.98f; private HashVisitor hashVisitor; private HashBucket hashBucket; private SourceFile sourceFile; /** * Duplicated code detector. */ public DuplicatedCodeDetectorVisitor() { hashBucket = new HashBucket(); } public void setSourceFile(SourceFile sourceFile) { this.sourceFile = sourceFile; } /** * Get the detected clones. * * @return {@link Clones} with all the detected clones. */ public Clones getClones() { Clones result = new Clones(); TreeSet<HashBucketElement> candidates = hashBucket.getDuplicates(); for (HashBucketElement candidate : candidates) { for (int i = 1; i < candidate.size(); i++) { ParseTree left = candidate.get(i - 1).getParseTree(); ParseTree right = candidate.get(i).getParseTree(); ParseTreeSimilarity similarity = new ParseTreeSimilarity( left, right); if (similarity.getSimilarity() > SimilarityThreshold) { result.addClonePair(candidate.get(i - 1), candidate.get(i)); } } } return result; } /** * Called when a class member is declared this are global variables and * methods. */ @Override public Void visitMemberDecl(MemberDeclContext ctx) { TreeSet<String> localVariables = MethodUtil.getLocalVariables(ctx); hashVisitor = new HashVisitor(localVariables); return super.visitMemberDecl(ctx); } /** * Called when a method body is the visited. This is the point where * the visit is handled by this class. This is done by not calling * {@code super.visitMethodBody(ctx);} or {@code visitChildren(ctx);} */ @Override public Void visitMethodBody(MethodBodyContext ctx) { hashSubtrees(ctx); return null; // The type Void require a return. } /** * Hash all the subtrees and add the hash to the hash bucket. * * @param tree Subtree to hash. */ private void hashSubtrees(ParseTree tree) { int mass = mass(tree); if (mass >= MassThreshold) { // Ignores small subtrees. for (int i = tree.getChildCount() - 1; i >= 0; i--) { hashSubtrees(tree.getChild(i)); } int iHash = hashVisitor.visit(tree); Clone candidate = new Clone(sourceFile, tree); hashBucket.put(iHash, candidate, mass); } } /** * Get the tree mass this is the number nodes. * * @param tree ParseTree * @return Number of nodes in the tree. */ private int mass(ParseTree tree) { int iChilderen = tree.getChildCount(); if (iChilderen > 0) { for (int i = tree.getChildCount() - 1; i >= 0; i--) { iChilderen += mass(tree.getChild(i)); } } return iChilderen; } }
UTF-8
Java
4,563
java
DuplicatedCodeDetectorVisitor.java
Java
[ { "context": "ght (c) 2013 HAN University of Applied Sciences\n * Arjan Oortgiese\n * Boyd Hofman\n * Joëll Portier\n * Michiel Wester", "end": 79, "score": 0.9998723268508911, "start": 64, "tag": "NAME", "value": "Arjan Oortgiese" }, { "context": "iversity of Applied Sciences\n * Arjan Oortgiese\n * Boyd Hofman\n * Joëll Portier\n * Michiel Westerbeek\n * Tim Waa", "end": 94, "score": 0.9998464584350586, "start": 83, "tag": "NAME", "value": "Boyd Hofman" }, { "context": "lied Sciences\n * Arjan Oortgiese\n * Boyd Hofman\n * Joëll Portier\n * Michiel Westerbeek\n * Tim Waalewijn\n * \n * Per", "end": 111, "score": 0.9998464584350586, "start": 98, "tag": "NAME", "value": "Joëll Portier" }, { "context": "Arjan Oortgiese\n * Boyd Hofman\n * Joëll Portier\n * Michiel Westerbeek\n * Tim Waalewijn\n * \n * Permission is hereby gran", "end": 133, "score": 0.9998570680618286, "start": 115, "tag": "NAME", "value": "Michiel Westerbeek" }, { "context": "d Hofman\n * Joëll Portier\n * Michiel Westerbeek\n * Tim Waalewijn\n * \n * Permission is hereby granted, free of char", "end": 150, "score": 0.9998536705970764, "start": 137, "tag": "NAME", "value": "Tim Waalewijn" }, { "context": "led \n * self for a method's body. \n * \n * @author Arjan\n */\nclass DuplicatedCodeDetectorVisitor extends J", "end": 1811, "score": 0.9998748302459717, "start": 1806, "tag": "NAME", "value": "Arjan" } ]
null
[]
/** * Copyright (c) 2013 HAN University of Applied Sciences * <NAME> * <NAME> * <NAME> * <NAME> * <NAME> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package nl.han.ica.ap.purify.module.java.duplicatecode; import java.util.TreeSet; import org.antlr.v4.runtime.tree.ParseTree; import nl.han.ica.ap.purify.language.java.JavaBaseVisitor; import nl.han.ica.ap.purify.language.java.JavaParser.MemberDeclContext; import nl.han.ica.ap.purify.language.java.JavaParser.MethodBodyContext; import nl.han.ica.ap.purify.language.java.util.MethodUtil; import nl.han.ica.ap.purify.modles.SourceFile; /** * Detect duplicated code. A visitor is used because the visit is handled * self for a method's body. * * @author Arjan */ class DuplicatedCodeDetectorVisitor extends JavaBaseVisitor<Void> { private static final int MassThreshold = 15; private static final float SimilarityThreshold = 0.98f; private HashVisitor hashVisitor; private HashBucket hashBucket; private SourceFile sourceFile; /** * Duplicated code detector. */ public DuplicatedCodeDetectorVisitor() { hashBucket = new HashBucket(); } public void setSourceFile(SourceFile sourceFile) { this.sourceFile = sourceFile; } /** * Get the detected clones. * * @return {@link Clones} with all the detected clones. */ public Clones getClones() { Clones result = new Clones(); TreeSet<HashBucketElement> candidates = hashBucket.getDuplicates(); for (HashBucketElement candidate : candidates) { for (int i = 1; i < candidate.size(); i++) { ParseTree left = candidate.get(i - 1).getParseTree(); ParseTree right = candidate.get(i).getParseTree(); ParseTreeSimilarity similarity = new ParseTreeSimilarity( left, right); if (similarity.getSimilarity() > SimilarityThreshold) { result.addClonePair(candidate.get(i - 1), candidate.get(i)); } } } return result; } /** * Called when a class member is declared this are global variables and * methods. */ @Override public Void visitMemberDecl(MemberDeclContext ctx) { TreeSet<String> localVariables = MethodUtil.getLocalVariables(ctx); hashVisitor = new HashVisitor(localVariables); return super.visitMemberDecl(ctx); } /** * Called when a method body is the visited. This is the point where * the visit is handled by this class. This is done by not calling * {@code super.visitMethodBody(ctx);} or {@code visitChildren(ctx);} */ @Override public Void visitMethodBody(MethodBodyContext ctx) { hashSubtrees(ctx); return null; // The type Void require a return. } /** * Hash all the subtrees and add the hash to the hash bucket. * * @param tree Subtree to hash. */ private void hashSubtrees(ParseTree tree) { int mass = mass(tree); if (mass >= MassThreshold) { // Ignores small subtrees. for (int i = tree.getChildCount() - 1; i >= 0; i--) { hashSubtrees(tree.getChild(i)); } int iHash = hashVisitor.visit(tree); Clone candidate = new Clone(sourceFile, tree); hashBucket.put(iHash, candidate, mass); } } /** * Get the tree mass this is the number nodes. * * @param tree ParseTree * @return Number of nodes in the tree. */ private int mass(ParseTree tree) { int iChilderen = tree.getChildCount(); if (iChilderen > 0) { for (int i = tree.getChildCount() - 1; i >= 0; i--) { iChilderen += mass(tree.getChild(i)); } } return iChilderen; } }
4,522
0.709776
0.705831
156
28.243589
25.398964
74
false
false
0
0
0
0
0
0
1.692308
false
false
4
52652318e88244ebea34a917be72705415977583
34,041,910,797,678
73223ed8173182be0f325d544d47adc07e1577ae
/src/main/java/com/starwars/starwarsplanets/services/FilmService.java
f462b3ee0fb166fe2cd1a06103f476127d98322a
[]
no_license
LucasRedigolo/StarWarsPlanetsApi
https://github.com/LucasRedigolo/StarWarsPlanetsApi
3a983a7a0f6d84cdb221df7e0090e20dfb2308d7
4bf24c561dc7e1ceb678e339caeacbd1388a27c6
refs/heads/master
2023-04-28T06:22:36.465000
2021-05-11T01:19:17
2021-05-11T01:19:17
366,204,861
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.starwars.starwarsplanets.services; import com.starwars.starwarsplanets.document.Film; import java.util.List; public interface FilmService { List<Film> listAll() throws Exception; }
UTF-8
Java
203
java
FilmService.java
Java
[]
null
[]
package com.starwars.starwarsplanets.services; import com.starwars.starwarsplanets.document.Film; import java.util.List; public interface FilmService { List<Film> listAll() throws Exception; }
203
0.783251
0.783251
12
15.916667
19.779865
50
false
false
0
0
0
0
0
0
0.333333
false
false
4
335ffeac6a94ca406e50ff94bd9c3499d25fd2e1
2,430,951,510,139
1e9b997b486cb9852ff636e53a8e3f46d14f0ed6
/ITpart1/Chapter09/src/Problem01.java
3cf103c09740afc54ae4a44aa62ad155f6f51bdf
[]
no_license
i-todorov91/ITtalents
https://github.com/i-todorov91/ITtalents
62105bea5f9fb81e52cd622efe5318d3013aba7e
7e376a3fa81bb23c689df7ec92e5e7edeb29e9b5
refs/heads/master
2021-01-23T08:03:50.574000
2017-02-13T19:32:34
2017-02-13T19:32:34
80,522,493
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Problem01 { public static void main(String[] args) { String firstWord = "uchilishe"; String secondWord = "uchenik"; String temp = firstWord.substring(0, 5); firstWord = firstWord.replace(temp, secondWord.substring(0, 5)); secondWord = secondWord.replace(secondWord.substring(0, 5), temp); if (firstWord.length() < secondWord.length()) { System.out.println(secondWord.length() + " " + secondWord); } else { System.out.println(firstWord.length() + " " + firstWord); } } }
UTF-8
Java
521
java
Problem01.java
Java
[ { "context": "id main(String[] args) {\n\t\t\n\t\tString firstWord = \"uchilishe\";\n\t\tString secondWord = \"uchenik\";\n\t\t\n\t\tStr", "end": 97, "score": 0.4328562617301941, "start": 94, "tag": "USERNAME", "value": "uch" }, { "context": "main(String[] args) {\n\t\t\n\t\tString firstWord = \"uchilishe\";\n\t\tString secondWord = \"uchenik\";\n\t\t\n\t\tStrin", "end": 99, "score": 0.3602888882160187, "start": 97, "tag": "PASSWORD", "value": "il" }, { "context": "in(String[] args) {\n\t\t\n\t\tString firstWord = \"uchilishe\";\n\t\tString secondWord = \"uchenik\";\n\t\t\n\t\tString te", "end": 103, "score": 0.46104246377944946, "start": 99, "tag": "USERNAME", "value": "ishe" }, { "context": "g firstWord = \"uchilishe\";\n\t\tString secondWord = \"uchenik\";\n\t\t\n\t\tString temp = firstWord.substring(0, 5", "end": 132, "score": 0.367168128490448, "start": 129, "tag": "NAME", "value": "uch" }, { "context": "irstWord = \"uchilishe\";\n\t\tString secondWord = \"uchenik\";\n\t\t\n\t\tString temp = firstWord.substring(0, 5);", "end": 134, "score": 0.4904809296131134, "start": 132, "tag": "PASSWORD", "value": "en" }, { "context": "stWord = \"uchilishe\";\n\t\tString secondWord = \"uchenik\";\n\t\t\n\t\tString temp = firstWord.substring(0, 5);\n\t", "end": 136, "score": 0.35932260751724243, "start": 134, "tag": "USERNAME", "value": "ik" } ]
null
[]
public class Problem01 { public static void main(String[] args) { String firstWord = "uchilishe"; String secondWord = "uchenik"; String temp = firstWord.substring(0, 5); firstWord = firstWord.replace(temp, secondWord.substring(0, 5)); secondWord = secondWord.replace(secondWord.substring(0, 5), temp); if (firstWord.length() < secondWord.length()) { System.out.println(secondWord.length() + " " + secondWord); } else { System.out.println(firstWord.length() + " " + firstWord); } } }
521
0.667946
0.652591
19
26.368422
25.003601
68
false
false
0
0
0
0
0
0
2.315789
false
false
4
0f709eb5fdbd00ca691d21c56d16faf337fc93bf
34,686,155,887,640
7a5aefd078421eef80fe5301fc6900e6a5b5fa01
/notifications/src/main/java/org/dominokit/domino/notifications/client/views/ui/NotificationsViewImpl.java
5c0ab6db5cee970d493bccc978902e333cc72bab
[]
no_license
ibaca/domino-ui-demo
https://github.com/ibaca/domino-ui-demo
cec674130ad7aa9421741f5ec4005d43f86c4f43
86ace39552e9c938189bb6d6b0f84d4143936a3e
refs/heads/master
2020-03-26T00:06:10.436000
2018-08-09T11:35:20
2018-08-09T11:35:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.dominokit.domino.notifications.client.views.ui; import org.dominokit.domino.api.client.annotations.UiView; import org.dominokit.domino.componentcase.shared.extension.ComponentView; import org.dominokit.domino.notifications.client.presenters.NotificationsPresenter; import org.dominokit.domino.notifications.client.views.CodeResource; import org.dominokit.domino.notifications.client.views.NotificationsView; import org.dominokit.domino.ui.animations.Transition; import org.dominokit.domino.ui.button.Button; import org.dominokit.domino.ui.cards.Card; import org.dominokit.domino.ui.column.Column; import org.dominokit.domino.ui.header.BlockHeader; import org.dominokit.domino.ui.notifications.Notification; import org.dominokit.domino.ui.row.Row; import elemental2.dom.HTMLDivElement; import org.dominokit.domino.ui.style.Color; import static org.jboss.gwt.elemento.core.Elements.a; import static org.jboss.gwt.elemento.core.Elements.div; @UiView(presentable = NotificationsPresenter.class) public class NotificationsViewImpl extends ComponentView<HTMLDivElement> implements NotificationsView { private HTMLDivElement element = div().asElement(); private final Column column = Column.create() .onLarge(Column.OnLarge.two) .onMedium(Column.OnMedium.two) .onSmall(Column.OnSmall.twelve) .onXSmall(Column.OnXSmall.twelve); @Override public HTMLDivElement getElement() { return element; } @Override public void init() { element.appendChild(BlockHeader.create("NOTIFICATIONS", "Taken by Bootstrap Notification ") .appendContent(a().attr("href", "https://github.com/mouse0270/bootstrap-notify") .attr("target", "_blank") .textContent("github.com/mouse0270/bootstrap-notify").asElement()) .asElement()); notificationsPosition(); notificationsTypes(); withMaterialColors(); withAnimation(); } private void notificationsPosition() { Button topLeft = Button.createPrimary("TOP LEFT").large(); topLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.TOP_LEFT) .show()); Button topCenter = Button.createPrimary("TOP CENTER").large(); topCenter.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.TOP_CENTER) .show()); Button topRight = Button.createPrimary("TOP RIGHT").large(); topRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.TOP_RIGHT) .show()); Button bottomLeft = Button.createPrimary("BOTTOM LEFT").large(); bottomLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.BOTTOM_LEFT) .show()); Button bottomCenter = Button.createPrimary("BOTTOM CENTER").large(); bottomCenter.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.BOTTOM_CENTER) .show()); Button bottomRight = Button.createPrimary("BOTTOM RIGHT").large(); bottomRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.BOTTOM_RIGHT) .show()); element.appendChild(Card.create("NOTIFICATION POSITIONS") .appendContent(Row.create() .addColumn(column.copy().addElement(topLeft.block().asElement())) .addColumn(column.copy().addElement(topCenter.block().asElement())) .addColumn(column.copy().addElement(topRight.block().asElement())) .addColumn(column.copy().addElement(bottomLeft.block().asElement())) .addColumn(column.copy().addElement(bottomCenter.block().asElement())) .addColumn(column.copy().addElement(bottomRight.block().asElement())) .asElement()) .asElement()); element.appendChild(Card.createCodeCard(CodeResource.INSTANCE.notificationsPosition()) .asElement()); } private void notificationsTypes() { Button danger = Button.createDanger("DANGER").large(); danger.getClickableElement().addEventListener("click", e -> Notification.createDanger("You received a message") .setPosition(Notification.TOP_LEFT) .show()); Button success = Button.createSuccess("SUCCESS").large(); success.getClickableElement().addEventListener("click", e -> Notification.createSuccess("You received a message") .setPosition(Notification.TOP_LEFT) .show()); Button warning = Button.createWarning("WARNING").large(); warning.getClickableElement().addEventListener("click", e -> Notification.createWarning("You received a message") .setPosition(Notification.TOP_LEFT) .show()); Button info = Button.createInfo("INFO").large(); info.getClickableElement().addEventListener("click", e -> Notification.createInfo("You received a message") .setPosition(Notification.TOP_LEFT) .show()); element.appendChild(Card.create("NOTIFICATION TYPES", "Use predefined notification styles.") .appendContent(Row.create() .addColumn(column.copy().addElement(danger.block().asElement())) .addColumn(column.copy().addElement(success.block().asElement())) .addColumn(column.copy().addElement(warning.block().asElement())) .addColumn(column.copy().addElement(info.block().asElement())) .asElement()) .asElement()); element.appendChild(Card.createCodeCard(CodeResource.INSTANCE.notificationsTypes()) .asElement()); } private void withMaterialColors() { Button redButton = Button.create("RED").setBackground(Color.RED).large(); redButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.RED) .setPosition(Notification.TOP_LEFT) .show()); Button greenButton = Button.create("GREEN").setBackground(Color.GREEN).large(); greenButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.GREEN) .setPosition(Notification.TOP_LEFT) .show()); Button orangeButton = Button.create("ORANGE").setBackground(Color.ORANGE).large(); orangeButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.ORANGE) .setPosition(Notification.TOP_LEFT) .show()); Button blueButton = Button.create("BLUE").setBackground(Color.BLUE).large(); blueButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.BLUE) .setPosition(Notification.TOP_LEFT) .show()); Button tealButton = Button.create("TEAL").setBackground(Color.TEAL).large(); tealButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.TEAL) .setPosition(Notification.TOP_LEFT) .show()); Button cyanButton = Button.create("CYAN").setBackground(Color.CYAN).large(); cyanButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.CYAN) .setPosition(Notification.TOP_LEFT) .show()); Button pinkButton = Button.create("PINK").setBackground(Color.PINK).large(); pinkButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.PINK) .setPosition(Notification.TOP_LEFT) .show()); Button purpleButton = Button.create("PURPLE").setBackground(Color.PURPLE).large(); purpleButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.PURPLE) .setPosition(Notification.TOP_LEFT) .show()); Button blueGreyButton = Button.create("BLUE GREY").setBackground(Color.BLUE_GREY).large(); blueGreyButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.BLUE_GREY) .setPosition(Notification.TOP_LEFT) .show()); Button deepOrangeButton = Button.create("DEEP ORANGE").setBackground(Color.DEEP_ORANGE).large(); deepOrangeButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.DEEP_ORANGE) .setPosition(Notification.TOP_LEFT) .show()); Button lightGreenButton = Button.create("LIGHT GREEN").setBackground(Color.LIGHT_GREEN).large(); lightGreenButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.LIGHT_GREEN) .setPosition(Notification.TOP_LEFT) .show()); Button blackButton = Button.create("BLACK").setBackground(Color.BLACK).large(); blackButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.BLACK) .setPosition(Notification.TOP_LEFT) .show()); element.appendChild(Card.create("WITH MATERIAL DESIGN COLORS") .appendContent(Row.create() .addColumn(column.copy().addElement(redButton.block().asElement())) .addColumn(column.copy().addElement(greenButton.block().asElement())) .addColumn(column.copy().addElement(orangeButton.block().asElement())) .addColumn(column.copy().addElement(blueButton.block().asElement())) .addColumn(column.copy().addElement(tealButton.block().asElement())) .addColumn(column.copy().addElement(cyanButton.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(pinkButton.block().asElement())) .addColumn(column.copy().addElement(purpleButton.block().asElement())) .addColumn(column.copy().addElement(blueGreyButton.block().asElement())) .addColumn(column.copy().addElement(deepOrangeButton.block().asElement())) .addColumn(column.copy().addElement(lightGreenButton.block().asElement())) .addColumn(column.copy().addElement(blackButton.block().asElement())) .asElement()) .asElement()); element.appendChild(Card.createCodeCard(CodeResource.INSTANCE.withMaterialColors()) .asElement()); } private void withAnimation() { Button fadeInOut = Button.create("FADE IN OUT").setBackground(Color.PINK).large(); fadeInOut.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FADE_IN) .outTransition(Transition.FADE_OUT) .setPosition(Notification.TOP_LEFT) .show()); Button fadeInOutLeft = Button.create("FADE IN OU LEFT").setBackground(Color.PINK).large(); fadeInOutLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FADE_IN_LEFT) .outTransition(Transition.FADE_OUT_LEFT) .setPosition(Notification.TOP_LEFT) .show()); Button fadeInOutRight = Button.create("FADE IN OUT RIGHT").setBackground(Color.PINK).large(); fadeInOutRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FADE_IN_RIGHT) .outTransition(Transition.FADE_OUT_RIGHT) .setPosition(Notification.TOP_RIGHT) .show()); Button fadeInOutUp = Button.create("FADE IN OUT UP").setBackground(Color.PINK).large(); fadeInOutUp.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FADE_IN_UP) .outTransition(Transition.FADE_OUT_UP) .setPosition(Notification.TOP_CENTER) .show()); Button fadeInOutDown = Button.create("FADE IN OUT DOWN").setBackground(Color.PINK).large(); fadeInOutDown.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FADE_IN_DOWN) .outTransition(Transition.FADE_OUT_DOWN) .setPosition(Notification.TOP_LEFT) .show()); Button bouneInOut = Button.create("BOUNCE IN OUT").setBackground(Color.CYAN).large(); bouneInOut.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.BOUNCE_IN) .outTransition(Transition.BOUNCE_OUT) .setPosition(Notification.TOP_LEFT) .show()); Button bounceInOutLeft = Button.create("BOUNCE IN OUT LEFT").setBackground(Color.CYAN).large(); bounceInOutLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.BOUNCE_IN_LEFT) .outTransition(Transition.BOUNCE_OUT_LEFT) .setPosition(Notification.TOP_LEFT) .show()); Button bounceInOutRight = Button.create("BOUNCE IN OUT RIGHT").setBackground(Color.CYAN).large(); bounceInOutRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.BOUNCE_IN_RIGHT) .outTransition(Transition.BOUNCE_OUT_RIGHT) .setPosition(Notification.TOP_RIGHT) .show()); Button bounceInOutUp = Button.create("BOUNCE IN OUT UP").setBackground(Color.CYAN).large(); bounceInOutUp.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.BOUNCE_IN_UP) .outTransition(Transition.BOUNCE_OUT_UP) .setPosition(Notification.TOP_CENTER) .show()); Button bounceInOutDown = Button.create("BOUNCE IN OUT DOWN").setBackground(Color.CYAN).large(); bounceInOutDown.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.BOUNCE_IN_DOWN) .outTransition(Transition.BOUNCE_OUT_DOWN) .setPosition(Notification.TOP_CENTER) .show()); Button rotateInOut = Button.create("ROTATE IN OUT").setBackground(Color.LIGHT_GREEN).large(); rotateInOut.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ROTATE_IN) .outTransition(Transition.ROTATE_OUT) .setPosition(Notification.TOP_LEFT) .show()); Button rotateInOutUpLeft = Button.create("ROTATE IN OUT UP LEFT").setBackground(Color.LIGHT_GREEN).large(); rotateInOutUpLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ROTATE_IN_UP_LEFT) .outTransition(Transition.ROTATE_OUT_UP_LEFT) .setPosition(Notification.TOP_LEFT) .show()); Button rotateInOutUpRight = Button.create("ROTATE IN OUT UP RIGHT").setBackground(Color.LIGHT_GREEN).large(); rotateInOutUpRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ROTATE_IN_UP_RIGHT) .outTransition(Transition.ROTATE_OUT_UP_RIGHT) .setPosition(Notification.TOP_LEFT) .show()); Button rotateInOutDownLeft = Button.create("ROTATE IN OUT DOWN LEFT").setBackground(Color.LIGHT_GREEN).large(); rotateInOutDownLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ROTATE_IN_DOWN_LEFT) .outTransition(Transition.ROTATE_OUT_DOWN_LEFT) .setPosition(Notification.TOP_LEFT) .show()); Button rotateInOutDownRight = Button.create("ROTATE IN OUT DOWN RIGHT").setBackground(Color.LIGHT_GREEN).large(); rotateInOutDownRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ROTATE_IN_DOWN_RIGHT) .outTransition(Transition.ROTATE_OUT_DOWN_RIGHT) .setPosition(Notification.TOP_LEFT) .show()); Button zoomInOut = Button.create("ZOOM IN OUT").setBackground(Color.TEAL).large(); zoomInOut.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ZOOM_IN) .outTransition(Transition.ZOOM_OUT) .setPosition(Notification.TOP_RIGHT) .show()); Button zoomInOutLeft = Button.create("ZOOM IN OUT LEFT").setBackground(Color.TEAL).large(); zoomInOutLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ZOOM_IN_LEFT) .outTransition(Transition.ZOOM_OUT_LEFT) .setPosition(Notification.TOP_RIGHT) .show()); Button zoomInOutRight = Button.create("ZOOM IN OUT RIGHT").setBackground(Color.TEAL).large(); zoomInOutRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ZOOM_IN_RIGHT) .outTransition(Transition.ZOOM_OUT_RIGHT) .setPosition(Notification.TOP_RIGHT) .show()); Button zoomInOutUp = Button.create("ZOOM IN OUT UP").setBackground(Color.TEAL).large(); zoomInOutUp.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ZOOM_IN_UP) .outTransition(Transition.ZOOM_OUT_UP) .setPosition(Notification.TOP_RIGHT) .show()); Button zoomInOutDown = Button.create("ZOOM IN OUT DOWN").setBackground(Color.TEAL).large(); zoomInOutDown.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ZOOM_IN_DOWN) .outTransition(Transition.ZOOM_OUT_DOWN) .setPosition(Notification.TOP_RIGHT) .show()); Button flipInOutX = Button.create("FLIP IN OUT X").setBackground(Color.PURPLE).large(); flipInOutX.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FLIP_IN_X) .outTransition(Transition.FLIP_OUT_X) .setPosition(Notification.BOTTOM_LEFT) .show()); Button flipInOutY = Button.create("FLIP IN OUT Y").setBackground(Color.PURPLE).large(); flipInOutY.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FLIP_IN_Y) .outTransition(Transition.FLIP_OUT_Y) .setPosition(Notification.BOTTOM_RIGHT) .show()); Button lightSpeedInOut = Button.create("LIGHT SPEED IN OUT").setBackground(Color.INDIGO).large(); lightSpeedInOut.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.LIGHT_SPEED_IN) .outTransition(Transition.LIGHT_SPEED_OUT) .setPosition(Notification.TOP_CENTER) .show()); element.appendChild(Card.create("NOTIFICATION ANIMATIONS") .appendContent(Row.create() .addColumn(column.copy().addElement(fadeInOut.block().asElement())) .addColumn(column.copy().addElement(fadeInOutLeft.block().asElement())) .addColumn(column.copy().addElement(fadeInOutRight.block().asElement())) .addColumn(column.copy().addElement(fadeInOutUp.block().asElement())) .addColumn(column.copy().addElement(fadeInOutDown.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(bouneInOut.block().asElement())) .addColumn(column.copy().addElement(bounceInOutLeft.block().asElement())) .addColumn(column.copy().addElement(bounceInOutRight.block().asElement())) .addColumn(column.copy().addElement(bounceInOutUp.block().asElement())) .addColumn(column.copy().addElement(bounceInOutDown.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(rotateInOut.block().asElement())) .addColumn(column.copy().addElement(rotateInOutUpLeft.block().asElement())) .addColumn(column.copy().addElement(rotateInOutUpRight.block().asElement())) .addColumn(column.copy().addElement(rotateInOutDownLeft.block().asElement())) .addColumn(column.copy().addElement(rotateInOutDownRight.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(zoomInOut.block().asElement())) .addColumn(column.copy().addElement(zoomInOutLeft.block().asElement())) .addColumn(column.copy().addElement(zoomInOutRight.block().asElement())) .addColumn(column.copy().addElement(zoomInOutUp.block().asElement())) .addColumn(column.copy().addElement(zoomInOutDown.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(flipInOutX.block().asElement())) .addColumn(column.copy().addElement(flipInOutY.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(lightSpeedInOut.block().asElement())) .asElement()) .asElement()); element.appendChild(Card.createCodeCard(CodeResource.INSTANCE.withAnimation()) .asElement()); } }
UTF-8
Java
26,395
java
NotificationsViewImpl.java
Java
[ { "context": "ppendContent(a().attr(\"href\", \"https://github.com/mouse0270/bootstrap-notify\")\n .attr(", "end": 1696, "score": 0.9993883967399597, "start": 1687, "tag": "USERNAME", "value": "mouse0270" }, { "context": "\n .textContent(\"github.com/mouse0270/bootstrap-notify\").asElement())\n .", "end": 1824, "score": 0.9994760751724243, "start": 1815, "tag": "USERNAME", "value": "mouse0270" } ]
null
[]
package org.dominokit.domino.notifications.client.views.ui; import org.dominokit.domino.api.client.annotations.UiView; import org.dominokit.domino.componentcase.shared.extension.ComponentView; import org.dominokit.domino.notifications.client.presenters.NotificationsPresenter; import org.dominokit.domino.notifications.client.views.CodeResource; import org.dominokit.domino.notifications.client.views.NotificationsView; import org.dominokit.domino.ui.animations.Transition; import org.dominokit.domino.ui.button.Button; import org.dominokit.domino.ui.cards.Card; import org.dominokit.domino.ui.column.Column; import org.dominokit.domino.ui.header.BlockHeader; import org.dominokit.domino.ui.notifications.Notification; import org.dominokit.domino.ui.row.Row; import elemental2.dom.HTMLDivElement; import org.dominokit.domino.ui.style.Color; import static org.jboss.gwt.elemento.core.Elements.a; import static org.jboss.gwt.elemento.core.Elements.div; @UiView(presentable = NotificationsPresenter.class) public class NotificationsViewImpl extends ComponentView<HTMLDivElement> implements NotificationsView { private HTMLDivElement element = div().asElement(); private final Column column = Column.create() .onLarge(Column.OnLarge.two) .onMedium(Column.OnMedium.two) .onSmall(Column.OnSmall.twelve) .onXSmall(Column.OnXSmall.twelve); @Override public HTMLDivElement getElement() { return element; } @Override public void init() { element.appendChild(BlockHeader.create("NOTIFICATIONS", "Taken by Bootstrap Notification ") .appendContent(a().attr("href", "https://github.com/mouse0270/bootstrap-notify") .attr("target", "_blank") .textContent("github.com/mouse0270/bootstrap-notify").asElement()) .asElement()); notificationsPosition(); notificationsTypes(); withMaterialColors(); withAnimation(); } private void notificationsPosition() { Button topLeft = Button.createPrimary("TOP LEFT").large(); topLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.TOP_LEFT) .show()); Button topCenter = Button.createPrimary("TOP CENTER").large(); topCenter.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.TOP_CENTER) .show()); Button topRight = Button.createPrimary("TOP RIGHT").large(); topRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.TOP_RIGHT) .show()); Button bottomLeft = Button.createPrimary("BOTTOM LEFT").large(); bottomLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.BOTTOM_LEFT) .show()); Button bottomCenter = Button.createPrimary("BOTTOM CENTER").large(); bottomCenter.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.BOTTOM_CENTER) .show()); Button bottomRight = Button.createPrimary("BOTTOM RIGHT").large(); bottomRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setPosition(Notification.BOTTOM_RIGHT) .show()); element.appendChild(Card.create("NOTIFICATION POSITIONS") .appendContent(Row.create() .addColumn(column.copy().addElement(topLeft.block().asElement())) .addColumn(column.copy().addElement(topCenter.block().asElement())) .addColumn(column.copy().addElement(topRight.block().asElement())) .addColumn(column.copy().addElement(bottomLeft.block().asElement())) .addColumn(column.copy().addElement(bottomCenter.block().asElement())) .addColumn(column.copy().addElement(bottomRight.block().asElement())) .asElement()) .asElement()); element.appendChild(Card.createCodeCard(CodeResource.INSTANCE.notificationsPosition()) .asElement()); } private void notificationsTypes() { Button danger = Button.createDanger("DANGER").large(); danger.getClickableElement().addEventListener("click", e -> Notification.createDanger("You received a message") .setPosition(Notification.TOP_LEFT) .show()); Button success = Button.createSuccess("SUCCESS").large(); success.getClickableElement().addEventListener("click", e -> Notification.createSuccess("You received a message") .setPosition(Notification.TOP_LEFT) .show()); Button warning = Button.createWarning("WARNING").large(); warning.getClickableElement().addEventListener("click", e -> Notification.createWarning("You received a message") .setPosition(Notification.TOP_LEFT) .show()); Button info = Button.createInfo("INFO").large(); info.getClickableElement().addEventListener("click", e -> Notification.createInfo("You received a message") .setPosition(Notification.TOP_LEFT) .show()); element.appendChild(Card.create("NOTIFICATION TYPES", "Use predefined notification styles.") .appendContent(Row.create() .addColumn(column.copy().addElement(danger.block().asElement())) .addColumn(column.copy().addElement(success.block().asElement())) .addColumn(column.copy().addElement(warning.block().asElement())) .addColumn(column.copy().addElement(info.block().asElement())) .asElement()) .asElement()); element.appendChild(Card.createCodeCard(CodeResource.INSTANCE.notificationsTypes()) .asElement()); } private void withMaterialColors() { Button redButton = Button.create("RED").setBackground(Color.RED).large(); redButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.RED) .setPosition(Notification.TOP_LEFT) .show()); Button greenButton = Button.create("GREEN").setBackground(Color.GREEN).large(); greenButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.GREEN) .setPosition(Notification.TOP_LEFT) .show()); Button orangeButton = Button.create("ORANGE").setBackground(Color.ORANGE).large(); orangeButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.ORANGE) .setPosition(Notification.TOP_LEFT) .show()); Button blueButton = Button.create("BLUE").setBackground(Color.BLUE).large(); blueButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.BLUE) .setPosition(Notification.TOP_LEFT) .show()); Button tealButton = Button.create("TEAL").setBackground(Color.TEAL).large(); tealButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.TEAL) .setPosition(Notification.TOP_LEFT) .show()); Button cyanButton = Button.create("CYAN").setBackground(Color.CYAN).large(); cyanButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.CYAN) .setPosition(Notification.TOP_LEFT) .show()); Button pinkButton = Button.create("PINK").setBackground(Color.PINK).large(); pinkButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.PINK) .setPosition(Notification.TOP_LEFT) .show()); Button purpleButton = Button.create("PURPLE").setBackground(Color.PURPLE).large(); purpleButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.PURPLE) .setPosition(Notification.TOP_LEFT) .show()); Button blueGreyButton = Button.create("BLUE GREY").setBackground(Color.BLUE_GREY).large(); blueGreyButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.BLUE_GREY) .setPosition(Notification.TOP_LEFT) .show()); Button deepOrangeButton = Button.create("DEEP ORANGE").setBackground(Color.DEEP_ORANGE).large(); deepOrangeButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.DEEP_ORANGE) .setPosition(Notification.TOP_LEFT) .show()); Button lightGreenButton = Button.create("LIGHT GREEN").setBackground(Color.LIGHT_GREEN).large(); lightGreenButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.LIGHT_GREEN) .setPosition(Notification.TOP_LEFT) .show()); Button blackButton = Button.create("BLACK").setBackground(Color.BLACK).large(); blackButton.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .setBackground(Color.BLACK) .setPosition(Notification.TOP_LEFT) .show()); element.appendChild(Card.create("WITH MATERIAL DESIGN COLORS") .appendContent(Row.create() .addColumn(column.copy().addElement(redButton.block().asElement())) .addColumn(column.copy().addElement(greenButton.block().asElement())) .addColumn(column.copy().addElement(orangeButton.block().asElement())) .addColumn(column.copy().addElement(blueButton.block().asElement())) .addColumn(column.copy().addElement(tealButton.block().asElement())) .addColumn(column.copy().addElement(cyanButton.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(pinkButton.block().asElement())) .addColumn(column.copy().addElement(purpleButton.block().asElement())) .addColumn(column.copy().addElement(blueGreyButton.block().asElement())) .addColumn(column.copy().addElement(deepOrangeButton.block().asElement())) .addColumn(column.copy().addElement(lightGreenButton.block().asElement())) .addColumn(column.copy().addElement(blackButton.block().asElement())) .asElement()) .asElement()); element.appendChild(Card.createCodeCard(CodeResource.INSTANCE.withMaterialColors()) .asElement()); } private void withAnimation() { Button fadeInOut = Button.create("FADE IN OUT").setBackground(Color.PINK).large(); fadeInOut.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FADE_IN) .outTransition(Transition.FADE_OUT) .setPosition(Notification.TOP_LEFT) .show()); Button fadeInOutLeft = Button.create("FADE IN OU LEFT").setBackground(Color.PINK).large(); fadeInOutLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FADE_IN_LEFT) .outTransition(Transition.FADE_OUT_LEFT) .setPosition(Notification.TOP_LEFT) .show()); Button fadeInOutRight = Button.create("FADE IN OUT RIGHT").setBackground(Color.PINK).large(); fadeInOutRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FADE_IN_RIGHT) .outTransition(Transition.FADE_OUT_RIGHT) .setPosition(Notification.TOP_RIGHT) .show()); Button fadeInOutUp = Button.create("FADE IN OUT UP").setBackground(Color.PINK).large(); fadeInOutUp.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FADE_IN_UP) .outTransition(Transition.FADE_OUT_UP) .setPosition(Notification.TOP_CENTER) .show()); Button fadeInOutDown = Button.create("FADE IN OUT DOWN").setBackground(Color.PINK).large(); fadeInOutDown.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FADE_IN_DOWN) .outTransition(Transition.FADE_OUT_DOWN) .setPosition(Notification.TOP_LEFT) .show()); Button bouneInOut = Button.create("BOUNCE IN OUT").setBackground(Color.CYAN).large(); bouneInOut.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.BOUNCE_IN) .outTransition(Transition.BOUNCE_OUT) .setPosition(Notification.TOP_LEFT) .show()); Button bounceInOutLeft = Button.create("BOUNCE IN OUT LEFT").setBackground(Color.CYAN).large(); bounceInOutLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.BOUNCE_IN_LEFT) .outTransition(Transition.BOUNCE_OUT_LEFT) .setPosition(Notification.TOP_LEFT) .show()); Button bounceInOutRight = Button.create("BOUNCE IN OUT RIGHT").setBackground(Color.CYAN).large(); bounceInOutRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.BOUNCE_IN_RIGHT) .outTransition(Transition.BOUNCE_OUT_RIGHT) .setPosition(Notification.TOP_RIGHT) .show()); Button bounceInOutUp = Button.create("BOUNCE IN OUT UP").setBackground(Color.CYAN).large(); bounceInOutUp.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.BOUNCE_IN_UP) .outTransition(Transition.BOUNCE_OUT_UP) .setPosition(Notification.TOP_CENTER) .show()); Button bounceInOutDown = Button.create("BOUNCE IN OUT DOWN").setBackground(Color.CYAN).large(); bounceInOutDown.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.BOUNCE_IN_DOWN) .outTransition(Transition.BOUNCE_OUT_DOWN) .setPosition(Notification.TOP_CENTER) .show()); Button rotateInOut = Button.create("ROTATE IN OUT").setBackground(Color.LIGHT_GREEN).large(); rotateInOut.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ROTATE_IN) .outTransition(Transition.ROTATE_OUT) .setPosition(Notification.TOP_LEFT) .show()); Button rotateInOutUpLeft = Button.create("ROTATE IN OUT UP LEFT").setBackground(Color.LIGHT_GREEN).large(); rotateInOutUpLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ROTATE_IN_UP_LEFT) .outTransition(Transition.ROTATE_OUT_UP_LEFT) .setPosition(Notification.TOP_LEFT) .show()); Button rotateInOutUpRight = Button.create("ROTATE IN OUT UP RIGHT").setBackground(Color.LIGHT_GREEN).large(); rotateInOutUpRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ROTATE_IN_UP_RIGHT) .outTransition(Transition.ROTATE_OUT_UP_RIGHT) .setPosition(Notification.TOP_LEFT) .show()); Button rotateInOutDownLeft = Button.create("ROTATE IN OUT DOWN LEFT").setBackground(Color.LIGHT_GREEN).large(); rotateInOutDownLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ROTATE_IN_DOWN_LEFT) .outTransition(Transition.ROTATE_OUT_DOWN_LEFT) .setPosition(Notification.TOP_LEFT) .show()); Button rotateInOutDownRight = Button.create("ROTATE IN OUT DOWN RIGHT").setBackground(Color.LIGHT_GREEN).large(); rotateInOutDownRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ROTATE_IN_DOWN_RIGHT) .outTransition(Transition.ROTATE_OUT_DOWN_RIGHT) .setPosition(Notification.TOP_LEFT) .show()); Button zoomInOut = Button.create("ZOOM IN OUT").setBackground(Color.TEAL).large(); zoomInOut.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ZOOM_IN) .outTransition(Transition.ZOOM_OUT) .setPosition(Notification.TOP_RIGHT) .show()); Button zoomInOutLeft = Button.create("ZOOM IN OUT LEFT").setBackground(Color.TEAL).large(); zoomInOutLeft.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ZOOM_IN_LEFT) .outTransition(Transition.ZOOM_OUT_LEFT) .setPosition(Notification.TOP_RIGHT) .show()); Button zoomInOutRight = Button.create("ZOOM IN OUT RIGHT").setBackground(Color.TEAL).large(); zoomInOutRight.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ZOOM_IN_RIGHT) .outTransition(Transition.ZOOM_OUT_RIGHT) .setPosition(Notification.TOP_RIGHT) .show()); Button zoomInOutUp = Button.create("ZOOM IN OUT UP").setBackground(Color.TEAL).large(); zoomInOutUp.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ZOOM_IN_UP) .outTransition(Transition.ZOOM_OUT_UP) .setPosition(Notification.TOP_RIGHT) .show()); Button zoomInOutDown = Button.create("ZOOM IN OUT DOWN").setBackground(Color.TEAL).large(); zoomInOutDown.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.ZOOM_IN_DOWN) .outTransition(Transition.ZOOM_OUT_DOWN) .setPosition(Notification.TOP_RIGHT) .show()); Button flipInOutX = Button.create("FLIP IN OUT X").setBackground(Color.PURPLE).large(); flipInOutX.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FLIP_IN_X) .outTransition(Transition.FLIP_OUT_X) .setPosition(Notification.BOTTOM_LEFT) .show()); Button flipInOutY = Button.create("FLIP IN OUT Y").setBackground(Color.PURPLE).large(); flipInOutY.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.FLIP_IN_Y) .outTransition(Transition.FLIP_OUT_Y) .setPosition(Notification.BOTTOM_RIGHT) .show()); Button lightSpeedInOut = Button.create("LIGHT SPEED IN OUT").setBackground(Color.INDIGO).large(); lightSpeedInOut.getClickableElement().addEventListener("click", e -> Notification.create("You received a message") .inTransition(Transition.LIGHT_SPEED_IN) .outTransition(Transition.LIGHT_SPEED_OUT) .setPosition(Notification.TOP_CENTER) .show()); element.appendChild(Card.create("NOTIFICATION ANIMATIONS") .appendContent(Row.create() .addColumn(column.copy().addElement(fadeInOut.block().asElement())) .addColumn(column.copy().addElement(fadeInOutLeft.block().asElement())) .addColumn(column.copy().addElement(fadeInOutRight.block().asElement())) .addColumn(column.copy().addElement(fadeInOutUp.block().asElement())) .addColumn(column.copy().addElement(fadeInOutDown.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(bouneInOut.block().asElement())) .addColumn(column.copy().addElement(bounceInOutLeft.block().asElement())) .addColumn(column.copy().addElement(bounceInOutRight.block().asElement())) .addColumn(column.copy().addElement(bounceInOutUp.block().asElement())) .addColumn(column.copy().addElement(bounceInOutDown.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(rotateInOut.block().asElement())) .addColumn(column.copy().addElement(rotateInOutUpLeft.block().asElement())) .addColumn(column.copy().addElement(rotateInOutUpRight.block().asElement())) .addColumn(column.copy().addElement(rotateInOutDownLeft.block().asElement())) .addColumn(column.copy().addElement(rotateInOutDownRight.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(zoomInOut.block().asElement())) .addColumn(column.copy().addElement(zoomInOutLeft.block().asElement())) .addColumn(column.copy().addElement(zoomInOutRight.block().asElement())) .addColumn(column.copy().addElement(zoomInOutUp.block().asElement())) .addColumn(column.copy().addElement(zoomInOutDown.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(flipInOutX.block().asElement())) .addColumn(column.copy().addElement(flipInOutY.block().asElement())) .asElement()) .appendContent(Row.create() .addColumn(column.copy().addElement(lightSpeedInOut.block().asElement())) .asElement()) .asElement()); element.appendChild(Card.createCodeCard(CodeResource.INSTANCE.withAnimation()) .asElement()); } }
26,395
0.581057
0.580716
486
53.312756
30.560015
121
false
false
0
0
0
0
0
0
0.353909
false
false
4
312031d25cac65609e6672a5cc126e0e1742d258
29,772,713,350,270
d6b5b32f6a50154c4b75af69d51015c0cc000361
/core/src/test/java/com/sequenceiq/cloudbreak/service/StackMatrixServiceTest.java
18740b8bc214c43cda10ec55a7d1b699dd9b9975
[ "LicenseRef-scancode-warranty-disclaimer", "ANTLR-PD", "CDDL-1.0", "bzip2-1.0.6", "Zlib", "BSD-3-Clause", "MIT", "EPL-1.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-jdbm-1.00", "Apache-2.0" ]
permissive
subhashjha35/cloudbreak
https://github.com/subhashjha35/cloudbreak
19f0ba660e7343d36e1bd840c5f32f3f2310b978
28265d0e4681ec9d8bef425e0ad6e339584127ed
refs/heads/master
2021-04-24T00:22:04.561000
2020-03-18T18:30:04
2020-03-25T12:02:51
250,041,790
1
0
Apache-2.0
true
2020-03-25T17:10:58
2020-03-25T17:10:58
2020-03-25T12:02:56
2020-03-25T16:47:17
80,591
0
0
0
null
false
false
package com.sequenceiq.cloudbreak.service; import static com.sequenceiq.cloudbreak.RepoTestUtil.getCMStackDescriptorResponse; import static com.sequenceiq.cloudbreak.RepoTestUtil.getDefaultCDHInfo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import com.sequenceiq.cloudbreak.api.endpoint.v4.util.responses.ClouderaManagerInfoV4Response; import com.sequenceiq.cloudbreak.api.endpoint.v4.util.responses.ClouderaManagerStackDescriptorV4Response; import com.sequenceiq.cloudbreak.api.endpoint.v4.util.responses.StackMatrixV4Response; import com.sequenceiq.cloudbreak.api.util.ConverterUtil; import com.sequenceiq.cloudbreak.cloud.model.component.DefaultCDHEntries; import com.sequenceiq.cloudbreak.cloud.model.component.DefaultCDHInfo; import com.sequenceiq.cloudbreak.cloud.model.component.RepositoryInfo; @RunWith(MockitoJUnitRunner.class) public class StackMatrixServiceTest { @Mock private DefaultCDHEntries defaultCDHEntries; @Mock private DefaultClouderaManagerRepoService defaultClouderaManagerRepoService; @Mock private ConverterUtil converterUtil; @InjectMocks private StackMatrixService stackMatrixService; @Test public void getStackMatrixWithoutAmbari() { setupStackEntries(); when(converterUtil.convert(any(RepositoryInfo.class), eq(ClouderaManagerInfoV4Response.class))).thenReturn(new ClouderaManagerInfoV4Response()); StackMatrixV4Response stackMatrixV4Response = stackMatrixService.getStackMatrix(); assertEquals(1L, stackMatrixV4Response.getCdh().size()); assertEquals("6.1", stackMatrixV4Response.getCdh().get("6.1.0").getMinCM()); assertEquals("6.1.0-1.cdh6.1.0.p0.770702", stackMatrixV4Response.getCdh().get("6.1.0").getVersion()); assertNull(stackMatrixV4Response.getCdh().get("6.1.0").getClouderaManager().getRepository()); assertNull(stackMatrixV4Response.getCdh().get("6.1.0").getClouderaManager().getVersion()); } private void setupStackEntries() { Map<String, DefaultCDHInfo> cdhEntries = new HashMap<>(); DefaultCDHInfo cdhInfo = getDefaultCDHInfo("6.1", "6.1.0-1.cdh6.1.0.p0.770702"); cdhEntries.put("6.1.0", cdhInfo); when(converterUtil.convert(cdhInfo, ClouderaManagerStackDescriptorV4Response.class)) .thenReturn(getCMStackDescriptorResponse("6.1", "6.1.0-1.cdh6.1.0.p0.770702")); when(defaultCDHEntries.getEntries()).thenReturn(cdhEntries); } }
UTF-8
Java
2,848
java
StackMatrixServiceTest.java
Java
[]
null
[]
package com.sequenceiq.cloudbreak.service; import static com.sequenceiq.cloudbreak.RepoTestUtil.getCMStackDescriptorResponse; import static com.sequenceiq.cloudbreak.RepoTestUtil.getDefaultCDHInfo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import com.sequenceiq.cloudbreak.api.endpoint.v4.util.responses.ClouderaManagerInfoV4Response; import com.sequenceiq.cloudbreak.api.endpoint.v4.util.responses.ClouderaManagerStackDescriptorV4Response; import com.sequenceiq.cloudbreak.api.endpoint.v4.util.responses.StackMatrixV4Response; import com.sequenceiq.cloudbreak.api.util.ConverterUtil; import com.sequenceiq.cloudbreak.cloud.model.component.DefaultCDHEntries; import com.sequenceiq.cloudbreak.cloud.model.component.DefaultCDHInfo; import com.sequenceiq.cloudbreak.cloud.model.component.RepositoryInfo; @RunWith(MockitoJUnitRunner.class) public class StackMatrixServiceTest { @Mock private DefaultCDHEntries defaultCDHEntries; @Mock private DefaultClouderaManagerRepoService defaultClouderaManagerRepoService; @Mock private ConverterUtil converterUtil; @InjectMocks private StackMatrixService stackMatrixService; @Test public void getStackMatrixWithoutAmbari() { setupStackEntries(); when(converterUtil.convert(any(RepositoryInfo.class), eq(ClouderaManagerInfoV4Response.class))).thenReturn(new ClouderaManagerInfoV4Response()); StackMatrixV4Response stackMatrixV4Response = stackMatrixService.getStackMatrix(); assertEquals(1L, stackMatrixV4Response.getCdh().size()); assertEquals("6.1", stackMatrixV4Response.getCdh().get("6.1.0").getMinCM()); assertEquals("6.1.0-1.cdh6.1.0.p0.770702", stackMatrixV4Response.getCdh().get("6.1.0").getVersion()); assertNull(stackMatrixV4Response.getCdh().get("6.1.0").getClouderaManager().getRepository()); assertNull(stackMatrixV4Response.getCdh().get("6.1.0").getClouderaManager().getVersion()); } private void setupStackEntries() { Map<String, DefaultCDHInfo> cdhEntries = new HashMap<>(); DefaultCDHInfo cdhInfo = getDefaultCDHInfo("6.1", "6.1.0-1.cdh6.1.0.p0.770702"); cdhEntries.put("6.1.0", cdhInfo); when(converterUtil.convert(cdhInfo, ClouderaManagerStackDescriptorV4Response.class)) .thenReturn(getCMStackDescriptorResponse("6.1", "6.1.0-1.cdh6.1.0.p0.770702")); when(defaultCDHEntries.getEntries()).thenReturn(cdhEntries); } }
2,848
0.777036
0.748947
71
39.126762
36.800156
152
false
false
0
0
0
0
0
0
0.676056
false
false
4
c1cd8a557953494cb5bd736076f88a57a8b940e2
29,772,713,352,949
a1adfbe57cbf00f380b6da4666c6f467f13ca531
/pnkfelix/objects-lecture/Main.java
3029ce4883d7aead4600430b4342f6eab5b40fd7
[]
no_license
pnkfelix/pnkfelix.github.com
https://github.com/pnkfelix/pnkfelix.github.com
b9856c6ff4fcb63fa450744d396b7d5cf4785cbe
2da02366dc0af520d79f3cb862bcfde2290a2f2b
refs/heads/master
2023-01-24T12:26:54.931000
2023-01-18T04:56:37
2023-01-18T04:56:37
7,489,545
5
2
null
false
2020-12-23T00:20:15
2013-01-07T20:45:18
2020-12-02T15:59:47
2020-12-02T15:59:44
14,988
3
2
1
HTML
false
false
public class Main { private static Tree leaf() { return Tree.leaf(); } private static Tree node( Tree l, Tree r, Object v ) { return Tree.node(l,r,v); } public static void main( String[] args ) { Queue q1 = Queue.empty(); System.out.println("> q1.toString():\n" + q1.toString()); Queue q2 = q1.addElem("a").addElem("b").addElem("c"); System.out.println("> q2.toString():\n" + q2.toString()); System.out.println("> q2.tail().toString():\n" + q2.tail().toString()); Tree t1 = leaf(); System.out.println("> t1.toString():\n" + t1.toString()); Tree t2 = node( node( leaf(), leaf(), "p"), node( node( leaf(), leaf(), "q"), node( leaf(), leaf(), "r"), "s" ), "t" ); System.out.println("> t2.toString():\n" + t2.toString()); System.out.println("> t2.isLeaf():\n" + t2.isLeaf() ); System.out.println("> t2.right().isLeaf():\n" + t2.right().isLeaf() ); System.out.println("> t2.left().isLeaf():\n" + t2.left().isLeaf() ); System.out.println("> t2.left().nodeValue():\n" + t2.left().nodeValue() ); System.out.println("> t2.right().toString():\n" + t2.right().toString() ); System.out.println("> q2.addAll(t2).toString():\n" + q2.addAll(t2).toString() ); } }
UTF-8
Java
1,583
java
Main.java
Java
[]
null
[]
public class Main { private static Tree leaf() { return Tree.leaf(); } private static Tree node( Tree l, Tree r, Object v ) { return Tree.node(l,r,v); } public static void main( String[] args ) { Queue q1 = Queue.empty(); System.out.println("> q1.toString():\n" + q1.toString()); Queue q2 = q1.addElem("a").addElem("b").addElem("c"); System.out.println("> q2.toString():\n" + q2.toString()); System.out.println("> q2.tail().toString():\n" + q2.tail().toString()); Tree t1 = leaf(); System.out.println("> t1.toString():\n" + t1.toString()); Tree t2 = node( node( leaf(), leaf(), "p"), node( node( leaf(), leaf(), "q"), node( leaf(), leaf(), "r"), "s" ), "t" ); System.out.println("> t2.toString():\n" + t2.toString()); System.out.println("> t2.isLeaf():\n" + t2.isLeaf() ); System.out.println("> t2.right().isLeaf():\n" + t2.right().isLeaf() ); System.out.println("> t2.left().isLeaf():\n" + t2.left().isLeaf() ); System.out.println("> t2.left().nodeValue():\n" + t2.left().nodeValue() ); System.out.println("> t2.right().toString():\n" + t2.right().toString() ); System.out.println("> q2.addAll(t2).toString():\n" + q2.addAll(t2).toString() ); } }
1,583
0.44662
0.428301
38
40.657894
23.369205
79
false
false
0
0
0
0
0
0
0.815789
false
false
4
1d4f1dfb4064e844e1dd54d431906063450a4202
24,369,644,476,850
477e2ff02b20638c820d75ae0a4083ef1f957198
/src/com/suiyue/MultiplyStrings.java
a53b13185cf3d03200e8b506076547fbb159a0d2
[]
no_license
suiyueming/MyLeetCode
https://github.com/suiyueming/MyLeetCode
b975abe395d3abefea0abd9e77496a4f2ba1df94
9724e5981d3e8e77dc1b7ec993fd0ef6f30ccd47
refs/heads/master
2021-01-21T13:14:52.225000
2016-04-24T14:43:44
2016-04-24T14:43:44
54,776,437
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.suiyue; /** * Created by suiyue on 2016/3/27 0027. */ public class MultiplyStrings { public static void main(String[]args){ System.out.println(new MultiplyStrings().multiply("511", "1000")); } //字符串实现乘法 public String multiply(String num1, String num2) { char[] a = num1.toCharArray(); char[] b = num2.toCharArray(); int[] c = new int[a.length + b.length]; String result = ""; //逐个相乘 for(int i=0; i<a.length; i++) { for(int j=0; j<b.length; j++) { c[i + j] += (a[a.length-1-i] - '0') * (b[b.length-1-j] - '0'); } } //进位 for (int i=0; i<c.length-1; i ++) { c[i+1] += c[i]/10; c[i] = c[i]%10; } //将int数组转为字符串 int j=c.length - 1; while(c[j] == 0) { if(j == 0) { return "0"; } j--; } for (int i=j; i>=0; i--) { result += c[i]; } return result; } }
UTF-8
Java
1,093
java
MultiplyStrings.java
Java
[ { "context": "package com.suiyue;\n\n/**\n * Created by suiyue on 2016/3/27 0027.\n */\n\npublic class MultiplyStri", "end": 45, "score": 0.9994979500770569, "start": 39, "tag": "USERNAME", "value": "suiyue" } ]
null
[]
package com.suiyue; /** * Created by suiyue on 2016/3/27 0027. */ public class MultiplyStrings { public static void main(String[]args){ System.out.println(new MultiplyStrings().multiply("511", "1000")); } //字符串实现乘法 public String multiply(String num1, String num2) { char[] a = num1.toCharArray(); char[] b = num2.toCharArray(); int[] c = new int[a.length + b.length]; String result = ""; //逐个相乘 for(int i=0; i<a.length; i++) { for(int j=0; j<b.length; j++) { c[i + j] += (a[a.length-1-i] - '0') * (b[b.length-1-j] - '0'); } } //进位 for (int i=0; i<c.length-1; i ++) { c[i+1] += c[i]/10; c[i] = c[i]%10; } //将int数组转为字符串 int j=c.length - 1; while(c[j] == 0) { if(j == 0) { return "0"; } j--; } for (int i=j; i>=0; i--) { result += c[i]; } return result; } }
1,093
0.420552
0.382493
44
22.886364
18.793394
78
false
false
0
0
0
0
0
0
0.545455
false
false
4
061e96c76121158ef2f2580103c55c7468b13170
21,818,433,925,155
24359f2c09f1cfa9b3f3000794fea7fc8a94e2b2
/QuoteGenerationApp/src/main/java/com/assurance/quotegeneration/client/ClaimsHistoryClient.java
19493563c0914d1ee786988d9ebd3eb6b5e5a04b
[]
no_license
rohit-kavoori/BCJ_AsuranceApplication
https://github.com/rohit-kavoori/BCJ_AsuranceApplication
d5d816cb828b9dcebee5b4e46a67d828810cef0a
14f0adec5fb14406ce51cb8dc618852095b436cc
refs/heads/master
2021-01-12T13:59:31.743000
2016-11-05T17:53:32
2016-11-05T17:53:32
69,683,087
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.assurance.quotegeneration.client; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import com.assurance.quotegeneration.model.ClaimHistory; /** * * ClaimsHistoryClient contains client to consume claim service and get claim history * @author Srinivas Kondapaneni * */ @Service("claimsHistoryClient") public class ClaimsHistoryClient { /** * getClaimHistory is restclient method to consume service from ClaimsHistory application * @param vin * @return ClaimHistory object */ public ClaimHistory getClaimHistory(String vin) { final String url = "http://localhost:8080/ClaimsHistory/rest/claims/{vin}"; Map<String, String> params = new HashMap<String, String>(); params.put("vin", vin); RestTemplate restTemplate = new RestTemplate(); ClaimHistory result = restTemplate.getForObject(url, ClaimHistory.class, params); return result; } /* public static void main(String[] args) { Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); int month = now.get(Calendar.MONTH) + 1; int date = now.get(Calendar.DATE); Random rand = new Random(); String s1 = Integer.toString(year); String s2 = Integer.toString(month); String s3 = Integer.toString(date); System.out.println(year); System.out.println(month); System.out.println(date); System.out.println(String.format("%04d", rand.nextInt(10000))); System.out.println(rand.nextInt(10000)); System.out.println(s1 + s2 + s3 + String.format("%04d", rand.nextInt(10000))); }*/ }
UTF-8
Java
1,736
java
ClaimsHistoryClient.java
Java
[ { "context": "e claim service and get claim history \r\n * @author Srinivas Kondapaneni\r\n *\r\n */\r\n@Service(\"claimsHistoryClient\")\r\npublic", "end": 393, "score": 0.9998773336410522, "start": 373, "tag": "NAME", "value": "Srinivas Kondapaneni" } ]
null
[]
package com.assurance.quotegeneration.client; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import com.assurance.quotegeneration.model.ClaimHistory; /** * * ClaimsHistoryClient contains client to consume claim service and get claim history * @author <NAME> * */ @Service("claimsHistoryClient") public class ClaimsHistoryClient { /** * getClaimHistory is restclient method to consume service from ClaimsHistory application * @param vin * @return ClaimHistory object */ public ClaimHistory getClaimHistory(String vin) { final String url = "http://localhost:8080/ClaimsHistory/rest/claims/{vin}"; Map<String, String> params = new HashMap<String, String>(); params.put("vin", vin); RestTemplate restTemplate = new RestTemplate(); ClaimHistory result = restTemplate.getForObject(url, ClaimHistory.class, params); return result; } /* public static void main(String[] args) { Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); int month = now.get(Calendar.MONTH) + 1; int date = now.get(Calendar.DATE); Random rand = new Random(); String s1 = Integer.toString(year); String s2 = Integer.toString(month); String s3 = Integer.toString(date); System.out.println(year); System.out.println(month); System.out.println(date); System.out.println(String.format("%04d", rand.nextInt(10000))); System.out.println(rand.nextInt(10000)); System.out.println(s1 + s2 + s3 + String.format("%04d", rand.nextInt(10000))); }*/ }
1,722
0.682028
0.664747
59
27.423729
26.021635
91
false
false
0
0
0
0
0
0
1.271186
false
false
4
b06244652c39f6361bcbb2b550459591e1f364fb
28,784,870,883,993
776b92da6313b2003a8f58d41252986835279c49
/src/main/java/ctrl/action/JoinAction.java
78d5aea592ab3a943f4969225868fdc31f226fe7
[]
no_license
systic2/login
https://github.com/systic2/login
5e8c053816eea2207c7999f4aafca1f4aa18dda7
262aacca19a9c2bf16fbe1271a08305b86d6a8cd
refs/heads/master
2023-09-04T08:03:02.490000
2021-10-08T08:09:57
2021-10-08T08:09:57
414,513,931
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ctrl.action; import ctrl.view.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class JoinAction implements Command{ @Override public ModelAndView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { return null; } }
UTF-8
Java
344
java
JoinAction.java
Java
[]
null
[]
package ctrl.action; import ctrl.view.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class JoinAction implements Command{ @Override public ModelAndView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { return null; } }
344
0.790698
0.790698
13
25.461538
29.248577
108
false
false
0
0
0
0
0
0
0.461538
false
false
4
6aad1ccd3086350d371eb780efada5197809d2a4
36,464,272,343,387
34f8d4ba30242a7045c689768c3472b7af80909c
/jdk-12/src/jdk.internal.vm.compiler/org.graalvm.compiler.hotspot.sparc/src/org/graalvm/compiler/hotspot/sparc/SPARCHotSpotPatchReturnAddressOp.java
cc3933a14a492c100d304edcd6402654ae9e3551
[ "Apache-2.0" ]
permissive
lovelycheng/JDK
https://github.com/lovelycheng/JDK
5b4cc07546f0dbfad15c46d427cae06ef282ef79
19a6c71e52f3ecd74e4a66be5d0d552ce7175531
refs/heads/master
2023-04-08T11:36:22.073000
2022-09-04T01:53:09
2022-09-04T01:53:09
227,544,567
0
0
null
true
2019-12-12T07:18:30
2019-12-12T07:18:29
2019-12-12T06:24:59
2019-11-24T12:36:46
177,316
0
0
0
null
false
false
/* * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * */ package org.graalvm.compiler.hotspot.sparc; import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.REG; import static jdk.vm.ci.code.ValueUtil.asRegister; import static jdk.vm.ci.sparc.SPARC.i7; import static jdk.vm.ci.sparc.SPARCKind.XWORD; import org.graalvm.compiler.asm.sparc.SPARCAssembler; import org.graalvm.compiler.asm.sparc.SPARCMacroAssembler; import org.graalvm.compiler.lir.LIRInstructionClass; import org.graalvm.compiler.lir.Opcode; import org.graalvm.compiler.lir.asm.CompilationResultBuilder; import org.graalvm.compiler.lir.sparc.SPARCLIRInstruction; import jdk.vm.ci.code.Register; import jdk.vm.ci.meta.AllocatableValue; /** * Patch the return address of the current frame. */ @Opcode("PATCH_RETURN") final class SPARCHotSpotPatchReturnAddressOp extends SPARCLIRInstruction { public static final LIRInstructionClass<SPARCHotSpotPatchReturnAddressOp> TYPE = LIRInstructionClass.create(SPARCHotSpotPatchReturnAddressOp.class); public static final SizeEstimate SIZE = SizeEstimate.create(1); @Use(REG) AllocatableValue address; SPARCHotSpotPatchReturnAddressOp(AllocatableValue address) { super(TYPE, SIZE); this.address = address; } @Override public void emitCode(CompilationResultBuilder crb, SPARCMacroAssembler masm) { Register addrRegister = asRegister(address, XWORD); masm.sub(addrRegister, SPARCAssembler.PC_RETURN_OFFSET, i7); } }
UTF-8
Java
1,653
java
SPARCHotSpotPatchReturnAddressOp.java
Java
[]
null
[]
/* * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * */ package org.graalvm.compiler.hotspot.sparc; import static org.graalvm.compiler.lir.LIRInstruction.OperandFlag.REG; import static jdk.vm.ci.code.ValueUtil.asRegister; import static jdk.vm.ci.sparc.SPARC.i7; import static jdk.vm.ci.sparc.SPARCKind.XWORD; import org.graalvm.compiler.asm.sparc.SPARCAssembler; import org.graalvm.compiler.asm.sparc.SPARCMacroAssembler; import org.graalvm.compiler.lir.LIRInstructionClass; import org.graalvm.compiler.lir.Opcode; import org.graalvm.compiler.lir.asm.CompilationResultBuilder; import org.graalvm.compiler.lir.sparc.SPARCLIRInstruction; import jdk.vm.ci.code.Register; import jdk.vm.ci.meta.AllocatableValue; /** * Patch the return address of the current frame. */ @Opcode("PATCH_RETURN") final class SPARCHotSpotPatchReturnAddressOp extends SPARCLIRInstruction { public static final LIRInstructionClass<SPARCHotSpotPatchReturnAddressOp> TYPE = LIRInstructionClass.create(SPARCHotSpotPatchReturnAddressOp.class); public static final SizeEstimate SIZE = SizeEstimate.create(1); @Use(REG) AllocatableValue address; SPARCHotSpotPatchReturnAddressOp(AllocatableValue address) { super(TYPE, SIZE); this.address = address; } @Override public void emitCode(CompilationResultBuilder crb, SPARCMacroAssembler masm) { Register addrRegister = asRegister(address, XWORD); masm.sub(addrRegister, SPARCAssembler.PC_RETURN_OFFSET, i7); } }
1,653
0.758016
0.751361
62
25.661291
31.442186
152
false
false
0
0
0
0
0
0
0.435484
false
false
4
d5c03e20ba234f2c15bb41e933335e8b4493660c
35,476,429,865,958
5735a89cbd4217d98e3ad88a3c3003f872b1df67
/app/src/main/java/com/yusion/shanghai/yusion4s/bean/upload/UploadFilesUrlReq.java
379106fffd68a97a4661358f47e9c30244b7efef
[]
no_license
Ze329966824/Yusion4s
https://github.com/Ze329966824/Yusion4s
4ab0b89b3714a58421e75e03b620baedd6a371d7
be4291e7da307bf5a70e1d4bd9b2e6ae40ef232a
refs/heads/master
2021-04-26T22:10:18.408000
2018-02-09T04:16:05
2018-02-09T04:16:05
124,031,504
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yusion.shanghai.yusion4s.bean.upload; import com.google.gson.Gson; import java.io.Serializable; import java.util.List; /** * 类描述: * 伟大的创建人:ice * 不可相信的创建时间:17/4/20 下午3:03 */ public class UploadFilesUrlReq implements Serializable{ public List<FileUrlBean> files; public String bucket; public String region; public static class FileUrlBean implements Serializable{ public String clt_id; public String app_id; public String label;//身份证正面,身份证反面 public String file_id; @Override public String toString() { return new Gson().toJson(this); } } @Override public String toString() { return new Gson().toJson(this); } }
UTF-8
Java
806
java
UploadFilesUrlReq.java
Java
[ { "context": "le;\nimport java.util.List;\n\n/**\n * 类描述:\n * 伟大的创建人:ice\n * 不可相信的创建时间:17/4/20 下午3:03\n */\n\npublic class Upl", "end": 159, "score": 0.8276447653770447, "start": 156, "tag": "USERNAME", "value": "ice" } ]
null
[]
package com.yusion.shanghai.yusion4s.bean.upload; import com.google.gson.Gson; import java.io.Serializable; import java.util.List; /** * 类描述: * 伟大的创建人:ice * 不可相信的创建时间:17/4/20 下午3:03 */ public class UploadFilesUrlReq implements Serializable{ public List<FileUrlBean> files; public String bucket; public String region; public static class FileUrlBean implements Serializable{ public String clt_id; public String app_id; public String label;//身份证正面,身份证反面 public String file_id; @Override public String toString() { return new Gson().toJson(this); } } @Override public String toString() { return new Gson().toJson(this); } }
806
0.65
0.637838
35
20.142857
17.399742
60
false
false
0
0
0
0
0
0
0.4
false
false
4
421846f6c7cdd867c09d0770f1f20f00f75822c9
31,920,197,012,556
2a2a9a864e8e198216923b06bfc22f1bcee0788b
/app/src/main/java/com/jxkj/readapp/activity/ColDemoActivity.java
19b6eb6cd36ec65e4f8865ea7a704dd13f4ffa20
[]
no_license
Anbinghui/ReadApp
https://github.com/Anbinghui/ReadApp
aa212023b55e82eccc9319aaebf15d95d84e0936
39cc4c974e165d0e187d83824a53c740c85cee85
refs/heads/master
2021-01-25T09:25:51.295000
2017-08-23T08:04:30
2017-08-23T08:04:30
93,829,682
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jxkj.readapp.activity; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.widget.NestedScrollView; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.jxkj.readapp.R; import com.jxkj.readapp.adapter.BusAdapter; import com.jxkj.readapp.bean.TestBean; import com.jxkj.readapp.fragment.ColDemoFragment; import com.jxkj.readapp.view.DisInterceptNestedRecyclerView; import com.jxkj.readapp.view.IndicatorView; import com.jxkj.readapp.view.NoScrollViewPager; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class ColDemoActivity extends FragmentActivity { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.rcl_business) DisInterceptNestedRecyclerView rclBusiness; @BindView(R.id.tv_business_location) TextView tvBusinessLocation; @BindView(R.id.tv_business_tabel1) TextView tvBusinessTabel1; @BindView(R.id.tv_business_tabel2) TextView tvBusinessTabel2; @BindView(R.id.tv_business_tabel3) TextView tvBusinessTabel3; @BindView(R.id.tv_business_tabel4) TextView tvBusinessTabel4; @BindView(R.id.ll_business_tabel) LinearLayout llBusinessTabel; @BindView(R.id.iv_business_line) IndicatorView ivBusinessLine; @BindView(R.id.scroll) NestedScrollView scroll; @BindView(R.id.pager_Dol) NoScrollViewPager pagerDol; @BindView(R.id.container) CoordinatorLayout container; @BindView(R.id.activity_col_demo) LinearLayout activityColDemo; private List<Fragment> fragments = new ArrayList<>(); private ColAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_col_demo); ButterKnife.bind(this); initView(); } private void initView() { fragments.add(new ColDemoFragment()); fragments.add(new ColDemoFragment()); fragments.add(new ColDemoFragment()); fragments.add(new ColDemoFragment()); adapter = new ColAdapter(getSupportFragmentManager(), fragments); rclBusiness.setLayoutManager(new GridLayoutManager(this, 4)); BusAdapter busAdapter = new BusAdapter(TestBean.getDataList()); rclBusiness.setAdapter(busAdapter); pagerDol.setAdapter(adapter); pagerDol.setCurrentItem(0); pagerDol.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { ivBusinessLine.setOffset(position, positionOffset); } @Override public void onPageSelected(int position) { setTextColor(); switch (position) { case 0: tvBusinessTabel1.setTextColor(Color.parseColor("#f40e47")); break; case 1: tvBusinessTabel2.setTextColor(Color.parseColor("#f40e47")); break; case 2: tvBusinessTabel3.setTextColor(Color.parseColor("#f40e47")); break; case 3: tvBusinessTabel4.setTextColor(Color.parseColor("#f40e47")); break; } } @Override public void onPageScrollStateChanged(int state) { } }); } /** * 字体颜色 */ private void setTextColor() { tvBusinessTabel1.setTextColor(Color.parseColor("#666666")); tvBusinessTabel2.setTextColor(Color.parseColor("#666666")); tvBusinessTabel3.setTextColor(Color.parseColor("#666666")); tvBusinessTabel4.setTextColor(Color.parseColor("#666666")); } @OnClick({R.id.tv_business_tabel1, R.id.tv_business_tabel2, R.id.tv_business_tabel3, R.id.tv_business_tabel4}) public void onClick(View v) { switch (v.getId()) { case R.id.tv_business_tabel1: pagerDol.setCurrentItem(0); break; case R.id.tv_business_tabel2: pagerDol.setCurrentItem(1); break; case R.id.tv_business_tabel3: pagerDol.setCurrentItem(2); break; case R.id.tv_business_tabel4: pagerDol.setCurrentItem(3); break; } } class ColAdapter extends FragmentPagerAdapter { private List<Fragment> fragments; public ColAdapter(FragmentManager fm, List<Fragment> fragmentList) { super(fm); this.fragments = fragmentList; } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } } }
UTF-8
Java
5,490
java
ColDemoActivity.java
Java
[]
null
[]
package com.jxkj.readapp.activity; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.widget.NestedScrollView; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.jxkj.readapp.R; import com.jxkj.readapp.adapter.BusAdapter; import com.jxkj.readapp.bean.TestBean; import com.jxkj.readapp.fragment.ColDemoFragment; import com.jxkj.readapp.view.DisInterceptNestedRecyclerView; import com.jxkj.readapp.view.IndicatorView; import com.jxkj.readapp.view.NoScrollViewPager; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class ColDemoActivity extends FragmentActivity { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.rcl_business) DisInterceptNestedRecyclerView rclBusiness; @BindView(R.id.tv_business_location) TextView tvBusinessLocation; @BindView(R.id.tv_business_tabel1) TextView tvBusinessTabel1; @BindView(R.id.tv_business_tabel2) TextView tvBusinessTabel2; @BindView(R.id.tv_business_tabel3) TextView tvBusinessTabel3; @BindView(R.id.tv_business_tabel4) TextView tvBusinessTabel4; @BindView(R.id.ll_business_tabel) LinearLayout llBusinessTabel; @BindView(R.id.iv_business_line) IndicatorView ivBusinessLine; @BindView(R.id.scroll) NestedScrollView scroll; @BindView(R.id.pager_Dol) NoScrollViewPager pagerDol; @BindView(R.id.container) CoordinatorLayout container; @BindView(R.id.activity_col_demo) LinearLayout activityColDemo; private List<Fragment> fragments = new ArrayList<>(); private ColAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_col_demo); ButterKnife.bind(this); initView(); } private void initView() { fragments.add(new ColDemoFragment()); fragments.add(new ColDemoFragment()); fragments.add(new ColDemoFragment()); fragments.add(new ColDemoFragment()); adapter = new ColAdapter(getSupportFragmentManager(), fragments); rclBusiness.setLayoutManager(new GridLayoutManager(this, 4)); BusAdapter busAdapter = new BusAdapter(TestBean.getDataList()); rclBusiness.setAdapter(busAdapter); pagerDol.setAdapter(adapter); pagerDol.setCurrentItem(0); pagerDol.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { ivBusinessLine.setOffset(position, positionOffset); } @Override public void onPageSelected(int position) { setTextColor(); switch (position) { case 0: tvBusinessTabel1.setTextColor(Color.parseColor("#f40e47")); break; case 1: tvBusinessTabel2.setTextColor(Color.parseColor("#f40e47")); break; case 2: tvBusinessTabel3.setTextColor(Color.parseColor("#f40e47")); break; case 3: tvBusinessTabel4.setTextColor(Color.parseColor("#f40e47")); break; } } @Override public void onPageScrollStateChanged(int state) { } }); } /** * 字体颜色 */ private void setTextColor() { tvBusinessTabel1.setTextColor(Color.parseColor("#666666")); tvBusinessTabel2.setTextColor(Color.parseColor("#666666")); tvBusinessTabel3.setTextColor(Color.parseColor("#666666")); tvBusinessTabel4.setTextColor(Color.parseColor("#666666")); } @OnClick({R.id.tv_business_tabel1, R.id.tv_business_tabel2, R.id.tv_business_tabel3, R.id.tv_business_tabel4}) public void onClick(View v) { switch (v.getId()) { case R.id.tv_business_tabel1: pagerDol.setCurrentItem(0); break; case R.id.tv_business_tabel2: pagerDol.setCurrentItem(1); break; case R.id.tv_business_tabel3: pagerDol.setCurrentItem(2); break; case R.id.tv_business_tabel4: pagerDol.setCurrentItem(3); break; } } class ColAdapter extends FragmentPagerAdapter { private List<Fragment> fragments; public ColAdapter(FragmentManager fm, List<Fragment> fragmentList) { super(fm); this.fragments = fragmentList; } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } } }
5,490
0.646297
0.631339
164
32.42683
22.144222
114
false
false
0
0
0
0
0
0
0.567073
false
false
4
79c55a7bb0a37d7d7fa023b9221e55be55989165
30,288,109,396,954
4c70f4770237b9d1ebb6272515764237e45e11f1
/app/src/main/java/edu/oregonstate/AiMLiteMobile/Network/ResponseWorkOrders.java
2c3a166716157eee93bd2f2bb11411cf7dc11e43
[]
no_license
nicjay/aim-mobile-android
https://github.com/nicjay/aim-mobile-android
eac74968e74e043ad0a26ae9912102180699986e
ad9ee0d85ff01994170ab7fef379f13cea076189
refs/heads/master
2021-10-10T18:30:45.085000
2018-08-27T18:35:05
2018-08-27T18:35:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.oregonstate.AiMLiteMobile.Network; import java.util.ArrayList; import edu.oregonstate.AiMLiteMobile.Models.WorkOrder; /** * Created by sellersk on 6/10/2015. */ public class ResponseWorkOrders { private static final String TAG = "AiM_ResponseWorkOrders"; private ArrayList<WorkOrder> workOrders; private String rawJson; public ResponseWorkOrders(ArrayList<WorkOrder> workOrders, String rawJson) { this.workOrders = workOrders; this.rawJson = rawJson; } public ArrayList<WorkOrder> getWorkOrders() { return workOrders; } public String getRawJson() { return rawJson; } }
UTF-8
Java
658
java
ResponseWorkOrders.java
Java
[ { "context": "AiMLiteMobile.Models.WorkOrder;\n\n/**\n * Created by sellersk on 6/10/2015.\n */\npublic class ResponseWorkOrders", "end": 159, "score": 0.9996564388275146, "start": 151, "tag": "USERNAME", "value": "sellersk" } ]
null
[]
package edu.oregonstate.AiMLiteMobile.Network; import java.util.ArrayList; import edu.oregonstate.AiMLiteMobile.Models.WorkOrder; /** * Created by sellersk on 6/10/2015. */ public class ResponseWorkOrders { private static final String TAG = "AiM_ResponseWorkOrders"; private ArrayList<WorkOrder> workOrders; private String rawJson; public ResponseWorkOrders(ArrayList<WorkOrder> workOrders, String rawJson) { this.workOrders = workOrders; this.rawJson = rawJson; } public ArrayList<WorkOrder> getWorkOrders() { return workOrders; } public String getRawJson() { return rawJson; } }
658
0.706687
0.696049
28
22.5
22.407747
80
false
false
0
0
0
0
0
0
0.392857
false
false
4
3852cc1f7d6c8364f0a5213a3dd6ce156eecd28a
34,505,767,272,855
342379b0e7a0572860158a34058dfad1c8944186
/core/src/test/java/com/vladmihalcea/hpjp/spring/data/query/exists/SpringDataJPAExistsTest.java
6e4d9ab483b96022d3df5b09c3e9d9f021644b5d
[ "Apache-2.0" ]
permissive
vladmihalcea/high-performance-java-persistence
https://github.com/vladmihalcea/high-performance-java-persistence
80a20e67fa376322f5b1c5eddf75758b29247a2a
acef7e84e8e2dff89a6113f007eb7656bc6bdea4
refs/heads/master
2023-09-01T03:43:41.263000
2023-08-31T14:44:54
2023-08-31T14:44:54
44,294,727
1,211
518
Apache-2.0
false
2023-07-21T19:06:38
2015-10-15T04:57:57
2023-07-13T15:48:17
2023-07-21T11:00:38
4,114
1,162
457
2
Java
false
false
package com.vladmihalcea.hpjp.spring.data.query.exists; import com.vladmihalcea.hpjp.spring.data.query.exists.config.SpringDataJPAExistsConfiguration; import com.vladmihalcea.hpjp.spring.data.query.exists.domain.Post; import com.vladmihalcea.hpjp.spring.data.query.exists.domain.Post_; import com.vladmihalcea.hpjp.spring.data.query.exists.repository.PostRepository; import jakarta.persistence.EntityManager; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import static org.junit.Assert.assertTrue; import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.exact; /** * @author Vlad Mihalcea */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringDataJPAExistsConfiguration.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class SpringDataJPAExistsTest { protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); @Autowired private TransactionTemplate transactionTemplate; @Autowired private EntityManager entityManager; @Autowired private PostRepository postRepository; /*@Autowired private HypersistenceOptimizer hypersistenceOptimizer;*/ @Before public void init() { try { transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> { entityManager.persist( new Post() .setId(1L) .setTitle("High-Performance Java Persistence") .setSlug("high-performance-java-persistence") ); entityManager.persist( new Post() .setId(2L) .setTitle("Hypersistence Optimizer") .setSlug("hypersistence-optimizer") ); for (long i = 3; i <= 1000; i++) { entityManager.persist( new Post() .setId(i) .setTitle(String.format("Post %d", i)) .setSlug(String.format("post-%d", i)) ); } return null; }); } catch (TransactionException e) { LOGGER.error("Failure", e); } } @Test public void test() { String slug = "high-performance-java-persistence"; //Query by id - Bad Idea assertTrue( postRepository.findBySlug(slug).isPresent() ); //Query by example - Bad Idea assertTrue( postRepository.exists( Example.of( new Post().setSlug(slug), ExampleMatcher.matching() .withIgnorePaths(Post_.ID) .withMatcher(Post_.SLUG, exact()) ) ) ); //hypersistenceOptimizer.getEvents().clear(); assertTrue( postRepository.existsById(1L) ); //assertTrue(hypersistenceOptimizer.getEvents().isEmpty()); //Query using exists - Okayish Idea assertTrue( postRepository.existsBySlug(slug) ); //assertTrue(hypersistenceOptimizer.getEvents().isEmpty()); //Query using exists - Okayish Idea assertTrue( postRepository.existsBySlugWithCount(slug) ); assertTrue( postRepository.existsBySlugWithCase(slug) ); } }
UTF-8
Java
4,175
java
SpringDataJPAExistsTest.java
Java
[ { "context": "her.GenericPropertyMatchers.exact;\n\n/**\n * @author Vlad Mihalcea\n */\n@RunWith(SpringJUnit4ClassRunner.class)\n@Cont", "end": 1269, "score": 0.9998512864112854, "start": 1256, "tag": "NAME", "value": "Vlad Mihalcea" } ]
null
[]
package com.vladmihalcea.hpjp.spring.data.query.exists; import com.vladmihalcea.hpjp.spring.data.query.exists.config.SpringDataJPAExistsConfiguration; import com.vladmihalcea.hpjp.spring.data.query.exists.domain.Post; import com.vladmihalcea.hpjp.spring.data.query.exists.domain.Post_; import com.vladmihalcea.hpjp.spring.data.query.exists.repository.PostRepository; import jakarta.persistence.EntityManager; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import static org.junit.Assert.assertTrue; import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.exact; /** * @author <NAME> */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringDataJPAExistsConfiguration.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class SpringDataJPAExistsTest { protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); @Autowired private TransactionTemplate transactionTemplate; @Autowired private EntityManager entityManager; @Autowired private PostRepository postRepository; /*@Autowired private HypersistenceOptimizer hypersistenceOptimizer;*/ @Before public void init() { try { transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> { entityManager.persist( new Post() .setId(1L) .setTitle("High-Performance Java Persistence") .setSlug("high-performance-java-persistence") ); entityManager.persist( new Post() .setId(2L) .setTitle("Hypersistence Optimizer") .setSlug("hypersistence-optimizer") ); for (long i = 3; i <= 1000; i++) { entityManager.persist( new Post() .setId(i) .setTitle(String.format("Post %d", i)) .setSlug(String.format("post-%d", i)) ); } return null; }); } catch (TransactionException e) { LOGGER.error("Failure", e); } } @Test public void test() { String slug = "high-performance-java-persistence"; //Query by id - Bad Idea assertTrue( postRepository.findBySlug(slug).isPresent() ); //Query by example - Bad Idea assertTrue( postRepository.exists( Example.of( new Post().setSlug(slug), ExampleMatcher.matching() .withIgnorePaths(Post_.ID) .withMatcher(Post_.SLUG, exact()) ) ) ); //hypersistenceOptimizer.getEvents().clear(); assertTrue( postRepository.existsById(1L) ); //assertTrue(hypersistenceOptimizer.getEvents().isEmpty()); //Query using exists - Okayish Idea assertTrue( postRepository.existsBySlug(slug) ); //assertTrue(hypersistenceOptimizer.getEvents().isEmpty()); //Query using exists - Okayish Idea assertTrue( postRepository.existsBySlugWithCount(slug) ); assertTrue( postRepository.existsBySlugWithCase(slug) ); } }
4,168
0.626108
0.622994
124
32.661289
24.936657
94
false
false
0
0
0
0
0
0
0.403226
false
false
4
2f44635f7787b4ecc4886eb312e760abb68e88ac
18,734,647,377,337
03a79e98ec3497dc663cad5753c9ebd053c2a4a6
/test/model/manager/PatientManagerTest.java
e3570ab59bbb605fdb3972c2643cc32e9e8ca854
[]
no_license
cell-life/idart
https://github.com/cell-life/idart
82f31512c294e83daeb5a3602839f3ce546bf112
a213e3e46c3fbac7da79da644d1d3af0affb5c03
refs/heads/master
2021-05-02T02:31:46.273000
2018-02-09T19:16:58
2018-02-09T19:16:58
120,884,421
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model.manager; import java.util.Date; import java.util.List; import java.util.Set; import org.celllife.idart.database.hibernate.AttributeType; import org.celllife.idart.database.hibernate.IdentifierType; import org.celllife.idart.database.hibernate.Patient; import org.celllife.idart.database.hibernate.PatientAttribute; import org.celllife.idart.database.hibernate.PatientAttributeInterface; import org.celllife.idart.database.hibernate.PatientIdentifier; import org.celllife.idart.test.HibernateTest; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class PatientManagerTest extends HibernateTest { private Patient patient; @BeforeMethod public void setup(){ List<AttributeType> types = PatientManager.getAllAttributeTypes(getSession()); for (AttributeType type : types) { getSession().delete(type); } getSession().createQuery("delete from PatientAttribute").executeUpdate(); patient = new Patient(); patient.setPatientId("managerTest"); patient.setClinic(AdministrationManager.getMainClinic(getSession())); patient.setSex('M'); patient.setModified('T'); IdentifierType type = new IdentifierType("type1",1); getSession().save(type); PatientIdentifier e = new PatientIdentifier(); e.setType(type); e.setPatient(patient); e.setValue("attribTest"); patient.getPatientIdentifiers().add(e); getSession().save(patient); getSession().flush(); } @Test public void testGetPatient(){ Patient patient2 = PatientManager.getPatient(getSession(), patient.getPatientId()); Assert.assertNotNull(patient2); Assert.assertEquals(patient.getId(), patient2.getId()); } @Test public void testGetPatient_multipleIdentifiers(){ Patient patient2 = new Patient(); patient2.setPatientId("attribTest1"); patient2.setClinic(AdministrationManager.getMainClinic(getSession())); patient2.setSex('M'); patient2.setModified('T'); PatientIdentifier e = new PatientIdentifier(); e.setType(new IdentifierType("type2",2)); e.setPatient(patient2); e.setValue("attribTest"); patient2.getPatientIdentifiers().add(e); getSession().save(patient2); Patient search = PatientManager.getPatient(getSession(), patient.getPatientId()); Assert.assertNotNull(search); Assert.assertEquals(patient.getId(), search.getId()); } @Test public void testGetPatientsWithAttribute(){ AttributeType t2 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, PatientAttributeInterface.ARV_START_DATE, ""); PatientAttribute att2 = new PatientAttribute(); att2.setPatient(patient); att2.setType(t2); getSession().save(att2); getSession().flush(); List<Integer> list = PatientManager.getPatientsWithAttribute(getSession(), PatientAttributeInterface.ARV_START_DATE); Assert.assertTrue(!list.isEmpty()); Assert.assertEquals(list.get(0).intValue(), patient.getId()); } @Test public void testCheckPatientAttributes_noCorrectType(){ PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv start date", ""); PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "ARV_start Date", ""); PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv START date", ""); getSession().flush(); AttributeType firstType = PatientManager.getAllAttributeTypes(getSession()).get(0); PatientManager.checkPatientAttributes(getSession()); getSession().flush(); List<AttributeType> types = PatientManager.getAllAttributeTypes(getSession()); Assert.assertEquals(types.size(),1); Assert.assertEquals(types.get(0).getName(), firstType.getName()); } @Test public void testCheckPatientAttributes_oneCorrectType(){ PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv start date", ""); PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "ARV_start Date", ""); PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv START date", ""); AttributeType correct = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, PatientAttribute.ARV_START_DATE, ""); getSession().flush(); PatientManager.checkPatientAttributes(getSession()); getSession().flush(); List<AttributeType> types = PatientManager.getAllAttributeTypes(getSession()); Assert.assertEquals(types.size(),1); Assert.assertEquals(types.get(0).getName(), correct.getName()); } @Test public void testCheckPatientAttributes_withPatientAttributes_noCorrectType(){ AttributeType t1 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv start date", ""); PatientAttribute att1 = new PatientAttribute(); att1.setPatient(patient); att1.setType(t1); getSession().save(att1); AttributeType t2 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "ARV_start Date", ""); PatientAttribute att2 = new PatientAttribute(); att1.setPatient(patient); att1.setType(t2); getSession().save(att2); AttributeType t3 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv START date", ""); PatientAttribute att3 = new PatientAttribute(); att1.setPatient(patient); att1.setType(t3); getSession().save(att3); getSession().flush(); AttributeType correct = PatientManager.getAllAttributeTypes(getSession()).get(0); PatientManager.checkPatientAttributes(getSession()); getSession().flush(); List<AttributeType> types = PatientManager.getAllAttributeTypes(getSession()); Assert.assertEquals(types.size(),1); Assert.assertEquals(types.get(0).getName(), correct.getName()); Patient p = PatientManager.getPatient(getSession(), patient.getPatientId()); Set<PatientAttribute> attributes = p.getAttributes(); for (PatientAttribute pa : attributes) { Assert.assertEquals(pa.getType().getName(), correct.getName()); } } @Test public void testCheckPatientAttributes_withPatientAttributes_withCorrectType(){ AttributeType t1 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv start date", ""); PatientAttribute att1 = new PatientAttribute(); att1.setPatient(patient); att1.setType(t1); getSession().save(att1); AttributeType correct = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, PatientAttribute.ARV_START_DATE, ""); PatientAttribute att2 = new PatientAttribute(); att1.setPatient(patient); att1.setType(correct); getSession().save(att2); AttributeType t3 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv START date", ""); PatientAttribute att3 = new PatientAttribute(); att1.setPatient(patient); att1.setType(t3); getSession().save(att3); getSession().flush(); PatientManager.checkPatientAttributes(getSession()); getSession().flush(); List<AttributeType> types = PatientManager.getAllAttributeTypes(getSession()); Assert.assertEquals(types.size(),1); Assert.assertEquals(types.get(0).getName(), correct.getName()); Patient p = PatientManager.getPatient(getSession(), patient.getPatientId()); Set<PatientAttribute> attributes = p.getAttributes(); for (PatientAttribute pa : attributes) { Assert.assertEquals(pa.getType().getName(), correct.getName()); } } }
UTF-8
Java
7,463
java
PatientManagerTest.java
Java
[ { "context": "patient = new Patient();\r\n\t\tpatient.setPatientId(\"managerTest\");\r\n\t\tpatient.setClinic(AdministrationManager.get", "end": 1069, "score": 0.9992402791976929, "start": 1058, "tag": "USERNAME", "value": "managerTest" } ]
null
[]
package model.manager; import java.util.Date; import java.util.List; import java.util.Set; import org.celllife.idart.database.hibernate.AttributeType; import org.celllife.idart.database.hibernate.IdentifierType; import org.celllife.idart.database.hibernate.Patient; import org.celllife.idart.database.hibernate.PatientAttribute; import org.celllife.idart.database.hibernate.PatientAttributeInterface; import org.celllife.idart.database.hibernate.PatientIdentifier; import org.celllife.idart.test.HibernateTest; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class PatientManagerTest extends HibernateTest { private Patient patient; @BeforeMethod public void setup(){ List<AttributeType> types = PatientManager.getAllAttributeTypes(getSession()); for (AttributeType type : types) { getSession().delete(type); } getSession().createQuery("delete from PatientAttribute").executeUpdate(); patient = new Patient(); patient.setPatientId("managerTest"); patient.setClinic(AdministrationManager.getMainClinic(getSession())); patient.setSex('M'); patient.setModified('T'); IdentifierType type = new IdentifierType("type1",1); getSession().save(type); PatientIdentifier e = new PatientIdentifier(); e.setType(type); e.setPatient(patient); e.setValue("attribTest"); patient.getPatientIdentifiers().add(e); getSession().save(patient); getSession().flush(); } @Test public void testGetPatient(){ Patient patient2 = PatientManager.getPatient(getSession(), patient.getPatientId()); Assert.assertNotNull(patient2); Assert.assertEquals(patient.getId(), patient2.getId()); } @Test public void testGetPatient_multipleIdentifiers(){ Patient patient2 = new Patient(); patient2.setPatientId("attribTest1"); patient2.setClinic(AdministrationManager.getMainClinic(getSession())); patient2.setSex('M'); patient2.setModified('T'); PatientIdentifier e = new PatientIdentifier(); e.setType(new IdentifierType("type2",2)); e.setPatient(patient2); e.setValue("attribTest"); patient2.getPatientIdentifiers().add(e); getSession().save(patient2); Patient search = PatientManager.getPatient(getSession(), patient.getPatientId()); Assert.assertNotNull(search); Assert.assertEquals(patient.getId(), search.getId()); } @Test public void testGetPatientsWithAttribute(){ AttributeType t2 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, PatientAttributeInterface.ARV_START_DATE, ""); PatientAttribute att2 = new PatientAttribute(); att2.setPatient(patient); att2.setType(t2); getSession().save(att2); getSession().flush(); List<Integer> list = PatientManager.getPatientsWithAttribute(getSession(), PatientAttributeInterface.ARV_START_DATE); Assert.assertTrue(!list.isEmpty()); Assert.assertEquals(list.get(0).intValue(), patient.getId()); } @Test public void testCheckPatientAttributes_noCorrectType(){ PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv start date", ""); PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "ARV_start Date", ""); PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv START date", ""); getSession().flush(); AttributeType firstType = PatientManager.getAllAttributeTypes(getSession()).get(0); PatientManager.checkPatientAttributes(getSession()); getSession().flush(); List<AttributeType> types = PatientManager.getAllAttributeTypes(getSession()); Assert.assertEquals(types.size(),1); Assert.assertEquals(types.get(0).getName(), firstType.getName()); } @Test public void testCheckPatientAttributes_oneCorrectType(){ PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv start date", ""); PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "ARV_start Date", ""); PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv START date", ""); AttributeType correct = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, PatientAttribute.ARV_START_DATE, ""); getSession().flush(); PatientManager.checkPatientAttributes(getSession()); getSession().flush(); List<AttributeType> types = PatientManager.getAllAttributeTypes(getSession()); Assert.assertEquals(types.size(),1); Assert.assertEquals(types.get(0).getName(), correct.getName()); } @Test public void testCheckPatientAttributes_withPatientAttributes_noCorrectType(){ AttributeType t1 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv start date", ""); PatientAttribute att1 = new PatientAttribute(); att1.setPatient(patient); att1.setType(t1); getSession().save(att1); AttributeType t2 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "ARV_start Date", ""); PatientAttribute att2 = new PatientAttribute(); att1.setPatient(patient); att1.setType(t2); getSession().save(att2); AttributeType t3 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv START date", ""); PatientAttribute att3 = new PatientAttribute(); att1.setPatient(patient); att1.setType(t3); getSession().save(att3); getSession().flush(); AttributeType correct = PatientManager.getAllAttributeTypes(getSession()).get(0); PatientManager.checkPatientAttributes(getSession()); getSession().flush(); List<AttributeType> types = PatientManager.getAllAttributeTypes(getSession()); Assert.assertEquals(types.size(),1); Assert.assertEquals(types.get(0).getName(), correct.getName()); Patient p = PatientManager.getPatient(getSession(), patient.getPatientId()); Set<PatientAttribute> attributes = p.getAttributes(); for (PatientAttribute pa : attributes) { Assert.assertEquals(pa.getType().getName(), correct.getName()); } } @Test public void testCheckPatientAttributes_withPatientAttributes_withCorrectType(){ AttributeType t1 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv start date", ""); PatientAttribute att1 = new PatientAttribute(); att1.setPatient(patient); att1.setType(t1); getSession().save(att1); AttributeType correct = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, PatientAttribute.ARV_START_DATE, ""); PatientAttribute att2 = new PatientAttribute(); att1.setPatient(patient); att1.setType(correct); getSession().save(att2); AttributeType t3 = PatientManager.addAttributeTypeToDatabase(getSession(), Date.class, "arv START date", ""); PatientAttribute att3 = new PatientAttribute(); att1.setPatient(patient); att1.setType(t3); getSession().save(att3); getSession().flush(); PatientManager.checkPatientAttributes(getSession()); getSession().flush(); List<AttributeType> types = PatientManager.getAllAttributeTypes(getSession()); Assert.assertEquals(types.size(),1); Assert.assertEquals(types.get(0).getName(), correct.getName()); Patient p = PatientManager.getPatient(getSession(), patient.getPatientId()); Set<PatientAttribute> attributes = p.getAttributes(); for (PatientAttribute pa : attributes) { Assert.assertEquals(pa.getType().getName(), correct.getName()); } } }
7,463
0.736299
0.727321
197
35.883247
32.016041
135
false
false
0
0
0
0
0
0
2.583756
false
false
4
ace192756eb6b7652fc17c9c1d29c3f71bbf95b1
6,700,149,022,521
6c1cffcd5baf559e1e27785ed2a2a0ab1f461f94
/src/main/java/com/dunzo/coffee/Application.java
6d39711cb1fca9b03021e83f3d6ffe45e2c3eeac
[]
no_license
abinaybingumalla/coffeeMachine
https://github.com/abinaybingumalla/coffeeMachine
09bb17621cd1aaae3604c8f23ca0a4a217cabb3e
51c18fc0cbeae430b8a46bd3cee33cdbcdbeff3e
refs/heads/master
2022-12-05T19:04:19.138000
2020-08-16T19:08:07
2020-08-16T19:08:07
288,005,993
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dunzo.coffee; import com.dunzo.coffee.service.BeverageCompositionService; import com.dunzo.coffee.service.DispenserService; import com.dunzo.coffee.service.FileReaderService; import com.dunzo.coffee.service.ResourceManagerService; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static java.lang.Thread.sleep; public class Application { private static final int OUTLET_COUNT = 2; public static void main(String[] args) throws InterruptedException { //Init all services and load initial/default values FileReaderService fileReaderService = new FileReaderService(); BeverageCompositionService beverageCompositionService = new BeverageCompositionService(fileReaderService); ResourceManagerService resourceManagerService = new ResourceManagerService(fileReaderService); Map<String, Integer> sharedMap = resourceManagerService.getIngredientMap(); ExecutorService executorService = Executors.newFixedThreadPool(OUTLET_COUNT); executorService.submit(new DispenserService(sharedMap, beverageCompositionService, "hot_tea")); executorService.submit(new DispenserService(sharedMap, beverageCompositionService, "hot_coffee")); executorService.submit(new DispenserService(sharedMap, beverageCompositionService, "green_tea")); executorService.submit(new DispenserService(sharedMap, beverageCompositionService, "black_tea")); // This is required to simulate low indicator sleep(1000); resourceManagerService.lowIndicator(); resourceManagerService.refill("hot_milk", 800); executorService.submit(new DispenserService(sharedMap, beverageCompositionService, "hot_tea")); executorService.shutdown(); } }
UTF-8
Java
1,813
java
Application.java
Java
[]
null
[]
package com.dunzo.coffee; import com.dunzo.coffee.service.BeverageCompositionService; import com.dunzo.coffee.service.DispenserService; import com.dunzo.coffee.service.FileReaderService; import com.dunzo.coffee.service.ResourceManagerService; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static java.lang.Thread.sleep; public class Application { private static final int OUTLET_COUNT = 2; public static void main(String[] args) throws InterruptedException { //Init all services and load initial/default values FileReaderService fileReaderService = new FileReaderService(); BeverageCompositionService beverageCompositionService = new BeverageCompositionService(fileReaderService); ResourceManagerService resourceManagerService = new ResourceManagerService(fileReaderService); Map<String, Integer> sharedMap = resourceManagerService.getIngredientMap(); ExecutorService executorService = Executors.newFixedThreadPool(OUTLET_COUNT); executorService.submit(new DispenserService(sharedMap, beverageCompositionService, "hot_tea")); executorService.submit(new DispenserService(sharedMap, beverageCompositionService, "hot_coffee")); executorService.submit(new DispenserService(sharedMap, beverageCompositionService, "green_tea")); executorService.submit(new DispenserService(sharedMap, beverageCompositionService, "black_tea")); // This is required to simulate low indicator sleep(1000); resourceManagerService.lowIndicator(); resourceManagerService.refill("hot_milk", 800); executorService.submit(new DispenserService(sharedMap, beverageCompositionService, "hot_tea")); executorService.shutdown(); } }
1,813
0.774407
0.769994
41
43.219513
37.809864
114
false
false
0
0
0
0
0
0
0.878049
false
false
4
6b785e1e6a73e567af6463bea53d3a6d440756e4
18,167,711,690,364
d47caf2d057600139f3c074700f5f8bbdf2c0ccb
/ol-vsam-api/src/main/java/com/vsam_api/openlegacy/constants/VsamFileProperty.java
98eb2eeb284379a4324a3ad3c231985fb46d1d8c
[]
no_license
omrsgl/vsam-demo
https://github.com/omrsgl/vsam-demo
90c1a2dd6c5ed951a8726de808cea9385c5a6967
d1da643dce981c005c6384b8e0502f937c1977af
refs/heads/master
2023-03-11T00:07:56.713000
2021-02-22T10:38:34
2021-02-22T10:38:34
271,141,300
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vsam_api.openlegacy.constants; public enum VsamFileProperty { type("type"), KEY_OFFSET("keyOffset"), KEY_LENGTH("keyLength"), RECORD_MAX_LENGTH("recordMaxLength"); private String fieldName; VsamFileProperty(String fieldName) { this.fieldName = fieldName; } public String getFieldName() { return fieldName; } }
UTF-8
Java
366
java
VsamFileProperty.java
Java
[]
null
[]
package com.vsam_api.openlegacy.constants; public enum VsamFileProperty { type("type"), KEY_OFFSET("keyOffset"), KEY_LENGTH("keyLength"), RECORD_MAX_LENGTH("recordMaxLength"); private String fieldName; VsamFileProperty(String fieldName) { this.fieldName = fieldName; } public String getFieldName() { return fieldName; } }
366
0.68306
0.68306
15
23.4
27.047613
105
false
false
0
0
0
0
0
0
0.533333
false
false
4
8489dfd7edf47bf7c04339063c107db6e5fd6ab4
35,184,372,095,677
28a67e272f3cb082e697342483d0f760ee7756bd
/ya/src/main/java/com/expleague/lyadzhin/report/sources/SourceCommunicationDomain.java
e783e438c6b1b3ac2fa62ef83c86245f00e96045
[]
no_license
VadimFarutin/yasm4u
https://github.com/VadimFarutin/yasm4u
81655fe85ccf4c823e7c84c4f5dd750e1acafe3e
080bc74422b3c1f23da2ec8ae73d44ded5991844
refs/heads/master
2020-04-27T17:36:20.220000
2019-03-07T12:19:15
2019-03-07T12:19:15
174,528,338
0
0
null
true
2019-05-14T11:23:36
2019-03-08T11:46:07
2019-03-08T11:46:10
2019-05-14T11:21:38
921
0
0
1
Java
false
false
package com.expleague.lyadzhin.report.sources; import com.expleague.yasm4u.Domain; import com.expleague.yasm4u.Joba; import com.expleague.yasm4u.Ref; import com.expleague.yasm4u.Routine; import java.util.HashSet; import java.util.List; import java.util.Set; /** * User: lyadzhin * Date: 04.04.15 12:46 */ public class SourceCommunicationDomain implements Domain { private final Set<SourceResponse> responses = new HashSet<>(); @Override public void publishExecutables(List<Joba> jobs, List<Routine> routines) { routines.add(new PublishSourceRequestExecutorsRoutine(this)); } @Override public void publishReferenceParsers(Ref.Parser parser, Controller controller) { } public void request(String sourceKey) { } void addResponse(SourceResponse response) { responses.add(response); } boolean hasResponse(SourceResponse response) { return responses.contains(response); } public static enum RequestStatus { OK, FAILED } }
UTF-8
Java
976
java
SourceCommunicationDomain.java
Java
[ { "context": "ava.util.List;\nimport java.util.Set;\n\n/**\n * User: lyadzhin\n * Date: 04.04.15 12:46\n */\npublic class SourceCo", "end": 282, "score": 0.9995574951171875, "start": 274, "tag": "USERNAME", "value": "lyadzhin" } ]
null
[]
package com.expleague.lyadzhin.report.sources; import com.expleague.yasm4u.Domain; import com.expleague.yasm4u.Joba; import com.expleague.yasm4u.Ref; import com.expleague.yasm4u.Routine; import java.util.HashSet; import java.util.List; import java.util.Set; /** * User: lyadzhin * Date: 04.04.15 12:46 */ public class SourceCommunicationDomain implements Domain { private final Set<SourceResponse> responses = new HashSet<>(); @Override public void publishExecutables(List<Joba> jobs, List<Routine> routines) { routines.add(new PublishSourceRequestExecutorsRoutine(this)); } @Override public void publishReferenceParsers(Ref.Parser parser, Controller controller) { } public void request(String sourceKey) { } void addResponse(SourceResponse response) { responses.add(response); } boolean hasResponse(SourceResponse response) { return responses.contains(response); } public static enum RequestStatus { OK, FAILED } }
976
0.75
0.735656
44
21.181818
23.085093
81
false
false
0
0
0
0
0
0
0.340909
false
false
4
96cc179c054345855f0e9a6a05931006cc269ed7
4,449,586,168,603
78581ad7f54126749a4f252a911ce17d0166b9ff
/src/main/java/com/index/shiro/UserRealm.java
f0aa5b214f46d6fe17ef5ccae3a4441fc199d00d
[]
no_license
playerlt/ssms
https://github.com/playerlt/ssms
e0212371bb053ddcfd0a79460dc3366583622cd1
558e9435cf61c274e615620eb2a3af6d7a14a1d1
refs/heads/main
2023-01-19T02:05:49.045000
2020-11-26T04:22:01
2020-11-26T04:22:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.index.shiro; import com.index.pojo.User; import com.index.service.UserService; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashSet; import java.util.Set; /** * @author index * @date 2020/8/18 **/ public class UserRealm extends AuthorizingRealm { @Autowired UserService userService; //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("执行了=>授权doGetAuthorizationInfo"); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); String username = (String) getAvailablePrincipal(principalCollection); User user = userService.getByNo(username); //获取角色Id int roleId = user.getRoleId(); Set<String> r = new HashSet<>(); r.add(String.valueOf(user.getRoleId())); info.setRoles(r); // info.addStringPermission("user:add"); return info; } //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("执行了=>认证doGetAuthenticationInfo"); UsernamePasswordToken userToken = (UsernamePasswordToken)authenticationToken; //用户名,密码 从数据库中取 User user = userService.getByNo(userToken.getUsername()); if(user == null) return null; //抛出异常 UnknownAccountException // SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo( // user.getName(), // user.getPassword(), // ByteSource.Util.bytes(user.getName()), // getName() // ); // // return simpleAuthenticationInfo; // //密码认证,shiro做 // return new SimpleAuthenticationInfo("", user.getPassword(), // ByteSource.Util.bytes(user.getSalt()), getName()); //密码认证,shiro做 return new SimpleAuthenticationInfo("", user.getPassword(), getName()); } }
UTF-8
Java
2,398
java
UserRealm.java
Java
[ { "context": "il.HashSet;\nimport java.util.Set;\n\n\n/**\n * @author index\n * @date 2020/8/18\n **/\n\npublic class UserRealm e", "end": 465, "score": 0.9970537424087524, "start": 460, "tag": "USERNAME", "value": "index" } ]
null
[]
package com.index.shiro; import com.index.pojo.User; import com.index.service.UserService; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashSet; import java.util.Set; /** * @author index * @date 2020/8/18 **/ public class UserRealm extends AuthorizingRealm { @Autowired UserService userService; //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("执行了=>授权doGetAuthorizationInfo"); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); String username = (String) getAvailablePrincipal(principalCollection); User user = userService.getByNo(username); //获取角色Id int roleId = user.getRoleId(); Set<String> r = new HashSet<>(); r.add(String.valueOf(user.getRoleId())); info.setRoles(r); // info.addStringPermission("user:add"); return info; } //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("执行了=>认证doGetAuthenticationInfo"); UsernamePasswordToken userToken = (UsernamePasswordToken)authenticationToken; //用户名,密码 从数据库中取 User user = userService.getByNo(userToken.getUsername()); if(user == null) return null; //抛出异常 UnknownAccountException // SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo( // user.getName(), // user.getPassword(), // ByteSource.Util.bytes(user.getName()), // getName() // ); // // return simpleAuthenticationInfo; // //密码认证,shiro做 // return new SimpleAuthenticationInfo("", user.getPassword(), // ByteSource.Util.bytes(user.getSalt()), getName()); //密码认证,shiro做 return new SimpleAuthenticationInfo("", user.getPassword(), getName()); } }
2,398
0.674328
0.671292
85
26.129412
28.445526
130
false
false
0
0
0
0
0
0
0.447059
false
false
4
cc8cdc411c9c6fea504e141b54c694dcd8295806
17,643,725,703,036
c24a54864232b3ffdd84f1ac249791ba7dcea004
/src/GameState/IntroState.java
b0e5104bb4f578d2814683b2b2628197d8252249
[]
no_license
mickey789/LL
https://github.com/mickey789/LL
6bb78057392bfd4cb20c746317fbac60c2d1b9db
df61fdefd2e443cd0488cc76a24d7ef72fa18f95
refs/heads/master
2023-01-03T00:15:20.429000
2020-10-27T20:23:52
2020-10-27T20:23:52
305,261,139
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package GameState; import TileMap.Background; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import lastlong.GamePanel; public class IntroState extends GameState { private Background logo; private int alpha; private int ticks = 0; private final int FADE_IN = 60; private final int LENGTH = 200; private final int FADE_OUT = 60; public IntroState(GameStateManager gsm) { this.gsm = gsm; try { logo = new Background("/Resources/Backgrounds/logo.png", 1); logo.setPosition(0, 0); } catch(Exception e) { e.printStackTrace(); } } public void update() { logo.update(); ticks++; if(ticks < FADE_IN) { alpha = (int) (255 - 255 * (1.0 * ticks / FADE_IN)); if(alpha < 0) alpha = 0; } if(ticks > FADE_IN + LENGTH) { alpha = (int) (255 * (1.0 * ticks - FADE_IN - LENGTH) / FADE_OUT); if(alpha > 255) alpha = 255; } if(ticks > FADE_IN + LENGTH + FADE_OUT) { gsm.setCurrentState(GameStateManager.MENUSTATE); } } public void draw(Graphics2D g) { logo.draw(g); g.fillRect(0, 0, GamePanel.WIDTH, GamePanel.HEIGHT); g.setColor(new Color(0, 0, 0, alpha)); g.fillRect(0, 0, GamePanel.WIDTH, GamePanel.HEIGHT); } public void keyPressed(int k){ if(k == KeyEvent.VK_SPACE){ gsm.setCurrentState(GameStateManager.MENUSTATE); } } public void keyReleased(int k){ } }
UTF-8
Java
1,693
java
IntroState.java
Java
[]
null
[]
package GameState; import TileMap.Background; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import lastlong.GamePanel; public class IntroState extends GameState { private Background logo; private int alpha; private int ticks = 0; private final int FADE_IN = 60; private final int LENGTH = 200; private final int FADE_OUT = 60; public IntroState(GameStateManager gsm) { this.gsm = gsm; try { logo = new Background("/Resources/Backgrounds/logo.png", 1); logo.setPosition(0, 0); } catch(Exception e) { e.printStackTrace(); } } public void update() { logo.update(); ticks++; if(ticks < FADE_IN) { alpha = (int) (255 - 255 * (1.0 * ticks / FADE_IN)); if(alpha < 0) alpha = 0; } if(ticks > FADE_IN + LENGTH) { alpha = (int) (255 * (1.0 * ticks - FADE_IN - LENGTH) / FADE_OUT); if(alpha > 255) alpha = 255; } if(ticks > FADE_IN + LENGTH + FADE_OUT) { gsm.setCurrentState(GameStateManager.MENUSTATE); } } public void draw(Graphics2D g) { logo.draw(g); g.fillRect(0, 0, GamePanel.WIDTH, GamePanel.HEIGHT); g.setColor(new Color(0, 0, 0, alpha)); g.fillRect(0, 0, GamePanel.WIDTH, GamePanel.HEIGHT); } public void keyPressed(int k){ if(k == KeyEvent.VK_SPACE){ gsm.setCurrentState(GameStateManager.MENUSTATE); } } public void keyReleased(int k){ } }
1,693
0.535735
0.511518
67
23.268656
18.890558
78
false
false
0
0
0
0
0
0
0.746269
false
false
4
0e53ec8710952cbd7c50d1cd2fbdae355859f3a0
8,246,337,256,165
9c978a2def8a2edd721bf8d0a100828b27397653
/src/Class7_12Jan/looping.java
0c085ae84a03881a211b3f39ec2b74d099c15f7b
[]
no_license
LanaRechkalova/JavaProjects
https://github.com/LanaRechkalova/JavaProjects
8a6c337b43a49f53692fcfd3f6b831a0203f2cdc
bd56d3fb2c53c186ff1bd8be3e5dba8e963ca12e
refs/heads/master
2020-12-21T06:13:56.151000
2020-01-26T16:21:43
2020-01-26T16:21:43
236,334,030
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Class7_12Jan; public class looping { public static void main(String[] args) { //write a program to print Goodbye, World 5 times in separate lines //System.out.println("Goodbye, World"); int i=1; //1. initializer while(i <= 10) { // 2. condition System.out.println("Goodbye, World"); i++; //increment/decrement // OR ++i } System.out.println("value of i = "+i); System.out.println("end of the program."); } }
UTF-8
Java
436
java
looping.java
Java
[]
null
[]
package Class7_12Jan; public class looping { public static void main(String[] args) { //write a program to print Goodbye, World 5 times in separate lines //System.out.println("Goodbye, World"); int i=1; //1. initializer while(i <= 10) { // 2. condition System.out.println("Goodbye, World"); i++; //increment/decrement // OR ++i } System.out.println("value of i = "+i); System.out.println("end of the program."); } }
436
0.66055
0.639908
19
22
20.13899
67
false
false
0
0
0
0
0
0
1.368421
false
false
4
ea45cbae31d0748c6d7ca99b2aaa138bc626495b
8,246,337,260,193
b079d85075f9f0843533731c0ad3e88baa7bb497
/src/main/java/com/interswitch/techquest/auth/Remote.java
ecb3454ea335f1aa152cfdf7bac3bfa332170c1e
[]
no_license
techquest/java-isw-api-utility-sample
https://github.com/techquest/java-isw-api-utility-sample
b1270fd6db7eed2725c3cb8466cdd27dc7ecf416
9f33f3aa499daf342923bcfd394bbd3be37e2f90
refs/heads/master
2021-05-03T22:56:37.144000
2016-10-26T13:39:44
2016-10-26T13:39:44
71,709,794
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.interswitch.techquest.auth; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import com.interswitch.techquest.auth.utils.ConstantUtils; public class Remote { public static HashMap<String, String> sendGET(String resourceUrl,HashMap<String, String> interswitchAuth) throws Exception { HashMap<String, String> responseMap = new HashMap<String, String>(); URL obj = new URL(resourceUrl); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Authorization",interswitchAuth.get(ConstantUtils.AUTHORIZATION)); con.setRequestProperty("Timestamp", interswitchAuth.get(ConstantUtils.TIMESTAMP)); con.setRequestProperty("Nonce", interswitchAuth.get(ConstantUtils.NONCE)); con.setRequestProperty("Signature", interswitchAuth.get(ConstantUtils.SIGNATURE)); con.setRequestProperty("SignatureMethod",interswitchAuth.get(ConstantUtils.SIGNATURE_METHOD)); int responseCode = con.getResponseCode(); InputStream inputStream; StringBuffer response = new StringBuffer(); int c; try { inputStream = con.getInputStream(); } catch(Exception ex) { inputStream = con.getErrorStream(); } while ((c = inputStream.read()) != -1) { response.append((char) c); } responseMap.put(ConstantUtils.RESPONSE_CODE, String.valueOf(responseCode)); responseMap.put(ConstantUtils.RESPONSE_MESSAGE, response.toString()); return responseMap; } public static HashMap<String, String> sendGET(String resourceUrl,HashMap<String, String> interswitchAuth, HashMap<String, String> extraHeaders) throws Exception { HashMap<String, String> responseMap = new HashMap<String, String>(); URL obj = new URL(resourceUrl); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Authorization",interswitchAuth.get(ConstantUtils.AUTHORIZATION)); con.setRequestProperty("Timestamp", interswitchAuth.get(ConstantUtils.TIMESTAMP)); con.setRequestProperty("Nonce", interswitchAuth.get(ConstantUtils.NONCE)); con.setRequestProperty("Signature", interswitchAuth.get(ConstantUtils.SIGNATURE)); con.setRequestProperty("SignatureMethod",interswitchAuth.get(ConstantUtils.SIGNATURE_METHOD)); if(extraHeaders != null && extraHeaders.size()>0) { Iterator<?> it = extraHeaders.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> pair = (Entry<String, String>)it.next(); con.setRequestProperty(pair.getKey(),pair.getValue()); } } int responseCode = con.getResponseCode(); InputStream inputStream; StringBuffer response = new StringBuffer(); int c; try { inputStream = con.getInputStream(); } catch(Exception ex) { inputStream = con.getErrorStream(); } while ((c = inputStream.read()) != -1) { response.append((char) c); } responseMap.put(ConstantUtils.RESPONSE_CODE, String.valueOf(responseCode)); responseMap.put(ConstantUtils.RESPONSE_MESSAGE, response.toString()); return responseMap; } public static HashMap<String, String> sendPOST(String jsonText, String resourceUrl, HashMap<String, String> interswitchAuth)throws Exception { HashMap<String, String> responseMap = new HashMap<String, String>(); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(resourceUrl); post.setHeader("Authorization", interswitchAuth.get(ConstantUtils.AUTHORIZATION)); post.setHeader("Timestamp", interswitchAuth.get(ConstantUtils.TIMESTAMP)); post.setHeader("Nonce", interswitchAuth.get(ConstantUtils.NONCE)); post.setHeader("Signature", interswitchAuth.get(ConstantUtils.SIGNATURE)); post.setHeader("SignatureMethod", interswitchAuth.get(ConstantUtils.SIGNATURE_METHOD)); StringEntity entity = new StringEntity(jsonText); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode(); HttpEntity httpEntity = response.getEntity(); StringBuffer stringBuffer = new StringBuffer(); if(httpEntity != null){ InputStream inputStream = httpEntity.getContent(); int c; while ((c = inputStream.read()) != -1) { stringBuffer.append((char) c); } } responseMap.put(ConstantUtils.RESPONSE_CODE, String.valueOf(responseCode)); responseMap.put(ConstantUtils.RESPONSE_MESSAGE, stringBuffer.toString()); return responseMap; } public static HashMap<String, String> sendPOST(String jsonText, String resourceUrl, HashMap<String, String> interswitchAuth, HashMap<String, String> extraHeaders)throws Exception { HashMap<String, String> responseMap = new HashMap<String, String>(); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(resourceUrl); post.setHeader("Authorization", interswitchAuth.get(ConstantUtils.AUTHORIZATION)); post.setHeader("Timestamp", interswitchAuth.get(ConstantUtils.TIMESTAMP)); post.setHeader("Nonce", interswitchAuth.get(ConstantUtils.NONCE)); post.setHeader("Signature", interswitchAuth.get(ConstantUtils.SIGNATURE)); post.setHeader("SignatureMethod", interswitchAuth.get(ConstantUtils.SIGNATURE_METHOD)); if(extraHeaders != null && extraHeaders.size()>0) { Iterator<?> it = extraHeaders.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> pair = (Entry<String, String>)it.next(); post.setHeader(pair.getKey(),pair.getValue()); } } StringEntity entity = new StringEntity(jsonText); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode(); HttpEntity httpEntity = response.getEntity(); StringBuffer stringBuffer = new StringBuffer(); if(httpEntity != null){ InputStream inputStream = httpEntity.getContent(); int c; while ((c = inputStream.read()) != -1) { stringBuffer.append((char) c); } } responseMap.put(ConstantUtils.RESPONSE_CODE, String.valueOf(responseCode)); responseMap.put(ConstantUtils.RESPONSE_MESSAGE, stringBuffer.toString()); return responseMap; } }
UTF-8
Java
6,654
java
Remote.java
Java
[]
null
[]
package com.interswitch.techquest.auth; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import com.interswitch.techquest.auth.utils.ConstantUtils; public class Remote { public static HashMap<String, String> sendGET(String resourceUrl,HashMap<String, String> interswitchAuth) throws Exception { HashMap<String, String> responseMap = new HashMap<String, String>(); URL obj = new URL(resourceUrl); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Authorization",interswitchAuth.get(ConstantUtils.AUTHORIZATION)); con.setRequestProperty("Timestamp", interswitchAuth.get(ConstantUtils.TIMESTAMP)); con.setRequestProperty("Nonce", interswitchAuth.get(ConstantUtils.NONCE)); con.setRequestProperty("Signature", interswitchAuth.get(ConstantUtils.SIGNATURE)); con.setRequestProperty("SignatureMethod",interswitchAuth.get(ConstantUtils.SIGNATURE_METHOD)); int responseCode = con.getResponseCode(); InputStream inputStream; StringBuffer response = new StringBuffer(); int c; try { inputStream = con.getInputStream(); } catch(Exception ex) { inputStream = con.getErrorStream(); } while ((c = inputStream.read()) != -1) { response.append((char) c); } responseMap.put(ConstantUtils.RESPONSE_CODE, String.valueOf(responseCode)); responseMap.put(ConstantUtils.RESPONSE_MESSAGE, response.toString()); return responseMap; } public static HashMap<String, String> sendGET(String resourceUrl,HashMap<String, String> interswitchAuth, HashMap<String, String> extraHeaders) throws Exception { HashMap<String, String> responseMap = new HashMap<String, String>(); URL obj = new URL(resourceUrl); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Authorization",interswitchAuth.get(ConstantUtils.AUTHORIZATION)); con.setRequestProperty("Timestamp", interswitchAuth.get(ConstantUtils.TIMESTAMP)); con.setRequestProperty("Nonce", interswitchAuth.get(ConstantUtils.NONCE)); con.setRequestProperty("Signature", interswitchAuth.get(ConstantUtils.SIGNATURE)); con.setRequestProperty("SignatureMethod",interswitchAuth.get(ConstantUtils.SIGNATURE_METHOD)); if(extraHeaders != null && extraHeaders.size()>0) { Iterator<?> it = extraHeaders.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> pair = (Entry<String, String>)it.next(); con.setRequestProperty(pair.getKey(),pair.getValue()); } } int responseCode = con.getResponseCode(); InputStream inputStream; StringBuffer response = new StringBuffer(); int c; try { inputStream = con.getInputStream(); } catch(Exception ex) { inputStream = con.getErrorStream(); } while ((c = inputStream.read()) != -1) { response.append((char) c); } responseMap.put(ConstantUtils.RESPONSE_CODE, String.valueOf(responseCode)); responseMap.put(ConstantUtils.RESPONSE_MESSAGE, response.toString()); return responseMap; } public static HashMap<String, String> sendPOST(String jsonText, String resourceUrl, HashMap<String, String> interswitchAuth)throws Exception { HashMap<String, String> responseMap = new HashMap<String, String>(); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(resourceUrl); post.setHeader("Authorization", interswitchAuth.get(ConstantUtils.AUTHORIZATION)); post.setHeader("Timestamp", interswitchAuth.get(ConstantUtils.TIMESTAMP)); post.setHeader("Nonce", interswitchAuth.get(ConstantUtils.NONCE)); post.setHeader("Signature", interswitchAuth.get(ConstantUtils.SIGNATURE)); post.setHeader("SignatureMethod", interswitchAuth.get(ConstantUtils.SIGNATURE_METHOD)); StringEntity entity = new StringEntity(jsonText); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode(); HttpEntity httpEntity = response.getEntity(); StringBuffer stringBuffer = new StringBuffer(); if(httpEntity != null){ InputStream inputStream = httpEntity.getContent(); int c; while ((c = inputStream.read()) != -1) { stringBuffer.append((char) c); } } responseMap.put(ConstantUtils.RESPONSE_CODE, String.valueOf(responseCode)); responseMap.put(ConstantUtils.RESPONSE_MESSAGE, stringBuffer.toString()); return responseMap; } public static HashMap<String, String> sendPOST(String jsonText, String resourceUrl, HashMap<String, String> interswitchAuth, HashMap<String, String> extraHeaders)throws Exception { HashMap<String, String> responseMap = new HashMap<String, String>(); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(resourceUrl); post.setHeader("Authorization", interswitchAuth.get(ConstantUtils.AUTHORIZATION)); post.setHeader("Timestamp", interswitchAuth.get(ConstantUtils.TIMESTAMP)); post.setHeader("Nonce", interswitchAuth.get(ConstantUtils.NONCE)); post.setHeader("Signature", interswitchAuth.get(ConstantUtils.SIGNATURE)); post.setHeader("SignatureMethod", interswitchAuth.get(ConstantUtils.SIGNATURE_METHOD)); if(extraHeaders != null && extraHeaders.size()>0) { Iterator<?> it = extraHeaders.entrySet().iterator(); while (it.hasNext()) { Entry<String, String> pair = (Entry<String, String>)it.next(); post.setHeader(pair.getKey(),pair.getValue()); } } StringEntity entity = new StringEntity(jsonText); entity.setContentType("application/json"); post.setEntity(entity); HttpResponse response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode(); HttpEntity httpEntity = response.getEntity(); StringBuffer stringBuffer = new StringBuffer(); if(httpEntity != null){ InputStream inputStream = httpEntity.getContent(); int c; while ((c = inputStream.read()) != -1) { stringBuffer.append((char) c); } } responseMap.put(ConstantUtils.RESPONSE_CODE, String.valueOf(responseCode)); responseMap.put(ConstantUtils.RESPONSE_MESSAGE, stringBuffer.toString()); return responseMap; } }
6,654
0.743162
0.74226
196
32.948978
33.736031
179
false
false
0
0
0
0
0
0
2.510204
false
false
4
b992c79814fdfcc6ec32d87f96a35b1a1ee3911a
11,424,613,062,830
e111147549097d4ee7a6a83e81f29defd6e5e35c
/timetable-management-system/rest-api-application/src/main/java/org/vdragun/tms/ui/rest/resource/v1/teacher/TeacherResource.java
4e6dbadeca1defecaeb211f8e166940fd64bcfa3
[]
no_license
VitaliyDragun1990/TMS
https://github.com/VitaliyDragun1990/TMS
6039a15afaa8ad3dbbbc6282fbaa96f210559d31
7414aad113d27feae7b10edac98c38d58e7c4894
refs/heads/master
2022-12-23T10:32:32.478000
2020-10-04T11:33:27
2020-10-04T11:33:27
301,111,321
0
0
null
false
2020-10-04T11:33:28
2020-10-04T11:23:34
2020-10-04T11:30:13
2020-10-04T11:33:28
0
0
0
0
Java
false
false
package org.vdragun.tms.ui.rest.resource.v1.teacher; import static org.springframework.http.HttpStatus.OK; import static org.vdragun.tms.util.WebUtil.getFullRequestUri; import javax.validation.Valid; import javax.validation.constraints.Positive; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.CollectionModel; import org.springframework.hateoas.IanaLinkRelations; import org.springframework.hateoas.Link; import org.springframework.hateoas.MediaTypes; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.vdragun.tms.core.application.service.teacher.TeacherData; import org.vdragun.tms.core.application.service.teacher.TeacherService; import org.vdragun.tms.core.domain.Teacher; import org.vdragun.tms.ui.rest.api.v1.model.TeacherModel; import org.vdragun.tms.ui.rest.exception.ApiError; import org.vdragun.tms.config.Constants.Message; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; /** * REST controller that processes teacher-related requests * * @author Vitaliy Dragun * */ @RestController @RequestMapping( path = TeacherResource.BASE_URL, produces = { MediaType.APPLICATION_JSON_VALUE, MediaTypes.HAL_JSON_VALUE }) @Validated @Tag(name = "teacher", description = "the Teacher API") public class TeacherResource { private static final Logger LOG = LoggerFactory.getLogger(TeacherResource.class); public static final String BASE_URL = "/api/v1/teachers"; @Autowired private TeacherService teacherService; @Autowired private RepresentationModelAssembler<Teacher, TeacherModel> teacherModelAssembler; @Operation( summary = "Find page with teachers available", tags = { "teacher" }) @ApiResponse( responseCode = "200", description = "successful operation", content = { @Content( mediaType = MediaTypes.HAL_JSON_VALUE, array = @ArraySchema(schema = @Schema(implementation = TeacherModel.class))), @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, array = @ArraySchema(schema = @Schema( implementation = TeacherModel.class))) }) @GetMapping @ResponseStatus(OK) public CollectionModel<TeacherModel> getTeachers( @Parameter( required = false, example = "{\"page\": 1, \"size\": 10}") Pageable pageRequest, @Parameter(hidden = true) PagedResourcesAssembler<Teacher> pagedAssembler) { LOG.trace("Received GET request to retrieve teachers, page request:{}, URI={}", pageRequest, getFullRequestUri()); Page<Teacher> page = teacherService.findTeachers(pageRequest); Link selfLink = new Link(getFullRequestUri()); return pagedAssembler.toModel(page, teacherModelAssembler, selfLink); } @Operation( summary = "Find teacher by ID", description = "Returns a single teacher", tags = { "teacher" }) @ApiResponse( responseCode = "200", description = "successful operation", content = { @Content( mediaType = MediaTypes.HAL_JSON_VALUE, schema = @Schema(implementation = TeacherModel.class)), @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = TeacherModel.class)) }) @ApiResponse( responseCode = "404", description = "Teacher not found", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ApiError.class))) @ApiResponse( responseCode = "400", description = "Invalid input", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ApiError.class))) @GetMapping("/{teacherId}") @ResponseStatus(OK) public TeacherModel getTeacherById( @Parameter(description = "Identifier of the teacher to be obtained. Cannot be null or empty.", example = "1") @PathVariable("teacherId") @Positive(message = Message.POSITIVE_ID) Integer teacherId) { LOG.trace("Received GET request to retrieve teacher with id={}, URI={}", teacherId, getFullRequestUri()); return teacherModelAssembler.toModel(teacherService.findTeacherById(teacherId)); } @Operation( summary = "Register new teacher record", tags = { "teacher" }) @ApiResponse( responseCode = "201", description = "Teacher registered", content = { @Content( mediaType = MediaTypes.HAL_JSON_VALUE, schema = @Schema(implementation = TeacherModel.class)), @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = TeacherModel.class)) }) @ApiResponse( responseCode = "400", description = "Invalid input", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ApiError.class))) @PostMapping public ResponseEntity<TeacherModel> registerNewTeacher( @Parameter( description = "Teacher to register. Cannot be null or empty.", required = true, schema = @Schema(implementation = TeacherData.class)) @RequestBody @Valid TeacherData teacherData) { LOG.trace("Received POST request to register new teacher, data={}, URI={}", teacherData, getFullRequestUri()); Teacher teacher = teacherService.registerNewTeacher(teacherData); TeacherModel teacherModel = teacherModelAssembler.toModel(teacher); return ResponseEntity .created(teacherModel.getRequiredLink(IanaLinkRelations.SELF).toUri()) .body(teacherModel); } }
UTF-8
Java
7,529
java
TeacherResource.java
Java
[ { "context": " processes teacher-related requests\n * \n * @author Vitaliy Dragun\n *\n */\n@RestController\n@RequestMapping(\n p", "end": 2169, "score": 0.9998552203178406, "start": 2155, "tag": "NAME", "value": "Vitaliy Dragun" } ]
null
[]
package org.vdragun.tms.ui.rest.resource.v1.teacher; import static org.springframework.http.HttpStatus.OK; import static org.vdragun.tms.util.WebUtil.getFullRequestUri; import javax.validation.Valid; import javax.validation.constraints.Positive; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PagedResourcesAssembler; import org.springframework.hateoas.CollectionModel; import org.springframework.hateoas.IanaLinkRelations; import org.springframework.hateoas.Link; import org.springframework.hateoas.MediaTypes; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.vdragun.tms.core.application.service.teacher.TeacherData; import org.vdragun.tms.core.application.service.teacher.TeacherService; import org.vdragun.tms.core.domain.Teacher; import org.vdragun.tms.ui.rest.api.v1.model.TeacherModel; import org.vdragun.tms.ui.rest.exception.ApiError; import org.vdragun.tms.config.Constants.Message; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; /** * REST controller that processes teacher-related requests * * @author <NAME> * */ @RestController @RequestMapping( path = TeacherResource.BASE_URL, produces = { MediaType.APPLICATION_JSON_VALUE, MediaTypes.HAL_JSON_VALUE }) @Validated @Tag(name = "teacher", description = "the Teacher API") public class TeacherResource { private static final Logger LOG = LoggerFactory.getLogger(TeacherResource.class); public static final String BASE_URL = "/api/v1/teachers"; @Autowired private TeacherService teacherService; @Autowired private RepresentationModelAssembler<Teacher, TeacherModel> teacherModelAssembler; @Operation( summary = "Find page with teachers available", tags = { "teacher" }) @ApiResponse( responseCode = "200", description = "successful operation", content = { @Content( mediaType = MediaTypes.HAL_JSON_VALUE, array = @ArraySchema(schema = @Schema(implementation = TeacherModel.class))), @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, array = @ArraySchema(schema = @Schema( implementation = TeacherModel.class))) }) @GetMapping @ResponseStatus(OK) public CollectionModel<TeacherModel> getTeachers( @Parameter( required = false, example = "{\"page\": 1, \"size\": 10}") Pageable pageRequest, @Parameter(hidden = true) PagedResourcesAssembler<Teacher> pagedAssembler) { LOG.trace("Received GET request to retrieve teachers, page request:{}, URI={}", pageRequest, getFullRequestUri()); Page<Teacher> page = teacherService.findTeachers(pageRequest); Link selfLink = new Link(getFullRequestUri()); return pagedAssembler.toModel(page, teacherModelAssembler, selfLink); } @Operation( summary = "Find teacher by ID", description = "Returns a single teacher", tags = { "teacher" }) @ApiResponse( responseCode = "200", description = "successful operation", content = { @Content( mediaType = MediaTypes.HAL_JSON_VALUE, schema = @Schema(implementation = TeacherModel.class)), @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = TeacherModel.class)) }) @ApiResponse( responseCode = "404", description = "Teacher not found", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ApiError.class))) @ApiResponse( responseCode = "400", description = "Invalid input", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ApiError.class))) @GetMapping("/{teacherId}") @ResponseStatus(OK) public TeacherModel getTeacherById( @Parameter(description = "Identifier of the teacher to be obtained. Cannot be null or empty.", example = "1") @PathVariable("teacherId") @Positive(message = Message.POSITIVE_ID) Integer teacherId) { LOG.trace("Received GET request to retrieve teacher with id={}, URI={}", teacherId, getFullRequestUri()); return teacherModelAssembler.toModel(teacherService.findTeacherById(teacherId)); } @Operation( summary = "Register new teacher record", tags = { "teacher" }) @ApiResponse( responseCode = "201", description = "Teacher registered", content = { @Content( mediaType = MediaTypes.HAL_JSON_VALUE, schema = @Schema(implementation = TeacherModel.class)), @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = TeacherModel.class)) }) @ApiResponse( responseCode = "400", description = "Invalid input", content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ApiError.class))) @PostMapping public ResponseEntity<TeacherModel> registerNewTeacher( @Parameter( description = "Teacher to register. Cannot be null or empty.", required = true, schema = @Schema(implementation = TeacherData.class)) @RequestBody @Valid TeacherData teacherData) { LOG.trace("Received POST request to register new teacher, data={}, URI={}", teacherData, getFullRequestUri()); Teacher teacher = teacherService.registerNewTeacher(teacherData); TeacherModel teacherModel = teacherModelAssembler.toModel(teacher); return ResponseEntity .created(teacherModel.getRequiredLink(IanaLinkRelations.SELF).toUri()) .body(teacherModel); } }
7,521
0.649754
0.645238
175
42.022858
27.712803
118
false
false
0
0
0
0
0
0
0.594286
false
false
4
97b9024843700a574b1a980bb4ad77d3da5ad776
29,600,914,653,964
f60977751c84e54ef045eb06840fbb4aa0a488e7
/src/main/java/com/adventofcode/day7/part1/Solution.java
53c88b9259b3a5ffc28099952a2a944165a161dd
[]
no_license
vsocolov/adventofcode
https://github.com/vsocolov/adventofcode
9448b4161b471d18aa9e7dfde8e27bdd52aad19c
858d4911452eb92f0ade94a750e1fcf1bb9b6c4c
refs/heads/main
2023-01-29T05:07:43.562000
2020-12-12T11:47:06
2020-12-12T11:47:06
318,242,816
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.adventofcode.day7.part1; import com.adventofcode.day7.Node; import java.util.*; import static com.adventofcode.day7.NodeUtils.createEmptyNodes; import static com.adventofcode.day7.NodeUtils.populateNodes; public class Solution { public int count(List<String> inputLines) { final Map<String, Node> nodes = createEmptyNodes(inputLines); populateNodes(inputLines, nodes); final var myBag = nodes.get("shiny gold"); return countParents(myBag); } private int countParents(Node myBag) { if (myBag.getParents().isEmpty()) return 0; int count = 0; final Stack<Node> nodesStack = new Stack<>(); final Set<Node> processedNodes = new HashSet<>(); processedNodes.add(myBag); nodesStack.addAll(myBag.getParents()); while (!nodesStack.isEmpty()) { final var parentBag = nodesStack.pop(); if (!processedNodes.contains(parentBag)) { count++; processedNodes.add(parentBag); nodesStack.addAll(parentBag.getParents()); } } return count; } }
UTF-8
Java
1,162
java
Solution.java
Java
[]
null
[]
package com.adventofcode.day7.part1; import com.adventofcode.day7.Node; import java.util.*; import static com.adventofcode.day7.NodeUtils.createEmptyNodes; import static com.adventofcode.day7.NodeUtils.populateNodes; public class Solution { public int count(List<String> inputLines) { final Map<String, Node> nodes = createEmptyNodes(inputLines); populateNodes(inputLines, nodes); final var myBag = nodes.get("shiny gold"); return countParents(myBag); } private int countParents(Node myBag) { if (myBag.getParents().isEmpty()) return 0; int count = 0; final Stack<Node> nodesStack = new Stack<>(); final Set<Node> processedNodes = new HashSet<>(); processedNodes.add(myBag); nodesStack.addAll(myBag.getParents()); while (!nodesStack.isEmpty()) { final var parentBag = nodesStack.pop(); if (!processedNodes.contains(parentBag)) { count++; processedNodes.add(parentBag); nodesStack.addAll(parentBag.getParents()); } } return count; } }
1,162
0.619621
0.613597
43
26.023256
22.465982
69
false
false
0
0
0
0
0
0
0.511628
false
false
4
ffa0fdf66771e29671db2b5081f3d01c3f2a5758
27,281,632,330,447
7ba1e1aae2f826e4a5091e4b78e85f245bd4246b
/library/src/main/java/android/support/v4/content/AsyncTaskLoaderSpier.java
72f9f8dd9496620e417fc849581fc06d736b824b
[ "Apache-2.0" ]
permissive
CyberEagle/AndroidTestLibrary
https://github.com/CyberEagle/AndroidTestLibrary
4e7c0aae8b4afc93d6cf32502672b9796c160077
44131a2ad75a9ddfd62e7d553486eb8d7d2eaf49
refs/heads/master
2016-09-06T02:45:35.104000
2014-07-31T00:57:57
2014-07-31T00:57:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2013 Cyber Eagle * * 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 android.support.v4.content; import android.os.AsyncTask; import android.os.SystemClock; import br.com.cybereagle.commonlibrary.util.ReflectionUtils; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import static org.mockito.Mockito.*; public class AsyncTaskLoaderSpier { public static <T extends AsyncTaskLoader> T spy(final T asyncTaskLoader, String observerFieldName){ final T spyAsyncTaskLoader = Mockito.spy(asyncTaskLoader); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { new AsyncTask<Void, Void, Object>() { @Override protected Object doInBackground(Void... params) { return spyAsyncTaskLoader.loadInBackground(); } @Override protected void onPostExecute(Object data) { spyAsyncTaskLoader.mLastLoadCompleteTime = SystemClock.uptimeMillis(); spyAsyncTaskLoader.deliverResult(data); } @Override protected void onCancelled(Object data) { spyAsyncTaskLoader.mLastLoadCompleteTime = SystemClock.uptimeMillis(); spyAsyncTaskLoader.onCanceled(data); spyAsyncTaskLoader.executePendingTask(); } }.execute(); return null; } }).when(spyAsyncTaskLoader).executePendingTask(); Field observerField = ReflectionUtils.getInstanceVariable(spyAsyncTaskLoader.getClass(), observerFieldName); ReflectionUtils.removeFinalModifier(observerField); try { ReflectionUtils.set(observerField, spyAsyncTaskLoader, spyAsyncTaskLoader.new ForceLoadContentObserver()); } catch(InvocationTargetException e) { e.printStackTrace(); } return spyAsyncTaskLoader; } }
UTF-8
Java
2,768
java
AsyncTaskLoaderSpier.java
Java
[ { "context": "/*\n * Copyright 2013 Cyber Eagle\n *\n * Licensed under the Apache License, Version ", "end": 32, "score": 0.9998247623443604, "start": 21, "tag": "NAME", "value": "Cyber Eagle" } ]
null
[]
/* * Copyright 2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v4.content; import android.os.AsyncTask; import android.os.SystemClock; import br.com.cybereagle.commonlibrary.util.ReflectionUtils; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import static org.mockito.Mockito.*; public class AsyncTaskLoaderSpier { public static <T extends AsyncTaskLoader> T spy(final T asyncTaskLoader, String observerFieldName){ final T spyAsyncTaskLoader = Mockito.spy(asyncTaskLoader); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { new AsyncTask<Void, Void, Object>() { @Override protected Object doInBackground(Void... params) { return spyAsyncTaskLoader.loadInBackground(); } @Override protected void onPostExecute(Object data) { spyAsyncTaskLoader.mLastLoadCompleteTime = SystemClock.uptimeMillis(); spyAsyncTaskLoader.deliverResult(data); } @Override protected void onCancelled(Object data) { spyAsyncTaskLoader.mLastLoadCompleteTime = SystemClock.uptimeMillis(); spyAsyncTaskLoader.onCanceled(data); spyAsyncTaskLoader.executePendingTask(); } }.execute(); return null; } }).when(spyAsyncTaskLoader).executePendingTask(); Field observerField = ReflectionUtils.getInstanceVariable(spyAsyncTaskLoader.getClass(), observerFieldName); ReflectionUtils.removeFinalModifier(observerField); try { ReflectionUtils.set(observerField, spyAsyncTaskLoader, spyAsyncTaskLoader.new ForceLoadContentObserver()); } catch(InvocationTargetException e) { e.printStackTrace(); } return spyAsyncTaskLoader; } }
2,763
0.653179
0.649928
73
36.917809
30.669584
118
false
false
0
0
0
0
0
0
0.493151
false
false
4
863c0c65ec4f32c912c63f6712e4562fd7bdc1dd
15,333,033,301,019
448b5781dfda55a4ad0a1ba9fb8dc5cbd4054b29
/app/src/main/java/il/co/idocare/mvcviews/loginnative/LoginNativeViewMvc.java
67a7df20ab11c96b3c54343f1b72fddb10f8c015
[]
no_license
techyourchance/idocare-android
https://github.com/techyourchance/idocare-android
b82eec8fcb9102bc37e4836a663298190f0acce6
82bae5b2a12e9f49faf9087f79ad2f9ca6d77983
refs/heads/master
2021-01-18T15:53:45.522000
2020-06-19T15:10:01
2020-06-19T15:10:01
86,685,951
65
20
null
null
null
null
null
null
null
null
null
null
null
null
null
package il.co.idocare.mvcviews.loginnative; import il.co.idocarecore.screens.common.mvcviews.ObservableViewMvc; /** * This MVC view represents the login screen which allows the user to log in using its "native" * credentials */ public interface LoginNativeViewMvc extends ObservableViewMvc<LoginNativeViewMvc.LoginNativeViewMvcListener> { public static final String VIEW_STATE_USERNAME = "username"; public static final String VIEW_STATE_PASSWORD = "password"; /** * This interface should be implemented by classes which instantiate LoginNativeViewMvc in * order to get notifications about input events */ interface LoginNativeViewMvcListener { void onLoginClicked(); void onSignupClicked(); } void onLoginInitiated(); void onLoginCompleted(); }
UTF-8
Java
855
java
LoginNativeViewMvc.java
Java
[ { "context": "public static final String VIEW_STATE_USERNAME = \"username\";\r\n public static final String VIEW_STATE_PASS", "end": 426, "score": 0.9994040727615356, "start": 418, "tag": "USERNAME", "value": "username" }, { "context": "public static final String VIEW_STATE_PASSWORD = \"password\";\r\n\r\n /**\r\n * This interface should be imp", "end": 492, "score": 0.9993775486946106, "start": 484, "tag": "PASSWORD", "value": "password" } ]
null
[]
package il.co.idocare.mvcviews.loginnative; import il.co.idocarecore.screens.common.mvcviews.ObservableViewMvc; /** * This MVC view represents the login screen which allows the user to log in using its "native" * credentials */ public interface LoginNativeViewMvc extends ObservableViewMvc<LoginNativeViewMvc.LoginNativeViewMvcListener> { public static final String VIEW_STATE_USERNAME = "username"; public static final String VIEW_STATE_PASSWORD = "<PASSWORD>"; /** * This interface should be implemented by classes which instantiate LoginNativeViewMvc in * order to get notifications about input events */ interface LoginNativeViewMvcListener { void onLoginClicked(); void onSignupClicked(); } void onLoginInitiated(); void onLoginCompleted(); }
857
0.708772
0.708772
30
26.5
30.280632
95
false
false
0
0
0
0
0
0
0.266667
false
false
4
f353f37e46a645029478c2f1e971b0fcbc31951e
16,149,077,103,791
d51d016d126a155f72078f488cbca38836a9b18f
/Sample2/src/Employee.java
acc724546c9f779db0825582a82fbad5a6681202
[]
no_license
rohit51197/Devops
https://github.com/rohit51197/Devops
611b58acf4fb9c603ec654ef5231f697355af985
b46a7b993865aa47c2a86fa76382742f2db70314
refs/heads/master
2020-12-18T21:41:40.622000
2020-02-04T08:24:24
2020-02-04T08:24:24
235,528,709
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Employee { int eid; String ename; int age; float salary; float annualsal; public void getDetails() { eid=101; ename="rohit"; age=32; salary=1.0f; } public void dispDetails() { System.out.println("Name:"+ename); System.out.println("Annual Salary"+annualsal); } public void calSal() { annualsal=salary*12; } }
UTF-8
Java
381
java
Employee.java
Java
[ { "context": "ublic void getDetails()\r\n {\r\n\t eid=101;\r\n\t ename=\"rohit\";\r\n\t age=32;\r\n\t salary=1.0f;\r\n }\r\n public void di", "end": 160, "score": 0.865863561630249, "start": 155, "tag": "NAME", "value": "rohit" } ]
null
[]
public class Employee { int eid; String ename; int age; float salary; float annualsal; public void getDetails() { eid=101; ename="rohit"; age=32; salary=1.0f; } public void dispDetails() { System.out.println("Name:"+ename); System.out.println("Annual Salary"+annualsal); } public void calSal() { annualsal=salary*12; } }
381
0.611549
0.587927
25
13.08
11.692459
47
false
false
0
0
0
0
0
0
0.76
false
false
4
9a89c3bf23164333c92a85cca52632f068e11a58
13,159,779,844,767
b225932f34b9e3032341de6debd5cfcb2a0cfe03
/what_is_asserted/src/main/java/com/practicalunittesting/CompilerSupportFactory.java
f5e5d073f04b9c5070050daff96204384de5458d
[]
no_license
hervesimon/bad-tests-good-tests-code
https://github.com/hervesimon/bad-tests-good-tests-code
c8f8c842c95aaad853f9b3a1f815b54cb2d01ae3
ecda78922a638b2e6d4ccaa44c0f6ff9f1480143
refs/heads/master
2021-10-25T14:05:12.471000
2013-12-30T20:06:08
2013-12-30T20:06:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.practicalunittesting; public class CompilerSupportFactory { private static CompilerSupport default32BitCompilerSupport; public static CompilerSupport getDefault32BitCompilerSupport() { return default32BitCompilerSupport; } }
UTF-8
Java
260
java
CompilerSupportFactory.java
Java
[]
null
[]
package com.practicalunittesting; public class CompilerSupportFactory { private static CompilerSupport default32BitCompilerSupport; public static CompilerSupport getDefault32BitCompilerSupport() { return default32BitCompilerSupport; } }
260
0.8
0.776923
10
25
25.837957
68
false
false
0
0
0
0
0
0
0.3
false
false
4
24ce4369a20fba6483dda7843f5d118342128a8f
1,838,246,003,374
c2ea97991bfe9eb294d2d2a033b9dbf54033c6f5
/InsertSortDemo.java
fb8720c6151d9bcf7679fab0560842ace5e4e919
[]
no_license
cc397845236/SortAlgorismPractice
https://github.com/cc397845236/SortAlgorismPractice
63251a8ce36a78493b75a5f3dc34192deabfa902
43e161d71b1858222147a218f6480073a3a2135b
refs/heads/master
2020-04-26T13:47:57.545000
2019-03-03T15:21:58
2019-03-03T15:21:58
173,591,372
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class InsertSortDemo { private static void insertSort(int[] array){ for(int i = 0; i < array.length-1; i++){ int j=0; int temp = array[i]; for (j =i-1; j >= 0 && array[j] > temp; j--){ array[j+1] = array[j]; } array[j+1] = temp; } } public static void main(String[] args){ int[] array = {5,4,3,2,1,5,3,21}; int[] array1 = {1,2,3,4,5,6,7}; insertSort(array); System.out.println(array); } }
UTF-8
Java
539
java
InsertSortDemo.java
Java
[]
null
[]
public class InsertSortDemo { private static void insertSort(int[] array){ for(int i = 0; i < array.length-1; i++){ int j=0; int temp = array[i]; for (j =i-1; j >= 0 && array[j] > temp; j--){ array[j+1] = array[j]; } array[j+1] = temp; } } public static void main(String[] args){ int[] array = {5,4,3,2,1,5,3,21}; int[] array1 = {1,2,3,4,5,6,7}; insertSort(array); System.out.println(array); } }
539
0.44898
0.404453
21
24.666666
18.090601
57
false
false
0
0
0
0
0
0
1.190476
false
false
4
66acfe3107fa469439806b8e0db3e350ff120179
17,042,430,284,618
ede5d20a2473025e5fb510385e4bef087446f580
/src/main/java/com/guohuasoft/base/rbac/mappers/UserRoleDao.java
3f4527b63cdb5cd8db6872a19262c76573189ee3
[]
no_license
linfuhaiye/FrogCallButton
https://github.com/linfuhaiye/FrogCallButton
c65d677bdfea7e67f370358fd5bf7de7df57966f
c9af9ca0ff248afc3a6de8611ce1ddfe574e444f
refs/heads/main
2023-05-08T13:47:34.498000
2021-05-26T02:45:15
2021-05-26T02:45:15
370,882,811
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.guohuasoft.base.rbac.mappers; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.guohuasoft.base.rbac.entities.UserRole; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Component; /** * 用户角色操作对象 * * @author chenfuqian */ @Mapper @Component public interface UserRoleDao extends BaseMapper<UserRole> { }
UTF-8
Java
382
java
UserRoleDao.java
Java
[ { "context": "ereotype.Component;\n\n/**\n * 用户角色操作对象\n *\n * @author chenfuqian\n */\n@Mapper\n@Component\npublic interface UserRoleD", "end": 280, "score": 0.9988568425178528, "start": 270, "tag": "USERNAME", "value": "chenfuqian" } ]
null
[]
package com.guohuasoft.base.rbac.mappers; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.guohuasoft.base.rbac.entities.UserRole; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Component; /** * 用户角色操作对象 * * @author chenfuqian */ @Mapper @Component public interface UserRoleDao extends BaseMapper<UserRole> { }
382
0.800546
0.800546
16
21.875
21.621387
59
false
false
0
0
0
0
0
0
0.3125
false
false
4
b463d04cf13c6591932e92191eb4517b4cb38a86
4,320,737,100,258
259d21ed34afe1c2e9ef3c8a962e7afa459bd8e2
/src/RSBerryServer/Model/Character.java
328093ea4a625f2c16bcec8230d967d80e701374
[]
no_license
rsberry/rsberry-server
https://github.com/rsberry/rsberry-server
267aa15d2c14af26ac7f0af7b64aecbe261f32f5
8acacfe75b6027528a41db812f7395fbc6f3e58a
refs/heads/master
2020-12-02T16:23:38.067000
2017-07-14T10:35:49
2017-07-14T10:35:49
96,546,281
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package RSBerryServer.Model; import RSBerryServer.Except.BadLogin; import RSBerryServer.Except.CharacterBanned; import RSBerryServer.Except.CharacterNotFound; import RSBerryServer.Legacy.Stream; import RSBerryServer.Utility.BCrypt; import RSBerryServer.Utility.Database; import java.sql.*; public class Character { private Integer id = null; private String username = null; private String password = null; private Integer x = null; private Integer y = null; private Integer banned = null; private Integer height = null; private Integer rights = null; private Integer member = null; private String last_connection = null; private String last_login = null; private Integer energy = null; private Integer game_time = null; private Integer game_count = null; private Integer look_0 = null; private Integer look_1 = null; private Integer look_2 = null; private Integer look_3 = null; private Integer look_4 = null; private Integer look_5 = null; public static Character read(int id) throws CharacterNotFound { // Create an empty instance of character Character instance = new Character(); // Get the connection Connection connection = Database.getInstance(); try { // Prepare a statement, no SQL injection here mother fuckers PreparedStatement statement = connection.prepareStatement("SELECT * FROM `users` WHERE `id` = ? LIMIT 1;"); // Set the id that we want to look up on statement.setInt(1, id); // Execute the statement statement.execute(); // Pull the results out ResultSet results = statement.getResultSet(); // Go to the last row results.last(); // Get the row number int count = results.getRow(); // If it's 0, there are no rows, so the character doesn't exist if (count < 1) { // Bitch and moan about it throw new CharacterNotFound("Character with ID '" + id + "' doesn't exist."); } // Otherwise, go to the first row results.first(); // Start putting the data into the object instance.id = results.getInt("id"); instance.username = results.getString("username"); instance.password = results.getString("password"); instance.x = results.getInt("x"); instance.y = results.getInt("y"); instance.height = results.getInt("height"); instance.rights = results.getInt("rights"); instance.banned = results.getInt("banned"); instance.member = results.getInt("member"); instance.last_connection = results.getString("last_connection"); instance.last_login = results.getString("last_login"); instance.energy = results.getInt("energy"); instance.game_time = results.getInt("game_time"); instance.game_count = results.getInt("game_count"); instance.look_0 = results.getInt("look_0"); instance.look_1 = results.getInt("look_1"); instance.look_2 = results.getInt("look_2"); instance.look_3 = results.getInt("look_3"); instance.look_4 = results.getInt("look_4"); instance.look_5 = results.getInt("look_5"); } catch (SQLException sqle) { // If the SQL is malformed, fall over here System.out.println(sqle.getMessage()); System.exit(1); } return instance; } public static Character readUsingCredentials(String username, String password) throws CharacterNotFound, CharacterBanned, BadLogin { // Create a holder Character character = null; // Get the connection Connection connection = Database.getInstance(); try { // Prepare a statement PreparedStatement statement = connection.prepareStatement("SELECT `id` FROM `users` WHERE `username` = ? LIMIT 1;"); // Set the username we're looking up on statement.setString(1, username); // Execute the statement statement.execute(); // Get the results ResultSet results = statement.getResultSet(); // Go to the last row results.last(); // Get the row number int count = results.getRow(); // Row number is 0 so there isn't a user with that name if (count < 1) { // User basically logging in with the wrong username. Bubble this exception up so it can be handled later throw new CharacterNotFound("Character with username '" + username + "' doesn't exist."); } // Go to the first row results.first(); // Read the character by it's id character = read(results.getInt("id")); // Is the character banned? if (character.isBanned()) { // Bubble the exception up... further up the code, tell them to fuck off throw new CharacterBanned("This character has been banned."); } // Check if the password they gave us matches the hash we stored // I'm using bcrypt because I want to create a PHP control panel for this later and bcrypt is // best practice over in that land of superior programming languages. if (!BCrypt.checkpw(password, character.getPassword())) { throw new BadLogin("Bad username/password combination"); } // Return the object return character; } catch (SQLException sqle) { // If the SQL is malformed, throw a wobbly and kill the game System.out.println(sqle.getMessage()); // TODO Probably want to throw an exception here so we can save games before everyone is booted System.exit(1); } return character; } public String getUsername() { return username; } public String getPassword() { // We have to do this because the people at bcrypt fucked up // When PHP did it, changing the prefix was stupid. But when *they* did it return password.replace("$2y", "$2a"); } public boolean isAdmin() { if (rights >= 2) { return true; } return false; } public boolean isMod() { // If you are an admin you are also a mod if (rights >= 1) { return true; } return false; } public boolean isBanned() { if (banned >= 1) { return true; } return false; } public Integer getId() { return id; } public Integer getX() { return x; } public Integer getY() { return y; } public Integer getHeight() { return height; } public boolean isMember() { if (member >= 1) { return true; } return false; } public String getLastConnection() { return last_connection; } public String getLastLogin() { return last_login; } public Integer getEnergy() { return energy; } public Integer getGameTime() { return game_time; } public Integer getGameCount() { return game_count; } public Integer getLook0() { return look_0; } public Integer getLook1() { return look_1; } public Integer getLook2() { return look_2; } public Integer getLook3() { return look_3; } public Integer getLook4() { return look_4; } public Integer getLook5() { return look_5; } }
UTF-8
Java
7,896
java
Character.java
Java
[ { "context": " public String getUsername()\n {\n return username;\n }\n\n public String getPassword()\n {\n ", "end": 6147, "score": 0.9973869919776917, "start": 6139, "tag": "USERNAME", "value": "username" }, { "context": "when *they* did it\n return password.replace(\"$2y\", \"$2a\");\n }\n\n public boolean isAdmin()\n ", "end": 6382, "score": 0.9486353993415833, "start": 6379, "tag": "PASSWORD", "value": "$2y" }, { "context": "hey* did it\n return password.replace(\"$2y\", \"$2a\");\n }\n\n public boolean isAdmin()\n {\n ", "end": 6389, "score": 0.9908502697944641, "start": 6385, "tag": "PASSWORD", "value": "\"$2a" } ]
null
[]
package RSBerryServer.Model; import RSBerryServer.Except.BadLogin; import RSBerryServer.Except.CharacterBanned; import RSBerryServer.Except.CharacterNotFound; import RSBerryServer.Legacy.Stream; import RSBerryServer.Utility.BCrypt; import RSBerryServer.Utility.Database; import java.sql.*; public class Character { private Integer id = null; private String username = null; private String password = null; private Integer x = null; private Integer y = null; private Integer banned = null; private Integer height = null; private Integer rights = null; private Integer member = null; private String last_connection = null; private String last_login = null; private Integer energy = null; private Integer game_time = null; private Integer game_count = null; private Integer look_0 = null; private Integer look_1 = null; private Integer look_2 = null; private Integer look_3 = null; private Integer look_4 = null; private Integer look_5 = null; public static Character read(int id) throws CharacterNotFound { // Create an empty instance of character Character instance = new Character(); // Get the connection Connection connection = Database.getInstance(); try { // Prepare a statement, no SQL injection here mother fuckers PreparedStatement statement = connection.prepareStatement("SELECT * FROM `users` WHERE `id` = ? LIMIT 1;"); // Set the id that we want to look up on statement.setInt(1, id); // Execute the statement statement.execute(); // Pull the results out ResultSet results = statement.getResultSet(); // Go to the last row results.last(); // Get the row number int count = results.getRow(); // If it's 0, there are no rows, so the character doesn't exist if (count < 1) { // Bitch and moan about it throw new CharacterNotFound("Character with ID '" + id + "' doesn't exist."); } // Otherwise, go to the first row results.first(); // Start putting the data into the object instance.id = results.getInt("id"); instance.username = results.getString("username"); instance.password = results.getString("password"); instance.x = results.getInt("x"); instance.y = results.getInt("y"); instance.height = results.getInt("height"); instance.rights = results.getInt("rights"); instance.banned = results.getInt("banned"); instance.member = results.getInt("member"); instance.last_connection = results.getString("last_connection"); instance.last_login = results.getString("last_login"); instance.energy = results.getInt("energy"); instance.game_time = results.getInt("game_time"); instance.game_count = results.getInt("game_count"); instance.look_0 = results.getInt("look_0"); instance.look_1 = results.getInt("look_1"); instance.look_2 = results.getInt("look_2"); instance.look_3 = results.getInt("look_3"); instance.look_4 = results.getInt("look_4"); instance.look_5 = results.getInt("look_5"); } catch (SQLException sqle) { // If the SQL is malformed, fall over here System.out.println(sqle.getMessage()); System.exit(1); } return instance; } public static Character readUsingCredentials(String username, String password) throws CharacterNotFound, CharacterBanned, BadLogin { // Create a holder Character character = null; // Get the connection Connection connection = Database.getInstance(); try { // Prepare a statement PreparedStatement statement = connection.prepareStatement("SELECT `id` FROM `users` WHERE `username` = ? LIMIT 1;"); // Set the username we're looking up on statement.setString(1, username); // Execute the statement statement.execute(); // Get the results ResultSet results = statement.getResultSet(); // Go to the last row results.last(); // Get the row number int count = results.getRow(); // Row number is 0 so there isn't a user with that name if (count < 1) { // User basically logging in with the wrong username. Bubble this exception up so it can be handled later throw new CharacterNotFound("Character with username '" + username + "' doesn't exist."); } // Go to the first row results.first(); // Read the character by it's id character = read(results.getInt("id")); // Is the character banned? if (character.isBanned()) { // Bubble the exception up... further up the code, tell them to fuck off throw new CharacterBanned("This character has been banned."); } // Check if the password they gave us matches the hash we stored // I'm using bcrypt because I want to create a PHP control panel for this later and bcrypt is // best practice over in that land of superior programming languages. if (!BCrypt.checkpw(password, character.getPassword())) { throw new BadLogin("Bad username/password combination"); } // Return the object return character; } catch (SQLException sqle) { // If the SQL is malformed, throw a wobbly and kill the game System.out.println(sqle.getMessage()); // TODO Probably want to throw an exception here so we can save games before everyone is booted System.exit(1); } return character; } public String getUsername() { return username; } public String getPassword() { // We have to do this because the people at bcrypt fucked up // When PHP did it, changing the prefix was stupid. But when *they* did it return password.replace("$2y", <PASSWORD>"); } public boolean isAdmin() { if (rights >= 2) { return true; } return false; } public boolean isMod() { // If you are an admin you are also a mod if (rights >= 1) { return true; } return false; } public boolean isBanned() { if (banned >= 1) { return true; } return false; } public Integer getId() { return id; } public Integer getX() { return x; } public Integer getY() { return y; } public Integer getHeight() { return height; } public boolean isMember() { if (member >= 1) { return true; } return false; } public String getLastConnection() { return last_connection; } public String getLastLogin() { return last_login; } public Integer getEnergy() { return energy; } public Integer getGameTime() { return game_time; } public Integer getGameCount() { return game_count; } public Integer getLook0() { return look_0; } public Integer getLook1() { return look_1; } public Integer getLook2() { return look_2; } public Integer getLook3() { return look_3; } public Integer getLook4() { return look_4; } public Integer getLook5() { return look_5; } }
7,902
0.576748
0.570922
251
30.458168
25.726133
134
false
false
0
0
0
0
0
0
0.478088
false
false
4
3422d191fbd56483b0465ccbbd7ea65f41b6dbc6
2,783,138,865,114
5e04564d70699c245e0a5470fac1c81b696b4824
/video-procedure-server/src/main/java/com/westwell/server/service/impl/IdentifyServiceImpl.java
08ec1952fb0fc8596596a0281f03dc57afeb1803
[]
no_license
haizeigh/video
https://github.com/haizeigh/video
7651e64679665ad330ce5fb7f7578a977ee0110e
f49445e508752b1c38ad55d3e337a855b6145488
refs/heads/main
2023-03-27T02:34:43.354000
2021-03-11T03:29:49
2021-03-11T03:29:49
337,028,256
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.westwell.server.service.impl; import com.google.common.base.Strings; import com.westwell.server.common.configs.DataConfig; import com.westwell.server.common.utils.RedisUtils; import com.westwell.server.container.IdentifyContainerManager; import com.westwell.server.dto.CompareSimilarityDto; import com.westwell.server.dto.TaskDetailInfoDto; import com.westwell.server.service.FeatureService; import com.westwell.server.service.IdentifyService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; @Slf4j @Service public class IdentifyServiceImpl implements IdentifyService { @Resource FeatureService featureService; @Resource RedisUtils redisUtils; @Resource IdentifyContainerManager identifyContainerManager; @Override public boolean identifyFaces(TaskDetailInfoDto task, List<String> faceKeyList) throws Exception { return identifyPic(task, faceKeyList); } @Override public boolean identifyBody(TaskDetailInfoDto task, List<String> bodyKeyList) throws Exception { return identifyPic(task, bodyKeyList); } @Override public boolean identifyPic(TaskDetailInfoDto task, List<String> picKeyList) throws Exception { if (CollectionUtils.isEmpty(picKeyList)) { return false; } boolean initBucket = identifyContainerManager.initBucket(picKeyList, task); if (initBucket){ List<String> newFaceKeys = new ArrayList<>(); for (int i = 1; i < picKeyList.size(); i++) { newFaceKeys.add(picKeyList.get(i)); } picKeyList = newFaceKeys; } for (String picKey : picKeyList) { // 把图归队 CompareSimilarityDto compareSimilarityDto = featureService.comparePicWithCollection(task, picKey); if (compareSimilarityDto == null) { continue; } String tempPicColleKey = compareSimilarityDto.getPicColleKey(); // 识别出出来了具体人物 if (!Strings.isNullOrEmpty(tempPicColleKey) && identifyContainerManager.containsKey(tempPicColleKey, task) && !Strings.isNullOrEmpty(identifyContainerManager.getIdentify(tempPicColleKey, task))) { String identify = identifyContainerManager.getIdentify(tempPicColleKey, task); log.info("{}find the student={}" , picKey, identify); redisUtils.putHash(picKey, DataConfig.STUDENT_ID, identify); } // 继续构建底库 /* if (compareSimilarityDto.isOverSimilarity()) { log.info(picKey + "加入底库" + tempPicColleKey); identifyContainerManager.addPicToExistBucket(picKey, tempPicColleKey, task); continue; }*/ if (!Strings.isNullOrEmpty(tempPicColleKey)) { // 归队 log.info(picKey + "加入底库" + tempPicColleKey); identifyContainerManager.addPicToExistBucket(picKey, tempPicColleKey, task); } else { // 增加新的集合 log.info(picKey + "创建新的底库"); identifyContainerManager.addPicToNewBucket(picKey, task); } //判断加入特征底库 仅仅是刚相似 if ( !Strings.isNullOrEmpty(tempPicColleKey) && !compareSimilarityDto.isOverSimilarity() ){ identifyContainerManager.addPicToSpecialBucket(picKey, tempPicColleKey, task); } } return true; } }
UTF-8
Java
3,767
java
IdentifyServiceImpl.java
Java
[]
null
[]
package com.westwell.server.service.impl; import com.google.common.base.Strings; import com.westwell.server.common.configs.DataConfig; import com.westwell.server.common.utils.RedisUtils; import com.westwell.server.container.IdentifyContainerManager; import com.westwell.server.dto.CompareSimilarityDto; import com.westwell.server.dto.TaskDetailInfoDto; import com.westwell.server.service.FeatureService; import com.westwell.server.service.IdentifyService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; @Slf4j @Service public class IdentifyServiceImpl implements IdentifyService { @Resource FeatureService featureService; @Resource RedisUtils redisUtils; @Resource IdentifyContainerManager identifyContainerManager; @Override public boolean identifyFaces(TaskDetailInfoDto task, List<String> faceKeyList) throws Exception { return identifyPic(task, faceKeyList); } @Override public boolean identifyBody(TaskDetailInfoDto task, List<String> bodyKeyList) throws Exception { return identifyPic(task, bodyKeyList); } @Override public boolean identifyPic(TaskDetailInfoDto task, List<String> picKeyList) throws Exception { if (CollectionUtils.isEmpty(picKeyList)) { return false; } boolean initBucket = identifyContainerManager.initBucket(picKeyList, task); if (initBucket){ List<String> newFaceKeys = new ArrayList<>(); for (int i = 1; i < picKeyList.size(); i++) { newFaceKeys.add(picKeyList.get(i)); } picKeyList = newFaceKeys; } for (String picKey : picKeyList) { // 把图归队 CompareSimilarityDto compareSimilarityDto = featureService.comparePicWithCollection(task, picKey); if (compareSimilarityDto == null) { continue; } String tempPicColleKey = compareSimilarityDto.getPicColleKey(); // 识别出出来了具体人物 if (!Strings.isNullOrEmpty(tempPicColleKey) && identifyContainerManager.containsKey(tempPicColleKey, task) && !Strings.isNullOrEmpty(identifyContainerManager.getIdentify(tempPicColleKey, task))) { String identify = identifyContainerManager.getIdentify(tempPicColleKey, task); log.info("{}find the student={}" , picKey, identify); redisUtils.putHash(picKey, DataConfig.STUDENT_ID, identify); } // 继续构建底库 /* if (compareSimilarityDto.isOverSimilarity()) { log.info(picKey + "加入底库" + tempPicColleKey); identifyContainerManager.addPicToExistBucket(picKey, tempPicColleKey, task); continue; }*/ if (!Strings.isNullOrEmpty(tempPicColleKey)) { // 归队 log.info(picKey + "加入底库" + tempPicColleKey); identifyContainerManager.addPicToExistBucket(picKey, tempPicColleKey, task); } else { // 增加新的集合 log.info(picKey + "创建新的底库"); identifyContainerManager.addPicToNewBucket(picKey, task); } //判断加入特征底库 仅仅是刚相似 if ( !Strings.isNullOrEmpty(tempPicColleKey) && !compareSimilarityDto.isOverSimilarity() ){ identifyContainerManager.addPicToSpecialBucket(picKey, tempPicColleKey, task); } } return true; } }
3,767
0.656088
0.654993
112
31.633928
31.447233
110
false
false
0
0
0
0
0
0
0.5625
false
false
4
d66aab70e4dff0191414800ba53d92b81a3b8cc1
22,033,182,284,222
018fc4e5d7029f41e7572d41a1c258a59fa0539d
/src/commandCenter/MessageCollector.java
db2c9839b22706e37c8af04ee95f0ed68b000b3a
[]
no_license
athemase/Minerva
https://github.com/athemase/Minerva
a30227c11c88820a6cef5f4b3695c7ce2d37dd22
b5fe16b1461f443c13e8956a852496718254766f
refs/heads/master
2021-01-10T13:56:57.783000
2015-05-23T11:01:52
2015-05-23T11:01:52
36,117,966
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package commandCenter; import java.io.IOException; import java.util.ArrayList; import data.DebugData; /**一條thread,隨時接收debugger的訊息,告訴minerva*/ public class MessageCollector extends Thread{ private static MessageCollector actionTrigger; /**一般而言,只放一個debugger,(可能可以移除)*/ ArrayList<DebugProcess> cmdArray; /**暫存訊息的buffer*/ StringBuffer strBuffer; DebugData data; char buffer[]; protected MessageCollector(){ cmdArray=new ArrayList<DebugProcess>(); buffer=new char[4096]; this.start(); } public static MessageCollector getInstance(){ if(actionTrigger==null) actionTrigger=new MessageCollector(); return actionTrigger; } public void addCommand(DebugProcess thisCE){ cmdArray.add(thisCE); } public void run(){ while(true){ for(int i=0;i<cmdArray.size();i++){ final DebugProcess thisDP=(DebugProcess)cmdArray.get(i); try{ /**如果debugger未完了,則會丟出IllegalThreadStateException,則try的內容不執行*/ /**否則,會執行這段try的內容(表示debugger已完了)*/ thisDP.getProcess().exitValue(); if(thisDP==CommandCenter.debugBridge.getDebugger()){ strBuffer=null; CommandCenter.debugBridge.removeDebugger(); CommandCenter.debugBridge=null; DebugData.getInstance().setRunning(false); System.err.println(MinervaMessage.TERMINATE); } else{ try { CommandCenter.debugBridge.messageParser(strBuffer.toString()); strBuffer=null; } catch (IOException e){} } cmdArray.remove(thisDP); i--; continue; }catch(IllegalThreadStateException exception){ } try{ /**如果結果抓取完了,則parse結果*/ if(!thisDP.getReader().ready()){ if(strBuffer!=null && CommandCenter.debugBridge.commandCompleted(strBuffer.toString())){ CommandCenter.debugBridge.messageParser(strBuffer.toString()); strBuffer=null; } } if(strBuffer==null) strBuffer=new StringBuffer(); /**否則,則繼續從Process的reader繼續抓取字串*/ int length; while (thisDP.getReader().ready()&&(length=thisDP.getReader().read(buffer,0,buffer.length))!=-1){ strBuffer.append(new String(buffer,0,length)); } }catch(IOException exception){} } if(cmdArray.size()==0){ try { Thread.sleep(300); } catch (InterruptedException e) {} } else{ try { Thread.sleep(30); } catch (InterruptedException e) {} } } } }
UTF-8
Java
2,576
java
MessageCollector.java
Java
[]
null
[]
package commandCenter; import java.io.IOException; import java.util.ArrayList; import data.DebugData; /**一條thread,隨時接收debugger的訊息,告訴minerva*/ public class MessageCollector extends Thread{ private static MessageCollector actionTrigger; /**一般而言,只放一個debugger,(可能可以移除)*/ ArrayList<DebugProcess> cmdArray; /**暫存訊息的buffer*/ StringBuffer strBuffer; DebugData data; char buffer[]; protected MessageCollector(){ cmdArray=new ArrayList<DebugProcess>(); buffer=new char[4096]; this.start(); } public static MessageCollector getInstance(){ if(actionTrigger==null) actionTrigger=new MessageCollector(); return actionTrigger; } public void addCommand(DebugProcess thisCE){ cmdArray.add(thisCE); } public void run(){ while(true){ for(int i=0;i<cmdArray.size();i++){ final DebugProcess thisDP=(DebugProcess)cmdArray.get(i); try{ /**如果debugger未完了,則會丟出IllegalThreadStateException,則try的內容不執行*/ /**否則,會執行這段try的內容(表示debugger已完了)*/ thisDP.getProcess().exitValue(); if(thisDP==CommandCenter.debugBridge.getDebugger()){ strBuffer=null; CommandCenter.debugBridge.removeDebugger(); CommandCenter.debugBridge=null; DebugData.getInstance().setRunning(false); System.err.println(MinervaMessage.TERMINATE); } else{ try { CommandCenter.debugBridge.messageParser(strBuffer.toString()); strBuffer=null; } catch (IOException e){} } cmdArray.remove(thisDP); i--; continue; }catch(IllegalThreadStateException exception){ } try{ /**如果結果抓取完了,則parse結果*/ if(!thisDP.getReader().ready()){ if(strBuffer!=null && CommandCenter.debugBridge.commandCompleted(strBuffer.toString())){ CommandCenter.debugBridge.messageParser(strBuffer.toString()); strBuffer=null; } } if(strBuffer==null) strBuffer=new StringBuffer(); /**否則,則繼續從Process的reader繼續抓取字串*/ int length; while (thisDP.getReader().ready()&&(length=thisDP.getReader().read(buffer,0,buffer.length))!=-1){ strBuffer.append(new String(buffer,0,length)); } }catch(IOException exception){} } if(cmdArray.size()==0){ try { Thread.sleep(300); } catch (InterruptedException e) {} } else{ try { Thread.sleep(30); } catch (InterruptedException e) {} } } } }
2,576
0.669179
0.663317
90
25.533333
21.176611
102
false
false
0
0
0
0
0
0
3.866667
false
false
4
21e75fc1819cae490c068e3cdb4f76a45f3a16a6
14,499,809,639,394
a5d01febfd8d45a61f815b6f5ed447e25fad4959
/Source Code/5.27.0/sources/com/airbnb/lottie/a/a/c.java
b39a5c8dae7a8e2f01d2e41095724c393ef14cf5
[]
no_license
kkagill/Decompiler-IQ-Option
https://github.com/kkagill/Decompiler-IQ-Option
7fe5911f90ed2490687f5d216cb2940f07b57194
c2a9dbbe79a959aa1ab8bb7a89c735e8f9dbc5a6
refs/heads/master
2020-09-14T20:44:49.115000
2019-11-04T06:58:55
2019-11-04T06:58:55
223,236,327
1
0
null
true
2019-11-21T18:17:17
2019-11-21T18:17:16
2019-11-04T07:03:15
2019-11-04T07:02:38
104,586
0
0
0
null
false
false
package com.airbnb.lottie.a.a; import java.util.List; /* compiled from: Content */ public interface c { void a(List<c> list, List<c> list2); String getName(); }
UTF-8
Java
172
java
c.java
Java
[]
null
[]
package com.airbnb.lottie.a.a; import java.util.List; /* compiled from: Content */ public interface c { void a(List<c> list, List<c> list2); String getName(); }
172
0.662791
0.656977
10
16.200001
14.091132
40
false
false
0
0
0
0
0
0
0.5
false
false
4
b47ff6d8a74fc76e43592ed824cc0268b2a6694a
16,552,804,009,025
9c46f1a9f9126713422b3a6f6e3b1e8b4fcc6faa
/dal/ConnectionManager.java
51a6eac86fb60eaf15a99ef558d5b096a5077dd8
[]
no_license
yhlinn/MedSearch
https://github.com/yhlinn/MedSearch
43b7d3e9bdf63c6202e4e9ee800202d6b906e321
27267de45126175ae9785fe44685192705034da9
refs/heads/main
2023-08-03T18:41:19.810000
2021-09-07T04:45:53
2021-09-07T04:45:53
403,842,055
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; // heroku MySQL : mysql://b7ab5ed8616eb3:b01c4920@us-cdbr-east-04.cleardb.com/heroku_41f67c41fc8a134?reconnect=true public class ConnectionManager { // private final String user = "root"; // private final String password = "4611"; // private final String hostName = "localhost"; // private final int port = 3306; // private final String schema = "MedSearch"; // private final String timezone = "UTC"; private final String user = "b7ab5ed8616eb3"; private final String password = "b01c4920"; private final String hostName = "us-cdbr-east-04.cleardb.com"; private final String schema = "heroku_41f67c41fc8a134"; private final int port = 3306; private final String timezone = "UTC"; /** * Get the connection to the DB instance. */ public Connection getConnection() throws SQLException { Connection connection = null; try { Properties connectionProperties = new Properties(); connectionProperties.put("user", this.user); connectionProperties.put("password", this.password); connectionProperties.put("serverTimezone", this.timezone); try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new SQLException(e); } connection = DriverManager.getConnection( "jdbc:mysql://" + this.hostName + ":" + this.port + "/" + this.schema + "?useSSL=false", connectionProperties); } catch (SQLException e) { e.printStackTrace(); throw e; } return connection; } /** * Close the connection to the DB instance. */ public void closeConnection(Connection connection) throws SQLException { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); throw e; } } }
UTF-8
Java
1,966
java
ConnectionManager.java
Java
[ { "context": "l.List;\n\n// heroku MySQL : mysql://b7ab5ed8616eb3:b01c4920@us-cdbr-east-04.cleardb.com/heroku_41f67c41fc8a134?reconnect=true\n\npublic cla", "end": 324, "score": 0.9215349555015564, "start": 288, "tag": "EMAIL", "value": "b01c4920@us-cdbr-east-04.cleardb.com" }, { "context": "ser = \"root\";\n//\tprivate final String password = \"4611\";\n//\tprivate final String hostName = \"localhost\";", "end": 478, "score": 0.9993343353271484, "start": 474, "tag": "PASSWORD", "value": "4611" }, { "context": "timezone = \"UTC\";\n\t\n\tprivate final String user = \"b7ab5ed8616eb3\";\n\tprivate final String password = \"b01c4920\";\n\tp", "end": 697, "score": 0.9993101358413696, "start": 683, "tag": "USERNAME", "value": "b7ab5ed8616eb3" }, { "context": "7ab5ed8616eb3\";\n\tprivate final String password = \"b01c4920\";\n\tprivate final String hostName = \"us-cdbr-east-", "end": 742, "score": 0.9993107318878174, "start": 734, "tag": "PASSWORD", "value": "b01c4920" } ]
null
[]
package dal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; // heroku MySQL : mysql://b7ab5ed8616eb3:<EMAIL>/heroku_41f67c41fc8a134?reconnect=true public class ConnectionManager { // private final String user = "root"; // private final String password = "<PASSWORD>"; // private final String hostName = "localhost"; // private final int port = 3306; // private final String schema = "MedSearch"; // private final String timezone = "UTC"; private final String user = "b7ab5ed8616eb3"; private final String password = "<PASSWORD>"; private final String hostName = "us-cdbr-east-04.cleardb.com"; private final String schema = "heroku_41f67c41fc8a134"; private final int port = 3306; private final String timezone = "UTC"; /** * Get the connection to the DB instance. */ public Connection getConnection() throws SQLException { Connection connection = null; try { Properties connectionProperties = new Properties(); connectionProperties.put("user", this.user); connectionProperties.put("password", this.password); connectionProperties.put("serverTimezone", this.timezone); try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new SQLException(e); } connection = DriverManager.getConnection( "jdbc:mysql://" + this.hostName + ":" + this.port + "/" + this.schema + "?useSSL=false", connectionProperties); } catch (SQLException e) { e.printStackTrace(); throw e; } return connection; } /** * Close the connection to the DB instance. */ public void closeConnection(Connection connection) throws SQLException { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); throw e; } } }
1,945
0.714649
0.683113
69
27.492754
23.417833
115
false
false
0
0
0
0
0
0
2.086957
false
false
4
1ad8bb42e46be8aa9cad957a12f5749455e42bfc
17,772,574,718,571
9e644485083c8c8f73c01ce97742d5deb742b74c
/TestDriver.java
7ce81fd05117b6bd500f0d900b501909a2f088c2
[]
no_license
hkboateng/Java
https://github.com/hkboateng/Java
5034b65f71b517aa69875ea3b0e088f9ee6ecc2e
617e8b5b70cad65a46c0db936eeefe3c5216c233
refs/heads/master
2015-07-12T19:09:16
2014-10-08T17:52:49
2014-10-08T17:52:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cscie97.asn2.Test; import java.io.*; import java.util.*; import org.yaml.snakeyaml.Yaml; import cscie97.asn2.shareddesk.provider.OfficeSpace; import cscie97.asn2.shareddesk.provider.Sharedesk; public class TestDriver { public static void main(String args[]) throws IOException{ processProvider(args[0]); } @SuppressWarnings({ "unused", "rawtypes" }) public static void processProvider(String filename) throws IOException{ Sharedesk sharedesk = Sharedesk.getInstance(); FileReader read = new FileReader(filename); Yaml yaml = new Yaml(); LinkedHashMap test = (LinkedHashMap) yaml.load(read); Map prov = (Map) test.get("provider"); String name = (String) prov.get("name"); String contact = (String)prov.get("contact"); Map pic = (Map)prov.get("picture"); String url = (String) pic .get("url"); String picname = (String) pic .get("name"); String picdesc = (String) pic .get("desc"); sharedesk.createNewOfficeProvider("",name, contact, url, picname, picdesc); Map offSs = (Map) test.get("officeSpaces"); Map offSp = (Map) offSs.get("officeSpace"); String officeSpacename = (String) offSp.get("name"); OfficeSpace officeSpace = sharedesk.createNewOfficeSpace(officeSpacename); Map capacity = (Map) offSp.get("capacity"); int squareFoot = (int)capacity.get("squarefeet"); int noOfpeople = (int)capacity.get("numberOfPeople"); int workspace = (int)capacity.get("workSpaces"); Map oSP = (Map) offSp.get("location"); Double lat = (Double) oSP.get("lat"); Double longi = (Double) oSP.get("long"); Map address = (Map)oSP.get("address"); String street1 = (String) address.get("street1"); String street2 = (String) address.get("street2"); String city = (String) address.get("city"); String state = (String) address.get("state"); String country = (String) address.get("countryCode"); Double zipcode = (Double) address.get("zipcode"); String feature = (String) offSp.get("features"); sharedesk.addFeatureToOfficeSpace(officeSpace.getIdentidfier(), feature); String[] list = feature.split(" "); //int features = feature.size(); System.out.println(list[0]); Map facility = (Map) offSp.get("facility"); String type = (String)facility.get("type"); String category = (String)facility.get("category"); sharedesk.addFacilityTypeToOfficeSpace(officeSpace.getIdentidfier(),type, category); //String[] ret = category.split(" "); //System.out.println(ret[1]); String commonAccess = (String) offSp.get("commonAccess"); System.out.println(commonAccess.replace("-", "\n")); } }
UTF-8
Java
2,621
java
TestDriver.java
Java
[]
null
[]
package cscie97.asn2.Test; import java.io.*; import java.util.*; import org.yaml.snakeyaml.Yaml; import cscie97.asn2.shareddesk.provider.OfficeSpace; import cscie97.asn2.shareddesk.provider.Sharedesk; public class TestDriver { public static void main(String args[]) throws IOException{ processProvider(args[0]); } @SuppressWarnings({ "unused", "rawtypes" }) public static void processProvider(String filename) throws IOException{ Sharedesk sharedesk = Sharedesk.getInstance(); FileReader read = new FileReader(filename); Yaml yaml = new Yaml(); LinkedHashMap test = (LinkedHashMap) yaml.load(read); Map prov = (Map) test.get("provider"); String name = (String) prov.get("name"); String contact = (String)prov.get("contact"); Map pic = (Map)prov.get("picture"); String url = (String) pic .get("url"); String picname = (String) pic .get("name"); String picdesc = (String) pic .get("desc"); sharedesk.createNewOfficeProvider("",name, contact, url, picname, picdesc); Map offSs = (Map) test.get("officeSpaces"); Map offSp = (Map) offSs.get("officeSpace"); String officeSpacename = (String) offSp.get("name"); OfficeSpace officeSpace = sharedesk.createNewOfficeSpace(officeSpacename); Map capacity = (Map) offSp.get("capacity"); int squareFoot = (int)capacity.get("squarefeet"); int noOfpeople = (int)capacity.get("numberOfPeople"); int workspace = (int)capacity.get("workSpaces"); Map oSP = (Map) offSp.get("location"); Double lat = (Double) oSP.get("lat"); Double longi = (Double) oSP.get("long"); Map address = (Map)oSP.get("address"); String street1 = (String) address.get("street1"); String street2 = (String) address.get("street2"); String city = (String) address.get("city"); String state = (String) address.get("state"); String country = (String) address.get("countryCode"); Double zipcode = (Double) address.get("zipcode"); String feature = (String) offSp.get("features"); sharedesk.addFeatureToOfficeSpace(officeSpace.getIdentidfier(), feature); String[] list = feature.split(" "); //int features = feature.size(); System.out.println(list[0]); Map facility = (Map) offSp.get("facility"); String type = (String)facility.get("type"); String category = (String)facility.get("category"); sharedesk.addFacilityTypeToOfficeSpace(officeSpace.getIdentidfier(),type, category); //String[] ret = category.split(" "); //System.out.println(ret[1]); String commonAccess = (String) offSp.get("commonAccess"); System.out.println(commonAccess.replace("-", "\n")); } }
2,621
0.688668
0.682564
68
37.544117
22.429913
89
false
false
0
0
0
0
0
0
2.588235
false
false
4
e3ffe8bff45ed2620f34e806e5c5ebb7bea3dc91
6,545,530,205,791
52dfcba98c26dbef28d573ff156e86dd726456e4
/app/src/main/java/com/berniesanders/connect/adapter/actionalert/ActionAlertHeader.java
6e2ee6452142cd07e7331987ac56450e7890ae6d
[ "Apache-2.0" ]
permissive
prejr-dev/Connect-Android
https://github.com/prejr-dev/Connect-Android
e1a3a387c58d213fa54c6a661343730133121351
f05543bf406ace7f76c26c4e6844b0d7bb6844ba
refs/heads/master
2020-12-28T19:11:22.339000
2016-04-24T19:50:55
2016-04-24T19:50:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.berniesanders.connect.adapter.actionalert; import android.content.Context; import android.support.v7.widget.RecyclerView.Adapter; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.berniesanders.connect.R; import com.berniesanders.connect.recycler.HeaderDecoration; public class ActionAlertHeader extends HeaderDecoration { private final Context mContext; private int mNumAlerts; public ActionAlertHeader(final Context context) { mContext = context; } public void setNumAlerts(final int numAlerts) { mNumAlerts = numAlerts; } @Override public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_header_view, parent, false); return new ViewHolder(view) {}; } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { final String string; if (mNumAlerts == 1) { string = mContext.getString(R.string.live_action_alert); } else { string = mContext.getString(R.string.live_action_alerts, mNumAlerts); } ((TextView) holder.itemView.findViewById(R.id.text)).setText(string); } @Override public int getItemCount(final Adapter adapter) { return adapter.getItemCount() == 0 ? 0 : 1; } }
UTF-8
Java
1,528
java
ActionAlertHeader.java
Java
[]
null
[]
package com.berniesanders.connect.adapter.actionalert; import android.content.Context; import android.support.v7.widget.RecyclerView.Adapter; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.berniesanders.connect.R; import com.berniesanders.connect.recycler.HeaderDecoration; public class ActionAlertHeader extends HeaderDecoration { private final Context mContext; private int mNumAlerts; public ActionAlertHeader(final Context context) { mContext = context; } public void setNumAlerts(final int numAlerts) { mNumAlerts = numAlerts; } @Override public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_header_view, parent, false); return new ViewHolder(view) {}; } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { final String string; if (mNumAlerts == 1) { string = mContext.getString(R.string.live_action_alert); } else { string = mContext.getString(R.string.live_action_alerts, mNumAlerts); } ((TextView) holder.itemView.findViewById(R.id.text)).setText(string); } @Override public int getItemCount(final Adapter adapter) { return adapter.getItemCount() == 0 ? 0 : 1; } }
1,528
0.711387
0.707461
51
28.960785
27.66534
104
false
false
0
0
0
0
0
0
0.509804
false
false
4
7dda1129039459329dd432203c565642c0dcb02c
22,686,017,306,952
35165d5116844acede64d35bdb234f88e6517019
/src/test/java/matrix/TheMatrixStory.java
658c3a90c3e351dc8c6538d294dab849dcfa1576
[]
no_license
rpadalka/SpringTheMatrix
https://github.com/rpadalka/SpringTheMatrix
8a30c05fd7c145e8d885d00f813d84c30309e471
94db782baa8d53a61439582201064065e6e4e1d6
refs/heads/master
2020-12-21T21:42:28.002000
2016-08-28T21:35:43
2016-08-28T21:35:43
62,551,768
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package matrix; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by rpadalka on 10.07.16. */ public class TheMatrixStory extends TestCase { /** * Create the test case * * @param testName name of the test case */ public TheMatrixStory(String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( TheMatrixStory.class ); } public void testApp() throws InterruptedException { ClassPathXmlApplicationContext xmlApplicationContext = new ClassPathXmlApplicationContext("XmlConfigApplicationContext.xml"); Morpheus morpheus = xmlApplicationContext.getBean("morpheus", Morpheus.class); Trinity trinity = xmlApplicationContext.getBean("trinity", Trinity.class); // Тринити выходит из матрицы trinity.setPill(morpheus.getPill()); // Нео выходит из матрицы DrugDealer neo = xmlApplicationContext.getBean("neo", DrugDealer.class); neo.setPill(morpheus.getPill()); // Сравниваем, разные ли таблетки ели Тринити и Нео System.out.println("\nPills are equals? " + (trinity.getPill().getRandomInt() == neo.getPill().getRandomInt()) + "\n"); System.out.println(String.format("Trinity ate a %s pill.", trinity.getPill().getColour().name())); System.out.println(String.format("Mr.Anderson ate a %s pill.", neo.getPill().getColour().name()) + "\n"); while (true) { Thread.sleep(1000); System.out.println("Morpheus has a " + morpheus.getPill().getColour().name() + " pill."); } } }
UTF-8
Java
1,891
java
TheMatrixStory.java
Java
[ { "context": "ClassPathXmlApplicationContext;\n\n/**\n * Created by rpadalka on 10.07.16.\n */\n\npublic class TheMatrixStory ext", "end": 215, "score": 0.999538242816925, "start": 207, "tag": "USERNAME", "value": "rpadalka" } ]
null
[]
package matrix; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by rpadalka on 10.07.16. */ public class TheMatrixStory extends TestCase { /** * Create the test case * * @param testName name of the test case */ public TheMatrixStory(String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( TheMatrixStory.class ); } public void testApp() throws InterruptedException { ClassPathXmlApplicationContext xmlApplicationContext = new ClassPathXmlApplicationContext("XmlConfigApplicationContext.xml"); Morpheus morpheus = xmlApplicationContext.getBean("morpheus", Morpheus.class); Trinity trinity = xmlApplicationContext.getBean("trinity", Trinity.class); // Тринити выходит из матрицы trinity.setPill(morpheus.getPill()); // Нео выходит из матрицы DrugDealer neo = xmlApplicationContext.getBean("neo", DrugDealer.class); neo.setPill(morpheus.getPill()); // Сравниваем, разные ли таблетки ели Тринити и Нео System.out.println("\nPills are equals? " + (trinity.getPill().getRandomInt() == neo.getPill().getRandomInt()) + "\n"); System.out.println(String.format("Trinity ate a %s pill.", trinity.getPill().getColour().name())); System.out.println(String.format("Mr.Anderson ate a %s pill.", neo.getPill().getColour().name()) + "\n"); while (true) { Thread.sleep(1000); System.out.println("Morpheus has a " + morpheus.getPill().getColour().name() + " pill."); } } }
1,891
0.660586
0.655058
53
33.132076
35.745453
133
false
false
0
0
0
0
0
0
0.45283
false
false
4
5e7235677a986e2dd82026a8dbeafea7568c2a18
34,359,791,881
bb29043385d93ea0dbcca76c9a0a1e0d90303840
/src/com/huison/gprsrecord/common/SrvTool.java
1bf2d8fba6c0ac58f0c827c74b7060dbe22441b1
[]
no_license
blackfur/gprsrecord
https://github.com/blackfur/gprsrecord
14aac4048aaf410790995d3686323db162cbe110
d300dbc10268bad6270f8eeab7547c87745606bc
refs/heads/master
2016-08-11T20:42:27.562000
2016-03-11T07:04:42
2016-03-11T07:04:42
43,947,568
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huison.gprsrecord.common; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; public class SrvTool { public final static String CHECK_IN = "http://61.142.253.40:8091/kaoqinQuery.aspx?UserID="; public final static String REPORT_PROBLEM = "http://61.142.253.40:8091/baozhangQuery.aspx?UserID="; public final static String REPORTS = "http://61.142.253.40:8091/BusinessReport.aspx?UserID="; public static String getHtml(String url) { String strResult = ""; try { HttpGet httpRequest = new HttpGet(url); HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == 200) { strResult = EntityUtils.toString(httpResponse.getEntity()); strResult = strResult.replace("(/r/n|/r|/n|/n/r)", ""); } } catch (Exception e) { e.printStackTrace(); } return strResult; } public static String uploadFile(String actionUrl, String path) { String result = null; try { URL url = new URL(actionUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestMethod("POST"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****"); DataOutputStream ds = new DataOutputStream(con.getOutputStream()); FileInputStream fStream = new FileInputStream(path); int bufferSize = 1024; // 1MB byte[] buffer = new byte[bufferSize]; int bufferLength = 0; int length; while ((length = fStream.read(buffer)) != -1) { bufferLength = bufferLength + 1; ds.write(buffer, 0, length); } fStream.close(); ds.flush(); InputStream is = con.getInputStream(); int ch; StringBuilder b = new StringBuilder(); while ((ch = is.read()) != -1) { b.append((char) ch); } result = b.toString(); // new String(b.toString().getBytes("ISO-8859-1"), "utf-8"); ds.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
UTF-8
Java
3,013
java
SrvTool.java
Java
[ { "context": " public final static String CHECK_IN = \"http://61.142.253.40:8091/kaoqinQuery.aspx?UserID=\";\n public final ", "end": 557, "score": 0.9994997382164001, "start": 544, "tag": "IP_ADDRESS", "value": "61.142.253.40" }, { "context": "blic final static String REPORT_PROBLEM = \"http://61.142.253.40:8091/baozhangQuery.aspx?UserID=\";\n public fina", "end": 659, "score": 0.9977640509605408, "start": 646, "tag": "IP_ADDRESS", "value": "61.142.253.40" }, { "context": "\n public final static String REPORTS = \"http://61.142.253.40:8091/BusinessReport.aspx?UserID=\";\n\n public st", "end": 756, "score": 0.9996119737625122, "start": 743, "tag": "IP_ADDRESS", "value": "61.142.253.40" } ]
null
[]
package com.huison.gprsrecord.common; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; public class SrvTool { public final static String CHECK_IN = "http://192.168.3.11:8091/kaoqinQuery.aspx?UserID="; public final static String REPORT_PROBLEM = "http://192.168.3.11:8091/baozhangQuery.aspx?UserID="; public final static String REPORTS = "http://192.168.3.11:8091/BusinessReport.aspx?UserID="; public static String getHtml(String url) { String strResult = ""; try { HttpGet httpRequest = new HttpGet(url); HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == 200) { strResult = EntityUtils.toString(httpResponse.getEntity()); strResult = strResult.replace("(/r/n|/r|/n|/n/r)", ""); } } catch (Exception e) { e.printStackTrace(); } return strResult; } public static String uploadFile(String actionUrl, String path) { String result = null; try { URL url = new URL(actionUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestMethod("POST"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****"); DataOutputStream ds = new DataOutputStream(con.getOutputStream()); FileInputStream fStream = new FileInputStream(path); int bufferSize = 1024; // 1MB byte[] buffer = new byte[bufferSize]; int bufferLength = 0; int length; while ((length = fStream.read(buffer)) != -1) { bufferLength = bufferLength + 1; ds.write(buffer, 0, length); } fStream.close(); ds.flush(); InputStream is = con.getInputStream(); int ch; StringBuilder b = new StringBuilder(); while ((ch = is.read()) != -1) { b.append((char) ch); } result = b.toString(); // new String(b.toString().getBytes("ISO-8859-1"), "utf-8"); ds.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
3,010
0.597411
0.576834
78
37.641026
24.155466
103
false
false
0
0
0
0
0
0
0.820513
false
false
4
5373b5adfdca074f62d0a82e7269817b4929a0a9
27,212,912,850,308
c6b3bf0af1e4204377927961a178674790223ff0
/app/src/main/java/com/u2/testease/handler/CoorHandler.java
39b152c9d4e8b513ffce2fcdf27bc3f9e927b694
[]
no_license
testerhome/screenrecorder
https://github.com/testerhome/screenrecorder
675a2c59986f4631217c037e0c6f42e6ccce036e
8a805ac3220d88bc351f7be4f1cd29694473d1d4
refs/heads/master
2020-06-09T15:58:54.105000
2019-06-25T09:16:29
2019-06-25T09:16:29
193,463,900
5
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.u2.testease.handler; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import com.u2.testease.MainActivity; import com.u2.testease.view.FloatView; public class CoorHandler extends Handler { private final String TAG = "Handler"; private FloatView mLayout; private MainActivity mActivity; public CoorHandler(FloatView mLayout, MainActivity mActivity){ this.mLayout = mLayout; this.mActivity = mActivity; } @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle bundle; String action; String type; String data; String[] coorData; if (this.mLayout == null || !this.mLayout.isShown()){ this.mActivity.showFloatView(); } switch (msg.what){ case 0: bundle = msg.getData(); action = bundle.getString("action", null); type = bundle.getString("type", null); switch (action){ case "start_record": if (mActivity != null){ mActivity.startRecord(); }else { Log.i(TAG, "service is down, start recording failed!"); } break; case "stop_record": if (mActivity != null){ mActivity.stopRecorder(); }else { Log.i(TAG, "service is down, start recording failed!"); } break; case "start_coor": mActivity.moveTaskToBack(true); break; case "start_app": mActivity.moveTaskToBack(true); break; case "coor": data = bundle.getString("data"); assert data != null; coorData = data.substring(1, data.length() - 1).split(","); if ("click".equals(type)){ int x = (int)Float.parseFloat(coorData[0]); int y = (int)Float.parseFloat(coorData[1]); mLayout.setVisibility(View.VISIBLE); mLayout.updateView(x, y, x, y); Message message = new Message(); message.what = 1; sendMessageDelayed(message, 600); }else { int fX = Integer.parseInt(coorData[0]); int fY = Integer.parseInt(coorData[1]); int tX = Integer.parseInt(coorData[2]); int tY = Integer.parseInt(coorData[3]); mLayout.setVisibility(View.VISIBLE); mLayout.updateView(fX, fY, tX, tY); Message message = new Message(); message.what = 1; sendMessageDelayed(message, 600); } case "stop_coor": bundle.putString("action", "stop_coor"); break; } break; case 1: mLayout.clearView(); break; } } public void updateFloatView(FloatView mLayout){ this.mLayout = mLayout; } }
UTF-8
Java
3,677
java
CoorHandler.java
Java
[]
null
[]
package com.u2.testease.handler; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import com.u2.testease.MainActivity; import com.u2.testease.view.FloatView; public class CoorHandler extends Handler { private final String TAG = "Handler"; private FloatView mLayout; private MainActivity mActivity; public CoorHandler(FloatView mLayout, MainActivity mActivity){ this.mLayout = mLayout; this.mActivity = mActivity; } @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle bundle; String action; String type; String data; String[] coorData; if (this.mLayout == null || !this.mLayout.isShown()){ this.mActivity.showFloatView(); } switch (msg.what){ case 0: bundle = msg.getData(); action = bundle.getString("action", null); type = bundle.getString("type", null); switch (action){ case "start_record": if (mActivity != null){ mActivity.startRecord(); }else { Log.i(TAG, "service is down, start recording failed!"); } break; case "stop_record": if (mActivity != null){ mActivity.stopRecorder(); }else { Log.i(TAG, "service is down, start recording failed!"); } break; case "start_coor": mActivity.moveTaskToBack(true); break; case "start_app": mActivity.moveTaskToBack(true); break; case "coor": data = bundle.getString("data"); assert data != null; coorData = data.substring(1, data.length() - 1).split(","); if ("click".equals(type)){ int x = (int)Float.parseFloat(coorData[0]); int y = (int)Float.parseFloat(coorData[1]); mLayout.setVisibility(View.VISIBLE); mLayout.updateView(x, y, x, y); Message message = new Message(); message.what = 1; sendMessageDelayed(message, 600); }else { int fX = Integer.parseInt(coorData[0]); int fY = Integer.parseInt(coorData[1]); int tX = Integer.parseInt(coorData[2]); int tY = Integer.parseInt(coorData[3]); mLayout.setVisibility(View.VISIBLE); mLayout.updateView(fX, fY, tX, tY); Message message = new Message(); message.what = 1; sendMessageDelayed(message, 600); } case "stop_coor": bundle.putString("action", "stop_coor"); break; } break; case 1: mLayout.clearView(); break; } } public void updateFloatView(FloatView mLayout){ this.mLayout = mLayout; } }
3,677
0.443568
0.437857
96
37.302082
20.7997
83
false
false
0
0
0
0
0
0
0.8125
false
false
4
eb6ceb6ef3d0c17099d577d8762524466dd65cd6
10,514,079,996,865
a28af5bb4b28efa5d8736968515e75c8c9bc33ab
/InscriptionsSportives/src/controllers/Mail.java
46b779ade610d351d26c3b0c0052491b47564cb4
[]
no_license
MarkoStefanovic-98/inscriptionsSportives
https://github.com/MarkoStefanovic-98/inscriptionsSportives
fa052d75f822b230220eb31b234a787ac9121446
baacd63d3119dc807b21b1e769100c640590d7ea
refs/heads/master
2020-04-06T23:06:33.019000
2019-05-28T11:57:43
2019-05-28T11:57:43
157,858,290
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controllers; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; import java.util.ResourceBundle; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Mail { public static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); // private static final String host = "smtp.gmail.com"; // private static final String port = "465"; // private static final String login = "bvasseur77@gmail.com"; // private static final String password = "kseqqkrtbynjbaak"; private Properties properties; private Session session; private static Mail INSTANCE = null; // Utiliser avec le singletion private Mail() {} public static Mail getInstance() { if (INSTANCE == null) { INSTANCE = new Mail(); } return INSTANCE; } private static boolean validateEmail(String emailStr) { Matcher matcher = VALID_EMAIL_ADDRESS_REGEX . matcher(emailStr); return matcher.find(); } public void initConnection(){ ResourceBundle config = ResourceBundle.getBundle("config.config"); properties = System.getProperties(); properties.put("mail.smtp.host", config.getString("mail.host")); properties.put("mail.smtp.socketFactory.port", config.getString("mail.port")); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", config.getString("mail.port")); setSession(Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getString("mail.login"), config.getString("mail.password")); } }) ); } public static void sendMail(String recipient, String subject, String text) { Mail mail = getInstance(); if ( validateEmail(recipient) ) { mail.initConnection(); try { ResourceBundle config = ResourceBundle.getBundle("config.config"); Message message = new MimeMessage(mail.session); message.setFrom(new InternetAddress(config.getString("mail.sender"))); message.setRecipients( Message.RecipientType.TO, InternetAddress.parse(recipient) ); message.setSubject(subject); message.setText(text); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } } } private void setSession(Session session) { this.session = session; } }
UTF-8
Java
2,933
java
Mail.java
Java
[ { "context": "\"465\";\n// private static final String login = \"bvasseur77@gmail.com\";\n// private static final String password = \"k", "end": 594, "score": 0.9997919797897339, "start": 574, "tag": "EMAIL", "value": "bvasseur77@gmail.com" }, { "context": "m\";\n// private static final String password = \"kseqqkrtbynjbaak\";\n\n private Properties properties;\n private", "end": 659, "score": 0.9993346333503723, "start": 643, "tag": "PASSWORD", "value": "kseqqkrtbynjbaak" } ]
null
[]
package controllers; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; import java.util.ResourceBundle; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Mail { public static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); // private static final String host = "smtp.gmail.com"; // private static final String port = "465"; // private static final String login = "<EMAIL>"; // private static final String password = "<PASSWORD>"; private Properties properties; private Session session; private static Mail INSTANCE = null; // Utiliser avec le singletion private Mail() {} public static Mail getInstance() { if (INSTANCE == null) { INSTANCE = new Mail(); } return INSTANCE; } private static boolean validateEmail(String emailStr) { Matcher matcher = VALID_EMAIL_ADDRESS_REGEX . matcher(emailStr); return matcher.find(); } public void initConnection(){ ResourceBundle config = ResourceBundle.getBundle("config.config"); properties = System.getProperties(); properties.put("mail.smtp.host", config.getString("mail.host")); properties.put("mail.smtp.socketFactory.port", config.getString("mail.port")); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", config.getString("mail.port")); setSession(Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getString("mail.login"), config.getString("mail.password")); } }) ); } public static void sendMail(String recipient, String subject, String text) { Mail mail = getInstance(); if ( validateEmail(recipient) ) { mail.initConnection(); try { ResourceBundle config = ResourceBundle.getBundle("config.config"); Message message = new MimeMessage(mail.session); message.setFrom(new InternetAddress(config.getString("mail.sender"))); message.setRecipients( Message.RecipientType.TO, InternetAddress.parse(recipient) ); message.setSubject(subject); message.setText(text); Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } } } private void setSession(Session session) { this.session = session; } }
2,914
0.634504
0.630754
84
33.916668
31.313015
147
false
false
0
0
0
0
0
0
0.678571
false
false
4
228793b91c974964c030cf33d8ba5579153d23cd
24,996,709,715,208
c964f136cb29b04215f442775b8552e25168fa6f
/src/StreamExample/StreamExersizes.java
471d23ec97303ed2fb4f57951af5c742b5c8b90a
[]
no_license
BrotherCrayon/StreamExamples
https://github.com/BrotherCrayon/StreamExamples
32af0988e9bb33cca7ec5905ce521da45ecd4404
893026036cbc4e2901d5766c061cf3dd771a950b
refs/heads/master
2020-06-14T20:21:53.671000
2019-07-03T19:33:35
2019-07-03T19:33:35
195,115,592
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package StreamExample; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamExersizes { public static void main(String[] args) { List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); StreamExersizes streams = new StreamExersizes(); System.out.println("Max: " + streams.max(nums)); System.out.println("Min: " + streams.min(nums)); System.out.println("Evens: " + streams.evens(nums)); System.out.println("Odds: " + streams.odds(nums)); System.out.println("Square-even-min: " + streams.squareEvenMin(nums)); } public int squareEvenMin(List<Integer> nums) { // return nums.stream().map(i -> i * i).filter(i -> i % 2 == 0).reduce((a, b) -> Math.min(a, b)).get(); return nums.stream().map(i -> i * i).filter(i -> i % 2 == 0).reduce(Math::min).get(); } // You can use :: to cut short on typing the method, as long as it knows the // parameters of the method. public int max(List<Integer> nums) { // return nums.stream().reduce((a, b) -> Math.max(a, b)).get(); return nums.stream().reduce(Math::max).get(); } public int min(List<Integer> nums) { // return nums.stream().reduce((a, b) -> Math.min(a, b)).get(); return nums.stream().reduce(Math::min).get(); } public int sum(List<Integer> nums) { return nums.stream().reduce((a, b) -> a + b).get(); } public List<Integer> evens(List<Integer> nums) { return nums.stream().filter(i -> i % 2 == 0).collect(Collectors.toList()); } public List<Integer> odds(List<Integer> nums) { return nums.stream().filter(i -> i % 2 != 0).collect(Collectors.toList()); } }
UTF-8
Java
1,611
java
StreamExersizes.java
Java
[]
null
[]
package StreamExample; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamExersizes { public static void main(String[] args) { List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); StreamExersizes streams = new StreamExersizes(); System.out.println("Max: " + streams.max(nums)); System.out.println("Min: " + streams.min(nums)); System.out.println("Evens: " + streams.evens(nums)); System.out.println("Odds: " + streams.odds(nums)); System.out.println("Square-even-min: " + streams.squareEvenMin(nums)); } public int squareEvenMin(List<Integer> nums) { // return nums.stream().map(i -> i * i).filter(i -> i % 2 == 0).reduce((a, b) -> Math.min(a, b)).get(); return nums.stream().map(i -> i * i).filter(i -> i % 2 == 0).reduce(Math::min).get(); } // You can use :: to cut short on typing the method, as long as it knows the // parameters of the method. public int max(List<Integer> nums) { // return nums.stream().reduce((a, b) -> Math.max(a, b)).get(); return nums.stream().reduce(Math::max).get(); } public int min(List<Integer> nums) { // return nums.stream().reduce((a, b) -> Math.min(a, b)).get(); return nums.stream().reduce(Math::min).get(); } public int sum(List<Integer> nums) { return nums.stream().reduce((a, b) -> a + b).get(); } public List<Integer> evens(List<Integer> nums) { return nums.stream().filter(i -> i % 2 == 0).collect(Collectors.toList()); } public List<Integer> odds(List<Integer> nums) { return nums.stream().filter(i -> i % 2 != 0).collect(Collectors.toList()); } }
1,611
0.646803
0.635009
48
32.583332
29.045103
104
false
false
0
0
0
0
0
0
1.770833
false
false
4
0665fc71488bee94971b0d4d2520bf184bcb0d95
15,238,544,013,456
525b0378990017ad68b689ce8ff005ad4d50bade
/src/main/java/leetcode11/Solution22.java
1aa364f8aa59f7ab44e2c96dcfae39dc0715b96b
[]
no_license
manghuang/Leetcode2
https://github.com/manghuang/Leetcode2
f0d4142b16d41e1da9f732ab833269765430bfe5
42de7597653dec3d4bc4ff2327d9cddd5ff03344
refs/heads/master
2023-03-23T09:40:00.348000
2021-03-20T03:09:12
2021-03-20T03:09:12
281,826,729
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode11; import java.util.Arrays; public class Solution22 { public int numOfSubarrays(int[] arr, int k, int threshold) { if(arr == null || arr.length == 0 || k <= 0 || k > arr.length){ return 0; } int length = arr.length; int res = 0; int temp = 0; for (int i = 0; i <length-k+1; i++) { if(i == 0){ for(int j=i; j<i+k; j++){ temp += arr[j]; } }else { temp = temp - arr[i-1] + arr[i+k-1]; } if(temp / k >= threshold){ res++; } } return res; } }
UTF-8
Java
690
java
Solution22.java
Java
[]
null
[]
package leetcode11; import java.util.Arrays; public class Solution22 { public int numOfSubarrays(int[] arr, int k, int threshold) { if(arr == null || arr.length == 0 || k <= 0 || k > arr.length){ return 0; } int length = arr.length; int res = 0; int temp = 0; for (int i = 0; i <length-k+1; i++) { if(i == 0){ for(int j=i; j<i+k; j++){ temp += arr[j]; } }else { temp = temp - arr[i-1] + arr[i+k-1]; } if(temp / k >= threshold){ res++; } } return res; } }
690
0.386957
0.366667
32
20.5625
18.627831
71
false
false
0
0
0
0
0
0
0.6875
false
false
4
592c2d778e7759a8d473ec2b94b15fdd20d1eb80
2,705,829,454,671
ace925b2ac64b9c8496610f0a1d72b29084c936f
/app/src/main/java/com/example/pwpb/SharedPref.java
c0bea95c531dfc9b32a68a7d9f7e1d09277613aa
[]
no_license
danarahnaf/P
https://github.com/danarahnaf/P
feb49542502eba32f2226beb18c18210474c4838
97c412c9f57ade6dba8871b55ea6ae6e95528316
refs/heads/master
2020-11-24T10:50:19.936000
2020-01-19T09:05:56
2020-01-19T09:05:56
228,115,607
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.pwpb; import android.content.Context; import android.content.SharedPreferences; public class SharedPref { SharedPreferences mySharedPref; public SharedPref(Context context){ mySharedPref = context.getSharedPreferences("filename", Context.MODE_PRIVATE); } public void SetTheme(String string) { SharedPreferences.Editor editor = mySharedPref.edit(); editor.putString("theme", string); editor.commit(); } public String LoadTheme() { String state = mySharedPref.getString("theme", "1"); return state; } }
UTF-8
Java
603
java
SharedPref.java
Java
[]
null
[]
package com.example.pwpb; import android.content.Context; import android.content.SharedPreferences; public class SharedPref { SharedPreferences mySharedPref; public SharedPref(Context context){ mySharedPref = context.getSharedPreferences("filename", Context.MODE_PRIVATE); } public void SetTheme(String string) { SharedPreferences.Editor editor = mySharedPref.edit(); editor.putString("theme", string); editor.commit(); } public String LoadTheme() { String state = mySharedPref.getString("theme", "1"); return state; } }
603
0.684909
0.68325
24
24.125
23.281452
86
false
false
0
0
0
0
0
0
0.541667
false
false
4
060ee4308cbc0a7986eff05457cfd37f26f30ee3
17,008,070,539,337
ce64b38685a7273063b51c30cdab793bdaf11167
/src/UserInfo/Kitchen.java
8c556eb9e9a065f22d6d2ee47d2f14edaaed9d29
[]
no_license
hacheson/CookingWithFriends
https://github.com/hacheson/CookingWithFriends
173a2e843c1fac82884952e132e5b07dbee87a37
fae4c2597563606518ef2e32eb7153eb333f655d
refs/heads/master
2020-12-25T17:04:42.667000
2013-04-27T23:30:48
2013-04-27T23:30:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package UserInfo; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; /** * @author hacheson * Represents a kitchen object. Kitchens have users, events, and a menu. */ public class Kitchen implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private HashSet<String> _userIDs; private HashSet<Event> _events; private HashSet<Recipe> _recipes; private HashMap<String, ArrayList<String>> _ingToUsers; private String _id, _name; private HashSet<String> _activeUsers; private HashSet<String> _requestedUsers; //TODO: Create a message board. //private ArrayList<String> _messageBoard; public Kitchen(HashSet<String> users, HashSet<Event> events, HashSet<Recipe> recipes, HashSet<String> activeUsers, HashSet<String> requestedUsers){ _userIDs = users; _events = events; _recipes = recipes; _ingToUsers = new HashMap<String, ArrayList<String>>(); _activeUsers = activeUsers; _requestedUsers = requestedUsers; } public Kitchen(String name){ _userIDs = new HashSet<String>(); _events = new HashSet<Event>(); _recipes = new HashSet<Recipe>(); _ingToUsers = new HashMap<String, ArrayList<String>>(); _activeUsers = new HashSet<String>(); _requestedUsers = new HashSet<String>(); _name = name; } public String getName(){ return _name; } public void addActiveUser(String user){ _activeUsers.add(user); } public void addRequestedUser(String user){ _requestedUsers.add(user); } public void removeActiveUser(String user){ _activeUsers.remove(user); } public void removeRequestedUser(String user){ _requestedUsers.remove(user); } public HashSet<String> getActiveUsers(){ return _activeUsers; } public HashSet<String> getRequestedUsers(){ return _requestedUsers; } /** * Sets the id of the kitchen object. * @param id */ public void setId(String id){ _id = id; } /** * Returns the string id. * @return */ public String getId(){ return _id; } /** * Adds a user to the kitchen. * @param u User to add to the kitchen. */ public void addUser(String u){ _userIDs.add(u); } /** * Removes a user from the kitchen. * @param u User to remove from kitchen. */ public void removeUser(String u){ _userIDs.remove(u); } /** * Adds an event to the kitchen. * @param e Event e to add to kitchen. */ public void addEvent(Event e){ _events.add(e); } /** * Removes an event from the kitchen. * @param e Event to remove from kitchen. */ public void removeEvent(Event e){ _events.remove(e); } /** * Adds a recipe to the panel. * @param r Recipe to remove from panel. */ public void addRecipe(Recipe r){ _recipes.add(r); } /** * Removes a recipe from the panel. * @param r */ public void removeRecipe(Recipe r){ _recipes.remove(r); } /** * Removes all recipes from the kitchen. */ public void removeAllRecipes(){ _recipes = new HashSet<Recipe>(); } @Override public String toString() { return "Kitchen [_users=" + _userIDs + ", _events=" + _events + ", _recipes=" + _recipes + ", _id=" + _id + "]"; } public HashSet<String> getUsers(){ return _userIDs; } }
UTF-8
Java
3,254
java
Kitchen.java
Java
[ { "context": "HashMap;\nimport java.util.HashSet;\n\n/**\n * @author hacheson\n * Represents a kitchen object. Kitchens have use", "end": 164, "score": 0.9929221272468567, "start": 156, "tag": "USERNAME", "value": "hacheson" } ]
null
[]
/** * */ package UserInfo; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; /** * @author hacheson * Represents a kitchen object. Kitchens have users, events, and a menu. */ public class Kitchen implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private HashSet<String> _userIDs; private HashSet<Event> _events; private HashSet<Recipe> _recipes; private HashMap<String, ArrayList<String>> _ingToUsers; private String _id, _name; private HashSet<String> _activeUsers; private HashSet<String> _requestedUsers; //TODO: Create a message board. //private ArrayList<String> _messageBoard; public Kitchen(HashSet<String> users, HashSet<Event> events, HashSet<Recipe> recipes, HashSet<String> activeUsers, HashSet<String> requestedUsers){ _userIDs = users; _events = events; _recipes = recipes; _ingToUsers = new HashMap<String, ArrayList<String>>(); _activeUsers = activeUsers; _requestedUsers = requestedUsers; } public Kitchen(String name){ _userIDs = new HashSet<String>(); _events = new HashSet<Event>(); _recipes = new HashSet<Recipe>(); _ingToUsers = new HashMap<String, ArrayList<String>>(); _activeUsers = new HashSet<String>(); _requestedUsers = new HashSet<String>(); _name = name; } public String getName(){ return _name; } public void addActiveUser(String user){ _activeUsers.add(user); } public void addRequestedUser(String user){ _requestedUsers.add(user); } public void removeActiveUser(String user){ _activeUsers.remove(user); } public void removeRequestedUser(String user){ _requestedUsers.remove(user); } public HashSet<String> getActiveUsers(){ return _activeUsers; } public HashSet<String> getRequestedUsers(){ return _requestedUsers; } /** * Sets the id of the kitchen object. * @param id */ public void setId(String id){ _id = id; } /** * Returns the string id. * @return */ public String getId(){ return _id; } /** * Adds a user to the kitchen. * @param u User to add to the kitchen. */ public void addUser(String u){ _userIDs.add(u); } /** * Removes a user from the kitchen. * @param u User to remove from kitchen. */ public void removeUser(String u){ _userIDs.remove(u); } /** * Adds an event to the kitchen. * @param e Event e to add to kitchen. */ public void addEvent(Event e){ _events.add(e); } /** * Removes an event from the kitchen. * @param e Event to remove from kitchen. */ public void removeEvent(Event e){ _events.remove(e); } /** * Adds a recipe to the panel. * @param r Recipe to remove from panel. */ public void addRecipe(Recipe r){ _recipes.add(r); } /** * Removes a recipe from the panel. * @param r */ public void removeRecipe(Recipe r){ _recipes.remove(r); } /** * Removes all recipes from the kitchen. */ public void removeAllRecipes(){ _recipes = new HashSet<Recipe>(); } @Override public String toString() { return "Kitchen [_users=" + _userIDs + ", _events=" + _events + ", _recipes=" + _recipes + ", _id=" + _id + "]"; } public HashSet<String> getUsers(){ return _userIDs; } }
3,254
0.664106
0.663798
163
18.96319
18.847105
115
false
false
0
0
0
0
0
0
1.460123
false
false
4
587b9a8725ffb45c52e5d34a790acf420db9abb3
14,379,550,546,393
11bd46494d46cdfabf7c33fde1b4c384cf1e49dc
/java/FenwickDouble.java
0d44bebbf10f26bc50a243c42c3f292b185c0599
[ "MIT" ]
permissive
petuhovskiy/Templates-CP
https://github.com/petuhovskiy/Templates-CP
e3f15b0ca1ad27073f9013d845fbafde07ae46c2
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
refs/heads/master
2021-01-17T04:01:06.072000
2019-10-05T17:05:42
2019-10-05T17:05:42
42,240,486
9
6
MIT
false
2018-02-03T15:32:29
2015-09-10T11:27:42
2017-11-12T12:28:23
2018-02-03T15:32:29
106
5
4
0
C++
false
null
package com.petukhovsky.solve.lib; import java.util.Arrays; /** * Created by petuh on 2/2/2016. */ public class FenwickDouble { double[] data; int n; public FenwickDouble(int n) { this.n = n; this.data = new double[n]; } public void inc(int pos, double delta) { for (int i = pos; i < n; i |= i + 1) data[i] += delta; } public double sum(int r) { double res = 0; for (int i = r; i >= 0; i = (i&(i+1))-1) res += data[i]; return res; } public double sum(int l, int r) { return sum(r) - sum(l - 1); } public int size() { return n; } }
UTF-8
Java
677
java
FenwickDouble.java
Java
[ { "context": ".lib;\n\nimport java.util.Arrays;\n\n/**\n * Created by petuh on 2/2/2016.\n */\npublic class FenwickDouble {\n\n ", "end": 85, "score": 0.9989145398139954, "start": 80, "tag": "USERNAME", "value": "petuh" } ]
null
[]
package com.petukhovsky.solve.lib; import java.util.Arrays; /** * Created by petuh on 2/2/2016. */ public class FenwickDouble { double[] data; int n; public FenwickDouble(int n) { this.n = n; this.data = new double[n]; } public void inc(int pos, double delta) { for (int i = pos; i < n; i |= i + 1) data[i] += delta; } public double sum(int r) { double res = 0; for (int i = r; i >= 0; i = (i&(i+1))-1) res += data[i]; return res; } public double sum(int l, int r) { return sum(r) - sum(l - 1); } public int size() { return n; } }
677
0.487445
0.469719
37
17.297297
15.238402
48
false
false
0
0
0
0
0
0
0.513514
false
false
4
0072b2127cc73eee017aa06a8c58b3ef878e9b70
19,104,014,570,400
51c9c61c5c49738e4c2d4d944534c59d4a422a0f
/src/com/scene/ingsta/services/MainService.java
552f070d1a68094df8922d0fae26333754caeffc
[ "MIT" ]
permissive
RachelleVanmeter/ingsta
https://github.com/RachelleVanmeter/ingsta
e386da13c18300bb89ccf91e82ae1ec349e593bc
ecd45c9bf3a1f079ecfc65a0f6793101851d7917
refs/heads/master
2020-05-21T08:08:46.324000
2017-04-17T08:25:36
2017-04-17T08:25:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.scene.ingsta.services; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.scene.ingsta.repositories.IngRepository; import com.scene.ingsta.repositories.IngstaRepository; /** * <h1> * * 메인 서비스 * * </h1> * * <p> * * 잉스타 콩 * * </p> * * 엔티티 빈 * * <ul> * <li></li> * </ul> * * @author parkHaNeul * * @version 0.0.1-SNAPSHOT * */ @Service public class MainService { /** * Logger */ private static final Logger LOGGER = LoggerFactory.getLogger(MainService.class); /** * 잉스타 리포지토리 */ @Autowired private IngstaRepository ingstaRepository; /** * 잉 리포지토리 */ @Autowired private IngRepository ingRepository; /** * 메인 서비스 */ public MainService() { } /** * 뉴스피드 */ public List<HashMap<String, Object>> allList(String ingstaId, String max){ Map<String, String> condition = new HashMap<String, String>(); condition.put("ingstaId", ingstaId); condition.put("max", max); return ingRepository.allList(condition); } }
UTF-8
Java
1,279
java
MainService.java
Java
[ { "context": "빈\n * \n * <ul>\n * <li></li>\n * </ul>\n * \n * @author parkHaNeul\n * \n * @version 0.0.1-SNAPSHOT\n * \n */\n@Service\np", "end": 531, "score": 0.9988327026367188, "start": 521, "tag": "USERNAME", "value": "parkHaNeul" } ]
null
[]
package com.scene.ingsta.services; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.scene.ingsta.repositories.IngRepository; import com.scene.ingsta.repositories.IngstaRepository; /** * <h1> * * 메인 서비스 * * </h1> * * <p> * * 잉스타 콩 * * </p> * * 엔티티 빈 * * <ul> * <li></li> * </ul> * * @author parkHaNeul * * @version 0.0.1-SNAPSHOT * */ @Service public class MainService { /** * Logger */ private static final Logger LOGGER = LoggerFactory.getLogger(MainService.class); /** * 잉스타 리포지토리 */ @Autowired private IngstaRepository ingstaRepository; /** * 잉 리포지토리 */ @Autowired private IngRepository ingRepository; /** * 메인 서비스 */ public MainService() { } /** * 뉴스피드 */ public List<HashMap<String, Object>> allList(String ingstaId, String max){ Map<String, String> condition = new HashMap<String, String>(); condition.put("ingstaId", ingstaId); condition.put("max", max); return ingRepository.allList(condition); } }
1,279
0.663629
0.657829
78
14.474359
18.609154
81
false
false
0
0
0
0
0
0
0.858974
false
false
4
e4d03bcd658c602a1651c6b53b5995522bfa1cb1
19,902,878,496,117
5d145e3ab9611b95f6063e60d31deade6856901b
/src/main/src/com/teacher/uz/my/controllers/SubjectController.java
911ce886164abec6d06fce17d6466e499f12d944
[]
no_license
Shohjahon/teacheruz
https://github.com/Shohjahon/teacheruz
835693d040095711c107672e2ff12c47af847bc3
da4786122878be1c8a62fac8f11ab06bab2e27e0
refs/heads/master
2022-12-30T17:37:35.703000
2019-10-15T04:08:25
2019-10-15T04:08:25
197,558,827
1
0
null
false
2022-12-16T11:08:17
2019-07-18T09:44:45
2019-10-15T04:08:28
2022-12-16T11:08:14
18,562
1
0
11
Java
false
false
package com.teacher.uz.my.controllers; import com.teacher.uz.my.domains.Category; import com.teacher.uz.my.domains.Subject; import com.teacher.uz.my.services.SubjectService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; /** * Created by Shoh Jahon on 10.05.2018. */ @Controller @RequestMapping("subject") public class SubjectController { @Autowired private SubjectService subjectService; @RequestMapping(value = "/subjects", method = RequestMethod.GET) public ModelAndView showManageSubjects(){ ModelAndView mv = new ModelAndView("dashboard"); mv.addObject("userClickSubjectList",true); mv.addObject("title", "Subject"); return mv; } @RequestMapping(value = "/create/subject",method = RequestMethod.GET) public ModelAndView showCreateSubject(){ ModelAndView mv = new ModelAndView("dashboard"); Subject subject = new Subject(); mv.addObject("title","Subject"); mv.addObject("subject",subject); mv.addObject("userClickCreateSubject",true); return mv; } @RequestMapping(value = "/create/{id}/subject",method = RequestMethod.GET) public ModelAndView showUpdateSubject(@PathVariable int id){ ModelAndView mv = new ModelAndView("dashboard"); mv.addObject("userClickCreateSubject",true); mv.addObject("title","Update Subject"); Subject subject = subjectService.getSubject(id); mv.addObject("subject",subject); return mv; } @RequestMapping(value = "/create/subject", method = RequestMethod.POST) public String showCreateSubject(@ModelAttribute("subject") Subject subject){ subjectService.saveSubject(subject); return "redirect:/subject/subjects"; } @RequestMapping(value = "/delete/{id}/subject", method = RequestMethod.POST) @ResponseBody public String handleSubjectDeletion(@PathVariable int id){ subjectService.deleteSubject(id); return "You have successfully removed this subject!"; } }
UTF-8
Java
2,193
java
SubjectController.java
Java
[ { "context": "ework.web.servlet.ModelAndView;\n\n/**\n * Created by Shoh Jahon on 10.05.2018.\n */\n@Controller\n@RequestMapping(\"s", "end": 420, "score": 0.9998380541801453, "start": 410, "tag": "NAME", "value": "Shoh Jahon" } ]
null
[]
package com.teacher.uz.my.controllers; import com.teacher.uz.my.domains.Category; import com.teacher.uz.my.domains.Subject; import com.teacher.uz.my.services.SubjectService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; /** * Created by <NAME> on 10.05.2018. */ @Controller @RequestMapping("subject") public class SubjectController { @Autowired private SubjectService subjectService; @RequestMapping(value = "/subjects", method = RequestMethod.GET) public ModelAndView showManageSubjects(){ ModelAndView mv = new ModelAndView("dashboard"); mv.addObject("userClickSubjectList",true); mv.addObject("title", "Subject"); return mv; } @RequestMapping(value = "/create/subject",method = RequestMethod.GET) public ModelAndView showCreateSubject(){ ModelAndView mv = new ModelAndView("dashboard"); Subject subject = new Subject(); mv.addObject("title","Subject"); mv.addObject("subject",subject); mv.addObject("userClickCreateSubject",true); return mv; } @RequestMapping(value = "/create/{id}/subject",method = RequestMethod.GET) public ModelAndView showUpdateSubject(@PathVariable int id){ ModelAndView mv = new ModelAndView("dashboard"); mv.addObject("userClickCreateSubject",true); mv.addObject("title","Update Subject"); Subject subject = subjectService.getSubject(id); mv.addObject("subject",subject); return mv; } @RequestMapping(value = "/create/subject", method = RequestMethod.POST) public String showCreateSubject(@ModelAttribute("subject") Subject subject){ subjectService.saveSubject(subject); return "redirect:/subject/subjects"; } @RequestMapping(value = "/delete/{id}/subject", method = RequestMethod.POST) @ResponseBody public String handleSubjectDeletion(@PathVariable int id){ subjectService.deleteSubject(id); return "You have successfully removed this subject!"; } }
2,189
0.706338
0.70269
59
36.169491
24.195639
80
false
false
0
0
0
0
0
0
0.711864
false
false
4
cc26477c36c0a42856cbd68ee03e372402045b2b
3,624,952,448,938
d492576b6d452f1f4bc8c4f4ffc1b054f5cc5eff
/CargaArchivosExcel/src/co/gov/ideam/sirh/archivos/model/Masivo/Converter/CmatFuniasTopografiaGeoV2MasivoConverter.java
b03954196af5be2868cf1d0a04b7cacd2db26277
[]
no_license
Sirhv2/AppSirh
https://github.com/Sirhv2/AppSirh
d5f3cb55e259c29e46f3e22a7d39ed7b01174c84
6074d04bc0f4deb313e7f3c73a284d51e499af4d
refs/heads/master
2021-01-15T12:04:12.129000
2016-09-16T21:09:30
2016-09-16T21:09:30
68,330,584
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package co.gov.ideam.sirh.archivos.model.Masivo.Converter; import co.gov.ideam.sirh.archivos.model.ModelConverter; import co.gov.ideam.sirh.parametros.business.ParametrosEJB; import co.gov.ideam.sirh.util.IdeamException; import co.gov.ideam.sirh.archivos.model.Masivo.Entidad.*; public class CmatFuniasTopografiaGeoV2MasivoConverter extends ModelConverter { public CmatFuniasTopografiaGeoV2MasivoConverter() { super(); } public Object getModel(Object model) throws IdeamException { if (model instanceof CmatFuniasTopografiaGeoV2) { return this.getCmatFuniasTopografiaGeoV2((CmatFuniasTopografiaGeoV2)model); } return null; } private CmatFuniasTopografiaGeoV2 getCmatFuniasTopografiaGeoV2(CmatFuniasTopografiaGeoV2 cmatfuniastopografiageov2) throws IdeamException { ParametrosEJB parametrosService = this.getParametrosService(); return cmatfuniastopografiageov2; } }
UTF-8
Java
954
java
CmatFuniasTopografiaGeoV2MasivoConverter.java
Java
[]
null
[]
package co.gov.ideam.sirh.archivos.model.Masivo.Converter; import co.gov.ideam.sirh.archivos.model.ModelConverter; import co.gov.ideam.sirh.parametros.business.ParametrosEJB; import co.gov.ideam.sirh.util.IdeamException; import co.gov.ideam.sirh.archivos.model.Masivo.Entidad.*; public class CmatFuniasTopografiaGeoV2MasivoConverter extends ModelConverter { public CmatFuniasTopografiaGeoV2MasivoConverter() { super(); } public Object getModel(Object model) throws IdeamException { if (model instanceof CmatFuniasTopografiaGeoV2) { return this.getCmatFuniasTopografiaGeoV2((CmatFuniasTopografiaGeoV2)model); } return null; } private CmatFuniasTopografiaGeoV2 getCmatFuniasTopografiaGeoV2(CmatFuniasTopografiaGeoV2 cmatfuniastopografiageov2) throws IdeamException { ParametrosEJB parametrosService = this.getParametrosService(); return cmatfuniastopografiageov2; } }
954
0.775681
0.765199
24
38.75
35.92382
143
false
false
0
0
0
0
0
0
0.416667
false
false
4
510494dfd8fb6962077491a8c608c04934de19f6
16,449,724,792,685
84171b12e8e1fa1a62acfa36cffb108f450b9190
/thingifier/src/main/java/uk/co/compendiumdev/thingifier/domain/definitions/FieldValue.java
3ba9be73639e7631a623886cd5b745fd132409f6
[ "MIT" ]
permissive
scrolltest/thingifier
https://github.com/scrolltest/thingifier
847ea378d4c8a087d31360ca6363eb33ff05f112
8a485caf63b04ae8c5151c7442061380895517d5
refs/heads/master
2022-11-24T01:40:19.201000
2020-07-29T15:09:27
2020-07-29T15:09:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uk.co.compendiumdev.thingifier.domain.definitions; final public class FieldValue { private final String fieldName; private final String fieldValue; public FieldValue(String fieldName, String fieldValue) { this.fieldName = fieldName; this.fieldValue = fieldValue; } public static FieldValue is(String fieldName, String fieldValue) { return new FieldValue(fieldName, fieldValue); } public String getName() { return fieldName; } public String getValue() { return fieldValue; } }
UTF-8
Java
570
java
FieldValue.java
Java
[]
null
[]
package uk.co.compendiumdev.thingifier.domain.definitions; final public class FieldValue { private final String fieldName; private final String fieldValue; public FieldValue(String fieldName, String fieldValue) { this.fieldName = fieldName; this.fieldValue = fieldValue; } public static FieldValue is(String fieldName, String fieldValue) { return new FieldValue(fieldName, fieldValue); } public String getName() { return fieldName; } public String getValue() { return fieldValue; } }
570
0.680702
0.680702
24
22.75
21.861782
70
false
false
0
0
0
0
0
0
0.458333
false
false
4
a289348903ce41eb7e07212e89ce254784b612c4
28,552,942,634,129
4381f006a6e121cc65d3b2f95e0ab0035750a117
/cache-inventory/src/main/java/com/bill/service/impl/RequestAsyncProcessServiceImpl.java
a4ff643c2d0e6d1538f55f345f59e6a4d38bb897
[ "MIT" ]
permissive
charygao/cache-project
https://github.com/charygao/cache-project
5920be0d6f10358eb6cad26d79f777c41711c7f3
46cb67ab6cd5121a54e0ccbb7f95e8eb7e1d3234
refs/heads/master
2021-03-18T03:20:08.594000
2017-10-04T06:36:27
2017-10-04T06:36:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bill.service.impl; import java.util.concurrent.ArrayBlockingQueue; import org.springframework.stereotype.Service; import com.bill.request.Request; import com.bill.request.RequestQueue; import com.bill.service.RequestAsyncProcessService; /** 请求异步执行service实现 * @author bill * 2017年8月13日22:51:26 */ @Service public class RequestAsyncProcessServiceImpl implements RequestAsyncProcessService { @Override public void process(Request request) throws Exception { try { // 根据请求商品的id,计算路由到对应的内存队列 ArrayBlockingQueue<Request> queue = getRoutingQueue(request.getProductId()); //是否强制刷新 /*if(!request.isForceRefresh()){ //先做读请求的去重 RequestQueue requestQueue = RequestQueue.getInstance(); Map<Integer,Boolean> flagMap = requestQueue.getFlagMap(); if(request instanceof ProductInventoryDBUpdateRequest){ //如果是一个更新数据库请求,那么就将那个productId对应的标识设置为true flagMap.put(request.getProductId(), true); }else if(request instanceof ProductInventoryCacheRefreshRequest){ Boolean flag = flagMap.get(request.getProductId()); if(null == flag){ flagMap.put(request.getProductId(), false); } //如果是缓存刷新的请求,那么就判断,如果标识为不空,而且是true,就说明之前有一个这个商品库存的数据库更新请求 if(null != flag && flag){ flagMap.put(request.getProductId(), false); } //如果是缓存刷新的请求,而且发现标识不为空,但是标识是false //说明前面已经有一个数据库更新请求 +一个缓存刷新请求了 if(flag != null && !flag){ //对应这种读请求,直接过滤掉,不需要放到内存队列里面 return; } } }*/ // 将请求放入对应的队列中,完成处理 queue.put(request); } catch (Exception e) { throw e; } } /** * 根据productId计算,路由 到 某个内存队列 * @param productId 商品id * @return 内存队列 */ private ArrayBlockingQueue<Request> getRoutingQueue(Integer productId){ RequestQueue requestQueue = RequestQueue.getInstance(); String key = String.valueOf(productId); int h; int hash = (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); // 对hash值取模,将hash值路由到指定的内存队列中,比如内存队列大小 size // 用内存队列的数量对hash值取模之后,结果一定是在0 ~ ( size - 1 )之间 // 所以任何一个商品id都会被固定路由到同样的一个内存队列中去的 int index = (requestQueue.size() - 1) & hash; System.out.println("===========日志===========: 路由内存队列,商品id=" + productId + ", 队列索引=" + index); return requestQueue.getQueue(index); } }
UTF-8
Java
2,878
java
RequestAsyncProcessServiceImpl.java
Java
[ { "context": "yncProcessService;\n\n/** 请求异步执行service实现\n * @author bill\n * 2017年8月13日22:51:26\n */\n@Service\npublic class R", "end": 288, "score": 0.9889240264892578, "start": 284, "tag": "USERNAME", "value": "bill" }, { "context": "Queue = RequestQueue.getInstance();\n\t\tString key = String.valueOf(productId);\n\t\tint h;\n\t\tint hash = (key ==", "end": 1798, "score": 0.5076038241386414, "start": 1792, "tag": "KEY", "value": "String" }, { "context": "RequestQueue.getInstance();\n\t\tString key = String.valueOf(productId);\n\t\tint h;\n\t\tint hash = (key == null) ?", "end": 1806, "score": 0.9641671180725098, "start": 1799, "tag": "KEY", "value": "valueOf" } ]
null
[]
package com.bill.service.impl; import java.util.concurrent.ArrayBlockingQueue; import org.springframework.stereotype.Service; import com.bill.request.Request; import com.bill.request.RequestQueue; import com.bill.service.RequestAsyncProcessService; /** 请求异步执行service实现 * @author bill * 2017年8月13日22:51:26 */ @Service public class RequestAsyncProcessServiceImpl implements RequestAsyncProcessService { @Override public void process(Request request) throws Exception { try { // 根据请求商品的id,计算路由到对应的内存队列 ArrayBlockingQueue<Request> queue = getRoutingQueue(request.getProductId()); //是否强制刷新 /*if(!request.isForceRefresh()){ //先做读请求的去重 RequestQueue requestQueue = RequestQueue.getInstance(); Map<Integer,Boolean> flagMap = requestQueue.getFlagMap(); if(request instanceof ProductInventoryDBUpdateRequest){ //如果是一个更新数据库请求,那么就将那个productId对应的标识设置为true flagMap.put(request.getProductId(), true); }else if(request instanceof ProductInventoryCacheRefreshRequest){ Boolean flag = flagMap.get(request.getProductId()); if(null == flag){ flagMap.put(request.getProductId(), false); } //如果是缓存刷新的请求,那么就判断,如果标识为不空,而且是true,就说明之前有一个这个商品库存的数据库更新请求 if(null != flag && flag){ flagMap.put(request.getProductId(), false); } //如果是缓存刷新的请求,而且发现标识不为空,但是标识是false //说明前面已经有一个数据库更新请求 +一个缓存刷新请求了 if(flag != null && !flag){ //对应这种读请求,直接过滤掉,不需要放到内存队列里面 return; } } }*/ // 将请求放入对应的队列中,完成处理 queue.put(request); } catch (Exception e) { throw e; } } /** * 根据productId计算,路由 到 某个内存队列 * @param productId 商品id * @return 内存队列 */ private ArrayBlockingQueue<Request> getRoutingQueue(Integer productId){ RequestQueue requestQueue = RequestQueue.getInstance(); String key = String.valueOf(productId); int h; int hash = (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); // 对hash值取模,将hash值路由到指定的内存队列中,比如内存队列大小 size // 用内存队列的数量对hash值取模之后,结果一定是在0 ~ ( size - 1 )之间 // 所以任何一个商品id都会被固定路由到同样的一个内存队列中去的 int index = (requestQueue.size() - 1) & hash; System.out.println("===========日志===========: 路由内存队列,商品id=" + productId + ", 队列索引=" + index); return requestQueue.getQueue(index); } }
2,878
0.699279
0.690712
73
29.383562
23.96323
97
false
false
0
0
0
0
0
0
2.739726
false
false
4
72f3c96b472e53ac1a008f69ba94d45760167b4c
3,590,592,708,868
a0e0478f9d273eea5683992dae380ef45f06871c
/FeedbackAdaper.java
9033eae1e39a127040c46f180494d07187aef245
[]
no_license
prt452taxipooling/taxi-pooling
https://github.com/prt452taxipooling/taxi-pooling
f2bbf901922803704d60ff5dad699495f5a4fb21
71491d6741989993e6751a287a58e2429d944cea
refs/heads/master
2021-05-04T06:14:23.814000
2016-10-16T19:21:36
2016-10-16T19:21:36
71,042,719
1
3
null
false
2016-10-16T19:13:20
2016-10-16T10:11:44
2016-10-16T19:02:34
2016-10-16T19:13:19
5,045
1
3
0
Java
null
null
package com.example.taxipooling; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ProgressDialog; import android.content.Context; import android.media.Image; import android.os.AsyncTask; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class FeedbackAdaper extends ArrayAdapter<String> { ArrayList<String> _poolerList; ArrayList<String> _poolerID; int imageId; int index; Context context; int rate; boolean likeFlag=true, dislikeFlag=true, like_dislike=false; static int p; String _userComment=null; public FeedbackAdaper(Context context, int userPicture, ArrayList<String> poolerList,ArrayList<String> poolerid ) { super(context, userPicture, poolerList); // TODO Auto-generated constructor stub this._poolerList = poolerList; this.imageId= userPicture; this.context = context; this._poolerID= poolerid; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub //return super.getView(position, convertView, parent); index=position; LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View single_row = inflater.inflate(R.layout.feedback_list_item, null, true); TextView tv_poolerName = (TextView) single_row.findViewById(R.id.tv_poolerName); ImageView poolerImage = (ImageView) single_row.findViewById(R.id.poolerImage); final ImageButton likeButton = (ImageButton) single_row.findViewById(R.id.likeButton); final ImageButton dislikeButton = (ImageButton) single_row.findViewById(R.id.dislikeButton); final EditText comment = (EditText) single_row.findViewById(R.id.et_comment_feedback); //comment.setText("hello mr..."); final TextView tv_like = (TextView) single_row.findViewById(R.id.tv_Like); final TextView tv_dislike= (TextView) single_row.findViewById(R.id.tv_dislike); Button send = (Button) single_row.findViewById(R.id.send_feeback); likeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(p!=position){ likeFlag=true; } if(likeFlag){ p=position; likeButton.setImageResource(R.drawable.like_fill); tv_like.setText("liked"); tv_dislike.setText("dislike"); rate=1; likeFlag=false; dislikeButton.setImageResource(R.drawable.dislike_empty); Toast.makeText(context, rate+"", Toast.LENGTH_LONG).show(); } else { likeButton.setImageResource(R.drawable.like_empty); likeFlag=true; tv_like.setText("like"); } } }); dislikeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(p!=position){ dislikeFlag=true; } if(dislikeFlag){ p=position; dislikeButton.setImageResource(R.drawable.dislike_fill); tv_dislike.setText("disliked"); tv_like.setText("like"); dislikeFlag=false; rate=-1; likeButton.setImageResource(R.drawable.like_empty); Toast.makeText(context, rate+"", Toast.LENGTH_LONG).show(); } else { dislikeButton.setImageResource(R.drawable.dislike_empty); dislikeFlag=true; tv_dislike.setText("dislike"); } } }); send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { index=position; //new MyAsyncTaskForFeedback().execute(); _userComment = comment.getText().toString(); Toast.makeText(context, "Comment: "+rate+" "+_userComment, Toast.LENGTH_LONG).show(); } }); //SETTING VARIABLE VALUES....................... tv_poolerName.setText(_poolerList.get(position)); poolerImage.setImageResource(imageId); return single_row; } //ASYNC TASK FOR FEEDBACK ABOUT POOLERS___________________________________________________________________(*) private class MyAsyncTaskForFeedback extends AsyncTask<Object, Void, String> { int responseCode; String responseBody; JSONArray jArray; JSONObject jObject; ProgressDialog progressDialog = new ProgressDialog(getContext()); @Override protected String doInBackground(Object... params) { return postData(); } protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); // progressDialog.setMessage("Getting Poolers"); progressDialog.setIndeterminate(true); progressDialog.setCancelable(true); progressDialog.show(); } @SuppressWarnings("unused") protected void onProgressUpdate(Integer... progress) { } public String postData() { HttpClient httpclient = new DefaultHttpClient(); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 2000); HttpConnectionParams.setSoTimeout(httpParameters,5000); HttpPost httppost = new HttpPost(Url.SERVER_URL+"feedback.php"); try { @SuppressWarnings("rawtypes") List nameValuePairs = new ArrayList(); nameValuePairs.add(new BasicNameValuePair("fromID",User.userId )); nameValuePairs.add(new BasicNameValuePair("toID",_poolerID.get(index) )); nameValuePairs.add(new BasicNameValuePair("commentor",User.userNAME )); nameValuePairs.add(new BasicNameValuePair("rate",rate+"" )); nameValuePairs.add(new BasicNameValuePair("comment",_userComment )); nameValuePairs.add(new BasicNameValuePair("image",User.image )); // Execute HTTP Post Request httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); responseCode = response.getStatusLine().getStatusCode(); responseBody = EntityUtils.toString(response.getEntity()); } catch (Throwable t) { Log.d("Error Time of Login", t + ""); } return responseBody; } protected void onPostExecute(String responseBody) { super.onPostExecute(responseBody); //Toast.makeText(LoginActivity.this, responseBody, //Toast.LENGTH_LONG).show(); if(responseBody.matches("fail")) { Toast.makeText(context, "Operation Failed...", Toast.LENGTH_LONG).show(); } else { JSONArray jArray; JSONObject jObject; try { jArray = new JSONArray(responseBody); jObject = jArray.getJSONObject(0); User.totalRATING= jObject.getString("totalRating"); Toast.makeText(context, User.totalRATING, Toast.LENGTH_LONG).show(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } progressDialog.dismiss(); } } //ENDING ASYNC TASK FOR SENDING FEEDBACK ABOUT POOLERS_________________________________________________(*) }
UTF-8
Java
8,005
java
FeedbackAdaper.java
Java
[]
null
[]
package com.example.taxipooling; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ProgressDialog; import android.content.Context; import android.media.Image; import android.os.AsyncTask; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class FeedbackAdaper extends ArrayAdapter<String> { ArrayList<String> _poolerList; ArrayList<String> _poolerID; int imageId; int index; Context context; int rate; boolean likeFlag=true, dislikeFlag=true, like_dislike=false; static int p; String _userComment=null; public FeedbackAdaper(Context context, int userPicture, ArrayList<String> poolerList,ArrayList<String> poolerid ) { super(context, userPicture, poolerList); // TODO Auto-generated constructor stub this._poolerList = poolerList; this.imageId= userPicture; this.context = context; this._poolerID= poolerid; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub //return super.getView(position, convertView, parent); index=position; LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View single_row = inflater.inflate(R.layout.feedback_list_item, null, true); TextView tv_poolerName = (TextView) single_row.findViewById(R.id.tv_poolerName); ImageView poolerImage = (ImageView) single_row.findViewById(R.id.poolerImage); final ImageButton likeButton = (ImageButton) single_row.findViewById(R.id.likeButton); final ImageButton dislikeButton = (ImageButton) single_row.findViewById(R.id.dislikeButton); final EditText comment = (EditText) single_row.findViewById(R.id.et_comment_feedback); //comment.setText("hello mr..."); final TextView tv_like = (TextView) single_row.findViewById(R.id.tv_Like); final TextView tv_dislike= (TextView) single_row.findViewById(R.id.tv_dislike); Button send = (Button) single_row.findViewById(R.id.send_feeback); likeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(p!=position){ likeFlag=true; } if(likeFlag){ p=position; likeButton.setImageResource(R.drawable.like_fill); tv_like.setText("liked"); tv_dislike.setText("dislike"); rate=1; likeFlag=false; dislikeButton.setImageResource(R.drawable.dislike_empty); Toast.makeText(context, rate+"", Toast.LENGTH_LONG).show(); } else { likeButton.setImageResource(R.drawable.like_empty); likeFlag=true; tv_like.setText("like"); } } }); dislikeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(p!=position){ dislikeFlag=true; } if(dislikeFlag){ p=position; dislikeButton.setImageResource(R.drawable.dislike_fill); tv_dislike.setText("disliked"); tv_like.setText("like"); dislikeFlag=false; rate=-1; likeButton.setImageResource(R.drawable.like_empty); Toast.makeText(context, rate+"", Toast.LENGTH_LONG).show(); } else { dislikeButton.setImageResource(R.drawable.dislike_empty); dislikeFlag=true; tv_dislike.setText("dislike"); } } }); send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { index=position; //new MyAsyncTaskForFeedback().execute(); _userComment = comment.getText().toString(); Toast.makeText(context, "Comment: "+rate+" "+_userComment, Toast.LENGTH_LONG).show(); } }); //SETTING VARIABLE VALUES....................... tv_poolerName.setText(_poolerList.get(position)); poolerImage.setImageResource(imageId); return single_row; } //ASYNC TASK FOR FEEDBACK ABOUT POOLERS___________________________________________________________________(*) private class MyAsyncTaskForFeedback extends AsyncTask<Object, Void, String> { int responseCode; String responseBody; JSONArray jArray; JSONObject jObject; ProgressDialog progressDialog = new ProgressDialog(getContext()); @Override protected String doInBackground(Object... params) { return postData(); } protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); // progressDialog.setMessage("Getting Poolers"); progressDialog.setIndeterminate(true); progressDialog.setCancelable(true); progressDialog.show(); } @SuppressWarnings("unused") protected void onProgressUpdate(Integer... progress) { } public String postData() { HttpClient httpclient = new DefaultHttpClient(); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 2000); HttpConnectionParams.setSoTimeout(httpParameters,5000); HttpPost httppost = new HttpPost(Url.SERVER_URL+"feedback.php"); try { @SuppressWarnings("rawtypes") List nameValuePairs = new ArrayList(); nameValuePairs.add(new BasicNameValuePair("fromID",User.userId )); nameValuePairs.add(new BasicNameValuePair("toID",_poolerID.get(index) )); nameValuePairs.add(new BasicNameValuePair("commentor",User.userNAME )); nameValuePairs.add(new BasicNameValuePair("rate",rate+"" )); nameValuePairs.add(new BasicNameValuePair("comment",_userComment )); nameValuePairs.add(new BasicNameValuePair("image",User.image )); // Execute HTTP Post Request httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); responseCode = response.getStatusLine().getStatusCode(); responseBody = EntityUtils.toString(response.getEntity()); } catch (Throwable t) { Log.d("Error Time of Login", t + ""); } return responseBody; } protected void onPostExecute(String responseBody) { super.onPostExecute(responseBody); //Toast.makeText(LoginActivity.this, responseBody, //Toast.LENGTH_LONG).show(); if(responseBody.matches("fail")) { Toast.makeText(context, "Operation Failed...", Toast.LENGTH_LONG).show(); } else { JSONArray jArray; JSONObject jObject; try { jArray = new JSONArray(responseBody); jObject = jArray.getJSONObject(0); User.totalRATING= jObject.getString("totalRating"); Toast.makeText(context, User.totalRATING, Toast.LENGTH_LONG).show(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } progressDialog.dismiss(); } } //ENDING ASYNC TASK FOR SENDING FEEDBACK ABOUT POOLERS_________________________________________________(*) }
8,005
0.678701
0.677327
241
31.215767
25.319927
114
false
false
0
0
0
0
0
0
3.79668
false
false
4
5510109c9402031cdcdb34e7434d5aa918a00bc6
2,697,239,511,036
31d7717e3aa8da831e439ced3b061933c0ce0988
/OpenHome/Net/Bindings/Java/org/openhome/net/device/providers/DvProviderAvOpenhomeOrgWebClockConfig1.java
a0ff454df2c845af02bf046e128dc58e668e0325
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
imateev/Lightning-ohNet
https://github.com/imateev/Lightning-ohNet
586f5d7b1e29c6c61269a064085ca11078ed5092
bd8ea0ef4f5237820f445951574818f6e7dfff9c
refs/heads/master
2021-12-25T23:07:13.914000
2018-01-02T01:11:27
2018-01-02T01:11:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.openhome.net.device.providers; import java.util.LinkedList; import java.util.List; import org.openhome.net.core.*; import org.openhome.net.device.*; interface IDvProviderAvOpenhomeOrgWebClockConfig1 { /** * Set the value of the Alive property * * @param aValue new value for the property. * @return <tt>true</tt> if the value has been updated; <tt>false</tt> if <tt>aValue</tt> was the same as the previous value. * */ public boolean setPropertyAlive(boolean aValue); /** * Get a copy of the value of the Alive property * * @return value of the Alive property. */ public boolean getPropertyAlive(); /** * Set the value of the ClockConfig property * * @param aValue new value for the property. * @return <tt>true</tt> if the value has been updated; <tt>false</tt> if <tt>aValue</tt> was the same as the previous value. * */ public boolean setPropertyClockConfig(String aValue); /** * Get a copy of the value of the ClockConfig property * * @return value of the ClockConfig property. */ public String getPropertyClockConfig(); } /** * Provider for the av.openhome.org:WebClockConfig:1 UPnP service. */ public class DvProviderAvOpenhomeOrgWebClockConfig1 extends DvProvider implements IDvProviderAvOpenhomeOrgWebClockConfig1 { private IDvInvocationListener iDelegateGetClockConfig; private IDvInvocationListener iDelegateSetClockConfig; private PropertyBool iPropertyAlive; private PropertyString iPropertyClockConfig; /** * Constructor * * @param aDevice device which owns this provider. */ protected DvProviderAvOpenhomeOrgWebClockConfig1(DvDevice aDevice) { super(aDevice, "av.openhome.org", "WebClockConfig", 1); } /** * Enable the Alive property. */ public void enablePropertyAlive() { iPropertyAlive = new PropertyBool(new ParameterBool("Alive")); addProperty(iPropertyAlive); } /** * Enable the ClockConfig property. */ public void enablePropertyClockConfig() { List<String> allowedValues = new LinkedList<String>(); iPropertyClockConfig = new PropertyString(new ParameterString("ClockConfig", allowedValues)); addProperty(iPropertyClockConfig); } /** * Set the value of the Alive property * * @param aValue new value for the property. * @return <tt>true</tt> if the value has been updated; <tt>false</tt> * if <tt>aValue</tt> was the same as the previous value. */ public boolean setPropertyAlive(boolean aValue) { return setPropertyBool(iPropertyAlive, aValue); } /** * Get a copy of the value of the Alive property * * @return value of the Alive property. */ public boolean getPropertyAlive() { return iPropertyAlive.getValue(); } /** * Set the value of the ClockConfig property * * @param aValue new value for the property. * @return <tt>true</tt> if the value has been updated; <tt>false</tt> * if <tt>aValue</tt> was the same as the previous value. */ public boolean setPropertyClockConfig(String aValue) { return setPropertyString(iPropertyClockConfig, aValue); } /** * Get a copy of the value of the ClockConfig property * * @return value of the ClockConfig property. */ public String getPropertyClockConfig() { return iPropertyClockConfig.getValue(); } /** * Signal that the action GetClockConfig is supported. * * <p>The action's availability will be published in the device's service.xml. * GetClockConfig must be overridden if this is called. */ protected void enableActionGetClockConfig() { Action action = new Action("GetClockConfig"); action.addOutputParameter(new ParameterRelated("ClockConfig", iPropertyClockConfig)); iDelegateGetClockConfig = new DoGetClockConfig(); enableAction(action, iDelegateGetClockConfig); } /** * Signal that the action SetClockConfig is supported. * * <p>The action's availability will be published in the device's service.xml. * SetClockConfig must be overridden if this is called. */ protected void enableActionSetClockConfig() { Action action = new Action("SetClockConfig"); action.addInputParameter(new ParameterRelated("ClockConfig", iPropertyClockConfig)); iDelegateSetClockConfig = new DoSetClockConfig(); enableAction(action, iDelegateSetClockConfig); } /** * GetClockConfig action. * * <p>Will be called when the device stack receives an invocation of the * GetClockConfig action for the owning device. * * <p>Must be implemented iff {@link #enableActionGetClockConfig} was called.</remarks> * * @param aInvocation Interface allowing querying of aspects of this particular action invocation.</param> */ protected String getClockConfig(IDvInvocation aInvocation) { throw (new ActionDisabledError()); } /** * SetClockConfig action. * * <p>Will be called when the device stack receives an invocation of the * SetClockConfig action for the owning device. * * <p>Must be implemented iff {@link #enableActionSetClockConfig} was called.</remarks> * * @param aInvocation Interface allowing querying of aspects of this particular action invocation.</param> * @param aClockConfig */ protected void setClockConfig(IDvInvocation aInvocation, String aClockConfig) { throw (new ActionDisabledError()); } /** * Must be called for each class instance. Must be called before Core.Library.Close(). */ public void dispose() { synchronized (this) { if (iHandle == 0) { return; } super.dispose(); iHandle = 0; } } private class DoGetClockConfig implements IDvInvocationListener { public void actionInvoked(long aInvocation) { DvInvocation invocation = new DvInvocation(aInvocation); String clockConfig; try { invocation.readStart(); invocation.readEnd(); clockConfig = getClockConfig(invocation); } catch (ActionError ae) { invocation.reportActionError(ae, "GetClockConfig"); return; } catch (PropertyUpdateError pue) { invocation.reportError(501, "Invalid XML"); return; } catch (Exception e) { System.out.println("WARNING: unexpected exception: " + e.getMessage()); System.out.println(" Only ActionError or PropertyUpdateError can be thrown by actions"); e.printStackTrace(); return; } try { invocation.writeStart(); invocation.writeString("ClockConfig", clockConfig); invocation.writeEnd(); } catch (ActionError ae) { return; } catch (Exception e) { System.out.println("ERROR: unexpected exception: " + e.getMessage()); System.out.println(" Only ActionError can be thrown by action response writer"); e.printStackTrace(); } } } private class DoSetClockConfig implements IDvInvocationListener { public void actionInvoked(long aInvocation) { DvInvocation invocation = new DvInvocation(aInvocation); String clockConfig; try { invocation.readStart(); clockConfig = invocation.readString("ClockConfig"); invocation.readEnd(); setClockConfig(invocation, clockConfig); } catch (ActionError ae) { invocation.reportActionError(ae, "SetClockConfig"); return; } catch (PropertyUpdateError pue) { invocation.reportError(501, "Invalid XML"); return; } catch (Exception e) { System.out.println("WARNING: unexpected exception: " + e.getMessage()); System.out.println(" Only ActionError or PropertyUpdateError can be thrown by actions"); e.printStackTrace(); return; } try { invocation.writeStart(); invocation.writeEnd(); } catch (ActionError ae) { return; } catch (Exception e) { System.out.println("ERROR: unexpected exception: " + e.getMessage()); System.out.println(" Only ActionError can be thrown by action response writer"); e.printStackTrace(); } } } }
UTF-8
Java
9,401
java
DvProviderAvOpenhomeOrgWebClockConfig1.java
Java
[]
null
[]
package org.openhome.net.device.providers; import java.util.LinkedList; import java.util.List; import org.openhome.net.core.*; import org.openhome.net.device.*; interface IDvProviderAvOpenhomeOrgWebClockConfig1 { /** * Set the value of the Alive property * * @param aValue new value for the property. * @return <tt>true</tt> if the value has been updated; <tt>false</tt> if <tt>aValue</tt> was the same as the previous value. * */ public boolean setPropertyAlive(boolean aValue); /** * Get a copy of the value of the Alive property * * @return value of the Alive property. */ public boolean getPropertyAlive(); /** * Set the value of the ClockConfig property * * @param aValue new value for the property. * @return <tt>true</tt> if the value has been updated; <tt>false</tt> if <tt>aValue</tt> was the same as the previous value. * */ public boolean setPropertyClockConfig(String aValue); /** * Get a copy of the value of the ClockConfig property * * @return value of the ClockConfig property. */ public String getPropertyClockConfig(); } /** * Provider for the av.openhome.org:WebClockConfig:1 UPnP service. */ public class DvProviderAvOpenhomeOrgWebClockConfig1 extends DvProvider implements IDvProviderAvOpenhomeOrgWebClockConfig1 { private IDvInvocationListener iDelegateGetClockConfig; private IDvInvocationListener iDelegateSetClockConfig; private PropertyBool iPropertyAlive; private PropertyString iPropertyClockConfig; /** * Constructor * * @param aDevice device which owns this provider. */ protected DvProviderAvOpenhomeOrgWebClockConfig1(DvDevice aDevice) { super(aDevice, "av.openhome.org", "WebClockConfig", 1); } /** * Enable the Alive property. */ public void enablePropertyAlive() { iPropertyAlive = new PropertyBool(new ParameterBool("Alive")); addProperty(iPropertyAlive); } /** * Enable the ClockConfig property. */ public void enablePropertyClockConfig() { List<String> allowedValues = new LinkedList<String>(); iPropertyClockConfig = new PropertyString(new ParameterString("ClockConfig", allowedValues)); addProperty(iPropertyClockConfig); } /** * Set the value of the Alive property * * @param aValue new value for the property. * @return <tt>true</tt> if the value has been updated; <tt>false</tt> * if <tt>aValue</tt> was the same as the previous value. */ public boolean setPropertyAlive(boolean aValue) { return setPropertyBool(iPropertyAlive, aValue); } /** * Get a copy of the value of the Alive property * * @return value of the Alive property. */ public boolean getPropertyAlive() { return iPropertyAlive.getValue(); } /** * Set the value of the ClockConfig property * * @param aValue new value for the property. * @return <tt>true</tt> if the value has been updated; <tt>false</tt> * if <tt>aValue</tt> was the same as the previous value. */ public boolean setPropertyClockConfig(String aValue) { return setPropertyString(iPropertyClockConfig, aValue); } /** * Get a copy of the value of the ClockConfig property * * @return value of the ClockConfig property. */ public String getPropertyClockConfig() { return iPropertyClockConfig.getValue(); } /** * Signal that the action GetClockConfig is supported. * * <p>The action's availability will be published in the device's service.xml. * GetClockConfig must be overridden if this is called. */ protected void enableActionGetClockConfig() { Action action = new Action("GetClockConfig"); action.addOutputParameter(new ParameterRelated("ClockConfig", iPropertyClockConfig)); iDelegateGetClockConfig = new DoGetClockConfig(); enableAction(action, iDelegateGetClockConfig); } /** * Signal that the action SetClockConfig is supported. * * <p>The action's availability will be published in the device's service.xml. * SetClockConfig must be overridden if this is called. */ protected void enableActionSetClockConfig() { Action action = new Action("SetClockConfig"); action.addInputParameter(new ParameterRelated("ClockConfig", iPropertyClockConfig)); iDelegateSetClockConfig = new DoSetClockConfig(); enableAction(action, iDelegateSetClockConfig); } /** * GetClockConfig action. * * <p>Will be called when the device stack receives an invocation of the * GetClockConfig action for the owning device. * * <p>Must be implemented iff {@link #enableActionGetClockConfig} was called.</remarks> * * @param aInvocation Interface allowing querying of aspects of this particular action invocation.</param> */ protected String getClockConfig(IDvInvocation aInvocation) { throw (new ActionDisabledError()); } /** * SetClockConfig action. * * <p>Will be called when the device stack receives an invocation of the * SetClockConfig action for the owning device. * * <p>Must be implemented iff {@link #enableActionSetClockConfig} was called.</remarks> * * @param aInvocation Interface allowing querying of aspects of this particular action invocation.</param> * @param aClockConfig */ protected void setClockConfig(IDvInvocation aInvocation, String aClockConfig) { throw (new ActionDisabledError()); } /** * Must be called for each class instance. Must be called before Core.Library.Close(). */ public void dispose() { synchronized (this) { if (iHandle == 0) { return; } super.dispose(); iHandle = 0; } } private class DoGetClockConfig implements IDvInvocationListener { public void actionInvoked(long aInvocation) { DvInvocation invocation = new DvInvocation(aInvocation); String clockConfig; try { invocation.readStart(); invocation.readEnd(); clockConfig = getClockConfig(invocation); } catch (ActionError ae) { invocation.reportActionError(ae, "GetClockConfig"); return; } catch (PropertyUpdateError pue) { invocation.reportError(501, "Invalid XML"); return; } catch (Exception e) { System.out.println("WARNING: unexpected exception: " + e.getMessage()); System.out.println(" Only ActionError or PropertyUpdateError can be thrown by actions"); e.printStackTrace(); return; } try { invocation.writeStart(); invocation.writeString("ClockConfig", clockConfig); invocation.writeEnd(); } catch (ActionError ae) { return; } catch (Exception e) { System.out.println("ERROR: unexpected exception: " + e.getMessage()); System.out.println(" Only ActionError can be thrown by action response writer"); e.printStackTrace(); } } } private class DoSetClockConfig implements IDvInvocationListener { public void actionInvoked(long aInvocation) { DvInvocation invocation = new DvInvocation(aInvocation); String clockConfig; try { invocation.readStart(); clockConfig = invocation.readString("ClockConfig"); invocation.readEnd(); setClockConfig(invocation, clockConfig); } catch (ActionError ae) { invocation.reportActionError(ae, "SetClockConfig"); return; } catch (PropertyUpdateError pue) { invocation.reportError(501, "Invalid XML"); return; } catch (Exception e) { System.out.println("WARNING: unexpected exception: " + e.getMessage()); System.out.println(" Only ActionError or PropertyUpdateError can be thrown by actions"); e.printStackTrace(); return; } try { invocation.writeStart(); invocation.writeEnd(); } catch (ActionError ae) { return; } catch (Exception e) { System.out.println("ERROR: unexpected exception: " + e.getMessage()); System.out.println(" Only ActionError can be thrown by action response writer"); e.printStackTrace(); } } } }
9,401
0.590682
0.589193
301
30.229237
29.049116
134
false
false
0
0
0
0
0
0
0.322259
false
false
4
feff0960d3fcdf924e344dd8cd37ca6d5259afb8
34,583,076,667,731
e48aa71f72ca2dfc1993145f32f57c6acc5e403f
/app/src/main/java/whatsappclone/ivecio/com/whatsappclone/activity/ValidadorAcitivity.java
6581338ca9b877c13ad1a8c4360a2e6eb093233d
[]
no_license
ivecio/WhatsAppClone
https://github.com/ivecio/WhatsAppClone
7d95a3a2e176d126f81923fccbcc846140e4fc03
d0eb87baf6c9aaaf2ffe613d198923b097b7b7a0
refs/heads/master
2020-07-28T21:15:41.766000
2016-09-13T23:50:40
2016-09-13T23:50:40
67,957,580
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package whatsappclone.ivecio.com.whatsappclone.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.github.rtoshiro.util.format.SimpleMaskFormatter; import com.github.rtoshiro.util.format.text.MaskTextWatcher; import java.util.HashMap; import whatsappclone.ivecio.com.whatsappclone.R; import whatsappclone.ivecio.com.whatsappclone.helper.Preferencias; public class ValidadorAcitivity extends AppCompatActivity { private EditText codigoValidacao; private Button validar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_validador_acitivity); codigoValidacao = (EditText) findViewById(R.id.cod_validador); validar = (Button) findViewById(R.id.bt_validar); SimpleMaskFormatter simpleMaskCodigoValidacao = new SimpleMaskFormatter("NNNN"); MaskTextWatcher mascaraCodigoValidacao = new MaskTextWatcher(codigoValidacao, simpleMaskCodigoValidacao); codigoValidacao.addTextChangedListener( mascaraCodigoValidacao ); validar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Preferencias preferencias = new Preferencias( ValidadorAcitivity.this ); HashMap<String, String> usuario = preferencias.getDadosUsuario(); String tokenGerado = usuario.get( "token" ); String tokenDigitado = codigoValidacao.getText().toString(); if ( tokenDigitado.equals( tokenGerado) ) { Toast.makeText(ValidadorAcitivity.this, "Token VALIDADO", Toast.LENGTH_LONG).show(); }else { Toast.makeText(ValidadorAcitivity.this, "Token NÃO VALIDADO", Toast.LENGTH_LONG).show(); } } }); } }
UTF-8
Java
2,030
java
ValidadorAcitivity.java
Java
[ { "context": ";\nimport android.widget.Toast;\n\nimport com.github.rtoshiro.util.format.SimpleMaskFormatter;\nimport com.githu", "end": 277, "score": 0.7811853885650635, "start": 269, "tag": "USERNAME", "value": "rtoshiro" }, { "context": "til.format.SimpleMaskFormatter;\nimport com.github.rtoshiro.util.format.text.MaskTextWatcher;\n\nimport java.ut", "end": 337, "score": 0.7192047238349915, "start": 329, "tag": "USERNAME", "value": "rtoshiro" } ]
null
[]
package whatsappclone.ivecio.com.whatsappclone.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.github.rtoshiro.util.format.SimpleMaskFormatter; import com.github.rtoshiro.util.format.text.MaskTextWatcher; import java.util.HashMap; import whatsappclone.ivecio.com.whatsappclone.R; import whatsappclone.ivecio.com.whatsappclone.helper.Preferencias; public class ValidadorAcitivity extends AppCompatActivity { private EditText codigoValidacao; private Button validar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_validador_acitivity); codigoValidacao = (EditText) findViewById(R.id.cod_validador); validar = (Button) findViewById(R.id.bt_validar); SimpleMaskFormatter simpleMaskCodigoValidacao = new SimpleMaskFormatter("NNNN"); MaskTextWatcher mascaraCodigoValidacao = new MaskTextWatcher(codigoValidacao, simpleMaskCodigoValidacao); codigoValidacao.addTextChangedListener( mascaraCodigoValidacao ); validar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Preferencias preferencias = new Preferencias( ValidadorAcitivity.this ); HashMap<String, String> usuario = preferencias.getDadosUsuario(); String tokenGerado = usuario.get( "token" ); String tokenDigitado = codigoValidacao.getText().toString(); if ( tokenDigitado.equals( tokenGerado) ) { Toast.makeText(ValidadorAcitivity.this, "Token VALIDADO", Toast.LENGTH_LONG).show(); }else { Toast.makeText(ValidadorAcitivity.this, "Token NÃO VALIDADO", Toast.LENGTH_LONG).show(); } } }); } }
2,030
0.704288
0.703795
57
34.596493
32.742409
113
false
false
0
0
0
0
0
0
0.596491
false
false
4
f46a62c577262cd39f2be45e8ea8ac2f261b7db9
33,517,924,812,385
d23c7c5618b7d308e5e5199e2d38f4e222193f28
/src/gameengine/RNG.java
7f99c69d73ea35bbd54dd0ecd77dd15f9c06d64c
[]
no_license
ElGabroDev/oopokemon
https://github.com/ElGabroDev/oopokemon
7d92ad0be343acf23168526a5e389750221fe4f8
4b33a97621c8e75394948fad7d04e324be40932e
refs/heads/main
2023-07-01T07:40:14.095000
2021-07-31T09:45:31
2021-07-31T09:45:31
389,995,154
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 gameengine; import java.security.SecureRandom; /** * * @author elgabro */ public class RNG { public static int roll10(){ SecureRandom rand = new SecureRandom(); return (int) (rand.nextInt(10) + 1); } }
UTF-8
Java
443
java
RNG.java
Java
[ { "context": "ort java.security.SecureRandom;\n\n/**\n *\n * @author elgabro\n */\npublic class RNG {\n \n public static int", "end": 267, "score": 0.9996322989463806, "start": 260, "tag": "USERNAME", "value": "elgabro" } ]
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 gameengine; import java.security.SecureRandom; /** * * @author elgabro */ public class RNG { public static int roll10(){ SecureRandom rand = new SecureRandom(); return (int) (rand.nextInt(10) + 1); } }
443
0.645598
0.634311
22
19.136364
21.724087
79
false
false
0
0
0
0
0
0
0.318182
false
false
4
75acbe3b7cff6eb6e502c5237ad6bc02dba4254c
16,226,386,491,956
799592e760e2409ccb64ad97ead5f81ac18703ea
/app/models/BaseModel.java
b305dc708131eedb0c38361fe6d28fc126c1973e
[]
no_license
ST466/play-java-bbs
https://github.com/ST466/play-java-bbs
8000e4b6ced3af497b03591f1c3491b687f91a05
88d9e54e9677e4137a8f6cb780d93cd08bd9b435
refs/heads/main
2023-06-08T06:40:56.512000
2021-06-30T12:31:56
2021-06-30T12:31:56
381,688,150
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package models; import io.ebean.Finder; import io.ebean.Model; import jdk.nashorn.internal.objects.annotations.Getter; import jdk.nashorn.internal.objects.annotations.Setter; import play.data.validation.Constraints; import javax.persistence.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; @MappedSuperclass public class BaseModel extends Model { @Column(name = "created_at") private Date createdAt; @Column(name = "updated_at") private Date updatedAt; @PrePersist public void onPrePersist() { createdAt = new Date(); updatedAt = new Date(); } @PreUpdate public void onPreUpdate() { updatedAt = new Date(); } /** * * @return createdAt */ public Date getCreatedAt() { return createdAt; } /** * * @return updatedAt */ public Date getUpdatedAt() { return updatedAt; } /** * * @return createdAt (yyyy-MM-dd HH:mm:ss) */ public String getCreatedAtWithFormat() { return dateWithFormat(createdAt); } /** * * @return updatedAt (yyyy-MM-dd HH:mm:ss) */ public String getUpdatedAtWithFormat() { return dateWithFormat(updatedAt); } private String dateWithFormat(Date date) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return df.format(date); } }
UTF-8
Java
1,504
java
BaseModel.java
Java
[]
null
[]
package models; import io.ebean.Finder; import io.ebean.Model; import jdk.nashorn.internal.objects.annotations.Getter; import jdk.nashorn.internal.objects.annotations.Setter; import play.data.validation.Constraints; import javax.persistence.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; @MappedSuperclass public class BaseModel extends Model { @Column(name = "created_at") private Date createdAt; @Column(name = "updated_at") private Date updatedAt; @PrePersist public void onPrePersist() { createdAt = new Date(); updatedAt = new Date(); } @PreUpdate public void onPreUpdate() { updatedAt = new Date(); } /** * * @return createdAt */ public Date getCreatedAt() { return createdAt; } /** * * @return updatedAt */ public Date getUpdatedAt() { return updatedAt; } /** * * @return createdAt (yyyy-MM-dd HH:mm:ss) */ public String getCreatedAtWithFormat() { return dateWithFormat(createdAt); } /** * * @return updatedAt (yyyy-MM-dd HH:mm:ss) */ public String getUpdatedAtWithFormat() { return dateWithFormat(updatedAt); } private String dateWithFormat(Date date) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return df.format(date); } }
1,504
0.59641
0.59641
70
19.485714
17.037558
68
false
false
0
0
0
0
0
0
0.3
false
false
4
10cecfadad5dcbc9e98eb546fd229cd4275ff577
5,549,097,795,416
ea4fa6d8be5b2ce3c6329858d703ccd95859486c
/order/order-server/src/main/java/com/gxy/order/service/OrderMasterService.java
b2b7556c440f0bc95b102bef57b13fed38555342
[]
no_license
optimistic9527/spring-cloud-demo
https://github.com/optimistic9527/spring-cloud-demo
29cad3530aa0238ac83fc8eb2df87c7578d5d8ff
aaf6c9bcb5fe6bb3b8ab3f0ca043add119a46b5a
refs/heads/master
2020-04-13T20:09:25.911000
2019-04-10T03:58:02
2019-04-10T03:58:02
163,422,627
1
1
null
false
2018-12-30T06:53:54
2018-12-28T15:09:07
2018-12-29T07:39:55
2018-12-30T06:53:54
14
0
0
0
Java
false
null
package com.gxy.order.service; import com.codingapi.txlcn.tc.annotation.LcnTransaction; import com.gxy.common.base.BaseService; import com.gxy.common.utils.SnowFlakeIdGenerator; import com.gxy.common.utils.SuccessUtil; import com.gxy.common.vo.ResultVO; import com.gxy.order.entity.OrderDetail; import com.gxy.order.entity.OrderMaster; import com.gxy.order.exception.OrderException; import com.gxy.order.mapper.OrderMasterMapper; import com.gxy.store.client.StoreGoodsClient; import com.gxy.store.qo.PurchaseDetailQuery; import com.gxy.order.common.qo.OrderQuery; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; @Service @Slf4j public class OrderMasterService extends BaseService<OrderMasterMapper, OrderMaster> { @Autowired private OrderDetailService orderDetailService; @Autowired private SnowFlakeIdGenerator snowFlakeIdGenerator; @Autowired private StoreGoodsClient storeGoodsClient; static int a=0; @LcnTransaction @Transactional(rollbackFor = Exception.class) public void addOrder(OrderQuery orderQuery) { List<PurchaseDetailQuery> purchaseDetailQueries = orderQuery.getPurchaseDetailQueries(); //减少库存 ResultVO resultVO = storeGoodsClient.reduceInventory(purchaseDetailQueries); if (SuccessUtil.isFail(resultVO)) { throw new OrderException("减少库存失败"); } //创建订单 OrderMaster orderMaster = new OrderMaster(); long orderId = snowFlakeIdGenerator.nextId(); orderMaster.setOrderId(orderId); orderMaster.setUserId(orderQuery.userId); orderMaster.setStoreId(orderQuery.getStoreId()); orderMaster.setOrderTime(LocalDateTime.now()); orderMaster.setOrderStatus(1); add(orderMaster); //创建订单详情 List<OrderDetail> orderDetailList = purchaseDetailQueries.stream().map(orderDetailInput -> { OrderDetail orderDetail = new OrderDetail(); orderDetail.setOrderDetailId(snowFlakeIdGenerator.nextId()); orderDetail.setGoodsId(orderDetailInput.getGoodsId()); orderDetail.setCount(orderDetailInput.getCount()); orderDetail.setOrderId(orderId); return orderDetail; }).collect(Collectors.toList()); orderDetailService.insertList(orderDetailList); //throw new RuntimeException("test"); } }
UTF-8
Java
2,644
java
OrderMasterService.java
Java
[]
null
[]
package com.gxy.order.service; import com.codingapi.txlcn.tc.annotation.LcnTransaction; import com.gxy.common.base.BaseService; import com.gxy.common.utils.SnowFlakeIdGenerator; import com.gxy.common.utils.SuccessUtil; import com.gxy.common.vo.ResultVO; import com.gxy.order.entity.OrderDetail; import com.gxy.order.entity.OrderMaster; import com.gxy.order.exception.OrderException; import com.gxy.order.mapper.OrderMasterMapper; import com.gxy.store.client.StoreGoodsClient; import com.gxy.store.qo.PurchaseDetailQuery; import com.gxy.order.common.qo.OrderQuery; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; @Service @Slf4j public class OrderMasterService extends BaseService<OrderMasterMapper, OrderMaster> { @Autowired private OrderDetailService orderDetailService; @Autowired private SnowFlakeIdGenerator snowFlakeIdGenerator; @Autowired private StoreGoodsClient storeGoodsClient; static int a=0; @LcnTransaction @Transactional(rollbackFor = Exception.class) public void addOrder(OrderQuery orderQuery) { List<PurchaseDetailQuery> purchaseDetailQueries = orderQuery.getPurchaseDetailQueries(); //减少库存 ResultVO resultVO = storeGoodsClient.reduceInventory(purchaseDetailQueries); if (SuccessUtil.isFail(resultVO)) { throw new OrderException("减少库存失败"); } //创建订单 OrderMaster orderMaster = new OrderMaster(); long orderId = snowFlakeIdGenerator.nextId(); orderMaster.setOrderId(orderId); orderMaster.setUserId(orderQuery.userId); orderMaster.setStoreId(orderQuery.getStoreId()); orderMaster.setOrderTime(LocalDateTime.now()); orderMaster.setOrderStatus(1); add(orderMaster); //创建订单详情 List<OrderDetail> orderDetailList = purchaseDetailQueries.stream().map(orderDetailInput -> { OrderDetail orderDetail = new OrderDetail(); orderDetail.setOrderDetailId(snowFlakeIdGenerator.nextId()); orderDetail.setGoodsId(orderDetailInput.getGoodsId()); orderDetail.setCount(orderDetailInput.getCount()); orderDetail.setOrderId(orderId); return orderDetail; }).collect(Collectors.toList()); orderDetailService.insertList(orderDetailList); //throw new RuntimeException("test"); } }
2,644
0.744624
0.742704
66
38.454544
23.30443
100
false
false
0
0
0
0
0
0
0.681818
false
false
4
fd716f85b137d2ab796991216b58fa5a4ca8b0df
14,121,852,490,899
1009f7fb596463b69dc4ea5e106cb647c9668447
/Sor_Servicios/src/java/Servicios/BorrarPeticion.java
29b4dedd60d2642f1ea55147e6ed007f56531503
[]
no_license
franbn14/SORPAPETEAM
https://github.com/franbn14/SORPAPETEAM
e829c11ee3121dd7933f596031c894d11b01afdd
487fb54b4ab6ef773894b4624db828d948a8ae8b
refs/heads/master
2020-03-29T19:40:55.358000
2014-05-25T15:22:40
2014-05-25T15:22:40
13,744,382
0
2
null
false
2013-11-24T15:59:57
2013-10-21T14:12:43
2013-11-24T15:59:57
2013-11-24T15:59:57
32,288
0
0
0
Java
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 Servicios; import CEN.ClientCEN; import CEN.OfferCEN; import CEN.RequestCEN; import Email.Email; import Email.EmailFactoria; import java.util.ArrayList; import javax.crypto.SecretKey; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.mail.MessagingException; import logger.ClientLogger; import security.AES; import security.KeysManager; /** * * @author fran */ @WebService(serviceName = "BorrarPeticion") public class BorrarPeticion { /** * Web service operation */ @WebMethod(operationName = "BorrarWeb") public void BorrarWeb(@WebParam(name = "id") int id) { RequestCEN request = RequestCEN.getByCode(id); //Obtengo las ofertas para avisar a los desguaces que se han rechazado sus ofertas. ArrayList<OfferCEN> ofertas = OfferCEN.getByRequest(id); if (ofertas != null) { for (int i = 0; i < ofertas.size(); i++) { //Enviamos el email para notificar de el rechazo de las ofertas Email email = EmailFactoria.getEmail(EmailFactoria.tipoEmail.OfertaRechazada, ofertas.get(i)); try { email.send(); } catch (MessagingException ex) { System.err.println(ex.getMessage()); } } } ClientLogger.setLogMessage(3,ClientCEN.getByID(request.getClient().getId()).getNIF(),id+""); request.delete(); } @WebMethod(operationName = "Borrar") public void Borrar(@WebParam(name = "id") int id, @WebParam(name = "idP") String idP) { KeysManager km = KeysManager.GetInstance(); try { idP = AES.decrypt(idP, (SecretKey)km.getKey(id)); } catch (Exception ex) { System.err.println(ex); } int idInt = Integer.parseInt(idP); RequestCEN request = RequestCEN.getByCode(idInt); //Obtengo las ofertas para avisar a los desguaces que se han rechazado sus ofertas. ArrayList<OfferCEN> ofertas = OfferCEN.getByRequest(idInt); if (ofertas != null) { for (int i = 0; i < ofertas.size(); i++) { //Enviamos el email para notificar de el rechazo de las ofertas Email email = EmailFactoria.getEmail(EmailFactoria.tipoEmail.OfertaRechazada, ofertas.get(i)); try { email.send(); } catch (MessagingException ex) { System.err.println(ex.getMessage()); } } } ClientLogger.setLogMessage(3,ClientCEN.getByID(request.getClient().getId()).getNIF(),id+""); request.delete(); } }
UTF-8
Java
2,919
java
BorrarPeticion.java
Java
[ { "context": ";\nimport security.KeysManager;\n\n\n/**\n *\n * @author fran\n */\n@WebService(serviceName = \"BorrarPeticion\")\np", "end": 602, "score": 0.9834892749786377, "start": 598, "tag": "USERNAME", "value": "fran" } ]
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 Servicios; import CEN.ClientCEN; import CEN.OfferCEN; import CEN.RequestCEN; import Email.Email; import Email.EmailFactoria; import java.util.ArrayList; import javax.crypto.SecretKey; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.mail.MessagingException; import logger.ClientLogger; import security.AES; import security.KeysManager; /** * * @author fran */ @WebService(serviceName = "BorrarPeticion") public class BorrarPeticion { /** * Web service operation */ @WebMethod(operationName = "BorrarWeb") public void BorrarWeb(@WebParam(name = "id") int id) { RequestCEN request = RequestCEN.getByCode(id); //Obtengo las ofertas para avisar a los desguaces que se han rechazado sus ofertas. ArrayList<OfferCEN> ofertas = OfferCEN.getByRequest(id); if (ofertas != null) { for (int i = 0; i < ofertas.size(); i++) { //Enviamos el email para notificar de el rechazo de las ofertas Email email = EmailFactoria.getEmail(EmailFactoria.tipoEmail.OfertaRechazada, ofertas.get(i)); try { email.send(); } catch (MessagingException ex) { System.err.println(ex.getMessage()); } } } ClientLogger.setLogMessage(3,ClientCEN.getByID(request.getClient().getId()).getNIF(),id+""); request.delete(); } @WebMethod(operationName = "Borrar") public void Borrar(@WebParam(name = "id") int id, @WebParam(name = "idP") String idP) { KeysManager km = KeysManager.GetInstance(); try { idP = AES.decrypt(idP, (SecretKey)km.getKey(id)); } catch (Exception ex) { System.err.println(ex); } int idInt = Integer.parseInt(idP); RequestCEN request = RequestCEN.getByCode(idInt); //Obtengo las ofertas para avisar a los desguaces que se han rechazado sus ofertas. ArrayList<OfferCEN> ofertas = OfferCEN.getByRequest(idInt); if (ofertas != null) { for (int i = 0; i < ofertas.size(); i++) { //Enviamos el email para notificar de el rechazo de las ofertas Email email = EmailFactoria.getEmail(EmailFactoria.tipoEmail.OfertaRechazada, ofertas.get(i)); try { email.send(); } catch (MessagingException ex) { System.err.println(ex.getMessage()); } } } ClientLogger.setLogMessage(3,ClientCEN.getByID(request.getClient().getId()).getNIF(),id+""); request.delete(); } }
2,919
0.608428
0.607057
87
32.551723
28.483816
110
false
false
0
0
0
0
0
0
0.551724
false
false
4
1f29c8ac3a16cc5a2a1bae60238c432c95acd8e1
10,325,101,394,714
8810e3ed9d4a24082fdabad5b4eb8a9737c33527
/src/main/java/net/unit8/maven/plugins/ElmRunMojo.java
5d6a79c9aec97c9c6a88968a57121d945e2cf956
[ "Apache-2.0" ]
permissive
perty/elm-maven-plugin
https://github.com/perty/elm-maven-plugin
f05af7fea98e7cdc8752f48d8a937a10330bb530
6fe8450a683641ed2f6d4fd59be7caebb2fbb99a
refs/heads/master
2023-08-24T06:34:52.008000
2020-05-12T15:45:16
2020-05-12T15:45:16
263,352,451
0
0
Apache-2.0
true
2023-08-15T17:42:38
2020-05-12T13:57:54
2020-05-12T15:45:27
2023-08-15T17:42:38
35
0
0
1
Java
false
false
package net.unit8.maven.plugins; /* * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.github.eirslett.maven.plugins.frontend.lib.ElmPluginFactory; import com.github.eirslett.maven.plugins.frontend.lib.ElmRunner; import com.github.eirslett.maven.plugins.frontend.lib.FrontendException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.eclipse.aether.RepositorySystemSession; import java.io.File; /** * Running Elm. */ @Mojo(name = "run", defaultPhase = LifecyclePhase.GENERATE_RESOURCES) public class ElmRunMojo extends AbstractElmMojo { /** * npm arguments. Default is "install". */ @Parameter(defaultValue = "", property = "frontend.elm.arguments", required = false) private String arguments; @Parameter(defaultValue = "${project}", readonly = true) private MavenProject project; @Parameter(defaultValue = "${repositorySystemSession}", readonly = true) private RepositorySystemSession repositorySystemSession; /** * Skips execution of this mojo. */ @Parameter(property = "skip.elm", defaultValue = "${skip.elm}") private boolean skip; protected boolean skipExecution() { return this.skip; } /** * Location of the file. * @parameter expression="${project.build.directory}" * @required */ private File outputDirectory; public void execute(ElmPluginFactory factory) throws FrontendException { final ElmRunner elmRunner = factory.getElmRunner(); elmRunner.execute(this.arguments, this.environmentVariables); } }
UTF-8
Java
2,307
java
ElmRunMojo.java
Java
[]
null
[]
package net.unit8.maven.plugins; /* * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.github.eirslett.maven.plugins.frontend.lib.ElmPluginFactory; import com.github.eirslett.maven.plugins.frontend.lib.ElmRunner; import com.github.eirslett.maven.plugins.frontend.lib.FrontendException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.eclipse.aether.RepositorySystemSession; import java.io.File; /** * Running Elm. */ @Mojo(name = "run", defaultPhase = LifecyclePhase.GENERATE_RESOURCES) public class ElmRunMojo extends AbstractElmMojo { /** * npm arguments. Default is "install". */ @Parameter(defaultValue = "", property = "frontend.elm.arguments", required = false) private String arguments; @Parameter(defaultValue = "${project}", readonly = true) private MavenProject project; @Parameter(defaultValue = "${repositorySystemSession}", readonly = true) private RepositorySystemSession repositorySystemSession; /** * Skips execution of this mojo. */ @Parameter(property = "skip.elm", defaultValue = "${skip.elm}") private boolean skip; protected boolean skipExecution() { return this.skip; } /** * Location of the file. * @parameter expression="${project.build.directory}" * @required */ private File outputDirectory; public void execute(ElmPluginFactory factory) throws FrontendException { final ElmRunner elmRunner = factory.getElmRunner(); elmRunner.execute(this.arguments, this.environmentVariables); } }
2,307
0.727785
0.72215
70
31.957144
27.73365
88
false
false
0
0
0
0
0
0
0.428571
false
false
4
1737adf8f20fed551053251d3154889286cd7c40
5,901,285,074,752
fdd5db856e7991dd1e55736af8ee600d21a8b468
/JGZUTLab01B/app/src/main/java/com/example/jgzutlab01b/enums/DistanceUnit.java
5f93288819847d2c3fa004cf0e7a0942d5d731ab
[]
no_license
Jacob273/JG.ZUT.Android
https://github.com/Jacob273/JG.ZUT.Android
5ff205bee852184aba097ddb94c056c4d1af4eeb
a82101a637a13d66e77f84a76bcadb9385b8dde7
refs/heads/master
2023-04-30T01:21:34.011000
2021-05-11T22:33:41
2021-05-11T22:33:41
349,670,500
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.jgzutlab01b.enums; public enum DistanceUnit { Metres }
UTF-8
Java
81
java
DistanceUnit.java
Java
[]
null
[]
package com.example.jgzutlab01b.enums; public enum DistanceUnit { Metres }
81
0.753086
0.728395
5
15
14.805405
38
false
false
0
0
0
0
0
0
0.2
false
false
4
83726fc4329bfa658a9fc4ad4ede1157cdb96dae
28,389,733,895,025
a2b770101dc80454423e79524e99354f93322534
/src/stack/StackApp.java
22309b9b301cac8d2afc434289517df9654a0cb9
[]
no_license
cuikangyuan/java-data-structure
https://github.com/cuikangyuan/java-data-structure
59027f1313e7375ad6d16789a1d912d75f80a289
19a35d81c58c06a604e56b56ab32d317b3caab75
refs/heads/master
2021-12-10T11:45:55.349000
2021-12-04T15:37:03
2021-12-04T15:37:03
93,464,362
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package stack; /** * Created by cuikangyuan on 2017/9/1. */ public class StackApp { public static void main(String[] args) { StackX stackX = new StackX(10); stackX.push(1); stackX.push(2); stackX.push(3); stackX.push(4); stackX.push(5); stackX.push(6); stackX.push(7); stackX.push(8); stackX.push(9); stackX.push(10); stackX.push(11); while (!stackX.isEmpty()){ long pop = stackX.pop(); System.out.print(pop + " "); } } }
UTF-8
Java
576
java
StackApp.java
Java
[ { "context": "package stack;\n\n/**\n * Created by cuikangyuan on 2017/9/1.\n */\npublic class StackApp {\n\n pub", "end": 45, "score": 0.998120129108429, "start": 34, "tag": "USERNAME", "value": "cuikangyuan" } ]
null
[]
package stack; /** * Created by cuikangyuan on 2017/9/1. */ public class StackApp { public static void main(String[] args) { StackX stackX = new StackX(10); stackX.push(1); stackX.push(2); stackX.push(3); stackX.push(4); stackX.push(5); stackX.push(6); stackX.push(7); stackX.push(8); stackX.push(9); stackX.push(10); stackX.push(11); while (!stackX.isEmpty()){ long pop = stackX.pop(); System.out.print(pop + " "); } } }
576
0.496528
0.460069
32
17
14.217067
44
false
false
0
0
0
0
0
0
0.46875
false
false
4
36ca3f7a94bd905632fe5e80231a7f055588555d
5,703,716,579,883
5ecd15baa833422572480fad3946e0e16a389000
/framework/Synergetics-Open/subsystems/cache/main/impl/java/com/volantis/cache/impl/CacheImpl.java
94b826c0b189abf61f7a497084b844ce68c3363c
[]
no_license
jabley/volmobserverce
https://github.com/jabley/volmobserverce
4c5db36ef72c3bb7ef20fb81855e18e9b53823b9
6d760f27ac5917533eca6708f389ed9347c7016d
refs/heads/master
2021-01-01T05:31:21.902000
2009-02-04T02:29:06
2009-02-04T02:29:06
38,675,289
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* This file is part of Volantis Mobility Server. Volantis Mobility Server is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Volantis Mobility Server is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Volantis Mobility Server.  If not, see <http://www.gnu.org/licenses/>. */ /* ---------------------------------------------------------------------------- * (c) Volantis Systems Ltd 2006. * ---------------------------------------------------------------------------- */ package com.volantis.cache.impl; import com.volantis.cache.AsyncResult; import com.volantis.cache.Cache; import com.volantis.cache.CacheEntry; import com.volantis.cache.expiration.ExpirationChecker; import com.volantis.cache.group.Group; import com.volantis.cache.impl.expiration.DefaultExpirationChecker; import com.volantis.cache.impl.group.InternalGroup; import com.volantis.cache.impl.group.InternalGroupBuilder; import com.volantis.cache.impl.integrity.IntegrityCheckingReporter; import com.volantis.cache.provider.CacheableObjectProvider; import com.volantis.cache.provider.ProviderResult; import com.volantis.shared.io.IndentingWriter; import com.volantis.shared.system.SystemClock; import com.volantis.shared.throwable.ExtendedRuntimeException; import com.volantis.shared.time.Countdown; import com.volantis.shared.time.Period; import com.volantis.shared.time.TimedOutException; import java.util.HashMap; import java.util.Map; import java.util.Timer; /** * The implementation of a {@link Cache}. * * <p>Maintains a map to get an entry based on a hashing key and an ordered * linked list of the entries for the purpose of pruning entries.</p> */ public class CacheImpl implements InternalCache { /** * A timer to use to clean up any asynchronous queries. */ private static final Timer TIMER = new Timer(true); /** * Default object reponsible for proving the cacheable objects. * * <p>This may be overridden by a provider supplied directly to the * {@link #retrieve(Object, CacheableObjectProvider)} method.</p> */ private final CacheableObjectProvider provider; /** * The expiration checker. */ private final ExpirationChecker expirationChecker; /** * The default group. */ private final InternalGroup rootGroup; /** * The map from key to {@link CacheEntryImpl}. * * <p>Must only be accessed while synchronized upon it.</p> */ private final Map map; /** * The clock to use by the cache for computing expiration times, etc. */ private final SystemClock clock; /** * Initialise. * * @param builder The builder. */ public CacheImpl(CacheBuilderImpl builder) { map = new HashMap(); provider = builder.getObjectProvider(); // Initialise the expiration checker, if none is specified then use the // default one. ExpirationChecker expirationChecker = builder.getExpirationChecker(); if (expirationChecker == null) { expirationChecker = DefaultExpirationChecker.getDefaultInstance(); } this.expirationChecker = expirationChecker; // Initialise the clock, if none is specified then use the default // instance. SystemClock clock = builder.getClock(); if (clock == null) { clock = SystemClock.getDefaultInstance(); } this.clock = clock; InternalGroupBuilder rootGroupBuilder = builder.getRootGroupBuilder(); rootGroup = rootGroupBuilder.buildGroup(this, null, "root", clock); } // Javadoc inherited. public Object retrieve(Object key) { return retrieveInternal(key, provider); } // Javadoc inherited. public Object retrieve(Object key, CacheableObjectProvider provider) { if (provider == null) { throw new IllegalArgumentException("provider cannot be null"); } return retrieveInternal(key, provider); } /** * Retrieve the object for the key. * * @param key The key to use to retrieve the object. * @param provider The {@link CacheableObjectProvider} to use. * @return The object for the key, may be null. */ private Object retrieveInternal( Object key, final CacheableObjectProvider provider) { Object value = null; AsyncResult async = asyncQuery(key, Period.INDEFINITELY); // Act on the state of the entry. It is possible that within this // window where the entry is not synchronized that the entry could // change, the only case were it cannot is if it was in the update // state as all other threads will see it as pending and wait. // Some of the things that can happen in this window are: // 1) Entries may have been removed, either implicitly, or explicitly. // 2) Entries may have expired on another thread. // 3) Entries may have moved groups. // 4) Entries may have new values. if (async.isReady()) { value = async.getValue(); } else { ProviderResult result = null; Throwable throwable = null; boolean failed = true; try { // Get the entry, this will return null if the entry is marked // as being uncacheable. CacheEntry entry = async.getEntry(); // Get the provider to retrieve the object. It is given the // whole entry so that it can perform revalidation of an // existing entry if it has expired. result = provider.retrieve(clock, key, entry); if (result == null) { throw new IllegalStateException("Result from provider is null"); } // Request to the provider did not fail. failed = false; } catch (RuntimeException e) { // Remember the exception so that it can be stored in the // entry to indicate the original cause. throwable = e; // Rethrow the exceptions. throw e; } catch (Error e) { // Remember the exception so that it can be stored in the // entry to indicate the original cause. throwable = e; // Rethrow the exceptions. throw e; } finally { if (failed) { async.failed(throwable); } else { // the cache must be updated even if the result has a // non-null throwable value = async.update(result); // if the result has a throwable, thow it wrapped inside a // runtime exception Throwable cause = result.getThrowable(); if (cause != null) { // The entry has a throwable so throw a runtime // exception, encapsulating the original throwable. throw new ExtendedRuntimeException( "Attempt to access " + key + " failed due to the following error", cause); } } } } return value; } // Javadoc inherited. public AsyncResult asyncQuery(Object key, Period timeout) { InternalAsyncResult async; // Get the entry from the map while synchronized. InternalCacheEntry entry = getCacheEntry(key); // Synchronize on the entry in order to get and possibly update the // state of the entry. synchronized (entry) { EntryState state = entry.getState(); // If the entry may have expired then check it. if (state.mayHaveExpired()) { // Check the entry and if it has expired then it requires // updating. if (expirationChecker.hasExpired(clock, entry)) { state = EntryState.UPDATE; } } // If the state requires it then wait until the state changes. if (state.mustWait()) { Countdown countdown = Countdown.getCountdown(timeout, clock); do { try { Period remaining = countdown.countdown(); entry.wait(remaining.inMillisTreatIndefinitelyAsZero()); state = entry.getState(); } catch (InterruptedException e) { throw new ExtendedRuntimeException(e); } catch (TimedOutException e) { throw new ExtendedRuntimeException(e); } } while (state.mustWait()); } // At this point we know that the state will not be pending. if (state == EntryState.UPDATE) { // The entry is new so mark it as pending so other threads // will wait. entry.setState(EntryState.PENDING); entry.setAsyncResult(null); // Create a new one each time and do not hold a reference to it // within the cache as it needs to clean up if the caller // discards its reference to it before updating the entry. async = new AsyncUpdate(entry); } else if (state == EntryState.READY || state == EntryState.ERROR) { // Check to see whether the entry is in error or not. Throwable throwable = entry.getThrowable(); if (throwable == null) { // Entry is not in error. async = entry.getAsyncResult(); if (entry.inCache()) { // Inform the group that one of its entries was hit so // it can update the structure to support the least // recently used strategy. InternalGroup group = entry.getGroup(); group.hitEntry(entry); } } else { // remove cache entry with ERROR saved, we can't cache it removeEntry(key); // The entry is in the error state so throw an // exception, encapsulating the reason why the entry // is in that state. throw new ExtendedRuntimeException( "Previous attempt to access " + key + " failed due to the following error", throwable); } } else if (state == EntryState.UNCACHEABLE) { async = entry.getAsyncResult(); } else { throw new IllegalStateException("Unknown state " + state); } } // If a limited timeout has been specified then schedule a task to // ensure it is updated within that period if necessary. if (timeout != Period.INDEFINITELY) { async.schedule(TIMER, timeout); } return async; } /** * Get the cache entry from the map. * * <p>If the entry does not exist then a new one is created and added to * the cache.</p> * * <p>This obtains the mutex for the cache map.</p> * * @param key The key to use. * @return The entry. */ private InternalCacheEntry getCacheEntry(Object key) { InternalCacheEntry entry; synchronized (map) { entry = (CacheEntryImpl) map.get(key); if (entry == null) { // If the entry could not be found then create a new one and // add it to the map. It needs adding to the map so that other // concurrent requests can find it and wait on it but it is // not added to the list of entries, or cause other entries to // be removed until the object has been retrieved. entry = new CacheEntryImpl(this, key); map.put(key, entry); } } return entry; } // Javadoc inherited. public Group getRootGroup() { return rootGroup; } // Javadoc inherited. public void removeFromMap(Object key) { // Protect the map from being accessed concurrently. synchronized (map) { map.remove(key); } } // Javadoc inherited. public void performIntegrityCheck(IntegrityCheckingReporter reporter) { rootGroup.performIntegrityCheck(reporter); } // Javadoc inherited. public void debugStructure(IndentingWriter writer) { rootGroup.debugStructure(writer); } // Javadoc inherited. public CacheEntry removeEntry(Object key) { InternalCacheEntry entry; synchronized (map) { entry = (CacheEntryImpl) map.get(key); } if (entry == null) { return null; } entry.removeFromCache(); return entry; } }
UTF-8
Java
13,759
java
CacheImpl.java
Java
[]
null
[]
/* This file is part of Volantis Mobility Server. Volantis Mobility Server is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Volantis Mobility Server is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Volantis Mobility Server.  If not, see <http://www.gnu.org/licenses/>. */ /* ---------------------------------------------------------------------------- * (c) Volantis Systems Ltd 2006. * ---------------------------------------------------------------------------- */ package com.volantis.cache.impl; import com.volantis.cache.AsyncResult; import com.volantis.cache.Cache; import com.volantis.cache.CacheEntry; import com.volantis.cache.expiration.ExpirationChecker; import com.volantis.cache.group.Group; import com.volantis.cache.impl.expiration.DefaultExpirationChecker; import com.volantis.cache.impl.group.InternalGroup; import com.volantis.cache.impl.group.InternalGroupBuilder; import com.volantis.cache.impl.integrity.IntegrityCheckingReporter; import com.volantis.cache.provider.CacheableObjectProvider; import com.volantis.cache.provider.ProviderResult; import com.volantis.shared.io.IndentingWriter; import com.volantis.shared.system.SystemClock; import com.volantis.shared.throwable.ExtendedRuntimeException; import com.volantis.shared.time.Countdown; import com.volantis.shared.time.Period; import com.volantis.shared.time.TimedOutException; import java.util.HashMap; import java.util.Map; import java.util.Timer; /** * The implementation of a {@link Cache}. * * <p>Maintains a map to get an entry based on a hashing key and an ordered * linked list of the entries for the purpose of pruning entries.</p> */ public class CacheImpl implements InternalCache { /** * A timer to use to clean up any asynchronous queries. */ private static final Timer TIMER = new Timer(true); /** * Default object reponsible for proving the cacheable objects. * * <p>This may be overridden by a provider supplied directly to the * {@link #retrieve(Object, CacheableObjectProvider)} method.</p> */ private final CacheableObjectProvider provider; /** * The expiration checker. */ private final ExpirationChecker expirationChecker; /** * The default group. */ private final InternalGroup rootGroup; /** * The map from key to {@link CacheEntryImpl}. * * <p>Must only be accessed while synchronized upon it.</p> */ private final Map map; /** * The clock to use by the cache for computing expiration times, etc. */ private final SystemClock clock; /** * Initialise. * * @param builder The builder. */ public CacheImpl(CacheBuilderImpl builder) { map = new HashMap(); provider = builder.getObjectProvider(); // Initialise the expiration checker, if none is specified then use the // default one. ExpirationChecker expirationChecker = builder.getExpirationChecker(); if (expirationChecker == null) { expirationChecker = DefaultExpirationChecker.getDefaultInstance(); } this.expirationChecker = expirationChecker; // Initialise the clock, if none is specified then use the default // instance. SystemClock clock = builder.getClock(); if (clock == null) { clock = SystemClock.getDefaultInstance(); } this.clock = clock; InternalGroupBuilder rootGroupBuilder = builder.getRootGroupBuilder(); rootGroup = rootGroupBuilder.buildGroup(this, null, "root", clock); } // Javadoc inherited. public Object retrieve(Object key) { return retrieveInternal(key, provider); } // Javadoc inherited. public Object retrieve(Object key, CacheableObjectProvider provider) { if (provider == null) { throw new IllegalArgumentException("provider cannot be null"); } return retrieveInternal(key, provider); } /** * Retrieve the object for the key. * * @param key The key to use to retrieve the object. * @param provider The {@link CacheableObjectProvider} to use. * @return The object for the key, may be null. */ private Object retrieveInternal( Object key, final CacheableObjectProvider provider) { Object value = null; AsyncResult async = asyncQuery(key, Period.INDEFINITELY); // Act on the state of the entry. It is possible that within this // window where the entry is not synchronized that the entry could // change, the only case were it cannot is if it was in the update // state as all other threads will see it as pending and wait. // Some of the things that can happen in this window are: // 1) Entries may have been removed, either implicitly, or explicitly. // 2) Entries may have expired on another thread. // 3) Entries may have moved groups. // 4) Entries may have new values. if (async.isReady()) { value = async.getValue(); } else { ProviderResult result = null; Throwable throwable = null; boolean failed = true; try { // Get the entry, this will return null if the entry is marked // as being uncacheable. CacheEntry entry = async.getEntry(); // Get the provider to retrieve the object. It is given the // whole entry so that it can perform revalidation of an // existing entry if it has expired. result = provider.retrieve(clock, key, entry); if (result == null) { throw new IllegalStateException("Result from provider is null"); } // Request to the provider did not fail. failed = false; } catch (RuntimeException e) { // Remember the exception so that it can be stored in the // entry to indicate the original cause. throwable = e; // Rethrow the exceptions. throw e; } catch (Error e) { // Remember the exception so that it can be stored in the // entry to indicate the original cause. throwable = e; // Rethrow the exceptions. throw e; } finally { if (failed) { async.failed(throwable); } else { // the cache must be updated even if the result has a // non-null throwable value = async.update(result); // if the result has a throwable, thow it wrapped inside a // runtime exception Throwable cause = result.getThrowable(); if (cause != null) { // The entry has a throwable so throw a runtime // exception, encapsulating the original throwable. throw new ExtendedRuntimeException( "Attempt to access " + key + " failed due to the following error", cause); } } } } return value; } // Javadoc inherited. public AsyncResult asyncQuery(Object key, Period timeout) { InternalAsyncResult async; // Get the entry from the map while synchronized. InternalCacheEntry entry = getCacheEntry(key); // Synchronize on the entry in order to get and possibly update the // state of the entry. synchronized (entry) { EntryState state = entry.getState(); // If the entry may have expired then check it. if (state.mayHaveExpired()) { // Check the entry and if it has expired then it requires // updating. if (expirationChecker.hasExpired(clock, entry)) { state = EntryState.UPDATE; } } // If the state requires it then wait until the state changes. if (state.mustWait()) { Countdown countdown = Countdown.getCountdown(timeout, clock); do { try { Period remaining = countdown.countdown(); entry.wait(remaining.inMillisTreatIndefinitelyAsZero()); state = entry.getState(); } catch (InterruptedException e) { throw new ExtendedRuntimeException(e); } catch (TimedOutException e) { throw new ExtendedRuntimeException(e); } } while (state.mustWait()); } // At this point we know that the state will not be pending. if (state == EntryState.UPDATE) { // The entry is new so mark it as pending so other threads // will wait. entry.setState(EntryState.PENDING); entry.setAsyncResult(null); // Create a new one each time and do not hold a reference to it // within the cache as it needs to clean up if the caller // discards its reference to it before updating the entry. async = new AsyncUpdate(entry); } else if (state == EntryState.READY || state == EntryState.ERROR) { // Check to see whether the entry is in error or not. Throwable throwable = entry.getThrowable(); if (throwable == null) { // Entry is not in error. async = entry.getAsyncResult(); if (entry.inCache()) { // Inform the group that one of its entries was hit so // it can update the structure to support the least // recently used strategy. InternalGroup group = entry.getGroup(); group.hitEntry(entry); } } else { // remove cache entry with ERROR saved, we can't cache it removeEntry(key); // The entry is in the error state so throw an // exception, encapsulating the reason why the entry // is in that state. throw new ExtendedRuntimeException( "Previous attempt to access " + key + " failed due to the following error", throwable); } } else if (state == EntryState.UNCACHEABLE) { async = entry.getAsyncResult(); } else { throw new IllegalStateException("Unknown state " + state); } } // If a limited timeout has been specified then schedule a task to // ensure it is updated within that period if necessary. if (timeout != Period.INDEFINITELY) { async.schedule(TIMER, timeout); } return async; } /** * Get the cache entry from the map. * * <p>If the entry does not exist then a new one is created and added to * the cache.</p> * * <p>This obtains the mutex for the cache map.</p> * * @param key The key to use. * @return The entry. */ private InternalCacheEntry getCacheEntry(Object key) { InternalCacheEntry entry; synchronized (map) { entry = (CacheEntryImpl) map.get(key); if (entry == null) { // If the entry could not be found then create a new one and // add it to the map. It needs adding to the map so that other // concurrent requests can find it and wait on it but it is // not added to the list of entries, or cause other entries to // be removed until the object has been retrieved. entry = new CacheEntryImpl(this, key); map.put(key, entry); } } return entry; } // Javadoc inherited. public Group getRootGroup() { return rootGroup; } // Javadoc inherited. public void removeFromMap(Object key) { // Protect the map from being accessed concurrently. synchronized (map) { map.remove(key); } } // Javadoc inherited. public void performIntegrityCheck(IntegrityCheckingReporter reporter) { rootGroup.performIntegrityCheck(reporter); } // Javadoc inherited. public void debugStructure(IndentingWriter writer) { rootGroup.debugStructure(writer); } // Javadoc inherited. public CacheEntry removeEntry(Object key) { InternalCacheEntry entry; synchronized (map) { entry = (CacheEntryImpl) map.get(key); } if (entry == null) { return null; } entry.removeFromCache(); return entry; } }
13,759
0.57229
0.571636
386
34.639896
26.326416
84
true
false
0
0
0
0
0
0
0.352332
false
false
4
02f76f05782bdebd640ad46d9a59f485a6a5605e
20,100,447,006,703
30bd0e38fd61f3a90e0de920b68d5594b5fb90ae
/src/Node.java
94e144cb90ee581cdd08caf33f7983b90edcd990
[]
no_license
yannisvl/Artificial-Intelligence-NTUA
https://github.com/yannisvl/Artificial-Intelligence-NTUA
e7011bd8725820c41d3fef1dad29feed032988a6
cc72d59589bc3a5603b186345441268e88e38f5d
refs/heads/main
2023-03-12T00:12:25.561000
2021-02-28T16:31:16
2021-02-28T16:31:16
343,137,709
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.List; class Node { double X, Y; int id, lineid; String name; List<Node> L; Node parent; double eurist ; double fromstart; double total, real_dist, real_from_start; double rating; public double getX() { return X; } public double getY() { return Y; } public void setX(double val) { X = val; } public void setY(double val) { Y = val; } public int getid() { return id; } public void setid(int val) { id = val; } public String getname() { return name; } public void setname(String n) { name = n; } public void setparent(Node val) { parent = val; } public void seteurist(double val) { eurist=val; } public void setfromstart(double val) { fromstart = val; } public void settotal(double val) { total = val; } public void setL(){L = new ArrayList<>();} public void insertneighbor(Node neighbor) { L.add(neighbor); } public String toString() { String foo = this.id + " " + this.X + " " + this.Y; return foo; } int compareTo(Node n2){ if (this.total < n2.total) return -1; else if (this.total > n2.total) return 1; else return 0; } int compareTo2(Node n2) { if (this.X < n2.X || (this.X == n2.X && this.Y < n2.Y)) return -1; else if (this.X > n2.X || (this.X == n2.X && this.Y > n2.Y)) return 1; return 0; } int compareTo3(Node n2){ if (this.rating > n2.rating) return -1; else if (this.rating < n2.rating) return 1; else return 0; } }
UTF-8
Java
1,726
java
Node.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.List; class Node { double X, Y; int id, lineid; String name; List<Node> L; Node parent; double eurist ; double fromstart; double total, real_dist, real_from_start; double rating; public double getX() { return X; } public double getY() { return Y; } public void setX(double val) { X = val; } public void setY(double val) { Y = val; } public int getid() { return id; } public void setid(int val) { id = val; } public String getname() { return name; } public void setname(String n) { name = n; } public void setparent(Node val) { parent = val; } public void seteurist(double val) { eurist=val; } public void setfromstart(double val) { fromstart = val; } public void settotal(double val) { total = val; } public void setL(){L = new ArrayList<>();} public void insertneighbor(Node neighbor) { L.add(neighbor); } public String toString() { String foo = this.id + " " + this.X + " " + this.Y; return foo; } int compareTo(Node n2){ if (this.total < n2.total) return -1; else if (this.total > n2.total) return 1; else return 0; } int compareTo2(Node n2) { if (this.X < n2.X || (this.X == n2.X && this.Y < n2.Y)) return -1; else if (this.X > n2.X || (this.X == n2.X && this.Y > n2.Y)) return 1; return 0; } int compareTo3(Node n2){ if (this.rating > n2.rating) return -1; else if (this.rating < n2.rating) return 1; else return 0; } }
1,726
0.533604
0.519699
80
20.575001
18.162994
78
false
false
0
0
0
0
0
0
0.55
false
false
4
fff6ede68d5a5448730d4cffb956f6d4e2a9989a
11,227,044,545,686
33a5fcf025d92929669d53cf2dc3f1635eeb59c6
/黑龙江移动执法/src/MobileEnforcement/src/com/mapuni/android/infoQuery/TreeViewAdapter.java
c56c8348f6a22b8f146ebf86849016723e860ff8
[]
no_license
dayunxiang/MyHistoryProjects
https://github.com/dayunxiang/MyHistoryProjects
2cacbe26d522eeb3f858d69aa6b3c77f3c533f37
6e041f53a184e7c4380ce25f5c0274aa10f06c8e
refs/heads/master
2020-11-29T09:23:27.085000
2018-03-12T07:07:18
2018-03-12T07:07:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mapuni.android.infoQuery; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.mapuni.android.MobileEnforcement.R; import com.mapuni.android.dataprovider.SqliteUtil; import com.mapuni.android.infoQuery.SuperTreeViewAdapter.SuperTreeNode; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.AbsListView; import android.widget.BaseExpandableListAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class TreeViewAdapter extends BaseExpandableListAdapter { /** 每一个节点的高度 */ public static final int ItemHeight = 75; /** 每一项距左边的距离 */ public static final int PaddingLeft = 36; /** 初始化据左边的的距离 */ private int myPaddingLeft = 0; static public class TreeNode { Object Title; Object Id; List<Object> childs = new ArrayList<Object>(); } List<TreeNode> treeNodes = new ArrayList<TreeNode>(); Context parentContext; public TreeViewAdapter(Context context, int myPaddingLeft) { parentContext = context; this.myPaddingLeft = myPaddingLeft; } public List<TreeNode> getTreeNode() { return treeNodes; } public void updateTreeNode(List<TreeNode> nodes) { treeNodes = nodes; } public void removeAll() { treeNodes.clear(); } @Override public Object getChild(int groupPosition, int childPosition) { // TODO Auto-generated method stub return treeNodes.get(groupPosition).childs.get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { // TODO Auto-generated method stub return childPosition; } static public TextView getTextView(Context context) { AbsListView.LayoutParams lp = new AbsListView.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); TextView textView = new TextView(context); textView.setTextSize(22); textView.setLayoutParams(lp); textView.setPadding(10, 0, 0, 0); textView.setGravity(Gravity.CENTER_VERTICAL); return textView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { // TODO Auto-generated method stub convertView = LayoutInflater.from(parentContext).inflate( R.layout.flfgtreeview, null); TextView textView = (TextView) convertView.findViewById(R.id.flfgtitle); String str = getChild(groupPosition, childPosition).toString(); String id = str.substring(0, str.indexOf("|")); String title = str.substring(str.indexOf("|") + 1); ImageView imageView = (ImageView) convertView.findViewById(R.id.flfglefticon); imageView.setVisibility(View.INVISIBLE); textView.setText(title); Button fuhan = (Button) convertView.findViewById(R.id.fuhan); Button xxfg = (Button) convertView.findViewById(R.id.xxfg); // 查询出复函数量 ArrayList<HashMap<String, Object>> listFH = SqliteUtil.getInstance() .queryBySqlReturnArrayListHashMap( "select count(*) from t_attachment where FK_Id = '" + id + "' and remark = '复函'"); // wsc 增加显示文件夹下文件的复函数量 if (listFH != null) { String sfh = "复函" + "(" + listFH.get(0).get("count(*)") + ")"; fuhan.setText(sfh); } // 查询出先行法律数量 ArrayList<HashMap<String, Object>> listXXFL = SqliteUtil.getInstance() .queryBySqlReturnArrayListHashMap( "select count(*) from t_attachment where FK_Id = '" + id + "' and remark = '现行法律'"); if (listXXFL != null) { String sfhxx = "现行法律" + "(" + listXXFL.get(0).get("count(*)") + ")"; xxfg.setText(sfhxx); } xxfg.setTag(id + "|" + title); fuhan.setTag(id + "|" + title); xxfg.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClassName("com.mapuni.android.MobileEnforcement", "com.mapuni.android.infoQuery.LNFLFGShow"); String str = v.getTag().toString(); intent.putExtra("pid", str.substring(0, str.indexOf("|"))); intent.putExtra("title", str.substring(str.indexOf("|") + 1)); intent.putExtra("remark", "现行法律"); parentContext.startActivity(intent); } }); fuhan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClassName("com.mapuni.android.MobileEnforcement", "com.mapuni.android.infoQuery.LNFLFGShow"); String str = v.getTag().toString(); intent.putExtra("pid", str.substring(0, str.indexOf("|"))); intent.putExtra("title", str.substring(str.indexOf("|") + 1)); intent.putExtra("remark", "复函"); parentContext.startActivity(intent); } }); textView.setText(title); return convertView; } @Override public int getChildrenCount(int groupPosition) { // TODO Auto-generated method stub return treeNodes.get(groupPosition).childs.size(); } @Override public Object getGroup(int groupPosition) { // TODO Auto-generated method stub return treeNodes.get(groupPosition); } @Override public int getGroupCount() { // TODO Auto-generated method stub return treeNodes.size(); } @Override public long getGroupId(int groupPosition) { // TODO Auto-generated method stub return groupPosition; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { // TODO Auto-generated method stub convertView = LayoutInflater.from(parentContext).inflate( R.layout.threeflfgtreeview, null); TextView textView = (TextView) convertView .findViewById(R.id.threeflfgtitle); ImageView imageView = (ImageView) convertView.findViewById(R.id.threeflfgimage); if(expandableListView!=null){ if(expandableListView.isGroupExpanded(groupPosition)) imageView.setImageResource(R.drawable.specialitem_down); else imageView.setImageResource(R.drawable.specialitem_right); } // 查询出包含子项数目 ArrayList<HashMap<String, Object>> list = SqliteUtil.getInstance() .queryBySqlReturnArrayListHashMap( "select count(*) from T_HandBookCatalog where pid = '" + ((TreeNode) getGroup(groupPosition)).Id .toString() + "'"); String numStr = "0"; if (list != null) { numStr = list.get(0).get("count(*)").toString(); } textView.setText(((TreeNode) getGroup(groupPosition)).Title.toString() + "(" + numStr + ")"); return convertView; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { // TODO Auto-generated method stub return true; } ReceiversExpandableListView expandableListView; public void setListView(ReceiversExpandableListView treeView) { expandableListView = treeView; } }
GB18030
Java
7,072
java
TreeViewAdapter.java
Java
[]
null
[]
package com.mapuni.android.infoQuery; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.mapuni.android.MobileEnforcement.R; import com.mapuni.android.dataprovider.SqliteUtil; import com.mapuni.android.infoQuery.SuperTreeViewAdapter.SuperTreeNode; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.AbsListView; import android.widget.BaseExpandableListAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class TreeViewAdapter extends BaseExpandableListAdapter { /** 每一个节点的高度 */ public static final int ItemHeight = 75; /** 每一项距左边的距离 */ public static final int PaddingLeft = 36; /** 初始化据左边的的距离 */ private int myPaddingLeft = 0; static public class TreeNode { Object Title; Object Id; List<Object> childs = new ArrayList<Object>(); } List<TreeNode> treeNodes = new ArrayList<TreeNode>(); Context parentContext; public TreeViewAdapter(Context context, int myPaddingLeft) { parentContext = context; this.myPaddingLeft = myPaddingLeft; } public List<TreeNode> getTreeNode() { return treeNodes; } public void updateTreeNode(List<TreeNode> nodes) { treeNodes = nodes; } public void removeAll() { treeNodes.clear(); } @Override public Object getChild(int groupPosition, int childPosition) { // TODO Auto-generated method stub return treeNodes.get(groupPosition).childs.get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { // TODO Auto-generated method stub return childPosition; } static public TextView getTextView(Context context) { AbsListView.LayoutParams lp = new AbsListView.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); TextView textView = new TextView(context); textView.setTextSize(22); textView.setLayoutParams(lp); textView.setPadding(10, 0, 0, 0); textView.setGravity(Gravity.CENTER_VERTICAL); return textView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { // TODO Auto-generated method stub convertView = LayoutInflater.from(parentContext).inflate( R.layout.flfgtreeview, null); TextView textView = (TextView) convertView.findViewById(R.id.flfgtitle); String str = getChild(groupPosition, childPosition).toString(); String id = str.substring(0, str.indexOf("|")); String title = str.substring(str.indexOf("|") + 1); ImageView imageView = (ImageView) convertView.findViewById(R.id.flfglefticon); imageView.setVisibility(View.INVISIBLE); textView.setText(title); Button fuhan = (Button) convertView.findViewById(R.id.fuhan); Button xxfg = (Button) convertView.findViewById(R.id.xxfg); // 查询出复函数量 ArrayList<HashMap<String, Object>> listFH = SqliteUtil.getInstance() .queryBySqlReturnArrayListHashMap( "select count(*) from t_attachment where FK_Id = '" + id + "' and remark = '复函'"); // wsc 增加显示文件夹下文件的复函数量 if (listFH != null) { String sfh = "复函" + "(" + listFH.get(0).get("count(*)") + ")"; fuhan.setText(sfh); } // 查询出先行法律数量 ArrayList<HashMap<String, Object>> listXXFL = SqliteUtil.getInstance() .queryBySqlReturnArrayListHashMap( "select count(*) from t_attachment where FK_Id = '" + id + "' and remark = '现行法律'"); if (listXXFL != null) { String sfhxx = "现行法律" + "(" + listXXFL.get(0).get("count(*)") + ")"; xxfg.setText(sfhxx); } xxfg.setTag(id + "|" + title); fuhan.setTag(id + "|" + title); xxfg.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClassName("com.mapuni.android.MobileEnforcement", "com.mapuni.android.infoQuery.LNFLFGShow"); String str = v.getTag().toString(); intent.putExtra("pid", str.substring(0, str.indexOf("|"))); intent.putExtra("title", str.substring(str.indexOf("|") + 1)); intent.putExtra("remark", "现行法律"); parentContext.startActivity(intent); } }); fuhan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClassName("com.mapuni.android.MobileEnforcement", "com.mapuni.android.infoQuery.LNFLFGShow"); String str = v.getTag().toString(); intent.putExtra("pid", str.substring(0, str.indexOf("|"))); intent.putExtra("title", str.substring(str.indexOf("|") + 1)); intent.putExtra("remark", "复函"); parentContext.startActivity(intent); } }); textView.setText(title); return convertView; } @Override public int getChildrenCount(int groupPosition) { // TODO Auto-generated method stub return treeNodes.get(groupPosition).childs.size(); } @Override public Object getGroup(int groupPosition) { // TODO Auto-generated method stub return treeNodes.get(groupPosition); } @Override public int getGroupCount() { // TODO Auto-generated method stub return treeNodes.size(); } @Override public long getGroupId(int groupPosition) { // TODO Auto-generated method stub return groupPosition; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { // TODO Auto-generated method stub convertView = LayoutInflater.from(parentContext).inflate( R.layout.threeflfgtreeview, null); TextView textView = (TextView) convertView .findViewById(R.id.threeflfgtitle); ImageView imageView = (ImageView) convertView.findViewById(R.id.threeflfgimage); if(expandableListView!=null){ if(expandableListView.isGroupExpanded(groupPosition)) imageView.setImageResource(R.drawable.specialitem_down); else imageView.setImageResource(R.drawable.specialitem_right); } // 查询出包含子项数目 ArrayList<HashMap<String, Object>> list = SqliteUtil.getInstance() .queryBySqlReturnArrayListHashMap( "select count(*) from T_HandBookCatalog where pid = '" + ((TreeNode) getGroup(groupPosition)).Id .toString() + "'"); String numStr = "0"; if (list != null) { numStr = list.get(0).get("count(*)").toString(); } textView.setText(((TreeNode) getGroup(groupPosition)).Title.toString() + "(" + numStr + ")"); return convertView; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { // TODO Auto-generated method stub return true; } ReceiversExpandableListView expandableListView; public void setListView(ReceiversExpandableListView treeView) { expandableListView = treeView; } }
7,072
0.724283
0.721095
225
29.675556
22.587835
82
false
false
0
0
0
0
0
0
2.395555
false
false
4
2c728602838794bb2d67cba43839d6f654f66c1d
1,047,972,065,243
0142e11405b8108baba8ff5cf039d3a2c9fa1bc8
/src/main/java/com/example/tos/result/ResultUtil.java
2c5d4c082a32ea7fa1e6a75ab75d603e2a8133a3
[]
no_license
epsilon-2048/tos
https://github.com/epsilon-2048/tos
3dff0ec35ed3d5938b424fa355503abc490d26d7
966e5b853cc390943df6dcb0cb87b63d25efea14
refs/heads/master
2020-05-09T12:10:52.726000
2019-04-14T15:20:41
2019-04-14T15:20:41
181,104,358
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.tos.result; /** * 统一格式处理工具类 */ public class ResultUtil { public static Result error(Integer code, String msg){ Result result = new Result(); result.setCode(code); result.setMsg(msg); return result; } public static Result sussess(Object data){ Result result = new Result(); result.setMsg(CodeEnum.SUCCESS.getMsg()); result.setCode(CodeEnum.SUCCESS.getCode()); result.setData(data); return result; } public static Result sussess(){ return sussess(null); } }
UTF-8
Java
609
java
ResultUtil.java
Java
[]
null
[]
package com.example.tos.result; /** * 统一格式处理工具类 */ public class ResultUtil { public static Result error(Integer code, String msg){ Result result = new Result(); result.setCode(code); result.setMsg(msg); return result; } public static Result sussess(Object data){ Result result = new Result(); result.setMsg(CodeEnum.SUCCESS.getMsg()); result.setCode(CodeEnum.SUCCESS.getCode()); result.setData(data); return result; } public static Result sussess(){ return sussess(null); } }
609
0.607445
0.607445
30
18.700001
18.173515
57
false
false
0
0
0
0
0
0
0.4
false
false
4
75464358a1e3a5b395e3f23ae893409c713723b4
15,685,220,582,401
8e34f18631a8842efc6198a07463bda7b4a7b681
/src/main/java/net/robinfriedli/aiode/audio/youtube/YouTubeVideo.java
97dc57934db69fc667e5ab6fffe3a3fec49a7675
[ "Apache-2.0" ]
permissive
robinfriedli/botify
https://github.com/robinfriedli/botify
49ccc96c19e043cef95e5d558b56e48aeb669ee4
b7e886514c0a95f3582a45690fa7362061a529b7
refs/heads/master
2021-11-19T02:39:33.768000
2021-11-18T16:05:52
2021-11-18T16:05:52
146,214,533
178
64
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.robinfriedli.aiode.audio.youtube; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.annotation.Nullable; import net.dv8tion.jda.api.entities.User; import net.robinfriedli.aiode.audio.Playable; import net.robinfriedli.aiode.audio.spotify.SpotifyTrack; import net.robinfriedli.aiode.entities.Episode; import net.robinfriedli.aiode.entities.Playlist; import net.robinfriedli.aiode.entities.PlaylistItem; import net.robinfriedli.aiode.entities.Song; import net.robinfriedli.aiode.entities.Video; import net.robinfriedli.aiode.exceptions.UnavailableResourceException; import org.hibernate.Session; /** * Interface for all classes that may represent a YouTube video. Currently implemented by {@link YouTubeVideoImpl} * as the standard implementation for YouTube videos and {@link HollowYouTubeVideo} for YouTube videos that are loaded * asynchronously. This interface extends {@link Playable}, meaning it can be added to the queued and be played directly. */ public interface YouTubeVideo extends Playable { /** * @return the id of the YouTube video, throwing an {@link UnavailableResourceException} if cancelled */ String getVideoId() throws UnavailableResourceException; @Override default String getId() throws UnavailableResourceException { return getRedirectedSpotifyTrack() != null ? getRedirectedSpotifyTrack().getId() : getVideoId(); } @Override default String getTitle() throws UnavailableResourceException { return getRedirectedSpotifyTrack() != null ? getRedirectedSpotifyTrack().getName() : getDisplay(); } @Override default String getTitle(long timeOut, TimeUnit unit) throws UnavailableResourceException, TimeoutException { return getRedirectedSpotifyTrack() != null ? getRedirectedSpotifyTrack().getName() : getDisplay(timeOut, unit); } @Override default String getTitleNow(String alternativeValue) throws UnavailableResourceException { return getRedirectedSpotifyTrack() != null ? getRedirectedSpotifyTrack().getName() : getDisplayNow(alternativeValue); } @Override default String getPlaybackUrl() throws UnavailableResourceException { return String.format("https://www.youtube.com/watch?v=%s", getVideoId()); } /** * @return the duration of the YouTube video in milliseconds or throw an {@link UnavailableResourceException} if cancelled */ long getDuration() throws UnavailableResourceException; /** * @return the duration of the YouTube video in milliseconds or throw a {@link TimeoutException} if loading takes * longer that the provided amount of time */ long getDuration(long timeOut, TimeUnit unit) throws UnavailableResourceException, TimeoutException; @Override default long getDurationMs() throws UnavailableResourceException { return getDuration(); } @Override default long getDurationMs(long timeOut, TimeUnit unit) throws UnavailableResourceException, TimeoutException { return getDuration(timeOut, unit); } @Override default long getDurationNow(long alternativeValue) throws UnavailableResourceException { return getDuration(); } @Nullable @Override default String getAlbumCoverUrl() { if (getRedirectedSpotifyTrack() != null) { return getRedirectedSpotifyTrack().getAlbumCoverUrl(); } try { return String.format("https://img.youtube.com/vi/%s/maxresdefault.jpg", getVideoId()); } catch (UnavailableResourceException e) { return null; } } @Override default PlaylistItem export(Playlist playlist, User user, Session session) { if (getRedirectedSpotifyTrack() != null) { return getRedirectedSpotifyTrack().exhaustiveMatch( track -> new Song(track, user, playlist, session), episode -> new Episode(episode, user, playlist) ); } return new Video(this, user, playlist, session); } @Override default Source getSource() { return getRedirectedSpotifyTrack() != null ? Source.SPOTIFY : Source.YOUTUBE; } /** * @return if this YouTube video is the result of a redirected Spotify track, return the corresponding track, * else return null. For more about Spotify track redirection, see {@link YouTubeService#redirectSpotify(HollowYouTubeVideo)} */ @Nullable SpotifyTrack getRedirectedSpotifyTrack(); void setRedirectedSpotifyTrack(@Nullable SpotifyTrack track); }
UTF-8
Java
4,612
java
YouTubeVideo.java
Java
[]
null
[]
package net.robinfriedli.aiode.audio.youtube; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.annotation.Nullable; import net.dv8tion.jda.api.entities.User; import net.robinfriedli.aiode.audio.Playable; import net.robinfriedli.aiode.audio.spotify.SpotifyTrack; import net.robinfriedli.aiode.entities.Episode; import net.robinfriedli.aiode.entities.Playlist; import net.robinfriedli.aiode.entities.PlaylistItem; import net.robinfriedli.aiode.entities.Song; import net.robinfriedli.aiode.entities.Video; import net.robinfriedli.aiode.exceptions.UnavailableResourceException; import org.hibernate.Session; /** * Interface for all classes that may represent a YouTube video. Currently implemented by {@link YouTubeVideoImpl} * as the standard implementation for YouTube videos and {@link HollowYouTubeVideo} for YouTube videos that are loaded * asynchronously. This interface extends {@link Playable}, meaning it can be added to the queued and be played directly. */ public interface YouTubeVideo extends Playable { /** * @return the id of the YouTube video, throwing an {@link UnavailableResourceException} if cancelled */ String getVideoId() throws UnavailableResourceException; @Override default String getId() throws UnavailableResourceException { return getRedirectedSpotifyTrack() != null ? getRedirectedSpotifyTrack().getId() : getVideoId(); } @Override default String getTitle() throws UnavailableResourceException { return getRedirectedSpotifyTrack() != null ? getRedirectedSpotifyTrack().getName() : getDisplay(); } @Override default String getTitle(long timeOut, TimeUnit unit) throws UnavailableResourceException, TimeoutException { return getRedirectedSpotifyTrack() != null ? getRedirectedSpotifyTrack().getName() : getDisplay(timeOut, unit); } @Override default String getTitleNow(String alternativeValue) throws UnavailableResourceException { return getRedirectedSpotifyTrack() != null ? getRedirectedSpotifyTrack().getName() : getDisplayNow(alternativeValue); } @Override default String getPlaybackUrl() throws UnavailableResourceException { return String.format("https://www.youtube.com/watch?v=%s", getVideoId()); } /** * @return the duration of the YouTube video in milliseconds or throw an {@link UnavailableResourceException} if cancelled */ long getDuration() throws UnavailableResourceException; /** * @return the duration of the YouTube video in milliseconds or throw a {@link TimeoutException} if loading takes * longer that the provided amount of time */ long getDuration(long timeOut, TimeUnit unit) throws UnavailableResourceException, TimeoutException; @Override default long getDurationMs() throws UnavailableResourceException { return getDuration(); } @Override default long getDurationMs(long timeOut, TimeUnit unit) throws UnavailableResourceException, TimeoutException { return getDuration(timeOut, unit); } @Override default long getDurationNow(long alternativeValue) throws UnavailableResourceException { return getDuration(); } @Nullable @Override default String getAlbumCoverUrl() { if (getRedirectedSpotifyTrack() != null) { return getRedirectedSpotifyTrack().getAlbumCoverUrl(); } try { return String.format("https://img.youtube.com/vi/%s/maxresdefault.jpg", getVideoId()); } catch (UnavailableResourceException e) { return null; } } @Override default PlaylistItem export(Playlist playlist, User user, Session session) { if (getRedirectedSpotifyTrack() != null) { return getRedirectedSpotifyTrack().exhaustiveMatch( track -> new Song(track, user, playlist, session), episode -> new Episode(episode, user, playlist) ); } return new Video(this, user, playlist, session); } @Override default Source getSource() { return getRedirectedSpotifyTrack() != null ? Source.SPOTIFY : Source.YOUTUBE; } /** * @return if this YouTube video is the result of a redirected Spotify track, return the corresponding track, * else return null. For more about Spotify track redirection, see {@link YouTubeService#redirectSpotify(HollowYouTubeVideo)} */ @Nullable SpotifyTrack getRedirectedSpotifyTrack(); void setRedirectedSpotifyTrack(@Nullable SpotifyTrack track); }
4,612
0.723981
0.723764
120
37.433334
39.05418
129
false
false
0
0
0
0
0
0
0.491667
false
false
4
fcb6d750c2fcdb0085d8b255030bdf1a65a93079
10,462,540,334,153
b122d74548ab385cc47252cd3a3ba44406c141dd
/dev-server/src/main/java/appstraction/tools/dev_server/RequestHandler.java
c4f0c0db700b37f77594b791cc251a9443fe58be
[]
no_license
michan85/Appstraction
https://github.com/michan85/Appstraction
d56ba2ed2b19ef8c438ab4730feaafeb87964dbd
3ea70db33c737dc17ee9af37d5f8f1a9ad905604
refs/heads/master
2021-01-22T01:28:12.254000
2014-10-30T17:15:43
2014-10-30T17:15:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package appstraction.tools.dev_server; public interface RequestHandler{ public void handleRequest(RequestContext ctx) throws Exception; }
UTF-8
Java
140
java
RequestHandler.java
Java
[]
null
[]
package appstraction.tools.dev_server; public interface RequestHandler{ public void handleRequest(RequestContext ctx) throws Exception; }
140
0.835714
0.835714
6
22.5
24.246992
64
false
false
0
0
0
0
0
0
0.5
false
false
4
2fd92e5cf4f8607d291434743747b4a3fcc55544
17,008,070,544,887
40bb066bbd2097ea3ff90e3375be966e9ecd5c4a
/raclette-ext-rx/src/main/java/de/chefkoch/raclette/rx/lifecycle/CustomViewLifecycleState.java
2be913d50847a0171b165b09abbbfc9629a27a5b
[ "Apache-2.0" ]
permissive
christophwidulle/Raclette
https://github.com/christophwidulle/Raclette
83946147b3b9215aac9c121eb57e63a5b827e6f9
0d4a0ba019a9f5c2b33071d059b0e229c8fe0edd
refs/heads/master
2021-01-16T23:36:34.729000
2020-03-17T17:58:06
2020-03-17T17:58:06
48,925,590
4
2
Apache-2.0
false
2018-11-30T14:48:52
2016-01-02T22:13:24
2018-11-29T15:45:14
2018-11-30T14:48:20
694
4
1
3
Java
false
null
package de.chefkoch.raclette.rx.lifecycle; /** * Created by christophwidulle on 14.04.16. */ public enum CustomViewLifecycleState { NEW, ON_ATTACH, ON_DETACH }
UTF-8
Java
177
java
CustomViewLifecycleState.java
Java
[ { "context": "chefkoch.raclette.rx.lifecycle;\n\n/**\n * Created by christophwidulle on 14.04.16.\n */\npublic enum CustomViewLifecycleS", "end": 78, "score": 0.9597575664520264, "start": 62, "tag": "USERNAME", "value": "christophwidulle" } ]
null
[]
package de.chefkoch.raclette.rx.lifecycle; /** * Created by christophwidulle on 14.04.16. */ public enum CustomViewLifecycleState { NEW, ON_ATTACH, ON_DETACH }
177
0.689266
0.655367
12
13.75
16.422165
43
false
false
0
0
0
0
0
0
0.25
false
false
4
2e0f28c219da36dfe655e4b484f360d281e8a8c7
3,848,290,749,922
d1e651fbdf85f4d929efe7fbfc24bd577d63d0a8
/SlidingWindow/src/ArithmeticSlices.java
9af8d62b8a24b423cfa152fa2564cfe06cfdd341
[]
no_license
louieiuol/LintCode
https://github.com/louieiuol/LintCode
a25de9a5f19eb8e6326226af19717e53ad5ac295
20ed98f7cebb20d1fd136afc24c16dda44b4ccd1
refs/heads/master
2023-05-24T16:48:59.301000
2023-05-16T14:26:19
2023-05-16T14:26:19
218,160,839
1
0
null
false
2021-07-24T02:11:37
2019-10-28T23:00:10
2020-12-01T12:25:28
2021-07-24T02:11:37
22,799
1
0
0
HTML
false
false
//982. Arithmetic Slices //中文English //A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. // //For example, these are arithmetic sequence: // //1, 3, 5, 7, 9 //7, 7, 7, 7 //3, -1, -5, -9 //The following sequence is not arithmetic. // //1, 1, 2, 5, 7 //A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N. // //A slice (P, Q) of array A is called arithmetic if the sequence: //A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q. // //The function should return the number of arithmetic slices in the array A. // //Example //Example1 // //Input: [1, 2, 3, 4] //Output: 3 //Explanation: //for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself. //Example2 // //Input: [1, 2, 3] //Output: 1 public class ArithmeticSlices { public int numberOfArithmeticSlices(int[] A) { // 节省时间的Two pointer // 因为 start 到 end 之间每个数的差值valid // 那么我们求 和 start 到 end+1之间是否valid 只用查看 end和end+1的元素是不是和之前具有相同的差值 // 所以可以省去一遍的start再到end的计算 if(A == null || A.length < 3) return 0; int res=0; for(int i=0; i<A.length-2; i++){ //设定start index从0到 len-2 (至少要3个数) int diff=A[i+1]-A[i]; //我们先计算第一次的差值 for(int j=i+2; j<A.length;j++){ //end index 是从start index 到结尾的 if(A[j]-A[j-1] == diff){ //我们只计算最后一次end index和前一个数的差值 res++; //结果++ }else{ break; //跳出内循环 当前start index找不到合适的了 } } } return res; } }
UTF-8
Java
2,043
java
ArithmeticSlices.java
Java
[]
null
[]
//982. Arithmetic Slices //中文English //A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. // //For example, these are arithmetic sequence: // //1, 3, 5, 7, 9 //7, 7, 7, 7 //3, -1, -5, -9 //The following sequence is not arithmetic. // //1, 1, 2, 5, 7 //A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N. // //A slice (P, Q) of array A is called arithmetic if the sequence: //A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q. // //The function should return the number of arithmetic slices in the array A. // //Example //Example1 // //Input: [1, 2, 3, 4] //Output: 3 //Explanation: //for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself. //Example2 // //Input: [1, 2, 3] //Output: 1 public class ArithmeticSlices { public int numberOfArithmeticSlices(int[] A) { // 节省时间的Two pointer // 因为 start 到 end 之间每个数的差值valid // 那么我们求 和 start 到 end+1之间是否valid 只用查看 end和end+1的元素是不是和之前具有相同的差值 // 所以可以省去一遍的start再到end的计算 if(A == null || A.length < 3) return 0; int res=0; for(int i=0; i<A.length-2; i++){ //设定start index从0到 len-2 (至少要3个数) int diff=A[i+1]-A[i]; //我们先计算第一次的差值 for(int j=i+2; j<A.length;j++){ //end index 是从start index 到结尾的 if(A[j]-A[j-1] == diff){ //我们只计算最后一次end index和前一个数的差值 res++; //结果++ }else{ break; //跳出内循环 当前start index找不到合适的了 } } } return res; } }
2,043
0.558152
0.524763
59
29.457626
30.750126
157
false
false
0
0
0
0
0
0
0.898305
false
false
4
50a90fd7cd6ab945114cd7a87233e4ce0ec89385
10,204,842,343,766
26790ce3c23196581851ba9ca0ba01629a029a14
/chapter_001/src/main/java/ru/job4j/loop/CheckPrimeNumber.java
efe3a80cb24009f950d1d044bcce7db6d4b25cec
[ "Apache-2.0" ]
permissive
yarmail/job4j
https://github.com/yarmail/job4j
808e562cc1aa5512389d6a34e4a43eb493bcc0c4
5653304932a90143a6728c51e4376fb39e4ea1a6
refs/heads/master
2022-09-24T04:58:05.862000
2022-08-29T07:46:46
2022-08-29T07:46:46
162,922,810
1
0
Apache-2.0
false
2020-10-13T11:36:35
2018-12-23T20:45:26
2020-09-13T09:56:02
2020-10-13T11:36:34
419
0
0
1
Java
false
false
package ru.job4j.loop; /** * 5.5. Простое число [#171694] * Оператор прерывания цикла - break * (тесты есть) */ public class CheckPrimeNumber { /** * Странное упрощение предлагает IDEA * Изначально было: * primeNumber = true; * if (number = 1) -> primeNumber = false * Стало: * boolean primeNumber = number != 1; * * if (number % index == 0) { -> если остаток от деления равен 0 * */ public static boolean check(int number) { boolean primeNumber = number > 1; for (int index = 2; index < number; index++) { if (number % index == 0) { primeNumber = false; break; } } return primeNumber; } }
UTF-8
Java
859
java
CheckPrimeNumber.java
Java
[]
null
[]
package ru.job4j.loop; /** * 5.5. Простое число [#171694] * Оператор прерывания цикла - break * (тесты есть) */ public class CheckPrimeNumber { /** * Странное упрощение предлагает IDEA * Изначально было: * primeNumber = true; * if (number = 1) -> primeNumber = false * Стало: * boolean primeNumber = number != 1; * * if (number % index == 0) { -> если остаток от деления равен 0 * */ public static boolean check(int number) { boolean primeNumber = number > 1; for (int index = 2; index < number; index++) { if (number % index == 0) { primeNumber = false; break; } } return primeNumber; } }
859
0.530914
0.509409
30
23.833334
17.616438
68
false
false
0
0
0
0
0
0
0.3
false
false
4
3696511e6081682e0c8600df46e399823121d7db
19,713,899,950,909
59b5cf2cb2f10cd202354f5d25b3ee6c7fc56600
/src/main/java/com/nineleaps/EmployeeDaoImpl.java
7937360e7f416b0c3bcf6b4184581a15e54ff35b
[]
no_license
rajforsha/emp
https://github.com/rajforsha/emp
87d406564fc51e59911f14a78ca8c3159356f007
2d709231916b47bee14071ae0d034f6c327572b6
refs/heads/master
2021-05-10T19:34:51.954000
2018-01-19T17:57:58
2018-01-19T17:57:58
118,159,324
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nineleaps; import org.springframework.stereotype.Component; @Component public class EmployeeDaoImpl implements EmployeeDao { JdbcWrapper wrapper=null; public EmployeeDaoImpl(){ wrapper= new JdbcWrapper(); } public Employee getEmployeeDetails(String name) { return wrapper.getEmployeeByName(name); } public void addEmployee(Employee emp) { wrapper.insertIntoDb(emp.getName(), emp.getDesignation(), emp.getManager()); } public void updateEmployee(Employee emp) { // TODO Auto-generated method stub } }
UTF-8
Java
545
java
EmployeeDaoImpl.java
Java
[]
null
[]
package com.nineleaps; import org.springframework.stereotype.Component; @Component public class EmployeeDaoImpl implements EmployeeDao { JdbcWrapper wrapper=null; public EmployeeDaoImpl(){ wrapper= new JdbcWrapper(); } public Employee getEmployeeDetails(String name) { return wrapper.getEmployeeByName(name); } public void addEmployee(Employee emp) { wrapper.insertIntoDb(emp.getName(), emp.getDesignation(), emp.getManager()); } public void updateEmployee(Employee emp) { // TODO Auto-generated method stub } }
545
0.754128
0.754128
28
18.464285
21.860731
78
false
false
0
0
0
0
0
0
1.071429
false
false
4
1e144ce8a6aec9b88e153f5cccacb63a0aba71a8
17,111,149,773,701
17461a1146c38245835380df5437ceeaaf4f8523
/app/src/main/java/com/example/bookapp/DashboardAdminActivity.java
c9c541315c5d0e07a4e48cea5d27057d29ba860a
[]
no_license
Zeemalcs2022/Mad-Project
https://github.com/Zeemalcs2022/Mad-Project
2ff5129601bee83579a4fd00e49939de7053d6e1
adbb84f6fccfa80065f361bc6ad8b1fbbf1fbf0b
refs/heads/master
2023-08-03T03:19:44.786000
2021-09-22T06:24:29
2021-09-22T06:24:29
409,082,117
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.bookapp; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.MenuItem; import android.view.View; import com.example.bookapp.adapter.AdapterCatagory; import com.example.bookapp.databinding.ActivityDashboardAdminBinding; import com.example.bookapp.models.ModelCatagory; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; public class DashboardAdminActivity extends AppCompatActivity { private FirebaseAuth firebaseAuth; private ActivityDashboardAdminBinding binding; private ArrayList<ModelCatagory> catagoryArrayList; private AdapterCatagory adapterCatagory; private ActionBarDrawerToggle actionBarDrawerToggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityDashboardAdminBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); setUpViews(); firebaseAuth = FirebaseAuth.getInstance(); checkUser(); loadbooks(); binding.searchbar.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { try { adapterCatagory.getFilter().filter(s); } catch (Exception e) { } } @Override public void afterTextChanged(Editable s) { } }); binding.logoutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { firebaseAuth.signOut(); checkUser(); } }); binding.addcatagorybtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intemt = new Intent(DashboardAdminActivity.this, CatagoryAddActivity.class); startActivity(intemt); } }); binding.addPdf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(DashboardAdminActivity.this, PdfAddActivity.class)); } }); } private void setUpViews() { setUpDrawerLayout(); } private void setUpDrawerLayout() { setSupportActionBar(binding.appbar); actionBarDrawerToggle = new ActionBarDrawerToggle(this,findViewById(R.id.mainDrawer),R.string.app_name, R.string.app_name); actionBarDrawerToggle.syncState(); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (actionBarDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } private void loadbooks() { catagoryArrayList = new ArrayList<>(); DatabaseReference reference = FirebaseDatabase.getInstance().getReference("catagories"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { //clear arraylist beforeadding data catagoryArrayList.clear(); for (DataSnapshot ds: snapshot.getChildren()) { ModelCatagory modelCatagory = ds.getValue(ModelCatagory.class); catagoryArrayList.add(modelCatagory); } //setup adapter adapterCatagory = new AdapterCatagory(DashboardAdminActivity.this, catagoryArrayList); binding.catagoryEt.setAdapter(adapterCatagory); } @Override public void onCancelled(DatabaseError error) { } }); } private void checkUser() { FirebaseUser firebaseUser = firebaseAuth.getCurrentUser(); if(firebaseUser == null) { //not login go to main screen startActivity(new Intent(this, MainActivity.class)); finish(); } else { String email = firebaseUser.getEmail(); // binding.subtitle.setText(email); } } }
UTF-8
Java
5,022
java
DashboardAdminActivity.java
Java
[]
null
[]
package com.example.bookapp; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.MenuItem; import android.view.View; import com.example.bookapp.adapter.AdapterCatagory; import com.example.bookapp.databinding.ActivityDashboardAdminBinding; import com.example.bookapp.models.ModelCatagory; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; public class DashboardAdminActivity extends AppCompatActivity { private FirebaseAuth firebaseAuth; private ActivityDashboardAdminBinding binding; private ArrayList<ModelCatagory> catagoryArrayList; private AdapterCatagory adapterCatagory; private ActionBarDrawerToggle actionBarDrawerToggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityDashboardAdminBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); setUpViews(); firebaseAuth = FirebaseAuth.getInstance(); checkUser(); loadbooks(); binding.searchbar.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { try { adapterCatagory.getFilter().filter(s); } catch (Exception e) { } } @Override public void afterTextChanged(Editable s) { } }); binding.logoutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { firebaseAuth.signOut(); checkUser(); } }); binding.addcatagorybtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intemt = new Intent(DashboardAdminActivity.this, CatagoryAddActivity.class); startActivity(intemt); } }); binding.addPdf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(DashboardAdminActivity.this, PdfAddActivity.class)); } }); } private void setUpViews() { setUpDrawerLayout(); } private void setUpDrawerLayout() { setSupportActionBar(binding.appbar); actionBarDrawerToggle = new ActionBarDrawerToggle(this,findViewById(R.id.mainDrawer),R.string.app_name, R.string.app_name); actionBarDrawerToggle.syncState(); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (actionBarDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } private void loadbooks() { catagoryArrayList = new ArrayList<>(); DatabaseReference reference = FirebaseDatabase.getInstance().getReference("catagories"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { //clear arraylist beforeadding data catagoryArrayList.clear(); for (DataSnapshot ds: snapshot.getChildren()) { ModelCatagory modelCatagory = ds.getValue(ModelCatagory.class); catagoryArrayList.add(modelCatagory); } //setup adapter adapterCatagory = new AdapterCatagory(DashboardAdminActivity.this, catagoryArrayList); binding.catagoryEt.setAdapter(adapterCatagory); } @Override public void onCancelled(DatabaseError error) { } }); } private void checkUser() { FirebaseUser firebaseUser = firebaseAuth.getCurrentUser(); if(firebaseUser == null) { //not login go to main screen startActivity(new Intent(this, MainActivity.class)); finish(); } else { String email = firebaseUser.getEmail(); // binding.subtitle.setText(email); } } }
5,022
0.63401
0.63401
164
29.628048
26.532114
115
false
false
0
0
0
0
0
0
0.457317
false
false
4
c479dcd5b8b3e441be9566eeb874bc8b796623e3
876,173,393,382
3dcbe078feb68e41ac81581c1170558507aea4f5
/src/com/application/rss/model/RSSFeed.java
63ab49a6c3d71dce03ac03478809604686ec1e72
[ "MIT" ]
permissive
poluh/iReadNews
https://github.com/poluh/iReadNews
a6d7c2576fb0a1ad1909010b1a79e6e508c387eb
09699e43e8448bca6441bd4143f71ddbb497bebe
refs/heads/master
2021-05-15T05:54:26.562000
2018-01-14T07:55:18
2018-01-14T07:55:18
115,824,736
27
0
MIT
false
2018-01-14T07:41:36
2017-12-30T21:18:31
2018-01-05T13:45:28
2018-01-14T07:41:35
196
1
0
0
Java
false
null
package com.application.rss.model; import javafx.scene.image.Image; import java.util.ArrayList; import java.util.List; public class RSSFeed { private final String title, description, link, date; private final Image image; private final List<RSSMessage> messages = new ArrayList<>(); public RSSFeed(String title, String description, String link, String date, Image image) { this.title = title; this.description = description; this.link = link; this.date = date; this.image = image; } public String getTitle() { return title; } public String getDescription() { return description; } public String getLink() { return link; } public String getDate() { return date; } public List<RSSMessage> getMessages() { return messages; } public Image getImage() { return image; } }
UTF-8
Java
936
java
RSSFeed.java
Java
[]
null
[]
package com.application.rss.model; import javafx.scene.image.Image; import java.util.ArrayList; import java.util.List; public class RSSFeed { private final String title, description, link, date; private final Image image; private final List<RSSMessage> messages = new ArrayList<>(); public RSSFeed(String title, String description, String link, String date, Image image) { this.title = title; this.description = description; this.link = link; this.date = date; this.image = image; } public String getTitle() { return title; } public String getDescription() { return description; } public String getLink() { return link; } public String getDate() { return date; } public List<RSSMessage> getMessages() { return messages; } public Image getImage() { return image; } }
936
0.620726
0.620726
48
18.5
19.466852
93
false
false
0
0
0
0
0
0
0.520833
false
false
4
84076066d4f155c7c3df8b0185629943740aea50
17,987,323,089,733
f077f9c5bcf41699b11687e2b3c10909e9943c23
/phantomjs/src/com/ylx/entity/Author.java
8d6cfa028183e79a6902d7e8e4d101c40505c74e
[]
no_license
liangyangtao/phantomjs
https://github.com/liangyangtao/phantomjs
d943d000c687462c207f3b205c74788b1cafd7a2
3199a9dd93aee13b928f9d43e6c4175abebe4365
refs/heads/master
2016-09-11T04:23:31.230000
2015-01-29T11:42:15
2015-01-29T11:42:15
18,754,353
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ylx.entity; import java.util.Date; /** * * @author 梁杨桃 * */ public class Author { // 微博抓取实体类 public int auto_id; // 微博自增编号 public String author_id; // 用户编号 public String author_nickName;// 用户昵称 public String author_url; // 用户微博url public String author_img_url; // 用户的头像 public String mid; // 微博 的Mid public String content; // 微博的内容 public String content_image; // 微博的图片(可能没有) public Date news_time; // 微博发布的时间 public String follow; // 微博发布的客户端 public Date crawl_time; // 抓取的时间 public int getAuto_id() { return auto_id; } public void setAuto_id(int auto_id) { this.auto_id = auto_id; } public String getAuthor_id() { return author_id; } public void setAuthor_id(String author_id) { this.author_id = author_id; } public String getAuthor_nickName() { return author_nickName; } public void setAuthor_nickName(String author_nickName) { this.author_nickName = author_nickName; } public String getAuthor_url() { return author_url; } public void setAuthor_url(String author_url) { this.author_url = author_url; } public String getAuthor_img_url() { return author_img_url; } public void setAuthor_img_url(String author_img_url) { this.author_img_url = author_img_url; } public String getMid() { return mid; } public void setMid(String mid) { this.mid = mid; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getNews_time() { return news_time; } public void setNews_time(Date news_time) { this.news_time = news_time; } public String getFollow() { return follow; } public void setFollow(String follow) { this.follow = follow; } public Date getCrawl_time() { return crawl_time; } public void setCrawl_time(Date crawl_time) { this.crawl_time = crawl_time; } public String getContent_image() { return content_image; } public void setContent_image(String content_image) { this.content_image = content_image; } }
UTF-8
Java
2,275
java
Author.java
Java
[ { "context": "\r\n\r\nimport java.util.Date;\r\n\r\n/**\r\n * \r\n * @author 梁杨桃\r\n * */\r\npublic class Author {\r\n\t// 微博抓取实体类\r\n\tpubl", "end": 77, "score": 0.999821662902832, "start": 74, "tag": "NAME", "value": "梁杨桃" } ]
null
[]
package com.ylx.entity; import java.util.Date; /** * * @author 梁杨桃 * */ public class Author { // 微博抓取实体类 public int auto_id; // 微博自增编号 public String author_id; // 用户编号 public String author_nickName;// 用户昵称 public String author_url; // 用户微博url public String author_img_url; // 用户的头像 public String mid; // 微博 的Mid public String content; // 微博的内容 public String content_image; // 微博的图片(可能没有) public Date news_time; // 微博发布的时间 public String follow; // 微博发布的客户端 public Date crawl_time; // 抓取的时间 public int getAuto_id() { return auto_id; } public void setAuto_id(int auto_id) { this.auto_id = auto_id; } public String getAuthor_id() { return author_id; } public void setAuthor_id(String author_id) { this.author_id = author_id; } public String getAuthor_nickName() { return author_nickName; } public void setAuthor_nickName(String author_nickName) { this.author_nickName = author_nickName; } public String getAuthor_url() { return author_url; } public void setAuthor_url(String author_url) { this.author_url = author_url; } public String getAuthor_img_url() { return author_img_url; } public void setAuthor_img_url(String author_img_url) { this.author_img_url = author_img_url; } public String getMid() { return mid; } public void setMid(String mid) { this.mid = mid; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getNews_time() { return news_time; } public void setNews_time(Date news_time) { this.news_time = news_time; } public String getFollow() { return follow; } public void setFollow(String follow) { this.follow = follow; } public Date getCrawl_time() { return crawl_time; } public void setCrawl_time(Date crawl_time) { this.crawl_time = crawl_time; } public String getContent_image() { return content_image; } public void setContent_image(String content_image) { this.content_image = content_image; } }
2,275
0.651807
0.651807
113
16.858408
16.65308
57
false
false
0
0
0
0
0
0
1.19469
false
false
4
ce2ec4e2a24c7b5260fac93676a6235c857d48d1
4,947,802,389,379
604b861b5b5812771dba859e0ebe0ece785e7e63
/mobile/src/main/java/com/yobalabs/socialwf/view/PreviewView.java
49c2d701c6a27283c69d2a05fa562d5d68838cab
[]
no_license
xgear-public/social-watch-face
https://github.com/xgear-public/social-watch-face
4958a048a3b34ab4350392cd2b715dfff4b31714
c1924fc4fc59c776a548307d24cfc4df21c904e6
refs/heads/master
2020-03-30T16:24:12.180000
2015-04-07T20:31:02
2015-04-07T20:32:14
32,760,213
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yobalabs.socialwf.view; import com.yobalabs.socialwf.util.BitmapUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; public class PreviewView extends ImageView { public PreviewView(Context context, AttributeSet attrs) { super(context, attrs); } public PreviewView(Context context) { super(context); } public PreviewView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private int topX = 0, topY = 0; @Override protected void onDraw(Canvas canvas) { Drawable drawable = getDrawable(); if (drawable == null) { return; } if (getWidth() == 0 || getHeight() == 0) { return; } if (drawable instanceof BitmapDrawable) { Bitmap b = ((BitmapDrawable) drawable).getBitmap(); Bitmap roundBitmap = BitmapUtils.getCircleBitmap(b); if(roundBitmap.getWidth() < getWidth()) { int curW = getWidth(); int bitmapW = roundBitmap.getWidth(); topX = (int) ((double) curW / 2 - (double)bitmapW / 2); int curH = getHeight(); int bitmapH = roundBitmap.getHeight(); topY = (int) ((double) curH / 2 - (double)bitmapH / 2); } else { topX = 0; topY = 0; } canvas.drawBitmap(roundBitmap, topX, topY, null); } else super.onDraw(canvas); } }
UTF-8
Java
1,471
java
PreviewView.java
Java
[]
null
[]
package com.yobalabs.socialwf.view; import com.yobalabs.socialwf.util.BitmapUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; public class PreviewView extends ImageView { public PreviewView(Context context, AttributeSet attrs) { super(context, attrs); } public PreviewView(Context context) { super(context); } public PreviewView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private int topX = 0, topY = 0; @Override protected void onDraw(Canvas canvas) { Drawable drawable = getDrawable(); if (drawable == null) { return; } if (getWidth() == 0 || getHeight() == 0) { return; } if (drawable instanceof BitmapDrawable) { Bitmap b = ((BitmapDrawable) drawable).getBitmap(); Bitmap roundBitmap = BitmapUtils.getCircleBitmap(b); if(roundBitmap.getWidth() < getWidth()) { int curW = getWidth(); int bitmapW = roundBitmap.getWidth(); topX = (int) ((double) curW / 2 - (double)bitmapW / 2); int curH = getHeight(); int bitmapH = roundBitmap.getHeight(); topY = (int) ((double) curH / 2 - (double)bitmapH / 2); } else { topX = 0; topY = 0; } canvas.drawBitmap(roundBitmap, topX, topY, null); } else super.onDraw(canvas); } }
1,471
0.696125
0.689327
59
23.932203
20.44245
72
false
false
0
0
0
0
0
0
2.186441
false
false
4
9af17734f7126a60eb768b7d10900622e3873366
20,160,576,542,145
e818974ed892c56d4bc5dce614a6e4c4a8b3f124
/src/com/gospell/boss/controller/DispatchController.java
ae1a3a84f12fcffd20e70c1255cd5c871dbf2067
[]
no_license
lucher007/boss
https://github.com/lucher007/boss
761b575052a51f8e4cfaced8f154b64e6bd2e348
e399d6143b24a33618e4df132a48c65a84c962d7
refs/heads/master
2020-04-14T19:28:25.688000
2019-01-04T04:44:39
2019-01-04T04:44:39
164,058,848
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gospell.boss.controller; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import com.gospell.boss.common.Tools; import com.gospell.boss.dao.IAreaDao; import com.gospell.boss.dao.IDispatchDao; import com.gospell.boss.dao.INetworkDao; import com.gospell.boss.dao.IOperatorDao; import com.gospell.boss.dao.IProblemcomplaintDao; import com.gospell.boss.dao.IUserDao; import com.gospell.boss.po.Area; import com.gospell.boss.po.Dispatch; import com.gospell.boss.po.Network; import com.gospell.boss.po.Operator; import com.gospell.boss.po.Problemcomplaint; import com.gospell.boss.po.User; /** * 用户控制层 */ @Controller @Scope("prototype") @RequestMapping("/dispatch") @Transactional public class DispatchController extends BaseController { @Autowired private ServletContext servletContext; @Autowired private IDispatchDao dispatchDao; @Autowired private IUserDao userDao; @Autowired private IProblemcomplaintDao problemcomplaintDao; @Autowired private INetworkDao networkDao; @Autowired private IAreaDao areaDao; @Autowired private IOperatorDao operatorDao; /** * 查询工单信息 */ @RequestMapping(value = "/findByList") public String findByList(Dispatch form) { form.setPager_openset(Integer.valueOf(servletContext.getInitParameter("pager_openset"))); form.setPager_count(dispatchDao.findByCount(form)); System.out.println("**********before*******90:" + form.getQuerystate()); //查询工单界面,需要判断操作员类型,如果是维修人员,只能看到自己的工单 if (form.getJumping().equals("findReturnDispatchList")) { Operator operator = (Operator)getSession().getAttribute("Operator"); if("2".equals(operator.getOperatortype())){//施工人员 form.setQuerydispatcherid(operator.getId()); } } List<Dispatch> dispatchlist = dispatchDao.findByList(form); System.out.println("******************90:" + form.getQuerystate()); for (Dispatch dispatch : dispatchlist) { dispatch.setUser(userDao.findById(dispatch.getUserid())); Network network = networkDao.findById(dispatch.getNetid()); dispatch.setNetwork(network!=null?network:new Network()); Area findarea = new Area(); findarea.setAreacode(dispatch.getAreacode()); findarea.setNetid(dispatch.getNetid()); findarea = areaDao.findByAreacode(findarea); dispatch.setArea(findarea!=null?findarea:new Area()); Operator worker = operatorDao.findById(dispatch.getDispatcherid()); dispatch.setWorker(worker!=null?worker:new Operator()); } form.setDispatchlist(dispatchlist); if (form.getJumping().equals("findDispatchListForAssign")) { return "dispatch/findDispatchListForAssign"; } else if (form.getJumping().equals("findDispatchList")) { return "dispatch/findDispatchList"; } else if (form.getJumping().equals("findReturnDispatchList")) { return "dispatch/findReturnDispatchList"; } else if (form.getJumping().equals("findDispatchListForCheck")) { return "dispatch/findDispatchListForCheck"; } else return null; } /** * 添加信息初始化 */ @RequestMapping(value = "/addInit") public String addInit(Dispatch form) { form.setJumping("findDispatchList"); return "dispatch/addDispatch"; } /** * 新增 */ @RequestMapping(value = "/save") public String save(Dispatch form) { Operator operator = (Operator)getSession().getAttribute("Operator"); Dispatch oldDispatch = dispatchDao.findByComplaintid(form.getComplaintid()); if (oldDispatch != null) { form.setReturninfo(getMessage("dispatch.complaintid.existed")); // complaint return addInit(form); } Problemcomplaint problemcomplaint = problemcomplaintDao.findById(form.getComplaintid()); if(problemcomplaint == null){ problemcomplaint = new Problemcomplaint(); } User user = userDao.findById(problemcomplaint.getUserid()); if(user == null ){ user = new User(); } form.setNetid(user.getNetid()); form.setAreacode(user.getAreacode()); form.setComplaintid(problemcomplaint.getId()); form.setComplaintno(problemcomplaint.getComplaintno()); form.setProblemtype(problemcomplaint.getProblemtype()); form.setUserid(user.getId()); form.setAdddate(Tools.getCurrentTime()); form.setOperatorid(operator.getId()); form.setState("0"); dispatchDao.save(form); // 维护对应投诉单的状态为1:受理中 problemcomplaint.setState("1"); problemcomplaintDao.updateState(problemcomplaint); form.setReturninfo(getMessage("page.execution.success")); return addInit(form); } /** * 更新初始化 */ @RequestMapping(value = "/updateInit") public String updateInit(Dispatch form) { form.setDispatch(dispatchDao.findById(form.getId())); form.setUser(userDao.findById(form.getDispatch().getUserid())); return "dispatch/updateDispatch"; } /** * 更新 */ @RequestMapping(value = "/update") public String update(Dispatch form) { Dispatch dispatch = dispatchDao.findById(form.getId()); dispatch.setProblemtype(form.getProblemtype()); dispatch.setContent(form.getContent()); dispatch.setState("0");//修改工单内容就必须需要重新派单 dispatch.setDispatcherid(null); dispatch.setDealdate(null); dispatch.setDealresult(null); dispatchDao.update(dispatch); form.setReturninfo(getMessage("page.execution.success")); return updateInit(form); } /** * 删除 */ @RequestMapping(value = "/delete") public String delete(Dispatch form) { Dispatch dispatch = dispatchDao.findById(form.getId()); Problemcomplaint correspondingComplaint = problemcomplaintDao.findById(dispatch.getComplaintid()); if(correspondingComplaint !=null && correspondingComplaint.getId() !=null){ correspondingComplaint.setState("0"); // 维护投诉单状态为0-未受理 problemcomplaintDao.updateState(correspondingComplaint); } dispatchDao.delete(form.getId()); form.setReturninfo(getMessage("page.execution.success")); form.setJumping("findDispatchList"); return findByList(form); } /** * 审核通过结单 */ @RequestMapping(value = "/savePass") public String savePass(Dispatch form) { Dispatch dispatch = dispatchDao.findById(form.getId()); dispatch.setState("5"); // 通过则结单设置state = 5-结单 dispatchDao.updateState(dispatch); //查询此工单关联的问题投诉 if(!StringUtils.isEmpty(dispatch.getComplaintid())){ Problemcomplaint correspondingComplaint = problemcomplaintDao.findById(dispatch.getComplaintid()); if(correspondingComplaint != null && correspondingComplaint.getId() != null){ correspondingComplaint.setState("3"); // 问题投诉单状态为已处理 problemcomplaintDao.updateState(correspondingComplaint); } } form.setReturninfo(getMessage("page.execution.success")); form.setJumping("findDispatchListForCheck"); form.setQuerystate("34");// 设立Querystate标识,在工单审核页面只显示state=3(已处理)和4(处理失败)的工单 return findByList(form); } /** * 重新发送工单给营业员修改 */ @RequestMapping(value = "/saveReturn") public String saveReturn(Dispatch form) { Dispatch dispatch = dispatchDao.findById(form.getId()); dispatch.setState("0"); //通过则结单设置state = 0-未派单 dispatch.setDispatcherid(null); dispatch.setDealdate(null); dispatch.setDealresult(null); dispatchDao.updateReturnInfo(dispatch); dispatchDao.saveAssign(dispatch); form.setReturninfo(getMessage("page.execution.success")); form.setJumping("findDispatchListForCheck"); form.setQuerystate("34");// 设立Querystate标识,在工单审核页面只显示state=3(已处理)和4(处理失败)的工单 return findByList(form); } /** * 派单初始化 */ @RequestMapping(value = "/assignInit") public String assignInit(Dispatch form) { form.setDispatch(dispatchDao.findById(form.getId())); form.setUser(userDao.findById(form.getDispatch().getUserid())); form.getDispatch().setJumping(form.getJumping());// 判断返回跳转 return "dispatch/assignDispatch"; } /** * 派发工单 */ @RequestMapping(value = "/saveAssign") public String saveAssign(Dispatch form) { form.setState("1");// 设置工单状态为1(已派单) dispatchDao.saveAssign(form); form.setReturninfo(getMessage("page.execution.success")); return assignInit(form); } /** * 回单状态更新初始化 */ @RequestMapping(value = "/updateReturnInfoInit") public String updateReturnInfoInit(Dispatch form) { Dispatch disptch = dispatchDao.findById(form.getId()); if(disptch == null){ disptch = new Dispatch(); } form.setDispatch(disptch); form.setUser(userDao.findById(form.getDispatch().getUserid())); form.setWorker(operatorDao.findById(disptch.getDispatcherid())); return "dispatch/updateReturnInfo"; } /** * 更新回单信息 */ @RequestMapping(value = "/updateReturnInfo") public String updateReturnInfo(Dispatch form) { dispatchDao.updateReturnInfo(form); form.setReturninfo(getMessage("page.execution.success")); return updateReturnInfoInit(form); } /** * 获取问题单列表以生成工单 */ @RequestMapping(value = "/findProblemcomplaintListForDialog") public String findProblemcomplaintListForDialog(Problemcomplaint form) { form.setPager_openset(5); form.setPager_count(problemcomplaintDao.findByCount(form)); List<Problemcomplaint> problemcomplaintlist = problemcomplaintDao.findByList(form); for (Problemcomplaint problemcomplaint : problemcomplaintlist) { problemcomplaint.setUser(userDao.findById(problemcomplaint.getUserid())); } form.setProblemcomplaintlist(problemcomplaintlist); return "dispatch/findProblemcomplaintListForDialog"; } /** * 获取维修员列表以备选择 */ @RequestMapping(value = "/findDispatcherListForDialog") public String findDispatcherListForDialog(Dispatch form) { return "dispatch/findDispatcherListForDialog"; } /** * 获取维修员列表以备选择 */ @RequestMapping(value = "/saveAssignSelected") public String saveAssignSelected(Dispatch form, HttpServletRequest request) { String[] idArray = request.getParameterValues("ids"); Integer dispatcherid = Integer.parseInt(request.getParameter("dispatcherSelected")); if (idArray == null || idArray.length < 1) { form.setReturninfo(getMessage("page.select.empty")); } else { for (int i = 0; i < idArray.length; i++) { Dispatch dispatch = dispatchDao.findById(Integer.parseInt(idArray[i])); dispatch.setState("1"); // 通过则结单设置state = 已经派单 dispatch.setDispatcherid(dispatcherid); dispatchDao.saveAssign(dispatch); } form.setReturninfo(getMessage("page.execution.success")); } form.setJumping("findDispatchListForAssign"); form.setQuerystate("0");// 设立Querystate标识,在工单审核页面只显示state=0(未派单)的工单 return findByList(form); } /** * 批量通过 */ @RequestMapping(value = "/savePassSelected") public String savePassSelected(Dispatch form, HttpServletRequest request) { String[] idArray = request.getParameterValues("ids"); if (idArray == null || idArray.length < 1) { form.setReturninfo(getMessage("page.select.empty")); } else { for (int i = 0; i < idArray.length; i++) { Dispatch dispatch = dispatchDao.findById(Integer.parseInt(idArray[i])); dispatch.setState("5"); // 通过则结单设置state = 5-结单 dispatchDao.updateState(dispatch); //查询此工单关联的问题投诉 if(!StringUtils.isEmpty(dispatch.getComplaintid())){ Problemcomplaint correspondingComplaint = problemcomplaintDao.findById(dispatch.getComplaintid()); if(correspondingComplaint != null && correspondingComplaint.getId() != null){ correspondingComplaint.setState("3"); // 问题投诉单状态为已处理 problemcomplaintDao.updateState(correspondingComplaint); } } } form.setReturninfo(getMessage("page.execution.success")); } form.setJumping("findDispatchListForCheck"); form.setQuerystate("34");// 设立Querystate标识,在工单审核页面只显示state=3(已处理)和4(处理失败)的工单 return findByList(form); } public INetworkDao getNetworkDao() { return networkDao; } public void setNetworkDao(INetworkDao networkDao) { this.networkDao = networkDao; } }
UTF-8
Java
13,074
java
DispatchController.java
Java
[]
null
[]
package com.gospell.boss.controller; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import com.gospell.boss.common.Tools; import com.gospell.boss.dao.IAreaDao; import com.gospell.boss.dao.IDispatchDao; import com.gospell.boss.dao.INetworkDao; import com.gospell.boss.dao.IOperatorDao; import com.gospell.boss.dao.IProblemcomplaintDao; import com.gospell.boss.dao.IUserDao; import com.gospell.boss.po.Area; import com.gospell.boss.po.Dispatch; import com.gospell.boss.po.Network; import com.gospell.boss.po.Operator; import com.gospell.boss.po.Problemcomplaint; import com.gospell.boss.po.User; /** * 用户控制层 */ @Controller @Scope("prototype") @RequestMapping("/dispatch") @Transactional public class DispatchController extends BaseController { @Autowired private ServletContext servletContext; @Autowired private IDispatchDao dispatchDao; @Autowired private IUserDao userDao; @Autowired private IProblemcomplaintDao problemcomplaintDao; @Autowired private INetworkDao networkDao; @Autowired private IAreaDao areaDao; @Autowired private IOperatorDao operatorDao; /** * 查询工单信息 */ @RequestMapping(value = "/findByList") public String findByList(Dispatch form) { form.setPager_openset(Integer.valueOf(servletContext.getInitParameter("pager_openset"))); form.setPager_count(dispatchDao.findByCount(form)); System.out.println("**********before*******90:" + form.getQuerystate()); //查询工单界面,需要判断操作员类型,如果是维修人员,只能看到自己的工单 if (form.getJumping().equals("findReturnDispatchList")) { Operator operator = (Operator)getSession().getAttribute("Operator"); if("2".equals(operator.getOperatortype())){//施工人员 form.setQuerydispatcherid(operator.getId()); } } List<Dispatch> dispatchlist = dispatchDao.findByList(form); System.out.println("******************90:" + form.getQuerystate()); for (Dispatch dispatch : dispatchlist) { dispatch.setUser(userDao.findById(dispatch.getUserid())); Network network = networkDao.findById(dispatch.getNetid()); dispatch.setNetwork(network!=null?network:new Network()); Area findarea = new Area(); findarea.setAreacode(dispatch.getAreacode()); findarea.setNetid(dispatch.getNetid()); findarea = areaDao.findByAreacode(findarea); dispatch.setArea(findarea!=null?findarea:new Area()); Operator worker = operatorDao.findById(dispatch.getDispatcherid()); dispatch.setWorker(worker!=null?worker:new Operator()); } form.setDispatchlist(dispatchlist); if (form.getJumping().equals("findDispatchListForAssign")) { return "dispatch/findDispatchListForAssign"; } else if (form.getJumping().equals("findDispatchList")) { return "dispatch/findDispatchList"; } else if (form.getJumping().equals("findReturnDispatchList")) { return "dispatch/findReturnDispatchList"; } else if (form.getJumping().equals("findDispatchListForCheck")) { return "dispatch/findDispatchListForCheck"; } else return null; } /** * 添加信息初始化 */ @RequestMapping(value = "/addInit") public String addInit(Dispatch form) { form.setJumping("findDispatchList"); return "dispatch/addDispatch"; } /** * 新增 */ @RequestMapping(value = "/save") public String save(Dispatch form) { Operator operator = (Operator)getSession().getAttribute("Operator"); Dispatch oldDispatch = dispatchDao.findByComplaintid(form.getComplaintid()); if (oldDispatch != null) { form.setReturninfo(getMessage("dispatch.complaintid.existed")); // complaint return addInit(form); } Problemcomplaint problemcomplaint = problemcomplaintDao.findById(form.getComplaintid()); if(problemcomplaint == null){ problemcomplaint = new Problemcomplaint(); } User user = userDao.findById(problemcomplaint.getUserid()); if(user == null ){ user = new User(); } form.setNetid(user.getNetid()); form.setAreacode(user.getAreacode()); form.setComplaintid(problemcomplaint.getId()); form.setComplaintno(problemcomplaint.getComplaintno()); form.setProblemtype(problemcomplaint.getProblemtype()); form.setUserid(user.getId()); form.setAdddate(Tools.getCurrentTime()); form.setOperatorid(operator.getId()); form.setState("0"); dispatchDao.save(form); // 维护对应投诉单的状态为1:受理中 problemcomplaint.setState("1"); problemcomplaintDao.updateState(problemcomplaint); form.setReturninfo(getMessage("page.execution.success")); return addInit(form); } /** * 更新初始化 */ @RequestMapping(value = "/updateInit") public String updateInit(Dispatch form) { form.setDispatch(dispatchDao.findById(form.getId())); form.setUser(userDao.findById(form.getDispatch().getUserid())); return "dispatch/updateDispatch"; } /** * 更新 */ @RequestMapping(value = "/update") public String update(Dispatch form) { Dispatch dispatch = dispatchDao.findById(form.getId()); dispatch.setProblemtype(form.getProblemtype()); dispatch.setContent(form.getContent()); dispatch.setState("0");//修改工单内容就必须需要重新派单 dispatch.setDispatcherid(null); dispatch.setDealdate(null); dispatch.setDealresult(null); dispatchDao.update(dispatch); form.setReturninfo(getMessage("page.execution.success")); return updateInit(form); } /** * 删除 */ @RequestMapping(value = "/delete") public String delete(Dispatch form) { Dispatch dispatch = dispatchDao.findById(form.getId()); Problemcomplaint correspondingComplaint = problemcomplaintDao.findById(dispatch.getComplaintid()); if(correspondingComplaint !=null && correspondingComplaint.getId() !=null){ correspondingComplaint.setState("0"); // 维护投诉单状态为0-未受理 problemcomplaintDao.updateState(correspondingComplaint); } dispatchDao.delete(form.getId()); form.setReturninfo(getMessage("page.execution.success")); form.setJumping("findDispatchList"); return findByList(form); } /** * 审核通过结单 */ @RequestMapping(value = "/savePass") public String savePass(Dispatch form) { Dispatch dispatch = dispatchDao.findById(form.getId()); dispatch.setState("5"); // 通过则结单设置state = 5-结单 dispatchDao.updateState(dispatch); //查询此工单关联的问题投诉 if(!StringUtils.isEmpty(dispatch.getComplaintid())){ Problemcomplaint correspondingComplaint = problemcomplaintDao.findById(dispatch.getComplaintid()); if(correspondingComplaint != null && correspondingComplaint.getId() != null){ correspondingComplaint.setState("3"); // 问题投诉单状态为已处理 problemcomplaintDao.updateState(correspondingComplaint); } } form.setReturninfo(getMessage("page.execution.success")); form.setJumping("findDispatchListForCheck"); form.setQuerystate("34");// 设立Querystate标识,在工单审核页面只显示state=3(已处理)和4(处理失败)的工单 return findByList(form); } /** * 重新发送工单给营业员修改 */ @RequestMapping(value = "/saveReturn") public String saveReturn(Dispatch form) { Dispatch dispatch = dispatchDao.findById(form.getId()); dispatch.setState("0"); //通过则结单设置state = 0-未派单 dispatch.setDispatcherid(null); dispatch.setDealdate(null); dispatch.setDealresult(null); dispatchDao.updateReturnInfo(dispatch); dispatchDao.saveAssign(dispatch); form.setReturninfo(getMessage("page.execution.success")); form.setJumping("findDispatchListForCheck"); form.setQuerystate("34");// 设立Querystate标识,在工单审核页面只显示state=3(已处理)和4(处理失败)的工单 return findByList(form); } /** * 派单初始化 */ @RequestMapping(value = "/assignInit") public String assignInit(Dispatch form) { form.setDispatch(dispatchDao.findById(form.getId())); form.setUser(userDao.findById(form.getDispatch().getUserid())); form.getDispatch().setJumping(form.getJumping());// 判断返回跳转 return "dispatch/assignDispatch"; } /** * 派发工单 */ @RequestMapping(value = "/saveAssign") public String saveAssign(Dispatch form) { form.setState("1");// 设置工单状态为1(已派单) dispatchDao.saveAssign(form); form.setReturninfo(getMessage("page.execution.success")); return assignInit(form); } /** * 回单状态更新初始化 */ @RequestMapping(value = "/updateReturnInfoInit") public String updateReturnInfoInit(Dispatch form) { Dispatch disptch = dispatchDao.findById(form.getId()); if(disptch == null){ disptch = new Dispatch(); } form.setDispatch(disptch); form.setUser(userDao.findById(form.getDispatch().getUserid())); form.setWorker(operatorDao.findById(disptch.getDispatcherid())); return "dispatch/updateReturnInfo"; } /** * 更新回单信息 */ @RequestMapping(value = "/updateReturnInfo") public String updateReturnInfo(Dispatch form) { dispatchDao.updateReturnInfo(form); form.setReturninfo(getMessage("page.execution.success")); return updateReturnInfoInit(form); } /** * 获取问题单列表以生成工单 */ @RequestMapping(value = "/findProblemcomplaintListForDialog") public String findProblemcomplaintListForDialog(Problemcomplaint form) { form.setPager_openset(5); form.setPager_count(problemcomplaintDao.findByCount(form)); List<Problemcomplaint> problemcomplaintlist = problemcomplaintDao.findByList(form); for (Problemcomplaint problemcomplaint : problemcomplaintlist) { problemcomplaint.setUser(userDao.findById(problemcomplaint.getUserid())); } form.setProblemcomplaintlist(problemcomplaintlist); return "dispatch/findProblemcomplaintListForDialog"; } /** * 获取维修员列表以备选择 */ @RequestMapping(value = "/findDispatcherListForDialog") public String findDispatcherListForDialog(Dispatch form) { return "dispatch/findDispatcherListForDialog"; } /** * 获取维修员列表以备选择 */ @RequestMapping(value = "/saveAssignSelected") public String saveAssignSelected(Dispatch form, HttpServletRequest request) { String[] idArray = request.getParameterValues("ids"); Integer dispatcherid = Integer.parseInt(request.getParameter("dispatcherSelected")); if (idArray == null || idArray.length < 1) { form.setReturninfo(getMessage("page.select.empty")); } else { for (int i = 0; i < idArray.length; i++) { Dispatch dispatch = dispatchDao.findById(Integer.parseInt(idArray[i])); dispatch.setState("1"); // 通过则结单设置state = 已经派单 dispatch.setDispatcherid(dispatcherid); dispatchDao.saveAssign(dispatch); } form.setReturninfo(getMessage("page.execution.success")); } form.setJumping("findDispatchListForAssign"); form.setQuerystate("0");// 设立Querystate标识,在工单审核页面只显示state=0(未派单)的工单 return findByList(form); } /** * 批量通过 */ @RequestMapping(value = "/savePassSelected") public String savePassSelected(Dispatch form, HttpServletRequest request) { String[] idArray = request.getParameterValues("ids"); if (idArray == null || idArray.length < 1) { form.setReturninfo(getMessage("page.select.empty")); } else { for (int i = 0; i < idArray.length; i++) { Dispatch dispatch = dispatchDao.findById(Integer.parseInt(idArray[i])); dispatch.setState("5"); // 通过则结单设置state = 5-结单 dispatchDao.updateState(dispatch); //查询此工单关联的问题投诉 if(!StringUtils.isEmpty(dispatch.getComplaintid())){ Problemcomplaint correspondingComplaint = problemcomplaintDao.findById(dispatch.getComplaintid()); if(correspondingComplaint != null && correspondingComplaint.getId() != null){ correspondingComplaint.setState("3"); // 问题投诉单状态为已处理 problemcomplaintDao.updateState(correspondingComplaint); } } } form.setReturninfo(getMessage("page.execution.success")); } form.setJumping("findDispatchListForCheck"); form.setQuerystate("34");// 设立Querystate标识,在工单审核页面只显示state=3(已处理)和4(处理失败)的工单 return findByList(form); } public INetworkDao getNetworkDao() { return networkDao; } public void setNetworkDao(INetworkDao networkDao) { this.networkDao = networkDao; } }
13,074
0.719711
0.716377
369
31.327913
25.1989
103
false
false
0
0
0
0
0
0
2.065041
false
false
4
70fa28da27887e6b5214e1f4330d5744531ba016
19,387,482,427,985
0a8bbc5c88f7a362304d5a1547f9999249aec1ff
/flf/src/com/fc/flf/fparty/mapper/IEventInfoCustomerMapper.java
ddb542fcc2d0856a2a28b2505a59c3cff026ede3
[]
no_license
yangjiugang/teamway
https://github.com/yangjiugang/teamway
697ea4296f92d7982166f5607b42b4ece6374a91
425cf8b1d0bc759a5f79c40cde700adbef39ba12
refs/heads/master
2021-10-20T21:46:13.327000
2018-07-30T08:10:01
2018-07-30T08:10:01
108,513,918
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fc.flf.fparty.mapper; import java.util.List; import java.util.Map; import com.fc.flf.common.domain.EventInfoCustomer; public interface IEventInfoCustomerMapper { public List<EventInfoCustomer> findEventRemarkByIdToPage(Map<String, Object> map); public int findEventRemarkCountById(int cusId); }
UTF-8
Java
323
java
IEventInfoCustomerMapper.java
Java
[]
null
[]
package com.fc.flf.fparty.mapper; import java.util.List; import java.util.Map; import com.fc.flf.common.domain.EventInfoCustomer; public interface IEventInfoCustomerMapper { public List<EventInfoCustomer> findEventRemarkByIdToPage(Map<String, Object> map); public int findEventRemarkCountById(int cusId); }
323
0.789474
0.789474
11
27.363636
25.797367
83
false
false
0
0
0
0
0
0
0.818182
false
false
4
e621f6417dd31c8272ac513094f0e02e98e6eed5
4,982,162,119,603
daa5c18f9d0510dca339ebbac61650d8980d985d
/src/model/Locking.java
652b84cf34d4f3073228ff344600c25a7703453b
[]
no_license
sphurtidixit/matchmaker-abstraction
https://github.com/sphurtidixit/matchmaker-abstraction
5c50f7e40bd2b14cc1e9ffef8359d86a546f43d2
0c4af9a746a8641c08ae510f11bb9a69cc837fca
refs/heads/master
2016-08-09T06:03:12.662000
2016-01-07T00:22:16
2016-01-07T00:22:16
49,169,940
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import javax.persistence.LockModeType; public class Locking{ static LockModeType readLockType = LockModeType.PESSIMISTIC_READ; static LockModeType writeLockType = LockModeType.PESSIMISTIC_WRITE; public static void readLock(EntityManager em, Object o){ em.lock(o,readLockType); } public static void writeLock(EntityManager em, Object o){ em.lock(o,writeLockType); } public static LockModeType getReadLockType(){ return readLockType; } public static LockModeType getWriteLockType(){ return writeLockType; } }
UTF-8
Java
735
java
Locking.java
Java
[]
null
[]
package model; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import javax.persistence.LockModeType; public class Locking{ static LockModeType readLockType = LockModeType.PESSIMISTIC_READ; static LockModeType writeLockType = LockModeType.PESSIMISTIC_WRITE; public static void readLock(EntityManager em, Object o){ em.lock(o,readLockType); } public static void writeLock(EntityManager em, Object o){ em.lock(o,writeLockType); } public static LockModeType getReadLockType(){ return readLockType; } public static LockModeType getWriteLockType(){ return writeLockType; } }
735
0.821769
0.821769
30
23.466667
22.246698
67
false
false
0
0
0
0
0
0
0.7
false
false
4
69bb1fd6efb26467b6005484ae41415369e2a29d
13,735,305,425,251
af8a1bd857dcf63119bcfc300954320df4364287
/A2 - Mortgage Calculator/src/edu/niu/cs/rosshettel/mortgage/monthlyPaymentActivity.java
cb2deb2bd9eb0eb941536933f7d191bb59f6f9df
[]
no_license
rosshettel/CSCI-490
https://github.com/rosshettel/CSCI-490
f4ff807195ce86ac464b818f28afd3bfcda5e9c6
891e441687b9a4a2820b3f972852482ed75e7866
refs/heads/master
2016-08-05T00:13:05.117000
2011-11-29T05:42:04
2011-11-29T05:42:04
2,434,434
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.niu.cs.rosshettel.mortgage; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class monthlyPaymentActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView textview = new TextView(this); textview.setText("This is the monthly payment calculator tab."); setContentView(textview); } }
UTF-8
Java
418
java
monthlyPaymentActivity.java
Java
[]
null
[]
package edu.niu.cs.rosshettel.mortgage; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class monthlyPaymentActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView textview = new TextView(this); textview.setText("This is the monthly payment calculator tab."); setContentView(textview); } }
418
0.789474
0.789474
15
26.866667
21.013859
66
false
false
0
0
0
0
0
0
1.333333
false
false
4
792faddb0621a68e8468713fed7a35f0a94a4573
30,030,411,340,282
16b3d3904c552194fdb27d9a16efd63186eda5a2
/jodd-proxetta/src/main/java/jodd/aop/Aspect.java
c31de513edd08aa0ab7427c422bf30d68898ff0a
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
brandon8863/jodd
https://github.com/brandon8863/jodd
4bd7886303635bcd6e9adae11ce2975100e73e2d
7fe46720866c409a5cf3d6ba5abdabb177ac8192
refs/heads/master
2021-01-20T02:33:05.194000
2017-08-27T20:37:02
2017-08-27T20:37:02
101,325,029
0
1
null
true
2017-08-27T20:37:03
2017-08-24T18:19:47
2017-08-24T18:19:54
2017-08-27T20:37:03
36,586
0
1
0
Java
null
null
package jodd.aop; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Base aspect class that holds the target instance. */ public abstract class Aspect implements InvocationHandler { private Object target; public Aspect(Object target) { this.target = target; } /** * Returns target object. */ public final Object getTarget() { return this.target; } /** * Runs before targets method. Returns {@code true} if target method * should run. */ public abstract boolean before(Object target, Method method, Object[] args); /** * Runs after targets method. Returns {@code true} if aspect method should * return value, otherwise {@code null}. */ public abstract boolean after(Object target, Method method, Object[] args); /** * Invoked after exception. */ public abstract boolean afterException(Object target, Method method, Object[] args, Throwable throwable); @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; if (before(target, method, args)) { try { result = method.invoke(target, args); } catch (InvocationTargetException e) { afterException(args, method, args, e.getTargetException()); } catch (Exception ex) { throw ex; } } if (after(target, method, args)) { return result; } return null; } }
UTF-8
Java
1,435
java
Aspect.java
Java
[]
null
[]
package jodd.aop; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Base aspect class that holds the target instance. */ public abstract class Aspect implements InvocationHandler { private Object target; public Aspect(Object target) { this.target = target; } /** * Returns target object. */ public final Object getTarget() { return this.target; } /** * Runs before targets method. Returns {@code true} if target method * should run. */ public abstract boolean before(Object target, Method method, Object[] args); /** * Runs after targets method. Returns {@code true} if aspect method should * return value, otherwise {@code null}. */ public abstract boolean after(Object target, Method method, Object[] args); /** * Invoked after exception. */ public abstract boolean afterException(Object target, Method method, Object[] args, Throwable throwable); @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; if (before(target, method, args)) { try { result = method.invoke(target, args); } catch (InvocationTargetException e) { afterException(args, method, args, e.getTargetException()); } catch (Exception ex) { throw ex; } } if (after(target, method, args)) { return result; } return null; } }
1,435
0.699652
0.699652
63
21.793652
25.666456
106
false
false
0
0
0
0
0
0
1.714286
false
false
4
c426762a929a45820291c1ac10c0879aa35ca4ef
32,160,715,172,979
296280d291cb7e1b6863efc2c2dfbc807f75974f
/joc/src/main/joc/internal/compiler/CompareExp.java
0fa26f5e8cf368cfa464dc5091cfa50270637a22
[]
no_license
tectronics/java-on-contracts
https://github.com/tectronics/java-on-contracts
4b7d83b18b34c2aa9e3a534e0581ed0814b4970d
d3ace3846e2185713b26bf1713fbd35784d399d1
refs/heads/master
2018-01-11T15:16:44.784000
2012-02-20T07:42:07
2012-02-20T07:42:07
46,922,790
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package joc.internal.compiler; public class CompareExp extends NestedExp { private String code; public CompareExp(NestedExp exp) { this(exp.getCode()); } private CompareExp(String code) { this.code = code; } public CompareExp eq(NestedExp exp) { return new CompareExp("(" + code + " == " + exp.getCode() + ")"); } public CompareExp gt(NestedExp exp) { return new CompareExp("(" + code + " > " + exp.getCode() + ")"); } public CompareExp ge(NestedExp exp) { return new CompareExp("(" + code + " >= " + exp.getCode() + ")"); } public CompareExp lt(NestedExp exp) { return new CompareExp("(" + code + " < " + exp.getCode() + ")"); } public CompareExp le(NestedExp exp) { return new CompareExp("(" + code + " <= " + exp.getCode() + ")"); } @Override protected String getCode() { return code; } }
UTF-8
Java
873
java
CompareExp.java
Java
[]
null
[]
package joc.internal.compiler; public class CompareExp extends NestedExp { private String code; public CompareExp(NestedExp exp) { this(exp.getCode()); } private CompareExp(String code) { this.code = code; } public CompareExp eq(NestedExp exp) { return new CompareExp("(" + code + " == " + exp.getCode() + ")"); } public CompareExp gt(NestedExp exp) { return new CompareExp("(" + code + " > " + exp.getCode() + ")"); } public CompareExp ge(NestedExp exp) { return new CompareExp("(" + code + " >= " + exp.getCode() + ")"); } public CompareExp lt(NestedExp exp) { return new CompareExp("(" + code + " < " + exp.getCode() + ")"); } public CompareExp le(NestedExp exp) { return new CompareExp("(" + code + " <= " + exp.getCode() + ")"); } @Override protected String getCode() { return code; } }
873
0.591065
0.591065
38
20.973684
23.095325
67
false
false
0
0
0
0
0
0
1.157895
false
false
4
61991c891655fb812e517be1909f4cd693c0448b
17,394,617,617,044
b3a8ab9f630230cd33ac314bc6fe467fb713fc35
/openrest4j-api/src/main/java/com/wix/restaurants/reservations/Statuses.java
c7f7198e7de556208ff8b8fab6d6a2b301a49215
[ "Apache-2.0" ]
permissive
wix-incubator/openrest4j
https://github.com/wix-incubator/openrest4j
c3895f3d0839a2d39c796e44d576cfba901f40bd
28aa74af5acf032bdad427af0887de014399958f
refs/heads/master
2023-03-17T09:32:52.194000
2022-12-08T08:45:09
2022-12-08T08:45:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wix.restaurants.reservations; /** Reservation statuses, from the perspective of either the restaurant or the customer (depending on context). */ public class Statuses { private Statuses() {} /** * Further confirmation is required before the reservation is submitted, e.g. validating the customer's phone * number by SMS. */ public static final String pending = "pending"; /** The reservation has been submitted, and awaits approval. */ public static final String new_ = "new"; /** The reservation has been processed and accepted. */ public static final String accepted = "accepted"; /** The reservation has been canceled. */ public static final String canceled = "canceled"; }
UTF-8
Java
766
java
Statuses.java
Java
[]
null
[]
package com.wix.restaurants.reservations; /** Reservation statuses, from the perspective of either the restaurant or the customer (depending on context). */ public class Statuses { private Statuses() {} /** * Further confirmation is required before the reservation is submitted, e.g. validating the customer's phone * number by SMS. */ public static final String pending = "pending"; /** The reservation has been submitted, and awaits approval. */ public static final String new_ = "new"; /** The reservation has been processed and accepted. */ public static final String accepted = "accepted"; /** The reservation has been canceled. */ public static final String canceled = "canceled"; }
766
0.678851
0.678851
21
34.476189
34.037262
114
false
false
0
0
0
0
0
0
0.380952
false
false
4
1798540bf00a6a59e713113782833eff383987b5
8,100,308,330,959
f71971f5f9803b52376d782c289d13c88f0d3121
/SeaPortFourTryOne/src/seaportfourtryone/Person.java
4913c09371fc74214887da047e37eeff83ee6319
[]
no_license
LukeMarkwordt/SeaPort
https://github.com/LukeMarkwordt/SeaPort
c9697a8708b17b934e609d13a47be4f6875acd15
89c71f3171d86d09644ab4454bafab5153b5930f
refs/heads/master
2020-04-01T11:27:40.986000
2018-10-15T18:46:52
2018-10-15T18:46:52
153,163,187
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package seaportfourtryone; import java.util.*; public class Person extends Thing{ private String skill; private boolean busy = false; private Ship ship = null; public Person(Scanner sc){ super(sc); if(sc.hasNext())skill = sc.next(); } //from project 2 forget for now public void assignPort(HashMap<Integer, Thing> map, Person person){ //upcast map to SeaPort then Person to port try{ SeaPort port = (SeaPort)map.get(person.getParent()); port.setPersons(person); }catch(Exception e){ } } public String getSkill(){ return skill; } public void setSkill(String st){ skill = st; } @Override public String toString(){ String st = super.toString()+" "+skill; return st; } @Override String printName() { return toString(); } /** * getters and setters for busy */ public boolean getBusy(){ return busy; } public void setBusy(boolean b){ busy = b; } /** * getters and setters for ship */ public Ship getShip(){ return ship; } public void setShip(Ship ship){ this.ship = ship; } }
UTF-8
Java
1,223
java
Person.java
Java
[]
null
[]
package seaportfourtryone; import java.util.*; public class Person extends Thing{ private String skill; private boolean busy = false; private Ship ship = null; public Person(Scanner sc){ super(sc); if(sc.hasNext())skill = sc.next(); } //from project 2 forget for now public void assignPort(HashMap<Integer, Thing> map, Person person){ //upcast map to SeaPort then Person to port try{ SeaPort port = (SeaPort)map.get(person.getParent()); port.setPersons(person); }catch(Exception e){ } } public String getSkill(){ return skill; } public void setSkill(String st){ skill = st; } @Override public String toString(){ String st = super.toString()+" "+skill; return st; } @Override String printName() { return toString(); } /** * getters and setters for busy */ public boolean getBusy(){ return busy; } public void setBusy(boolean b){ busy = b; } /** * getters and setters for ship */ public Ship getShip(){ return ship; } public void setShip(Ship ship){ this.ship = ship; } }
1,223
0.573181
0.572363
58
20.086206
15.415268
71
false
false
0
0
0
0
0
0
0.62069
false
false
4
67eed47b5895d009b412503536381ad3e5aa21d5
25,958,782,406,743
fa809eb324402d45b768ea84e34cc2c122e49165
/src/week03/EmptyStringException.java
d5080e623d208b3c5e1f7c48215e3b4a70895599
[]
no_license
WojoInc/SE1021
https://github.com/WojoInc/SE1021
af98db895322586974d66c1f9c9523f46f3061fd
9de2907feeebb311713ce63731e1f2aa6316fdbc
refs/heads/master
2020-12-24T08:29:33.235000
2016-08-24T01:23:57
2016-08-24T01:23:57
32,036,442
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package week03; /** * Created by Owner on 4/8/2015. */ public class EmptyStringException extends Throwable { String message; @Override public String getMessage() { return message; } EmptyStringException(String message){ this.message = message; } }
UTF-8
Java
294
java
EmptyStringException.java
Java
[ { "context": "package week03;\n\n/**\n * Created by Owner on 4/8/2015.\n */\npublic class EmptyStringExceptio", "end": 40, "score": 0.907480776309967, "start": 35, "tag": "NAME", "value": "Owner" } ]
null
[]
package week03; /** * Created by Owner on 4/8/2015. */ public class EmptyStringException extends Throwable { String message; @Override public String getMessage() { return message; } EmptyStringException(String message){ this.message = message; } }
294
0.642857
0.615646
18
15.333333
16.020821
53
false
false
0
0
0
0
0
0
0.222222
false
false
4
f80eb4ba465919b653243c00f7b5dd03b6ae8ef6
10,196,252,413,864
e1aa6b6f2734b84f9a71c666eeb202af36bc1c52
/lib/android/src/main/java/com/airbnb/android/react/lottie/JSONReadableMap.java
deecd63c983973b3ea08766bf93fb410e4728462
[ "Apache-2.0" ]
permissive
arnaud-zg/lottie-react-native
https://github.com/arnaud-zg/lottie-react-native
bcf2a2d61d8a72ac341e8899fa76403f290f3dd2
a84ff9b81a5509f1108850ee62c34396f7a1c35c
refs/heads/master
2019-07-02T08:54:20.366000
2019-06-10T11:32:45
2019-06-10T11:32:45
81,023,050
0
0
Apache-2.0
true
2019-06-10T11:32:47
2017-02-05T21:21:27
2018-12-05T22:12:04
2019-06-10T11:32:46
7,693
0
0
0
Java
false
false
package com.airbnb.android.react.lottie; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * This class is a thin wrapper around React Native's `ReadableMap` and `ReadableArray` classes, * which are what React Native uses to serialize data efficiently across the bridge. * <p> * Many things in android land use `org.json.*` classes, and expect those to get passed around * instead when dealing with JSON (LottieAnimationView is one such example). In an effort to be * efficient, this class simply subclass `JSONObject` and override all of the core methods to * provide a shim around a `ReadableMap`. * <p> * See also: `JSONReadableArray.java` */ class JSONReadableMap extends JSONObject { private final ReadableMap map; JSONReadableMap(ReadableMap map) { this.map = map; } @Override public boolean has(String name) { return map.hasKey(name); } @Override public boolean getBoolean(String name) throws JSONException { try { return map.getBoolean(name); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public int getInt(String name) throws JSONException { try { return map.getInt(name); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public long getLong(String name) throws JSONException { try { try { return (long)map.getInt(name); } catch (RuntimeException e) { return (long)map.getDouble(name); } } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public double getDouble(String name) throws JSONException { try { return map.getDouble(name); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public String getString(String name) throws JSONException { try { return map.getString(name); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public JSONArray getJSONArray(String name) throws JSONException { try { return new JSONReadableArray(map.getArray(name)); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public JSONObject getJSONObject(String name) throws JSONException { try { return new JSONReadableMap(map.getMap(name)); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public Object get(String name) throws JSONException { ReadableType type = map.getType(name); try { switch (type) { case Null: return null; case Boolean: return getBoolean(name); case Number: try { return map.getInt(name); } catch (RuntimeException e) { return map.getDouble(name); } case String: return getString(name); case Map: return getJSONObject(name); case Array: return getJSONArray(name); default: throw new JSONException("Could not convert object with key '" + name + "'."); } } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } }
UTF-8
Java
3,405
java
JSONReadableMap.java
Java
[]
null
[]
package com.airbnb.android.react.lottie; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * This class is a thin wrapper around React Native's `ReadableMap` and `ReadableArray` classes, * which are what React Native uses to serialize data efficiently across the bridge. * <p> * Many things in android land use `org.json.*` classes, and expect those to get passed around * instead when dealing with JSON (LottieAnimationView is one such example). In an effort to be * efficient, this class simply subclass `JSONObject` and override all of the core methods to * provide a shim around a `ReadableMap`. * <p> * See also: `JSONReadableArray.java` */ class JSONReadableMap extends JSONObject { private final ReadableMap map; JSONReadableMap(ReadableMap map) { this.map = map; } @Override public boolean has(String name) { return map.hasKey(name); } @Override public boolean getBoolean(String name) throws JSONException { try { return map.getBoolean(name); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public int getInt(String name) throws JSONException { try { return map.getInt(name); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public long getLong(String name) throws JSONException { try { try { return (long)map.getInt(name); } catch (RuntimeException e) { return (long)map.getDouble(name); } } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public double getDouble(String name) throws JSONException { try { return map.getDouble(name); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public String getString(String name) throws JSONException { try { return map.getString(name); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public JSONArray getJSONArray(String name) throws JSONException { try { return new JSONReadableArray(map.getArray(name)); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public JSONObject getJSONObject(String name) throws JSONException { try { return new JSONReadableMap(map.getMap(name)); } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } @Override public Object get(String name) throws JSONException { ReadableType type = map.getType(name); try { switch (type) { case Null: return null; case Boolean: return getBoolean(name); case Number: try { return map.getInt(name); } catch (RuntimeException e) { return map.getDouble(name); } case String: return getString(name); case Map: return getJSONObject(name); case Array: return getJSONArray(name); default: throw new JSONException("Could not convert object with key '" + name + "'."); } } catch (RuntimeException e) { throw new JSONException(e.getMessage()); } } }
3,405
0.656388
0.656388
119
27.613445
25.140316
96
false
false
0
0
0
0
0
0
0.310924
false
false
4
9b79067af6cfeeb6b29d3ac9b19df2c0e680d857
28,690,381,552,013
3b8d2344e02fcaee6869f42642a1c5f7089602cc
/src/main/java/com/mahdix/activeQueue/model/ThreadMessage.java
b1eccbe4c2180ae464b18e04fced566f7d08e4d3
[]
no_license
mahdix/activeQueue
https://github.com/mahdix/activeQueue
71d99dc8f81c3575e92515cb4ad87fc5f074c7bb
6517737d5b9d1f49c85a49d9ccc170aee3bee528
refs/heads/main
2023-04-29T03:48:48.603000
2021-05-19T19:55:20
2021-05-19T19:55:20
364,077,756
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mahdix.activeQueue.model; import com.mahdix.activeQueue.enums.ThreadMessageType; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.Optional; @SuppressWarnings("unused") @Getter @AllArgsConstructor(access = AccessLevel.PROTECTED) public class ThreadMessage<T> { private final Optional<T> data; private final ThreadMessageType messageType; public static <U> ThreadMessage<U> ofRequestTerminate() { return new ThreadMessage<>(Optional.empty(), ThreadMessageType.REQUEST_TERMINATE); } public static <U> ThreadMessage<U> ofRequestStart() { return new ThreadMessage<>(Optional.empty(), ThreadMessageType.REQUEST_START); } public static <U> ThreadMessage<U> ofData(U data) { return new ThreadMessage<>(Optional.of(data), ThreadMessageType.DATA); } }
UTF-8
Java
867
java
ThreadMessage.java
Java
[]
null
[]
package com.mahdix.activeQueue.model; import com.mahdix.activeQueue.enums.ThreadMessageType; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.Optional; @SuppressWarnings("unused") @Getter @AllArgsConstructor(access = AccessLevel.PROTECTED) public class ThreadMessage<T> { private final Optional<T> data; private final ThreadMessageType messageType; public static <U> ThreadMessage<U> ofRequestTerminate() { return new ThreadMessage<>(Optional.empty(), ThreadMessageType.REQUEST_TERMINATE); } public static <U> ThreadMessage<U> ofRequestStart() { return new ThreadMessage<>(Optional.empty(), ThreadMessageType.REQUEST_START); } public static <U> ThreadMessage<U> ofData(U data) { return new ThreadMessage<>(Optional.of(data), ThreadMessageType.DATA); } }
867
0.747405
0.747405
28
29.964285
27.740484
90
false
false
0
0
0
0
0
0
0.5
false
false
4