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
f7a580d1ef4c0b36f6129c3870767385d5d1672c
3,444,563,778,113
fae9546b1206e927e6fc90e797e051cd7649202e
/第09天内部类、异常/neibulei.java
ca9587306b3e6d670d58efb362e893e69eef8e7c
[]
no_license
MenmoEugene/cove
https://github.com/MenmoEugene/cove
858deb3d3f45c3001d5825998654ca31122a5a53
ce261077b4ff01044ee687e3893e8ae7ca6da361
refs/heads/master
2020-03-07T17:25:05.207000
2018-04-01T08:22:03
2018-04-01T08:22:03
127,610,602
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* 内部类的访问规则: 1,内部类可以直接访问外部类中的成员,包括私有。 之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式:外部类名.this 2,外部类要访问内部类,必须建立内部类对象。 访问格式: 1, 当内部类定义在外部类的成员的成员位置上,而且非私有,可以在外部其他类中。 可以直接建立内部类对象。 格式 外部类名.内部类名 变量名 = 外部类对象.内部类对象; Outer.Inner in = new Outer().new Inner(); 2, 当内部类在成员位置上,就可以别成员修饰符所修饰。 比如,private:将内部类在外部类中进行封装。 static:内部类就具备static的特性。 当内部类被static修饰后,只能直接访问外部类中的static成员。出现了访问局限。 在外部其他类中,如何直接访问static内部类的非静态成员呢? new Outer.Inner().function(); 在外部其他类中,如何直接访问static内部类的静态成员呢? Outer.Inner.function(); 注意:当内部类中定义了静态成员,该内部类必须是static的。 当外部类中的静态方法访问内部类时,内部类也必须是static的。 当描述事物时,事物的内部还有事物,该事物用内部类来描述。 因为内部事务在使用外部事物的内容。 局部内部类不能定义静态成员 内部类定义在局部时 1,不可以被成员修饰符修饰 2,可以直接访问外部类中的成员,因为还持有外部类中的引用。 但是不可以访问它所在的局部中的变量,只能访问被final修饰的局部变量。 */ class Outer { private int x = 3; class Inner//内部类 { int x = 4; void function() { int x = 6; System.out.println("inner:"+Outer.this.x); System.out.println("inner:"+this.x); System.out.println("inner:"+x); } } void method() { Inner in = new Inner(); in.function(); } } class neibulei { public static void main(String[] args) { //Outer out = new Outer(); //out.method(); //直接访问内部类的成员 (用于面试) Outer.Inner in = new Outer().new Inner(); in.function(); } }
GB18030
Java
2,258
java
neibulei.java
Java
[]
null
[]
/* 内部类的访问规则: 1,内部类可以直接访问外部类中的成员,包括私有。 之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式:外部类名.this 2,外部类要访问内部类,必须建立内部类对象。 访问格式: 1, 当内部类定义在外部类的成员的成员位置上,而且非私有,可以在外部其他类中。 可以直接建立内部类对象。 格式 外部类名.内部类名 变量名 = 外部类对象.内部类对象; Outer.Inner in = new Outer().new Inner(); 2, 当内部类在成员位置上,就可以别成员修饰符所修饰。 比如,private:将内部类在外部类中进行封装。 static:内部类就具备static的特性。 当内部类被static修饰后,只能直接访问外部类中的static成员。出现了访问局限。 在外部其他类中,如何直接访问static内部类的非静态成员呢? new Outer.Inner().function(); 在外部其他类中,如何直接访问static内部类的静态成员呢? Outer.Inner.function(); 注意:当内部类中定义了静态成员,该内部类必须是static的。 当外部类中的静态方法访问内部类时,内部类也必须是static的。 当描述事物时,事物的内部还有事物,该事物用内部类来描述。 因为内部事务在使用外部事物的内容。 局部内部类不能定义静态成员 内部类定义在局部时 1,不可以被成员修饰符修饰 2,可以直接访问外部类中的成员,因为还持有外部类中的引用。 但是不可以访问它所在的局部中的变量,只能访问被final修饰的局部变量。 */ class Outer { private int x = 3; class Inner//内部类 { int x = 4; void function() { int x = 6; System.out.println("inner:"+Outer.this.x); System.out.println("inner:"+this.x); System.out.println("inner:"+x); } } void method() { Inner in = new Inner(); in.function(); } } class neibulei { public static void main(String[] args) { //Outer out = new Outer(); //out.method(); //直接访问内部类的成员 (用于面试) Outer.Inner in = new Outer().new Inner(); in.function(); } }
2,258
0.712662
0.705357
69
16.855072
14.657713
49
false
false
0
0
0
0
0
0
1.26087
false
false
7
9787fac790dd15409562d3ff14ec5227d07cf2a2
10,428,180,647,861
80ca24337cc4501491fa944bbb98a3affc7b4cf2
/src/DynamicProgramming/RepeatingSubSequence.java
66f31ace896a8e245580483129359dcc28f27820
[]
no_license
RajeshAatrayan/InterviewPreparation
https://github.com/RajeshAatrayan/InterviewPreparation
235661cb77c5d9002d0c0609f7840104882b776d
f93eebc44a0cf6094411c05c7989561b53da42bb
refs/heads/master
2023-03-03T20:37:14.247000
2023-02-28T19:55:53
2023-02-28T19:55:53
197,302,550
3
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package DynamicProgramming; /** * Created by RajeshAatrayan|InterviewPreparation|DynamicProgramming|RepeatingSubSequence| on Sep,2020 *   * Happy Coding :) **/ public class RepeatingSubSequence { public int anytwo(String a) { String b = a; int dp[][] = new int[a.length() + 1][b.length() + 1]; int m = dp.length; int n = dp[0].length; for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (a.charAt(i - 1) == b.charAt(j - 1) && i != j) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[m - 1][n - 1] >= 2 ? 1 : 0; } }
UTF-8
Java
772
java
RepeatingSubSequence.java
Java
[ { "context": "package DynamicProgramming;\n\n/**\n * Created by RajeshAatrayan|InterviewPreparation|DynamicProgramming|Repeating", "end": 61, "score": 0.9998893737792969, "start": 47, "tag": "NAME", "value": "RajeshAatrayan" } ]
null
[]
package DynamicProgramming; /** * Created by RajeshAatrayan|InterviewPreparation|DynamicProgramming|RepeatingSubSequence| on Sep,2020 *   * Happy Coding :) **/ public class RepeatingSubSequence { public int anytwo(String a) { String b = a; int dp[][] = new int[a.length() + 1][b.length() + 1]; int m = dp.length; int n = dp[0].length; for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (a.charAt(i - 1) == b.charAt(j - 1) && i != j) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[m - 1][n - 1] >= 2 ? 1 : 0; } }
772
0.433204
0.405966
29
25.586206
25.283928
102
false
false
0
0
0
0
0
0
0.62069
false
false
7
965f76e1839c2d7317ab00b9fb1236e1b002f70c
26,121,991,097,311
7ab26d4bc788b5d437cb69992ea94b56a4899b6c
/jPSICS/src/org/catacomb/druid/blocks/PrintEffect.java
358dc891a9d728e19515db8f6b06a6a165e810cd
[]
no_license
MattNolanLab/PSICS
https://github.com/MattNolanLab/PSICS
d8e777d9a18e332231de244c23431b34c655cfa5
68b4f17e9aef2e6c7ca3c23da2a175eeaeb7251f
refs/heads/master
2021-05-27T02:01:24.747000
2014-05-13T16:19:21
2014-05-13T16:19:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.catacomb.druid.blocks; import org.catacomb.druid.build.Context; import org.catacomb.druid.build.GUIPath; import org.catacomb.druid.gui.base.DruPrintEffect; import org.catacomb.druid.gui.edit.Effect; public class PrintEffect extends BaseEffect { public String text; public Effect realize(Context ctx, GUIPath gpath) { return new DruPrintEffect(text); } }
UTF-8
Java
397
java
PrintEffect.java
Java
[]
null
[]
package org.catacomb.druid.blocks; import org.catacomb.druid.build.Context; import org.catacomb.druid.build.GUIPath; import org.catacomb.druid.gui.base.DruPrintEffect; import org.catacomb.druid.gui.edit.Effect; public class PrintEffect extends BaseEffect { public String text; public Effect realize(Context ctx, GUIPath gpath) { return new DruPrintEffect(text); } }
397
0.75063
0.75063
23
16.26087
20.253218
54
false
false
0
0
0
0
0
0
0.347826
false
false
7
910e438a6992f91e66c94416bad85c864fe7d11f
10,960,756,605,360
d974ba215c5da6a1c7b52da1a55856352f5c6beb
/GroupProject/JobCompare6300/app/src/main/java/edu/gatech/seclass/jobcompare6300/model/JobCompareContract.java
a9d171dc5034b30b960fd4a67559918b0375d88f
[]
no_license
lillianzhang331/JobComparison
https://github.com/lillianzhang331/JobComparison
e16a9d5dcf82e2a430922f173796a988b6918cc4
754ffaf79326476260e097e1547cdbec39c73317
refs/heads/master
2023-06-19T02:30:47.629000
2020-10-19T06:28:27
2020-10-19T06:28:27
387,565,051
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.gatech.seclass.jobcompare6300.model; import android.provider.BaseColumns; public final class JobCompareContract { private JobCompareContract(){} public static class CurrentJob implements BaseColumns { public static final String TABLE_NAME = "currentjob"; public static final String COLUMN_NAME_TITLE = "title"; public static final String COLUMN_NAME_COMPANY = "company"; public static final String COLUMN_NAME_CITY = "city"; public static final String COLUMN_NAME_STATE = "state"; public static final String COLUMN_NAME_COSTOFLIVING = "costofliving"; public static final String COLUMN_NAME_COMMUTE = "commute"; public static final String COLUMN_NAME_SALARY = "salary"; public static final String COLUMN_NAME_BONUS = "bonus"; public static final String COLUMN_NAME_RETIREMENTBENEFITS = "retirementbenefits"; public static final String COLUMN_NAME_LEAVETIME = "leavetime"; public static final String COLUMN_NAME_JOBSCORE = "jobscore"; } public static class JobOffer implements BaseColumns { public static final String TABLE_NAME = "joboffer"; public static final String COLUMN_NAME_TITLE = "title"; public static final String COLUMN_NAME_COMPANY = "company"; public static final String COLUMN_NAME_CITY = "city"; public static final String COLUMN_NAME_STATE = "state"; public static final String COLUMN_NAME_COSTOFLIVING = "costofliving"; public static final String COLUMN_NAME_COMMUTE = "commute"; public static final String COLUMN_NAME_SALARY = "salary"; public static final String COLUMN_NAME_BONUS = "bonus"; public static final String COLUMN_NAME_RETIREMENTBENEFITS = "retirementbenefits"; public static final String COLUMN_NAME_LEAVETIME = "leavetime"; public static final String COLUMN_NAME_JOBSCORE = "jobscore"; } public static class ComparisonSettings implements BaseColumns { public static final String TABLE_NAME = "comparisonsettings"; public static final String COLUMN_NAME_COMMUTEWT = "commuteweight"; public static final String COLUMN_NAME_SALARYWT = "salaryweight"; public static final String COLUMN_NAME_BONUSWT = "bonusweight"; public static final String COLUMN_NAME_RETIREMENTWT = "retirementweight"; public static final String COLUMN_NAME_LEAVEWT = "leaveweight"; } }
UTF-8
Java
2,470
java
JobCompareContract.java
Java
[]
null
[]
package edu.gatech.seclass.jobcompare6300.model; import android.provider.BaseColumns; public final class JobCompareContract { private JobCompareContract(){} public static class CurrentJob implements BaseColumns { public static final String TABLE_NAME = "currentjob"; public static final String COLUMN_NAME_TITLE = "title"; public static final String COLUMN_NAME_COMPANY = "company"; public static final String COLUMN_NAME_CITY = "city"; public static final String COLUMN_NAME_STATE = "state"; public static final String COLUMN_NAME_COSTOFLIVING = "costofliving"; public static final String COLUMN_NAME_COMMUTE = "commute"; public static final String COLUMN_NAME_SALARY = "salary"; public static final String COLUMN_NAME_BONUS = "bonus"; public static final String COLUMN_NAME_RETIREMENTBENEFITS = "retirementbenefits"; public static final String COLUMN_NAME_LEAVETIME = "leavetime"; public static final String COLUMN_NAME_JOBSCORE = "jobscore"; } public static class JobOffer implements BaseColumns { public static final String TABLE_NAME = "joboffer"; public static final String COLUMN_NAME_TITLE = "title"; public static final String COLUMN_NAME_COMPANY = "company"; public static final String COLUMN_NAME_CITY = "city"; public static final String COLUMN_NAME_STATE = "state"; public static final String COLUMN_NAME_COSTOFLIVING = "costofliving"; public static final String COLUMN_NAME_COMMUTE = "commute"; public static final String COLUMN_NAME_SALARY = "salary"; public static final String COLUMN_NAME_BONUS = "bonus"; public static final String COLUMN_NAME_RETIREMENTBENEFITS = "retirementbenefits"; public static final String COLUMN_NAME_LEAVETIME = "leavetime"; public static final String COLUMN_NAME_JOBSCORE = "jobscore"; } public static class ComparisonSettings implements BaseColumns { public static final String TABLE_NAME = "comparisonsettings"; public static final String COLUMN_NAME_COMMUTEWT = "commuteweight"; public static final String COLUMN_NAME_SALARYWT = "salaryweight"; public static final String COLUMN_NAME_BONUSWT = "bonusweight"; public static final String COLUMN_NAME_RETIREMENTWT = "retirementweight"; public static final String COLUMN_NAME_LEAVEWT = "leaveweight"; } }
2,470
0.710931
0.709312
44
55.136364
25.377684
89
false
false
0
0
0
0
0
0
0.727273
false
false
7
d72dc4f9e763be2e27a2b866446c80af81182c67
2,456,721,301,078
c05a99d659bf172692faad2e6da6076bf5f4a7d2
/src/main/java/com/boxuegu/mapper/ExercisesMapper.java
b369b1a76fb3a1c04b53195f11db37e05f8635b4
[]
no_license
onellx/boxueguweb
https://github.com/onellx/boxueguweb
4492a194c1bb4a0d5c4c09f9bfd5eb9c5db73ca3
6c41ddaf9232472a58fef77bc383eb09f78ebccf
refs/heads/master
2020-04-07T15:37:47.459000
2018-11-21T05:09:03
2018-11-21T05:09:03
158,493,789
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.boxuegu.mapper; import com.boxuegu.pojo.Exercises; import com.boxuegu.pojo.ExercisesExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface ExercisesMapper { long countByExample(ExercisesExample example); int deleteByExample(ExercisesExample example); int deleteByPrimaryKey(Integer id); int insert(Exercises record); int insertSelective(Exercises record); List<Exercises> selectByExample(ExercisesExample example); Exercises selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") Exercises record, @Param("example") ExercisesExample example); int updateByExample(@Param("record") Exercises record, @Param("example") ExercisesExample example); int updateByPrimaryKeySelective(Exercises record); int updateByPrimaryKey(Exercises record); }
UTF-8
Java
866
java
ExercisesMapper.java
Java
[]
null
[]
package com.boxuegu.mapper; import com.boxuegu.pojo.Exercises; import com.boxuegu.pojo.ExercisesExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface ExercisesMapper { long countByExample(ExercisesExample example); int deleteByExample(ExercisesExample example); int deleteByPrimaryKey(Integer id); int insert(Exercises record); int insertSelective(Exercises record); List<Exercises> selectByExample(ExercisesExample example); Exercises selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") Exercises record, @Param("example") ExercisesExample example); int updateByExample(@Param("record") Exercises record, @Param("example") ExercisesExample example); int updateByPrimaryKeySelective(Exercises record); int updateByPrimaryKey(Exercises record); }
866
0.781755
0.781755
30
27.9
30.022602
112
false
false
0
0
0
0
0
0
0.6
false
false
7
067c1fadaaa8fbfa2619e1f48f0ee60d7fce2005
2,456,721,297,343
b07d23954c35e7a73837a770f93ca90d0c2f3af9
/src/com/anxpp/designpattern/bridge/ISaveData.java
7b0e2718504413a053a6d603e7f5d2ede6cdc000
[]
no_license
dsczs/JavaDesignPattern
https://github.com/dsczs/JavaDesignPattern
a991ddf1b81a8fa3c96c9f78276567a0312a1603
39d2f9834f77e4eaa66d05a9af73538b25a6ca4e
refs/heads/master
2022-11-06T15:20:50.984000
2020-06-28T09:59:32
2020-06-28T09:59:32
275,555,952
0
0
null
true
2020-06-28T09:57:15
2020-06-28T09:57:14
2020-06-23T12:08:06
2016-11-22T16:59:32
57
0
0
0
null
false
false
package com.anxpp.designpattern.bridge; //实现 public interface ISaveData { void save(Object data); }
UTF-8
Java
109
java
ISaveData.java
Java
[]
null
[]
package com.anxpp.designpattern.bridge; //实现 public interface ISaveData { void save(Object data); }
109
0.742857
0.742857
6
16.5
15.370426
39
false
false
0
0
0
0
0
0
0.333333
false
false
7
b1e9b04ea6cbe05b828ead07aa92824d1bbdc621
2,353,642,121,251
37237ad6bc00d590b8002b0c72f18e1d744279d9
/BOJ_Judge_algorithm/src/BFS/Practice/MovingThroughWalls_BFS.java
14835bf9d04c98c120f72c7fcdbf7519a30b3062
[]
no_license
shy-nxx/Algorithms_practice
https://github.com/shy-nxx/Algorithms_practice
fa245bdfd1a38572f8df5d9ab21e9fc55322177d
6dbd7ebad95974caad4c972770436eb6c08b10a8
refs/heads/master
2020-04-18T13:20:15.448000
2019-05-20T08:30:44
2019-05-20T08:30:44
167,559,384
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package BFS.Practice; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class MovingThroughWalls_BFS { /** * 벽을 부쉈는지 안부수었는지 확인하기 위해 visited 배열을 3차원 배열로 선언한다. * <p> * 좌표를 저장하는 클래스에 해당 좌표에 벽이 부수어져있는지 확이하는 변수를 선언한다. * <p> * 큐가 빌때까지 큐의 사이즈만큼 반복하면서 최단거리를 구한다. */ static int M , N; static int[][] map; static boolean[][][] visited; static final int YES = 1; static final int NO = 0; static int result = 0; static int[] dx = {-1,1,0,0}; static int[] dy = {0,0,-1,1}; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); map = new int[N][M]; visited = new boolean[N][M][2]; for (int i = 0; i < N; i++) { String s = br.readLine(); for (int j = 0; j < M; j++) { map[i][j] = s.charAt(j) - 48; } } if (bfs(0,0)) { System.out.println(result); return; } else { System.out.println(-1); return; } } static boolean bfs(int x, int y) { Queue<Pos> q = new LinkedList<>(); q.add(new Pos(x, y, NO)); //처음은 무조건 벽이 아님 visited[x][y][YES] = true; visited[x][y][NO] = true; int temp = 0; while(!q.isEmpty()) { ++temp; int n = q.size(); for (int i = 0; i < n; i++) { Pos p = q.poll(); int cx = p.x; int cy = p.y; if (p.x == N-1 && p.y == M-1) { result = temp; return true; } for (int j = 0; j < 4; j++) { int nx = cx + dx[j]; int ny = cy + dy[j]; if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue; if (map[nx][ny] == 1) { //벽이면 일단 벽을 부순게 있는지 확인한다. if (!visited[nx][ny][YES] && p.brokenWall < YES) { q.add(new Pos(nx, ny, YES)); visited[nx][ny][YES] = true; } } else { if (!visited[nx][ny][p.brokenWall]) { q.add(new Pos(nx, ny, p.brokenWall)); visited[nx][ny][p.brokenWall] = true; } } } } } return false; } static class Pos { int x, y; int brokenWall; public Pos(int x, int y, int brokenWall) { this.x = x; this.y = y; this.brokenWall = brokenWall; } } }
UTF-8
Java
3,345
java
MovingThroughWalls_BFS.java
Java
[]
null
[]
package BFS.Practice; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class MovingThroughWalls_BFS { /** * 벽을 부쉈는지 안부수었는지 확인하기 위해 visited 배열을 3차원 배열로 선언한다. * <p> * 좌표를 저장하는 클래스에 해당 좌표에 벽이 부수어져있는지 확이하는 변수를 선언한다. * <p> * 큐가 빌때까지 큐의 사이즈만큼 반복하면서 최단거리를 구한다. */ static int M , N; static int[][] map; static boolean[][][] visited; static final int YES = 1; static final int NO = 0; static int result = 0; static int[] dx = {-1,1,0,0}; static int[] dy = {0,0,-1,1}; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); map = new int[N][M]; visited = new boolean[N][M][2]; for (int i = 0; i < N; i++) { String s = br.readLine(); for (int j = 0; j < M; j++) { map[i][j] = s.charAt(j) - 48; } } if (bfs(0,0)) { System.out.println(result); return; } else { System.out.println(-1); return; } } static boolean bfs(int x, int y) { Queue<Pos> q = new LinkedList<>(); q.add(new Pos(x, y, NO)); //처음은 무조건 벽이 아님 visited[x][y][YES] = true; visited[x][y][NO] = true; int temp = 0; while(!q.isEmpty()) { ++temp; int n = q.size(); for (int i = 0; i < n; i++) { Pos p = q.poll(); int cx = p.x; int cy = p.y; if (p.x == N-1 && p.y == M-1) { result = temp; return true; } for (int j = 0; j < 4; j++) { int nx = cx + dx[j]; int ny = cy + dy[j]; if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue; if (map[nx][ny] == 1) { //벽이면 일단 벽을 부순게 있는지 확인한다. if (!visited[nx][ny][YES] && p.brokenWall < YES) { q.add(new Pos(nx, ny, YES)); visited[nx][ny][YES] = true; } } else { if (!visited[nx][ny][p.brokenWall]) { q.add(new Pos(nx, ny, p.brokenWall)); visited[nx][ny][p.brokenWall] = true; } } } } } return false; } static class Pos { int x, y; int brokenWall; public Pos(int x, int y, int brokenWall) { this.x = x; this.y = y; this.brokenWall = brokenWall; } } }
3,345
0.422272
0.412939
121
24.677687
19.799915
81
false
false
0
0
0
0
0
0
0.694215
false
false
7
ec80ca210a9ec34bfd5fcdb14ff785f7174f9f8b
7,894,149,902,283
a523119428a8d3db5c3154f5dbd7dcdc2e1b29fe
/src/main/java/com/design/pattern/factory/concreteCreator/NYPizzaStore.java
80a4c6c7b61965d1212f51b424fbadb547f5659c
[]
no_license
qihouying/design-pattern
https://github.com/qihouying/design-pattern
7811c1b223ad8ca62c8d987bce51be921867ed22
cd4feb81f89bdebedc705d4930e544a6bc4d3ec2
refs/heads/master
2021-01-22T05:27:58.783000
2017-04-17T13:36:42
2017-04-17T13:36:42
81,663,293
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.design.pattern.factory.concreteCreator; import com.design.pattern.factory.ConcreteProduct.NYStyleCheesePizza; import com.design.pattern.factory.ConcreteProduct.NYStyleVeggiePizza; import com.design.pattern.factory.Pizza; import com.design.pattern.factory.PizzaStore; /** * Created by dream on 08/04/2017. */ public class NYPizzaStore extends PizzaStore { public Pizza createPizza(String type) { if (type.equals("cheese")) { return new NYStyleCheesePizza(); } else if (type.equals("veggie")) { return new NYStyleVeggiePizza(); } return null; } }
UTF-8
Java
625
java
NYPizzaStore.java
Java
[ { "context": "ign.pattern.factory.PizzaStore;\n\n/**\n * Created by dream on 08/04/2017.\n */\npublic class NYPizzaStore exte", "end": 304, "score": 0.9519392251968384, "start": 299, "tag": "USERNAME", "value": "dream" } ]
null
[]
package com.design.pattern.factory.concreteCreator; import com.design.pattern.factory.ConcreteProduct.NYStyleCheesePizza; import com.design.pattern.factory.ConcreteProduct.NYStyleVeggiePizza; import com.design.pattern.factory.Pizza; import com.design.pattern.factory.PizzaStore; /** * Created by dream on 08/04/2017. */ public class NYPizzaStore extends PizzaStore { public Pizza createPizza(String type) { if (type.equals("cheese")) { return new NYStyleCheesePizza(); } else if (type.equals("veggie")) { return new NYStyleVeggiePizza(); } return null; } }
625
0.7072
0.6944
20
30.25
22.483049
69
false
false
0
0
0
0
0
0
0.4
false
false
7
9cb3dceb3d72f9c19ba63d1e1223e310f94fc47d
23,716,809,471,887
2a0b5df31c675070761dca0d3d719733fc2ea187
/java/oreilly/designpatterns/src/main/java/com/designpatterns/chp4/ChicagoStyleClamPizza.java
24939946820929175405c18df84f777733e261c0
[]
no_license
oussamad-blip/bookcode-compile-lang
https://github.com/oussamad-blip/bookcode-compile-lang
55ff480d50f6101fd727bbfedb60587cb9930b60
87a959cf821624765df34eff506faf28ae429b4c
refs/heads/master
2023-05-05T00:05:49.387000
2019-02-17T10:08:17
2019-02-17T10:08:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.designpatterns.chp4; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChicagoStyleClamPizza extends Pizza { private static final Logger logger = LoggerFactory.getLogger(ChicagoStyleClamPizza.class); @Override public void prepare() { logger.info("Preparing Chicago clam Pizza"); } @Override public void bake() { logger.info("Baking Chicago clam Pizza"); } @Override public void cut() { logger.info("Chicago Clam Pizza sliced and diced"); } @Override public void box() { logger.info("Chicago Clam Pizza boxed and ready for pick-up/delivery"); } }
UTF-8
Java
670
java
ChicagoStyleClamPizza.java
Java
[]
null
[]
package com.designpatterns.chp4; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChicagoStyleClamPizza extends Pizza { private static final Logger logger = LoggerFactory.getLogger(ChicagoStyleClamPizza.class); @Override public void prepare() { logger.info("Preparing Chicago clam Pizza"); } @Override public void bake() { logger.info("Baking Chicago clam Pizza"); } @Override public void cut() { logger.info("Chicago Clam Pizza sliced and diced"); } @Override public void box() { logger.info("Chicago Clam Pizza boxed and ready for pick-up/delivery"); } }
670
0.670149
0.665672
30
21.333334
24.637821
94
false
false
0
0
0
0
0
0
0.266667
false
false
7
0fe4fc67c273426f0f1cae0c11c3c83913b33908
6,055,903,918,575
6ffa11531ebb2f9b7090e2a414e8ad54c8cd5624
/jsp+servlet/CH06-分页和上传/CH06_PageAndUpload/src/com/whcs/servlet/UploadServlet.java
e9b02d34f1a0c06df59d1839daf12ca018681b50
[]
no_license
chenshengtyd/myGitHub
https://github.com/chenshengtyd/myGitHub
9d826e9c10b5a2fcb746dc0b65f7d1c01dd46985
a1e28ae75013d763cb1d052170156652342a7280
refs/heads/master
2022-12-22T02:27:18.433000
2021-09-16T15:48:01
2021-09-16T15:48:01
140,400,190
2
1
null
false
2022-12-16T11:40:26
2018-07-10T08:18:08
2021-09-16T15:48:11
2022-12-16T11:40:26
234,065
1
0
25
Java
false
false
package com.whcs.servlet; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @WebServlet("/UploadServlet") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UploadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // request.setCharacterEncoding("utf-8"):设置request的编码格式 response.setCharacterEncoding("UTF-8"); String uploadFileName = ""; // 上传的文件名 String fieldName = ""; // 表单字段元素的name属性值 // 请求信息中的内容是否是multipart类型,判断上传的表单是不是multipart类型 boolean isMultipart = ServletFileUpload.isMultipartContent(request); // 上传文件的存储路径(服务器文件系统上的绝对文件路径) // String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/"); String uploadFilePath = "D:\\works\\"; System.out.println("uploadFilePath=" + uploadFilePath); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { // 解析form表单中所有文件 List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { // 依次处理每个文件 // <input type="text" name="user"> // <input type="file" name="nfile"> FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // 普通表单字段 text password checkbox fieldName = item.getFieldName(); // 表单字段的name属性值=user if (fieldName.equals("user")) { // 输出表单字段的值 response.getWriter().append(item.getString("UTF-8") + "上传了文件。<br/>"); } } else { // 文件表单字段 file String fileName = item.getName();// item.getName():获取上传文件名称:杰森史坦森.jpg if (fileName != null && !fileName.equals("")) { File fullFile = new File(item.getName()); String fileFullName = fullFile.getName(); File saveFile = new File(uploadFilePath, fileFullName); item.write(saveFile);//文件复制,上传文件了 response.getWriter().append("上传成功后的文件名是:" + fileFullName); } } } } catch (Exception e) { e.printStackTrace(); } } else { response.getWriter().append("Form表单的类型不正确"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
UTF-8
Java
3,173
java
UploadServlet.java
Java
[]
null
[]
package com.whcs.servlet; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @WebServlet("/UploadServlet") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UploadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // request.setCharacterEncoding("utf-8"):设置request的编码格式 response.setCharacterEncoding("UTF-8"); String uploadFileName = ""; // 上传的文件名 String fieldName = ""; // 表单字段元素的name属性值 // 请求信息中的内容是否是multipart类型,判断上传的表单是不是multipart类型 boolean isMultipart = ServletFileUpload.isMultipartContent(request); // 上传文件的存储路径(服务器文件系统上的绝对文件路径) // String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/"); String uploadFilePath = "D:\\works\\"; System.out.println("uploadFilePath=" + uploadFilePath); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { // 解析form表单中所有文件 List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { // 依次处理每个文件 // <input type="text" name="user"> // <input type="file" name="nfile"> FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // 普通表单字段 text password checkbox fieldName = item.getFieldName(); // 表单字段的name属性值=user if (fieldName.equals("user")) { // 输出表单字段的值 response.getWriter().append(item.getString("UTF-8") + "上传了文件。<br/>"); } } else { // 文件表单字段 file String fileName = item.getName();// item.getName():获取上传文件名称:杰森史坦森.jpg if (fileName != null && !fileName.equals("")) { File fullFile = new File(item.getName()); String fileFullName = fullFile.getName(); File saveFile = new File(uploadFilePath, fileFullName); item.write(saveFile);//文件复制,上传文件了 response.getWriter().append("上传成功后的文件名是:" + fileFullName); } } } } catch (Exception e) { e.printStackTrace(); } } else { response.getWriter().append("Form表单的类型不正确"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
3,173
0.717659
0.71625
83
33.180721
23.986012
92
false
false
0
0
0
0
0
0
3.024096
false
false
7
3319b2560c648c438c069e03dcfb61f6af76f53b
11,312,943,900,675
2df6a5532ffa719155ff1f9f489c7000617fb0ab
/mybatis-mapper/src/main/java/com/pan/controller/UserController.java
397371d8ecc02597fe8eb96fccf48e9cfa147c61
[]
no_license
panzhimin1325/spring-workspace
https://github.com/panzhimin1325/spring-workspace
ca1bb8b6355c6f6e8b6666c1c239046e94e02a07
a2c88018fc9c36bdc3cf20187315af5fef07268d
refs/heads/master
2020-04-18T01:57:01.561000
2019-08-23T09:14:56
2019-08-23T09:14:56
167,140,850
0
0
null
false
2020-10-13T22:07:46
2019-01-23T07:50:19
2019-08-23T09:15:58
2020-10-13T22:07:44
1,831
0
0
23
CSS
false
false
package com.pan.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.pan.entity.User; import com.pan.mapper.UserMapper; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserMapper userMapper; @RequestMapping("/info") @ResponseBody public String hello(){ User user = userMapper.getUserById("5ef8541a-f907-11e8-bf90-507b9d442813"); return user.toString(); } }
UTF-8
Java
619
java
UserController.java
Java
[]
null
[]
package com.pan.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.pan.entity.User; import com.pan.mapper.UserMapper; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserMapper userMapper; @RequestMapping("/info") @ResponseBody public String hello(){ User user = userMapper.getUserById("5ef8541a-f907-11e8-bf90-507b9d442813"); return user.toString(); } }
619
0.799677
0.76252
24
24.791666
22.379267
77
false
false
0
0
0
0
0
0
0.916667
false
false
7
0cb38d510aecbad0d9ca2fdec005e52d8e12f611
25,924,422,647,542
0545b653543d2518964024ed9dd05512219b1e07
/hcg/src/main/java/com/deco2800/hcg/quests/QuestReader.java
36855648012567911a3a4423d8c6dc32628563fd
[]
no_license
hobrien17/deco2800-hcg-copy
https://github.com/hobrien17/deco2800-hcg-copy
0b48a5c40960ca21850c245eaabd2c633939cd61
f5a32a1b25ce81f8e60dbb35c5667845263b6638
refs/heads/master
2021-04-06T02:13:58.428000
2017-10-22T19:25:08
2017-10-22T19:25:08
124,708,884
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.deco2800.hcg.quests; import com.deco2800.hcg.entities.enemyentities.EnemyType; import com.deco2800.hcg.items.Item; import com.deco2800.hcg.managers.ResourceLoadException; import com.deco2800.hcg.managers.ItemManager; import com.deco2800.hcg.managers.GameManager; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.*; /** * Quest reader handles quest loading from files * * @author Harry Guthrie */ public class QuestReader { static ArrayList<Integer> validEnemyID = new ArrayList<>(Arrays.asList(1,2,3,4)); /** * A function which loads all the quests into the quest manager, this utalizes the loadQuest function, and it then * adds all the files in the folder to the hash map of quests titles to quests. */ public Map<String,Quest> loadAllQuests() { HashMap<String,Quest> quests = new HashMap<>(); String questsFolder = "resources/quests/"; final File jQuestFile = new File(questsFolder); Quest q; for (String fp: jQuestFile.list()) { try { q = loadQuest(questsFolder + fp); if (quests.containsKey(q.getTitle())) { throw new ResourceLoadException("Quest title is a duplicate (" + q.getTitle() + ") in file (" + fp +")"); } quests.put(q.getTitle(),q); } catch (JsonSyntaxException | ResourceLoadException e) { throw new ResourceLoadException("Failure during quest file load: " + fp, e); } } return quests; } /** * Loads a particular quest and returns the Quest object, or it throws and informative error as to why the file * being passed into the function is wrong. * * @param fp * @return * @throws IOException */ public Quest loadQuest(String fp) { //Make sure the file is a json file if (!fp.substring(fp.length() - ".json".length(),fp.length()).equals(".json")) { throw new ResourceLoadException("All files in the quest resources files must be .json files"); } //Containers for the information in the quest String title; //Name of the quest to be displayed HashMap<String,Integer> rewards; // items to amount for reward EnumMap<EnemyType, Integer> killRequirement; //Kills for enemy ID required HashMap<String, Integer> itemRequirement; //Item required to complete quest String description; //Get the inital json obj JsonObject jQuest; BufferedReader reader = null; try { JsonParser parser = new JsonParser(); reader = new BufferedReader(new FileReader(fp)); jQuest = (JsonObject) parser.parse(reader); reader.close(); } catch (JsonSyntaxException | IOException | ResourceLoadException e){ throw new ResourceLoadException("Unable to load and parse Quest File - invalid JSON file is likely cause", e); } //Validate the json obj title = jQuest.get("title").toString(); title = title.replaceAll("^\"|\"$", ""); if (title.equals("")) { throw new ResourceLoadException(""); } //The item requirements and rewards are stored as a mapping between item ID and count JsonObject itemReqs = jQuest.getAsJsonObject("iReq"); itemRequirement = parseItemQuantityHashMap(title,itemReqs); JsonObject itemRewards = jQuest.getAsJsonObject("rewards"); rewards = parseItemQuantityHashMap(title,itemRewards); description = jQuest.get("optDesc").toString(); description = description.replaceAll("^\"|\"$", ""); JsonObject killReqs = jQuest.getAsJsonObject("kReq"); killRequirement = parseKillReqMap(title,killReqs); return new Quest(title,rewards,killRequirement,itemRequirement,description); } private HashMap<String,Integer> parseItemQuantityHashMap(String title, JsonObject iqMap) { //Create Instance of the Item Manager class for checking valid items ItemManager itemManager = (ItemManager) GameManager.get().getManager(ItemManager.class); HashMap<String,Integer> returnMap = new HashMap<>(); if (!iqMap.entrySet().isEmpty()) { for (Map.Entry i:iqMap.entrySet()) { //For each entry in the item req obj make sure it is valid //No duplicate entries allowed if (returnMap.containsKey(i.getKey())) { throw new ResourceLoadException("Can't add the same key (" + i.getKey().toString() + ") twice into the item requirements for quest (" + title + ")"); } //Key and Value must not be empty if (i.getKey().toString().equals("")) { throw new ResourceLoadException("Can't add an empty item requirement key for quest (" + title + ")"); } if (i.getValue().toString().equals("")) { throw new ResourceLoadException("Can't add an empty item requirement amount for quest (" + title + ")"); } //Make sure the amount of the item is an integer int count; try { count = Integer.parseUnsignedInt(i.getValue().toString()); if (count < 1) { throw new NumberFormatException(); } } catch (NumberFormatException e) { throw new ResourceLoadException("Can't add a non positive integer item requirement amount for quest (" + title + ")"); } //The item key must be an actual item if (itemManager.getNew(i.getKey().toString()) == null) { throw new ResourceLoadException("Can't add an item which currently does not exist in the Item Manager"); } //Create new instance of valid item - catch if fails (invalid) Item entryItem = itemManager.getNew(i.getKey().toString()); if (entryItem == null) { throw new ResourceLoadException("Item (" + i.getKey().toString() + ") is not a valid item in quest (" + title + ")"); } //Item names use the _ when creating, but " " when checking returnMap.put(i.getKey().toString(),Integer.parseUnsignedInt(i.getValue().toString())); } } return returnMap; } private EnumMap<EnemyType, Integer> parseKillReqMap(String title, JsonObject krmMap) { EnumMap<EnemyType, Integer> returnKRM = new EnumMap<>(EnemyType.class); if (!krmMap.entrySet().isEmpty()) { for (Map.Entry<String,JsonElement> enemyMap: krmMap.entrySet()) { String forQConst = ") for quest ("; //Key and value must not be empty if (enemyMap.getKey().equals("")) { throw new ResourceLoadException("Can't add an kill requirement key to node (" + enemyMap.getKey() + forQConst + title + ")"); } if (enemyMap.getValue().toString().equals("")) { throw new ResourceLoadException("Can't add an kill requirement value to node (" + enemyMap.getKey() + forQConst + title + ")"); } EnemyType et; try { et = EnemyType.valueOf(enemyMap.getKey()); } catch (IllegalArgumentException e) { throw new ResourceLoadException("Invalid enemy type supplied (" + enemyMap.getKey()+ forQConst + title + ")"); } if (returnKRM.containsKey(et)) { throw new ResourceLoadException("Can't add the same enemy key (" + enemyMap.getKey() + ") twice into the kill requirements node for quest (" + title + ")"); } int killCount = 0; try { killCount = Integer.parseUnsignedInt(enemyMap.getValue().toString()); if (killCount < 1) { throw new NumberFormatException(); } } catch (NumberFormatException e){ throw new ResourceLoadException("Can't add a non valid enemy kill count to enemy type (" + enemyMap.getKey() + ")"); } returnKRM.put(et,killCount); } } return returnKRM; } }
UTF-8
Java
9,331
java
QuestReader.java
Java
[ { "context": "der handles quest loading from files\n *\n * @author Harry Guthrie\n */\npublic class QuestReader {\n\n static ArrayL", "end": 635, "score": 0.9997923970222473, "start": 622, "tag": "NAME", "value": "Harry Guthrie" } ]
null
[]
package com.deco2800.hcg.quests; import com.deco2800.hcg.entities.enemyentities.EnemyType; import com.deco2800.hcg.items.Item; import com.deco2800.hcg.managers.ResourceLoadException; import com.deco2800.hcg.managers.ItemManager; import com.deco2800.hcg.managers.GameManager; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.*; /** * Quest reader handles quest loading from files * * @author <NAME> */ public class QuestReader { static ArrayList<Integer> validEnemyID = new ArrayList<>(Arrays.asList(1,2,3,4)); /** * A function which loads all the quests into the quest manager, this utalizes the loadQuest function, and it then * adds all the files in the folder to the hash map of quests titles to quests. */ public Map<String,Quest> loadAllQuests() { HashMap<String,Quest> quests = new HashMap<>(); String questsFolder = "resources/quests/"; final File jQuestFile = new File(questsFolder); Quest q; for (String fp: jQuestFile.list()) { try { q = loadQuest(questsFolder + fp); if (quests.containsKey(q.getTitle())) { throw new ResourceLoadException("Quest title is a duplicate (" + q.getTitle() + ") in file (" + fp +")"); } quests.put(q.getTitle(),q); } catch (JsonSyntaxException | ResourceLoadException e) { throw new ResourceLoadException("Failure during quest file load: " + fp, e); } } return quests; } /** * Loads a particular quest and returns the Quest object, or it throws and informative error as to why the file * being passed into the function is wrong. * * @param fp * @return * @throws IOException */ public Quest loadQuest(String fp) { //Make sure the file is a json file if (!fp.substring(fp.length() - ".json".length(),fp.length()).equals(".json")) { throw new ResourceLoadException("All files in the quest resources files must be .json files"); } //Containers for the information in the quest String title; //Name of the quest to be displayed HashMap<String,Integer> rewards; // items to amount for reward EnumMap<EnemyType, Integer> killRequirement; //Kills for enemy ID required HashMap<String, Integer> itemRequirement; //Item required to complete quest String description; //Get the inital json obj JsonObject jQuest; BufferedReader reader = null; try { JsonParser parser = new JsonParser(); reader = new BufferedReader(new FileReader(fp)); jQuest = (JsonObject) parser.parse(reader); reader.close(); } catch (JsonSyntaxException | IOException | ResourceLoadException e){ throw new ResourceLoadException("Unable to load and parse Quest File - invalid JSON file is likely cause", e); } //Validate the json obj title = jQuest.get("title").toString(); title = title.replaceAll("^\"|\"$", ""); if (title.equals("")) { throw new ResourceLoadException(""); } //The item requirements and rewards are stored as a mapping between item ID and count JsonObject itemReqs = jQuest.getAsJsonObject("iReq"); itemRequirement = parseItemQuantityHashMap(title,itemReqs); JsonObject itemRewards = jQuest.getAsJsonObject("rewards"); rewards = parseItemQuantityHashMap(title,itemRewards); description = jQuest.get("optDesc").toString(); description = description.replaceAll("^\"|\"$", ""); JsonObject killReqs = jQuest.getAsJsonObject("kReq"); killRequirement = parseKillReqMap(title,killReqs); return new Quest(title,rewards,killRequirement,itemRequirement,description); } private HashMap<String,Integer> parseItemQuantityHashMap(String title, JsonObject iqMap) { //Create Instance of the Item Manager class for checking valid items ItemManager itemManager = (ItemManager) GameManager.get().getManager(ItemManager.class); HashMap<String,Integer> returnMap = new HashMap<>(); if (!iqMap.entrySet().isEmpty()) { for (Map.Entry i:iqMap.entrySet()) { //For each entry in the item req obj make sure it is valid //No duplicate entries allowed if (returnMap.containsKey(i.getKey())) { throw new ResourceLoadException("Can't add the same key (" + i.getKey().toString() + ") twice into the item requirements for quest (" + title + ")"); } //Key and Value must not be empty if (i.getKey().toString().equals("")) { throw new ResourceLoadException("Can't add an empty item requirement key for quest (" + title + ")"); } if (i.getValue().toString().equals("")) { throw new ResourceLoadException("Can't add an empty item requirement amount for quest (" + title + ")"); } //Make sure the amount of the item is an integer int count; try { count = Integer.parseUnsignedInt(i.getValue().toString()); if (count < 1) { throw new NumberFormatException(); } } catch (NumberFormatException e) { throw new ResourceLoadException("Can't add a non positive integer item requirement amount for quest (" + title + ")"); } //The item key must be an actual item if (itemManager.getNew(i.getKey().toString()) == null) { throw new ResourceLoadException("Can't add an item which currently does not exist in the Item Manager"); } //Create new instance of valid item - catch if fails (invalid) Item entryItem = itemManager.getNew(i.getKey().toString()); if (entryItem == null) { throw new ResourceLoadException("Item (" + i.getKey().toString() + ") is not a valid item in quest (" + title + ")"); } //Item names use the _ when creating, but " " when checking returnMap.put(i.getKey().toString(),Integer.parseUnsignedInt(i.getValue().toString())); } } return returnMap; } private EnumMap<EnemyType, Integer> parseKillReqMap(String title, JsonObject krmMap) { EnumMap<EnemyType, Integer> returnKRM = new EnumMap<>(EnemyType.class); if (!krmMap.entrySet().isEmpty()) { for (Map.Entry<String,JsonElement> enemyMap: krmMap.entrySet()) { String forQConst = ") for quest ("; //Key and value must not be empty if (enemyMap.getKey().equals("")) { throw new ResourceLoadException("Can't add an kill requirement key to node (" + enemyMap.getKey() + forQConst + title + ")"); } if (enemyMap.getValue().toString().equals("")) { throw new ResourceLoadException("Can't add an kill requirement value to node (" + enemyMap.getKey() + forQConst + title + ")"); } EnemyType et; try { et = EnemyType.valueOf(enemyMap.getKey()); } catch (IllegalArgumentException e) { throw new ResourceLoadException("Invalid enemy type supplied (" + enemyMap.getKey()+ forQConst + title + ")"); } if (returnKRM.containsKey(et)) { throw new ResourceLoadException("Can't add the same enemy key (" + enemyMap.getKey() + ") twice into the kill requirements node for quest (" + title + ")"); } int killCount = 0; try { killCount = Integer.parseUnsignedInt(enemyMap.getValue().toString()); if (killCount < 1) { throw new NumberFormatException(); } } catch (NumberFormatException e){ throw new ResourceLoadException("Can't add a non valid enemy kill count to enemy type (" + enemyMap.getKey() + ")"); } returnKRM.put(et,killCount); } } return returnKRM; } }
9,324
0.550102
0.54678
219
41.607307
32.915016
124
false
false
0
0
0
0
0
0
0.534247
false
false
7
d447d196bd4d86f54087ad19b18f8936adbf42b9
26,989,574,494,499
18473bde29a1f91ba3ce8fc7f5f7720c0c10c294
/src/main/java/com/payneteasy/firewall/service/model/OutputPacket.java
9dceb4b0bcb5f383f35f91e5bdd7cb5d35047456
[]
no_license
evsinev/firewall-config
https://github.com/evsinev/firewall-config
801ad9e95a63a31f6c5617c93d4fc9c331c01a1e
807c8a21055c5d46c6e7c993c6286265db770822
refs/heads/master
2023-08-09T04:22:25.070000
2023-07-28T15:50:39
2023-07-28T15:50:39
7,672,586
5
5
null
false
2022-12-14T20:21:16
2013-01-17T19:25:52
2022-02-07T17:16:01
2022-12-14T20:21:13
248
2
7
2
Java
false
false
package com.payneteasy.firewall.service.model; /** * */ public class OutputPacket extends AbstractPacket { public String destination_address_name; public String serviceName; public String getDestination_address_name() { return destination_address_name; } }
UTF-8
Java
288
java
OutputPacket.java
Java
[]
null
[]
package com.payneteasy.firewall.service.model; /** * */ public class OutputPacket extends AbstractPacket { public String destination_address_name; public String serviceName; public String getDestination_address_name() { return destination_address_name; } }
288
0.715278
0.715278
16
17
20.600365
50
false
false
0
0
0
0
0
0
0.25
false
false
7
ee42d378d22027a9f6bd11e5a8eb4b01fd4482e6
30,958,124,292,922
73fbb35995b7401f0a9008f70f8b8396e45ab9ad
/SimpleSpringMVCApp/src/main/java/com/spring/SimpleSpringMVCApp/dto/Account.java
a5a81363d50bcf75527093db5ff87fe99fa69837
[]
no_license
JCCouture/SimpleSpringMVCApp
https://github.com/JCCouture/SimpleSpringMVCApp
fc92acdc9cfbc4a1fc29af39163081f25097eb29
b42912d4fdd2b0068cb83d24d8b615017c1dc4a0
refs/heads/master
2021-01-10T16:32:53.364000
2015-11-02T01:36:54
2015-11-02T01:36:54
44,494,330
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.spring.SimpleSpringMVCApp.dto; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Account { private String email; private String password; protected Account() { } public Account(String email, String password) { this.email = email; this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(this); return json; } }
UTF-8
Java
769
java
Account.java
Java
[]
null
[]
package com.spring.SimpleSpringMVCApp.dto; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class Account { private String email; private String password; protected Account() { } public Account(String email, String password) { this.email = email; this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(this); return json; } }
769
0.660598
0.660598
42
16.309525
16.266367
61
false
false
0
0
0
0
0
0
1.142857
false
false
7
616388a5f2825e97657a1589718ae7309f338a05
26,225,070,317,976
4e247c054d5f7b59db26e3831a49fcf772720f0f
/levels/LevelInformation.java
76f2014e99a1aa3d0bed534371fba03969b3fe5b
[]
no_license
orspiegel/Arkanoid-game
https://github.com/orspiegel/Arkanoid-game
04ecae59f4126309dc4059c6b528ce11adcc25c3
678649bf62e6e94ce0765ed4ef8f6382a254b616
refs/heads/main
2023-09-05T18:23:02.838000
2021-11-18T20:31:58
2021-11-18T20:31:58
429,562,629
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package levels; import animation.Velocity; import collidables.Block; import sprites.Sprite; import java.util.List; //ID: 318720067 /** * interFace of the level information. * contains the settings of every level * that will implement this interface. */ public interface LevelInformation { /** * The number of the balls at that current level. * * @return the number. */ int numberOfBalls(); /** * Initial velocities method. * * @return the lost of balls current level velocities. */ List<Velocity> initialBallVelocities(); /** * the velocity of the paddle. * * @return the speed */ int paddleSpeed(); /** * the width of the paddle. * * @return the width */ int paddleWidth(); /** * the level name will be displayed at the top of the screen. * * @return the name string. */ String levelName(); /** * Returns a sprite with the background of the level. * * @return sprite. */ Sprite getBackground(); /** * Blocks list. * The Blocks that make up this level, each block contains * its size, color and location. * * @return the list of blocks. */ List<Block> blocks(); /** * Number of blocks that should be removed. * before the level is considered to be "cleared". * This number should be <= blocks.size(); * * @return the number. */ int numberOfBlocksToRemove(); /** * getter. * @return the level. */ int getLevel(); }
UTF-8
Java
1,679
java
LevelInformation.java
Java
[]
null
[]
package levels; import animation.Velocity; import collidables.Block; import sprites.Sprite; import java.util.List; //ID: 318720067 /** * interFace of the level information. * contains the settings of every level * that will implement this interface. */ public interface LevelInformation { /** * The number of the balls at that current level. * * @return the number. */ int numberOfBalls(); /** * Initial velocities method. * * @return the lost of balls current level velocities. */ List<Velocity> initialBallVelocities(); /** * the velocity of the paddle. * * @return the speed */ int paddleSpeed(); /** * the width of the paddle. * * @return the width */ int paddleWidth(); /** * the level name will be displayed at the top of the screen. * * @return the name string. */ String levelName(); /** * Returns a sprite with the background of the level. * * @return sprite. */ Sprite getBackground(); /** * Blocks list. * The Blocks that make up this level, each block contains * its size, color and location. * * @return the list of blocks. */ List<Block> blocks(); /** * Number of blocks that should be removed. * before the level is considered to be "cleared". * This number should be <= blocks.size(); * * @return the number. */ int numberOfBlocksToRemove(); /** * getter. * @return the level. */ int getLevel(); }
1,679
0.551519
0.546158
82
18.475609
17.035992
65
false
false
0
0
0
0
0
0
0.207317
false
false
7
f52606e763f74f25144297058379e9e7cc931782
6,210,522,742,595
36d32eab8a8805ea8e4aecbcec15c8b60fde28c1
/src/week4/Board.java
51cce61f5a7d1516dde5b752fd0205f57208c0b2
[]
no_license
johnttan/algorithms_in_java
https://github.com/johnttan/algorithms_in_java
9fb17595469b76f9b8e22b7595f5a52b4a7e3f00
db2f17c541410742a99631031da3cb26886d3ed8
refs/heads/master
2020-05-18T05:30:44.332000
2015-04-01T07:18:33
2015-04-01T07:18:33
29,942,593
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayDeque; import java.util.ArrayList; public class Board { private int[][] board; private int N; private int hammingDistance; private int manhattanDistance; private int[][]twinGrid; private ArrayDeque<Board>neighborsQueue = null; private ArrayList<int[][]>neighborsList; private int[][] copyBoard(int[][] blocks){ int[][] result = new int[blocks.length][blocks.length]; for(int i=0;i<blocks.length;i++){ for(int j=0;j<blocks.length;j++){ result[i][j] = blocks[i][j]; } } return result; } public Board(int[][] blocks) throws NullPointerException { if(blocks == null){ throw new NullPointerException(); } board = blocks; N = board.length; hammingDistance = 0; manhattanDistance = 0; int[] swap1 = null; int[] swap2 = null; twinGrid = new int[N][N]; neighborsList = new ArrayList<int[][]>(); // StdOut.println(this.toString()); // Iterate through and precompute swaps, neighbors, hamming distance, and manhattan distance. for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ twinGrid[i][j] = board[i][j]; // System.out.println(String.format("At (%d, %d) %d)", i, j, board[i][j])); if(board[i][j] != 0){ int realY = (board[i][j]-1) % N; int realX = (board[i][j]-1) / N; // System.out.print(String.format("%d (%d %d)->(%d %d) ", board[i][j], i, j, realX, realY)); if(i != realX || j != realY){ hammingDistance ++; } manhattanDistance += Math.abs(realX - i) + Math.abs(realY - j); if(j + 1 < N && swap1 == null && board[i][j+1] != 0){ swap1 = new int[2]; swap1[0] = i; swap1[1] = j+1; swap2 = new int[2]; swap2[0] = i; swap2[1] = j; } }else{ // System.out.println(String.format("\nCOMPUTING NEIGHBORS: %d, %d, %d", i, j, board[i][j])); if(i + 1 < N){ int[][] neighbor1 = copyBoard(board); neighbor1[i][j] = board[i+1][j]; neighbor1[i+1][j] = board[i][j]; neighborsList.add(neighbor1); } if(j + 1 < N){ int[][] neighbor2 = copyBoard(board); neighbor2[i][j] = board[i][j+1]; neighbor2[i][j+1] = board[i][j]; neighborsList.add(neighbor2); } if(i - 1 >= 0){ int[][] neighbor3 = copyBoard(board); neighbor3[i][j] = board[i-1][j]; neighbor3[i-1][j] = board[i][j]; neighborsList.add(neighbor3); } if(j - 1 >= 0){ int[][] neighbor4 = copyBoard(board); neighbor4[i][j] = board[i][j-1]; neighbor4[i][j-1] = board[i][j]; neighborsList.add(neighbor4); } } } } // Precompute swaps for twin. twinGrid[swap1[0]][swap1[1]] = board[swap2[0]][swap2[1]]; twinGrid[swap2[0]][swap2[1]] = board[swap1[0]][swap1[1]]; } public int dimension() { return N; } public int hamming() { return hammingDistance; } public int manhattan() { return manhattanDistance; } public boolean isGoal() { return hamming() == 0; } public Board twin() { // StdOut.println("NEW GRID"); // StdOut.println(new Board(twinGrid)); // StdOut.println("OLD GRID"); // StdOut.println(this.toString()); return new Board(twinGrid); } public boolean equals(Object y) { if(y == this){ return true; } if(y == null){ return false; } if(y.getClass() != this.getClass()){ return false; } Board that = (Board) y; return that.toString().equals(toString()); } public String toString() { StringBuilder s = new StringBuilder(); s.append(N + "\n"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { s.append(String.format("%2d ", board[i][j])); } s.append("\n"); } return s.toString(); } public Iterable<Board> neighbors() { if(neighborsQueue != null){ return neighborsQueue; }else{ neighborsQueue = new ArrayDeque<Board>(); for(int[][] grid : neighborsList){ neighborsQueue.add(new Board(grid)); } return neighborsQueue; } } public static void main(String[] args) { int[][] testGrid = new int[3][3]; for(int i=0;i<testGrid.length;i++){ for(int j=0;j<testGrid.length;j++){ testGrid[i][j] = 3 * 3 - (i * testGrid.length + j) - 1; // System.out.print(testGrid[i][j]); } // System.out.println(""); } Board testBoard = new Board(testGrid); System.out.println("\nMANHATTAN"); System.out.println(testBoard.manhattan()); assert testBoard.manhattan() == 20 : "manhattan should be 20"; assert testBoard.hamming() == 7: "hamming should be 7"; System.out.println("HAMMING"); System.out.println(testBoard.hamming()); System.out.println(testBoard.toString()); // System.out.println(testBoard.twin().toString()); for(Board neighbor : testBoard.neighbors()){ System.out.println(neighbor.toString()); } testGrid = new int[3][3]; for(int i=0;i<testGrid.length;i++){ for(int j=0;j<testGrid.length;j++){ testGrid[i][j] = (i * testGrid.length + j) + 1; if(i == testGrid.length-1 && j == testGrid.length-1){ testGrid[i][j] = 0; } System.out.print(testGrid[i][j]); } System.out.println(""); } testBoard = new Board(testGrid); StdOut.println(testBoard.isGoal()); } }
UTF-8
Java
6,676
java
Board.java
Java
[]
null
[]
import java.util.ArrayDeque; import java.util.ArrayList; public class Board { private int[][] board; private int N; private int hammingDistance; private int manhattanDistance; private int[][]twinGrid; private ArrayDeque<Board>neighborsQueue = null; private ArrayList<int[][]>neighborsList; private int[][] copyBoard(int[][] blocks){ int[][] result = new int[blocks.length][blocks.length]; for(int i=0;i<blocks.length;i++){ for(int j=0;j<blocks.length;j++){ result[i][j] = blocks[i][j]; } } return result; } public Board(int[][] blocks) throws NullPointerException { if(blocks == null){ throw new NullPointerException(); } board = blocks; N = board.length; hammingDistance = 0; manhattanDistance = 0; int[] swap1 = null; int[] swap2 = null; twinGrid = new int[N][N]; neighborsList = new ArrayList<int[][]>(); // StdOut.println(this.toString()); // Iterate through and precompute swaps, neighbors, hamming distance, and manhattan distance. for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ twinGrid[i][j] = board[i][j]; // System.out.println(String.format("At (%d, %d) %d)", i, j, board[i][j])); if(board[i][j] != 0){ int realY = (board[i][j]-1) % N; int realX = (board[i][j]-1) / N; // System.out.print(String.format("%d (%d %d)->(%d %d) ", board[i][j], i, j, realX, realY)); if(i != realX || j != realY){ hammingDistance ++; } manhattanDistance += Math.abs(realX - i) + Math.abs(realY - j); if(j + 1 < N && swap1 == null && board[i][j+1] != 0){ swap1 = new int[2]; swap1[0] = i; swap1[1] = j+1; swap2 = new int[2]; swap2[0] = i; swap2[1] = j; } }else{ // System.out.println(String.format("\nCOMPUTING NEIGHBORS: %d, %d, %d", i, j, board[i][j])); if(i + 1 < N){ int[][] neighbor1 = copyBoard(board); neighbor1[i][j] = board[i+1][j]; neighbor1[i+1][j] = board[i][j]; neighborsList.add(neighbor1); } if(j + 1 < N){ int[][] neighbor2 = copyBoard(board); neighbor2[i][j] = board[i][j+1]; neighbor2[i][j+1] = board[i][j]; neighborsList.add(neighbor2); } if(i - 1 >= 0){ int[][] neighbor3 = copyBoard(board); neighbor3[i][j] = board[i-1][j]; neighbor3[i-1][j] = board[i][j]; neighborsList.add(neighbor3); } if(j - 1 >= 0){ int[][] neighbor4 = copyBoard(board); neighbor4[i][j] = board[i][j-1]; neighbor4[i][j-1] = board[i][j]; neighborsList.add(neighbor4); } } } } // Precompute swaps for twin. twinGrid[swap1[0]][swap1[1]] = board[swap2[0]][swap2[1]]; twinGrid[swap2[0]][swap2[1]] = board[swap1[0]][swap1[1]]; } public int dimension() { return N; } public int hamming() { return hammingDistance; } public int manhattan() { return manhattanDistance; } public boolean isGoal() { return hamming() == 0; } public Board twin() { // StdOut.println("NEW GRID"); // StdOut.println(new Board(twinGrid)); // StdOut.println("OLD GRID"); // StdOut.println(this.toString()); return new Board(twinGrid); } public boolean equals(Object y) { if(y == this){ return true; } if(y == null){ return false; } if(y.getClass() != this.getClass()){ return false; } Board that = (Board) y; return that.toString().equals(toString()); } public String toString() { StringBuilder s = new StringBuilder(); s.append(N + "\n"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { s.append(String.format("%2d ", board[i][j])); } s.append("\n"); } return s.toString(); } public Iterable<Board> neighbors() { if(neighborsQueue != null){ return neighborsQueue; }else{ neighborsQueue = new ArrayDeque<Board>(); for(int[][] grid : neighborsList){ neighborsQueue.add(new Board(grid)); } return neighborsQueue; } } public static void main(String[] args) { int[][] testGrid = new int[3][3]; for(int i=0;i<testGrid.length;i++){ for(int j=0;j<testGrid.length;j++){ testGrid[i][j] = 3 * 3 - (i * testGrid.length + j) - 1; // System.out.print(testGrid[i][j]); } // System.out.println(""); } Board testBoard = new Board(testGrid); System.out.println("\nMANHATTAN"); System.out.println(testBoard.manhattan()); assert testBoard.manhattan() == 20 : "manhattan should be 20"; assert testBoard.hamming() == 7: "hamming should be 7"; System.out.println("HAMMING"); System.out.println(testBoard.hamming()); System.out.println(testBoard.toString()); // System.out.println(testBoard.twin().toString()); for(Board neighbor : testBoard.neighbors()){ System.out.println(neighbor.toString()); } testGrid = new int[3][3]; for(int i=0;i<testGrid.length;i++){ for(int j=0;j<testGrid.length;j++){ testGrid[i][j] = (i * testGrid.length + j) + 1; if(i == testGrid.length-1 && j == testGrid.length-1){ testGrid[i][j] = 0; } System.out.print(testGrid[i][j]); } System.out.println(""); } testBoard = new Board(testGrid); StdOut.println(testBoard.isGoal()); } }
6,676
0.451917
0.437088
206
31.407766
22.445375
112
false
false
0
0
0
0
0
0
0.669903
false
false
7
09686e40db9db1e469abe5af8912456438b40b10
19,739,669,703,561
626f60db71b0e38906aa380aad7e89e115927897
/sources/com/tencent/bugly/proguard/C1975ah.java
ff2c2620ad8160b697c0f7120993d3ffbd4a9f36
[]
no_license
hongducthbk123/locsource
https://github.com/hongducthbk123/locsource
2b53424ff8b3aeb5c06b65a7fad9c19c058d361f
2a4f4c2221e996446bde43329ccbd1659ca1f68b
refs/heads/master
2021-05-24T17:34:35.820000
2020-04-07T03:55:39
2020-04-07T03:55:39
253,675,393
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tencent.bugly.proguard; import java.util.ArrayList; import java.util.Collection; /* renamed from: com.tencent.bugly.proguard.ah */ /* compiled from: BUGLY */ public final class C1975ah extends C1994j implements Cloneable { /* renamed from: c */ private static ArrayList<String> f1458c; /* renamed from: a */ private String f1459a = ""; /* renamed from: b */ private ArrayList<String> f1460b = null; /* renamed from: a */ public final void mo19550a(C1993i iVar) { iVar.mo19581a(this.f1459a, 0); if (this.f1460b != null) { iVar.mo19582a((Collection<T>) this.f1460b, 1); } } /* renamed from: a */ public final void mo19549a(C1991h hVar) { this.f1459a = hVar.mo19572b(0, true); if (f1458c == null) { f1458c = new ArrayList<>(); f1458c.add(""); } this.f1460b = (ArrayList) hVar.mo19567a(f1458c, 1, false); } /* renamed from: a */ public final void mo19551a(StringBuilder sb, int i) { } }
UTF-8
Java
1,055
java
C1975ah.java
Java
[]
null
[]
package com.tencent.bugly.proguard; import java.util.ArrayList; import java.util.Collection; /* renamed from: com.tencent.bugly.proguard.ah */ /* compiled from: BUGLY */ public final class C1975ah extends C1994j implements Cloneable { /* renamed from: c */ private static ArrayList<String> f1458c; /* renamed from: a */ private String f1459a = ""; /* renamed from: b */ private ArrayList<String> f1460b = null; /* renamed from: a */ public final void mo19550a(C1993i iVar) { iVar.mo19581a(this.f1459a, 0); if (this.f1460b != null) { iVar.mo19582a((Collection<T>) this.f1460b, 1); } } /* renamed from: a */ public final void mo19549a(C1991h hVar) { this.f1459a = hVar.mo19572b(0, true); if (f1458c == null) { f1458c = new ArrayList<>(); f1458c.add(""); } this.f1460b = (ArrayList) hVar.mo19567a(f1458c, 1, false); } /* renamed from: a */ public final void mo19551a(StringBuilder sb, int i) { } }
1,055
0.599052
0.501422
40
25.375
19.818789
66
false
false
0
0
0
0
0
0
0.45
false
false
7
8a4e400f0ecdc9488c6292656792765dd3111ba2
9,929,964,437,030
163e0a7c7fc275b28c1c377648cc77a67a07851e
/src/aula_17_09_01/ConverteBinario.java
5d8839541745ca3c54d14a97cade5a1ab11188a2
[]
no_license
anapbr/Algoritmos
https://github.com/anapbr/Algoritmos
8b50e80e47d8f7c4be9315b9bb6fb1384d323e12
705e04657f65ee76a44fc6ee6dc95369f14aeebd
refs/heads/master
2021-08-11T09:47:03.368000
2017-11-13T14:35:06
2017-11-13T14:35:06
109,975,585
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package aula_17_09_01; import auxiliares.Auxiliar; public class ConverteBinario { public static void main(String[] args) { int decimal = 10; int[] resultado = converterBinario(decimal); System.out.print(decimal + " convertido em binário é igual a "); Auxiliar.imprimeVetor(resultado); } public static int[] converterBinario (int n) { int t = n; int tamanho = (int) (Math.log10(n) / Math.log10(2)) + 1; int[] b = new int[tamanho]; int k=-1; while (t>0) { k++; // Precisa gravar de trás para frente do vetor // Do contrário, precisará inverter ao final o // vetor para encontrar o resultado b[tamanho-1-k] = t % 2; t = t/2; } return b; } }
WINDOWS-1250
Java
728
java
ConverteBinario.java
Java
[]
null
[]
package aula_17_09_01; import auxiliares.Auxiliar; public class ConverteBinario { public static void main(String[] args) { int decimal = 10; int[] resultado = converterBinario(decimal); System.out.print(decimal + " convertido em binário é igual a "); Auxiliar.imprimeVetor(resultado); } public static int[] converterBinario (int n) { int t = n; int tamanho = (int) (Math.log10(n) / Math.log10(2)) + 1; int[] b = new int[tamanho]; int k=-1; while (t>0) { k++; // Precisa gravar de trás para frente do vetor // Do contrário, precisará inverter ao final o // vetor para encontrar o resultado b[tamanho-1-k] = t % 2; t = t/2; } return b; } }
728
0.616874
0.590595
44
15.431818
18.873259
66
false
false
0
0
0
0
0
0
1.818182
false
false
7
f881261b1676b7295151b150471f788b3bee4417
14,920,716,390,924
9b1d666cf7faafb45e9b456190dbb649ad70665c
/src/main/java/com/ServiciesHomeworks/model/Order.java
ed1b65b299ca9ea9f895e97323217d22f8543591
[]
no_license
songhee24/ServiciesHomeworks
https://github.com/songhee24/ServiciesHomeworks
cdc3b87785e8308db346dfce644f5cfafae6c006
66c8c9fac5e1848e21e7fefb1c160c4cd488aa8e
refs/heads/master
2021-01-06T14:30:06.781000
2020-02-18T12:56:37
2020-02-18T12:56:37
241,360,945
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ServiciesHomeworks.model; public class Order { }
UTF-8
Java
62
java
Order.java
Java
[]
null
[]
package com.ServiciesHomeworks.model; public class Order { }
62
0.790323
0.790323
4
14.5
15.239751
37
false
false
0
0
0
0
0
0
0.25
false
false
7
fff38bd32d4c7c4ff071e0b175b0bb3ab056a0ef
14,087,492,744,076
1fd25520b9a1d19e53a1953bf91fdddd3a694ebc
/aac-framework-common/src/main/java/com/aac/framework/common/util/poi/CellModel.java
7725119ab7ca7d8d440bb65ba51e8ef30a1bab92
[]
no_license
yuzhixingdao/framework-ssm
https://github.com/yuzhixingdao/framework-ssm
99933d918901e8e047d75ed4993ea4fe7564ee27
3c751beeb3e7d73bbf660dc458d6c5fc1d8826eb
refs/heads/master
2021-01-15T10:21:01
2016-09-21T05:57:06
2016-09-21T05:57:06
68,783,053
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aac.framework.common.util.poi; import com.aac.framework.common.util.poi.skin.Style; public class CellModel { private String value; private Style style; public CellModel() { super(); } public CellModel(String value) { super(); this.value = value; } public CellModel(String value, Style style) { super(); this.value = value; this.style = style; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Style getStyle() { if (this.style == null) { this.style = new Style(); } return this.style; } public void setStyle(Style style) { this.style = style; } }
UTF-8
Java
720
java
CellModel.java
Java
[]
null
[]
package com.aac.framework.common.util.poi; import com.aac.framework.common.util.poi.skin.Style; public class CellModel { private String value; private Style style; public CellModel() { super(); } public CellModel(String value) { super(); this.value = value; } public CellModel(String value, Style style) { super(); this.value = value; this.style = style; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Style getStyle() { if (this.style == null) { this.style = new Style(); } return this.style; } public void setStyle(Style style) { this.style = style; } }
720
0.623611
0.623611
45
14
14.564797
52
false
false
0
0
0
0
0
0
1.311111
false
false
7
a1887c3e1e91f2d12713cd29c94b4b70b08a894d
7,507,602,875,708
2d91fa5b3fc55e0bdabec7750f52146845273eb0
/ocms/src/main/java/in/careerscale/apps/ocms/dao/model/UserNetwork.java
81250526ce4f3ccfc89ba6b1db02aaebe47e9d7b
[]
no_license
careerscale/cs-ocms
https://github.com/careerscale/cs-ocms
d9b43a6d49844b370a7f73034999f2dfdea21656
45db8bbb04d1c642f7d16b0203abcd4f41ca8434
refs/heads/master
2021-01-15T09:28:53.061000
2015-02-28T11:58:28
2015-02-28T11:58:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package in.careerscale.apps.ocms.dao.model; // Generated Jul 7, 2013 10:49:55 AM by Hibernate Tools 4.0.0 import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * UserNetwork generated by hbm2java */ @Entity @Table(name = "user_network", catalog = "ocms") public class UserNetwork implements java.io.Serializable { private String userNetworkId; private LoginMaster loginMaster; private SocialNetwork socialNetwork; private Date lastAccessDate; private String userAccessToken; public UserNetwork() { } public UserNetwork(String userNetworkId, LoginMaster loginMaster, SocialNetwork socialNetwork) { this.userNetworkId = userNetworkId; this.loginMaster = loginMaster; this.socialNetwork = socialNetwork; } public UserNetwork(String userNetworkId, LoginMaster loginMaster, SocialNetwork socialNetwork,String accessToken) { this.userNetworkId = userNetworkId; this.loginMaster = loginMaster; this.socialNetwork = socialNetwork; this.userAccessToken=accessToken; } public UserNetwork(String userNetworkId, LoginMaster loginMaster, SocialNetwork socialNetwork, Date lastAccessDate, String userAccessToken) { this.userNetworkId = userNetworkId; this.loginMaster = loginMaster; this.socialNetwork = socialNetwork; this.lastAccessDate = lastAccessDate; this.userAccessToken = userAccessToken; } @Id @Column(name = "user_network_id", unique = true, nullable = false, length = 100) public String getUserNetworkId() { return this.userNetworkId; } public void setUserNetworkId(String userNetworkId) { this.userNetworkId = userNetworkId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id", nullable = false) public LoginMaster getLoginMaster() { return this.loginMaster; } public void setLoginMaster(LoginMaster loginMaster) { this.loginMaster = loginMaster; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "network_id", nullable = false) public SocialNetwork getSocialNetwork() { return this.socialNetwork; } public void setSocialNetwork(SocialNetwork socialNetwork) { this.socialNetwork = socialNetwork; } @Temporal(TemporalType.DATE) @Column(name = "last_access_date", length = 10) public Date getLastAccessDate() { return this.lastAccessDate; } public void setLastAccessDate(Date lastAccessDate) { this.lastAccessDate = lastAccessDate; } @Column(name = "user_access_token", length = 100) public String getUserAccessToken() { return this.userAccessToken; } public void setUserAccessToken(String userAccessToken) { this.userAccessToken = userAccessToken; } }
UTF-8
Java
2,872
java
UserNetwork.java
Java
[]
null
[]
package in.careerscale.apps.ocms.dao.model; // Generated Jul 7, 2013 10:49:55 AM by Hibernate Tools 4.0.0 import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * UserNetwork generated by hbm2java */ @Entity @Table(name = "user_network", catalog = "ocms") public class UserNetwork implements java.io.Serializable { private String userNetworkId; private LoginMaster loginMaster; private SocialNetwork socialNetwork; private Date lastAccessDate; private String userAccessToken; public UserNetwork() { } public UserNetwork(String userNetworkId, LoginMaster loginMaster, SocialNetwork socialNetwork) { this.userNetworkId = userNetworkId; this.loginMaster = loginMaster; this.socialNetwork = socialNetwork; } public UserNetwork(String userNetworkId, LoginMaster loginMaster, SocialNetwork socialNetwork,String accessToken) { this.userNetworkId = userNetworkId; this.loginMaster = loginMaster; this.socialNetwork = socialNetwork; this.userAccessToken=accessToken; } public UserNetwork(String userNetworkId, LoginMaster loginMaster, SocialNetwork socialNetwork, Date lastAccessDate, String userAccessToken) { this.userNetworkId = userNetworkId; this.loginMaster = loginMaster; this.socialNetwork = socialNetwork; this.lastAccessDate = lastAccessDate; this.userAccessToken = userAccessToken; } @Id @Column(name = "user_network_id", unique = true, nullable = false, length = 100) public String getUserNetworkId() { return this.userNetworkId; } public void setUserNetworkId(String userNetworkId) { this.userNetworkId = userNetworkId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id", nullable = false) public LoginMaster getLoginMaster() { return this.loginMaster; } public void setLoginMaster(LoginMaster loginMaster) { this.loginMaster = loginMaster; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "network_id", nullable = false) public SocialNetwork getSocialNetwork() { return this.socialNetwork; } public void setSocialNetwork(SocialNetwork socialNetwork) { this.socialNetwork = socialNetwork; } @Temporal(TemporalType.DATE) @Column(name = "last_access_date", length = 10) public Date getLastAccessDate() { return this.lastAccessDate; } public void setLastAccessDate(Date lastAccessDate) { this.lastAccessDate = lastAccessDate; } @Column(name = "user_access_token", length = 100) public String getUserAccessToken() { return this.userAccessToken; } public void setUserAccessToken(String userAccessToken) { this.userAccessToken = userAccessToken; } }
2,872
0.77507
0.767061
106
26.094339
20.820675
81
false
false
0
0
0
0
0
0
1.462264
false
false
7
6931653ff250738c388d3482e415400e52225756
7,284,264,550,414
ed7383ede7ebf5848660c60a57a4ee742a7583b1
/src/bankomatic/Main.java
89d8b95833ec7e1b6cdcc028dec48b8c04e7f23a
[]
no_license
Yeahsper/Ovning4_AccessDB
https://github.com/Yeahsper/Ovning4_AccessDB
ec1e79183575fbf4d21b41f25e0a530b81a26fb7
9a5254785c9840475cca166232a197ba4dd4fed3
refs/heads/master
2020-09-26T21:51:50.902000
2019-12-09T11:02:39
2019-12-09T11:02:39
226,349,663
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bankomatic; import bankomatic.Gui.LoginGUI; import javafx.application.Application; import javafx.stage.Stage; /** * Main Class to run the program. * @author Jesper * */ public class Main extends Application { private LoginGUI loginGUI = new LoginGUI(); @Override public void start(Stage primaryStage) throws Exception{ loginGUI.display(); } public static void main(String[] args) { launch(args); } }
UTF-8
Java
455
java
Main.java
Java
[ { "context": "/**\r\n * Main Class to run the program.\r\n * @author Jesper\r\n *\r\n */\r\npublic class Main extends Application {", "end": 185, "score": 0.998798131942749, "start": 179, "tag": "NAME", "value": "Jesper" } ]
null
[]
package bankomatic; import bankomatic.Gui.LoginGUI; import javafx.application.Application; import javafx.stage.Stage; /** * Main Class to run the program. * @author Jesper * */ public class Main extends Application { private LoginGUI loginGUI = new LoginGUI(); @Override public void start(Stage primaryStage) throws Exception{ loginGUI.display(); } public static void main(String[] args) { launch(args); } }
455
0.687912
0.687912
26
15.5
17.14699
56
false
false
0
0
0
0
0
0
0.653846
false
false
7
7114f344f9ebab2cca5ded73429cf342f7ed7a4d
395,137,017,166
e6f455a3e7fbde2dd3189273adb63ea37e19cfd6
/testing/app/src/main/java/com/example/TransitiveDependency.java
f96f1204a3cefd846e8b1b83cc62148e82d5f924
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
AndrewReitz/gradle-plugin-robospock
https://github.com/AndrewReitz/gradle-plugin-robospock
dce64e02e9f07bb6f13fa91ad25f22d7c7bfa6ce
144c1ab663f5299d45cd4898d894b897c10ec680
refs/heads/master
2021-05-28T18:28:02.416000
2015-01-01T18:02:10
2015-01-01T18:02:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example; import timber.log.Timber; public final class TransitiveDependency { public TransitiveDependency() { Class<?> c = Timber.class; } }
UTF-8
Java
170
java
TransitiveDependency.java
Java
[]
null
[]
package com.example; import timber.log.Timber; public final class TransitiveDependency { public TransitiveDependency() { Class<?> c = Timber.class; } }
170
0.688235
0.688235
9
17.888889
15.751151
41
false
false
0
0
0
0
0
0
0.333333
false
false
7
a37ec50e5fca56ef078cd4dbec2d5cc3ef7ddf33
36,593,121,383,322
18bb60fd5fadf715ed23a49ac5fb5dbf3c087177
/adages-restlet/src/main/java/oracle/training/oce/ws/adages/restlet/AdagesApplication.java
2f7fa1a7321dc1230370d9bb00da33f8b83a5b4c
[]
no_license
ecristobal/cacharreo-java
https://github.com/ecristobal/cacharreo-java
dd73d2b9731dc6d3a3b55692ccbd84678d9b8505
4ad5705b7c1b1a236599e92f0fc9473a7b822eda
refs/heads/master
2016-08-04T16:27:14.075000
2014-11-09T10:37:40
2014-11-09T10:37:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package oracle.training.oce.ws.adages.restlet; import org.restlet.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.routing.Router; /** * Sets up a routing table for REST services. * * @author esteban.a.rodriguez */ public class AdagesApplication extends Application { /* * (non-Javadoc) * * @see org.restlet.Application#createInboundRoot() */ @Override public Restlet createInboundRoot() { final Restlet janitor = new Restlet(this.getContext()) { /* (non-Javadoc) * @see org.restlet.Restlet#handle(org.restlet.Request, org.restlet.Response) */ @Override public void handle(Request request, Response response) { String message = null; String sid = (String) request.getAttributes().get("id"); if(sid == null) { message = badRequest("No ID given.\n"); } int id = 0; try { id = Integer.parseInt(sid); } catch(NumberFormatException e) { message = badRequest("Ill-formed ID.\n"); } final Adage adage = Adages.find(id); if(adage == null) { message = badRequest("No adage with ID " + id + ".\n"); } else { Adages.getList().remove(adage); message = "Adage with ID " + id + " removed.\n"; } response.setEntity(message, MediaType.TEXT_PLAIN); } }; final Router router = new Router(this.getContext()); router.attach("/", PlainResource.class); router.attach("/xml", XmlAllResource.class); router.attach("/xml/{id}", XmlOneResource.class); router.attach("/json", JsonAllResource.class); router.attach("/create", CreateResource.class); router.attach("/update", UpdateResource.class); router.attach("/delete/{id}", janitor); return router; } private String badRequest(String message) { final Status error = new Status(Status.CLIENT_ERROR_BAD_REQUEST, message); return error.toString(); } }
UTF-8
Java
1,969
java
AdagesApplication.java
Java
[ { "context": "p a routing table for REST services.\n *\n * @author esteban.a.rodriguez\n */\npublic class AdagesApplication extends Applic", "end": 351, "score": 0.9996699094772339, "start": 332, "tag": "NAME", "value": "esteban.a.rodriguez" } ]
null
[]
package oracle.training.oce.ws.adages.restlet; import org.restlet.Application; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.routing.Router; /** * Sets up a routing table for REST services. * * @author esteban.a.rodriguez */ public class AdagesApplication extends Application { /* * (non-Javadoc) * * @see org.restlet.Application#createInboundRoot() */ @Override public Restlet createInboundRoot() { final Restlet janitor = new Restlet(this.getContext()) { /* (non-Javadoc) * @see org.restlet.Restlet#handle(org.restlet.Request, org.restlet.Response) */ @Override public void handle(Request request, Response response) { String message = null; String sid = (String) request.getAttributes().get("id"); if(sid == null) { message = badRequest("No ID given.\n"); } int id = 0; try { id = Integer.parseInt(sid); } catch(NumberFormatException e) { message = badRequest("Ill-formed ID.\n"); } final Adage adage = Adages.find(id); if(adage == null) { message = badRequest("No adage with ID " + id + ".\n"); } else { Adages.getList().remove(adage); message = "Adage with ID " + id + " removed.\n"; } response.setEntity(message, MediaType.TEXT_PLAIN); } }; final Router router = new Router(this.getContext()); router.attach("/", PlainResource.class); router.attach("/xml", XmlAllResource.class); router.attach("/xml/{id}", XmlOneResource.class); router.attach("/json", JsonAllResource.class); router.attach("/create", CreateResource.class); router.attach("/update", UpdateResource.class); router.attach("/delete/{id}", janitor); return router; } private String badRequest(String message) { final Status error = new Status(Status.CLIENT_ERROR_BAD_REQUEST, message); return error.toString(); } }
1,969
0.67547
0.674962
71
26.746479
21.189766
80
false
false
0
0
0
0
0
0
2.605634
false
false
7
a1a9c0326ef79b81cca68c2276f0d72e080c22d2
36,593,121,383,285
e6754396911e99b6c97fa9d906f745d00afe482b
/ContentEditorFX/ContentEditorFX/src/gui/docmodify/DocOverview.java
f737ab653bcd04ffbdd0d2cec706c1cefa647a64
[]
no_license
binonsekiz/mostar
https://github.com/binonsekiz/mostar
7a1ae9a4617f320882d916d11c598496f156efaa
88d00c96dc3b687787c18ac98b3d177e1f975147
refs/heads/master
2021-01-17T07:30:46.666000
2014-06-25T06:23:50
2014-06-25T06:23:50
15,288,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//package gui.docmodify; // //import javafx.scene.control.TreeItem; //import javafx.scene.control.TreeView; //import javafx.scene.layout.StackPane; //import settings.Translator; // //public class DocOverview extends StackPane{ // // @SuppressWarnings("rawtypes") // private TreeView treeView; // // private TreeItem treeRoot; // private int activeSection; // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public DocOverview(){ // treeView = new TreeView<>(); // treeRoot = new TreeItem(Translator.get("New Book")); // treeRoot.setExpanded(true); // /* treeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem>() { // @Override // public void changed(ObservableValue<? extends TreeItem> arg0, // TreeItem arg1, TreeItem arg2) { // if(treeView.getSelectionModel().getSelectedIndex() > 0){ // activeSection = treeView.getSelectionModel().getSelectedIndex() - 1; // DocSelectionModel.instance.sectionSelectionFromOverview(activeSection); // System.out.println("Tree selection changed to :" + (treeView.getSelectionModel().getSelectedIndex() - 1)); // } // } // });*/ // this.setId("doc-overview"); // } // // @SuppressWarnings("unchecked") // public void populateTreeView(){ // /* this.getChildren().remove(treeView); // // int columnCounter = 0; // // treeRoot.getChildren().clear(); // for(int i = 0; i < guiFacade.getDocument().getChapterCount(); i++){ // @SuppressWarnings("rawtypes") // TreeItem chapterItem = new TreeItem<String>(guiFacade.getDocument().getChapter(i).getName()); // chapterItem.setExpanded(true); // treeRoot.getChildren().add(chapterItem); // // for(int j = 0; j < guiFacade.getDocument().getChapter(i).getSectionCount(); j++){ // @SuppressWarnings("rawtypes") // TreeItem sectionItem = new TreeItem<String>(guiFacade.getDocument().getChapter(i).getSection(j).getName()); // sectionItem.setExpanded(true); // chapterItem.getChildren().add(sectionItem); // // for(int k=0; k < guiFacade.getDocument().getChapter(i).getSection(j).getColumnCount(); k++){ // TreeItem tempItem; // //take a snapshot of the columnviewpane // ImageView snapshot = new ImageView(guiFacade.takeSnapshot(columnCounter)); // snapshot.setPreserveRatio(true); // snapshot.setFitHeight(90); // tempItem = new TreeItem(snapshot); // columnCounter ++; // sectionItem.getChildren().add(tempItem); // } // // } // } // treeView.setRoot(treeRoot); // // this.getChildren().add(treeView);*/ // } // // /** // * Refreshes the view for the document attached. // * Should only be called by GuiFacade. // */ // public void refresh(){ // populateTreeView(); // } // // public int getActivePage(){ // return activeSection; // } // //}
UTF-8
Java
2,866
java
DocOverview.java
Java
[]
null
[]
//package gui.docmodify; // //import javafx.scene.control.TreeItem; //import javafx.scene.control.TreeView; //import javafx.scene.layout.StackPane; //import settings.Translator; // //public class DocOverview extends StackPane{ // // @SuppressWarnings("rawtypes") // private TreeView treeView; // // private TreeItem treeRoot; // private int activeSection; // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public DocOverview(){ // treeView = new TreeView<>(); // treeRoot = new TreeItem(Translator.get("New Book")); // treeRoot.setExpanded(true); // /* treeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem>() { // @Override // public void changed(ObservableValue<? extends TreeItem> arg0, // TreeItem arg1, TreeItem arg2) { // if(treeView.getSelectionModel().getSelectedIndex() > 0){ // activeSection = treeView.getSelectionModel().getSelectedIndex() - 1; // DocSelectionModel.instance.sectionSelectionFromOverview(activeSection); // System.out.println("Tree selection changed to :" + (treeView.getSelectionModel().getSelectedIndex() - 1)); // } // } // });*/ // this.setId("doc-overview"); // } // // @SuppressWarnings("unchecked") // public void populateTreeView(){ // /* this.getChildren().remove(treeView); // // int columnCounter = 0; // // treeRoot.getChildren().clear(); // for(int i = 0; i < guiFacade.getDocument().getChapterCount(); i++){ // @SuppressWarnings("rawtypes") // TreeItem chapterItem = new TreeItem<String>(guiFacade.getDocument().getChapter(i).getName()); // chapterItem.setExpanded(true); // treeRoot.getChildren().add(chapterItem); // // for(int j = 0; j < guiFacade.getDocument().getChapter(i).getSectionCount(); j++){ // @SuppressWarnings("rawtypes") // TreeItem sectionItem = new TreeItem<String>(guiFacade.getDocument().getChapter(i).getSection(j).getName()); // sectionItem.setExpanded(true); // chapterItem.getChildren().add(sectionItem); // // for(int k=0; k < guiFacade.getDocument().getChapter(i).getSection(j).getColumnCount(); k++){ // TreeItem tempItem; // //take a snapshot of the columnviewpane // ImageView snapshot = new ImageView(guiFacade.takeSnapshot(columnCounter)); // snapshot.setPreserveRatio(true); // snapshot.setFitHeight(90); // tempItem = new TreeItem(snapshot); // columnCounter ++; // sectionItem.getChildren().add(tempItem); // } // // } // } // treeView.setRoot(treeRoot); // // this.getChildren().add(treeView);*/ // } // // /** // * Refreshes the view for the document attached. // * Should only be called by GuiFacade. // */ // public void refresh(){ // populateTreeView(); // } // // public int getActivePage(){ // return activeSection; // } // //}
2,866
0.652477
0.64829
84
32.119049
27.768347
113
false
false
0
0
0
0
0
0
2.773809
false
false
7
416513b96c433742bffd6a04269e2dcab2b61d9c
34,333,968,604,063
f81e65ec332ca792b5fefdf1f77aa2fe7f3d6183
/src/main/java/bmo5/bmo5tests/bmo/pages/SingleReportPage.java
57d0699ef324e804ca820735a3b21be29aa67f42
[]
no_license
vvoicu/MajorProject
https://github.com/vvoicu/MajorProject
50b3c140cfa47b9486ed2d3c9fddc72cbb61f820
59c0b8198547abfa95d115bba5ce1e46e8771566
refs/heads/master
2016-09-16T15:06:15.957000
2015-04-07T10:08:07
2015-04-07T10:08:07
33,535,886
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bmo5.bmo5tests.bmo.pages; import java.io.IOException; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import bmo5.bmo5tests.tools.FileChecker; import bmo5.bmo5tests.tools.bmo.AbstractPage; public class SingleReportPage extends AbstractPage{ @FindBy(css = "section i.icon-c-cancel") @CacheLookup private WebElement printPagePreviewCancel; @FindBy(css = "div[class='btn-group btn-toolbar pull-right'] a > i.icon-c-email") @CacheLookup private WebElement emailIconReport; @FindBy(css = "div[class='btn-group btn-toolbar pull-right'] a > i.icon-c-floppy") @CacheLookup private WebElement saveIconReport; @FindBy(css = "div[class='btn-group btn-toolbar pull-right'] a > i.icon-c-download") @CacheLookup private WebElement downloadIconReport; @FindBy(css = "div[class='btn-group btn-toolbar pull-right'] > a > i.icon-c-print") @CacheLookup private WebElement printIconReport; @FindBy(css = "div[class='btn-toolbar pull-left'] > a") @CacheLookup private WebElement backToPreviousPageButtonReport; @FindBy(css = "div[class='pull-right drop-content-toggler'] > div > a") @CacheLookup private WebElement pastVersionsToggler; @FindBy(css = "div[class='pull-right drop-content-toggler'] > div > a > span") @CacheLookup private WebElement pastVersionsTogglerNumber; @FindBy(css = " div.page-wrap > div:nth-child(1) > div >div ") @CacheLookup private WebElement saveItemAfterOpening; @FindBy(css = "div#permission-enterprise-user strong") private WebElement alertMessageEnterprise; @FindBy(css = "div#permission-enterprise-user > div:nth-child(2) > button") private WebElement cancelButtonModalWindowEnterprise; @FindBy(css = "div#permission-modal-print strong") private WebElement alertMessagePrint; @FindBy(css = "div#permission-modal-print div:nth-child(2) > button") private WebElement cancelButtonModalWindowTrialPrint; @FindBy(css = "div#permission-modal-print div:nth-child(2) > a") private WebElement contactAccountManagementButtonTrialPrint; @FindBy(css = "div#permission-modal-pdf strong") private WebElement alertMessageDownload; @FindBy(css = "div#permission-modal-pdf div:nth-child(2) > button") private WebElement cancelButtonModalWindowTrialDownload; @FindBy(css = "div#permission-modal-pdf div:nth-child(2) > a") private WebElement contactAccountManagementButtonTrialDownload; public void clickOnEmailIconReportFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-email"); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-email"); } } else { System.out.println("There aren't any reports!"); } } public void clickOnSaveIconReportFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-floppy"); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-floppy"); } } else { System.out.println("There aren't any reports!"); } } public void verifyMediaActionOnHoveredReport(int reportNumber) { Actions tag = new Actions(getDriver()); tag.moveToElement(getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child("+reportNumber+") > div > div.tags"))).build().perform(); //element(getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child("+reportNumber+") > div > div.tags"))).click(); System.out.println("clicked!"); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-download")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-print")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-email")).isDisplayed()); } public void verifyMediaActionsOnReportView() { Assert.assertTrue(getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-download")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-print")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-email")).isDisplayed()); } public void verifyMediaActionInReportPreview() { Assert.assertTrue(getDriver().findElement(By.cssSelector("div#js-overflow > section > div > div:nth-child(1) > div > a > i.icon-c-download")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#js-overflow > section > div > div:nth-child(1) > div > a > i.icon-c-print")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#js-overflow > section > div > div:nth-child(1) > div > a > i.icon-c-email")).isDisplayed()); } //TODO Fix this // public void clickOnDownloadIconReportFromList(int reportNumber){ // int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); // String reportTitle=""; // if (numberOfReportsDisplayed > 0) { // if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { // elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-download"); // reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).getText(); // DataToolPage data = new DataToolPage(getDriver()); // data.saveImageHandle2(); // FileChecker fileChecker = new FileChecker(); // System.out.println(fileChecker.convertFileName(reportTitle)); // fileChecker.verifyFileIsDownloaded1(fileChecker.convertFileName(reportTitle)); // } else { // System.out.println("There aren't so many reports displayed so clicking the first report"); // elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-download"); // reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).getText(); // DataToolPage data = new DataToolPage(getDriver()); // data.saveImageHandle2(); // FileChecker fileChecker = new FileChecker(); // System.out.println(fileChecker.convertFileName(reportTitle)); // fileChecker.verifyFileIsDownloaded1(fileChecker.convertFileName(reportTitle)); // } // } else { // System.out.println("There aren't any reports!"); // } // } public void clickOnDownloadIconReportFromListTrialUser(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-download"); Assert.assertTrue(alertMessageDownload.isDisplayed()); cancelButtonModalWindowTrialDownload.click(); // Assert.assertTrue(getDriver().findElements(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-download")).size() == 0); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-download"); Assert.assertTrue(alertMessageDownload.isDisplayed()); cancelButtonModalWindowTrialDownload.click(); // Assert.assertTrue(getDriver().findElements(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-download")).size() == 0); } } else { System.out.println("There aren't any reports!"); } } public String clickOnDownloadIconReportFromListTrialUserAndVerifyContactAccountManager(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).getText(); elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-download"); Assert.assertTrue(alertMessageDownload.isDisplayed()); contactAccountManagementButtonTrialDownload.click(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).getText(); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-download"); Assert.assertTrue(alertMessageDownload.isDisplayed()); contactAccountManagementButtonTrialDownload.click(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public void clickOnPrintIconReportFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-print"); String winHandleBefore = getDriver().getWindowHandle(); for (String winHandle : getDriver().getWindowHandles()) { getDriver().switchTo().window(winHandle); } printPagePreviewCancel.click(); getDriver().switchTo().window(winHandleBefore); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-print"); String winHandleBefore = getDriver().getWindowHandle(); for (String winHandle : getDriver().getWindowHandles()) { getDriver().switchTo().window(winHandle); } printPagePreviewCancel.click(); getDriver().switchTo().window(winHandleBefore); } } else { System.out.println("There aren't any reports!"); } } public void clickOnPrintIconReportFromListTrialUser(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-print"); Assert.assertTrue(alertMessagePrint.isDisplayed()); cancelButtonModalWindowTrialPrint.click(); // Assert.assertTrue(getDriver().findElements(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-print")).size() == 0); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-print"); Assert.assertTrue(alertMessagePrint.isDisplayed()); cancelButtonModalWindowTrialPrint.click(); // Assert.assertTrue(getDriver().findElements(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-print")).size() == 0); } } else { System.out.println("There aren't any reports!"); } } public String clickOnPrintIconReportFromListTrialUserAndVerifyContactAccountManager(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).getText(); elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-print"); Assert.assertTrue(alertMessagePrint.isDisplayed()); contactAccountManagementButtonTrialPrint.click(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).getText(); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-print"); Assert.assertTrue(alertMessagePrint.isDisplayed()); contactAccountManagementButtonTrialPrint.click(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public String clickOnPreviewReportFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div > a.btn.btn-link.preview-report"); waitUntilElementDoesntExist(By.cssSelector("div.affix.loading"),50); reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).getText(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(2) > div a[class='btn btn-link preview-report']"); reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).getText(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public String clickOnPreviewReportArchiveFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div.media-listing > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { waitABit(5000); elementClick("div.media-listing > div:nth-child( "+ reportNumber +") > div:nth-child(2) > div > a.btn.btn-link.preview-report.hide-actions"); reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child("+ reportNumber +") > div:nth-child(1) > div > h5 > a")).getText(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div.media-listing > div:nth-child(1) > div:nth-child(2) > div > a.btn.btn-link.preview-report"); reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(1) > div:nth-child(1) > div > h5 > a")).getText(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public String clickOnPreviewReportsFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div.media-listing > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div.media-listing > div:nth-child( "+ reportNumber +") > div:nth-child(2) > div > a.btn.btn-link.preview-report.hide-actions"); reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child("+ reportNumber +") > div:nth-child(1) > h5 > a")).getText(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div.media-listing > div:nth-child(1) > div:nth-child(2) > div > a.btn.btn-link.preview-report"); reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(1) > div:nth-child(1) > div > h5 > a")).getText(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } //TODO Fix this // public void verifyDownloadFromHoveredMediaActions(int reportNumber) { // String reportTitle=""; // int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div.media-listing > div")).size(); // if (numberOfReportsDisplayed > 0) { // if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { // waitABit(5000); // reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(" + reportNumber + ")> div:nth-child(1) > div > h5 > a")).getText(); // elementClick("div.media-listing > div:nth-child(" + reportNumber + ") div.media-actions a > i.icon-c-download"); // DataToolPage data = new DataToolPage(getDriver()); // data.saveImageHandle2(); // FileChecker file = new FileChecker(); // file.verifyFileIsDownloaded1(file.convertFileName(reportTitle)); // } else { // System.out.println("There aren't so many reports displayed so clicking the first report"); // reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(1)> div:nth-child(1) > div > h5 > a")).getText(); // elementClick("div.media-listing > div:nth-child(1) div.media-actions a > i.icon-c-download"); // DataToolPage data = new DataToolPage(getDriver()); // data.saveImageHandle2(); // FileChecker file = new FileChecker(); // file.verifyFileIsDownloaded1(file.convertFileName(reportTitle)); // } // } else { // System.out.println("There aren't any reports!"); // } // } public String clickOnOneReportFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).click(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).click(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public String clickASpecialReportsFromListing(int reportNumber) { int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div.media-listing > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child("+ reportNumber +") > div:nth-child(1) > div > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child("+ reportNumber +") > div:nth-child(1) > div > h5 > a")).click(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(1) > div:nth-child(1) > div > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(1) > div:nth-child(1) > div > h5 > a")).click(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public void clickOnSaveIconReport() { saveIconReport.click(); Assert.assertTrue(saveItemAfterOpening.getText().contains("The article already exists in Saved Content!")|| saveItemAfterOpening.getText().contains("This report already exists in Saved Reports!") || saveItemAfterOpening.getText().contains("Report successfully saved!") || saveItemAfterOpening.getText().contains("Sucessfully added the article to Saved Content")); } public void saveEnterpriseIconInsideReport() { saveIconReport.click(); } public void clickOnPrintIconReport(String reportName) { printIconReport.click(); String winHandleBefore = getDriver().getWindowHandle(); for (String winHandle : getDriver().getWindowHandles()) { getDriver().switchTo().window(winHandle); } Assert.assertTrue(getDriver().findElement(By.cssSelector("div.padding-20 > h3#use")).getText().contains(reportName)); printPagePreviewCancel.click(); getDriver().switchTo().window(winHandleBefore); } public void clickOnPrintIconReportTrialUser(){ if(getDriver().findElements(By.cssSelector("div[class='btn-group btn-toolbar pull-right'] > a > i.icon-c-print")).size() > 0){ printIconReport.click(); Assert.assertTrue(alertMessagePrint.isDisplayed()); cancelButtonModalWindowTrialPrint.click(); } else{ System.out.println("There is no print icon."); } // Assert.assertTrue(getDriver().findElements(By.cssSelector("div[class='btn-group btn-toolbar pull-right'] > a > i.icon-c-print")).size() == 0); } public void performDownload() { waitABit(2000); String script = "src\\test\\java\\drivers\\downloadTestScript.exe"; Process p; try { p = Runtime.getRuntime().exec(script); p.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } public void clickOnDownloadIconReport(String fileName) { downloadIconReport.click(); //TODO Fix this // DataToolPage data = new DataToolPage(getDriver()); // data.saveImageHandle2(); FileChecker fileChecker = new FileChecker(); fileChecker.verifyFileIsDownloaded1(fileChecker.convertFileName(fileName)); } public void clickOnDownloadIconReportTrialUser() { if(getDriver().findElements(By.cssSelector("i.icon-c-download")).size() > 0){ downloadIconReport.click(); Assert.assertTrue(alertMessageDownload.isDisplayed()); cancelButtonModalWindowTrialDownload.click(); } else{ System.out.println("There is no download icon."); } // Assert.assertTrue(getDriver().findElements(By.cssSelector("i.icon-c-download")).size() == 0); } public void clickOnBackToPreviousPage() { backToPreviousPageButtonReport.click(); } public void clickOnPastVersionsToggler(){ if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ pastVersionsToggler.click(); } } public void verifyIfPastVersionTogglerIsExpanded(){ if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ Assert.assertTrue(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] a[class='btn active']")).size() == 1); } } public void verifyIfPastVersionTogglerIsCollapsed(){ if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ Assert.assertTrue(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] a[class='btn'] ")).size() == 1); } } public void clickOnOneItemFromLeftHandPanelAndVerifyName(int itemNumber){ int numberOfItemsDisplayed, itemNameNumber; numberOfItemsDisplayed = getDriver().findElements(By.cssSelector("div#scrollContent > ul > li.nav-header > ul > li")).size(); String itemTitle="", itemName= ""; if (numberOfItemsDisplayed > 0) { if (itemNumber <= numberOfItemsDisplayed && itemNumber > 0) { itemTitle = getDriver().findElement(By.cssSelector("div#scrollContent > ul > li.nav-header > ul > li:nth-child(" + itemNumber + ") > a")).getText(); getDriver().findElement(By.cssSelector("div#scrollContent > ul > li.nav-header > ul > li:nth-child(" + itemNumber + ") > a")).click(); itemNameNumber = itemNumber + 2; itemName = getDriver().findElement(By.cssSelector("article > div:nth-child(" + itemNameNumber + ") > h4")).getText(); Assert.assertTrue(itemName.contains(itemTitle)); } else { System.out.println("There aren't so many items displayed so clicking the first item"); itemTitle = getDriver().findElement(By.cssSelector("div#scrollContent > ul > li.nav-header > ul > li:nth-child(1) > a")).getText(); getDriver().findElement(By.cssSelector("div#scrollContent > ul > li.nav-header > ul > li:nth-child(1) > a")).click(); itemName = getDriver().findElement(By.cssSelector("article > div:nth-child(3) > h4")).getText(); Assert.assertTrue(itemName.contains(itemTitle)); } } else { System.out.println("There aren't any items in the left hand panel!"); } } public void clickOnEmailIcon(){ emailIconReport.click(); } //TODO Fix this // public void verifyActionIconsOfPastVersions(int pastVersionNumber){ // getDriver().manage().window().maximize(); // if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ // int numberOfPastVersions = getDriver().findElements(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div")).size(); // String pastVersionName; // if(numberOfPastVersions > 0){ // if(pastVersionNumber > 0 && pastVersionNumber < numberOfPastVersions){ // pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > h5 > a")).getText(); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-email")).click(); // EmailPopUpWindowPage email = new EmailPopUpWindowPage(getDriver()); // email.submitWithoutCompletingAnyField(); // email.completeFieldsAndClear(); // email.closeEmailIconPageTitle(); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div > div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-floppy")).click(); // waitUntilElementExists(By.cssSelector("div#result > div"), 15); // Assert.assertTrue(getDriver().findElement(By.cssSelector("div#result > div")).getText().contains("This report already exists in Saved Reports!") || (getDriver().findElement(By.cssSelector("div#result > div")).getText().contains("Report successfully saved!"))); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-download")).click(); // System.out.println("Download button accessed"); // performDownload(); // FileChecker fileChecker = new FileChecker(); // fileChecker.verifyFileIsDownloadedRelativesArchives(fileChecker.convertFileName(pastVersionName)); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-print")).click(); // System.out.println("Print button accessed"); // String winHandleBefore = getDriver().getWindowHandle(); // for (String winHandle : getDriver().getWindowHandles()) { // getDriver().switchTo().window(winHandle); // } // Assert.assertTrue(pastVersionName.contains(getDriver().findElement(By.cssSelector("div.padding-20 > h3#use")).getText())); // printPagePreviewCancel.click(); // getDriver().switchTo().window(winHandleBefore); // } // else{ // System.out.println("There are not so many past versions, so verify the first one!"); // pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > h5 > a")).getText(); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div > a > i.icon-c-email")).click(); // EmailPopUpWindowPage email = new EmailPopUpWindowPage(getDriver()); // email.submitWithoutCompletingAnyField(); // email.completeFieldsAndClear(); // email.closeEmailIconPageTitle(); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div > a > i.icon-c-floppy")).click(); // Assert.assertTrue(getDriver().findElement(By.cssSelector("div#result > div")).isDisplayed()); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div > a > i.icon-c-download")).click(); // performDownload(); // FileChecker fileChecker = new FileChecker(); // fileChecker.verifyFileIsDownloadedRelativesArchives(fileChecker.convertFileName(pastVersionName)); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div > a > i.icon-c-print")).click(); // String winHandleBefore = getDriver().getWindowHandle(); // for (String winHandle : getDriver().getWindowHandles()) { // getDriver().switchTo().window(winHandle); // } // Assert.assertTrue(pastVersionName.contains(getDriver().findElement(By.cssSelector("div.padding-20 > h3#use")).getText())); // printPagePreviewCancel.click(); // getDriver().switchTo().window(winHandleBefore); // } // } // else{ // System.out.println("There is no past version.."); // } // } // } // public void verifyActionIconsOfPastVersionsTrialUsers(int pastVersionNumber){ if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ getDriver().manage().window().maximize(); int numberOfPastVersions = getDriver().findElements(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div")).size(); if(numberOfPastVersions > 0){ if(pastVersionNumber > 0 && pastVersionNumber < numberOfPastVersions){ getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-download")).click(); Assert.assertTrue(alertMessageDownload.isDisplayed()); cancelButtonModalWindowTrialDownload.click(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div >a > i.icon-c-print")).click(); Assert.assertTrue(alertMessagePrint.isDisplayed()); cancelButtonModalWindowTrialPrint.click(); } else{ System.out.println("There are not so many past versions, so verify the first one!"); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div >a > i.icon-c-download")).click(); Assert.assertTrue(alertMessageDownload.isDisplayed()); cancelButtonModalWindowTrialDownload.click(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div >a > i.icon-c-print")).click(); Assert.assertTrue(alertMessagePrint.isDisplayed()); cancelButtonModalWindowTrialPrint.click(); } } else{ System.out.println("There is no past version.."); } } } public String verifyDownloadAndContactAccountManagerFromPastVersionsForTrialUser(int pastVersionNumber){ String pastVersionName = null; if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ getDriver().manage().window().maximize(); int numberOfPastVersions = getDriver().findElements(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div")).size(); if(numberOfPastVersions > 0){ if(pastVersionNumber > 0 && pastVersionNumber < numberOfPastVersions){ pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-download")).click(); Assert.assertTrue(alertMessageDownload.isDisplayed()); contactAccountManagementButtonTrialDownload.click(); } else{ System.out.println("There are not so many past versions, so verify the first one!"); pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div >a > i.icon-c-download")).click(); Assert.assertTrue(alertMessageDownload.isDisplayed()); contactAccountManagementButtonTrialDownload.click(); } } else{ System.out.println("There is no past version.."); } } return pastVersionName; } public String verifyPrintAndContactAccountManagerFromPastVersionsForTrialUser(int pastVersionNumber){ String pastVersionName = null; if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ getDriver().manage().window().maximize(); int numberOfPastVersions = getDriver().findElements(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div")).size(); if(numberOfPastVersions > 0){ if(pastVersionNumber > 0 && pastVersionNumber < numberOfPastVersions){ pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div >a > i.icon-c-print")).click(); Assert.assertTrue(alertMessagePrint.isDisplayed()); contactAccountManagementButtonTrialPrint.click(); } else{ System.out.println("There are not so many past versions, so verify the first one!"); pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div >a > i.icon-c-print")).click(); Assert.assertTrue(alertMessagePrint.isDisplayed()); contactAccountManagementButtonTrialPrint.click(); } } else{ System.out.println("There is no past version.."); } } return pastVersionName; } public void verifyReportDetailMediaActions() { element((getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-floppy")))).waitUntilPresent(); Assert.assertTrue(getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-floppy")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-email")).isDisplayed()); } public void verifyReportHoveredMediaActions(int reportNumber) { element(getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child("+reportNumber+") > div > div.tags"))).click(); System.out.println("clicked!"); element(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-floppy"))).waitUntilPresent(); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-floppy")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-email")).isDisplayed()); } public void verifyReportPreviewMediaActions() { Assert.assertTrue(getDriver().findElement(By.cssSelector("div#js-overflow > section > div > div:nth-child(1) > div > a > i.icon-c-floppy")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#js-overflow > section > div > div:nth-child(1) > div > a > i.icon-c-email")).isDisplayed()); } }
UTF-8
Java
41,762
java
SingleReportPage.java
Java
[]
null
[]
package bmo5.bmo5tests.bmo.pages; import java.io.IOException; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import bmo5.bmo5tests.tools.FileChecker; import bmo5.bmo5tests.tools.bmo.AbstractPage; public class SingleReportPage extends AbstractPage{ @FindBy(css = "section i.icon-c-cancel") @CacheLookup private WebElement printPagePreviewCancel; @FindBy(css = "div[class='btn-group btn-toolbar pull-right'] a > i.icon-c-email") @CacheLookup private WebElement emailIconReport; @FindBy(css = "div[class='btn-group btn-toolbar pull-right'] a > i.icon-c-floppy") @CacheLookup private WebElement saveIconReport; @FindBy(css = "div[class='btn-group btn-toolbar pull-right'] a > i.icon-c-download") @CacheLookup private WebElement downloadIconReport; @FindBy(css = "div[class='btn-group btn-toolbar pull-right'] > a > i.icon-c-print") @CacheLookup private WebElement printIconReport; @FindBy(css = "div[class='btn-toolbar pull-left'] > a") @CacheLookup private WebElement backToPreviousPageButtonReport; @FindBy(css = "div[class='pull-right drop-content-toggler'] > div > a") @CacheLookup private WebElement pastVersionsToggler; @FindBy(css = "div[class='pull-right drop-content-toggler'] > div > a > span") @CacheLookup private WebElement pastVersionsTogglerNumber; @FindBy(css = " div.page-wrap > div:nth-child(1) > div >div ") @CacheLookup private WebElement saveItemAfterOpening; @FindBy(css = "div#permission-enterprise-user strong") private WebElement alertMessageEnterprise; @FindBy(css = "div#permission-enterprise-user > div:nth-child(2) > button") private WebElement cancelButtonModalWindowEnterprise; @FindBy(css = "div#permission-modal-print strong") private WebElement alertMessagePrint; @FindBy(css = "div#permission-modal-print div:nth-child(2) > button") private WebElement cancelButtonModalWindowTrialPrint; @FindBy(css = "div#permission-modal-print div:nth-child(2) > a") private WebElement contactAccountManagementButtonTrialPrint; @FindBy(css = "div#permission-modal-pdf strong") private WebElement alertMessageDownload; @FindBy(css = "div#permission-modal-pdf div:nth-child(2) > button") private WebElement cancelButtonModalWindowTrialDownload; @FindBy(css = "div#permission-modal-pdf div:nth-child(2) > a") private WebElement contactAccountManagementButtonTrialDownload; public void clickOnEmailIconReportFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-email"); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-email"); } } else { System.out.println("There aren't any reports!"); } } public void clickOnSaveIconReportFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-floppy"); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-floppy"); } } else { System.out.println("There aren't any reports!"); } } public void verifyMediaActionOnHoveredReport(int reportNumber) { Actions tag = new Actions(getDriver()); tag.moveToElement(getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child("+reportNumber+") > div > div.tags"))).build().perform(); //element(getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child("+reportNumber+") > div > div.tags"))).click(); System.out.println("clicked!"); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-download")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-print")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-email")).isDisplayed()); } public void verifyMediaActionsOnReportView() { Assert.assertTrue(getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-download")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-print")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-email")).isDisplayed()); } public void verifyMediaActionInReportPreview() { Assert.assertTrue(getDriver().findElement(By.cssSelector("div#js-overflow > section > div > div:nth-child(1) > div > a > i.icon-c-download")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#js-overflow > section > div > div:nth-child(1) > div > a > i.icon-c-print")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#js-overflow > section > div > div:nth-child(1) > div > a > i.icon-c-email")).isDisplayed()); } //TODO Fix this // public void clickOnDownloadIconReportFromList(int reportNumber){ // int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); // String reportTitle=""; // if (numberOfReportsDisplayed > 0) { // if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { // elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-download"); // reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).getText(); // DataToolPage data = new DataToolPage(getDriver()); // data.saveImageHandle2(); // FileChecker fileChecker = new FileChecker(); // System.out.println(fileChecker.convertFileName(reportTitle)); // fileChecker.verifyFileIsDownloaded1(fileChecker.convertFileName(reportTitle)); // } else { // System.out.println("There aren't so many reports displayed so clicking the first report"); // elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-download"); // reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).getText(); // DataToolPage data = new DataToolPage(getDriver()); // data.saveImageHandle2(); // FileChecker fileChecker = new FileChecker(); // System.out.println(fileChecker.convertFileName(reportTitle)); // fileChecker.verifyFileIsDownloaded1(fileChecker.convertFileName(reportTitle)); // } // } else { // System.out.println("There aren't any reports!"); // } // } public void clickOnDownloadIconReportFromListTrialUser(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-download"); Assert.assertTrue(alertMessageDownload.isDisplayed()); cancelButtonModalWindowTrialDownload.click(); // Assert.assertTrue(getDriver().findElements(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-download")).size() == 0); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-download"); Assert.assertTrue(alertMessageDownload.isDisplayed()); cancelButtonModalWindowTrialDownload.click(); // Assert.assertTrue(getDriver().findElements(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-download")).size() == 0); } } else { System.out.println("There aren't any reports!"); } } public String clickOnDownloadIconReportFromListTrialUserAndVerifyContactAccountManager(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).getText(); elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-download"); Assert.assertTrue(alertMessageDownload.isDisplayed()); contactAccountManagementButtonTrialDownload.click(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).getText(); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-download"); Assert.assertTrue(alertMessageDownload.isDisplayed()); contactAccountManagementButtonTrialDownload.click(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public void clickOnPrintIconReportFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-print"); String winHandleBefore = getDriver().getWindowHandle(); for (String winHandle : getDriver().getWindowHandles()) { getDriver().switchTo().window(winHandle); } printPagePreviewCancel.click(); getDriver().switchTo().window(winHandleBefore); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-print"); String winHandleBefore = getDriver().getWindowHandle(); for (String winHandle : getDriver().getWindowHandles()) { getDriver().switchTo().window(winHandle); } printPagePreviewCancel.click(); getDriver().switchTo().window(winHandleBefore); } } else { System.out.println("There aren't any reports!"); } } public void clickOnPrintIconReportFromListTrialUser(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-print"); Assert.assertTrue(alertMessagePrint.isDisplayed()); cancelButtonModalWindowTrialPrint.click(); // Assert.assertTrue(getDriver().findElements(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-print")).size() == 0); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-print"); Assert.assertTrue(alertMessagePrint.isDisplayed()); cancelButtonModalWindowTrialPrint.click(); // Assert.assertTrue(getDriver().findElements(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-print")).size() == 0); } } else { System.out.println("There aren't any reports!"); } } public String clickOnPrintIconReportFromListTrialUserAndVerifyContactAccountManager(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).getText(); elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div:nth-child(1) > a > i.icon-c-print"); Assert.assertTrue(alertMessagePrint.isDisplayed()); contactAccountManagementButtonTrialPrint.click(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).getText(); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > a > i.icon-c-print"); Assert.assertTrue(alertMessagePrint.isDisplayed()); contactAccountManagementButtonTrialPrint.click(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public String clickOnPreviewReportFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(2) > div > a.btn.btn-link.preview-report"); waitUntilElementDoesntExist(By.cssSelector("div.affix.loading"),50); reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).getText(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div#sar-reports-container > div:nth-child(1) > div:nth-child(2) > div a[class='btn btn-link preview-report']"); reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).getText(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public String clickOnPreviewReportArchiveFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div.media-listing > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { waitABit(5000); elementClick("div.media-listing > div:nth-child( "+ reportNumber +") > div:nth-child(2) > div > a.btn.btn-link.preview-report.hide-actions"); reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child("+ reportNumber +") > div:nth-child(1) > div > h5 > a")).getText(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div.media-listing > div:nth-child(1) > div:nth-child(2) > div > a.btn.btn-link.preview-report"); reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(1) > div:nth-child(1) > div > h5 > a")).getText(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public String clickOnPreviewReportsFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div.media-listing > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { elementClick("div.media-listing > div:nth-child( "+ reportNumber +") > div:nth-child(2) > div > a.btn.btn-link.preview-report.hide-actions"); reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child("+ reportNumber +") > div:nth-child(1) > h5 > a")).getText(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); elementClick("div.media-listing > div:nth-child(1) > div:nth-child(2) > div > a.btn.btn-link.preview-report"); reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(1) > div:nth-child(1) > div > h5 > a")).getText(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } //TODO Fix this // public void verifyDownloadFromHoveredMediaActions(int reportNumber) { // String reportTitle=""; // int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div.media-listing > div")).size(); // if (numberOfReportsDisplayed > 0) { // if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { // waitABit(5000); // reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(" + reportNumber + ")> div:nth-child(1) > div > h5 > a")).getText(); // elementClick("div.media-listing > div:nth-child(" + reportNumber + ") div.media-actions a > i.icon-c-download"); // DataToolPage data = new DataToolPage(getDriver()); // data.saveImageHandle2(); // FileChecker file = new FileChecker(); // file.verifyFileIsDownloaded1(file.convertFileName(reportTitle)); // } else { // System.out.println("There aren't so many reports displayed so clicking the first report"); // reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(1)> div:nth-child(1) > div > h5 > a")).getText(); // elementClick("div.media-listing > div:nth-child(1) div.media-actions a > i.icon-c-download"); // DataToolPage data = new DataToolPage(getDriver()); // data.saveImageHandle2(); // FileChecker file = new FileChecker(); // file.verifyFileIsDownloaded1(file.convertFileName(reportTitle)); // } // } else { // System.out.println("There aren't any reports!"); // } // } public String clickOnOneReportFromList(int reportNumber){ int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div#sar-reports-container > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(" + reportNumber + ") > div:nth-child(1) > h5 > a")).click(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); reportTitle = getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child(1) > div:nth-child(1) > h5 > a")).click(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public String clickASpecialReportsFromListing(int reportNumber) { int numberOfReportsDisplayed = getDriver().findElements(By.cssSelector("div.media-listing > div")).size(); String reportTitle=""; if (numberOfReportsDisplayed > 0) { if (reportNumber <= numberOfReportsDisplayed && reportNumber > 0) { reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child("+ reportNumber +") > div:nth-child(1) > div > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child("+ reportNumber +") > div:nth-child(1) > div > h5 > a")).click(); } else { System.out.println("There aren't so many reports displayed so clicking the first report"); reportTitle = getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(1) > div:nth-child(1) > div > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div.media-listing > div:nth-child(1) > div:nth-child(1) > div > h5 > a")).click(); } } else { System.out.println("There aren't any reports!"); } return reportTitle; } public void clickOnSaveIconReport() { saveIconReport.click(); Assert.assertTrue(saveItemAfterOpening.getText().contains("The article already exists in Saved Content!")|| saveItemAfterOpening.getText().contains("This report already exists in Saved Reports!") || saveItemAfterOpening.getText().contains("Report successfully saved!") || saveItemAfterOpening.getText().contains("Sucessfully added the article to Saved Content")); } public void saveEnterpriseIconInsideReport() { saveIconReport.click(); } public void clickOnPrintIconReport(String reportName) { printIconReport.click(); String winHandleBefore = getDriver().getWindowHandle(); for (String winHandle : getDriver().getWindowHandles()) { getDriver().switchTo().window(winHandle); } Assert.assertTrue(getDriver().findElement(By.cssSelector("div.padding-20 > h3#use")).getText().contains(reportName)); printPagePreviewCancel.click(); getDriver().switchTo().window(winHandleBefore); } public void clickOnPrintIconReportTrialUser(){ if(getDriver().findElements(By.cssSelector("div[class='btn-group btn-toolbar pull-right'] > a > i.icon-c-print")).size() > 0){ printIconReport.click(); Assert.assertTrue(alertMessagePrint.isDisplayed()); cancelButtonModalWindowTrialPrint.click(); } else{ System.out.println("There is no print icon."); } // Assert.assertTrue(getDriver().findElements(By.cssSelector("div[class='btn-group btn-toolbar pull-right'] > a > i.icon-c-print")).size() == 0); } public void performDownload() { waitABit(2000); String script = "src\\test\\java\\drivers\\downloadTestScript.exe"; Process p; try { p = Runtime.getRuntime().exec(script); p.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } public void clickOnDownloadIconReport(String fileName) { downloadIconReport.click(); //TODO Fix this // DataToolPage data = new DataToolPage(getDriver()); // data.saveImageHandle2(); FileChecker fileChecker = new FileChecker(); fileChecker.verifyFileIsDownloaded1(fileChecker.convertFileName(fileName)); } public void clickOnDownloadIconReportTrialUser() { if(getDriver().findElements(By.cssSelector("i.icon-c-download")).size() > 0){ downloadIconReport.click(); Assert.assertTrue(alertMessageDownload.isDisplayed()); cancelButtonModalWindowTrialDownload.click(); } else{ System.out.println("There is no download icon."); } // Assert.assertTrue(getDriver().findElements(By.cssSelector("i.icon-c-download")).size() == 0); } public void clickOnBackToPreviousPage() { backToPreviousPageButtonReport.click(); } public void clickOnPastVersionsToggler(){ if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ pastVersionsToggler.click(); } } public void verifyIfPastVersionTogglerIsExpanded(){ if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ Assert.assertTrue(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] a[class='btn active']")).size() == 1); } } public void verifyIfPastVersionTogglerIsCollapsed(){ if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ Assert.assertTrue(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] a[class='btn'] ")).size() == 1); } } public void clickOnOneItemFromLeftHandPanelAndVerifyName(int itemNumber){ int numberOfItemsDisplayed, itemNameNumber; numberOfItemsDisplayed = getDriver().findElements(By.cssSelector("div#scrollContent > ul > li.nav-header > ul > li")).size(); String itemTitle="", itemName= ""; if (numberOfItemsDisplayed > 0) { if (itemNumber <= numberOfItemsDisplayed && itemNumber > 0) { itemTitle = getDriver().findElement(By.cssSelector("div#scrollContent > ul > li.nav-header > ul > li:nth-child(" + itemNumber + ") > a")).getText(); getDriver().findElement(By.cssSelector("div#scrollContent > ul > li.nav-header > ul > li:nth-child(" + itemNumber + ") > a")).click(); itemNameNumber = itemNumber + 2; itemName = getDriver().findElement(By.cssSelector("article > div:nth-child(" + itemNameNumber + ") > h4")).getText(); Assert.assertTrue(itemName.contains(itemTitle)); } else { System.out.println("There aren't so many items displayed so clicking the first item"); itemTitle = getDriver().findElement(By.cssSelector("div#scrollContent > ul > li.nav-header > ul > li:nth-child(1) > a")).getText(); getDriver().findElement(By.cssSelector("div#scrollContent > ul > li.nav-header > ul > li:nth-child(1) > a")).click(); itemName = getDriver().findElement(By.cssSelector("article > div:nth-child(3) > h4")).getText(); Assert.assertTrue(itemName.contains(itemTitle)); } } else { System.out.println("There aren't any items in the left hand panel!"); } } public void clickOnEmailIcon(){ emailIconReport.click(); } //TODO Fix this // public void verifyActionIconsOfPastVersions(int pastVersionNumber){ // getDriver().manage().window().maximize(); // if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ // int numberOfPastVersions = getDriver().findElements(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div")).size(); // String pastVersionName; // if(numberOfPastVersions > 0){ // if(pastVersionNumber > 0 && pastVersionNumber < numberOfPastVersions){ // pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > h5 > a")).getText(); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-email")).click(); // EmailPopUpWindowPage email = new EmailPopUpWindowPage(getDriver()); // email.submitWithoutCompletingAnyField(); // email.completeFieldsAndClear(); // email.closeEmailIconPageTitle(); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div > div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-floppy")).click(); // waitUntilElementExists(By.cssSelector("div#result > div"), 15); // Assert.assertTrue(getDriver().findElement(By.cssSelector("div#result > div")).getText().contains("This report already exists in Saved Reports!") || (getDriver().findElement(By.cssSelector("div#result > div")).getText().contains("Report successfully saved!"))); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-download")).click(); // System.out.println("Download button accessed"); // performDownload(); // FileChecker fileChecker = new FileChecker(); // fileChecker.verifyFileIsDownloadedRelativesArchives(fileChecker.convertFileName(pastVersionName)); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-print")).click(); // System.out.println("Print button accessed"); // String winHandleBefore = getDriver().getWindowHandle(); // for (String winHandle : getDriver().getWindowHandles()) { // getDriver().switchTo().window(winHandle); // } // Assert.assertTrue(pastVersionName.contains(getDriver().findElement(By.cssSelector("div.padding-20 > h3#use")).getText())); // printPagePreviewCancel.click(); // getDriver().switchTo().window(winHandleBefore); // } // else{ // System.out.println("There are not so many past versions, so verify the first one!"); // pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > h5 > a")).getText(); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div > a > i.icon-c-email")).click(); // EmailPopUpWindowPage email = new EmailPopUpWindowPage(getDriver()); // email.submitWithoutCompletingAnyField(); // email.completeFieldsAndClear(); // email.closeEmailIconPageTitle(); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div > a > i.icon-c-floppy")).click(); // Assert.assertTrue(getDriver().findElement(By.cssSelector("div#result > div")).isDisplayed()); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div > a > i.icon-c-download")).click(); // performDownload(); // FileChecker fileChecker = new FileChecker(); // fileChecker.verifyFileIsDownloadedRelativesArchives(fileChecker.convertFileName(pastVersionName)); // // getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); // getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div > a > i.icon-c-print")).click(); // String winHandleBefore = getDriver().getWindowHandle(); // for (String winHandle : getDriver().getWindowHandles()) { // getDriver().switchTo().window(winHandle); // } // Assert.assertTrue(pastVersionName.contains(getDriver().findElement(By.cssSelector("div.padding-20 > h3#use")).getText())); // printPagePreviewCancel.click(); // getDriver().switchTo().window(winHandleBefore); // } // } // else{ // System.out.println("There is no past version.."); // } // } // } // public void verifyActionIconsOfPastVersionsTrialUsers(int pastVersionNumber){ if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ getDriver().manage().window().maximize(); int numberOfPastVersions = getDriver().findElements(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div")).size(); if(numberOfPastVersions > 0){ if(pastVersionNumber > 0 && pastVersionNumber < numberOfPastVersions){ getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-download")).click(); Assert.assertTrue(alertMessageDownload.isDisplayed()); cancelButtonModalWindowTrialDownload.click(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div >a > i.icon-c-print")).click(); Assert.assertTrue(alertMessagePrint.isDisplayed()); cancelButtonModalWindowTrialPrint.click(); } else{ System.out.println("There are not so many past versions, so verify the first one!"); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div >a > i.icon-c-download")).click(); Assert.assertTrue(alertMessageDownload.isDisplayed()); cancelButtonModalWindowTrialDownload.click(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div >a > i.icon-c-print")).click(); Assert.assertTrue(alertMessagePrint.isDisplayed()); cancelButtonModalWindowTrialPrint.click(); } } else{ System.out.println("There is no past version.."); } } } public String verifyDownloadAndContactAccountManagerFromPastVersionsForTrialUser(int pastVersionNumber){ String pastVersionName = null; if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ getDriver().manage().window().maximize(); int numberOfPastVersions = getDriver().findElements(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div")).size(); if(numberOfPastVersions > 0){ if(pastVersionNumber > 0 && pastVersionNumber < numberOfPastVersions){ pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div > a > i.icon-c-download")).click(); Assert.assertTrue(alertMessageDownload.isDisplayed()); contactAccountManagementButtonTrialDownload.click(); } else{ System.out.println("There are not so many past versions, so verify the first one!"); pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div >a > i.icon-c-download")).click(); Assert.assertTrue(alertMessageDownload.isDisplayed()); contactAccountManagementButtonTrialDownload.click(); } } else{ System.out.println("There is no past version.."); } } return pastVersionName; } public String verifyPrintAndContactAccountManagerFromPastVersionsForTrialUser(int pastVersionNumber){ String pastVersionName = null; if(getDriver().findElements(By.cssSelector("div[class='pull-right drop-content-toggler'] > div > a > span")).size() == 1){ getDriver().manage().window().maximize(); int numberOfPastVersions = getDriver().findElements(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div")).size(); if(numberOfPastVersions > 0){ if(pastVersionNumber > 0 && pastVersionNumber < numberOfPastVersions){ pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(" + pastVersionNumber + ") > div > span:nth-of-type(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(" + pastVersionNumber + ") > h5 > div > div >a > i.icon-c-print")).click(); Assert.assertTrue(alertMessagePrint.isDisplayed()); contactAccountManagementButtonTrialPrint.click(); } else{ System.out.println("There are not so many past versions, so verify the first one!"); pastVersionName = getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > h5 > a")).getText(); getDriver().findElement(By.cssSelector("div[class='media-listing media-list-view-past-versions'] > div:nth-child(1) > div > span:nth-child(1)")).click(); getDriver().findElement(By.cssSelector("article > div.drop-content > div > div >div:nth-child(1) > h5 > div > div >a > i.icon-c-print")).click(); Assert.assertTrue(alertMessagePrint.isDisplayed()); contactAccountManagementButtonTrialPrint.click(); } } else{ System.out.println("There is no past version.."); } } return pastVersionName; } public void verifyReportDetailMediaActions() { element((getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-floppy")))).waitUntilPresent(); Assert.assertTrue(getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-floppy")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div.container-fluid > section:nth-child(5) > div:nth-child(1) > div:nth-child(2) > a> i.icon-c-email")).isDisplayed()); } public void verifyReportHoveredMediaActions(int reportNumber) { element(getDriver().findElement(By.cssSelector("div#sar-reports-container > div:nth-child("+reportNumber+") > div > div.tags"))).click(); System.out.println("clicked!"); element(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-floppy"))).waitUntilPresent(); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-floppy")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#sar-reports-container >div:nth-child("+reportNumber+") > div:nth-child(2) > div > a > i.icon-c-email")).isDisplayed()); } public void verifyReportPreviewMediaActions() { Assert.assertTrue(getDriver().findElement(By.cssSelector("div#js-overflow > section > div > div:nth-child(1) > div > a > i.icon-c-floppy")).isDisplayed()); Assert.assertTrue(getDriver().findElement(By.cssSelector("div#js-overflow > section > div > div:nth-child(1) > div > a > i.icon-c-email")).isDisplayed()); } }
41,762
0.693477
0.686078
682
59.234604
56.864922
365
false
false
0
0
0
0
72
0.004957
3.252199
false
false
7
b6066bebe326c3cb20bc01da4181e78bcabbc008
36,730,560,346,000
e95318ca12571cf2ed7109250d15b8919aec1977
/hahaxueche/src/main/java/com/hahaxueche/api/HHApiService.java
ca953656a4fc6ff4f4402fecb4e59531ed2d4804
[]
no_license
XiaosongTech/hahaxueche-android
https://github.com/XiaosongTech/hahaxueche-android
91a0ea82404ef65c1298609e1d36c9c297f85b04
ae7886f57d975f542356581f2685ec3f456c4cdf
refs/heads/master
2021-06-18T04:24:55.028000
2017-07-01T04:10:12
2017-07-01T04:10:12
49,932,832
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hahaxueche.api; import com.hahaxueche.BuildConfig; import com.hahaxueche.model.base.BaseBoolean; import com.hahaxueche.model.base.BaseModel; import com.hahaxueche.model.base.BaseSuccess; import com.hahaxueche.model.base.BaseValid; import com.hahaxueche.model.base.CityConstants; import com.hahaxueche.model.base.Constants; import com.hahaxueche.model.base.Field; import com.hahaxueche.model.base.ShortenUrl; import com.hahaxueche.model.base.UserIdentityParam; import com.hahaxueche.model.community.Article; import com.hahaxueche.model.course.ScheduleEvent; import com.hahaxueche.model.drivingSchool.DrivingSchool; import com.hahaxueche.model.examLib.Question; import com.hahaxueche.model.payment.BankCard; import com.hahaxueche.model.payment.PurchasedService; import com.hahaxueche.model.payment.Voucher; import com.hahaxueche.model.payment.WithdrawRecord; import com.hahaxueche.model.responseList.ArticleResponseList; import com.hahaxueche.model.responseList.CoachResponseList; import com.hahaxueche.model.responseList.DrivingSchoolResponseList; import com.hahaxueche.model.responseList.FieldResponseList; import com.hahaxueche.model.responseList.PartnerResponseList; import com.hahaxueche.model.responseList.ReferrerResponseList; import com.hahaxueche.model.responseList.ReviewResponseList; import com.hahaxueche.model.responseList.ScheduleEventResponseList; import com.hahaxueche.model.user.IdCardUrl; import com.hahaxueche.model.user.User; import com.hahaxueche.model.user.UserIdentityInfo; import com.hahaxueche.model.user.coach.Coach; import com.hahaxueche.model.user.coach.Follow; import com.hahaxueche.model.user.coach.Partner; import com.hahaxueche.model.user.coach.Review; import com.hahaxueche.model.user.employee.Adviser; import com.hahaxueche.model.user.identity.MarketingInfo; import com.hahaxueche.model.user.student.BookAddress; import com.hahaxueche.model.user.student.ExamResult; import com.hahaxueche.model.user.student.Student; import com.hahaxueche.util.HHLog; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Part; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.QueryMap; import retrofit2.http.Url; import rx.Observable; /** * Created by wangshirui on 16/9/8. */ public interface HHApiService { String baseUrl = BuildConfig.SERVER_URL + "/api/v1/"; @GET("constants") Observable<Constants> getConstants(); @FormUrlEncoded @POST("send_auth_token") Observable<BaseModel> getAuthToken(@FieldMap HashMap<String, Object> map); @FormUrlEncoded @POST("sessions") Observable<User> login(@FieldMap HashMap<String, Object> map); @FormUrlEncoded @POST("users/reset_password") Observable<BaseModel> resetPassword(@FieldMap HashMap<String, Object> map); @FormUrlEncoded @POST("users") Observable<User> createSession(@FieldMap HashMap<String, Object> map); @FormUrlEncoded @PUT("students/{id}") Observable<Student> completeUserInfo(@Path("id") String studentId, @Header("X-Access-Token") String accessToken, @FieldMap HashMap<String, Object> map); @GET("students/{id}") Observable<Student> getStudent(@Path("id") String studentId, @Header("X-Access-Token") String accessToken); @DELETE("sessions/{id}") Observable<BaseModel> logOut(@Path("id") String sessionId, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("sessions/access_token/valid") Observable<BaseValid> isValidToken(@Header("X-Access-Token") String accessToken, @FieldMap HashMap<String, Object> map); @Multipart @POST("students/{id}/avatar") Observable<Student> uploadAvatar(@Path("id") String studentId, @Header("X-Access-Token") String accessToken, @Part MultipartBody.Part file); @GET("coaches") Observable<CoachResponseList> getCoaches(@Query("page") int page, @Query("per_page") int perPage, @Query("license_type") String licenseType, @Query("city_id") int cityId, @Query("training_field_ids[]") ArrayList<String> fieldIdList, @Query("distance") String distance, @Query("user_location[]") ArrayList<String> locations, @Query("sort_by") int sortBy, @Query("student_id") String studentId, @Query("price_from") String startMoney, @Query("price_to") String endMoney, @Query("business_area") String businessArea, @Query("zone") String zone); @GET("coaches") Observable<CoachResponseList> getNearCoaches(@Query("page") int page, @Query("per_page") int perPage, @Query("city_id") int cityId, @Query("user_location[]") ArrayList<String> locations, @Query("sort_by") int sortBy); @GET("coaches") Observable<CoachResponseList> getFieldCoaches(@Query("page") int page, @Query("per_page") int perPage, @Query("city_id") int cityId, @Query("training_field_ids[]") ArrayList<String> fieldIdList, @Query("sort_by") int sortBy); @GET Observable<CoachResponseList> getCoaches(@Url String path); @GET("coaches") Observable<ArrayList<Coach>> getCoachesByKeyword(@Query("keyword") String keyword, @Query("city_id") int cityId); @GET("coaches/{id}") Observable<Coach> getCoach(@Path("id") String coachId, @Query("student_id") String studentId); @GET("users/reviews/{id}") Observable<ReviewResponseList> getReviews(@Path("id") String coachUserId, @Query("page") int page, @Query("per_page") int perPage); @GET Observable<ReviewResponseList> getReviews(@Url String path); @GET("users/follows/{id}") Observable<BaseBoolean> isFollow(@Path("id") String coachUserId, @Header("X-Access-Token") String accessToken); @POST("users/follows/{id}") Observable<Follow> follow(@Path("id") String coachUserId, @Header("X-Access-Token") String accessToken); @DELETE("users/follows/{id}") Observable<BaseModel> cancelFollow(@Path("id") String coachUserId, @Header("X-Access-Token") String accessToken); @GET("users/follows") Observable<CoachResponseList> getFollowList(@Query("page") int page, @Query("per_page") int perPage, @Header("X-Access-Token") String accessToken); @GET Observable<CoachResponseList> getFollowList(@Url String path); @FormUrlEncoded @POST("students/{studentId}/like/{coachId}") Observable<Coach> like(@Path("studentId") String studentId, @Path("coachId") String coachId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("charges") Observable<ResponseBody> createCharge(@FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("training_partners") Observable<PartnerResponseList> getPartners(@Query("page") int page, @Query("per_page") int perPage, @Query("license_type") String licenseType, @Query("price_limit") String price, @Query("city_id") int cityId, @Query("sort_by") int sortBy, @Query("student_id") String studentId); @GET Observable<PartnerResponseList> getPartners(@Url String path); @FormUrlEncoded @POST("students/{studentId}/liked_training_partners/{partnerId}") Observable<Partner> likePartner(@Path("studentId") String studentId, @Path("partnerId") String partnerId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("employees/advisers") Observable<Adviser> getAdviser(@Query("student_id") String studentId); @FormUrlEncoded @POST("users/reviews/{coachUserId}") Observable<Review> reviewCoach(@Path("coachUserId") String coachUserId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @PUT("students/purchased_service") Observable<PurchasedService> payStage(@FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("training_partners/{id}") Observable<Partner> getPartner(@Path("id") String partnerId); @FormUrlEncoded @POST("students/{id}/withdraw") Observable<BaseModel> withdrawBonus(@FieldMap HashMap<String, Object> map, @Path("id") String studentId, @Header("X-Access-Token") String accessToken); @GET("bank_cards/withdraw_records") Observable<ArrayList<WithdrawRecord>> getWithdrawRecords(@Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("bank_cards") Observable<BankCard> addBankCard(@FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("students/{id}/referees") Observable<ReferrerResponseList> getReferrers(@Path("id") String studentId, @Query("page") int page, @Query("per_page") int perPage, @Header("X-Access-Token") String accessToken); @GET Observable<ReferrerResponseList> getReferrers(@Url String path, @Header("X-Access-Token") String accessToken); @GET("articles") Observable<ArticleResponseList> getArticles(@Query("page") int page, @Query("per_page") int perPage, @Query("is_popular") String isPopular, @Query("category") String category, @Query("student_id") String studentId); @GET Observable<ArticleResponseList> getArticles(@Url String path); @GET("articles/{id}") Observable<Article> getArticle(@Path("id") String articleId); @POST("students/{studentId}/liked_articles/{articleId}") Observable<Article> likeArticle(@Path("studentId") String studentId, @Path("articleId") String articleId, @Query("like") int like, @Header("X-Access-Token") String accessToken); @POST("articles/{articleId}/comments") Observable<Article> commentArticle(@Path("articleId") String articleId, @Query("student_id") String studentId, @Query("content") String content, @Header("X-Access-Token") String accessToken); @GET("articles/headline") Observable<Article> getHeadline(@Query("student_id") String studentId); @POST("students/{studentId}/{scheduleEventId}/schedule") Observable<ScheduleEvent> bookSchedule(@Path("studentId") String studentId, @Path("scheduleEventId") String scheduleEventId, @Header("X-Access-Token") String accessToken); @GET("students/{id}/course_schedules") Observable<ScheduleEventResponseList> getSchedules(@Path("id") String studentId, @Query("page") int page, @Query("per_page") int perPage, @Query("booked") int booked, @Header("X-Access-Token") String accessToken); @GET Observable<ScheduleEventResponseList> getSchedules(@Url String path, @Header("X-Access-Token") String accessToken); @POST("students/{studentId}/{scheduleEventId}/unschedule") Observable<BaseModel> cancelSchedule(@Path("studentId") String studentId, @Path("scheduleEventId") String scheduleEventId, @Header("X-Access-Token") String accessToken); @POST("students/{studentId}/{scheduleEventId}/review_schedule_event") Observable<Review> reviewSchedule(@Path("studentId") String studentId, @Path("scheduleEventId") String scheduleEventId, @Query("rating") float rating, @Header("X-Access-Token") String accessToken); @GET("students/{id}/vouchers") Observable<ArrayList<Voucher>> getAvailableVouchers(@Path("id") String studentId, @Query("coach_id") String coachId, @Query("cumulative") String cumulative, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("vouchers") Observable<Voucher> addVoucher(@FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @Multipart @POST("students/{id}/id_card") Observable<Response<IdCardUrl>> uploadIdCard(@Path("id") String studentId, @Header("X-Access-Token") String accessToken, @Part MultipartBody.Part file, @QueryMap HashMap<String, Object> map); @GET("students/{id}/agreement") Observable<Response<IdCardUrl>> createAgreement(@Path("id") String studentId, @Header("X-Access-Token") String accessToken); @POST("students/{id}/agreement") Observable<Student> signAgreement(@Path("id") String studentId, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("students/{id}/agreement_mail") Observable<BaseSuccess> sendAgreementEmail(@Path("id") String studentId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("students/{id}/exam_results") Observable<ExamResult> submitExamResult(@Path("id") String studentId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("students/{id}/exam_results") Observable<ArrayList<ExamResult>> getExamResults(@Path("id") String studentId, @Query("from") int fromScore, @Query("course") int course, @Header("X-Access-Token") String accessToken); @GET("exam_questions") Observable<ArrayList<Question>> getQuestions(@Query("course") int course); @GET Observable<ArrayList<ShortenUrl>> shortenUrl(@Url String url); @POST("address_books") Observable<String> uploadContacts(@Body BookAddress bookAddress); @GET("marketing_information") Observable<MarketingInfo> convertPromoCode(@Query("channel_id") String channelId, @Query("promo_code") String promoCode); @FormUrlEncoded @POST("students/{id}/id_card_info") Observable<BaseSuccess> uploadIdCard(@Path("id") String studentId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("students/{id}/insurance_services") Observable<ResponseBody> createInsuranceCharge(@Path("id") String studentId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @POST("students/{id}/insurance_services/hmb") Observable<Response<Student>> claimInsurance(@Path("id") String studentId, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("groupons") Observable<ResponseBody> getPrepayCharge(@FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("cities/{id}") Observable<CityConstants> getCityConstant(@Path("id") int cityId); @GET("fields") Observable<FieldResponseList> getFields(@Query("city_id") int cityId, @Query("driving_school_id") String drivingSchoolId); @POST("user_identities") Observable<UserIdentityInfo> getUserIdentity(@Body UserIdentityParam param); @GET("driving_schools") Observable<DrivingSchoolResponseList> getDrivingSchools(@Query("page") int page, @Query("per_page") int perPage, @Query("license_type") String licenseType, @Query("city_id") int cityId, @Query("distance") String distance, @Query("user_location[]") ArrayList<String> locations, @Query("sort_by") String sortBy, @Query("price_from") String startMoney, @Query("price_to") String endMoney, @Query("business_area") String businessArea, @Query("zone") String zone, @Query("order") String order); @GET Observable<DrivingSchoolResponseList> getDrivingSchools(@Url String path); @GET("driving_schools/{id}") Observable<DrivingSchool> getDrivingSchoolDetail(@Path("id") int drivingSchoolId); @GET("driving_schools/{id}/reviews") Observable<ReviewResponseList> getDrivingSchoolReviews(@Path("id") int drivingSchoolId, @Query("page") int page, @Query("per_page") int perPage); @GET("driving_schools") Observable<DrivingSchoolResponseList> getDrivingSchoolsByKeyword(@Query("name") String keyword, @Query("city_id") int cityId, @Query("page") int page, @Query("per_page") int perPage); class Factory { public static Retrofit getRetrofit() { HHLog.v("baseUrl -> " + baseUrl); OkHttpClient httpClient = new OkHttpClient(); if (BuildConfig.DEBUG) { //添加网络请求日志拦截 HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient = new OkHttpClient.Builder().addInterceptor(logging).build(); } return new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(httpClient) .build(); } public static HHApiService create() { return getRetrofit().create(HHApiService.class); } public static HHApiService createWithNoConverter() { HHLog.v("baseUrl -> " + baseUrl); OkHttpClient httpClient = new OkHttpClient(); if (BuildConfig.DEBUG) { //添加网络请求日志拦截 HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient = new OkHttpClient.Builder().addInterceptor(logging).build(); } Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(httpClient) .build(); return retrofit.create(HHApiService.class); } } }
UTF-8
Java
18,693
java
HHApiService.java
Java
[ { "context": "http.Url;\nimport rx.Observable;\n\n/**\n * Created by wangshirui on 16/9/8.\n */\npublic interface HHApiService {\n ", "end": 2843, "score": 0.9996640086174011, "start": 2833, "tag": "USERNAME", "value": "wangshirui" } ]
null
[]
package com.hahaxueche.api; import com.hahaxueche.BuildConfig; import com.hahaxueche.model.base.BaseBoolean; import com.hahaxueche.model.base.BaseModel; import com.hahaxueche.model.base.BaseSuccess; import com.hahaxueche.model.base.BaseValid; import com.hahaxueche.model.base.CityConstants; import com.hahaxueche.model.base.Constants; import com.hahaxueche.model.base.Field; import com.hahaxueche.model.base.ShortenUrl; import com.hahaxueche.model.base.UserIdentityParam; import com.hahaxueche.model.community.Article; import com.hahaxueche.model.course.ScheduleEvent; import com.hahaxueche.model.drivingSchool.DrivingSchool; import com.hahaxueche.model.examLib.Question; import com.hahaxueche.model.payment.BankCard; import com.hahaxueche.model.payment.PurchasedService; import com.hahaxueche.model.payment.Voucher; import com.hahaxueche.model.payment.WithdrawRecord; import com.hahaxueche.model.responseList.ArticleResponseList; import com.hahaxueche.model.responseList.CoachResponseList; import com.hahaxueche.model.responseList.DrivingSchoolResponseList; import com.hahaxueche.model.responseList.FieldResponseList; import com.hahaxueche.model.responseList.PartnerResponseList; import com.hahaxueche.model.responseList.ReferrerResponseList; import com.hahaxueche.model.responseList.ReviewResponseList; import com.hahaxueche.model.responseList.ScheduleEventResponseList; import com.hahaxueche.model.user.IdCardUrl; import com.hahaxueche.model.user.User; import com.hahaxueche.model.user.UserIdentityInfo; import com.hahaxueche.model.user.coach.Coach; import com.hahaxueche.model.user.coach.Follow; import com.hahaxueche.model.user.coach.Partner; import com.hahaxueche.model.user.coach.Review; import com.hahaxueche.model.user.employee.Adviser; import com.hahaxueche.model.user.identity.MarketingInfo; import com.hahaxueche.model.user.student.BookAddress; import com.hahaxueche.model.user.student.ExamResult; import com.hahaxueche.model.user.student.Student; import com.hahaxueche.util.HHLog; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Part; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.QueryMap; import retrofit2.http.Url; import rx.Observable; /** * Created by wangshirui on 16/9/8. */ public interface HHApiService { String baseUrl = BuildConfig.SERVER_URL + "/api/v1/"; @GET("constants") Observable<Constants> getConstants(); @FormUrlEncoded @POST("send_auth_token") Observable<BaseModel> getAuthToken(@FieldMap HashMap<String, Object> map); @FormUrlEncoded @POST("sessions") Observable<User> login(@FieldMap HashMap<String, Object> map); @FormUrlEncoded @POST("users/reset_password") Observable<BaseModel> resetPassword(@FieldMap HashMap<String, Object> map); @FormUrlEncoded @POST("users") Observable<User> createSession(@FieldMap HashMap<String, Object> map); @FormUrlEncoded @PUT("students/{id}") Observable<Student> completeUserInfo(@Path("id") String studentId, @Header("X-Access-Token") String accessToken, @FieldMap HashMap<String, Object> map); @GET("students/{id}") Observable<Student> getStudent(@Path("id") String studentId, @Header("X-Access-Token") String accessToken); @DELETE("sessions/{id}") Observable<BaseModel> logOut(@Path("id") String sessionId, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("sessions/access_token/valid") Observable<BaseValid> isValidToken(@Header("X-Access-Token") String accessToken, @FieldMap HashMap<String, Object> map); @Multipart @POST("students/{id}/avatar") Observable<Student> uploadAvatar(@Path("id") String studentId, @Header("X-Access-Token") String accessToken, @Part MultipartBody.Part file); @GET("coaches") Observable<CoachResponseList> getCoaches(@Query("page") int page, @Query("per_page") int perPage, @Query("license_type") String licenseType, @Query("city_id") int cityId, @Query("training_field_ids[]") ArrayList<String> fieldIdList, @Query("distance") String distance, @Query("user_location[]") ArrayList<String> locations, @Query("sort_by") int sortBy, @Query("student_id") String studentId, @Query("price_from") String startMoney, @Query("price_to") String endMoney, @Query("business_area") String businessArea, @Query("zone") String zone); @GET("coaches") Observable<CoachResponseList> getNearCoaches(@Query("page") int page, @Query("per_page") int perPage, @Query("city_id") int cityId, @Query("user_location[]") ArrayList<String> locations, @Query("sort_by") int sortBy); @GET("coaches") Observable<CoachResponseList> getFieldCoaches(@Query("page") int page, @Query("per_page") int perPage, @Query("city_id") int cityId, @Query("training_field_ids[]") ArrayList<String> fieldIdList, @Query("sort_by") int sortBy); @GET Observable<CoachResponseList> getCoaches(@Url String path); @GET("coaches") Observable<ArrayList<Coach>> getCoachesByKeyword(@Query("keyword") String keyword, @Query("city_id") int cityId); @GET("coaches/{id}") Observable<Coach> getCoach(@Path("id") String coachId, @Query("student_id") String studentId); @GET("users/reviews/{id}") Observable<ReviewResponseList> getReviews(@Path("id") String coachUserId, @Query("page") int page, @Query("per_page") int perPage); @GET Observable<ReviewResponseList> getReviews(@Url String path); @GET("users/follows/{id}") Observable<BaseBoolean> isFollow(@Path("id") String coachUserId, @Header("X-Access-Token") String accessToken); @POST("users/follows/{id}") Observable<Follow> follow(@Path("id") String coachUserId, @Header("X-Access-Token") String accessToken); @DELETE("users/follows/{id}") Observable<BaseModel> cancelFollow(@Path("id") String coachUserId, @Header("X-Access-Token") String accessToken); @GET("users/follows") Observable<CoachResponseList> getFollowList(@Query("page") int page, @Query("per_page") int perPage, @Header("X-Access-Token") String accessToken); @GET Observable<CoachResponseList> getFollowList(@Url String path); @FormUrlEncoded @POST("students/{studentId}/like/{coachId}") Observable<Coach> like(@Path("studentId") String studentId, @Path("coachId") String coachId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("charges") Observable<ResponseBody> createCharge(@FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("training_partners") Observable<PartnerResponseList> getPartners(@Query("page") int page, @Query("per_page") int perPage, @Query("license_type") String licenseType, @Query("price_limit") String price, @Query("city_id") int cityId, @Query("sort_by") int sortBy, @Query("student_id") String studentId); @GET Observable<PartnerResponseList> getPartners(@Url String path); @FormUrlEncoded @POST("students/{studentId}/liked_training_partners/{partnerId}") Observable<Partner> likePartner(@Path("studentId") String studentId, @Path("partnerId") String partnerId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("employees/advisers") Observable<Adviser> getAdviser(@Query("student_id") String studentId); @FormUrlEncoded @POST("users/reviews/{coachUserId}") Observable<Review> reviewCoach(@Path("coachUserId") String coachUserId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @PUT("students/purchased_service") Observable<PurchasedService> payStage(@FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("training_partners/{id}") Observable<Partner> getPartner(@Path("id") String partnerId); @FormUrlEncoded @POST("students/{id}/withdraw") Observable<BaseModel> withdrawBonus(@FieldMap HashMap<String, Object> map, @Path("id") String studentId, @Header("X-Access-Token") String accessToken); @GET("bank_cards/withdraw_records") Observable<ArrayList<WithdrawRecord>> getWithdrawRecords(@Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("bank_cards") Observable<BankCard> addBankCard(@FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("students/{id}/referees") Observable<ReferrerResponseList> getReferrers(@Path("id") String studentId, @Query("page") int page, @Query("per_page") int perPage, @Header("X-Access-Token") String accessToken); @GET Observable<ReferrerResponseList> getReferrers(@Url String path, @Header("X-Access-Token") String accessToken); @GET("articles") Observable<ArticleResponseList> getArticles(@Query("page") int page, @Query("per_page") int perPage, @Query("is_popular") String isPopular, @Query("category") String category, @Query("student_id") String studentId); @GET Observable<ArticleResponseList> getArticles(@Url String path); @GET("articles/{id}") Observable<Article> getArticle(@Path("id") String articleId); @POST("students/{studentId}/liked_articles/{articleId}") Observable<Article> likeArticle(@Path("studentId") String studentId, @Path("articleId") String articleId, @Query("like") int like, @Header("X-Access-Token") String accessToken); @POST("articles/{articleId}/comments") Observable<Article> commentArticle(@Path("articleId") String articleId, @Query("student_id") String studentId, @Query("content") String content, @Header("X-Access-Token") String accessToken); @GET("articles/headline") Observable<Article> getHeadline(@Query("student_id") String studentId); @POST("students/{studentId}/{scheduleEventId}/schedule") Observable<ScheduleEvent> bookSchedule(@Path("studentId") String studentId, @Path("scheduleEventId") String scheduleEventId, @Header("X-Access-Token") String accessToken); @GET("students/{id}/course_schedules") Observable<ScheduleEventResponseList> getSchedules(@Path("id") String studentId, @Query("page") int page, @Query("per_page") int perPage, @Query("booked") int booked, @Header("X-Access-Token") String accessToken); @GET Observable<ScheduleEventResponseList> getSchedules(@Url String path, @Header("X-Access-Token") String accessToken); @POST("students/{studentId}/{scheduleEventId}/unschedule") Observable<BaseModel> cancelSchedule(@Path("studentId") String studentId, @Path("scheduleEventId") String scheduleEventId, @Header("X-Access-Token") String accessToken); @POST("students/{studentId}/{scheduleEventId}/review_schedule_event") Observable<Review> reviewSchedule(@Path("studentId") String studentId, @Path("scheduleEventId") String scheduleEventId, @Query("rating") float rating, @Header("X-Access-Token") String accessToken); @GET("students/{id}/vouchers") Observable<ArrayList<Voucher>> getAvailableVouchers(@Path("id") String studentId, @Query("coach_id") String coachId, @Query("cumulative") String cumulative, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("vouchers") Observable<Voucher> addVoucher(@FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @Multipart @POST("students/{id}/id_card") Observable<Response<IdCardUrl>> uploadIdCard(@Path("id") String studentId, @Header("X-Access-Token") String accessToken, @Part MultipartBody.Part file, @QueryMap HashMap<String, Object> map); @GET("students/{id}/agreement") Observable<Response<IdCardUrl>> createAgreement(@Path("id") String studentId, @Header("X-Access-Token") String accessToken); @POST("students/{id}/agreement") Observable<Student> signAgreement(@Path("id") String studentId, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("students/{id}/agreement_mail") Observable<BaseSuccess> sendAgreementEmail(@Path("id") String studentId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("students/{id}/exam_results") Observable<ExamResult> submitExamResult(@Path("id") String studentId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("students/{id}/exam_results") Observable<ArrayList<ExamResult>> getExamResults(@Path("id") String studentId, @Query("from") int fromScore, @Query("course") int course, @Header("X-Access-Token") String accessToken); @GET("exam_questions") Observable<ArrayList<Question>> getQuestions(@Query("course") int course); @GET Observable<ArrayList<ShortenUrl>> shortenUrl(@Url String url); @POST("address_books") Observable<String> uploadContacts(@Body BookAddress bookAddress); @GET("marketing_information") Observable<MarketingInfo> convertPromoCode(@Query("channel_id") String channelId, @Query("promo_code") String promoCode); @FormUrlEncoded @POST("students/{id}/id_card_info") Observable<BaseSuccess> uploadIdCard(@Path("id") String studentId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("students/{id}/insurance_services") Observable<ResponseBody> createInsuranceCharge(@Path("id") String studentId, @FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @POST("students/{id}/insurance_services/hmb") Observable<Response<Student>> claimInsurance(@Path("id") String studentId, @Header("X-Access-Token") String accessToken); @FormUrlEncoded @POST("groupons") Observable<ResponseBody> getPrepayCharge(@FieldMap HashMap<String, Object> map, @Header("X-Access-Token") String accessToken); @GET("cities/{id}") Observable<CityConstants> getCityConstant(@Path("id") int cityId); @GET("fields") Observable<FieldResponseList> getFields(@Query("city_id") int cityId, @Query("driving_school_id") String drivingSchoolId); @POST("user_identities") Observable<UserIdentityInfo> getUserIdentity(@Body UserIdentityParam param); @GET("driving_schools") Observable<DrivingSchoolResponseList> getDrivingSchools(@Query("page") int page, @Query("per_page") int perPage, @Query("license_type") String licenseType, @Query("city_id") int cityId, @Query("distance") String distance, @Query("user_location[]") ArrayList<String> locations, @Query("sort_by") String sortBy, @Query("price_from") String startMoney, @Query("price_to") String endMoney, @Query("business_area") String businessArea, @Query("zone") String zone, @Query("order") String order); @GET Observable<DrivingSchoolResponseList> getDrivingSchools(@Url String path); @GET("driving_schools/{id}") Observable<DrivingSchool> getDrivingSchoolDetail(@Path("id") int drivingSchoolId); @GET("driving_schools/{id}/reviews") Observable<ReviewResponseList> getDrivingSchoolReviews(@Path("id") int drivingSchoolId, @Query("page") int page, @Query("per_page") int perPage); @GET("driving_schools") Observable<DrivingSchoolResponseList> getDrivingSchoolsByKeyword(@Query("name") String keyword, @Query("city_id") int cityId, @Query("page") int page, @Query("per_page") int perPage); class Factory { public static Retrofit getRetrofit() { HHLog.v("baseUrl -> " + baseUrl); OkHttpClient httpClient = new OkHttpClient(); if (BuildConfig.DEBUG) { //添加网络请求日志拦截 HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient = new OkHttpClient.Builder().addInterceptor(logging).build(); } return new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(httpClient) .build(); } public static HHApiService create() { return getRetrofit().create(HHApiService.class); } public static HHApiService createWithNoConverter() { HHLog.v("baseUrl -> " + baseUrl); OkHttpClient httpClient = new OkHttpClient(); if (BuildConfig.DEBUG) { //添加网络请求日志拦截 HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient = new OkHttpClient.Builder().addInterceptor(logging).build(); } Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(httpClient) .build(); return retrofit.create(HHApiService.class); } } }
18,693
0.68493
0.683483
377
48.477455
48.121422
195
false
false
0
0
0
0
0
0
0.779841
false
false
7
0aa425582de987ee695c617307c6fb7cc49eaeb2
34,205,119,583,079
a48999f09731128334e5052e448ad5a7ec95ad71
/server/src/com/deadlyboundaries/server/model/ServerWorldManager.java
86ee1d5748c382787f2f1189623d3e2bd97e51cf
[ "MIT", "CC0-1.0" ]
permissive
payne911/libgdx-desktop-multiplayer-template
https://github.com/payne911/libgdx-desktop-multiplayer-template
c5df09e9a15dd1c0b6652851d8b2b6c59140a275
8f39d765aa7b6313b3919e121e2c5ba368cf935a
refs/heads/master
2023-01-24T14:01:39.980000
2020-11-24T01:10:04
2020-11-24T01:10:04
302,441,136
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.deadlyboundaries.server.model; import com.deadlyboundaries.server.factories.EnemySpawner; import com.deadlyboundaries.common.model.entities.dynamic.enemies.Enemy; import com.deadlyboundaries.common.state.GameWorld; import com.deadlyboundaries.common.state.GameWorldManager; import java.util.ArrayList; import lombok.Getter; public class ServerWorldManager extends GameWorldManager { @Getter private final EnemySpawner enemySpawner; @Getter private final ArrayList<Enemy> spawnedEnemies = new ArrayList<>(); public ServerWorldManager(GameWorld initialGameWorld) { super(initialGameWorld); this.enemySpawner = new EnemySpawner(initialGameWorld.getLocalGameState()); } @Override public void updateGameState(float delta) { spawnEnemies(delta); commonGameStateUpdate(delta); } private void spawnEnemies(float delta) { var spawned = enemySpawner.update(delta, mutableGameWorld.getLevel().getAllSpawnPoints()); spawnedEnemies.addAll(spawned); } public ArrayList<Enemy> extractNewEnemies() { ArrayList<Enemy> returnedList = new ArrayList<>(spawnedEnemies); spawnedEnemies.clear(); return returnedList; } }
UTF-8
Java
1,242
java
ServerWorldManager.java
Java
[]
null
[]
package com.deadlyboundaries.server.model; import com.deadlyboundaries.server.factories.EnemySpawner; import com.deadlyboundaries.common.model.entities.dynamic.enemies.Enemy; import com.deadlyboundaries.common.state.GameWorld; import com.deadlyboundaries.common.state.GameWorldManager; import java.util.ArrayList; import lombok.Getter; public class ServerWorldManager extends GameWorldManager { @Getter private final EnemySpawner enemySpawner; @Getter private final ArrayList<Enemy> spawnedEnemies = new ArrayList<>(); public ServerWorldManager(GameWorld initialGameWorld) { super(initialGameWorld); this.enemySpawner = new EnemySpawner(initialGameWorld.getLocalGameState()); } @Override public void updateGameState(float delta) { spawnEnemies(delta); commonGameStateUpdate(delta); } private void spawnEnemies(float delta) { var spawned = enemySpawner.update(delta, mutableGameWorld.getLevel().getAllSpawnPoints()); spawnedEnemies.addAll(spawned); } public ArrayList<Enemy> extractNewEnemies() { ArrayList<Enemy> returnedList = new ArrayList<>(spawnedEnemies); spawnedEnemies.clear(); return returnedList; } }
1,242
0.742351
0.742351
39
30.846153
27.318199
98
false
false
0
0
0
0
0
0
0.487179
false
false
7
85d3823366539bd9e21754d7e081c7a5033b1bd3
34,574,486,770,962
9412cc1415e118c27cd1b0047c9f06d7d32e026d
/src/Ediable.java
94d2106eb1de3a3aaaf63a095a97e00226661f62
[]
no_license
duyettwyler2k/L-p-Animal-v-interface-Edible
https://github.com/duyettwyler2k/L-p-Animal-v-interface-Edible
fbf5159be7ddd828fc70730e9de73a26792705c8
1274ca8f63594308060dbfd0db587de03fc24927
refs/heads/master
2023-04-07T09:57:49.548000
2021-04-12T09:29:44
2021-04-12T09:29:44
357,133,960
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public interface Ediable { String howToEat(); }
UTF-8
Java
52
java
Ediable.java
Java
[]
null
[]
public interface Ediable { String howToEat(); }
52
0.692308
0.692308
3
16.333334
10.964589
26
false
false
0
0
0
0
0
0
0.333333
false
false
7
3386499800fc9abb149cfdef7b3c915061b3af7a
9,904,194,631,795
ff254eff16e070fc68a8a1ae51355c6c73f764f8
/src/main/java/com/wacai/bc/raft/transport/netty/NettyTls.java
40539ad653ca6643a8f9980176d37484efb8b485
[]
no_license
flym/open-chord
https://github.com/flym/open-chord
0cb83675c7a15e061f5248c7f265743af67c46eb
ab599ccd5d020b07636c2538bd6f0d00fe8629b5
refs/heads/master
2017-11-03T20:21:17.879000
2017-11-02T08:29:53
2017-11-02T08:29:53
96,792,073
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wacai.bc.raft.transport.netty; import de.uniba.wiai.lspi.util.Asserts; import lombok.extern.slf4j.Slf4j; import javax.net.ssl.*; import java.io.File; import java.io.FileInputStream; import java.security.KeyStore; /** * 使用netty实现相应的ssl处理 */ @Slf4j final class NettyTls { private NettyOptions properties; public NettyTls(NettyOptions properties) { this.properties = properties; } /** 初始化相应的ssl引擎 */ public SSLEngine initSslEngine(boolean client) throws Exception { // Load the keystore KeyStore keyStore = loadKeystore(properties.sslKeyStorePath(), properties.sslKeyStorePassword()); // Setup the keyManager to use our keystore KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyStoreKeyPass(properties)); // Setup the Trust keystore KeyStore trustStore; if(properties.sslTrustStorePath() != null) { // Use the separate Trust keystore log.debug("Using separate trust store"); trustStore = loadKeystore(properties.sslTrustStorePath(), properties.sslTrustStorePassword()); } else { // Reuse the existing keystore trustStore = keyStore; log.debug("Using key store as trust store"); } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(client); sslEngine.setWantClientAuth(true); sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols()); sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites()); sslEngine.setEnableSessionCreation(true); return sslEngine; } private KeyStore loadKeystore(String path, String password) throws Exception { Asserts.notNull(path, "Path"); File file = new File(path); log.debug("Using JKS at {}", file.getCanonicalPath()); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(file.getCanonicalPath()), password.toCharArray()); return ks; } private char[] keyStoreKeyPass(NettyOptions properties) throws Exception { if(properties.sslKeyStoreKeyPassword() != null) { return properties.sslKeyStoreKeyPassword().toCharArray(); } else { return properties.sslKeyStorePassword().toCharArray(); } } }
UTF-8
Java
2,937
java
NettyTls.java
Java
[]
null
[]
package com.wacai.bc.raft.transport.netty; import de.uniba.wiai.lspi.util.Asserts; import lombok.extern.slf4j.Slf4j; import javax.net.ssl.*; import java.io.File; import java.io.FileInputStream; import java.security.KeyStore; /** * 使用netty实现相应的ssl处理 */ @Slf4j final class NettyTls { private NettyOptions properties; public NettyTls(NettyOptions properties) { this.properties = properties; } /** 初始化相应的ssl引擎 */ public SSLEngine initSslEngine(boolean client) throws Exception { // Load the keystore KeyStore keyStore = loadKeystore(properties.sslKeyStorePath(), properties.sslKeyStorePassword()); // Setup the keyManager to use our keystore KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyStoreKeyPass(properties)); // Setup the Trust keystore KeyStore trustStore; if(properties.sslTrustStorePath() != null) { // Use the separate Trust keystore log.debug("Using separate trust store"); trustStore = loadKeystore(properties.sslTrustStorePath(), properties.sslTrustStorePassword()); } else { // Reuse the existing keystore trustStore = keyStore; log.debug("Using key store as trust store"); } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(client); sslEngine.setWantClientAuth(true); sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols()); sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites()); sslEngine.setEnableSessionCreation(true); return sslEngine; } private KeyStore loadKeystore(String path, String password) throws Exception { Asserts.notNull(path, "Path"); File file = new File(path); log.debug("Using JKS at {}", file.getCanonicalPath()); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(file.getCanonicalPath()), password.toCharArray()); return ks; } private char[] keyStoreKeyPass(NettyOptions properties) throws Exception { if(properties.sslKeyStoreKeyPassword() != null) { return properties.sslKeyStoreKeyPassword().toCharArray(); } else { return properties.sslKeyStorePassword().toCharArray(); } } }
2,937
0.693076
0.692043
79
35.746834
31.26387
125
false
false
0
0
0
0
0
0
0.594937
false
false
7
05b49f1208297679b7c9f954dd76c4c6b6fdcc1e
37,460,704,770,913
964244c9dc90f59ce5a38fb977b95c6cc27d4082
/framework/src/com/framework/tabs/persistence/model/Roles.java
9ddcd0373f98099e3e9500790c59eadd33abefce
[]
no_license
brainmemo/tools
https://github.com/brainmemo/tools
8e0039bf7e60cb22a3d673b09396cdbdc15a74f6
cd25adeca6c7bf051a39fee64a40d0bfc8312e32
refs/heads/main
2023-03-26T16:50:30.515000
2021-03-28T20:50:35
2021-03-28T20:50:35
326,480,575
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.framework.tabs.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import lombok.Data; import lombok.EqualsAndHashCode; @Entity @Data @EqualsAndHashCode(callSuper = false) public class Roles extends GenericColumns { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long role_cd; @Column(length = 50, nullable =false) private String role_name; @Column(length = 500) private String role_desc; @OneToOne @JoinColumn(name = "template", referencedColumnName = "groupID", nullable = false) private BusinessGroups template; }
UTF-8
Java
781
java
Roles.java
Java
[]
null
[]
package com.framework.tabs.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import lombok.Data; import lombok.EqualsAndHashCode; @Entity @Data @EqualsAndHashCode(callSuper = false) public class Roles extends GenericColumns { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long role_cd; @Column(length = 50, nullable =false) private String role_name; @Column(length = 500) private String role_desc; @OneToOne @JoinColumn(name = "template", referencedColumnName = "groupID", nullable = false) private BusinessGroups template; }
781
0.796415
0.790013
31
24.193548
19.351452
83
false
false
0
0
0
0
0
0
0.967742
false
false
7
dabd6629d3b70ab54bd825445d26ac9f09c34ea5
37,460,704,774,849
6acc727e75e59c429f171cf40f6a645e3472fe7a
/Programming_with_classesTask1-7/src/com/company/Test1.java
0ce52f418432fc0ffa1e26f9b76b73bd0bf8233c
[]
no_license
nik-2/Introduction-to-Java.-General-Programming-online-course-
https://github.com/nik-2/Introduction-to-Java.-General-Programming-online-course-
65d441e07338b2aef79397142b4dea73f97749ae
f8faed7f5a13a71b296a8ecf65dd5e4ac60b4ede
refs/heads/master
2020-07-09T13:03:18.424000
2019-08-23T13:28:05
2019-08-23T13:28:05
203,975,117
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; public class Test1 { private int x = 5; private int y = 6; private void print() { System.out.println(" x = " + x + "\n y = " + y); } private void change(int x, int y) { this.x = x; this.y = y; } private void sum() { System.out.println(" Sum(x + y) = " + (x + y)); } private void max() { if( x > y) { System.out.println( " x > y ... x = " + x); } else { if ( x < y) { System.out.println( " x < y ... y = " + y); } else { System.out.println( " x = y = " + x); } } } public static void main(String[] args) { Test1 test1 = new Test1(); test1.print(); test1.sum(); test1.max(); test1.change(15, 10); test1.print(); test1.sum(); test1.max(); } }
UTF-8
Java
991
java
Test1.java
Java
[]
null
[]
package com.company; public class Test1 { private int x = 5; private int y = 6; private void print() { System.out.println(" x = " + x + "\n y = " + y); } private void change(int x, int y) { this.x = x; this.y = y; } private void sum() { System.out.println(" Sum(x + y) = " + (x + y)); } private void max() { if( x > y) { System.out.println( " x > y ... x = " + x); } else { if ( x < y) { System.out.println( " x < y ... y = " + y); } else { System.out.println( " x = y = " + x); } } } public static void main(String[] args) { Test1 test1 = new Test1(); test1.print(); test1.sum(); test1.max(); test1.change(15, 10); test1.print(); test1.sum(); test1.max(); } }
991
0.375378
0.358224
53
17.698112
15.771463
59
false
false
0
0
0
0
0
0
0.377358
false
false
7
38cc28c52052fb3231bde7e203634ef231259249
37,452,114,841,171
44ab3fee89c590479c04fe4fe997539d41a37d3e
/api/src/test/java/org/sanelib/ils/api/converters/patronCategory/UpdatePatronCategoryConverterTest.java
c146929ab1df59e1cb00beff9005ab6e9ca531b2
[ "MIT" ]
permissive
sanelib/springils
https://github.com/sanelib/springils
826412b85d07086c559edffaab200690e2e6c8a1
13adb1db7325b7297f7da68c529294c9e16726a3
refs/heads/dev
2021-01-10T04:02:25.349000
2016-03-05T08:55:59
2016-03-05T08:55:59
49,132,512
0
1
null
false
2016-03-07T07:39:18
2016-01-06T11:59:35
2016-01-12T14:24:09
2016-03-07T07:39:18
1,345
0
0
5
Java
null
null
package org.sanelib.ils.api.converters.patronCategory; import org.junit.Test; import org.sanelib.ils.api.dto.patronCategory.PatronCategoryDto; import org.sanelib.ils.core.commands.ProcessCommand; import org.sanelib.ils.core.commands.patronCategory.UpdatePatronCategory; import org.sanelib.ils.core.exceptions.ProcessError; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class UpdatePatronCategoryConverterTest { @Test public void testUpdatePatronCategorySuccessExecute() throws Exception{ PatronCategoryDto dto = new PatronCategoryDto(); dto.setId("1"); dto.setLibraryId("1"); dto.setName("PCName"); dto.setAllowILLFromNet(true); dto.setAllowRenewalFromNet(true); dto.setOverallLoanLimit("2"); dto.setAllowMultipleCopies(true); dto.setAcqWorkflow("AcqWorkflow"); ProcessError processError = new ProcessError(); UpdatePatronCategoryConverter updatePatronCategoryConverter = new UpdatePatronCategoryConverter(); ProcessCommand command = updatePatronCategoryConverter.convert(dto, processError); assertTrue("Conversion error occurred", processError.isValid()); assertTrue("Wrong output " + command, command instanceof UpdatePatronCategory); UpdatePatronCategory updatePatronCategory = (UpdatePatronCategory) command; assertEquals("Id is not mapped", dto.getId(), String.valueOf(updatePatronCategory.getId())); assertEquals("Library Id is not mapped", dto.getLibraryId(), String.valueOf(updatePatronCategory.getLibraryId())); assertEquals("Name is not mapped", dto.getName(), updatePatronCategory.getName()); assertEquals("Library Id is not mapped", dto.getLibraryId(), String.valueOf(updatePatronCategory.getLibraryId())); assertEquals("Name is not mapped", dto.getName(), updatePatronCategory.getName()); assertEquals("Ill Thru Net not Mapped ", dto.isAllowILLFromNet(), updatePatronCategory.isAllowILLFromNet()); assertEquals("Renewal Thru Net not Mapped ", dto.isAllowRenewalFromNet(), updatePatronCategory.isAllowRenewalFromNet()); assertEquals("Overall Loan limit not Mapped ", dto.getOverallLoanLimit(), String.valueOf(updatePatronCategory.getOverallLoanLimit())); assertEquals("Allow Multiple Copies not Mapped ", dto.isAllowMultipleCopies(), updatePatronCategory.isAllowILLFromNet()); assertEquals("Acq Workflow not Mapped ", dto.getAcqWorkflow(),updatePatronCategory.getAcqWorkflow()); } }
UTF-8
Java
2,567
java
UpdatePatronCategoryConverterTest.java
Java
[]
null
[]
package org.sanelib.ils.api.converters.patronCategory; import org.junit.Test; import org.sanelib.ils.api.dto.patronCategory.PatronCategoryDto; import org.sanelib.ils.core.commands.ProcessCommand; import org.sanelib.ils.core.commands.patronCategory.UpdatePatronCategory; import org.sanelib.ils.core.exceptions.ProcessError; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class UpdatePatronCategoryConverterTest { @Test public void testUpdatePatronCategorySuccessExecute() throws Exception{ PatronCategoryDto dto = new PatronCategoryDto(); dto.setId("1"); dto.setLibraryId("1"); dto.setName("PCName"); dto.setAllowILLFromNet(true); dto.setAllowRenewalFromNet(true); dto.setOverallLoanLimit("2"); dto.setAllowMultipleCopies(true); dto.setAcqWorkflow("AcqWorkflow"); ProcessError processError = new ProcessError(); UpdatePatronCategoryConverter updatePatronCategoryConverter = new UpdatePatronCategoryConverter(); ProcessCommand command = updatePatronCategoryConverter.convert(dto, processError); assertTrue("Conversion error occurred", processError.isValid()); assertTrue("Wrong output " + command, command instanceof UpdatePatronCategory); UpdatePatronCategory updatePatronCategory = (UpdatePatronCategory) command; assertEquals("Id is not mapped", dto.getId(), String.valueOf(updatePatronCategory.getId())); assertEquals("Library Id is not mapped", dto.getLibraryId(), String.valueOf(updatePatronCategory.getLibraryId())); assertEquals("Name is not mapped", dto.getName(), updatePatronCategory.getName()); assertEquals("Library Id is not mapped", dto.getLibraryId(), String.valueOf(updatePatronCategory.getLibraryId())); assertEquals("Name is not mapped", dto.getName(), updatePatronCategory.getName()); assertEquals("Ill Thru Net not Mapped ", dto.isAllowILLFromNet(), updatePatronCategory.isAllowILLFromNet()); assertEquals("Renewal Thru Net not Mapped ", dto.isAllowRenewalFromNet(), updatePatronCategory.isAllowRenewalFromNet()); assertEquals("Overall Loan limit not Mapped ", dto.getOverallLoanLimit(), String.valueOf(updatePatronCategory.getOverallLoanLimit())); assertEquals("Allow Multiple Copies not Mapped ", dto.isAllowMultipleCopies(), updatePatronCategory.isAllowILLFromNet()); assertEquals("Acq Workflow not Mapped ", dto.getAcqWorkflow(),updatePatronCategory.getAcqWorkflow()); } }
2,567
0.750682
0.749513
49
51.387756
42.917015
142
false
false
0
0
0
0
0
0
1.142857
false
false
7
a739a6d2632828c4f493f150a65a14bc27bd71bc
18,889,266,231,541
14c38af4f1cbe70ad0d76bf75f10a179baf607e4
/Orcinus/src/cn/sharp/android/ncr/display/domain/Email.java
9cacb721b71447b7fe939f97f8a92eb2768c52b8
[]
no_license
joyyiwei/Android
https://github.com/joyyiwei/Android
cabe66f6dfd914e0e64d5a2ea17c9a376491cf60
de46742aa800f138aa070c89dbcdbb21eabef1f0
refs/heads/master
2016-08-03T02:16:45.465000
2014-09-21T13:51:53
2014-09-21T13:51:53
24,291,113
3
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.sharp.android.ncr.display.domain; public class Email extends BaseDomain { private static int ID = 0; public int type; public String value; public Email() { super(ID++); } }
UTF-8
Java
193
java
Email.java
Java
[]
null
[]
package cn.sharp.android.ncr.display.domain; public class Email extends BaseDomain { private static int ID = 0; public int type; public String value; public Email() { super(ID++); } }
193
0.709845
0.704663
11
16.545454
14.754745
44
false
false
0
0
0
0
0
0
1.090909
false
false
7
cffcda5fbd03e4e414b6da36d6b806e7aaadc3b3
32,658,931,376,827
7ab8c3586361ee73c197d4ac61d0278a97a0979d
/designpatterswithjava/src/main/java/com/whw/designpatterswithjava/observer/java/ObserverRun.java
3318dd39fbe12cbd46a99f661fdbdeb10a9bfed9
[]
no_license
boj17/DesignPatterns
https://github.com/boj17/DesignPatterns
9b8d966c168f37ec1abdfa25136d687936855e13
06bb1eea8bbeb432cf871465a0286e7c0dd5f4ce
refs/heads/master
2020-07-13T00:39:18.199000
2019-08-29T09:49:33
2019-08-29T09:49:33
204,949,375
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.whw.designpatterswithjava.observer.java; public class ObserverRun { public static void main(String[] arrays){ Observable postman=new Postman(); Observer boy1=new Boy("路飞"); Observer boy2=new Boy("乔巴"); Observer girl=new Girl("娜美"); postman.add(boy1); postman.add(boy2); postman.add(girl); postman.notify("拿快递啦各位"); } }
UTF-8
Java
431
java
ObserverRun.java
Java
[ { "context": "man=new Postman();\n Observer boy1=new Boy(\"路飞\");\n Observer boy2=new Boy(\"乔巴\");\n O", "end": 204, "score": 0.945835530757904, "start": 202, "tag": "NAME", "value": "路飞" }, { "context": "oy1=new Boy(\"路飞\");\n Observer boy2=new Boy(\"乔巴\"...
null
[]
package com.whw.designpatterswithjava.observer.java; public class ObserverRun { public static void main(String[] arrays){ Observable postman=new Postman(); Observer boy1=new Boy("路飞"); Observer boy2=new Boy("乔巴"); Observer girl=new Girl("娜美"); postman.add(boy1); postman.add(boy2); postman.add(girl); postman.notify("拿快递啦各位"); } }
431
0.611794
0.601966
16
24.4375
17.186363
52
false
false
0
0
0
0
0
0
0.5625
false
false
7
f0fee272f6d8bfb5149feeea1217411ffea01451
14,310,831,082,705
0c1d809bb8cac6b8c27fdf5aef9aeee5604bc49f
/app/src/main/java/uk/ac/sussex/wear/android/datalogger/collector/SatelliteDataCollector.java
3f6a7b0564ee86d3cce132bcb06be0e300e76e67
[ "MIT" ]
permissive
institut-galilee/DataLogger
https://github.com/institut-galilee/DataLogger
8c2f383ab119b77b0816825128aee06e9b734b90
6aa00e66cf6d212542ff577c0e76ac6be97cd9ee
refs/heads/master
2021-01-05T18:06:46.025000
2019-11-11T14:58:15
2019-11-11T14:58:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2017. Mathias Ciliberto, Francisco Javier Ordoñez Morales, * Hristijan Gjoreski, Daniel Roggen * * 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 uk.ac.sussex.wear.android.datalogger.collector; import android.content.Context; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.LocationManager; import android.os.SystemClock; import android.util.Log; import java.io.File; import java.util.Date; import uk.ac.sussex.wear.android.datalogger.log.CustomLogger; public class SatelliteDataCollector extends AbstractDataCollector { private static final String TAG = SatelliteDataCollector.class.getSimpleName(); private CustomLogger logger = null; // The location manager reference private LocationManager mLocationManager = null; // Listener class for monitoring changes in gps status private GpsStatusListener mGpsStatusListener = null; public SatelliteDataCollector(Context context, String sessionName, String sensorName, long nanosOffset, int logFileMaxSize){ mSensorName = sensorName; String path = sessionName + File.separator + mSensorName + "_" + sessionName; logger = new CustomLogger(context, path, sessionName, mSensorName, "txt", false, mNanosOffset, logFileMaxSize); mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); // Offset to match timestamps both in master and slaves devices mNanosOffset = nanosOffset; mGpsStatusListener = new GpsStatusListener(); } private Iterable<GpsSatellite> getGpsSatellites(){ synchronized (this) { GpsStatus status = mLocationManager.getGpsStatus(null); return (status == null) ? null : status.getSatellites(); } } private void logSatelliteInfo(Iterable<GpsSatellite> gpsSatellites){ int satCounter = 0; // System nanoseconds since boot, including time spent in sleep. long nanoTime = SystemClock.elapsedRealtimeNanos() + mNanosOffset; // System local time in millis long currentMillis = (new Date()).getTime(); String message = String.format("%s", currentMillis) + ";" + String.format("%s", nanoTime) + ";" + String.format("%s", mNanosOffset); for(GpsSatellite satellite: gpsSatellites){ satCounter++; // PRN (pseudo-random number) for the satellite. int prn = satellite.getPrn(); // Signal to noise ratio for the satellite. float snr = satellite.getSnr(); // Azimuth of the satellite in degrees. float azimuth = satellite.getAzimuth(); // Elevation of the satellite in degrees. float elevation = satellite.getElevation(); message += ";" + prn + ";" + snr + ";" + azimuth + ";" + elevation; } message += ";" + Integer.toString(satCounter); logger.log(message); logger.log(System.lineSeparator()); } private class GpsStatusListener implements GpsStatus.Listener { @Override public void onGpsStatusChanged(int event) { if (event != GpsStatus.GPS_EVENT_STOPPED) { logSatelliteInfo(getGpsSatellites()); } } } @Override public void start() { Log.i(TAG, "start:: Starting listener for sensor: " + getSensorName()); logger.start(); mLocationManager.addGpsStatusListener(mGpsStatusListener); } @Override public void stop() { Log.i(TAG,"stop:: Stopping listener for sensor " + getSensorName()); logger.stop(); if (mLocationManager != null) { mLocationManager.removeGpsStatusListener(mGpsStatusListener); } } @Override public void haltAndRestartLogging() { logger.stop(); logger.resetByteCounter(); logger.start(); } @Override public void updateNanosOffset(long nanosOffset) { mNanosOffset = nanosOffset; } }
UTF-8
Java
5,178
java
SatelliteDataCollector.java
Java
[ { "context": "/*\n * Copyright (c) 2017. Mathias Ciliberto, Francisco Javier Ordoñez Morales,\n * Hristijan G", "end": 43, "score": 0.9998478889465332, "start": 26, "tag": "NAME", "value": "Mathias Ciliberto" }, { "context": "/*\n * Copyright (c) 2017. Mathias Ciliberto, Francisco Ja...
null
[]
/* * Copyright (c) 2017. <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 uk.ac.sussex.wear.android.datalogger.collector; import android.content.Context; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.LocationManager; import android.os.SystemClock; import android.util.Log; import java.io.File; import java.util.Date; import uk.ac.sussex.wear.android.datalogger.log.CustomLogger; public class SatelliteDataCollector extends AbstractDataCollector { private static final String TAG = SatelliteDataCollector.class.getSimpleName(); private CustomLogger logger = null; // The location manager reference private LocationManager mLocationManager = null; // Listener class for monitoring changes in gps status private GpsStatusListener mGpsStatusListener = null; public SatelliteDataCollector(Context context, String sessionName, String sensorName, long nanosOffset, int logFileMaxSize){ mSensorName = sensorName; String path = sessionName + File.separator + mSensorName + "_" + sessionName; logger = new CustomLogger(context, path, sessionName, mSensorName, "txt", false, mNanosOffset, logFileMaxSize); mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); // Offset to match timestamps both in master and slaves devices mNanosOffset = nanosOffset; mGpsStatusListener = new GpsStatusListener(); } private Iterable<GpsSatellite> getGpsSatellites(){ synchronized (this) { GpsStatus status = mLocationManager.getGpsStatus(null); return (status == null) ? null : status.getSatellites(); } } private void logSatelliteInfo(Iterable<GpsSatellite> gpsSatellites){ int satCounter = 0; // System nanoseconds since boot, including time spent in sleep. long nanoTime = SystemClock.elapsedRealtimeNanos() + mNanosOffset; // System local time in millis long currentMillis = (new Date()).getTime(); String message = String.format("%s", currentMillis) + ";" + String.format("%s", nanoTime) + ";" + String.format("%s", mNanosOffset); for(GpsSatellite satellite: gpsSatellites){ satCounter++; // PRN (pseudo-random number) for the satellite. int prn = satellite.getPrn(); // Signal to noise ratio for the satellite. float snr = satellite.getSnr(); // Azimuth of the satellite in degrees. float azimuth = satellite.getAzimuth(); // Elevation of the satellite in degrees. float elevation = satellite.getElevation(); message += ";" + prn + ";" + snr + ";" + azimuth + ";" + elevation; } message += ";" + Integer.toString(satCounter); logger.log(message); logger.log(System.lineSeparator()); } private class GpsStatusListener implements GpsStatus.Listener { @Override public void onGpsStatusChanged(int event) { if (event != GpsStatus.GPS_EVENT_STOPPED) { logSatelliteInfo(getGpsSatellites()); } } } @Override public void start() { Log.i(TAG, "start:: Starting listener for sensor: " + getSensorName()); logger.start(); mLocationManager.addGpsStatusListener(mGpsStatusListener); } @Override public void stop() { Log.i(TAG,"stop:: Stopping listener for sensor " + getSensorName()); logger.stop(); if (mLocationManager != null) { mLocationManager.removeGpsStatusListener(mGpsStatusListener); } } @Override public void haltAndRestartLogging() { logger.stop(); logger.resetByteCounter(); logger.start(); } @Override public void updateNanosOffset(long nanosOffset) { mNanosOffset = nanosOffset; } }
5,121
0.669886
0.66892
151
33.284767
30.577744
128
false
false
0
0
0
0
0
0
0.629139
false
false
7
2c52cc227ae68347a58d2a6ce0ec8beeda2fc771
9,320,079,081,365
0e8e80c99ea1ddf9bfe69b77c8dee81b8611bb31
/src/com/example/Codeforces/CodeforcesRound712/A.java
a42cef9cfb1512ec42a233a4260bcb3cfc079820
[]
no_license
anshus7007/CodeMode
https://github.com/anshus7007/CodeMode
28484b3f4a90c9fe778657db17b10279d722dd69
f86ac371d3250bf988f1f516b872c965ae667588
refs/heads/master
2023-08-06T09:31:01.355000
2021-09-24T07:07:55
2021-09-24T07:07:55
290,453,045
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.Codeforces.CodeforcesRound712; import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while (t-->0) { String s=sc.next(); int flag=0; for(int i=s.length()-1;i>=0;i--) { if('a'==s.charAt(i)) continue; else { s=s.substring(0,s.length()-i-1)+'a'+s.substring(s.length()-i-1); flag=1; break; } } if(flag==1) { System.out.println("YES"); System.out.println(s); } else System.out.println("NO"); } } }
UTF-8
Java
853
java
A.java
Java
[]
null
[]
package com.example.Codeforces.CodeforcesRound712; import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while (t-->0) { String s=sc.next(); int flag=0; for(int i=s.length()-1;i>=0;i--) { if('a'==s.charAt(i)) continue; else { s=s.substring(0,s.length()-i-1)+'a'+s.substring(s.length()-i-1); flag=1; break; } } if(flag==1) { System.out.println("YES"); System.out.println(s); } else System.out.println("NO"); } } }
853
0.390387
0.376319
36
22.694445
17.812012
84
false
false
0
0
0
0
0
0
0.444444
false
false
7
b26476a1098d2c5a5e3f6b110531873f6eafd609
12,051,678,290,522
d3f178599b3fd24ba1f2859c4de9c639f8219d87
/diptrack/src/test/java/fr/diptrack/service/MarkServiceTest.java
e8049103d5969a3f7623bbc74e0c4354a8b682c7
[]
no_license
gtandu/bougly
https://github.com/gtandu/bougly
16ddf6f1db24b5c3e95146e2d34d2a92f4e374fd
3203f01600697f34ee7dd12d4f28bd4014157821
refs/heads/master
2021-01-22T02:08:53.112000
2017-06-27T12:20:08
2017-06-27T12:20:08
81,027,695
0
0
null
false
2017-03-29T18:11:22
2017-02-05T22:43:08
2017-02-05T22:47:16
2017-03-29T18:11:22
19,202
0
0
2
JavaScript
null
null
package fr.diptrack.service; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import fr.diptrack.model.Mark; import fr.diptrack.repository.MarkRepository; @RunWith(MockitoJUnitRunner.class) public class MarkServiceTest { @Mock private MarkRepository markRepository; @InjectMocks private MarkService markService; @Test public void testFindById() throws Exception { //WHEN Long id = new Long(2); when(markRepository.findOne(anyLong())).thenReturn(new Mark()); //GIVEN markService.findById(id); //THEN verify(markRepository).findOne(eq(id)); } @Test public void testSaveMark() throws Exception { //WHEN Mark mark = new Mark(); when(markRepository.save(any(Mark.class))).thenReturn(new Mark()); //GIVEN markService.saveMark(mark); //THEN verify(markRepository).save(any(Mark.class)); } @Test public void testUpdateMark() throws Exception { //WHEN float mark = 20; Long id = new Long(2); Mark markFromDb = mock(Mark.class); when(markRepository.findOne(anyLong())).thenReturn(markFromDb); //THEN markService.updateMark(id, mark); //GIVEN verify(markRepository).findOne(eq(id)); verify(markFromDb).setMark(eq(mark)); } }
UTF-8
Java
1,554
java
MarkServiceTest.java
Java
[]
null
[]
package fr.diptrack.service; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import fr.diptrack.model.Mark; import fr.diptrack.repository.MarkRepository; @RunWith(MockitoJUnitRunner.class) public class MarkServiceTest { @Mock private MarkRepository markRepository; @InjectMocks private MarkService markService; @Test public void testFindById() throws Exception { //WHEN Long id = new Long(2); when(markRepository.findOne(anyLong())).thenReturn(new Mark()); //GIVEN markService.findById(id); //THEN verify(markRepository).findOne(eq(id)); } @Test public void testSaveMark() throws Exception { //WHEN Mark mark = new Mark(); when(markRepository.save(any(Mark.class))).thenReturn(new Mark()); //GIVEN markService.saveMark(mark); //THEN verify(markRepository).save(any(Mark.class)); } @Test public void testUpdateMark() throws Exception { //WHEN float mark = 20; Long id = new Long(2); Mark markFromDb = mock(Mark.class); when(markRepository.findOne(anyLong())).thenReturn(markFromDb); //THEN markService.updateMark(id, mark); //GIVEN verify(markRepository).findOne(eq(id)); verify(markFromDb).setMark(eq(mark)); } }
1,554
0.743243
0.740669
67
22.194031
18.93054
68
false
false
0
0
0
0
0
0
1.537313
false
false
7
43aea13113c20e34ebb2d6532edc66c9224bc73d
34,626,026,357,785
2a1880fdfe204bb5614d864bf422a0e35473f541
/src/main/java/com/weather/api/entities/weather/WeatherInfo.java
e1af6eb3f3302c29a6ca79c0af3815e35022adc4
[]
no_license
charip/weather-api-test
https://github.com/charip/weather-api-test
526176d4263a5e8e96d61194dd4647a4606480eb
de422fe90fc0947064bfba50a7ca6cadb04cc5bc
refs/heads/main
2023-08-27T13:25:54.440000
2021-11-08T05:47:24
2021-11-08T05:47:24
425,711,130
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.weather.api.entities.weather; public class WeatherInfo { private String description; public WeatherInfo() { } public WeatherInfo(String description) { this.description = description; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
UTF-8
Java
361
java
WeatherInfo.java
Java
[]
null
[]
package com.weather.api.entities.weather; public class WeatherInfo { private String description; public WeatherInfo() { } public WeatherInfo(String description) { this.description = description; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
361
0.742382
0.742382
24
14.041667
16.764246
49
false
false
0
0
0
0
0
0
0.833333
false
false
7
8e1ce59257f9405afe665459e656212252b6f5fc
36,344,013,266,504
b8acaaffe398f642872df9b97c059d2622a32ccd
/app/src/main/java/com/example/abhis/myblogapp/Data/BlogRecyclerAdapter.java
ded6ec60f09509f03e29c6557d45af8daf7e0887
[]
no_license
I-AM-0xBIT/Blog-App
https://github.com/I-AM-0xBIT/Blog-App
2d4e6a9c04ab725553a3b7998f6d5a51b3d94e3c
8e692c19871c6814c842715eb3af239caf17021a
refs/heads/master
2020-03-31T02:26:42.271000
2018-10-06T09:17:26
2018-10-06T09:17:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.abhis.myblogapp.Data; import android.content.Context; import android.graphics.drawable.Drawable; import android.media.Image; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.abhis.myblogapp.Model.Blog; import com.example.abhis.myblogapp.R; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FileDownloadTask; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import java.io.File; import java.util.Date; import java.util.List; import it.sephiroth.android.library.picasso.Picasso; public class BlogRecyclerAdapter extends RecyclerView.Adapter<BlogRecyclerAdapter.ViewHolder> { private Context context; private List<Blog> blogList; public BlogRecyclerAdapter(Context context, List<Blog> blogList) { this.context = context; this.blogList = blogList; } @Override public BlogRecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_row, parent, false); return new ViewHolder(view, context); } @Override public void onBindViewHolder(@NonNull BlogRecyclerAdapter.ViewHolder holder, int position) { Blog blog = blogList.get(position); //String imageURL = null; holder.title.setText(blog.getTitle()); holder.desc.setText(blog.getDesc()); java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance(); String formattedDate = dateFormat.format(new Date(Long.valueOf(blog.getTimestamp())).getTime()); holder.timestamp.setText(formattedDate); String imageURL = blog.getImage(); //ImageView image1 = mStorage.getFile(new File(imageURL)); Log.d("Got Image Url", imageURL); Glide.with(context).load(imageURL).into(holder.image); } @Override public int getItemCount() { return blogList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public TextView title; public TextView desc; public TextView timestamp; public ImageView image; public String userid; public ViewHolder(View view , Context ctx) { super(view); context = ctx; title = view.findViewById(R.id.postTitleList); desc = view.findViewById(R.id.postTextList); image = view.findViewById(R.id.postImageList); timestamp = view.findViewById(R.id.timeStampList); userid = null; view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } } }
UTF-8
Java
3,410
java
BlogRecyclerAdapter.java
Java
[]
null
[]
package com.example.abhis.myblogapp.Data; import android.content.Context; import android.graphics.drawable.Drawable; import android.media.Image; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.example.abhis.myblogapp.Model.Blog; import com.example.abhis.myblogapp.R; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FileDownloadTask; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import java.io.File; import java.util.Date; import java.util.List; import it.sephiroth.android.library.picasso.Picasso; public class BlogRecyclerAdapter extends RecyclerView.Adapter<BlogRecyclerAdapter.ViewHolder> { private Context context; private List<Blog> blogList; public BlogRecyclerAdapter(Context context, List<Blog> blogList) { this.context = context; this.blogList = blogList; } @Override public BlogRecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_row, parent, false); return new ViewHolder(view, context); } @Override public void onBindViewHolder(@NonNull BlogRecyclerAdapter.ViewHolder holder, int position) { Blog blog = blogList.get(position); //String imageURL = null; holder.title.setText(blog.getTitle()); holder.desc.setText(blog.getDesc()); java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance(); String formattedDate = dateFormat.format(new Date(Long.valueOf(blog.getTimestamp())).getTime()); holder.timestamp.setText(formattedDate); String imageURL = blog.getImage(); //ImageView image1 = mStorage.getFile(new File(imageURL)); Log.d("Got Image Url", imageURL); Glide.with(context).load(imageURL).into(holder.image); } @Override public int getItemCount() { return blogList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public TextView title; public TextView desc; public TextView timestamp; public ImageView image; public String userid; public ViewHolder(View view , Context ctx) { super(view); context = ctx; title = view.findViewById(R.id.postTitleList); desc = view.findViewById(R.id.postTextList); image = view.findViewById(R.id.postImageList); timestamp = view.findViewById(R.id.timeStampList); userid = null; view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } } }
3,410
0.708211
0.707625
115
28.652174
26.165043
104
false
false
0
0
0
0
0
0
0.608696
false
false
7
ef16c8f51d6df17545be81390a8aabf556c611c6
36,344,013,268,261
bb522282fe23d90084553817a448e7211dc97bfa
/src/main/java/com/cse/helium/app/utils/CommonUtils.java
ba2004ece9c75f35031116cd97de76796c2c905b
[ "MIT", "LicenseRef-scancode-generic-cla" ]
permissive
retaildevcrews/helium-java
https://github.com/retaildevcrews/helium-java
1e40db1b19e5696b932d18e0dd1829fa1f3754d6
3423640fb78b93eef3be21157a82ea97cae120ed
refs/heads/main
2022-01-08T16:40:55.881000
2022-01-07T17:50:56
2022-01-07T17:50:56
229,196,673
2
13
MIT
false
2022-01-07T17:50:57
2019-12-20T05:32:38
2022-01-07T17:50:36
2022-01-07T17:50:56
13,994
2
6
8
Java
false
false
package com.cse.helium.app.utils; import com.cse.helium.app.Constants; import com.cse.helium.app.config.BuildConfig; import com.cse.helium.app.services.keyvault.EnvironmentReader; import com.cse.helium.app.services.keyvault.IEnvironmentReader; import com.cse.helium.app.services.keyvault.IKeyVaultService; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.text.MessageFormat; import java.util.Arrays; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.config.Configurator; import org.springframework.boot.ApplicationArguments; import org.springframework.core.env.SimpleCommandLinePropertySource; import org.springframework.stereotype.Component; /** * CommonUtils. */ @Component public class CommonUtils { private CommonUtils() { // disable constructor for utility class } /** * handleCliLogLevelOption. * * @param args the log level in string form. */ public static void handleCliLogLevelOption(String[] args) { if (args != null) { SimpleCommandLinePropertySource commandLinePropertySource = new SimpleCommandLinePropertySource(args); Arrays.stream(commandLinePropertySource.getPropertyNames()).forEach(s -> { if (s.equals("log-level") || s.equals("l")) { Level level = setLogLevel(commandLinePropertySource.getProperty(s)); if (level == null) { printCmdLineHelp(); System.exit(-1); } Configurator.setLevel("com.cse.helium", level); } }); } } private static Level setLogLevel(String logLevel) { switch (logLevel) { case "trace": return Level.TRACE; case "debug": return Level.DEBUG; case "info": return Level.INFO; case "warn": return Level.WARN; case "error": return Level.ERROR; case "fatal": return Level.FATAL; default: return null; } } /** * validate cli dry run option. */ public static void validateCliDryRunOption(ApplicationArguments applicationArguments, IKeyVaultService keyVaultService, BuildConfig buildConfig, IEnvironmentReader environmentReader) { if (applicationArguments != null) { SimpleCommandLinePropertySource commandLinePropertySource = new SimpleCommandLinePropertySource(applicationArguments.getSourceArgs()); Arrays.stream(commandLinePropertySource.getPropertyNames()).forEach(s -> { if (s.equals("dry-run") || s.equals("d")) { printDryRunParameters(keyVaultService, buildConfig, environmentReader); System.exit(0); } }); } } @SuppressFBWarnings({"NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD"}) @SuppressWarnings ("squid:S106") // System.out needed to print usage static void printDryRunParameters(IKeyVaultService keyVaultService, BuildConfig buildConfig, IEnvironmentReader environmentReader) { System.out.println(MessageFormat.format("Version {0}", buildConfig.getBuildVersion())); System.out.println(MessageFormat.format("Auth Type {0}", environmentReader.getAuthType())); System.out.println(MessageFormat.format("Cosmos Server {0}", keyVaultService.getSecret(Constants.COSMOS_URL_KEYNAME).block())); String cosmosKey = keyVaultService.getSecretValue(Constants.COSMOS_KEY_KEYNAME).block(); System.out.println(MessageFormat.format("Cosmos Key {0}", cosmosKey == null || cosmosKey.isEmpty() ? "(not set)".length() : cosmosKey.length())); System.out.println(MessageFormat.format("Cosmos Database {0}", keyVaultService.getSecret(Constants.COSMOS_DATABASE_KEYNAME).block())); System.out.println(MessageFormat.format("Cosmos Collection {0}", keyVaultService.getSecret(Constants.COSMOS_COLLECTION_KEYNAME).block())); String appInsightsKey = keyVaultService.getSecretValue(Constants.APP_INSIGHTS_KEY).block(); System.out.println(MessageFormat.format("App Insights Key {0}", appInsightsKey == null || appInsightsKey.isEmpty() ? "(not set)".length() : appInsightsKey.length())); } /** * validateCliKeyvaultAndAuthType - validate the authtype and keyvault name from CLI. */ public static void validateCliKeyvaultAndAuthTypeOption(ApplicationArguments applicationArguments, EnvironmentReader environmentReader) { if (applicationArguments != null) { SimpleCommandLinePropertySource commandLinePropertySource = new SimpleCommandLinePropertySource(applicationArguments.getSourceArgs()); Arrays.stream(commandLinePropertySource.getPropertyNames()).forEach(s -> { if (s.equals("auth-type")) { environmentReader.setAuthType(commandLinePropertySource.getProperty(s)); } else if (s.equals("keyvault-name")) { environmentReader.setKeyVaultName(commandLinePropertySource.getProperty(s)); } else if (s.equals("help")) { CommonUtils.printCmdLineHelp(); System.exit(0); } }); } } /** * prints the command line help. */ @SuppressWarnings ("squid:S106") // System.out needed to print usage public static void printCmdLineHelp() { System.out.println("\r\nUsage:\r\n" + " mvn clean spring-boot:run \r\n " + "\t-Dspring-boot.run.arguments=\" --help \r\n" + "\t\t--auth-type=<CLI|MI|VS>\r\n" + "\t\t--keyvault-name=<keyVaultName>\r\n" + "\t\t--dry-run\r\n" + "\t\t--log-level=<trace|info|warn|error|fatal>\""); } }
UTF-8
Java
5,852
java
CommonUtils.java
Java
[]
null
[]
package com.cse.helium.app.utils; import com.cse.helium.app.Constants; import com.cse.helium.app.config.BuildConfig; import com.cse.helium.app.services.keyvault.EnvironmentReader; import com.cse.helium.app.services.keyvault.IEnvironmentReader; import com.cse.helium.app.services.keyvault.IKeyVaultService; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.text.MessageFormat; import java.util.Arrays; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.config.Configurator; import org.springframework.boot.ApplicationArguments; import org.springframework.core.env.SimpleCommandLinePropertySource; import org.springframework.stereotype.Component; /** * CommonUtils. */ @Component public class CommonUtils { private CommonUtils() { // disable constructor for utility class } /** * handleCliLogLevelOption. * * @param args the log level in string form. */ public static void handleCliLogLevelOption(String[] args) { if (args != null) { SimpleCommandLinePropertySource commandLinePropertySource = new SimpleCommandLinePropertySource(args); Arrays.stream(commandLinePropertySource.getPropertyNames()).forEach(s -> { if (s.equals("log-level") || s.equals("l")) { Level level = setLogLevel(commandLinePropertySource.getProperty(s)); if (level == null) { printCmdLineHelp(); System.exit(-1); } Configurator.setLevel("com.cse.helium", level); } }); } } private static Level setLogLevel(String logLevel) { switch (logLevel) { case "trace": return Level.TRACE; case "debug": return Level.DEBUG; case "info": return Level.INFO; case "warn": return Level.WARN; case "error": return Level.ERROR; case "fatal": return Level.FATAL; default: return null; } } /** * validate cli dry run option. */ public static void validateCliDryRunOption(ApplicationArguments applicationArguments, IKeyVaultService keyVaultService, BuildConfig buildConfig, IEnvironmentReader environmentReader) { if (applicationArguments != null) { SimpleCommandLinePropertySource commandLinePropertySource = new SimpleCommandLinePropertySource(applicationArguments.getSourceArgs()); Arrays.stream(commandLinePropertySource.getPropertyNames()).forEach(s -> { if (s.equals("dry-run") || s.equals("d")) { printDryRunParameters(keyVaultService, buildConfig, environmentReader); System.exit(0); } }); } } @SuppressFBWarnings({"NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD"}) @SuppressWarnings ("squid:S106") // System.out needed to print usage static void printDryRunParameters(IKeyVaultService keyVaultService, BuildConfig buildConfig, IEnvironmentReader environmentReader) { System.out.println(MessageFormat.format("Version {0}", buildConfig.getBuildVersion())); System.out.println(MessageFormat.format("Auth Type {0}", environmentReader.getAuthType())); System.out.println(MessageFormat.format("Cosmos Server {0}", keyVaultService.getSecret(Constants.COSMOS_URL_KEYNAME).block())); String cosmosKey = keyVaultService.getSecretValue(Constants.COSMOS_KEY_KEYNAME).block(); System.out.println(MessageFormat.format("Cosmos Key {0}", cosmosKey == null || cosmosKey.isEmpty() ? "(not set)".length() : cosmosKey.length())); System.out.println(MessageFormat.format("Cosmos Database {0}", keyVaultService.getSecret(Constants.COSMOS_DATABASE_KEYNAME).block())); System.out.println(MessageFormat.format("Cosmos Collection {0}", keyVaultService.getSecret(Constants.COSMOS_COLLECTION_KEYNAME).block())); String appInsightsKey = keyVaultService.getSecretValue(Constants.APP_INSIGHTS_KEY).block(); System.out.println(MessageFormat.format("App Insights Key {0}", appInsightsKey == null || appInsightsKey.isEmpty() ? "(not set)".length() : appInsightsKey.length())); } /** * validateCliKeyvaultAndAuthType - validate the authtype and keyvault name from CLI. */ public static void validateCliKeyvaultAndAuthTypeOption(ApplicationArguments applicationArguments, EnvironmentReader environmentReader) { if (applicationArguments != null) { SimpleCommandLinePropertySource commandLinePropertySource = new SimpleCommandLinePropertySource(applicationArguments.getSourceArgs()); Arrays.stream(commandLinePropertySource.getPropertyNames()).forEach(s -> { if (s.equals("auth-type")) { environmentReader.setAuthType(commandLinePropertySource.getProperty(s)); } else if (s.equals("keyvault-name")) { environmentReader.setKeyVaultName(commandLinePropertySource.getProperty(s)); } else if (s.equals("help")) { CommonUtils.printCmdLineHelp(); System.exit(0); } }); } } /** * prints the command line help. */ @SuppressWarnings ("squid:S106") // System.out needed to print usage public static void printCmdLineHelp() { System.out.println("\r\nUsage:\r\n" + " mvn clean spring-boot:run \r\n " + "\t-Dspring-boot.run.arguments=\" --help \r\n" + "\t\t--auth-type=<CLI|MI|VS>\r\n" + "\t\t--keyvault-name=<keyVaultName>\r\n" + "\t\t--dry-run\r\n" + "\t\t--log-level=<trace|info|warn|error|fatal>\""); } }
5,852
0.649522
0.646446
151
37.754967
30.275986
100
false
false
0
0
0
0
0
0
0.516556
false
false
7
2a433e61aed126451f469b1ee27c544b024a58d5
30,150,670,481,405
f82106fcb00ef2a790f01e6607f6fd0d2b96533a
/Filter/src/main/java/ru/nsu/fit/g14203/popov/filter/filters/InvertFilter.java
f67dbd65566efaa3a5b48807a4290bf4ba0883e4
[]
no_license
Bolodya1997/graphics
https://github.com/Bolodya1997/graphics
f5be0c6fb61f7332de887e920c72465d5f6222ad
475a50e05f2f64dd300518953afe96216665a079
refs/heads/master
2020-03-21T06:08:54.621000
2017-06-01T18:38:40
2017-06-01T18:38:40
138,202,219
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.nsu.fit.g14203.popov.filter.filters; import java.awt.image.BufferedImage; public class InvertFilter implements Filter { @Override public BufferedImage apply(BufferedImage image) { BufferedImage result = Util.copyImage(image); for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { int RGB = image.getRGB(x, y) & 0xFFFFFF; result.setRGB(x, y, 0xFFFFFF - RGB); } } return result; } }
UTF-8
Java
533
java
InvertFilter.java
Java
[]
null
[]
package ru.nsu.fit.g14203.popov.filter.filters; import java.awt.image.BufferedImage; public class InvertFilter implements Filter { @Override public BufferedImage apply(BufferedImage image) { BufferedImage result = Util.copyImage(image); for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { int RGB = image.getRGB(x, y) & 0xFFFFFF; result.setRGB(x, y, 0xFFFFFF - RGB); } } return result; } }
533
0.575985
0.559099
19
27.052631
22.901329
57
false
false
0
0
0
0
0
0
0.684211
false
false
7
97fa1c6875309462abca184693ce18db107da5bb
27,376,121,570,968
4d69b8b3a8025dc9a8660090005e93943924b915
/src/day9/MultiBranchIfStatementIntro.java
4b33877f9ca72603e0b71de7ab5e7fa6732e8993
[]
no_license
HurmaH/JavaCore
https://github.com/HurmaH/JavaCore
648de2cbb2935ac0edcb0760caf70832a33e65ac
b7ba23c74849dbb6131cceb7fc5db676ac094e03
refs/heads/master
2020-06-04T00:47:46.598000
2019-07-21T21:42:27
2019-07-21T21:42:27
191,799,853
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day9; public class MultiBranchIfStatementIntro { public static void main(String[] args) { // TODO Auto-generated method stub //GRADEBOOK int score =75; if (90<=score) { System.out.println("A"); }else if (80<=score) { System.out.println("B"); }else if (70<=score) { System.out.println("C"); }else { System.out.println("D"); System.out.println("Study Harder!"); } // if(score>=90) System.out.println("You got A"); // if(score>=80) System.out.println("You got B"); // if(score>=70) System.out.println("You got C"); // if(score>=60) System.out.println("You got D"); // else System.out.println("You got F"); } }
UTF-8
Java
712
java
MultiBranchIfStatementIntro.java
Java
[]
null
[]
package day9; public class MultiBranchIfStatementIntro { public static void main(String[] args) { // TODO Auto-generated method stub //GRADEBOOK int score =75; if (90<=score) { System.out.println("A"); }else if (80<=score) { System.out.println("B"); }else if (70<=score) { System.out.println("C"); }else { System.out.println("D"); System.out.println("Study Harder!"); } // if(score>=90) System.out.println("You got A"); // if(score>=80) System.out.println("You got B"); // if(score>=70) System.out.println("You got C"); // if(score>=60) System.out.println("You got D"); // else System.out.println("You got F"); } }
712
0.581461
0.557584
32
20.25
18.457722
52
false
false
0
0
0
0
0
0
1.96875
false
false
7
bd0ff3183170d0eafa3a7db66a9f6d92edc75dac
13,391,708,079,625
0212e949ecbac88b45d52a3482ee37d98b7b380e
/src/warehouse/ActionRight.java
72b7e9705fe877ab78828a09855d9341f5989e89
[]
no_license
andre00nogueira/project-warehouse
https://github.com/andre00nogueira/project-warehouse
5c3ee8c203111421a0e8498ca4815bd3d24df5b1
26ff346794288f2d41e523abe160e7e7392c925e
refs/heads/master
2021-05-17T04:23:47.645000
2020-06-06T14:49:40
2020-06-06T14:49:40
250,621,730
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package warehouse; import agentSearch.Action; public class ActionRight extends Action<WarehouseState>{ public ActionRight(){ super(1); } @Override public void execute(WarehouseState state){ state.moveRight(); state.setAction(this); } @Override public boolean isValid(WarehouseState state){ return state.canMoveRight(); } }
UTF-8
Java
391
java
ActionRight.java
Java
[]
null
[]
package warehouse; import agentSearch.Action; public class ActionRight extends Action<WarehouseState>{ public ActionRight(){ super(1); } @Override public void execute(WarehouseState state){ state.moveRight(); state.setAction(this); } @Override public boolean isValid(WarehouseState state){ return state.canMoveRight(); } }
391
0.657289
0.654731
21
17.666666
17.318676
56
false
false
0
0
0
0
0
0
0.285714
false
false
7
8f930f375caa2e7aeb888278ff501dc10cf68506
19,808,389,190,838
0ac4c7ee22a519c4e3651834974641dc29f6fc63
/Source/src/mainWindow/Building.java
3785e43dea3e82ec772b4318f228999763569f29
[]
no_license
ddodds399/Monopoly-Desktop-Game
https://github.com/ddodds399/Monopoly-Desktop-Game
e55de7d4d05690ee503bd2aca6a074de30c4e63e
d1204e7d5ed881224bff6c4c2582685603226d88
refs/heads/master
2021-01-20T18:48:05.114000
2016-06-19T20:00:01
2016-06-19T20:00:01
61,497,222
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mainWindow; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import mainGame.Properties; import mainGame.PropertySetup; /** * This class creates the interface to build flats/halls and sell properties * * @author Brogrammers */ @SuppressWarnings("serial") public class Building extends JFrame { @SuppressWarnings("unused") private int TASKBARSIZE = 45; // private static Dimension screenRes; /** * This constructor creates the interface */ public Building() { setupFrame(); validate(); revalidate(); repaint(); } /** * This method sets up the frame giving it's default options and adding action listeners * for each JButton in each tab of the interface */ private void setupFrame() { // screenRes = Toolkit.getDefaultToolkit().getScreenSize(); setSize(600, 400); setVisible(true); setResizable(false); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setLocationRelativeTo(null); ImageIcon windowIcon = new ImageIcon("images/windowIcon.jpg"); setIconImage(windowIcon.getImage()); setTitle("Build"); JPanel topPanel = new JPanel(); topPanel.setBackground(Color.lightGray); JTabbedPane tabbedPane = new JTabbedPane(); JPanel middlePanel = new JPanel(new GridLayout()); JPanel brownPanel = new JPanel(new GridLayout(3, 2)); Color brown = new Color(129, 69, 19); brownPanel.setBackground(brown); JPanel bluePanel = new JPanel(new GridLayout(3, 3)); bluePanel.setBackground(Color.cyan); JPanel pinkPanel = new JPanel(new GridLayout(3, 3)); Color pink = new Color(255, 51, 153); pinkPanel.setBackground(pink); JPanel orangePanel = new JPanel(new GridLayout(3, 3)); orangePanel.setBackground(Color.orange); JPanel redPanel = new JPanel(new GridLayout(3, 3)); redPanel.setBackground(Color.red); JPanel yellowPanel = new JPanel(new GridLayout(3, 3)); yellowPanel.setBackground(Color.yellow); JPanel greenPanel = new JPanel(new GridLayout(3, 3)); greenPanel.setBackground(Color.GREEN); JPanel purplePanel = new JPanel(new GridLayout(3, 2)); purplePanel.setBackground(Color.blue); /** * The brown tab * * */ final JButton buildAginHouse = new JButton("Build Flat £" +PropertySetup.getAgincourtAve().getCostBuyFlat()); disableButtons(PropertySetup.getAgincourtAve(), buildAginHouse); final JLabel agin = new JLabel("<html>Agincourt Avenue<br>Flats: " + PropertySetup.getAgincourtAve().getFlats() + "<br>Halls: " + PropertySetup.getAgincourtAve().getHalls() + "<html>"); agin.setHorizontalAlignment(SwingConstants.CENTER); agin.setForeground(Color.white); agin.setBorder(BorderFactory.createLineBorder(Color.black)); JButton aginOverdraft = new JButton("Overdraft"); // Buying a house for AginCourt buildAginHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain2Method(PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player1FlatsAndHalls(1, PropertySetup.getAgincourtAve(), buildAginHouse); } else if (player2Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player2FlatsAndHalls(1, PropertySetup.getAgincourtAve(), buildAginHouse); } else if (player3Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player3FlatsAndHalls(1, PropertySetup.getAgincourtAve(), buildAginHouse); } else if (player4Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player4FlatsAndHalls(1, PropertySetup.getAgincourtAve(), buildAginHouse); } else { JOptionPane.showMessageDialog(null, "You do not own both of the brown properties"); } agin.setText("<html>Agincourt Avenue<br>Flats: " + PropertySetup.getAgincourtAve().getFlats() + "<br>Halls: " + PropertySetup.getAgincourtAve().getHalls() + "<html>"); } }); final JButton buildTatesHouse = new JButton("Build Flat £"+PropertySetup.getTatesAve().getCostBuyFlat()); disableButtons(PropertySetup.getTatesAve(), buildTatesHouse); final JLabel tate = new JLabel("<html>Tates" + "<br>Flats: " + PropertySetup.getTatesAve().getFlats() + "<br>Halls: " + PropertySetup.getTatesAve().getHalls() + "<html>"); JButton tatesOverdraft = new JButton("Overdraft"); tate.setHorizontalAlignment(SwingConstants.CENTER); tate.setForeground(Color.WHITE); tate.setBorder(BorderFactory.createLineBorder(Color.black)); buildTatesHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain2Method(PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player1FlatsAndHalls(3, PropertySetup.getAgincourtAve(), buildTatesHouse); } else if (player2Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player2FlatsAndHalls(3, PropertySetup.getAgincourtAve(), buildTatesHouse); } else if (player3Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player3FlatsAndHalls(3, PropertySetup.getAgincourtAve(), buildTatesHouse); } else if (player4Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player4FlatsAndHalls(3, PropertySetup.getAgincourtAve(), buildTatesHouse); } else { JOptionPane.showMessageDialog(null, "You do not own both of the brown properties"); } tate.setText("<html>Tates" + "<br>Flats: " + PropertySetup.getTatesAve().getFlats() + "<br>Halls: " + PropertySetup.getTatesAve().getHalls() + "<html>"); } }); brownPanel.add(agin); brownPanel.add(tate); brownPanel.add(buildAginHouse); brownPanel.add(buildTatesHouse); brownPanel.add(aginOverdraft); brownPanel.add(tatesOverdraft); /** * The Blue Tab */ final JButton buildBcbHouse = new JButton("Build Flat £"+PropertySetup.getBcbRubble().getCostBuyFlat()); disableButtons(PropertySetup.getBcbRubble(), buildBcbHouse); final JLabel bcb = new JLabel("<html>BCB Rubble" + "<br>Flats: " + PropertySetup.getBcbRubble().getFlats() + "<br>Halls: " + PropertySetup.getBcbRubble().getHalls() + "</html>"); bcb.setForeground(Color.black); bcb.setHorizontalAlignment(SwingConstants.CENTER); bcb.setBorder(BorderFactory.createLineBorder(Color.black)); JButton bcbOverdraft = new JButton("Overdraft"); buildBcbHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player1FlatsAndHalls(6, PropertySetup.getBcbRubble(), buildBcbHouse); } else if (player2Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player2FlatsAndHalls(6, PropertySetup.getBcbRubble(), buildBcbHouse); } else if (player3Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player3FlatsAndHalls(6, PropertySetup.getBcbRubble(), buildBcbHouse); } else if (player4Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player4FlatsAndHalls(3, PropertySetup.getBcbRubble(), buildBcbHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the blue properties"); } bcb.setText("<html>BCB Rubble" + "<br>Flats: " + PropertySetup.getBcbRubble().getFlats() + "<br>Halls: " + PropertySetup.getBcbRubble().getHalls() + "</html>"); } }); final JButton buildDunluceHouse = new JButton("Build Flat £"+PropertySetup.getDunluceAve().getCostBuyFlat()); disableButtons(PropertySetup.getDunluceAve(), buildDunluceHouse); final JLabel dun = new JLabel("<html>Dunluce Avenue" + "<br>Flats: " + PropertySetup.getDunluceAve().getFlats() + "<br>Halls: " + PropertySetup.getDunluceAve().getHalls() + "</html>"); dun.setForeground(Color.black); dun.setHorizontalAlignment(SwingConstants.CENTER); dun.setBorder(BorderFactory.createLineBorder(Color.black)); JButton dunOverdraft = new JButton("Overdraft"); buildDunluceHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player1FlatsAndHalls(8, PropertySetup.getDunluceAve(), buildDunluceHouse); } else if (player2Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player2FlatsAndHalls(8, PropertySetup.getDunluceAve(), buildDunluceHouse); } else if (player3Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player3FlatsAndHalls(8, PropertySetup.getDunluceAve(), buildDunluceHouse); } else if (player4Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player4FlatsAndHalls(8, PropertySetup.getDunluceAve(), buildDunluceHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the blue properties"); } dun.setText("<html>Dunluce Avenue" + "<br>Flats: " + PropertySetup.getDunluceAve().getFlats() + "<br>Halls: " + PropertySetup.getDunluceAve().getHalls() + "</html>"); } }); final JButton buildMaloneAHouse = new JButton("Build Flat £"+PropertySetup.getMaloneAve().getCostBuyFlat()); disableButtons(PropertySetup.getMaloneAve(), buildMaloneAHouse); final JLabel maloneA = new JLabel("<html>Malone Avenue" + "<br>Flats: " + PropertySetup.getMaloneAve().getFlats() + "<br>Halls: " + PropertySetup.getMaloneAve().getHalls() + "</html>"); JButton maloneAOverdraft = new JButton("Overdraft"); maloneA.setForeground(Color.black); maloneA.setHorizontalAlignment(SwingConstants.CENTER); maloneA.setBorder(BorderFactory.createLineBorder(Color.black)); buildMaloneAHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player1FlatsAndHalls(9, PropertySetup.getMaloneAve(), buildMaloneAHouse); } else if (player2Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player2FlatsAndHalls(9, PropertySetup.getMaloneAve(), buildMaloneAHouse); } else if (player3Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player3FlatsAndHalls(9, PropertySetup.getMaloneAve(), buildMaloneAHouse); } else if (player4Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player4FlatsAndHalls(9, PropertySetup.getMaloneAve(), buildMaloneAHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the blue properties"); } maloneA.setText("<html>Malone Avenue" + "<br>Flats: " + PropertySetup.getMaloneAve().getFlats() + "<br>Halls: " + PropertySetup.getMaloneAve().getHalls() + "</html>"); } }); bluePanel.add(bcb); bluePanel.add(dun); bluePanel.add(maloneA); bluePanel.add(buildBcbHouse); bluePanel.add(buildDunluceHouse); bluePanel.add(buildMaloneAHouse); bluePanel.add(bcbOverdraft); bluePanel.add(dunOverdraft); bluePanel.add(maloneAOverdraft); /** * * The Pinks */ final JButton buildSocaHouse = new JButton("Build Flat £"+PropertySetup.getSoca().getCostBuyFlat()); disableButtons(PropertySetup.getSoca(), buildSocaHouse); final JLabel soca = new JLabel("<html>School Of Creative Arts" + "<br>Flats: " + PropertySetup.getSoca().getFlats() + "<br>Halls: " + PropertySetup.getSoca().getHalls() + "</html>"); JButton socaOverdraft = new JButton("Overdraft"); soca.setForeground(Color.white); soca.setHorizontalAlignment(SwingConstants.CENTER); soca.setBorder(BorderFactory.createLineBorder(Color.black)); buildSocaHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player1FlatsAndHalls(11, PropertySetup.getSoca(), buildSocaHouse); } else if (player2Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player2FlatsAndHalls(11, PropertySetup.getSoca(), buildSocaHouse); } else if (player3Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player3FlatsAndHalls(11, PropertySetup.getSoca(), buildSocaHouse); } else if (player4Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player4FlatsAndHalls(11, PropertySetup.getSoca(), buildSocaHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the pink properties"); } soca.setText("<html>School Of Creative Arts" + "<br>Flats: " + PropertySetup.getSoca().getFlats() + "<br>Halls: " + PropertySetup.getSoca().getHalls() + "</html>"); } }); final JButton buildTheologyHouse = new JButton("Build Flat £"+PropertySetup.getTheologyCentre().getCostBuyFlat()); disableButtons(PropertySetup.getTheologyCentre(), buildTheologyHouse); final JLabel theo = new JLabel("<html>Theology Centre" + "<br>Flats: " + PropertySetup.getTheologyCentre().getFlats() + "<br>Halls: " + PropertySetup.getTheologyCentre().getHalls() + "</html>"); JButton theologyOverdraft = new JButton("Overdraft"); theo.setForeground(Color.white); theo.setHorizontalAlignment(SwingConstants.CENTER); theo.setBorder(BorderFactory.createLineBorder(Color.black)); buildTheologyHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player1FlatsAndHalls(13, PropertySetup.getTheologyCentre(), buildTheologyHouse); } else if (player2Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player2FlatsAndHalls(13, PropertySetup.getTheologyCentre(), buildTheologyHouse); } else if (player3Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player3FlatsAndHalls(13, PropertySetup.getTheologyCentre(), buildTheologyHouse); } else if (player4Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player4FlatsAndHalls(13, PropertySetup.getTheologyCentre(), buildTheologyHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the pink properties"); } theo.setText("<html>Theology Centre" + "<br>Flats: " + PropertySetup.getTheologyCentre().getFlats() + "<br>Halls: " + PropertySetup.getTheologyCentre().getHalls() + "</html>"); } }); final JButton buildMaloneRHouse = new JButton("Build Flat £"+PropertySetup.getMaloneRoad().getCostBuyFlat()); disableButtons(PropertySetup.getMaloneRoad(), buildMaloneRHouse); final JLabel maloneR = new JLabel("<html>Malone Road" + "<br>Flats: " + PropertySetup.getMaloneRoad().getFlats() + "<br>Halls: " + PropertySetup.getMaloneRoad().getHalls() + "</html>"); JButton maloneROverdraft = new JButton("Overdraft"); maloneR.setForeground(Color.white); maloneR.setHorizontalAlignment(SwingConstants.CENTER); maloneR.setBorder(BorderFactory.createLineBorder(Color.black)); buildMaloneRHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player1FlatsAndHalls(14, PropertySetup.getMaloneRoad(), buildMaloneRHouse); } else if (player2Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player2FlatsAndHalls(14, PropertySetup.getMaloneRoad(), buildMaloneRHouse); } else if (player3Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player3FlatsAndHalls(14, PropertySetup.getMaloneRoad(), buildMaloneRHouse); } else if (player4Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player4FlatsAndHalls(14, PropertySetup.getMaloneRoad(), buildMaloneRHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the pink properties"); } maloneR.setText("<html>Malone Road" + "<br>Flats: " + PropertySetup.getMaloneRoad().getFlats() + "<br>Halls: " + PropertySetup.getMaloneRoad().getHalls() + "</html>"); } }); pinkPanel.add(soca); pinkPanel.add(theo); pinkPanel.add(maloneR); pinkPanel.add(buildSocaHouse); pinkPanel.add(buildTheologyHouse); pinkPanel.add(buildMaloneRHouse); pinkPanel.add(socaOverdraft); pinkPanel.add(theologyOverdraft); pinkPanel.add(maloneROverdraft); /** * * The orange */ final JButton buildFitzHouse = new JButton("Build Flat £"+PropertySetup.getFitzwilliamStreet().getCostBuyFlat()); disableButtons(PropertySetup.getFitzwilliamStreet(), buildFitzHouse); final JLabel fitz = new JLabel("<html>Fitzwilliam Street" + "<br>Flats: " + PropertySetup.getFitzwilliamStreet().getFlats() + "<br>Halls: " + PropertySetup.getFitzwilliamStreet().getHalls() + "</html>"); JButton fitzOverdraft = new JButton("Overdraft"); fitz.setForeground(Color.white); fitz.setHorizontalAlignment(SwingConstants.CENTER); fitz.setBorder(BorderFactory.createLineBorder(Color.black)); buildFitzHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player1FlatsAndHalls(16, PropertySetup.getFitzwilliamStreet(), buildFitzHouse); } else if (player2Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player2FlatsAndHalls(16, PropertySetup.getFitzwilliamStreet(), buildFitzHouse); } else if (player3Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player3FlatsAndHalls(16, PropertySetup.getFitzwilliamStreet(), buildFitzHouse); } else if (player4Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player4FlatsAndHalls(16, PropertySetup.getFitzwilliamStreet(), buildFitzHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the orange properties"); } fitz.setText("<html>Fitzwilliam Street" + "<br>Flats: " + PropertySetup.getFitzwilliamStreet().getFlats() + "<br>Halls: " + PropertySetup.getFitzwilliamStreet().getHalls() + "</html>"); } }); final JButton buildGeoHouse = new JButton("Build Flat £"+PropertySetup.getGeographyBuilding().getCostBuyFlat()); disableButtons(PropertySetup.getGeographyBuilding(), buildGeoHouse); final JLabel geo = new JLabel("<html>Geography Building" + "<br>Flats: " + PropertySetup.getGeographyBuilding().getFlats() + "<br>Halls: " + PropertySetup.getGeographyBuilding().getHalls() + "</html>"); JButton geoOverdraft = new JButton("Overdraft"); geo.setForeground(Color.white); geo.setHorizontalAlignment(SwingConstants.CENTER); geo.setBorder(BorderFactory.createLineBorder(Color.black)); buildGeoHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player1FlatsAndHalls(18, PropertySetup.getGeographyBuilding(), buildGeoHouse); } else if (player2Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player2FlatsAndHalls(18, PropertySetup.getGeographyBuilding(), buildGeoHouse); } else if (player3Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player3FlatsAndHalls(18, PropertySetup.getGeographyBuilding(), buildGeoHouse); } else if (player4Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player4FlatsAndHalls(18, PropertySetup.getGeographyBuilding(), buildGeoHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the orange properties"); } geo.setText("<html>Geography Building" + "<br>Flats: " + PropertySetup.getGeographyBuilding().getFlats() + "<br>Halls: " + PropertySetup.getGeographyBuilding().getHalls() + "</html>"); } }); final JButton buildEcsHouse = new JButton("Build Flat £"+PropertySetup.getEcsBuilding().getCostBuyFlat()); disableButtons(PropertySetup.getEcsBuilding(), buildEcsHouse); final JLabel ecs = new JLabel("<html>ECS Building" + "<br>Flats: " + PropertySetup.getEcsBuilding().getFlats() + "<br>Halls: " + PropertySetup.getEcsBuilding().getHalls() + "</html>"); JButton ecsOverdraft = new JButton("Overdraft"); ecs.setForeground(Color.white); ecs.setHorizontalAlignment(SwingConstants.CENTER); ecs.setBorder(BorderFactory.createLineBorder(Color.black)); buildEcsHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player1FlatsAndHalls(19, PropertySetup.getEcsBuilding(), buildEcsHouse); } else if (player2Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player2FlatsAndHalls(19, PropertySetup.getEcsBuilding(), buildEcsHouse); } else if (player3Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player3FlatsAndHalls(19, PropertySetup.getEcsBuilding(), buildEcsHouse); } else if (player4Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player4FlatsAndHalls(19, PropertySetup.getEcsBuilding(), buildEcsHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the orange properties"); } ecs.setText("<html>ECS Building" + "<br>Flats: " + PropertySetup.getEcsBuilding().getFlats() + "<br>Halls: " + PropertySetup.getEcsBuilding().getHalls() + "</html>"); } }); orangePanel.add(fitz); orangePanel.add(geo); orangePanel.add(ecs); orangePanel.add(buildFitzHouse); orangePanel.add(buildGeoHouse); orangePanel.add(buildEcsHouse); orangePanel.add(fitzOverdraft); orangePanel.add(geoOverdraft); orangePanel.add(ecsOverdraft); /** * The red * */ final JButton buildBoojumHouse = new JButton("Build Flat £"+PropertySetup.getBoojum().getCostBuyFlat()); disableButtons(PropertySetup.getBoojum(), buildBoojumHouse); final JLabel boojum = new JLabel("<html>Boojum" + "<br>Flats: " + PropertySetup.getBoojum().getFlats() + "<br>Halls: " + PropertySetup.getBoojum().getHalls() + "</html>"); JButton boojumOverdraft = new JButton("Overdraft"); boojum.setForeground(Color.white); boojum.setHorizontalAlignment(SwingConstants.CENTER); boojum.setBorder(BorderFactory.createLineBorder(Color.black)); buildBoojumHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player1FlatsAndHalls(21, PropertySetup.getBoojum(), buildBoojumHouse); } else if (player2Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player2FlatsAndHalls(21, PropertySetup.getBoojum(), buildBoojumHouse); } else if (player3Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player3FlatsAndHalls(21, PropertySetup.getBoojum(), buildBoojumHouse); } else if (player4Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player4FlatsAndHalls(21, PropertySetup.getBoojum(), buildBoojumHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the red properties"); } boojum.setText("<html>Boojum" + "<br>Flats: " + PropertySetup.getBoojum().getFlats() + "<br>Halls: " + PropertySetup.getBoojum().getHalls() + "</html>"); } }); final JButton buildPECHouse = new JButton("Build Flat £"+PropertySetup.getPec().getCostBuyFlat()); disableButtons(PropertySetup.getPec(), buildPECHouse); final JLabel pec = new JLabel("<html>PEC" + "<br>Flats: " + PropertySetup.getPec().getFlats() + "<br>Halls: " + PropertySetup.getPec().getHalls() + "</html>"); JButton pecOverdraft = new JButton("Overdraft"); pec.setForeground(Color.white); pec.setHorizontalAlignment(SwingConstants.CENTER); pec.setBorder(BorderFactory.createLineBorder(Color.black)); buildPECHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player1FlatsAndHalls(23, PropertySetup.getPec(), buildPECHouse); } else if (player2Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player2FlatsAndHalls(23, PropertySetup.getPec(), buildPECHouse); } else if (player3Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player3FlatsAndHalls(23, PropertySetup.getPec(), buildPECHouse); } else if (player4Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player4FlatsAndHalls(23, PropertySetup.getPec(), buildPECHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the red properties"); } pec.setText("<html>PEC" + "<br>Flats: " + PropertySetup.getPec().getFlats() + "<br>Halls: " + PropertySetup.getPec().getHalls() + "</html>"); } }); final JButton buildAshbyHouse = new JButton("Build Flat £"+PropertySetup.getAshbyBuilding().getCostBuyFlat()); disableButtons(PropertySetup.getAshbyBuilding(), buildAshbyHouse); final JLabel ashby = new JLabel("<html>Ashby Building" + "<br>Flats: " + PropertySetup.getAshbyBuilding().getFlats() + "<br>Halls: " + PropertySetup.getAshbyBuilding().getHalls() + "</html>"); JButton ashbyOverdraft = new JButton("Overdraft"); ashby.setForeground(Color.white); ashby.setHorizontalAlignment(SwingConstants.CENTER); ashby.setBorder(BorderFactory.createLineBorder(Color.black)); buildAshbyHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player1FlatsAndHalls(24, PropertySetup.getAshbyBuilding(), buildAshbyHouse); } else if (player2Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player2FlatsAndHalls(24, PropertySetup.getAshbyBuilding(), buildAshbyHouse); } else if (player3Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player3FlatsAndHalls(24, PropertySetup.getAshbyBuilding(), buildAshbyHouse); } else if (player4Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player4FlatsAndHalls(24, PropertySetup.getAshbyBuilding(), buildAshbyHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the red properties"); } ashby.setText("<html>Ashby Building" + "<br>Flats: " + PropertySetup.getAshbyBuilding().getFlats() + "<br>Halls: " + PropertySetup.getAshbyBuilding().getHalls() + "</html>"); } }); redPanel.add(boojum); redPanel.add(pec); redPanel.add(ashby); redPanel.add(buildBoojumHouse); redPanel.add(buildPECHouse); redPanel.add(buildAshbyHouse); redPanel.add(boojumOverdraft); redPanel.add(pecOverdraft); redPanel.add(ashbyOverdraft); /** * The Yellow */ final JButton buildMcClayHouse = new JButton("Build Flat £"+PropertySetup.getMcClayLibrary().getCostBuyFlat()); disableButtons(PropertySetup.getMcClayLibrary(), buildMcClayHouse); final JLabel mcClay = new JLabel("<html>McClay Library" + "<br>Flats: " + PropertySetup.getMcClayLibrary().getFlats() + "<br>Halls: " + PropertySetup.getMcClayLibrary().getHalls() + "</html>"); JButton mcClayOverdraft = new JButton("Overdraft"); mcClay.setForeground(Color.black); mcClay.setHorizontalAlignment(SwingConstants.CENTER); mcClay.setBorder(BorderFactory.createLineBorder(Color.black)); buildMcClayHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player1FlatsAndHalls(26, PropertySetup.getMcClayLibrary(), buildMcClayHouse); } else if (player2Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player2FlatsAndHalls(26, PropertySetup.getMcClayLibrary(), buildMcClayHouse); } else if (player3Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player3FlatsAndHalls(26, PropertySetup.getMcClayLibrary(), buildMcClayHouse); } else if (player4Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player4FlatsAndHalls(26, PropertySetup.getMcClayLibrary(), buildMcClayHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the yellow properties"); } mcClay.setText("<html>McClay Library" + "<br>Flats: " + PropertySetup.getMcClayLibrary().getFlats() + "<br>Halls: " + PropertySetup.getMcClayLibrary().getHalls() + "</html>"); } }); final JButton buildPeterHouse = new JButton("Build Flat £"+PropertySetup.getPeterFroggatCentre().getCostBuyFlat()); disableButtons(PropertySetup.getPeterFroggatCentre(), buildPeterHouse); final JLabel peter = new JLabel("<html>Peter Froggat Centre" + "<br>Flats: " + PropertySetup.getPeterFroggatCentre().getFlats() + "<br>Halls: " + PropertySetup.getPeterFroggatCentre().getHalls() + "</html>"); JButton peterOverdraft = new JButton("Overdraft"); peter.setForeground(Color.black); peter.setHorizontalAlignment(SwingConstants.CENTER); peter.setBorder(BorderFactory.createLineBorder(Color.black)); buildPeterHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player1FlatsAndHalls(27, PropertySetup.getPeterFroggatCentre(), buildPeterHouse); } else if (player2Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player2FlatsAndHalls(27, PropertySetup.getPeterFroggatCentre(), buildPeterHouse); } else if (player3Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player3FlatsAndHalls(27, PropertySetup.getPeterFroggatCentre(), buildPeterHouse); } else if (player4Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player4FlatsAndHalls(27, PropertySetup.getPeterFroggatCentre(), buildPeterHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the yellow properties"); } peter.setText("<html>Peter Froggat Centre" + "<br>Flats: " + PropertySetup.getPeterFroggatCentre().getFlats() + "<br>Halls: " + PropertySetup.getPeterFroggatCentre().getHalls() + "</html>"); } }); final JButton buildMbcHouse = new JButton("Build Flat £"+PropertySetup.getMbc().getCostBuyFlat()); disableButtons(PropertySetup.getMbc(), buildMbcHouse); final JLabel mbc = new JLabel("<html>MBC" + "<br>Flats: " + PropertySetup.getMbc().getFlats() + "<br>Halls: " + PropertySetup.getMbc().getHalls() + "</html>"); JButton mbcOverdraft = new JButton("Overdraft"); mbc.setForeground(Color.black); mbc.setHorizontalAlignment(SwingConstants.CENTER); mbc.setBorder(BorderFactory.createLineBorder(Color.black)); buildMbcHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player1FlatsAndHalls(29, PropertySetup.getMbc(), buildMbcHouse); } else if (player2Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player2FlatsAndHalls(29, PropertySetup.getMbc(), buildMbcHouse); } else if (player3Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player3FlatsAndHalls(29, PropertySetup.getMbc(), buildMbcHouse); } else if (player4Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player4FlatsAndHalls(29, PropertySetup.getMbc(), buildMbcHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the yellow properties"); } mbc.setText("<html>MBC" + "<br>Flats: " + PropertySetup.getMbc().getFlats() + "<br>Halls: " + PropertySetup.getMbc().getHalls() + "</html>"); } }); yellowPanel.add(mcClay); yellowPanel.add(peter); yellowPanel.add(mbc); yellowPanel.add(buildMcClayHouse); yellowPanel.add(buildPeterHouse); yellowPanel.add(buildMbcHouse); yellowPanel.add(mcClayOverdraft); yellowPanel.add(peterOverdraft); yellowPanel.add(mbcOverdraft); /** * The greens */ final JButton buildWhitlaHouse = new JButton("Build Flat £"+PropertySetup.getWhitlaHall().getCostBuyFlat()); disableButtons(PropertySetup.getWhitlaHall(), buildWhitlaHouse); final JLabel whitla = new JLabel("<html>Whitla Hall" + "<br>Flats: " + PropertySetup.getWhitlaHall().getFlats() + "<br>Halls: " + PropertySetup.getWhitlaHall().getHalls() + "</html>"); JButton whitlaOverdraft = new JButton("Overdraft"); whitla.setForeground(Color.white); whitla.setHorizontalAlignment(SwingConstants.CENTER); whitla.setBorder(BorderFactory.createLineBorder(Color.black)); buildWhitlaHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player1FlatsAndHalls(31, PropertySetup.getWhitlaHall(), buildWhitlaHouse); } else if (player2Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player2FlatsAndHalls(31, PropertySetup.getWhitlaHall(), buildWhitlaHouse); } else if (player3Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player3FlatsAndHalls(31, PropertySetup.getWhitlaHall(), buildWhitlaHouse); } else if (player4Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player4FlatsAndHalls(31, PropertySetup.getWhitlaHall(), buildWhitlaHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the green properties"); } whitla.setText("<html>Whitla Hall" + "<br>Flats: " + PropertySetup.getWhitlaHall().getFlats() + "<br>Halls: " + PropertySetup.getWhitlaHall().getHalls() + "</html>"); } }); final JButton buildDkbHouse = new JButton("Build Flat £"+PropertySetup.getDkb().getCostBuyFlat()); disableButtons(PropertySetup.getDkb(), buildDkbHouse); final JLabel dkb = new JLabel("<html>David Keir Building" + "<br>Flats: " + PropertySetup.getDkb().getFlats() + "<br>Halls: " + PropertySetup.getDkb().getHalls() + "</html>"); JButton dkbOverdraft = new JButton("Overdraft"); dkb.setForeground(Color.white); dkb.setHorizontalAlignment(SwingConstants.CENTER); dkb.setBorder(BorderFactory.createLineBorder(Color.black)); buildDkbHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player1FlatsAndHalls(32, PropertySetup.getDkb(), buildDkbHouse); } else if (player2Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player2FlatsAndHalls(32, PropertySetup.getDkb(), buildDkbHouse); } else if (player3Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player3FlatsAndHalls(32, PropertySetup.getDkb(), buildDkbHouse); } else if (player4Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player4FlatsAndHalls(32, PropertySetup.getDkb(), buildDkbHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the green properties"); } dkb.setText("<html>David Keir Building" + "<br>Flats: " + PropertySetup.getDkb().getFlats() + "<br>Halls: " + PropertySetup.getDkb().getHalls() + "</html>"); } }); final JButton buildSUHouse = new JButton("Build Flat £"+PropertySetup.getStudentUnion().getCostBuyFlat()); disableButtons(PropertySetup.getStudentUnion(), buildSUHouse); final JLabel su = new JLabel("<html>Students Union" + "<br>Flats: " + PropertySetup.getStudentUnion().getFlats() + "<br>Halls: " + PropertySetup.getStudentUnion().getHalls() + "</html>"); JButton suOverdraft = new JButton("Overdraft"); su.setForeground(Color.white); su.setHorizontalAlignment(SwingConstants.CENTER); su.setBorder(BorderFactory.createLineBorder(Color.black)); buildSUHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player1FlatsAndHalls(34, PropertySetup.getStudentUnion(), buildSUHouse); } else if (player2Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player2FlatsAndHalls(34, PropertySetup.getStudentUnion(), buildSUHouse); } else if (player3Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player3FlatsAndHalls(34, PropertySetup.getStudentUnion(), buildSUHouse); } else if (player4Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player4FlatsAndHalls(34, PropertySetup.getStudentUnion(), buildSUHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the green properties"); } su.setText("<html>Students Union" + "<br>Flats: " + PropertySetup.getStudentUnion().getFlats() + "<br>Halls: " + PropertySetup.getStudentUnion().getHalls() + "</html>"); } }); greenPanel.add(whitla); greenPanel.add(dkb); greenPanel.add(su); greenPanel.add(buildWhitlaHouse); greenPanel.add(buildDkbHouse); greenPanel.add(buildSUHouse); greenPanel.add(whitlaOverdraft); greenPanel.add(dkbOverdraft); greenPanel.add(suOverdraft); tabbedPane.addTab("Browns", brownPanel); tabbedPane.addTab("Blue", bluePanel); tabbedPane.addTab("Pink", pinkPanel); tabbedPane.addTab("Orange", orangePanel); tabbedPane.addTab("Red", redPanel); tabbedPane.addTab("Yellow", yellowPanel); tabbedPane.addTab("Green", greenPanel); tabbedPane.addTab("Purple", purplePanel); /** * * The purples */ final JButton buildBotHouse = new JButton("Build Flat £"+PropertySetup.getBotanicGardens().getCostBuyFlat()); disableButtons(PropertySetup.getBotanicGardens(), buildBotHouse); final JLabel bot = new JLabel("<html>Botanic Gardens" + "<br>Flats: " + PropertySetup.getBotanicGardens().getFlats() + "<br>Halls: " + PropertySetup.getBotanicGardens().getHalls() + "</html>"); JButton botOverdraft = new JButton("Overdraft"); bot.setForeground(Color.white); bot.setHorizontalAlignment(SwingConstants.CENTER); bot.setBorder(BorderFactory.createLineBorder(Color.black)); buildBotHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain2Method(PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player1FlatsAndHalls(37, PropertySetup.getBotanicGardens(), buildBotHouse); } else if (player2Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player2FlatsAndHalls(37, PropertySetup.getBotanicGardens(), buildBotHouse); } else if (player3Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player3FlatsAndHalls(37, PropertySetup.getBotanicGardens(), buildBotHouse); } else if (player4Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player4FlatsAndHalls(37, PropertySetup.getBotanicGardens(), buildBotHouse); } else { JOptionPane.showMessageDialog(null, "You do not own both of the purple properties"); } bot.setText("<html>Botanic Gardens" + "<br>Flats: " + PropertySetup.getBotanicGardens().getFlats() + "<br>Halls: " + PropertySetup.getBotanicGardens().getHalls() + "</html>"); } }); final JButton buildLanyonHouse = new JButton("Build Flat £"+PropertySetup.getLanyonBuilding().getCostBuyFlat()); disableButtons(PropertySetup.getLanyonBuilding(), buildLanyonHouse); final JLabel lanyon = new JLabel("<html>Lanyon Building" + "<br>Flats: " + PropertySetup.getLanyonBuilding().getFlats() + "<br>Halls: " + PropertySetup.getLanyonBuilding().getHalls() + "</html>"); JButton lanyonOverdraft = new JButton("Overdraft"); lanyon.setForeground(Color.white); lanyon.setHorizontalAlignment(SwingConstants.CENTER); lanyon.setBorder(BorderFactory.createLineBorder(Color.black)); buildLanyonHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain2Method(PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player1FlatsAndHalls(39, PropertySetup.getLanyonBuilding(), buildLanyonHouse); } else if (player2Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player2FlatsAndHalls(39, PropertySetup.getLanyonBuilding(), buildLanyonHouse); } else if (player3Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player3FlatsAndHalls(39, PropertySetup.getLanyonBuilding(), buildLanyonHouse); } else if (player4Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player4FlatsAndHalls(39, PropertySetup.getLanyonBuilding(), buildLanyonHouse); } else { JOptionPane.showMessageDialog(null, "You do not own both of the purple properties"); } lanyon.setText("<html>Lanyon Building" + "<br>Flats: " + PropertySetup.getLanyonBuilding().getFlats() + "<br>Halls: " + PropertySetup.getLanyonBuilding().getHalls() + "</html>"); } }); purplePanel.add(bot); purplePanel.add(lanyon); purplePanel.add(buildBotHouse); purplePanel.add(buildLanyonHouse); purplePanel.add(botOverdraft); purplePanel.add(lanyonOverdraft); add(topPanel); middlePanel.add(tabbedPane); add(middlePanel); aginOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getAgincourtAve()); } }); tatesOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getTatesAve()); } }); bcbOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getBcbRubble()); } }); dunOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getDunluceAve()); } }); maloneAOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getMaloneAve()); } }); socaOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getSoca()); } }); theologyOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getTheologyCentre()); } }); maloneROverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getMaloneRoad()); } }); fitzOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getFitzwilliamStreet()); } }); geoOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getGeographyBuilding()); } }); ecsOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getEcsBuilding()); } }); boojumOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getBoojum()); } }); pecOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getPec()); } }); ashbyOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getAshbyBuilding()); } }); mcClayOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getMcClayLibrary()); } }); peterOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getPeterFroggatCentre()); } }); mbcOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getMbc()); } }); whitlaOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getWhitlaHall()); } }); dkbOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getDkb()); } }); suOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getStudentUnion()); } }); botOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getBotanicGardens()); } }); lanyonOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getLanyonBuilding()); } }); } /** * This method is used to check if player 1 contains two properties in a row * @param properties - first property * @param properties2 - second property * @return - true or false depending on the above comments */ public boolean player1Contain2Method(Properties properties, Properties properties2) { if (LeftPanel.getPlayer1().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer1().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer1().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 1 contains three properties in a row * @param properties - first property * @param properties2 - second property * @param properties 3 - third property * @return - true or false depending on the above comments */ public boolean player1Contain3Method(Properties properties, Properties properties2, Properties properties3) { if (LeftPanel.getPlayer1().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer1().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer1().getPropertiesArray() .contains(properties3) && LeftPanel.getPlayer1().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 2 contains two properties in a row * @param properties - first property * @param properties2 - second property * @return - true or false depending on the above comments */ public boolean player2Contain2Method(Properties properties, Properties properties2) { if (LeftPanel.getPlayer2().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer2().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer2().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 2 contains three properties in a row * @param properties - first property * @param properties2 - second property * @param properties 3 - third property * @return - true or false depending on the above comments */ public boolean player2Contain3Method(Properties properties, Properties properties2, Properties properties3) { if (LeftPanel.getPlayer2().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer2().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer2().getPropertiesArray() .contains(properties3) && LeftPanel.getPlayer2().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 3 contains two properties in a row * @param properties - first property * @param properties2 - second property * @return - true or false depending on the above comments */ public boolean player3Contain2Method(Properties properties, Properties properties2) { if (LeftPanel.getPlayer3().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer3().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer3().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 3 contains three properties in a row * @param properties - first property * @param properties2 - second property * @param properties3 - third property * @return - true or false depending on the above comments */ public boolean player3Contain3Method(Properties properties, Properties properties2, Properties properties3) { if (LeftPanel.getPlayer3().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer3().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer3().getPropertiesArray() .contains(properties3) && LeftPanel.getPlayer3().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 4 contains two properties in a row * @param properties - first property * @param properties2 - second property * @return - true or false depending on the above comments */ public boolean player4Contain2Method(Properties properties, Properties properties2) { if (LeftPanel.getPlayer4().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer4().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer4().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 4 contains three properties in a row * @param properties - first property * @param properties2 - second property * @param properties 3 - third property * @return - true or false depending on the above comments */ public boolean player4Contain3Method(Properties properties, Properties properties2, Properties properties3) { if (LeftPanel.getPlayer4().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer4().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer4().getPropertiesArray() .contains(properties3) && LeftPanel.getPlayer4().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to build flats and halls for player 1 * @param i - property index * @param properties - the property to buy flats and halls on * @param button - the button to change the text of */ public void player1FlatsAndHalls(int i, Properties properties, JButton button) { if (PropertySetup.getProps().get(i).getFlats() < 4 && PropertySetup.getProps().get(i).getHalls() == 0) { PropertySetup.getProps().get(i) .setFlats(PropertySetup.getProps().get(i).getFlats() + 1); LeftPanel.getPlayer1().setPlayerMoney( LeftPanel.getPlayer1().getPlayerMoney() - properties.getCostBuyFlat()); } else if (PropertySetup.getProps().get(i).getFlats() == 4) { button.setText("Build Hall £" +PropertySetup.getProps().get(i).getCostBuyHalls()); PropertySetup.getProps().get(i).setFlats(0); PropertySetup.getProps().get(i).setHalls(1); LeftPanel.getPlayer1().setPlayerMoney( LeftPanel.getPlayer1().getPlayerMoney() - properties.getCostBuyHalls()); } else { button.setText("Maxed Out"); } updateLabels(); } /** * This method is used to build flats and halls for player 2 * @param i - property index * @param properties - the property to buy flats and halls on * @param button - the button to change the text of */ public void player2FlatsAndHalls(int i, Properties properties, JButton button) { if (PropertySetup.getProps().get(i).getFlats() < 4 && PropertySetup.getProps().get(i).getHalls() == 0) { PropertySetup.getProps().get(i) .setFlats(PropertySetup.getProps().get(i).getFlats() + 1); LeftPanel.getPlayer2().setPlayerMoney( LeftPanel.getPlayer2().getPlayerMoney() - properties.getCostBuyFlat()); } else if (PropertySetup.getProps().get(i).getFlats() == 4) { button.setText("Build Hall £"+PropertySetup.getProps().get(i).getCostBuyHalls()); PropertySetup.getProps().get(i).setFlats(0); PropertySetup.getProps().get(i).setHalls(1); LeftPanel.getPlayer2().setPlayerMoney( LeftPanel.getPlayer2().getPlayerMoney() - properties.getCostBuyHalls()); } else { button.setText("Maxed Out"); } updateLabels(); } /** * This method is used to build flats and halls for player 3 * @param i - property index * @param properties - the property to buy flats and halls on * @param button - the button to change the text of */ public void player3FlatsAndHalls(int i, Properties properties, JButton button) { if (PropertySetup.getProps().get(i).getFlats() < 4 && PropertySetup.getProps().get(i).getHalls() == 0) { PropertySetup.getProps().get(i) .setFlats(PropertySetup.getProps().get(i).getFlats() + 1); LeftPanel.getPlayer3().setPlayerMoney( LeftPanel.getPlayer3().getPlayerMoney() - properties.getCostBuyFlat()); } else if (PropertySetup.getProps().get(i).getFlats() == 4) { button.setText("Build Hall £"+PropertySetup.getProps().get(i).getCostBuyHalls()); PropertySetup.getProps().get(i).setFlats(0); PropertySetup.getProps().get(i).setHalls(1); LeftPanel.getPlayer3().setPlayerMoney( LeftPanel.getPlayer3().getPlayerMoney() - properties.getCostBuyHalls()); } else { button.setText("Maxed Out"); } updateLabels(); } /** * This method is used to build flats and halls for player 4 * @param i - property index * @param properties - the property to buy flats and halls on * @param button - the button to change the text of */ public void player4FlatsAndHalls(int i, Properties properties, JButton button) { if (PropertySetup.getProps().get(i).getFlats() < 4 && PropertySetup.getProps().get(i).getHalls() == 0) { PropertySetup.getProps().get(i) .setFlats(PropertySetup.getProps().get(i).getFlats() + 1); LeftPanel.getPlayer4().setPlayerMoney( LeftPanel.getPlayer4().getPlayerMoney() - properties.getCostBuyFlat()); } else if (PropertySetup.getProps().get(i).getFlats() == 4) { button.setText("Build Hall £"+PropertySetup.getProps().get(i).getCostBuyHalls()); PropertySetup.getProps().get(i).setFlats(0); PropertySetup.getProps().get(i).setHalls(1); LeftPanel.getPlayer4().setPlayerMoney( LeftPanel.getPlayer4().getPlayerMoney() - properties.getCostBuyHalls()); } else { button.setText("Maxed Out"); } updateLabels(); } /** * This method disables the button is the flats and halls for a property is at the limit * @param property - the property in question * @param button - the button to disable */ public void disableButtons(Properties property, JButton button) { if (property.getFlats() == 4) { button.setText("Build Hall"); } if (property.getHalls() == 1) { button.setEnabled(false); button.setText("Maxed Out"); } } /** * This method is used to sell properties * @param properties - the property to sell */ public void sellForOverdraft(Properties properties){ if(LeftPanel.getPlayer1().getPropertiesArray().contains(properties)){ LeftPanel.getPlayer1().getPropertiesArray().remove(properties); properties.setFlats(0); properties.setHalls(0); properties.setBuyable(true); LeftPanel.getPlayer1().setPlayerMoney(LeftPanel.getPlayer1().getPlayerMoney() + properties.getMortgageValue()); JOptionPane.showMessageDialog(null, "You have sold this property"); } else if(LeftPanel.getPlayer2().getPropertiesArray().contains(properties)){ LeftPanel.getPlayer2().getPropertiesArray().remove(properties); properties.setFlats(0); properties.setHalls(0); properties.setBuyable(true); LeftPanel.getPlayer2().setPlayerMoney(LeftPanel.getPlayer2().getPlayerMoney() + properties.getMortgageValue()); JOptionPane.showMessageDialog(null, "You have sold this property"); } else if(LeftPanel.getPlayer3().getPropertiesArray().contains(properties)){ LeftPanel.getPlayer3().getPropertiesArray().remove(properties); properties.setFlats(0); properties.setHalls(0); properties.setBuyable(true); LeftPanel.getPlayer3().setPlayerMoney(LeftPanel.getPlayer3().getPlayerMoney() + properties.getMortgageValue()); JOptionPane.showMessageDialog(null, "You have sold this property"); } else if(LeftPanel.getPlayer4().getPropertiesArray().contains(properties)){ LeftPanel.getPlayer4().getPropertiesArray().remove(properties); properties.setFlats(0); properties.setHalls(0); properties.setBuyable(true); LeftPanel.getPlayer4().setPlayerMoney(LeftPanel.getPlayer4().getPlayerMoney() + properties.getMortgageValue()); JOptionPane.showMessageDialog(null, "You have sold this property"); } else{ JOptionPane.showMessageDialog(null, "You do not own this property"); } updateLabels(); } public static void updateLabels(){ if(LeftPanel.getTotalPlayers() == 2){ LeftPanel.getPlayer1Label().setText( LeftPanel.getPlayer1().getPlayerName() + " £" + LeftPanel.getPlayer1().getPlayerMoney()); LeftPanel.getPlayer2Label().setText( LeftPanel.getPlayer2().getPlayerName() + " £" + LeftPanel.getPlayer2().getPlayerMoney()); } else if(LeftPanel.getTotalPlayers() == 3){ LeftPanel.getPlayer1Label().setText( LeftPanel.getPlayer1().getPlayerName() + " £" + LeftPanel.getPlayer1().getPlayerMoney()); LeftPanel.getPlayer2Label().setText( LeftPanel.getPlayer2().getPlayerName() + " £" + LeftPanel.getPlayer2().getPlayerMoney()); LeftPanel.getPlayer3Label().setText( LeftPanel.getPlayer3().getPlayerName() + " £" + LeftPanel.getPlayer3().getPlayerMoney()); } else if(LeftPanel.getTotalPlayers() == 4){ LeftPanel.getPlayer1Label().setText( LeftPanel.getPlayer1().getPlayerName() + " £" + LeftPanel.getPlayer1().getPlayerMoney()); LeftPanel.getPlayer2Label().setText( LeftPanel.getPlayer2().getPlayerName() + " £" + LeftPanel.getPlayer2().getPlayerMoney()); LeftPanel.getPlayer3Label().setText( LeftPanel.getPlayer3().getPlayerName() + " £" + LeftPanel.getPlayer3().getPlayerMoney()); LeftPanel.getPlayer4Label().setText( LeftPanel.getPlayer4().getPlayerName() + " £" + LeftPanel.getPlayer4().getPlayerMoney()); } } }
WINDOWS-1252
Java
64,993
java
Building.java
Java
[ { "context": "ild flats/halls and sell properties\n * \n * @author Brogrammers\n */\n@SuppressWarnings(\"serial\")\npublic class ", "end": 582, "score": 0.5649631023406982, "start": 575, "tag": "USERNAME", "value": "Brogram" }, { "context": "s/halls and sell properties\n * \n * @auth...
null
[]
package mainWindow; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingConstants; import mainGame.Properties; import mainGame.PropertySetup; /** * This class creates the interface to build flats/halls and sell properties * * @author Brogrammers */ @SuppressWarnings("serial") public class Building extends JFrame { @SuppressWarnings("unused") private int TASKBARSIZE = 45; // private static Dimension screenRes; /** * This constructor creates the interface */ public Building() { setupFrame(); validate(); revalidate(); repaint(); } /** * This method sets up the frame giving it's default options and adding action listeners * for each JButton in each tab of the interface */ private void setupFrame() { // screenRes = Toolkit.getDefaultToolkit().getScreenSize(); setSize(600, 400); setVisible(true); setResizable(false); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setLocationRelativeTo(null); ImageIcon windowIcon = new ImageIcon("images/windowIcon.jpg"); setIconImage(windowIcon.getImage()); setTitle("Build"); JPanel topPanel = new JPanel(); topPanel.setBackground(Color.lightGray); JTabbedPane tabbedPane = new JTabbedPane(); JPanel middlePanel = new JPanel(new GridLayout()); JPanel brownPanel = new JPanel(new GridLayout(3, 2)); Color brown = new Color(129, 69, 19); brownPanel.setBackground(brown); JPanel bluePanel = new JPanel(new GridLayout(3, 3)); bluePanel.setBackground(Color.cyan); JPanel pinkPanel = new JPanel(new GridLayout(3, 3)); Color pink = new Color(255, 51, 153); pinkPanel.setBackground(pink); JPanel orangePanel = new JPanel(new GridLayout(3, 3)); orangePanel.setBackground(Color.orange); JPanel redPanel = new JPanel(new GridLayout(3, 3)); redPanel.setBackground(Color.red); JPanel yellowPanel = new JPanel(new GridLayout(3, 3)); yellowPanel.setBackground(Color.yellow); JPanel greenPanel = new JPanel(new GridLayout(3, 3)); greenPanel.setBackground(Color.GREEN); JPanel purplePanel = new JPanel(new GridLayout(3, 2)); purplePanel.setBackground(Color.blue); /** * The brown tab * * */ final JButton buildAginHouse = new JButton("Build Flat £" +PropertySetup.getAgincourtAve().getCostBuyFlat()); disableButtons(PropertySetup.getAgincourtAve(), buildAginHouse); final JLabel agin = new JLabel("<html>Agincourt Avenue<br>Flats: " + PropertySetup.getAgincourtAve().getFlats() + "<br>Halls: " + PropertySetup.getAgincourtAve().getHalls() + "<html>"); agin.setHorizontalAlignment(SwingConstants.CENTER); agin.setForeground(Color.white); agin.setBorder(BorderFactory.createLineBorder(Color.black)); JButton aginOverdraft = new JButton("Overdraft"); // Buying a house for AginCourt buildAginHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain2Method(PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player1FlatsAndHalls(1, PropertySetup.getAgincourtAve(), buildAginHouse); } else if (player2Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player2FlatsAndHalls(1, PropertySetup.getAgincourtAve(), buildAginHouse); } else if (player3Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player3FlatsAndHalls(1, PropertySetup.getAgincourtAve(), buildAginHouse); } else if (player4Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player4FlatsAndHalls(1, PropertySetup.getAgincourtAve(), buildAginHouse); } else { JOptionPane.showMessageDialog(null, "You do not own both of the brown properties"); } agin.setText("<html>Agincourt Avenue<br>Flats: " + PropertySetup.getAgincourtAve().getFlats() + "<br>Halls: " + PropertySetup.getAgincourtAve().getHalls() + "<html>"); } }); final JButton buildTatesHouse = new JButton("Build Flat £"+PropertySetup.getTatesAve().getCostBuyFlat()); disableButtons(PropertySetup.getTatesAve(), buildTatesHouse); final JLabel tate = new JLabel("<html>Tates" + "<br>Flats: " + PropertySetup.getTatesAve().getFlats() + "<br>Halls: " + PropertySetup.getTatesAve().getHalls() + "<html>"); JButton tatesOverdraft = new JButton("Overdraft"); tate.setHorizontalAlignment(SwingConstants.CENTER); tate.setForeground(Color.WHITE); tate.setBorder(BorderFactory.createLineBorder(Color.black)); buildTatesHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain2Method(PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player1FlatsAndHalls(3, PropertySetup.getAgincourtAve(), buildTatesHouse); } else if (player2Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player2FlatsAndHalls(3, PropertySetup.getAgincourtAve(), buildTatesHouse); } else if (player3Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player3FlatsAndHalls(3, PropertySetup.getAgincourtAve(), buildTatesHouse); } else if (player4Contain2Method( PropertySetup.getAgincourtAve(), PropertySetup.getTatesAve())) { player4FlatsAndHalls(3, PropertySetup.getAgincourtAve(), buildTatesHouse); } else { JOptionPane.showMessageDialog(null, "You do not own both of the brown properties"); } tate.setText("<html>Tates" + "<br>Flats: " + PropertySetup.getTatesAve().getFlats() + "<br>Halls: " + PropertySetup.getTatesAve().getHalls() + "<html>"); } }); brownPanel.add(agin); brownPanel.add(tate); brownPanel.add(buildAginHouse); brownPanel.add(buildTatesHouse); brownPanel.add(aginOverdraft); brownPanel.add(tatesOverdraft); /** * The Blue Tab */ final JButton buildBcbHouse = new JButton("Build Flat £"+PropertySetup.getBcbRubble().getCostBuyFlat()); disableButtons(PropertySetup.getBcbRubble(), buildBcbHouse); final JLabel bcb = new JLabel("<html>BCB Rubble" + "<br>Flats: " + PropertySetup.getBcbRubble().getFlats() + "<br>Halls: " + PropertySetup.getBcbRubble().getHalls() + "</html>"); bcb.setForeground(Color.black); bcb.setHorizontalAlignment(SwingConstants.CENTER); bcb.setBorder(BorderFactory.createLineBorder(Color.black)); JButton bcbOverdraft = new JButton("Overdraft"); buildBcbHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player1FlatsAndHalls(6, PropertySetup.getBcbRubble(), buildBcbHouse); } else if (player2Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player2FlatsAndHalls(6, PropertySetup.getBcbRubble(), buildBcbHouse); } else if (player3Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player3FlatsAndHalls(6, PropertySetup.getBcbRubble(), buildBcbHouse); } else if (player4Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player4FlatsAndHalls(3, PropertySetup.getBcbRubble(), buildBcbHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the blue properties"); } bcb.setText("<html>BCB Rubble" + "<br>Flats: " + PropertySetup.getBcbRubble().getFlats() + "<br>Halls: " + PropertySetup.getBcbRubble().getHalls() + "</html>"); } }); final JButton buildDunluceHouse = new JButton("Build Flat £"+PropertySetup.getDunluceAve().getCostBuyFlat()); disableButtons(PropertySetup.getDunluceAve(), buildDunluceHouse); final JLabel dun = new JLabel("<html>Dunluce Avenue" + "<br>Flats: " + PropertySetup.getDunluceAve().getFlats() + "<br>Halls: " + PropertySetup.getDunluceAve().getHalls() + "</html>"); dun.setForeground(Color.black); dun.setHorizontalAlignment(SwingConstants.CENTER); dun.setBorder(BorderFactory.createLineBorder(Color.black)); JButton dunOverdraft = new JButton("Overdraft"); buildDunluceHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player1FlatsAndHalls(8, PropertySetup.getDunluceAve(), buildDunluceHouse); } else if (player2Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player2FlatsAndHalls(8, PropertySetup.getDunluceAve(), buildDunluceHouse); } else if (player3Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player3FlatsAndHalls(8, PropertySetup.getDunluceAve(), buildDunluceHouse); } else if (player4Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player4FlatsAndHalls(8, PropertySetup.getDunluceAve(), buildDunluceHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the blue properties"); } dun.setText("<html>Dunluce Avenue" + "<br>Flats: " + PropertySetup.getDunluceAve().getFlats() + "<br>Halls: " + PropertySetup.getDunluceAve().getHalls() + "</html>"); } }); final JButton buildMaloneAHouse = new JButton("Build Flat £"+PropertySetup.getMaloneAve().getCostBuyFlat()); disableButtons(PropertySetup.getMaloneAve(), buildMaloneAHouse); final JLabel maloneA = new JLabel("<html>Malone Avenue" + "<br>Flats: " + PropertySetup.getMaloneAve().getFlats() + "<br>Halls: " + PropertySetup.getMaloneAve().getHalls() + "</html>"); JButton maloneAOverdraft = new JButton("Overdraft"); maloneA.setForeground(Color.black); maloneA.setHorizontalAlignment(SwingConstants.CENTER); maloneA.setBorder(BorderFactory.createLineBorder(Color.black)); buildMaloneAHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player1FlatsAndHalls(9, PropertySetup.getMaloneAve(), buildMaloneAHouse); } else if (player2Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player2FlatsAndHalls(9, PropertySetup.getMaloneAve(), buildMaloneAHouse); } else if (player3Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player3FlatsAndHalls(9, PropertySetup.getMaloneAve(), buildMaloneAHouse); } else if (player4Contain3Method(PropertySetup.getBcbRubble(), PropertySetup.getDunluceAve(), PropertySetup.getMaloneAve())) { player4FlatsAndHalls(9, PropertySetup.getMaloneAve(), buildMaloneAHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the blue properties"); } maloneA.setText("<html>Malone Avenue" + "<br>Flats: " + PropertySetup.getMaloneAve().getFlats() + "<br>Halls: " + PropertySetup.getMaloneAve().getHalls() + "</html>"); } }); bluePanel.add(bcb); bluePanel.add(dun); bluePanel.add(maloneA); bluePanel.add(buildBcbHouse); bluePanel.add(buildDunluceHouse); bluePanel.add(buildMaloneAHouse); bluePanel.add(bcbOverdraft); bluePanel.add(dunOverdraft); bluePanel.add(maloneAOverdraft); /** * * The Pinks */ final JButton buildSocaHouse = new JButton("Build Flat £"+PropertySetup.getSoca().getCostBuyFlat()); disableButtons(PropertySetup.getSoca(), buildSocaHouse); final JLabel soca = new JLabel("<html>School Of Creative Arts" + "<br>Flats: " + PropertySetup.getSoca().getFlats() + "<br>Halls: " + PropertySetup.getSoca().getHalls() + "</html>"); JButton socaOverdraft = new JButton("Overdraft"); soca.setForeground(Color.white); soca.setHorizontalAlignment(SwingConstants.CENTER); soca.setBorder(BorderFactory.createLineBorder(Color.black)); buildSocaHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player1FlatsAndHalls(11, PropertySetup.getSoca(), buildSocaHouse); } else if (player2Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player2FlatsAndHalls(11, PropertySetup.getSoca(), buildSocaHouse); } else if (player3Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player3FlatsAndHalls(11, PropertySetup.getSoca(), buildSocaHouse); } else if (player4Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player4FlatsAndHalls(11, PropertySetup.getSoca(), buildSocaHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the pink properties"); } soca.setText("<html>School Of Creative Arts" + "<br>Flats: " + PropertySetup.getSoca().getFlats() + "<br>Halls: " + PropertySetup.getSoca().getHalls() + "</html>"); } }); final JButton buildTheologyHouse = new JButton("Build Flat £"+PropertySetup.getTheologyCentre().getCostBuyFlat()); disableButtons(PropertySetup.getTheologyCentre(), buildTheologyHouse); final JLabel theo = new JLabel("<html>Theology Centre" + "<br>Flats: " + PropertySetup.getTheologyCentre().getFlats() + "<br>Halls: " + PropertySetup.getTheologyCentre().getHalls() + "</html>"); JButton theologyOverdraft = new JButton("Overdraft"); theo.setForeground(Color.white); theo.setHorizontalAlignment(SwingConstants.CENTER); theo.setBorder(BorderFactory.createLineBorder(Color.black)); buildTheologyHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player1FlatsAndHalls(13, PropertySetup.getTheologyCentre(), buildTheologyHouse); } else if (player2Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player2FlatsAndHalls(13, PropertySetup.getTheologyCentre(), buildTheologyHouse); } else if (player3Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player3FlatsAndHalls(13, PropertySetup.getTheologyCentre(), buildTheologyHouse); } else if (player4Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player4FlatsAndHalls(13, PropertySetup.getTheologyCentre(), buildTheologyHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the pink properties"); } theo.setText("<html>Theology Centre" + "<br>Flats: " + PropertySetup.getTheologyCentre().getFlats() + "<br>Halls: " + PropertySetup.getTheologyCentre().getHalls() + "</html>"); } }); final JButton buildMaloneRHouse = new JButton("Build Flat £"+PropertySetup.getMaloneRoad().getCostBuyFlat()); disableButtons(PropertySetup.getMaloneRoad(), buildMaloneRHouse); final JLabel maloneR = new JLabel("<html>Malone Road" + "<br>Flats: " + PropertySetup.getMaloneRoad().getFlats() + "<br>Halls: " + PropertySetup.getMaloneRoad().getHalls() + "</html>"); JButton maloneROverdraft = new JButton("Overdraft"); maloneR.setForeground(Color.white); maloneR.setHorizontalAlignment(SwingConstants.CENTER); maloneR.setBorder(BorderFactory.createLineBorder(Color.black)); buildMaloneRHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player1FlatsAndHalls(14, PropertySetup.getMaloneRoad(), buildMaloneRHouse); } else if (player2Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player2FlatsAndHalls(14, PropertySetup.getMaloneRoad(), buildMaloneRHouse); } else if (player3Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player3FlatsAndHalls(14, PropertySetup.getMaloneRoad(), buildMaloneRHouse); } else if (player4Contain3Method(PropertySetup.getSoca(), PropertySetup.getTheologyCentre(), PropertySetup.getMaloneRoad())) { player4FlatsAndHalls(14, PropertySetup.getMaloneRoad(), buildMaloneRHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the pink properties"); } maloneR.setText("<html>Malone Road" + "<br>Flats: " + PropertySetup.getMaloneRoad().getFlats() + "<br>Halls: " + PropertySetup.getMaloneRoad().getHalls() + "</html>"); } }); pinkPanel.add(soca); pinkPanel.add(theo); pinkPanel.add(maloneR); pinkPanel.add(buildSocaHouse); pinkPanel.add(buildTheologyHouse); pinkPanel.add(buildMaloneRHouse); pinkPanel.add(socaOverdraft); pinkPanel.add(theologyOverdraft); pinkPanel.add(maloneROverdraft); /** * * The orange */ final JButton buildFitzHouse = new JButton("Build Flat £"+PropertySetup.getFitzwilliamStreet().getCostBuyFlat()); disableButtons(PropertySetup.getFitzwilliamStreet(), buildFitzHouse); final JLabel fitz = new JLabel("<html>Fitzwilliam Street" + "<br>Flats: " + PropertySetup.getFitzwilliamStreet().getFlats() + "<br>Halls: " + PropertySetup.getFitzwilliamStreet().getHalls() + "</html>"); JButton fitzOverdraft = new JButton("Overdraft"); fitz.setForeground(Color.white); fitz.setHorizontalAlignment(SwingConstants.CENTER); fitz.setBorder(BorderFactory.createLineBorder(Color.black)); buildFitzHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player1FlatsAndHalls(16, PropertySetup.getFitzwilliamStreet(), buildFitzHouse); } else if (player2Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player2FlatsAndHalls(16, PropertySetup.getFitzwilliamStreet(), buildFitzHouse); } else if (player3Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player3FlatsAndHalls(16, PropertySetup.getFitzwilliamStreet(), buildFitzHouse); } else if (player4Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player4FlatsAndHalls(16, PropertySetup.getFitzwilliamStreet(), buildFitzHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the orange properties"); } fitz.setText("<html>Fitzwilliam Street" + "<br>Flats: " + PropertySetup.getFitzwilliamStreet().getFlats() + "<br>Halls: " + PropertySetup.getFitzwilliamStreet().getHalls() + "</html>"); } }); final JButton buildGeoHouse = new JButton("Build Flat £"+PropertySetup.getGeographyBuilding().getCostBuyFlat()); disableButtons(PropertySetup.getGeographyBuilding(), buildGeoHouse); final JLabel geo = new JLabel("<html>Geography Building" + "<br>Flats: " + PropertySetup.getGeographyBuilding().getFlats() + "<br>Halls: " + PropertySetup.getGeographyBuilding().getHalls() + "</html>"); JButton geoOverdraft = new JButton("Overdraft"); geo.setForeground(Color.white); geo.setHorizontalAlignment(SwingConstants.CENTER); geo.setBorder(BorderFactory.createLineBorder(Color.black)); buildGeoHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player1FlatsAndHalls(18, PropertySetup.getGeographyBuilding(), buildGeoHouse); } else if (player2Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player2FlatsAndHalls(18, PropertySetup.getGeographyBuilding(), buildGeoHouse); } else if (player3Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player3FlatsAndHalls(18, PropertySetup.getGeographyBuilding(), buildGeoHouse); } else if (player4Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player4FlatsAndHalls(18, PropertySetup.getGeographyBuilding(), buildGeoHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the orange properties"); } geo.setText("<html>Geography Building" + "<br>Flats: " + PropertySetup.getGeographyBuilding().getFlats() + "<br>Halls: " + PropertySetup.getGeographyBuilding().getHalls() + "</html>"); } }); final JButton buildEcsHouse = new JButton("Build Flat £"+PropertySetup.getEcsBuilding().getCostBuyFlat()); disableButtons(PropertySetup.getEcsBuilding(), buildEcsHouse); final JLabel ecs = new JLabel("<html>ECS Building" + "<br>Flats: " + PropertySetup.getEcsBuilding().getFlats() + "<br>Halls: " + PropertySetup.getEcsBuilding().getHalls() + "</html>"); JButton ecsOverdraft = new JButton("Overdraft"); ecs.setForeground(Color.white); ecs.setHorizontalAlignment(SwingConstants.CENTER); ecs.setBorder(BorderFactory.createLineBorder(Color.black)); buildEcsHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player1FlatsAndHalls(19, PropertySetup.getEcsBuilding(), buildEcsHouse); } else if (player2Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player2FlatsAndHalls(19, PropertySetup.getEcsBuilding(), buildEcsHouse); } else if (player3Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player3FlatsAndHalls(19, PropertySetup.getEcsBuilding(), buildEcsHouse); } else if (player4Contain3Method( PropertySetup.getFitzwilliamStreet(), PropertySetup.getGeographyBuilding(), PropertySetup.getEcsBuilding())) { player4FlatsAndHalls(19, PropertySetup.getEcsBuilding(), buildEcsHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the orange properties"); } ecs.setText("<html>ECS Building" + "<br>Flats: " + PropertySetup.getEcsBuilding().getFlats() + "<br>Halls: " + PropertySetup.getEcsBuilding().getHalls() + "</html>"); } }); orangePanel.add(fitz); orangePanel.add(geo); orangePanel.add(ecs); orangePanel.add(buildFitzHouse); orangePanel.add(buildGeoHouse); orangePanel.add(buildEcsHouse); orangePanel.add(fitzOverdraft); orangePanel.add(geoOverdraft); orangePanel.add(ecsOverdraft); /** * The red * */ final JButton buildBoojumHouse = new JButton("Build Flat £"+PropertySetup.getBoojum().getCostBuyFlat()); disableButtons(PropertySetup.getBoojum(), buildBoojumHouse); final JLabel boojum = new JLabel("<html>Boojum" + "<br>Flats: " + PropertySetup.getBoojum().getFlats() + "<br>Halls: " + PropertySetup.getBoojum().getHalls() + "</html>"); JButton boojumOverdraft = new JButton("Overdraft"); boojum.setForeground(Color.white); boojum.setHorizontalAlignment(SwingConstants.CENTER); boojum.setBorder(BorderFactory.createLineBorder(Color.black)); buildBoojumHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player1FlatsAndHalls(21, PropertySetup.getBoojum(), buildBoojumHouse); } else if (player2Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player2FlatsAndHalls(21, PropertySetup.getBoojum(), buildBoojumHouse); } else if (player3Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player3FlatsAndHalls(21, PropertySetup.getBoojum(), buildBoojumHouse); } else if (player4Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player4FlatsAndHalls(21, PropertySetup.getBoojum(), buildBoojumHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the red properties"); } boojum.setText("<html>Boojum" + "<br>Flats: " + PropertySetup.getBoojum().getFlats() + "<br>Halls: " + PropertySetup.getBoojum().getHalls() + "</html>"); } }); final JButton buildPECHouse = new JButton("Build Flat £"+PropertySetup.getPec().getCostBuyFlat()); disableButtons(PropertySetup.getPec(), buildPECHouse); final JLabel pec = new JLabel("<html>PEC" + "<br>Flats: " + PropertySetup.getPec().getFlats() + "<br>Halls: " + PropertySetup.getPec().getHalls() + "</html>"); JButton pecOverdraft = new JButton("Overdraft"); pec.setForeground(Color.white); pec.setHorizontalAlignment(SwingConstants.CENTER); pec.setBorder(BorderFactory.createLineBorder(Color.black)); buildPECHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player1FlatsAndHalls(23, PropertySetup.getPec(), buildPECHouse); } else if (player2Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player2FlatsAndHalls(23, PropertySetup.getPec(), buildPECHouse); } else if (player3Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player3FlatsAndHalls(23, PropertySetup.getPec(), buildPECHouse); } else if (player4Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player4FlatsAndHalls(23, PropertySetup.getPec(), buildPECHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the red properties"); } pec.setText("<html>PEC" + "<br>Flats: " + PropertySetup.getPec().getFlats() + "<br>Halls: " + PropertySetup.getPec().getHalls() + "</html>"); } }); final JButton buildAshbyHouse = new JButton("Build Flat £"+PropertySetup.getAshbyBuilding().getCostBuyFlat()); disableButtons(PropertySetup.getAshbyBuilding(), buildAshbyHouse); final JLabel ashby = new JLabel("<html>Ashby Building" + "<br>Flats: " + PropertySetup.getAshbyBuilding().getFlats() + "<br>Halls: " + PropertySetup.getAshbyBuilding().getHalls() + "</html>"); JButton ashbyOverdraft = new JButton("Overdraft"); ashby.setForeground(Color.white); ashby.setHorizontalAlignment(SwingConstants.CENTER); ashby.setBorder(BorderFactory.createLineBorder(Color.black)); buildAshbyHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player1FlatsAndHalls(24, PropertySetup.getAshbyBuilding(), buildAshbyHouse); } else if (player2Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player2FlatsAndHalls(24, PropertySetup.getAshbyBuilding(), buildAshbyHouse); } else if (player3Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player3FlatsAndHalls(24, PropertySetup.getAshbyBuilding(), buildAshbyHouse); } else if (player4Contain3Method(PropertySetup.getBoojum(), PropertySetup.getPec(), PropertySetup.getAshbyBuilding())) { player4FlatsAndHalls(24, PropertySetup.getAshbyBuilding(), buildAshbyHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the red properties"); } ashby.setText("<html>Ashby Building" + "<br>Flats: " + PropertySetup.getAshbyBuilding().getFlats() + "<br>Halls: " + PropertySetup.getAshbyBuilding().getHalls() + "</html>"); } }); redPanel.add(boojum); redPanel.add(pec); redPanel.add(ashby); redPanel.add(buildBoojumHouse); redPanel.add(buildPECHouse); redPanel.add(buildAshbyHouse); redPanel.add(boojumOverdraft); redPanel.add(pecOverdraft); redPanel.add(ashbyOverdraft); /** * The Yellow */ final JButton buildMcClayHouse = new JButton("Build Flat £"+PropertySetup.getMcClayLibrary().getCostBuyFlat()); disableButtons(PropertySetup.getMcClayLibrary(), buildMcClayHouse); final JLabel mcClay = new JLabel("<html>McClay Library" + "<br>Flats: " + PropertySetup.getMcClayLibrary().getFlats() + "<br>Halls: " + PropertySetup.getMcClayLibrary().getHalls() + "</html>"); JButton mcClayOverdraft = new JButton("Overdraft"); mcClay.setForeground(Color.black); mcClay.setHorizontalAlignment(SwingConstants.CENTER); mcClay.setBorder(BorderFactory.createLineBorder(Color.black)); buildMcClayHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player1FlatsAndHalls(26, PropertySetup.getMcClayLibrary(), buildMcClayHouse); } else if (player2Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player2FlatsAndHalls(26, PropertySetup.getMcClayLibrary(), buildMcClayHouse); } else if (player3Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player3FlatsAndHalls(26, PropertySetup.getMcClayLibrary(), buildMcClayHouse); } else if (player4Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player4FlatsAndHalls(26, PropertySetup.getMcClayLibrary(), buildMcClayHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the yellow properties"); } mcClay.setText("<html>McClay Library" + "<br>Flats: " + PropertySetup.getMcClayLibrary().getFlats() + "<br>Halls: " + PropertySetup.getMcClayLibrary().getHalls() + "</html>"); } }); final JButton buildPeterHouse = new JButton("Build Flat £"+PropertySetup.getPeterFroggatCentre().getCostBuyFlat()); disableButtons(PropertySetup.getPeterFroggatCentre(), buildPeterHouse); final JLabel peter = new JLabel("<html>Peter Froggat Centre" + "<br>Flats: " + PropertySetup.getPeterFroggatCentre().getFlats() + "<br>Halls: " + PropertySetup.getPeterFroggatCentre().getHalls() + "</html>"); JButton peterOverdraft = new JButton("Overdraft"); peter.setForeground(Color.black); peter.setHorizontalAlignment(SwingConstants.CENTER); peter.setBorder(BorderFactory.createLineBorder(Color.black)); buildPeterHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player1FlatsAndHalls(27, PropertySetup.getPeterFroggatCentre(), buildPeterHouse); } else if (player2Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player2FlatsAndHalls(27, PropertySetup.getPeterFroggatCentre(), buildPeterHouse); } else if (player3Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player3FlatsAndHalls(27, PropertySetup.getPeterFroggatCentre(), buildPeterHouse); } else if (player4Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player4FlatsAndHalls(27, PropertySetup.getPeterFroggatCentre(), buildPeterHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the yellow properties"); } peter.setText("<html>Peter Froggat Centre" + "<br>Flats: " + PropertySetup.getPeterFroggatCentre().getFlats() + "<br>Halls: " + PropertySetup.getPeterFroggatCentre().getHalls() + "</html>"); } }); final JButton buildMbcHouse = new JButton("Build Flat £"+PropertySetup.getMbc().getCostBuyFlat()); disableButtons(PropertySetup.getMbc(), buildMbcHouse); final JLabel mbc = new JLabel("<html>MBC" + "<br>Flats: " + PropertySetup.getMbc().getFlats() + "<br>Halls: " + PropertySetup.getMbc().getHalls() + "</html>"); JButton mbcOverdraft = new JButton("Overdraft"); mbc.setForeground(Color.black); mbc.setHorizontalAlignment(SwingConstants.CENTER); mbc.setBorder(BorderFactory.createLineBorder(Color.black)); buildMbcHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player1FlatsAndHalls(29, PropertySetup.getMbc(), buildMbcHouse); } else if (player2Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player2FlatsAndHalls(29, PropertySetup.getMbc(), buildMbcHouse); } else if (player3Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player3FlatsAndHalls(29, PropertySetup.getMbc(), buildMbcHouse); } else if (player4Contain3Method( PropertySetup.getMcClayLibrary(), PropertySetup.getPeterFroggatCentre(), PropertySetup.getMbc())) { player4FlatsAndHalls(29, PropertySetup.getMbc(), buildMbcHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the yellow properties"); } mbc.setText("<html>MBC" + "<br>Flats: " + PropertySetup.getMbc().getFlats() + "<br>Halls: " + PropertySetup.getMbc().getHalls() + "</html>"); } }); yellowPanel.add(mcClay); yellowPanel.add(peter); yellowPanel.add(mbc); yellowPanel.add(buildMcClayHouse); yellowPanel.add(buildPeterHouse); yellowPanel.add(buildMbcHouse); yellowPanel.add(mcClayOverdraft); yellowPanel.add(peterOverdraft); yellowPanel.add(mbcOverdraft); /** * The greens */ final JButton buildWhitlaHouse = new JButton("Build Flat £"+PropertySetup.getWhitlaHall().getCostBuyFlat()); disableButtons(PropertySetup.getWhitlaHall(), buildWhitlaHouse); final JLabel whitla = new JLabel("<html>Whitla Hall" + "<br>Flats: " + PropertySetup.getWhitlaHall().getFlats() + "<br>Halls: " + PropertySetup.getWhitlaHall().getHalls() + "</html>"); JButton whitlaOverdraft = new JButton("Overdraft"); whitla.setForeground(Color.white); whitla.setHorizontalAlignment(SwingConstants.CENTER); whitla.setBorder(BorderFactory.createLineBorder(Color.black)); buildWhitlaHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player1FlatsAndHalls(31, PropertySetup.getWhitlaHall(), buildWhitlaHouse); } else if (player2Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player2FlatsAndHalls(31, PropertySetup.getWhitlaHall(), buildWhitlaHouse); } else if (player3Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player3FlatsAndHalls(31, PropertySetup.getWhitlaHall(), buildWhitlaHouse); } else if (player4Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player4FlatsAndHalls(31, PropertySetup.getWhitlaHall(), buildWhitlaHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the green properties"); } whitla.setText("<html>Whitla Hall" + "<br>Flats: " + PropertySetup.getWhitlaHall().getFlats() + "<br>Halls: " + PropertySetup.getWhitlaHall().getHalls() + "</html>"); } }); final JButton buildDkbHouse = new JButton("Build Flat £"+PropertySetup.getDkb().getCostBuyFlat()); disableButtons(PropertySetup.getDkb(), buildDkbHouse); final JLabel dkb = new JLabel("<html><NAME> Building" + "<br>Flats: " + PropertySetup.getDkb().getFlats() + "<br>Halls: " + PropertySetup.getDkb().getHalls() + "</html>"); JButton dkbOverdraft = new JButton("Overdraft"); dkb.setForeground(Color.white); dkb.setHorizontalAlignment(SwingConstants.CENTER); dkb.setBorder(BorderFactory.createLineBorder(Color.black)); buildDkbHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player1FlatsAndHalls(32, PropertySetup.getDkb(), buildDkbHouse); } else if (player2Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player2FlatsAndHalls(32, PropertySetup.getDkb(), buildDkbHouse); } else if (player3Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player3FlatsAndHalls(32, PropertySetup.getDkb(), buildDkbHouse); } else if (player4Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player4FlatsAndHalls(32, PropertySetup.getDkb(), buildDkbHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the green properties"); } dkb.setText("<html><NAME> Building" + "<br>Flats: " + PropertySetup.getDkb().getFlats() + "<br>Halls: " + PropertySetup.getDkb().getHalls() + "</html>"); } }); final JButton buildSUHouse = new JButton("Build Flat £"+PropertySetup.getStudentUnion().getCostBuyFlat()); disableButtons(PropertySetup.getStudentUnion(), buildSUHouse); final JLabel su = new JLabel("<html>Students Union" + "<br>Flats: " + PropertySetup.getStudentUnion().getFlats() + "<br>Halls: " + PropertySetup.getStudentUnion().getHalls() + "</html>"); JButton suOverdraft = new JButton("Overdraft"); su.setForeground(Color.white); su.setHorizontalAlignment(SwingConstants.CENTER); su.setBorder(BorderFactory.createLineBorder(Color.black)); buildSUHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player1FlatsAndHalls(34, PropertySetup.getStudentUnion(), buildSUHouse); } else if (player2Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player2FlatsAndHalls(34, PropertySetup.getStudentUnion(), buildSUHouse); } else if (player3Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player3FlatsAndHalls(34, PropertySetup.getStudentUnion(), buildSUHouse); } else if (player4Contain3Method(PropertySetup.getWhitlaHall(), PropertySetup.getDkb(), PropertySetup.getStudentUnion())) { player4FlatsAndHalls(34, PropertySetup.getStudentUnion(), buildSUHouse); } else { JOptionPane.showMessageDialog(null, "You do not own all of the green properties"); } su.setText("<html>Students Union" + "<br>Flats: " + PropertySetup.getStudentUnion().getFlats() + "<br>Halls: " + PropertySetup.getStudentUnion().getHalls() + "</html>"); } }); greenPanel.add(whitla); greenPanel.add(dkb); greenPanel.add(su); greenPanel.add(buildWhitlaHouse); greenPanel.add(buildDkbHouse); greenPanel.add(buildSUHouse); greenPanel.add(whitlaOverdraft); greenPanel.add(dkbOverdraft); greenPanel.add(suOverdraft); tabbedPane.addTab("Browns", brownPanel); tabbedPane.addTab("Blue", bluePanel); tabbedPane.addTab("Pink", pinkPanel); tabbedPane.addTab("Orange", orangePanel); tabbedPane.addTab("Red", redPanel); tabbedPane.addTab("Yellow", yellowPanel); tabbedPane.addTab("Green", greenPanel); tabbedPane.addTab("Purple", purplePanel); /** * * The purples */ final JButton buildBotHouse = new JButton("Build Flat £"+PropertySetup.getBotanicGardens().getCostBuyFlat()); disableButtons(PropertySetup.getBotanicGardens(), buildBotHouse); final JLabel bot = new JLabel("<html>Botanic Gardens" + "<br>Flats: " + PropertySetup.getBotanicGardens().getFlats() + "<br>Halls: " + PropertySetup.getBotanicGardens().getHalls() + "</html>"); JButton botOverdraft = new JButton("Overdraft"); bot.setForeground(Color.white); bot.setHorizontalAlignment(SwingConstants.CENTER); bot.setBorder(BorderFactory.createLineBorder(Color.black)); buildBotHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain2Method(PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player1FlatsAndHalls(37, PropertySetup.getBotanicGardens(), buildBotHouse); } else if (player2Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player2FlatsAndHalls(37, PropertySetup.getBotanicGardens(), buildBotHouse); } else if (player3Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player3FlatsAndHalls(37, PropertySetup.getBotanicGardens(), buildBotHouse); } else if (player4Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player4FlatsAndHalls(37, PropertySetup.getBotanicGardens(), buildBotHouse); } else { JOptionPane.showMessageDialog(null, "You do not own both of the purple properties"); } bot.setText("<html>Botanic Gardens" + "<br>Flats: " + PropertySetup.getBotanicGardens().getFlats() + "<br>Halls: " + PropertySetup.getBotanicGardens().getHalls() + "</html>"); } }); final JButton buildLanyonHouse = new JButton("Build Flat £"+PropertySetup.getLanyonBuilding().getCostBuyFlat()); disableButtons(PropertySetup.getLanyonBuilding(), buildLanyonHouse); final JLabel lanyon = new JLabel("<html>Lanyon Building" + "<br>Flats: " + PropertySetup.getLanyonBuilding().getFlats() + "<br>Halls: " + PropertySetup.getLanyonBuilding().getHalls() + "</html>"); JButton lanyonOverdraft = new JButton("Overdraft"); lanyon.setForeground(Color.white); lanyon.setHorizontalAlignment(SwingConstants.CENTER); lanyon.setBorder(BorderFactory.createLineBorder(Color.black)); buildLanyonHouse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent build) { if (player1Contain2Method(PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player1FlatsAndHalls(39, PropertySetup.getLanyonBuilding(), buildLanyonHouse); } else if (player2Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player2FlatsAndHalls(39, PropertySetup.getLanyonBuilding(), buildLanyonHouse); } else if (player3Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player3FlatsAndHalls(39, PropertySetup.getLanyonBuilding(), buildLanyonHouse); } else if (player4Contain2Method( PropertySetup.getBotanicGardens(), PropertySetup.getLanyonBuilding())) { player4FlatsAndHalls(39, PropertySetup.getLanyonBuilding(), buildLanyonHouse); } else { JOptionPane.showMessageDialog(null, "You do not own both of the purple properties"); } lanyon.setText("<html>Lanyon Building" + "<br>Flats: " + PropertySetup.getLanyonBuilding().getFlats() + "<br>Halls: " + PropertySetup.getLanyonBuilding().getHalls() + "</html>"); } }); purplePanel.add(bot); purplePanel.add(lanyon); purplePanel.add(buildBotHouse); purplePanel.add(buildLanyonHouse); purplePanel.add(botOverdraft); purplePanel.add(lanyonOverdraft); add(topPanel); middlePanel.add(tabbedPane); add(middlePanel); aginOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getAgincourtAve()); } }); tatesOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getTatesAve()); } }); bcbOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getBcbRubble()); } }); dunOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getDunluceAve()); } }); maloneAOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getMaloneAve()); } }); socaOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getSoca()); } }); theologyOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getTheologyCentre()); } }); maloneROverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getMaloneRoad()); } }); fitzOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getFitzwilliamStreet()); } }); geoOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getGeographyBuilding()); } }); ecsOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getEcsBuilding()); } }); boojumOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getBoojum()); } }); pecOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getPec()); } }); ashbyOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getAshbyBuilding()); } }); mcClayOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getMcClayLibrary()); } }); peterOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getPeterFroggatCentre()); } }); mbcOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getMbc()); } }); whitlaOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getWhitlaHall()); } }); dkbOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getDkb()); } }); suOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getStudentUnion()); } }); botOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getBotanicGardens()); } }); lanyonOverdraft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent over){ sellForOverdraft(PropertySetup.getLanyonBuilding()); } }); } /** * This method is used to check if player 1 contains two properties in a row * @param properties - first property * @param properties2 - second property * @return - true or false depending on the above comments */ public boolean player1Contain2Method(Properties properties, Properties properties2) { if (LeftPanel.getPlayer1().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer1().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer1().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 1 contains three properties in a row * @param properties - first property * @param properties2 - second property * @param properties 3 - third property * @return - true or false depending on the above comments */ public boolean player1Contain3Method(Properties properties, Properties properties2, Properties properties3) { if (LeftPanel.getPlayer1().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer1().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer1().getPropertiesArray() .contains(properties3) && LeftPanel.getPlayer1().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 2 contains two properties in a row * @param properties - first property * @param properties2 - second property * @return - true or false depending on the above comments */ public boolean player2Contain2Method(Properties properties, Properties properties2) { if (LeftPanel.getPlayer2().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer2().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer2().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 2 contains three properties in a row * @param properties - first property * @param properties2 - second property * @param properties 3 - third property * @return - true or false depending on the above comments */ public boolean player2Contain3Method(Properties properties, Properties properties2, Properties properties3) { if (LeftPanel.getPlayer2().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer2().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer2().getPropertiesArray() .contains(properties3) && LeftPanel.getPlayer2().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 3 contains two properties in a row * @param properties - first property * @param properties2 - second property * @return - true or false depending on the above comments */ public boolean player3Contain2Method(Properties properties, Properties properties2) { if (LeftPanel.getPlayer3().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer3().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer3().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 3 contains three properties in a row * @param properties - first property * @param properties2 - second property * @param properties3 - third property * @return - true or false depending on the above comments */ public boolean player3Contain3Method(Properties properties, Properties properties2, Properties properties3) { if (LeftPanel.getPlayer3().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer3().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer3().getPropertiesArray() .contains(properties3) && LeftPanel.getPlayer3().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 4 contains two properties in a row * @param properties - first property * @param properties2 - second property * @return - true or false depending on the above comments */ public boolean player4Contain2Method(Properties properties, Properties properties2) { if (LeftPanel.getPlayer4().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer4().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer4().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to check if player 4 contains three properties in a row * @param properties - first property * @param properties2 - second property * @param properties 3 - third property * @return - true or false depending on the above comments */ public boolean player4Contain3Method(Properties properties, Properties properties2, Properties properties3) { if (LeftPanel.getPlayer4().getPropertiesArray().contains((properties)) && LeftPanel.getPlayer4().getPropertiesArray() .contains((properties2)) && LeftPanel.getPlayer4().getPropertiesArray() .contains(properties3) && LeftPanel.getPlayer4().getPlayerNum() == RightPanel .getCurrentPlayer()) { return true; } else { return false; } } /** * This method is used to build flats and halls for player 1 * @param i - property index * @param properties - the property to buy flats and halls on * @param button - the button to change the text of */ public void player1FlatsAndHalls(int i, Properties properties, JButton button) { if (PropertySetup.getProps().get(i).getFlats() < 4 && PropertySetup.getProps().get(i).getHalls() == 0) { PropertySetup.getProps().get(i) .setFlats(PropertySetup.getProps().get(i).getFlats() + 1); LeftPanel.getPlayer1().setPlayerMoney( LeftPanel.getPlayer1().getPlayerMoney() - properties.getCostBuyFlat()); } else if (PropertySetup.getProps().get(i).getFlats() == 4) { button.setText("Build Hall £" +PropertySetup.getProps().get(i).getCostBuyHalls()); PropertySetup.getProps().get(i).setFlats(0); PropertySetup.getProps().get(i).setHalls(1); LeftPanel.getPlayer1().setPlayerMoney( LeftPanel.getPlayer1().getPlayerMoney() - properties.getCostBuyHalls()); } else { button.setText("Maxed Out"); } updateLabels(); } /** * This method is used to build flats and halls for player 2 * @param i - property index * @param properties - the property to buy flats and halls on * @param button - the button to change the text of */ public void player2FlatsAndHalls(int i, Properties properties, JButton button) { if (PropertySetup.getProps().get(i).getFlats() < 4 && PropertySetup.getProps().get(i).getHalls() == 0) { PropertySetup.getProps().get(i) .setFlats(PropertySetup.getProps().get(i).getFlats() + 1); LeftPanel.getPlayer2().setPlayerMoney( LeftPanel.getPlayer2().getPlayerMoney() - properties.getCostBuyFlat()); } else if (PropertySetup.getProps().get(i).getFlats() == 4) { button.setText("Build Hall £"+PropertySetup.getProps().get(i).getCostBuyHalls()); PropertySetup.getProps().get(i).setFlats(0); PropertySetup.getProps().get(i).setHalls(1); LeftPanel.getPlayer2().setPlayerMoney( LeftPanel.getPlayer2().getPlayerMoney() - properties.getCostBuyHalls()); } else { button.setText("Maxed Out"); } updateLabels(); } /** * This method is used to build flats and halls for player 3 * @param i - property index * @param properties - the property to buy flats and halls on * @param button - the button to change the text of */ public void player3FlatsAndHalls(int i, Properties properties, JButton button) { if (PropertySetup.getProps().get(i).getFlats() < 4 && PropertySetup.getProps().get(i).getHalls() == 0) { PropertySetup.getProps().get(i) .setFlats(PropertySetup.getProps().get(i).getFlats() + 1); LeftPanel.getPlayer3().setPlayerMoney( LeftPanel.getPlayer3().getPlayerMoney() - properties.getCostBuyFlat()); } else if (PropertySetup.getProps().get(i).getFlats() == 4) { button.setText("Build Hall £"+PropertySetup.getProps().get(i).getCostBuyHalls()); PropertySetup.getProps().get(i).setFlats(0); PropertySetup.getProps().get(i).setHalls(1); LeftPanel.getPlayer3().setPlayerMoney( LeftPanel.getPlayer3().getPlayerMoney() - properties.getCostBuyHalls()); } else { button.setText("Maxed Out"); } updateLabels(); } /** * This method is used to build flats and halls for player 4 * @param i - property index * @param properties - the property to buy flats and halls on * @param button - the button to change the text of */ public void player4FlatsAndHalls(int i, Properties properties, JButton button) { if (PropertySetup.getProps().get(i).getFlats() < 4 && PropertySetup.getProps().get(i).getHalls() == 0) { PropertySetup.getProps().get(i) .setFlats(PropertySetup.getProps().get(i).getFlats() + 1); LeftPanel.getPlayer4().setPlayerMoney( LeftPanel.getPlayer4().getPlayerMoney() - properties.getCostBuyFlat()); } else if (PropertySetup.getProps().get(i).getFlats() == 4) { button.setText("Build Hall £"+PropertySetup.getProps().get(i).getCostBuyHalls()); PropertySetup.getProps().get(i).setFlats(0); PropertySetup.getProps().get(i).setHalls(1); LeftPanel.getPlayer4().setPlayerMoney( LeftPanel.getPlayer4().getPlayerMoney() - properties.getCostBuyHalls()); } else { button.setText("Maxed Out"); } updateLabels(); } /** * This method disables the button is the flats and halls for a property is at the limit * @param property - the property in question * @param button - the button to disable */ public void disableButtons(Properties property, JButton button) { if (property.getFlats() == 4) { button.setText("Build Hall"); } if (property.getHalls() == 1) { button.setEnabled(false); button.setText("Maxed Out"); } } /** * This method is used to sell properties * @param properties - the property to sell */ public void sellForOverdraft(Properties properties){ if(LeftPanel.getPlayer1().getPropertiesArray().contains(properties)){ LeftPanel.getPlayer1().getPropertiesArray().remove(properties); properties.setFlats(0); properties.setHalls(0); properties.setBuyable(true); LeftPanel.getPlayer1().setPlayerMoney(LeftPanel.getPlayer1().getPlayerMoney() + properties.getMortgageValue()); JOptionPane.showMessageDialog(null, "You have sold this property"); } else if(LeftPanel.getPlayer2().getPropertiesArray().contains(properties)){ LeftPanel.getPlayer2().getPropertiesArray().remove(properties); properties.setFlats(0); properties.setHalls(0); properties.setBuyable(true); LeftPanel.getPlayer2().setPlayerMoney(LeftPanel.getPlayer2().getPlayerMoney() + properties.getMortgageValue()); JOptionPane.showMessageDialog(null, "You have sold this property"); } else if(LeftPanel.getPlayer3().getPropertiesArray().contains(properties)){ LeftPanel.getPlayer3().getPropertiesArray().remove(properties); properties.setFlats(0); properties.setHalls(0); properties.setBuyable(true); LeftPanel.getPlayer3().setPlayerMoney(LeftPanel.getPlayer3().getPlayerMoney() + properties.getMortgageValue()); JOptionPane.showMessageDialog(null, "You have sold this property"); } else if(LeftPanel.getPlayer4().getPropertiesArray().contains(properties)){ LeftPanel.getPlayer4().getPropertiesArray().remove(properties); properties.setFlats(0); properties.setHalls(0); properties.setBuyable(true); LeftPanel.getPlayer4().setPlayerMoney(LeftPanel.getPlayer4().getPlayerMoney() + properties.getMortgageValue()); JOptionPane.showMessageDialog(null, "You have sold this property"); } else{ JOptionPane.showMessageDialog(null, "You do not own this property"); } updateLabels(); } public static void updateLabels(){ if(LeftPanel.getTotalPlayers() == 2){ LeftPanel.getPlayer1Label().setText( LeftPanel.getPlayer1().getPlayerName() + " £" + LeftPanel.getPlayer1().getPlayerMoney()); LeftPanel.getPlayer2Label().setText( LeftPanel.getPlayer2().getPlayerName() + " £" + LeftPanel.getPlayer2().getPlayerMoney()); } else if(LeftPanel.getTotalPlayers() == 3){ LeftPanel.getPlayer1Label().setText( LeftPanel.getPlayer1().getPlayerName() + " £" + LeftPanel.getPlayer1().getPlayerMoney()); LeftPanel.getPlayer2Label().setText( LeftPanel.getPlayer2().getPlayerName() + " £" + LeftPanel.getPlayer2().getPlayerMoney()); LeftPanel.getPlayer3Label().setText( LeftPanel.getPlayer3().getPlayerName() + " £" + LeftPanel.getPlayer3().getPlayerMoney()); } else if(LeftPanel.getTotalPlayers() == 4){ LeftPanel.getPlayer1Label().setText( LeftPanel.getPlayer1().getPlayerName() + " £" + LeftPanel.getPlayer1().getPlayerMoney()); LeftPanel.getPlayer2Label().setText( LeftPanel.getPlayer2().getPlayerName() + " £" + LeftPanel.getPlayer2().getPlayerMoney()); LeftPanel.getPlayer3Label().setText( LeftPanel.getPlayer3().getPlayerName() + " £" + LeftPanel.getPlayer3().getPlayerMoney()); LeftPanel.getPlayer4Label().setText( LeftPanel.getPlayer4().getPlayerName() + " £" + LeftPanel.getPlayer4().getPlayerMoney()); } } }
64,985
0.710582
0.70056
1,756
35.992596
24.027401
117
false
false
0
0
0
0
0
0
3.992027
false
false
7
a47e4c2bca7ffa0fda8fd0b786686063575d3d9c
2,448,131,380,093
a255dc3a63716d3424e41a7722dbcc5baecb31ed
/Decryptor.java
268b3faff6d1d4122e3ea4dcd1d92f0324c977a6
[]
no_license
angelalin2004/decryptor
https://github.com/angelalin2004/decryptor
57369811a848d2cc79ce3c49c4b496869eb0e398
bb99717dd817612a2e06e93ddf4ec819b2fa8621
refs/heads/master
2020-04-05T23:20:43.665000
2015-01-09T21:41:12
2015-01-09T21:41:12
28,708,379
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; import java.lang.*; import java.io.*; public class Decryptor { String message = ""; String [] words; boolean one_lettered_word; public static void main (String[] args) { Decryptor machine = new Decryptor(); // machine.promptUser(); if (machine.getMessageFromFile() == false) return; machine.makeWordsArray(); machine.rankLetterCommonality(); } public void promptUser ( ) { Scanner in = new Scanner (System.in); do { System.out.print( "/nEnter the message to be decrypted: " ); message = in.nextLine(); } while ( message == null ); System.out.println(); } public boolean getMessageFromFile ( ) { try { File cryptogram = new File ("cryptogram.txt"); Scanner in = new Scanner(new FileReader("cryptogram.txt")); while (in.hasNext()) { message += in.nextLine(); } System.out.println ( "/nThe message to be decrypted is: " ); System.out.println ( message ); }catch ( IOException e ) { System.err.println(e); return false; } return true; } public void makeWordsArray ( ) { // count spaces to determine number of words int spaces = 1; for ( int i = 0; i < message.length(); i++ ) { if ( message.charAt(i) == ' ' ) spaces++; } words = new String [spaces]; int arr_ind = 0; int start = 0; for ( int i = 0; i <= message.length(); i++ ) { if ( i == message.length() || message.charAt(i) == ' ' || message.charAt(i) == ',' || message.charAt(i) == '.' ) { if (i != start) { words[arr_ind] = message.substring(start,i); /* is there a one-lettered word? */ if (words[arr_ind].length() == 1) one_lettered_word = true; arr_ind++; } start = i+1; } } } public void rankLetterCommonality ( ) { Letter [] letters = new Letter [message.length()]; int arr_ind = 0; for ( int i = 0; i < message.length(); i++ ) { char ch = message.charAt(i); // if the array is empty, just insert if ( i == 0 ) { letters[arr_ind] = new Letter(ch); arr_ind++; } // if not, search through previous entries for a previous occurence else { for ( int j = 0; j < arr_ind; j++ ) { // if there is a match, then increment occurences if ( letters[j].getLetter() == ch ) { letters[j].increment(); } // otherwise insert into the array else { letters[arr_ind] = new Letter(ch); arr_ind++; } } } } } }
UTF-8
Java
3,102
java
Decryptor.java
Java
[]
null
[]
import java.util.*; import java.lang.*; import java.io.*; public class Decryptor { String message = ""; String [] words; boolean one_lettered_word; public static void main (String[] args) { Decryptor machine = new Decryptor(); // machine.promptUser(); if (machine.getMessageFromFile() == false) return; machine.makeWordsArray(); machine.rankLetterCommonality(); } public void promptUser ( ) { Scanner in = new Scanner (System.in); do { System.out.print( "/nEnter the message to be decrypted: " ); message = in.nextLine(); } while ( message == null ); System.out.println(); } public boolean getMessageFromFile ( ) { try { File cryptogram = new File ("cryptogram.txt"); Scanner in = new Scanner(new FileReader("cryptogram.txt")); while (in.hasNext()) { message += in.nextLine(); } System.out.println ( "/nThe message to be decrypted is: " ); System.out.println ( message ); }catch ( IOException e ) { System.err.println(e); return false; } return true; } public void makeWordsArray ( ) { // count spaces to determine number of words int spaces = 1; for ( int i = 0; i < message.length(); i++ ) { if ( message.charAt(i) == ' ' ) spaces++; } words = new String [spaces]; int arr_ind = 0; int start = 0; for ( int i = 0; i <= message.length(); i++ ) { if ( i == message.length() || message.charAt(i) == ' ' || message.charAt(i) == ',' || message.charAt(i) == '.' ) { if (i != start) { words[arr_ind] = message.substring(start,i); /* is there a one-lettered word? */ if (words[arr_ind].length() == 1) one_lettered_word = true; arr_ind++; } start = i+1; } } } public void rankLetterCommonality ( ) { Letter [] letters = new Letter [message.length()]; int arr_ind = 0; for ( int i = 0; i < message.length(); i++ ) { char ch = message.charAt(i); // if the array is empty, just insert if ( i == 0 ) { letters[arr_ind] = new Letter(ch); arr_ind++; } // if not, search through previous entries for a previous occurence else { for ( int j = 0; j < arr_ind; j++ ) { // if there is a match, then increment occurences if ( letters[j].getLetter() == ch ) { letters[j].increment(); } // otherwise insert into the array else { letters[arr_ind] = new Letter(ch); arr_ind++; } } } } } }
3,102
0.455835
0.452289
96
31.322916
20.045519
79
false
false
0
0
0
0
0
0
0.885417
false
false
7
73bf0bce78d200aecfdd598923e66557dbd9f592
6,949,257,105,264
9d55781f89acad8f8475001fd298ee51c999a21f
/src/org/usfirst/frc/team6359/robot/RobotMap.java
f567e9d4c3538edb22daad1578c4ab3ad814fd2b
[]
no_license
Team6359/FRC-2018
https://github.com/Team6359/FRC-2018
a749d8bda4be55ca783ef3f883f815f40b14a5ca
6f262bf3b2273de07182879c3477dd56d8749703
refs/heads/master
2021-09-23T12:11:48.427000
2018-09-22T17:21:44
2018-09-22T17:21:44
118,841,351
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.usfirst.frc.team6359.robot; public class RobotMap { /* * Left Stick X: 0 Left Stick Y: 1 Left Trigger: 2 Right Trigger: 3 Right Stick * X: 4 Right Stick Y: 5 * * A: 1 B: 2 X: 3 Y: 4 Left Bumper: 5 Left Bumper: 6 Back: 7 Start: 8 Left Stick * Click: 9 Right Stick Click: 10 */ // // VictorSPX // public static int BR = 1; // public static int CR = 2; // public static int BL = 3; // public static int CL = 4; // // // Victor // public static final int H1 = 7; // public static final int FL = 8; // public static final int FR = 6; // public static final int winch = 9; // // // Spark // public static final int intakeLeft = 3; //8 // public static final int intakeRight = 2; // // public static final int liftWheelLeft = 4; // public static final int liftWheelRight = 5; // // public static final int liftMotor1 = 0; // public static final int liftMotor2 = 1; // VictorSPX public static int BR = 1; public static int CR = 2; public static int BL = 3; public static int CL = 4; // Victor public static final int H1 = 2; public static final int FL = 1; public static final int FR = 0; public static final int winch = 3; public static final int intakeLeft = 5; public static final int intakeRight = 4; public static final int liftWheelLeft = 8; public static final int liftWheelRight = 9; public static final int liftMotor1 = 6; public static final int liftMotor2 = 7; // // // public static DigitalSource rEncoder1; // // public static DigitalSource rEncoder2; // // public static DigitalSource lEncoder1; // // public static DigitalSource lEncoder2; // // public static DigitalSource liftEncoder1; // // public static DigitalSource liftEncoder2; // public static final int rEncoder1 = 8; public static final int rEncoder2 = 7; public static final int lEncoder1 = 6; public static final int lEncoder2 = 5; public static final int liftEncoder1 = 1; public static final int liftEncoder2 = 0; public static final int liftLimitHigh = 2; public static final int liftLimitLow = 3; // public static final int bac1 = 2; public static final int bac2 = 3; public static double cpiLift = (3811.0 / 2) / 3.141; // Inches * cpiLift public static double liftSetPointFloor = 0; public static double liftSetPointDrive = 4 * cpiLift; public static double liftSetPointSwitch = 34 * cpiLift; //public static double liftSetPointScaleLow = 62 * cpiLift; public static double liftSetPointScaleNeutral = 72 * cpiLift; public static double liftSetPointScaleHigh = 49000; }
UTF-8
Java
2,597
java
RobotMap.java
Java
[ { "context": "\n\t * Click: 9 Right Stick Click: 10\r\n\t */\r\n\r\n//\t// VictorSPX\r\n//\tpublic static int BR = 1;\r\n//\tpublic ", "end": 324, "score": 0.42261162400245667, "start": 323, "tag": "NAME", "value": "V" }, { "context": " * Click: 9 Right Stick Click: 10\r\n\t */\r\n\r...
null
[]
package org.usfirst.frc.team6359.robot; public class RobotMap { /* * Left Stick X: 0 Left Stick Y: 1 Left Trigger: 2 Right Trigger: 3 Right Stick * X: 4 Right Stick Y: 5 * * A: 1 B: 2 X: 3 Y: 4 Left Bumper: 5 Left Bumper: 6 Back: 7 Start: 8 Left Stick * Click: 9 Right Stick Click: 10 */ // // VictorSPX // public static int BR = 1; // public static int CR = 2; // public static int BL = 3; // public static int CL = 4; // // // Victor // public static final int H1 = 7; // public static final int FL = 8; // public static final int FR = 6; // public static final int winch = 9; // // // Spark // public static final int intakeLeft = 3; //8 // public static final int intakeRight = 2; // // public static final int liftWheelLeft = 4; // public static final int liftWheelRight = 5; // // public static final int liftMotor1 = 0; // public static final int liftMotor2 = 1; // VictorSPX public static int BR = 1; public static int CR = 2; public static int BL = 3; public static int CL = 4; // Victor public static final int H1 = 2; public static final int FL = 1; public static final int FR = 0; public static final int winch = 3; public static final int intakeLeft = 5; public static final int intakeRight = 4; public static final int liftWheelLeft = 8; public static final int liftWheelRight = 9; public static final int liftMotor1 = 6; public static final int liftMotor2 = 7; // // // public static DigitalSource rEncoder1; // // public static DigitalSource rEncoder2; // // public static DigitalSource lEncoder1; // // public static DigitalSource lEncoder2; // // public static DigitalSource liftEncoder1; // // public static DigitalSource liftEncoder2; // public static final int rEncoder1 = 8; public static final int rEncoder2 = 7; public static final int lEncoder1 = 6; public static final int lEncoder2 = 5; public static final int liftEncoder1 = 1; public static final int liftEncoder2 = 0; public static final int liftLimitHigh = 2; public static final int liftLimitLow = 3; // public static final int bac1 = 2; public static final int bac2 = 3; public static double cpiLift = (3811.0 / 2) / 3.141; // Inches * cpiLift public static double liftSetPointFloor = 0; public static double liftSetPointDrive = 4 * cpiLift; public static double liftSetPointSwitch = 34 * cpiLift; //public static double liftSetPointScaleLow = 62 * cpiLift; public static double liftSetPointScaleNeutral = 72 * cpiLift; public static double liftSetPointScaleHigh = 49000; }
2,597
0.685791
0.64613
82
29.670732
19.556082
81
false
false
0
0
0
0
0
0
1.439024
false
false
7
26db40ee1bea2d4fb14c64942c72da4b763e4bf9
23,673,859,757,578
fd4da8afaeae6584b9d9e1accd66c43342bdb427
/src/main/java/com/chess/сore/сhessboard/ChessBoardLogic.java
57e81c1fc0f6ff06acf010342f3f20abb6afaa3c
[]
no_license
j-04/chess
https://github.com/j-04/chess
459c696d829ce81bab24b437d9a034978d19620b
2209e3c93ed56526e5af66e0b707b5678147f9c6
refs/heads/master
2023-08-07T22:32:16.844000
2020-02-04T11:18:00
2020-02-04T11:18:00
159,544,326
2
0
null
false
2023-07-20T07:35:09
2018-11-28T18:07:37
2023-05-18T11:53:17
2023-07-20T07:35:09
83
2
0
1
Java
false
false
package com.chess.сore.сhessboard; import com.chess.сore.figures.abstrac.Pawn; import com.chess.сore.figures.black.BlackPawn; import com.chess.сore.figures.abstrac.Figure; import com.chess.сore.figures.other.ChessBoardCell; import com.chess.сore.figures.white.WhitePawn; import javax.swing.*; import java.awt.*; import java.util.LinkedList; public class ChessBoardLogic { public static boolean flag = true; //true = Black, false = White public static final Figure[][] figuresArray = new Figure[8][8]; public static final LinkedList<Figure> figuresList = new LinkedList<>(); public static final ChessBoardCell[][] panelsArray = new ChessBoardCell[8][8]; private JLayeredPane layeredPane; private JFrame root; private static ChessBoardLogic instance; private ChessBoardLogic(JFrame root, JLayeredPane layeredPane) { this.layeredPane = layeredPane; this.root = root; } public void removeFigure(Figure figureToRemove) { ChessBoardLogic.figuresList.remove(figureToRemove); ChessBoardLogic.figuresArray[figureToRemove.getPositionInArrayY()][figureToRemove.getPositionInArrayX()] = null; layeredPane.remove(figureToRemove); } public void predictStepsOfAllFigures() { for (Figure figure: ChessBoardLogic.figuresList) { figure.predictSteps(); } } public void checkPawnsToChange() { Pawn pawn = null; for (Figure figure: figuresList) { if (figure instanceof WhitePawn && figure.getPositionInArrayY() == 0) { pawn = (Pawn) figure; break; } else { if (figure instanceof BlackPawn && figure.getPositionInArrayY() == 7) { pawn = (Pawn) figure; break; } } } if (pawn != null) { if (pawn.getColor().equals(Color.BLACK)) changeWhitePawn(pawn); else if (pawn.getColor().equals(Color.WHITE)) { changeBlackPawn(pawn); } } } private void changeWhitePawn(Pawn pawn) { ChessPawnChanger chessPawnChanger = new ChessPawnChanger(root); chessPawnChanger.chooseWhiteFigure(pawn); } private void changeBlackPawn(Pawn pawn) { ChessPawnChanger chessPawnChanger = new ChessPawnChanger(root); chessPawnChanger.chooseBlackFigure(pawn); } public void setLayeredPane(JLayeredPane layeredPane) { this.layeredPane = layeredPane; } public static void changeTurn() { flag = !flag; } public static void setInstance(JFrame root, JLayeredPane layeredPane) { if (instance == null) instance = new ChessBoardLogic(root, layeredPane); } public static ChessBoardLogic getInstance() { if (instance == null) throw new NullPointerException(); return instance; } }
UTF-8
Java
2,980
java
ChessBoardLogic.java
Java
[]
null
[]
package com.chess.сore.сhessboard; import com.chess.сore.figures.abstrac.Pawn; import com.chess.сore.figures.black.BlackPawn; import com.chess.сore.figures.abstrac.Figure; import com.chess.сore.figures.other.ChessBoardCell; import com.chess.сore.figures.white.WhitePawn; import javax.swing.*; import java.awt.*; import java.util.LinkedList; public class ChessBoardLogic { public static boolean flag = true; //true = Black, false = White public static final Figure[][] figuresArray = new Figure[8][8]; public static final LinkedList<Figure> figuresList = new LinkedList<>(); public static final ChessBoardCell[][] panelsArray = new ChessBoardCell[8][8]; private JLayeredPane layeredPane; private JFrame root; private static ChessBoardLogic instance; private ChessBoardLogic(JFrame root, JLayeredPane layeredPane) { this.layeredPane = layeredPane; this.root = root; } public void removeFigure(Figure figureToRemove) { ChessBoardLogic.figuresList.remove(figureToRemove); ChessBoardLogic.figuresArray[figureToRemove.getPositionInArrayY()][figureToRemove.getPositionInArrayX()] = null; layeredPane.remove(figureToRemove); } public void predictStepsOfAllFigures() { for (Figure figure: ChessBoardLogic.figuresList) { figure.predictSteps(); } } public void checkPawnsToChange() { Pawn pawn = null; for (Figure figure: figuresList) { if (figure instanceof WhitePawn && figure.getPositionInArrayY() == 0) { pawn = (Pawn) figure; break; } else { if (figure instanceof BlackPawn && figure.getPositionInArrayY() == 7) { pawn = (Pawn) figure; break; } } } if (pawn != null) { if (pawn.getColor().equals(Color.BLACK)) changeWhitePawn(pawn); else if (pawn.getColor().equals(Color.WHITE)) { changeBlackPawn(pawn); } } } private void changeWhitePawn(Pawn pawn) { ChessPawnChanger chessPawnChanger = new ChessPawnChanger(root); chessPawnChanger.chooseWhiteFigure(pawn); } private void changeBlackPawn(Pawn pawn) { ChessPawnChanger chessPawnChanger = new ChessPawnChanger(root); chessPawnChanger.chooseBlackFigure(pawn); } public void setLayeredPane(JLayeredPane layeredPane) { this.layeredPane = layeredPane; } public static void changeTurn() { flag = !flag; } public static void setInstance(JFrame root, JLayeredPane layeredPane) { if (instance == null) instance = new ChessBoardLogic(root, layeredPane); } public static ChessBoardLogic getInstance() { if (instance == null) throw new NullPointerException(); return instance; } }
2,980
0.636731
0.634712
93
30.967741
25.938078
120
false
false
0
0
0
0
0
0
0.451613
false
false
7
f385410b9d0e772c6f6663a724b06d3abfef672b
23,673,859,761,356
6a790822ca9fc4bcb349fed228e8d728739352a7
/src/org/glite/data/common/helpers/ServiceSetup.java
c4af1d5c8deaa6f959b3a75239a9ac88900c39ca
[ "Apache-2.0" ]
permissive
giovannibianco/Hydra-Service
https://github.com/giovannibianco/Hydra-Service
3daf9256d1096dc6bb07ed918e2355fed7af3fe7
c3b35d9fd46af2a2158a7443f0b50977dcbf5f2a
refs/heads/master
2020-05-17T03:50:13.989000
2014-10-07T13:11:43
2014-10-07T13:11:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) Members of the EGEE Collaboration. 2004. * See http://eu-egee.org/partners/ for details on the copyright holders. * For license conditions see the license file or http://www.apache.org/licenses/LICENSE-2.0 */ package org.glite.data.common.helpers; import org.apache.log4j.Logger; /** * Contains {@link #start} and {@link #stop} methods for starting and stopping * auxiliary services of the catalog service environment. This class can be used * both by the web application and the testing classes to encapsulate the * initialization and shutdown logic. */ public class ServiceSetup { private static final Logger log = Logger.getLogger(ServiceSetup.class); /** * Initializes the Service Java environment. */ public static void start() { try { // Initialize the base interface implementation Class.forName("org.glite.data.common.helpers.ServiceImpl"); } catch (ClassNotFoundException e) { log.fatal("*** FATAL DEPLOYMENT PROBLEM *** an essential class was not found:" + e.toString()); } log.info("The org.glite.data service is started"); } /** * Stops background threads, cleans up Java environment. */ public static void stop() { log.info("The org.glite.data service is stopped"); } }
UTF-8
Java
1,342
java
ServiceSetup.java
Java
[]
null
[]
/* * Copyright (c) Members of the EGEE Collaboration. 2004. * See http://eu-egee.org/partners/ for details on the copyright holders. * For license conditions see the license file or http://www.apache.org/licenses/LICENSE-2.0 */ package org.glite.data.common.helpers; import org.apache.log4j.Logger; /** * Contains {@link #start} and {@link #stop} methods for starting and stopping * auxiliary services of the catalog service environment. This class can be used * both by the web application and the testing classes to encapsulate the * initialization and shutdown logic. */ public class ServiceSetup { private static final Logger log = Logger.getLogger(ServiceSetup.class); /** * Initializes the Service Java environment. */ public static void start() { try { // Initialize the base interface implementation Class.forName("org.glite.data.common.helpers.ServiceImpl"); } catch (ClassNotFoundException e) { log.fatal("*** FATAL DEPLOYMENT PROBLEM *** an essential class was not found:" + e.toString()); } log.info("The org.glite.data service is started"); } /** * Stops background threads, cleans up Java environment. */ public static void stop() { log.info("The org.glite.data service is stopped"); } }
1,342
0.673621
0.668405
41
31.731707
31.52701
107
false
false
0
0
0
0
0
0
0.195122
false
false
7
e7b54e750a2a811cf4cc0ecbd55125cb7e39a473
20,229,295,987,291
67dbae479dcb232d717536c781bbf4e164bcabe9
/app/src/main/java/com/github/helltar/anpaside/adapters/ProjectsListAdapter.java
216db3f03fac20371fbb254936c4f1154bb73d9b
[ "MIT" ]
permissive
Helltar/ANPASIDE
https://github.com/Helltar/ANPASIDE
3bd5f46ac4604153b96c91be67ce67dd31f14755
6d3ca55b7b3e0fc43ab1bb49be45fc9f4c172d0c
refs/heads/master
2023-02-16T10:06:30.097000
2023-02-05T23:54:43
2023-02-05T23:54:43
59,431,700
33
10
MIT
false
2022-06-13T11:17:17
2016-05-22T20:02:03
2022-06-06T01:35:41
2022-06-13T11:17:16
6,103
14
5
0
Java
false
false
package com.github.helltar.anpaside.adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.github.helltar.anpaside.Consts; import com.github.helltar.anpaside.ProjectsList; import com.github.helltar.anpaside.R; import com.github.helltar.anpaside.activities.MainActivity; import com.github.helltar.anpaside.activities.ProjectsListActivity; import java.util.List; public class ProjectsListAdapter extends RecyclerView.Adapter<ProjectsListAdapter.ViewHolder> { private final List<ProjectsList> projectsList; public ProjectsListAdapter(List<ProjectsList> contacts) { projectsList = contacts; } public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public TextView tvProjectName; public ViewHolder(View itemView) { super(itemView); this.tvProjectName = (TextView) itemView.findViewById(R.id.tvProjectName); itemView.setOnClickListener(this); } @Override public void onClick(View view) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { MainActivity.projectFilename = Consts.PROJECTS_DIR_PATH + tvProjectName.getText() + "/" + tvProjectName.getText() + Consts.EXT_PROJ; ProjectsListActivity.activity.finish(); } } } @NonNull @Override public ProjectsListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View contactView = inflater.inflate(R.layout.item_project, parent, false); return new ViewHolder(contactView); } @Override public void onBindViewHolder(ProjectsListAdapter.ViewHolder holder, int position) { ProjectsList project = projectsList.get(position); TextView textView = holder.tvProjectName; textView.setText(project.getName()); } @Override public int getItemCount() { return projectsList.size(); } }
UTF-8
Java
2,391
java
ProjectsListAdapter.java
Java
[]
null
[]
package com.github.helltar.anpaside.adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.github.helltar.anpaside.Consts; import com.github.helltar.anpaside.ProjectsList; import com.github.helltar.anpaside.R; import com.github.helltar.anpaside.activities.MainActivity; import com.github.helltar.anpaside.activities.ProjectsListActivity; import java.util.List; public class ProjectsListAdapter extends RecyclerView.Adapter<ProjectsListAdapter.ViewHolder> { private final List<ProjectsList> projectsList; public ProjectsListAdapter(List<ProjectsList> contacts) { projectsList = contacts; } public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public TextView tvProjectName; public ViewHolder(View itemView) { super(itemView); this.tvProjectName = (TextView) itemView.findViewById(R.id.tvProjectName); itemView.setOnClickListener(this); } @Override public void onClick(View view) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { MainActivity.projectFilename = Consts.PROJECTS_DIR_PATH + tvProjectName.getText() + "/" + tvProjectName.getText() + Consts.EXT_PROJ; ProjectsListActivity.activity.finish(); } } } @NonNull @Override public ProjectsListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View contactView = inflater.inflate(R.layout.item_project, parent, false); return new ViewHolder(contactView); } @Override public void onBindViewHolder(ProjectsListAdapter.ViewHolder holder, int position) { ProjectsList project = projectsList.get(position); TextView textView = holder.tvProjectName; textView.setText(project.getName()); } @Override public int getItemCount() { return projectsList.size(); } }
2,391
0.669594
0.669594
72
32.208332
27.629461
100
false
false
0
0
0
0
0
0
0.458333
false
false
7
1d79a881707614c69d64430c7fe60e018a793d5d
2,937,757,658,393
dc0d4c91571ed4b70391120cb5c9e839cec1e6b1
/src/main/java/com/band/dao/BandCoverDAOImpl.java
8f784873e077b97a4797c8d2c912f006dbbc3afd
[]
no_license
jjoylee/band
https://github.com/jjoylee/band
dedbf713aef3543904a80223f43eeadd73658bfc
1767213ae074c3951859e243940bd50a86072394
refs/heads/master
2021-01-21T10:22:33.961000
2017-03-26T15:37:19
2017-03-26T15:37:19
83,419,443
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.band.dao; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import com.band.domain.BandCover; @Repository public class BandCoverDAOImpl implements BandCoverDAO{ private static final String namespace ="com.band.mapper.BandCoverMapper"; @Inject private SqlSession sqlSession; @Override public void insert(BandCover vo) throws Exception { sqlSession.insert(namespace + ".insert", vo); } @Override public void update(BandCover vo) throws Exception { sqlSession.update(namespace + ".update" , vo); } @Override public void delete(BandCover vo) throws Exception { sqlSession.delete(namespace + ".delete", vo); } @Override public BandCover findBandCover(BandCover vo) throws Exception { // TODO Auto-generated method stub return sqlSession.selectOne(namespace + ".findBandCover", vo); } }
UTF-8
Java
903
java
BandCoverDAOImpl.java
Java
[]
null
[]
package com.band.dao; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import com.band.domain.BandCover; @Repository public class BandCoverDAOImpl implements BandCoverDAO{ private static final String namespace ="com.band.mapper.BandCoverMapper"; @Inject private SqlSession sqlSession; @Override public void insert(BandCover vo) throws Exception { sqlSession.insert(namespace + ".insert", vo); } @Override public void update(BandCover vo) throws Exception { sqlSession.update(namespace + ".update" , vo); } @Override public void delete(BandCover vo) throws Exception { sqlSession.delete(namespace + ".delete", vo); } @Override public BandCover findBandCover(BandCover vo) throws Exception { // TODO Auto-generated method stub return sqlSession.selectOne(namespace + ".findBandCover", vo); } }
903
0.76412
0.76412
37
23.405405
23.654564
74
false
false
0
0
0
0
0
0
1.135135
false
false
7
f43dd97cdfc8fa8798075812162415ee2d9fc92f
17,308,718,235,906
f29d82534d4d27c044fb3de061184dddf93d74dc
/ConfigFiles/ConfigMain.java
7c29269eb4acc33662897ef7541b1c15bbfcdc57
[]
no_license
soniakevlia/Threads
https://github.com/soniakevlia/Threads
449348a7bfedcc942294b895d9ebd15784f86efa
46bf32c052be9b3cdd0c2ad48fd8044b82d30a87
refs/heads/master
2020-04-22T18:00:01.079000
2019-03-30T09:10:32
2019-03-30T09:10:32
170,561,448
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ConfigFiles; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; public class ConfigMain { public ConfigMain(String name) { this.filename = name; } private String filename; private enum lexemes { SIZE("InputBlockSize"), NUMBER("ThreadsNumber"), PREFIX("ThreadConfigPrefix"), CONFIGALG("ConfigAlg"); String name; String value; lexemes(String string) { this.name = string; this.value = " "; } } ; public void readConfigFile() throws FileNotFoundException { FileInputStream confFile = new FileInputStream(filename); Scanner scanner = new Scanner(confFile); while (scanner.hasNextLine()) { String[] str = scanner.nextLine().split("="); lexemes[] values = lexemes.values(); for (lexemes value : values) { if (str[0].equals(value.name)) { value.value = str[1]; System.out.println(value.name + '=' + value.value); } } } } public int getInputBlockSize() { String str = lexemes.SIZE.value; return Integer.parseInt(str); } public int getThreadsNumber() { String str = lexemes.NUMBER.value; return Integer.parseInt(str); } public String getConfigFilename() { return lexemes.CONFIGALG.value; } public String getThreadConfigPrefix() { return lexemes.PREFIX.value; } }
UTF-8
Java
1,619
java
ConfigMain.java
Java
[]
null
[]
package ConfigFiles; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; public class ConfigMain { public ConfigMain(String name) { this.filename = name; } private String filename; private enum lexemes { SIZE("InputBlockSize"), NUMBER("ThreadsNumber"), PREFIX("ThreadConfigPrefix"), CONFIGALG("ConfigAlg"); String name; String value; lexemes(String string) { this.name = string; this.value = " "; } } ; public void readConfigFile() throws FileNotFoundException { FileInputStream confFile = new FileInputStream(filename); Scanner scanner = new Scanner(confFile); while (scanner.hasNextLine()) { String[] str = scanner.nextLine().split("="); lexemes[] values = lexemes.values(); for (lexemes value : values) { if (str[0].equals(value.name)) { value.value = str[1]; System.out.println(value.name + '=' + value.value); } } } } public int getInputBlockSize() { String str = lexemes.SIZE.value; return Integer.parseInt(str); } public int getThreadsNumber() { String str = lexemes.NUMBER.value; return Integer.parseInt(str); } public String getConfigFilename() { return lexemes.CONFIGALG.value; } public String getThreadConfigPrefix() { return lexemes.PREFIX.value; } }
1,619
0.56084
0.559605
62
24.112904
22.464384
110
false
false
0
0
0
0
0
0
0.435484
false
false
7
e6f514560ad83396b75ebe2c54897b837e49af01
29,781,303,282,032
5c6e93171d20f3c0619cf56a05c96af2a4542b27
/src/faithnh/study/wordenglishstudy/util/XMLParser.java
78107350c75213b0f01356c13f6e968f02d3bfe2
[]
no_license
faithnh/wordenglishstudy
https://github.com/faithnh/wordenglishstudy
667fde2ef2b3777e8f5bc0c20992b7e6127d5a77
f293ad0998b10aced021778e862d3a5d2a8465a6
refs/heads/master
2020-04-05T05:58:00.096000
2012-01-03T17:31:13
2012-01-03T17:31:13
3,049,758
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package faithnh.study.wordenglishstudy.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.StringReader; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.xmlpull.v1.XmlPullParser; import android.util.Log; import android.util.Xml; public class XMLParser { public static ArrayList<String> getTagNameInfo(String tagName, String html) throws Exception{ ArrayList<String> result; int eventType; final XmlPullParser xmlPullParser; result= new ArrayList<String>(); xmlPullParser = Xml.newPullParser(); xmlPullParser.setInput(new StringReader(html)); for(eventType = xmlPullParser.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xmlPullParser.next()){ if(eventType == XmlPullParser.START_TAG && xmlPullParser.getName().equals(tagName)){ result.add(xmlPullParser.nextText()); } } return result; } public static ArrayList<String> getTagNameInfo(String tagName, String className, String html) throws Exception{ ArrayList<String> result; int eventType; final XmlPullParser xmlPullParser; result= new ArrayList<String>(); xmlPullParser = Xml.newPullParser(); xmlPullParser.setInput(new StringReader(html)); for(eventType = xmlPullParser.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xmlPullParser.next()){ if(eventType == XmlPullParser.START_TAG && xmlPullParser.getName().equals(tagName) && xmlPullParser.getClass().equals(className)){ result.add(xmlPullParser.nextText()); } } return result; } public static String getXPath(String xpathString, byte[] xml) throws Exception{ DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbFactory.newDocumentBuilder(); Document document = builder.parse(new ByteArrayInputStream(xml)); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); String result = xpath.evaluate(xpathString, document); return result; } }
UTF-8
Java
2,362
java
XMLParser.java
Java
[]
null
[]
package faithnh.study.wordenglishstudy.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.StringReader; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.xmlpull.v1.XmlPullParser; import android.util.Log; import android.util.Xml; public class XMLParser { public static ArrayList<String> getTagNameInfo(String tagName, String html) throws Exception{ ArrayList<String> result; int eventType; final XmlPullParser xmlPullParser; result= new ArrayList<String>(); xmlPullParser = Xml.newPullParser(); xmlPullParser.setInput(new StringReader(html)); for(eventType = xmlPullParser.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xmlPullParser.next()){ if(eventType == XmlPullParser.START_TAG && xmlPullParser.getName().equals(tagName)){ result.add(xmlPullParser.nextText()); } } return result; } public static ArrayList<String> getTagNameInfo(String tagName, String className, String html) throws Exception{ ArrayList<String> result; int eventType; final XmlPullParser xmlPullParser; result= new ArrayList<String>(); xmlPullParser = Xml.newPullParser(); xmlPullParser.setInput(new StringReader(html)); for(eventType = xmlPullParser.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xmlPullParser.next()){ if(eventType == XmlPullParser.START_TAG && xmlPullParser.getName().equals(tagName) && xmlPullParser.getClass().equals(className)){ result.add(xmlPullParser.nextText()); } } return result; } public static String getXPath(String xpathString, byte[] xml) throws Exception{ DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbFactory.newDocumentBuilder(); Document document = builder.parse(new ByteArrayInputStream(xml)); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); String result = xpath.evaluate(xpathString, document); return result; } }
2,362
0.712532
0.711685
73
30.328768
21.533062
80
false
false
0
0
0
0
0
0
2.369863
false
false
7
a837aa0651862b7c86bfd711e11aa87dde0be6ff
15,135,464,801,457
d202e939027baf73de18d71cbc4d57a2e28daba0
/app/src/main/java/com/olsplus/balancemall/core/http/FileResponseBody.java
a499efd49ac5440e1d7b2ba61b2f201518faecc6
[]
no_license
linceln/HPM
https://github.com/linceln/HPM
47721540ff30cce20a7ad1e16277938f7ab2b957
a38028145acb82fdd969d45c99d598824a63f9a9
refs/heads/master
2021-01-13T03:17:46.246000
2017-02-08T01:20:34
2017-02-08T01:20:34
77,589,809
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.olsplus.balancemall.core.http; import com.olsplus.balancemall.app.upgrade.bean.DownloadProgressEvent; import org.greenrobot.eventbus.EventBus; import java.io.IOException; import okhttp3.MediaType; import okhttp3.ResponseBody; import okio.Buffer; import okio.BufferedSource; import okio.ForwardingSource; import okio.Okio; import okio.Source; /** * 自定义OkHttp3的ResponseBody,在HttpManager中配置 * 添加实时下载进度 * 用EventBus发送进度到UpgradeDownDialog中 */ public class FileResponseBody extends ResponseBody { private ResponseBody responseBody; private BufferedSource bufferedSource; public FileResponseBody(ResponseBody responseBody) { this.responseBody = responseBody; } @Override public MediaType contentType() { return responseBody.contentType(); } @Override public long contentLength() { return responseBody.contentLength(); } @Override public BufferedSource source() { if (bufferedSource == null) { bufferedSource = Okio.buffer(source(responseBody.source())); } return bufferedSource; } private Source source(Source source) { return new ForwardingSource(source) { long bytesRead = 0; @Override public long read(Buffer sink, long byteCount) throws IOException { long bytesRead = super.read(sink, byteCount); this.bytesRead += bytesRead == -1 ? 0 : bytesRead; //实时发送当前已读取的字节和总字节 EventBus.getDefault().post(new DownloadProgressEvent(this.bytesRead, contentLength())); return bytesRead; } }; } }
UTF-8
Java
1,753
java
FileResponseBody.java
Java
[]
null
[]
package com.olsplus.balancemall.core.http; import com.olsplus.balancemall.app.upgrade.bean.DownloadProgressEvent; import org.greenrobot.eventbus.EventBus; import java.io.IOException; import okhttp3.MediaType; import okhttp3.ResponseBody; import okio.Buffer; import okio.BufferedSource; import okio.ForwardingSource; import okio.Okio; import okio.Source; /** * 自定义OkHttp3的ResponseBody,在HttpManager中配置 * 添加实时下载进度 * 用EventBus发送进度到UpgradeDownDialog中 */ public class FileResponseBody extends ResponseBody { private ResponseBody responseBody; private BufferedSource bufferedSource; public FileResponseBody(ResponseBody responseBody) { this.responseBody = responseBody; } @Override public MediaType contentType() { return responseBody.contentType(); } @Override public long contentLength() { return responseBody.contentLength(); } @Override public BufferedSource source() { if (bufferedSource == null) { bufferedSource = Okio.buffer(source(responseBody.source())); } return bufferedSource; } private Source source(Source source) { return new ForwardingSource(source) { long bytesRead = 0; @Override public long read(Buffer sink, long byteCount) throws IOException { long bytesRead = super.read(sink, byteCount); this.bytesRead += bytesRead == -1 ? 0 : bytesRead; //实时发送当前已读取的字节和总字节 EventBus.getDefault().post(new DownloadProgressEvent(this.bytesRead, contentLength())); return bytesRead; } }; } }
1,753
0.668858
0.665272
66
24.348484
23.268845
103
false
false
0
0
0
0
0
0
0.409091
false
false
7
b9a7fa783027f3cc92203221f3799f6621ae2820
10,479,720,253,127
423dc171fc540669d2379491a6dad1aa7c6cfc74
/excercises/implementation/Change.java
35372b74dce9b3270bd866308692ab737baf45b5
[]
no_license
chilja/Practice
https://github.com/chilja/Practice
fc098196906e251a4c43cc487c4109795e1ae997
183017cd11bbf5bc9f53abc8c5af30bbcb9277d4
refs/heads/master
2020-06-01T06:32:22.456000
2015-04-27T13:25:53
2015-04-27T13:25:53
34,312,385
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package excercises.implementation; import java.util.HashMap; import java.util.HashSet; /** * @author chiljagossow * */ public class Change { /** * @param args */ public static void main(String[] args) { HashSet<Change> set; try { set = getChange(100); for (Change c: set){ System.out.println("quarters " + c.quarters + " dimes " + c.dimes + " nickels " + c.nickels + " pennies " + c.pennies); } } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static HashMap<Integer, HashSet<Change>> sSets = new HashMap<Integer, HashSet<Change>>(); private int quarters; private int dimes; private int nickels; private int pennies; @Override public boolean equals(Object o) { if (o instanceof Change) { Change c = (Change) o; if ( quarters == c.quarters && dimes == c.dimes && nickels == c.nickels && pennies == c.pennies ) { return true; } } return false; } public int hashCode() { return quarters + dimes + nickels + pennies; } public Object clone() { Change c = new Change(); c.quarters = quarters; c.dimes = dimes; c.nickels = nickels; c.pennies = pennies; return c; } public static HashSet<Change> getChange(int amount) throws CloneNotSupportedException { if (amount < 0) return null; if (sSets.containsKey(amount)) { return sSets.get(amount); } HashSet<Change> set = new HashSet<Change>(); if (amount == 0) { Change c = new Change(); set.add(c); sSets.put(amount, set); return set; } HashSet<Change> set25 = getChange(amount - 25); if (set25 != null) { for (Change c: set25){ Change c2 = (Change) c.clone(); c2.quarters++; set.add(c2); } } HashSet<Change> set10 = getChange(amount - 10); if (set10 != null) { for (Change c: set10){ Change c2 = (Change) c.clone(); c2.dimes++; set.add(c2); } } HashSet<Change> set5 = getChange(amount - 5); if (set5 != null) { for (Change c: set5){ Change c2 = (Change) c.clone(); c2.nickels++; set.add(c2); } } HashSet<Change> set1 = getChange(amount - 1); if (set1 != null) { for (Change c: set1){ Change c2 = (Change) c.clone(); c2.pennies++; set.add(c2); } } sSets.put(amount, set); return set; } }
UTF-8
Java
2,602
java
Change.java
Java
[ { "context": "HashMap;\nimport java.util.HashSet;\n\n/**\n * @author chiljagossow\n *\n */\npublic class Change {\n\n /**\n * @param a", "end": 128, "score": 0.9924147129058838, "start": 116, "tag": "USERNAME", "value": "chiljagossow" } ]
null
[]
/** * */ package excercises.implementation; import java.util.HashMap; import java.util.HashSet; /** * @author chiljagossow * */ public class Change { /** * @param args */ public static void main(String[] args) { HashSet<Change> set; try { set = getChange(100); for (Change c: set){ System.out.println("quarters " + c.quarters + " dimes " + c.dimes + " nickels " + c.nickels + " pennies " + c.pennies); } } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static HashMap<Integer, HashSet<Change>> sSets = new HashMap<Integer, HashSet<Change>>(); private int quarters; private int dimes; private int nickels; private int pennies; @Override public boolean equals(Object o) { if (o instanceof Change) { Change c = (Change) o; if ( quarters == c.quarters && dimes == c.dimes && nickels == c.nickels && pennies == c.pennies ) { return true; } } return false; } public int hashCode() { return quarters + dimes + nickels + pennies; } public Object clone() { Change c = new Change(); c.quarters = quarters; c.dimes = dimes; c.nickels = nickels; c.pennies = pennies; return c; } public static HashSet<Change> getChange(int amount) throws CloneNotSupportedException { if (amount < 0) return null; if (sSets.containsKey(amount)) { return sSets.get(amount); } HashSet<Change> set = new HashSet<Change>(); if (amount == 0) { Change c = new Change(); set.add(c); sSets.put(amount, set); return set; } HashSet<Change> set25 = getChange(amount - 25); if (set25 != null) { for (Change c: set25){ Change c2 = (Change) c.clone(); c2.quarters++; set.add(c2); } } HashSet<Change> set10 = getChange(amount - 10); if (set10 != null) { for (Change c: set10){ Change c2 = (Change) c.clone(); c2.dimes++; set.add(c2); } } HashSet<Change> set5 = getChange(amount - 5); if (set5 != null) { for (Change c: set5){ Change c2 = (Change) c.clone(); c2.nickels++; set.add(c2); } } HashSet<Change> set1 = getChange(amount - 1); if (set1 != null) { for (Change c: set1){ Change c2 = (Change) c.clone(); c2.pennies++; set.add(c2); } } sSets.put(amount, set); return set; } }
2,602
0.544965
0.529208
114
21.824562
19.697824
127
false
false
0
0
0
0
0
0
0.447368
false
false
7
119a68c2badf28eb96a4dcd213db1de300c779e2
3,624,952,450,234
04c3a66ca44d6e790fd87d04606cc8b84b393c04
/binary_trees/Rahul_Counting_Trees.java
174046688081dc8060147c2a2582f19f67ba3284
[ "Apache-2.0" ]
permissive
sumitkrnitjsr/Coding_Ninjas_Java_DSA
https://github.com/sumitkrnitjsr/Coding_Ninjas_Java_DSA
16c433017b83ef6a20580679184ed5f3f9742486
269b78e5450fd0749f17c734ac3dd5e7251c1d99
refs/heads/main
2023-03-28T05:57:36.530000
2021-03-25T20:20:00
2021-03-25T20:30:11
351,561,685
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package binary_trees; import java.util.Scanner; /* You are given a Binary tree T and an integer K. Input binary Trees T is consisting of N (numbered from 1 to N) nodes rooted at node 1 and each node has a number written on it, where the number written on the ith node is A[i]. Now, Rahul needs to find the number of unordered triplets (i,j,k), such that node i is an ancestor of node j as well as node k, and A[i]+A[j]+A[k]>=K A node x is considered an ancestor of another node y, if x is parent of y or x is an ancestor of parent of y. */ public class Rahul_Counting_Trees { public static void main(String args[]){ long sum; // didn't use long variable, had wrong answer int n; Scanner sc = new Scanner(System.in); n = sc.nextInt(); sum = sc.nextLong(); long[] array = new long[n + 1]; long[] parent = new long[n + 1]; for(int i = 1;i <= n;i++){ array[i] = sc.nextLong(); } for(int i = 2;i <= n;i++){ parent[i] = sc.nextLong(); } boolean ancestor[][] = new boolean[n + 1][n + 1]; for(int i = 0;i <= n;i++){ for(int j = 0;j <= n;j++){ ancestor[i][j] = false; } } long root = 1; for(int i = 2;i <= n;i++){ int node = i; while(node != root){ node = (int)parent[node]; ancestor[node][i] = true; } } long ans = 0; for(int i = 1;i <= n;i++){ for(int j = 1;j <= n;j++){ for(int k = 1;k <= n;k++){ if(i != j && j != k && i != k && ancestor[i][k] && ancestor[i][j] && (array[i] + array[j] + array[k] >= sum)){ ans++; } } } } ans = (ans/2l); System.out.print(ans); } }
UTF-8
Java
2,006
java
Rahul_Counting_Trees.java
Java
[ { "context": "e the number written on the ith node is A[i].\nNow, Rahul needs to find the number of unordered triplet", "end": 283, "score": 0.7528465986251831, "start": 282, "tag": "NAME", "value": "R" } ]
null
[]
package binary_trees; import java.util.Scanner; /* You are given a Binary tree T and an integer K. Input binary Trees T is consisting of N (numbered from 1 to N) nodes rooted at node 1 and each node has a number written on it, where the number written on the ith node is A[i]. Now, Rahul needs to find the number of unordered triplets (i,j,k), such that node i is an ancestor of node j as well as node k, and A[i]+A[j]+A[k]>=K A node x is considered an ancestor of another node y, if x is parent of y or x is an ancestor of parent of y. */ public class Rahul_Counting_Trees { public static void main(String args[]){ long sum; // didn't use long variable, had wrong answer int n; Scanner sc = new Scanner(System.in); n = sc.nextInt(); sum = sc.nextLong(); long[] array = new long[n + 1]; long[] parent = new long[n + 1]; for(int i = 1;i <= n;i++){ array[i] = sc.nextLong(); } for(int i = 2;i <= n;i++){ parent[i] = sc.nextLong(); } boolean ancestor[][] = new boolean[n + 1][n + 1]; for(int i = 0;i <= n;i++){ for(int j = 0;j <= n;j++){ ancestor[i][j] = false; } } long root = 1; for(int i = 2;i <= n;i++){ int node = i; while(node != root){ node = (int)parent[node]; ancestor[node][i] = true; } } long ans = 0; for(int i = 1;i <= n;i++){ for(int j = 1;j <= n;j++){ for(int k = 1;k <= n;k++){ if(i != j && j != k && i != k && ancestor[i][k] && ancestor[i][j] && (array[i] + array[j] + array[k] >= sum)){ ans++; } } } } ans = (ans/2l); System.out.print(ans); } }
2,006
0.449651
0.441176
60
32.433334
37.475933
225
false
false
0
0
0
0
0
0
1.566667
false
false
7
d09e27662b141b3fd6c88fb6290334cd0c3ebd3c
4,037,269,313,869
3e18f2f1f8f319cbfb08e968446cf9b3eaa9b41f
/src/main/java/com/covens/common/item/ModItems.java
616dd802a6689e5a69909068a8649288511f0aa8
[ "MIT" ]
permissive
zabi94/Covens-reborn
https://github.com/zabi94/Covens-reborn
f35dbb85f78d1b297956907c3b05f0a9cc045be6
6fe956025ad47051e14e2e7c45893ddebc5c330a
refs/heads/master
2020-04-10T16:17:30.713000
2020-03-07T13:23:22
2020-03-07T13:23:22
161,140,468
11
2
NOASSERTION
false
2019-05-08T19:31:40
2018-12-10T08:15:04
2019-04-28T19:38:50
2019-05-08T19:31:39
5,885
6
2
22
Java
false
false
package com.covens.common.item; import javax.annotation.Nullable; import com.covens.api.ritual.EnumGlyphType; import com.covens.common.block.ModBlocks; import com.covens.common.block.chisel.BlockColdIronChiseled; import com.covens.common.block.chisel.BlockNetherSteelChiseled; import com.covens.common.block.chisel.BlockSilverChiseled; import com.covens.common.block.natural.Gem; import com.covens.common.core.capability.altar.MixedProvider; import com.covens.common.core.helper.CropHelper; import com.covens.common.item.block.ItemBlockColor; import com.covens.common.item.block.ItemBlockMeta; import com.covens.common.item.block.ItemBlockMeta.EnumNameMode; import com.covens.common.item.block.ItemBlockRevealingLantern; import com.covens.common.item.block.ItemBlockSapling; import com.covens.common.item.block.ItemGemBlock; import com.covens.common.item.block.ItemGemOre; import com.covens.common.item.block.ItemGoblet; import com.covens.common.item.equipment.ItemSilverArmor; import com.covens.common.item.equipment.ItemVampireArmor; import com.covens.common.item.equipment.ItemWitchesArmor; import com.covens.common.item.equipment.baubles.ItemGirdleOfTheWooded; import com.covens.common.item.equipment.baubles.ItemHellishBauble; import com.covens.common.item.equipment.baubles.ItemHorseshoe; import com.covens.common.item.equipment.baubles.ItemMantle; import com.covens.common.item.equipment.baubles.ItemOmenNeckalce; import com.covens.common.item.equipment.baubles.ItemPouch; import com.covens.common.item.equipment.baubles.ItemRemedyTalisman; import com.covens.common.item.equipment.baubles.ItemTalisman; import com.covens.common.item.equipment.baubles.ItemTriskelionAmulet; import com.covens.common.item.food.ItemFilledBowl; import com.covens.common.item.food.ItemHeart; import com.covens.common.item.food.ItemHoney; import com.covens.common.item.food.ItemJuniperBerries; import com.covens.common.item.food.ItemMagicSalve; import com.covens.common.item.magic.ItemBell; import com.covens.common.item.magic.ItemBroom; import com.covens.common.item.magic.ItemLocationStone; import com.covens.common.item.magic.ItemRitualChalk; import com.covens.common.item.magic.ItemSalt; import com.covens.common.item.magic.ItemSpellPage; import com.covens.common.item.magic.ItemTaglock; import com.covens.common.item.magic.ItemTarots; import com.covens.common.item.magic.brew.ItemBrewArrow; import com.covens.common.item.magic.brew.ItemBrewDrinkable; import com.covens.common.item.magic.brew.ItemBrewThrowable; import com.covens.common.item.misc.ItemBloodBottle; import com.covens.common.item.misc.ItemSparkDarkness; import com.covens.common.item.tool.ItemAthame; import com.covens.common.item.tool.ItemBoline; import com.covens.common.item.tool.ItemColdIronAxe; import com.covens.common.item.tool.ItemColdIronHoe; import com.covens.common.item.tool.ItemColdIronPickaxe; import com.covens.common.item.tool.ItemColdIronSpade; import com.covens.common.item.tool.ItemColdIronSword; import com.covens.common.item.tool.ItemSilverAxe; import com.covens.common.item.tool.ItemSilverHoe; import com.covens.common.item.tool.ItemSilverPickaxe; import com.covens.common.item.tool.ItemSilverSpade; import com.covens.common.item.tool.ItemSilverSword; import com.covens.common.lib.LibItemName; import com.covens.common.lib.LibMod; import baubles.api.BaubleType; import net.minecraft.block.Block; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.fml.common.LoaderException; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.registries.IForgeRegistry; @ObjectHolder(LibMod.MOD_ID) public final class ModItems { public static final Item mandrake_root = null; public static final Item seed_mandrake = null; public static final Item belladonna = null; public static final Item seed_belladonna = null; public static final Item mint = null; public static final Item seed_mint = null; public static final Item thistle = null; public static final Item seed_thistle = null; public static final Item garlic = null; public static final Item seed_garlic = null; public static final Item aconitum = null; public static final Item seed_aconitum = null; public static final Item white_sage = null; public static final Item seed_white_sage = null; public static final Item tulsi = null; public static final Item seed_tulsi = null; public static final Item wormwood = null; public static final Item seed_wormwood = null; public static final Item hellebore = null; public static final Item seed_hellebore = null; public static final Item sagebrush = null; public static final Item seed_sagebrush = null; public static final Item chrysanthemum = null; public static final Item seed_chrysanthemum = null; public static final Item moonbell = null; public static final Item glass_jar = null; public static final Item brew_phial_drink = null; public static final Item brew_phial_splash = null; public static final Item brew_phial_linger = null; public static final Item brew_arrow = null; public static final Item empty_brew_drink = null; public static final Item empty_brew_splash = null; public static final Item empty_brew_linger = null; //Old fumes public static final Item unfired_jar = null; public static final Item empty_jar = null; // Empty public static final Item oak_spirit = null; public static final Item birch_soul = null; public static final Item acacia_essence = null; public static final Item spruce_heart = null; // common trees public static final Item cloudy_oil = null; // equivalent of foul fume - byproduct public static final Item cleansing_aura = null; // connected with cleaning, purifying public static final Item emanation_of_dishonesty = null; // connected with evil public static final Item everchanging_presence = null; // connected with changing public static final Item undying_image = null; // connected with rebirth public static final Item demonic_dew = null; // connected with nether/infernal stuff public static final Item otherworld_tears = null; // connected with end/ethereal stuff public static final Item fiery_breeze = null; // connected with fire public static final Item heavenly_winds = null; // connected with air public static final Item petrichor_odour = null; // connected with earth public static final Item zephyr_of_the_depths = null; // connected with water public static final Item reek_of_death = null; //Cypress public static final Item vital_essence = null; //Yew public static final Item droplet_of_wisdom = null; //Elder public static final Item bottled_magic = null; // Juniper public static final Item wax = null; public static final Item honey = null; public static final Item salt = null; public static final Item wool_of_bat = null; public static final Item tongue_of_dog = null; public static final Item wood_ash = null; public static final Item honeycomb = null; public static final Item empty_honeycomb = null; public static final Item needle_bone = null; public static final Item cold_iron_ingot = null; public static final Item silver_ingot = null; public static final Item silver_nugget = null; public static final Item athame = null; public static final Item boline = null; public static final Item taglock = null; public static final Item spectral_dust = null; public static final Item silver_scales = null; public static final Item heart = null; public static final Item dimensional_sand = null; public static final Item owlets_wing = null; public static final Item ravens_feather = null; public static final Item equine_tail = null; public static final Item stew = null; public static final Item cold_iron_nugget = null; public static final Item spanish_moss = null; public static final Item juniper_berries = null; public static final Item sanguine_fabric = null; public static final Item golden_thread = null; public static final Item regal_silk = null; public static final Item witches_stitching = null; public static final Item diabolic_vein = null; public static final Item pure_filament = null; public static final Item soul_string = null; public static final Item graveyard_dust = null; public static final Item silver_pickaxe = null; public static final Item silver_axe = null; public static final Item silver_spade = null; public static final Item silver_hoe = null; public static final Item silver_sword = null; public static final Item silver_helmet = null; public static final Item silver_chestplate = null; public static final Item silver_leggings = null; public static final Item silver_boots = null; public static final Item witches_hat = null; public static final Item witches_robes = null; public static final Item witches_pants = null; public static final Item vampire_hat = null; public static final Item vampire_vest = null; public static final Item vampire_pants = null; // Baubles public static final Item omen_necklace = null; public static final Item talisman_aquamarine_crown = null; public static final Item talisman_adamantine_star_ring = null; public static final Item talisman_diamond_star = null; public static final Item talisman_emerald_pendant = null; public static final Item talisman_watching_eye = null; public static final Item talisman_ruby_orb = null; public static final Item horseshoe = null; public static final Item remedy_talisman = null; public static final Item girdle_of_the_wooded = null; public static final Item mantle = null; public static final Item pouch = null; public static final Item magic_salve = null; public static final Item tarots = null; public static final Item broom = null; public static final Item spell_page = null; public static final Item ritual_chalk_normal = null; public static final Item ritual_chalk_golden = null; public static final Item ritual_chalk_nether = null; public static final Item ritual_chalk_ender = null; public static final Item location_stone = null; public static final Item bell = null; public static final Item adders_fork = null; public static final Item toe_of_frog = null; public static final Item eye_of_newt = null; public static final Item lizard_leg = null; public static final Item pentacle = null; public static final Item cold_iron_sword = null; public static final Item cold_iron_axe = null; public static final Item cold_iron_hoe = null; public static final Item cold_iron_spade = null; public static final Item cold_iron_pickaxe = null; public static final Item blood_bottle = null; public static final Item spark_of_darkness = null; public static final Item gem_garnet = null; public static final Item gem_tourmaline = null; public static final Item gem_tigers_eye = null; public static final Item gem_malachite = null; public static ItemRitualChalk[] chalkType; private ModItems() { } public static void register(final IForgeRegistry<Item> registry) { CropHelper.getFoods().forEach((crop, item) -> registry.register(item)); CropHelper.getSeeds().forEach((crop, item) -> registry.register(item)); registry.register(new ItemMod(LibItemName.COLD_IRON_INGOT)); registry.register(new ItemMod(LibItemName.SILVER_INGOT)); registry.register(new ItemMod(LibItemName.SILVER_NUGGET)); registry.register(new ItemMod(LibItemName.UNFIRED_JAR)); registry.register(new ItemMod(LibItemName.EMPTY_JAR)); registry.register(new ItemMod(LibItemName.OAK_SPIRIT)); registry.register(new ItemMod(LibItemName.BIRCH_SOUL)); registry.register(new ItemMod(LibItemName.ACACIA_ESSENCE)); registry.register(new ItemMod(LibItemName.SPRUCE_HEART)); registry.register(new ItemMod(LibItemName.CLOUDY_OIL)); registry.register(new ItemMod(LibItemName.CLEANSING_AURA)); registry.register(new ItemMod(LibItemName.EMANATION_OF_DISHONESTY)); registry.register(new ItemMod(LibItemName.EVERCHANGING_PRESENCE)); registry.register(new ItemMod(LibItemName.UNDYING_IMAGE)); registry.register(new ItemMod(LibItemName.DEMONIC_DEW)); registry.register(new ItemMod(LibItemName.OTHERWORLD_TEARS)); registry.register(new ItemMod(LibItemName.FIERY_BREEZE)); registry.register(new ItemMod(LibItemName.HEAVENLY_WINDS)); registry.register(new ItemMod(LibItemName.PETRICHOR_ODOUR)); registry.register(new ItemMod(LibItemName.ZEPHYR_OF_THE_DEPTHS)); registry.register(new ItemMod(LibItemName.REEK_OF_DEATH)); registry.register(new ItemMod(LibItemName.VITAL_ESSENCE)); registry.register(new ItemMod(LibItemName.DROPLET_OF_WISDOM)); registry.register(new ItemMod(LibItemName.BOTTLED_MAGIC)); registry.register(new ItemSpellPage(LibItemName.SPELL_PAGE)); registry.register(new ItemBell()); chalkType = new ItemRitualChalk[] { new ItemRitualChalk(EnumGlyphType.NORMAL), // new ItemRitualChalk(EnumGlyphType.GOLDEN), // new ItemRitualChalk(EnumGlyphType.ENDER), // new ItemRitualChalk(EnumGlyphType.NETHER) // }; // Misc registry.registerAll( // new ItemHoney(), // new ItemSalt(), // new ItemMod(LibItemName.WAX), // new ItemMod(LibItemName.HONEYCOMB), // new ItemMod(LibItemName.EMPTY_HONEYCOMB), // new ItemBrewDrinkable(), // new ItemBrewThrowable(LibItemName.BREW_PHIAL_SPLASH), // new ItemBrewThrowable(LibItemName.BREW_PHIAL_LINGER), // new ItemMod(LibItemName.EMPTY_BREW_DRINK), // new ItemMod(LibItemName.EMPTY_BREW_SPLASH), // new ItemMod(LibItemName.EMPTY_BREW_LINGER), // new ItemBrewArrow(), // new ItemMod(LibItemName.GLASS_JAR), // new ItemAthame(), // new ItemBoline(), // new ItemTaglock(), // new ItemMod(LibItemName.NEEDLE_BONE), // new ItemMod(LibItemName.WOOL_OF_BAT), // new ItemMod(LibItemName.TONGUE_OF_DOG), // new ItemMod(LibItemName.WOOD_ASH), // new ItemMod(LibItemName.SPECTRAL_DUST), // new ItemMod(LibItemName.SILVER_SCALES), // new ItemMod(LibItemName.DIMENSIONAL_SAND), // new ItemMod(LibItemName.EQUINE_TAIL), // new ItemMod(LibItemName.GOLDEN_THREAD), // new ItemMod(LibItemName.COLD_IRON_NUGGET), // new ItemMod(LibItemName.OWLETS_WING), // // new ItemMod(LibItemName.RAVENS_FEATHER), // new ItemMod(LibItemName.REGAL_SILK), // new ItemMod(LibItemName.WITCHES_STITCHING), // new ItemMod(LibItemName.DIABOLIC_VEIN), // new ItemMod(LibItemName.PURE_FILAMENT), // new ItemMod(LibItemName.SOUL_STRING), // new ItemMod(LibItemName.GRAVEYARD_DUST), // new ItemMod(LibItemName.SANGUINE_FABRIC), // new ItemMod(LibItemName.PENTACLE) { private final MixedProvider caps = new MixedProvider(-2, 0.3); @Override @Nullable public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable NBTTagCompound nbt) { return caps; } }, // new ItemMod(LibItemName.ADDERS_FORK), // new ItemMod(LibItemName.TOE_OF_FROG), // new ItemMod(LibItemName.LIZARD_LEG), // new ItemMod(LibItemName.EYE_OF_NEWT), // new ItemHeart(), // new ItemJuniperBerries(), // new ItemFilledBowl(), // chalkType[0], chalkType[1], chalkType[2], chalkType[3], new ItemRemedyTalisman(), // new ItemMagicSalve(), // new ItemLocationStone(), // new ItemTarots(LibItemName.TAROTS), // new ItemBroom(LibItemName.BROOM), // new ItemBloodBottle(LibItemName.BLOOD_BOTTLE), // new ItemSparkDarkness(LibItemName.SPARK_DARKNESS) // // new ItemMod(LibItemName.WITCHWEED), // new ItemMod(LibItemName.INFESTED_WHEAT) ); // Baubles registry.registerAll(// new ItemOmenNeckalce(), // new ItemHorseshoe(), // new ItemTriskelionAmulet(), // new ItemHellishBauble(), // new ItemTalisman(BaubleType.HEAD, 35, LibItemName.TALISMAN_AQUAMARINE_CROWN), // new ItemTalisman(BaubleType.RING, 18, LibItemName.TALISMAN_ADAMANTINE_STAR_RING), // new ItemTalisman(BaubleType.AMULET, 18, LibItemName.TALISMAN_EMERALD_PENDANT), // new ItemTalisman(BaubleType.BELT, 30, LibItemName.TALISMAN_RUBY_ORB), // new ItemTalisman(BaubleType.CHARM, 18, LibItemName.TALISMAN_WATCHING_EYE), // new ItemGirdleOfTheWooded(LibItemName.GIRDLE_OF_THE_WOODED), // new ItemMantle(LibItemName.MANTLE), // new ItemPouch(LibItemName.POUCH)); // Equipment registry.registerAll(// new ItemSilverPickaxe(), // new ItemSilverAxe(), // new ItemSilverSpade(), // new ItemSilverHoe(), // new ItemSilverSword(), // new ItemSilverArmor(LibItemName.SILVER_HELMET, ModMaterials.ARMOR_SILVER, 1, EntityEquipmentSlot.HEAD), // new ItemSilverArmor(LibItemName.SILVER_CHESTPLATE, ModMaterials.ARMOR_SILVER, 1, EntityEquipmentSlot.CHEST), // new ItemSilverArmor(LibItemName.SILVER_LEGGINGS, ModMaterials.ARMOR_SILVER, 2, EntityEquipmentSlot.LEGS), // new ItemSilverArmor(LibItemName.SILVER_BOOTS, ModMaterials.ARMOR_SILVER, 1, EntityEquipmentSlot.FEET), // new ItemWitchesArmor(LibItemName.WITCHES_HAT, ModMaterials.ARMOR_WITCH_LEATHER, 1, EntityEquipmentSlot.HEAD), // new ItemWitchesArmor(LibItemName.WITCHES_ROBES, ModMaterials.ARMOR_WITCH_LEATHER, 1, EntityEquipmentSlot.CHEST), // new ItemWitchesArmor(LibItemName.WITCHES_PANTS, ModMaterials.ARMOR_WITCH_LEATHER, 2, EntityEquipmentSlot.LEGS), // new ItemVampireArmor(LibItemName.VAMPIRE_HAT, ModMaterials.ARMOR_VAMPIRE, 1, EntityEquipmentSlot.HEAD), // new ItemVampireArmor(LibItemName.VAMPIRE_VEST, ModMaterials.ARMOR_VAMPIRE, 2, EntityEquipmentSlot.CHEST), new ItemVampireArmor(LibItemName.VAMPIRE_PANTS, ModMaterials.ARMOR_VAMPIRE, 2, EntityEquipmentSlot.LEGS), new ItemColdIronSword(), // new ItemColdIronAxe(), // new ItemColdIronHoe(), // new ItemColdIronPickaxe(), // new ItemColdIronSpade()); // Item Blocks registry.registerAll(// new ItemBlockColor(ModBlocks.candle_medium), // new ItemBlockColor(ModBlocks.candle_small), // new ItemBlockColor(ModBlocks.candle_medium_lit), // new ItemBlockColor(ModBlocks.candle_small_lit), // itemBlock(ModBlocks.fake_ice), // itemBlock(ModBlocks.silver_block), // itemBlock(ModBlocks.silver_ore), // itemBlock(ModBlocks.cauldron), // itemBlock(ModBlocks.oven), // itemBlock(ModBlocks.distillery), // itemBlock(ModBlocks.apiary), // itemBlock(ModBlocks.brazier), // itemBlock(ModBlocks.beehive), // itemBlock(ModBlocks.salt_ore), // itemBlock(ModBlocks.nethersteel), // itemBlock(ModBlocks.log_elder), // itemBlock(ModBlocks.log_juniper), // itemBlock(ModBlocks.log_yew), // itemBlock(ModBlocks.log_cypress), // itemBlock(ModBlocks.leaves_elder), // itemBlock(ModBlocks.leaves_juniper), // itemBlock(ModBlocks.leaves_yew), // itemBlock(ModBlocks.leaves_cypress), // itemBlock(ModBlocks.planks_elder), // itemBlock(ModBlocks.planks_juniper), // itemBlock(ModBlocks.planks_yew), // itemBlock(ModBlocks.planks_cypress), // itemBlock(ModBlocks.purifying_earth), // new ItemBlockSapling(), itemBlock(ModBlocks.moonbell), // itemBlock(ModBlocks.witch_altar), // itemBlock(ModBlocks.thread_spinner), // itemBlock(ModBlocks.crystal_ball), // new ItemGoblet(), // itemBlock(ModBlocks.gem_bowl), // itemBlock(ModBlocks.magic_mirror), // itemBlock(ModBlocks.tarot_table), // itemBlock(ModBlocks.cold_iron_block), // itemBlock(ModBlocks.graveyard_dirt), // new ItemBlockRevealingLantern(ModBlocks.lantern, false), // new ItemBlockRevealingLantern(ModBlocks.revealing_lantern, true)// ); for (Gem g:Gem.values()) { registry.register(g.setGemItem(new ItemMod(g.getGemName()))); registry.register(new ItemGemBlock(g.getGemBlock())); registry.register(new ItemGemOre(g.getOreBlock())); } // Chisel registry.registerAll(// new ItemBlockMeta<>(ModBlocks.silver_block_chisel, BlockSilverChiseled.BlockSilverVariant.values(), EnumNameMode.TOOLTIP), // new ItemBlockMeta<>(ModBlocks.cold_iron_block_chisel, BlockColdIronChiseled.BlockColdIronVariant.values(), EnumNameMode.TOOLTIP), // new ItemBlockMeta<>(ModBlocks.nethersteel_chisel, BlockNetherSteelChiseled.BlockSteelVariant.values(), EnumNameMode.TOOLTIP)); } private static Item itemBlock(Block block) { if (block == null) { throw new LoaderException("[" + LibMod.MOD_NAME + "] Trying to register an ItemBlock for a null block"); } if (block.getRegistryName() == null) { throw new LoaderException("[" + LibMod.MOD_NAME + "] Trying to register an ItemBlock for a block with null name - " + block.getTranslationKey()); } if (block.getRegistryName().toString() == null) { throw new LoaderException("[" + LibMod.MOD_NAME + "] There's something wrong with the registry implementation of " + block.getTranslationKey()); } return new ItemBlockMod(block).setRegistryName(block.getRegistryName()); } public static void init() { initOreDictionary(); } private static void initOreDictionary() { OreDictionary.registerOre("gemGarnet", new ItemStack(ModItems.gem_garnet)); OreDictionary.registerOre("gemTourmaline", new ItemStack(ModItems.gem_tourmaline)); OreDictionary.registerOre("gemTigersEye", new ItemStack(ModItems.gem_tigers_eye)); OreDictionary.registerOre("gemMalachite", new ItemStack(ModItems.gem_malachite)); OreDictionary.registerOre("nuggetSilver", new ItemStack(ModItems.silver_nugget)); OreDictionary.registerOre("ingotSilver", new ItemStack(ModItems.silver_ingot)); OreDictionary.registerOre("honeyDrop", new ItemStack(ModItems.honey)); OreDictionary.registerOre("dropHoney", new ItemStack(ModItems.honey)); OreDictionary.registerOre("foodHoneydrop", new ItemStack(ModItems.honey)); OreDictionary.registerOre("listAllsugar", new ItemStack(ModItems.honey)); OreDictionary.registerOre("materialWax", new ItemStack(ModItems.wax)); OreDictionary.registerOre("materialBeeswax", new ItemStack(ModItems.wax)); OreDictionary.registerOre("materialPressedWax", new ItemStack(ModItems.wax)); OreDictionary.registerOre("itemBeeswax", new ItemStack(ModItems.wax)); OreDictionary.registerOre("foodSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("dustSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("materialSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("lumpSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("salt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("listAllsalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("ingredientSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("pinchSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("portionSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("cropBelladonna", new ItemStack(ModItems.belladonna)); OreDictionary.registerOre("cropMandrake", new ItemStack(ModItems.mandrake_root)); OreDictionary.registerOre("cropMint", new ItemStack(ModItems.mint)); OreDictionary.registerOre("listAllspice", new ItemStack(ModItems.mint)); OreDictionary.registerOre("cropSpiceleaf", new ItemStack(ModItems.mint)); OreDictionary.registerOre("listAllgreenveggie", new ItemStack(ModItems.mint)); OreDictionary.registerOre("cropThistle", new ItemStack(ModItems.thistle)); OreDictionary.registerOre("cropGarlic", new ItemStack(ModItems.garlic)); OreDictionary.registerOre("listAllherb", new ItemStack(ModItems.garlic)); OreDictionary.registerOre("cropAconitum", new ItemStack(ModItems.aconitum)); OreDictionary.registerOre("cropWhiteSage", new ItemStack(ModItems.white_sage)); OreDictionary.registerOre("cropTulsi", new ItemStack(ModItems.tulsi)); OreDictionary.registerOre("listAllherb", new ItemStack(ModItems.tulsi)); OreDictionary.registerOre("listAllspice", new ItemStack(ModItems.wormwood)); OreDictionary.registerOre("cropWormwood", new ItemStack(ModItems.wormwood)); OreDictionary.registerOre("ingotColdIron", new ItemStack(ModItems.cold_iron_ingot)); OreDictionary.registerOre("nuggetColdIron", new ItemStack(ModItems.cold_iron_nugget)); } }
UTF-8
Java
24,281
java
ModItems.java
Java
[]
null
[]
package com.covens.common.item; import javax.annotation.Nullable; import com.covens.api.ritual.EnumGlyphType; import com.covens.common.block.ModBlocks; import com.covens.common.block.chisel.BlockColdIronChiseled; import com.covens.common.block.chisel.BlockNetherSteelChiseled; import com.covens.common.block.chisel.BlockSilverChiseled; import com.covens.common.block.natural.Gem; import com.covens.common.core.capability.altar.MixedProvider; import com.covens.common.core.helper.CropHelper; import com.covens.common.item.block.ItemBlockColor; import com.covens.common.item.block.ItemBlockMeta; import com.covens.common.item.block.ItemBlockMeta.EnumNameMode; import com.covens.common.item.block.ItemBlockRevealingLantern; import com.covens.common.item.block.ItemBlockSapling; import com.covens.common.item.block.ItemGemBlock; import com.covens.common.item.block.ItemGemOre; import com.covens.common.item.block.ItemGoblet; import com.covens.common.item.equipment.ItemSilverArmor; import com.covens.common.item.equipment.ItemVampireArmor; import com.covens.common.item.equipment.ItemWitchesArmor; import com.covens.common.item.equipment.baubles.ItemGirdleOfTheWooded; import com.covens.common.item.equipment.baubles.ItemHellishBauble; import com.covens.common.item.equipment.baubles.ItemHorseshoe; import com.covens.common.item.equipment.baubles.ItemMantle; import com.covens.common.item.equipment.baubles.ItemOmenNeckalce; import com.covens.common.item.equipment.baubles.ItemPouch; import com.covens.common.item.equipment.baubles.ItemRemedyTalisman; import com.covens.common.item.equipment.baubles.ItemTalisman; import com.covens.common.item.equipment.baubles.ItemTriskelionAmulet; import com.covens.common.item.food.ItemFilledBowl; import com.covens.common.item.food.ItemHeart; import com.covens.common.item.food.ItemHoney; import com.covens.common.item.food.ItemJuniperBerries; import com.covens.common.item.food.ItemMagicSalve; import com.covens.common.item.magic.ItemBell; import com.covens.common.item.magic.ItemBroom; import com.covens.common.item.magic.ItemLocationStone; import com.covens.common.item.magic.ItemRitualChalk; import com.covens.common.item.magic.ItemSalt; import com.covens.common.item.magic.ItemSpellPage; import com.covens.common.item.magic.ItemTaglock; import com.covens.common.item.magic.ItemTarots; import com.covens.common.item.magic.brew.ItemBrewArrow; import com.covens.common.item.magic.brew.ItemBrewDrinkable; import com.covens.common.item.magic.brew.ItemBrewThrowable; import com.covens.common.item.misc.ItemBloodBottle; import com.covens.common.item.misc.ItemSparkDarkness; import com.covens.common.item.tool.ItemAthame; import com.covens.common.item.tool.ItemBoline; import com.covens.common.item.tool.ItemColdIronAxe; import com.covens.common.item.tool.ItemColdIronHoe; import com.covens.common.item.tool.ItemColdIronPickaxe; import com.covens.common.item.tool.ItemColdIronSpade; import com.covens.common.item.tool.ItemColdIronSword; import com.covens.common.item.tool.ItemSilverAxe; import com.covens.common.item.tool.ItemSilverHoe; import com.covens.common.item.tool.ItemSilverPickaxe; import com.covens.common.item.tool.ItemSilverSpade; import com.covens.common.item.tool.ItemSilverSword; import com.covens.common.lib.LibItemName; import com.covens.common.lib.LibMod; import baubles.api.BaubleType; import net.minecraft.block.Block; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.fml.common.LoaderException; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.registries.IForgeRegistry; @ObjectHolder(LibMod.MOD_ID) public final class ModItems { public static final Item mandrake_root = null; public static final Item seed_mandrake = null; public static final Item belladonna = null; public static final Item seed_belladonna = null; public static final Item mint = null; public static final Item seed_mint = null; public static final Item thistle = null; public static final Item seed_thistle = null; public static final Item garlic = null; public static final Item seed_garlic = null; public static final Item aconitum = null; public static final Item seed_aconitum = null; public static final Item white_sage = null; public static final Item seed_white_sage = null; public static final Item tulsi = null; public static final Item seed_tulsi = null; public static final Item wormwood = null; public static final Item seed_wormwood = null; public static final Item hellebore = null; public static final Item seed_hellebore = null; public static final Item sagebrush = null; public static final Item seed_sagebrush = null; public static final Item chrysanthemum = null; public static final Item seed_chrysanthemum = null; public static final Item moonbell = null; public static final Item glass_jar = null; public static final Item brew_phial_drink = null; public static final Item brew_phial_splash = null; public static final Item brew_phial_linger = null; public static final Item brew_arrow = null; public static final Item empty_brew_drink = null; public static final Item empty_brew_splash = null; public static final Item empty_brew_linger = null; //Old fumes public static final Item unfired_jar = null; public static final Item empty_jar = null; // Empty public static final Item oak_spirit = null; public static final Item birch_soul = null; public static final Item acacia_essence = null; public static final Item spruce_heart = null; // common trees public static final Item cloudy_oil = null; // equivalent of foul fume - byproduct public static final Item cleansing_aura = null; // connected with cleaning, purifying public static final Item emanation_of_dishonesty = null; // connected with evil public static final Item everchanging_presence = null; // connected with changing public static final Item undying_image = null; // connected with rebirth public static final Item demonic_dew = null; // connected with nether/infernal stuff public static final Item otherworld_tears = null; // connected with end/ethereal stuff public static final Item fiery_breeze = null; // connected with fire public static final Item heavenly_winds = null; // connected with air public static final Item petrichor_odour = null; // connected with earth public static final Item zephyr_of_the_depths = null; // connected with water public static final Item reek_of_death = null; //Cypress public static final Item vital_essence = null; //Yew public static final Item droplet_of_wisdom = null; //Elder public static final Item bottled_magic = null; // Juniper public static final Item wax = null; public static final Item honey = null; public static final Item salt = null; public static final Item wool_of_bat = null; public static final Item tongue_of_dog = null; public static final Item wood_ash = null; public static final Item honeycomb = null; public static final Item empty_honeycomb = null; public static final Item needle_bone = null; public static final Item cold_iron_ingot = null; public static final Item silver_ingot = null; public static final Item silver_nugget = null; public static final Item athame = null; public static final Item boline = null; public static final Item taglock = null; public static final Item spectral_dust = null; public static final Item silver_scales = null; public static final Item heart = null; public static final Item dimensional_sand = null; public static final Item owlets_wing = null; public static final Item ravens_feather = null; public static final Item equine_tail = null; public static final Item stew = null; public static final Item cold_iron_nugget = null; public static final Item spanish_moss = null; public static final Item juniper_berries = null; public static final Item sanguine_fabric = null; public static final Item golden_thread = null; public static final Item regal_silk = null; public static final Item witches_stitching = null; public static final Item diabolic_vein = null; public static final Item pure_filament = null; public static final Item soul_string = null; public static final Item graveyard_dust = null; public static final Item silver_pickaxe = null; public static final Item silver_axe = null; public static final Item silver_spade = null; public static final Item silver_hoe = null; public static final Item silver_sword = null; public static final Item silver_helmet = null; public static final Item silver_chestplate = null; public static final Item silver_leggings = null; public static final Item silver_boots = null; public static final Item witches_hat = null; public static final Item witches_robes = null; public static final Item witches_pants = null; public static final Item vampire_hat = null; public static final Item vampire_vest = null; public static final Item vampire_pants = null; // Baubles public static final Item omen_necklace = null; public static final Item talisman_aquamarine_crown = null; public static final Item talisman_adamantine_star_ring = null; public static final Item talisman_diamond_star = null; public static final Item talisman_emerald_pendant = null; public static final Item talisman_watching_eye = null; public static final Item talisman_ruby_orb = null; public static final Item horseshoe = null; public static final Item remedy_talisman = null; public static final Item girdle_of_the_wooded = null; public static final Item mantle = null; public static final Item pouch = null; public static final Item magic_salve = null; public static final Item tarots = null; public static final Item broom = null; public static final Item spell_page = null; public static final Item ritual_chalk_normal = null; public static final Item ritual_chalk_golden = null; public static final Item ritual_chalk_nether = null; public static final Item ritual_chalk_ender = null; public static final Item location_stone = null; public static final Item bell = null; public static final Item adders_fork = null; public static final Item toe_of_frog = null; public static final Item eye_of_newt = null; public static final Item lizard_leg = null; public static final Item pentacle = null; public static final Item cold_iron_sword = null; public static final Item cold_iron_axe = null; public static final Item cold_iron_hoe = null; public static final Item cold_iron_spade = null; public static final Item cold_iron_pickaxe = null; public static final Item blood_bottle = null; public static final Item spark_of_darkness = null; public static final Item gem_garnet = null; public static final Item gem_tourmaline = null; public static final Item gem_tigers_eye = null; public static final Item gem_malachite = null; public static ItemRitualChalk[] chalkType; private ModItems() { } public static void register(final IForgeRegistry<Item> registry) { CropHelper.getFoods().forEach((crop, item) -> registry.register(item)); CropHelper.getSeeds().forEach((crop, item) -> registry.register(item)); registry.register(new ItemMod(LibItemName.COLD_IRON_INGOT)); registry.register(new ItemMod(LibItemName.SILVER_INGOT)); registry.register(new ItemMod(LibItemName.SILVER_NUGGET)); registry.register(new ItemMod(LibItemName.UNFIRED_JAR)); registry.register(new ItemMod(LibItemName.EMPTY_JAR)); registry.register(new ItemMod(LibItemName.OAK_SPIRIT)); registry.register(new ItemMod(LibItemName.BIRCH_SOUL)); registry.register(new ItemMod(LibItemName.ACACIA_ESSENCE)); registry.register(new ItemMod(LibItemName.SPRUCE_HEART)); registry.register(new ItemMod(LibItemName.CLOUDY_OIL)); registry.register(new ItemMod(LibItemName.CLEANSING_AURA)); registry.register(new ItemMod(LibItemName.EMANATION_OF_DISHONESTY)); registry.register(new ItemMod(LibItemName.EVERCHANGING_PRESENCE)); registry.register(new ItemMod(LibItemName.UNDYING_IMAGE)); registry.register(new ItemMod(LibItemName.DEMONIC_DEW)); registry.register(new ItemMod(LibItemName.OTHERWORLD_TEARS)); registry.register(new ItemMod(LibItemName.FIERY_BREEZE)); registry.register(new ItemMod(LibItemName.HEAVENLY_WINDS)); registry.register(new ItemMod(LibItemName.PETRICHOR_ODOUR)); registry.register(new ItemMod(LibItemName.ZEPHYR_OF_THE_DEPTHS)); registry.register(new ItemMod(LibItemName.REEK_OF_DEATH)); registry.register(new ItemMod(LibItemName.VITAL_ESSENCE)); registry.register(new ItemMod(LibItemName.DROPLET_OF_WISDOM)); registry.register(new ItemMod(LibItemName.BOTTLED_MAGIC)); registry.register(new ItemSpellPage(LibItemName.SPELL_PAGE)); registry.register(new ItemBell()); chalkType = new ItemRitualChalk[] { new ItemRitualChalk(EnumGlyphType.NORMAL), // new ItemRitualChalk(EnumGlyphType.GOLDEN), // new ItemRitualChalk(EnumGlyphType.ENDER), // new ItemRitualChalk(EnumGlyphType.NETHER) // }; // Misc registry.registerAll( // new ItemHoney(), // new ItemSalt(), // new ItemMod(LibItemName.WAX), // new ItemMod(LibItemName.HONEYCOMB), // new ItemMod(LibItemName.EMPTY_HONEYCOMB), // new ItemBrewDrinkable(), // new ItemBrewThrowable(LibItemName.BREW_PHIAL_SPLASH), // new ItemBrewThrowable(LibItemName.BREW_PHIAL_LINGER), // new ItemMod(LibItemName.EMPTY_BREW_DRINK), // new ItemMod(LibItemName.EMPTY_BREW_SPLASH), // new ItemMod(LibItemName.EMPTY_BREW_LINGER), // new ItemBrewArrow(), // new ItemMod(LibItemName.GLASS_JAR), // new ItemAthame(), // new ItemBoline(), // new ItemTaglock(), // new ItemMod(LibItemName.NEEDLE_BONE), // new ItemMod(LibItemName.WOOL_OF_BAT), // new ItemMod(LibItemName.TONGUE_OF_DOG), // new ItemMod(LibItemName.WOOD_ASH), // new ItemMod(LibItemName.SPECTRAL_DUST), // new ItemMod(LibItemName.SILVER_SCALES), // new ItemMod(LibItemName.DIMENSIONAL_SAND), // new ItemMod(LibItemName.EQUINE_TAIL), // new ItemMod(LibItemName.GOLDEN_THREAD), // new ItemMod(LibItemName.COLD_IRON_NUGGET), // new ItemMod(LibItemName.OWLETS_WING), // // new ItemMod(LibItemName.RAVENS_FEATHER), // new ItemMod(LibItemName.REGAL_SILK), // new ItemMod(LibItemName.WITCHES_STITCHING), // new ItemMod(LibItemName.DIABOLIC_VEIN), // new ItemMod(LibItemName.PURE_FILAMENT), // new ItemMod(LibItemName.SOUL_STRING), // new ItemMod(LibItemName.GRAVEYARD_DUST), // new ItemMod(LibItemName.SANGUINE_FABRIC), // new ItemMod(LibItemName.PENTACLE) { private final MixedProvider caps = new MixedProvider(-2, 0.3); @Override @Nullable public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable NBTTagCompound nbt) { return caps; } }, // new ItemMod(LibItemName.ADDERS_FORK), // new ItemMod(LibItemName.TOE_OF_FROG), // new ItemMod(LibItemName.LIZARD_LEG), // new ItemMod(LibItemName.EYE_OF_NEWT), // new ItemHeart(), // new ItemJuniperBerries(), // new ItemFilledBowl(), // chalkType[0], chalkType[1], chalkType[2], chalkType[3], new ItemRemedyTalisman(), // new ItemMagicSalve(), // new ItemLocationStone(), // new ItemTarots(LibItemName.TAROTS), // new ItemBroom(LibItemName.BROOM), // new ItemBloodBottle(LibItemName.BLOOD_BOTTLE), // new ItemSparkDarkness(LibItemName.SPARK_DARKNESS) // // new ItemMod(LibItemName.WITCHWEED), // new ItemMod(LibItemName.INFESTED_WHEAT) ); // Baubles registry.registerAll(// new ItemOmenNeckalce(), // new ItemHorseshoe(), // new ItemTriskelionAmulet(), // new ItemHellishBauble(), // new ItemTalisman(BaubleType.HEAD, 35, LibItemName.TALISMAN_AQUAMARINE_CROWN), // new ItemTalisman(BaubleType.RING, 18, LibItemName.TALISMAN_ADAMANTINE_STAR_RING), // new ItemTalisman(BaubleType.AMULET, 18, LibItemName.TALISMAN_EMERALD_PENDANT), // new ItemTalisman(BaubleType.BELT, 30, LibItemName.TALISMAN_RUBY_ORB), // new ItemTalisman(BaubleType.CHARM, 18, LibItemName.TALISMAN_WATCHING_EYE), // new ItemGirdleOfTheWooded(LibItemName.GIRDLE_OF_THE_WOODED), // new ItemMantle(LibItemName.MANTLE), // new ItemPouch(LibItemName.POUCH)); // Equipment registry.registerAll(// new ItemSilverPickaxe(), // new ItemSilverAxe(), // new ItemSilverSpade(), // new ItemSilverHoe(), // new ItemSilverSword(), // new ItemSilverArmor(LibItemName.SILVER_HELMET, ModMaterials.ARMOR_SILVER, 1, EntityEquipmentSlot.HEAD), // new ItemSilverArmor(LibItemName.SILVER_CHESTPLATE, ModMaterials.ARMOR_SILVER, 1, EntityEquipmentSlot.CHEST), // new ItemSilverArmor(LibItemName.SILVER_LEGGINGS, ModMaterials.ARMOR_SILVER, 2, EntityEquipmentSlot.LEGS), // new ItemSilverArmor(LibItemName.SILVER_BOOTS, ModMaterials.ARMOR_SILVER, 1, EntityEquipmentSlot.FEET), // new ItemWitchesArmor(LibItemName.WITCHES_HAT, ModMaterials.ARMOR_WITCH_LEATHER, 1, EntityEquipmentSlot.HEAD), // new ItemWitchesArmor(LibItemName.WITCHES_ROBES, ModMaterials.ARMOR_WITCH_LEATHER, 1, EntityEquipmentSlot.CHEST), // new ItemWitchesArmor(LibItemName.WITCHES_PANTS, ModMaterials.ARMOR_WITCH_LEATHER, 2, EntityEquipmentSlot.LEGS), // new ItemVampireArmor(LibItemName.VAMPIRE_HAT, ModMaterials.ARMOR_VAMPIRE, 1, EntityEquipmentSlot.HEAD), // new ItemVampireArmor(LibItemName.VAMPIRE_VEST, ModMaterials.ARMOR_VAMPIRE, 2, EntityEquipmentSlot.CHEST), new ItemVampireArmor(LibItemName.VAMPIRE_PANTS, ModMaterials.ARMOR_VAMPIRE, 2, EntityEquipmentSlot.LEGS), new ItemColdIronSword(), // new ItemColdIronAxe(), // new ItemColdIronHoe(), // new ItemColdIronPickaxe(), // new ItemColdIronSpade()); // Item Blocks registry.registerAll(// new ItemBlockColor(ModBlocks.candle_medium), // new ItemBlockColor(ModBlocks.candle_small), // new ItemBlockColor(ModBlocks.candle_medium_lit), // new ItemBlockColor(ModBlocks.candle_small_lit), // itemBlock(ModBlocks.fake_ice), // itemBlock(ModBlocks.silver_block), // itemBlock(ModBlocks.silver_ore), // itemBlock(ModBlocks.cauldron), // itemBlock(ModBlocks.oven), // itemBlock(ModBlocks.distillery), // itemBlock(ModBlocks.apiary), // itemBlock(ModBlocks.brazier), // itemBlock(ModBlocks.beehive), // itemBlock(ModBlocks.salt_ore), // itemBlock(ModBlocks.nethersteel), // itemBlock(ModBlocks.log_elder), // itemBlock(ModBlocks.log_juniper), // itemBlock(ModBlocks.log_yew), // itemBlock(ModBlocks.log_cypress), // itemBlock(ModBlocks.leaves_elder), // itemBlock(ModBlocks.leaves_juniper), // itemBlock(ModBlocks.leaves_yew), // itemBlock(ModBlocks.leaves_cypress), // itemBlock(ModBlocks.planks_elder), // itemBlock(ModBlocks.planks_juniper), // itemBlock(ModBlocks.planks_yew), // itemBlock(ModBlocks.planks_cypress), // itemBlock(ModBlocks.purifying_earth), // new ItemBlockSapling(), itemBlock(ModBlocks.moonbell), // itemBlock(ModBlocks.witch_altar), // itemBlock(ModBlocks.thread_spinner), // itemBlock(ModBlocks.crystal_ball), // new ItemGoblet(), // itemBlock(ModBlocks.gem_bowl), // itemBlock(ModBlocks.magic_mirror), // itemBlock(ModBlocks.tarot_table), // itemBlock(ModBlocks.cold_iron_block), // itemBlock(ModBlocks.graveyard_dirt), // new ItemBlockRevealingLantern(ModBlocks.lantern, false), // new ItemBlockRevealingLantern(ModBlocks.revealing_lantern, true)// ); for (Gem g:Gem.values()) { registry.register(g.setGemItem(new ItemMod(g.getGemName()))); registry.register(new ItemGemBlock(g.getGemBlock())); registry.register(new ItemGemOre(g.getOreBlock())); } // Chisel registry.registerAll(// new ItemBlockMeta<>(ModBlocks.silver_block_chisel, BlockSilverChiseled.BlockSilverVariant.values(), EnumNameMode.TOOLTIP), // new ItemBlockMeta<>(ModBlocks.cold_iron_block_chisel, BlockColdIronChiseled.BlockColdIronVariant.values(), EnumNameMode.TOOLTIP), // new ItemBlockMeta<>(ModBlocks.nethersteel_chisel, BlockNetherSteelChiseled.BlockSteelVariant.values(), EnumNameMode.TOOLTIP)); } private static Item itemBlock(Block block) { if (block == null) { throw new LoaderException("[" + LibMod.MOD_NAME + "] Trying to register an ItemBlock for a null block"); } if (block.getRegistryName() == null) { throw new LoaderException("[" + LibMod.MOD_NAME + "] Trying to register an ItemBlock for a block with null name - " + block.getTranslationKey()); } if (block.getRegistryName().toString() == null) { throw new LoaderException("[" + LibMod.MOD_NAME + "] There's something wrong with the registry implementation of " + block.getTranslationKey()); } return new ItemBlockMod(block).setRegistryName(block.getRegistryName()); } public static void init() { initOreDictionary(); } private static void initOreDictionary() { OreDictionary.registerOre("gemGarnet", new ItemStack(ModItems.gem_garnet)); OreDictionary.registerOre("gemTourmaline", new ItemStack(ModItems.gem_tourmaline)); OreDictionary.registerOre("gemTigersEye", new ItemStack(ModItems.gem_tigers_eye)); OreDictionary.registerOre("gemMalachite", new ItemStack(ModItems.gem_malachite)); OreDictionary.registerOre("nuggetSilver", new ItemStack(ModItems.silver_nugget)); OreDictionary.registerOre("ingotSilver", new ItemStack(ModItems.silver_ingot)); OreDictionary.registerOre("honeyDrop", new ItemStack(ModItems.honey)); OreDictionary.registerOre("dropHoney", new ItemStack(ModItems.honey)); OreDictionary.registerOre("foodHoneydrop", new ItemStack(ModItems.honey)); OreDictionary.registerOre("listAllsugar", new ItemStack(ModItems.honey)); OreDictionary.registerOre("materialWax", new ItemStack(ModItems.wax)); OreDictionary.registerOre("materialBeeswax", new ItemStack(ModItems.wax)); OreDictionary.registerOre("materialPressedWax", new ItemStack(ModItems.wax)); OreDictionary.registerOre("itemBeeswax", new ItemStack(ModItems.wax)); OreDictionary.registerOre("foodSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("dustSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("materialSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("lumpSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("salt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("listAllsalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("ingredientSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("pinchSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("portionSalt", new ItemStack(ModItems.salt)); OreDictionary.registerOre("cropBelladonna", new ItemStack(ModItems.belladonna)); OreDictionary.registerOre("cropMandrake", new ItemStack(ModItems.mandrake_root)); OreDictionary.registerOre("cropMint", new ItemStack(ModItems.mint)); OreDictionary.registerOre("listAllspice", new ItemStack(ModItems.mint)); OreDictionary.registerOre("cropSpiceleaf", new ItemStack(ModItems.mint)); OreDictionary.registerOre("listAllgreenveggie", new ItemStack(ModItems.mint)); OreDictionary.registerOre("cropThistle", new ItemStack(ModItems.thistle)); OreDictionary.registerOre("cropGarlic", new ItemStack(ModItems.garlic)); OreDictionary.registerOre("listAllherb", new ItemStack(ModItems.garlic)); OreDictionary.registerOre("cropAconitum", new ItemStack(ModItems.aconitum)); OreDictionary.registerOre("cropWhiteSage", new ItemStack(ModItems.white_sage)); OreDictionary.registerOre("cropTulsi", new ItemStack(ModItems.tulsi)); OreDictionary.registerOre("listAllherb", new ItemStack(ModItems.tulsi)); OreDictionary.registerOre("listAllspice", new ItemStack(ModItems.wormwood)); OreDictionary.registerOre("cropWormwood", new ItemStack(ModItems.wormwood)); OreDictionary.registerOre("ingotColdIron", new ItemStack(ModItems.cold_iron_ingot)); OreDictionary.registerOre("nuggetColdIron", new ItemStack(ModItems.cold_iron_nugget)); } }
24,281
0.76286
0.761748
514
46.2393
25.004652
148
false
false
0
0
0
0
0
0
2.86965
false
false
7
5b0837d5050cb882412a7fce4e6820f958d5e303
21,646,635,225,370
fc0ed028a68177e27adabd746ac4b8f83701327b
/app/src/main/java/com/sc/adapter/ContentAdapter.java
b387cb556ac44580a1c83a3e4473d837864f545c
[]
no_license
suchun00/Demo
https://github.com/suchun00/Demo
890a244a5fd17775a3f707da1b3d82867d48b73c
a67b2b3c3fc04958652dd36efce6ac02dedf2b45
refs/heads/master
2021-01-01T06:30:05.245000
2017-11-20T02:43:37
2017-11-20T02:43:37
97,440,061
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sc.adapter; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.orhanobut.logger.Logger; import com.sc.testdemo.R; import com.sc.utils.DBUtils; import com.sc.utils.Num; import com.sc.utils.ViewHolder; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by suchun on 2017/10/17. */ public class ContentAdapter extends BaseAdapter{ Context con; private List<Map<String, Object>> mdata; public Map<String, Object> etValue = new HashMap<>(); public List<Map<String, Object>> list; private LayoutInflater inflater; int type; DBUtils dbUtils = new DBUtils(); public ContentAdapter(Context context, List<Map<String,Object>> list){ this.con = context; this.list =list; inflater = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getItemViewType(int position){ Map<String, Object> map = list.get(position); return Integer.parseInt(map.get("type").toString()); } @Override public int getCount() { return list.size(); } @Override public Map<String, Object> getItem(int position) { if(position >= getCount()){ return null; } return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder viewHolder = new ViewHolder() ; type = getItemViewType(position); /*if (convertView == null) { //根据数据类型不同生成不同的convertView if(type == 1 || type ==2){ convertView = inflater.inflate(R.layout.item_name, parent, false); // viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); }else{ convertView = inflater.inflate(R.layout.item_type, parent, false); viewHolder.tv = ((TextView) convertView.findViewById(R.id.tv)); viewHolder.spinner = ((Spinner) convertView.findViewById(R.id.spinner)); //viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); } }else{ viewHolder = (ViewHolder) convertView.getTag(); }*/ final Map<String, Object> map = list.get(position); switch (type){ case Num.first: convertView = inflater.inflate(R.layout.item_name, parent, false); viewHolder.tv = ((TextView) convertView.findViewById(R.id.tv)); viewHolder.et = ((EditText) convertView.findViewById(R.id.et)); viewHolder.tv.setText("操作工"); viewHolder.et.setText(map.get("text").toString()); // data.add(position, map.get("text").toString()); break; case Num.second: convertView = inflater.inflate(R.layout.item_name, parent, false); viewHolder.tv = ((TextView) convertView.findViewById(R.id.tv)); viewHolder.et = ((EditText) convertView.findViewById(R.id.et)); viewHolder.tv.setText(map.get("text").toString()); viewHolder.et.setTag(position); try { //viewHolder.et.addTextChangedListener(null); viewHolder.et.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) { } @Override public void afterTextChanged(Editable s) { int position = (Integer) viewHolder.et.getTag(); if (s != null && !"".equals(s.toString())) { //int position = (Integer) viewHolder.et.getTag(); list.get(position).put("value", s.toString()); //etValue.put("inputvalue", s.toString());// 当EditText数据发生改变的时候存到data变量中 Logger.i(s.toString()); //load(); //data.add(position,s.toString()); String staff = funResult(position); //Logger.i(staff); System.out.println("员工姓名=========="+staff); String partloc = ((String) map.get("text")); Logger.i(partloc); dbUtils.updateCount(staff, partloc, s.toString()); } } }); Object value = list.get(position).get("value"); if(value!=null && !"".equals(value)){ viewHolder.et.setText(value.toString()); }else { viewHolder.et.setText(""); } }catch (Exception e){ e.printStackTrace(); } break; case Num.third: convertView = inflater.inflate(R.layout.item_type, parent, false); viewHolder.tv = ((TextView) convertView.findViewById(R.id.tv)); viewHolder.spinner = ((Spinner) convertView.findViewById(R.id.spinner)); viewHolder.tv.setText(map.get("text").toString()); final String staff = funResult(position); Logger.i(staff); final String partloc = ((String) map.get("text")); Logger.i(partloc); ArrayAdapter<CharSequence> adapterDefective = ArrayAdapter.createFromResource(con, R.array.defective, android.R.layout.simple_spinner_item); adapterDefective.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); viewHolder.spinner.setAdapter(adapterDefective); viewHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String result = viewHolder.spinner.getSelectedItem().toString(); Logger.i(result); dbUtils.updateCount(staff, partloc, result); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } return convertView; } public String funResult(int position){ String result = null; int pos=position; for( pos=position; pos>=0; pos-- ){ if(1 == getItemViewType(pos)){ Map<String, Object> map = this.getItem(pos); result = ((String) map.get("text")); break; } } return result; } /* public void load() { int k; data = new ArrayList<>(); //count = new ArrayList<>(); if(list.get(getCount()-1).get("value")!=null && !list.get(getCount()-1).get("value").equals("")){ for (int i = 0; i < list.size(); i++) { int type = ((int) list.get(i).get("type")); if (type == 1) { data.add(((String) list.get(i).get("text"))); } else if (type == 2) { String value = ((String) list.get(i).get("value")); if(value!=null && !value.equals("")){ data.add(value); }else { break; } } } }} if(data.size() == list.size()) { for (int j = 0; j < data.size(); j++) { for (k = j; k < j + 4; k++) { count = new ArrayList<String>(); String str = data.get(k); count.add(str); } dbUtils.insertName(count.get(0), count.get(1), count.get(2), count.get(3)); j = k; } } }*/ }
UTF-8
Java
8,942
java
ContentAdapter.java
Java
[ { "context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by suchun on 2017/10/17.\n */\npublic class ContentAdapter ex", "end": 660, "score": 0.9990930557250977, "start": 654, "tag": "USERNAME", "value": "suchun" } ]
null
[]
package com.sc.adapter; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.orhanobut.logger.Logger; import com.sc.testdemo.R; import com.sc.utils.DBUtils; import com.sc.utils.Num; import com.sc.utils.ViewHolder; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by suchun on 2017/10/17. */ public class ContentAdapter extends BaseAdapter{ Context con; private List<Map<String, Object>> mdata; public Map<String, Object> etValue = new HashMap<>(); public List<Map<String, Object>> list; private LayoutInflater inflater; int type; DBUtils dbUtils = new DBUtils(); public ContentAdapter(Context context, List<Map<String,Object>> list){ this.con = context; this.list =list; inflater = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getItemViewType(int position){ Map<String, Object> map = list.get(position); return Integer.parseInt(map.get("type").toString()); } @Override public int getCount() { return list.size(); } @Override public Map<String, Object> getItem(int position) { if(position >= getCount()){ return null; } return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder viewHolder = new ViewHolder() ; type = getItemViewType(position); /*if (convertView == null) { //根据数据类型不同生成不同的convertView if(type == 1 || type ==2){ convertView = inflater.inflate(R.layout.item_name, parent, false); // viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); }else{ convertView = inflater.inflate(R.layout.item_type, parent, false); viewHolder.tv = ((TextView) convertView.findViewById(R.id.tv)); viewHolder.spinner = ((Spinner) convertView.findViewById(R.id.spinner)); //viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); } }else{ viewHolder = (ViewHolder) convertView.getTag(); }*/ final Map<String, Object> map = list.get(position); switch (type){ case Num.first: convertView = inflater.inflate(R.layout.item_name, parent, false); viewHolder.tv = ((TextView) convertView.findViewById(R.id.tv)); viewHolder.et = ((EditText) convertView.findViewById(R.id.et)); viewHolder.tv.setText("操作工"); viewHolder.et.setText(map.get("text").toString()); // data.add(position, map.get("text").toString()); break; case Num.second: convertView = inflater.inflate(R.layout.item_name, parent, false); viewHolder.tv = ((TextView) convertView.findViewById(R.id.tv)); viewHolder.et = ((EditText) convertView.findViewById(R.id.et)); viewHolder.tv.setText(map.get("text").toString()); viewHolder.et.setTag(position); try { //viewHolder.et.addTextChangedListener(null); viewHolder.et.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) { } @Override public void afterTextChanged(Editable s) { int position = (Integer) viewHolder.et.getTag(); if (s != null && !"".equals(s.toString())) { //int position = (Integer) viewHolder.et.getTag(); list.get(position).put("value", s.toString()); //etValue.put("inputvalue", s.toString());// 当EditText数据发生改变的时候存到data变量中 Logger.i(s.toString()); //load(); //data.add(position,s.toString()); String staff = funResult(position); //Logger.i(staff); System.out.println("员工姓名=========="+staff); String partloc = ((String) map.get("text")); Logger.i(partloc); dbUtils.updateCount(staff, partloc, s.toString()); } } }); Object value = list.get(position).get("value"); if(value!=null && !"".equals(value)){ viewHolder.et.setText(value.toString()); }else { viewHolder.et.setText(""); } }catch (Exception e){ e.printStackTrace(); } break; case Num.third: convertView = inflater.inflate(R.layout.item_type, parent, false); viewHolder.tv = ((TextView) convertView.findViewById(R.id.tv)); viewHolder.spinner = ((Spinner) convertView.findViewById(R.id.spinner)); viewHolder.tv.setText(map.get("text").toString()); final String staff = funResult(position); Logger.i(staff); final String partloc = ((String) map.get("text")); Logger.i(partloc); ArrayAdapter<CharSequence> adapterDefective = ArrayAdapter.createFromResource(con, R.array.defective, android.R.layout.simple_spinner_item); adapterDefective.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); viewHolder.spinner.setAdapter(adapterDefective); viewHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String result = viewHolder.spinner.getSelectedItem().toString(); Logger.i(result); dbUtils.updateCount(staff, partloc, result); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } return convertView; } public String funResult(int position){ String result = null; int pos=position; for( pos=position; pos>=0; pos-- ){ if(1 == getItemViewType(pos)){ Map<String, Object> map = this.getItem(pos); result = ((String) map.get("text")); break; } } return result; } /* public void load() { int k; data = new ArrayList<>(); //count = new ArrayList<>(); if(list.get(getCount()-1).get("value")!=null && !list.get(getCount()-1).get("value").equals("")){ for (int i = 0; i < list.size(); i++) { int type = ((int) list.get(i).get("type")); if (type == 1) { data.add(((String) list.get(i).get("text"))); } else if (type == 2) { String value = ((String) list.get(i).get("value")); if(value!=null && !value.equals("")){ data.add(value); }else { break; } } } }} if(data.size() == list.size()) { for (int j = 0; j < data.size(); j++) { for (k = j; k < j + 4; k++) { count = new ArrayList<String>(); String str = data.get(k); count.add(str); } dbUtils.insertName(count.get(0), count.get(1), count.get(2), count.get(3)); j = k; } } }*/ }
8,942
0.512737
0.510144
223
38.784752
27.452011
105
false
false
0
0
0
0
0
0
0.757848
false
false
7
acff49842860475fe8108c556c3b081b1ac4d63d
1,142,461,337,081
4d488502084622d385ba82e30ccca52c92e9f8e6
/code/src/main/java/com/googlecode/cqengine/index/support/KeyStatisticsIndex.java
a627abdfc11f387ac52fa1619b398d6d29a80448
[ "Apache-2.0" ]
permissive
npgall/cqengine
https://github.com/npgall/cqengine
5c1f7f856c78a5191446095b4ee65aa7bcb92edd
a06923bca69719c51c622543fa0c2d63e71e8fab
refs/heads/master
2023-08-19T20:56:29.004000
2022-12-23T12:33:28
2022-12-23T12:33:28
41,263,775
1,694
282
Apache-2.0
false
2023-07-17T10:00:49
2015-08-23T19:27:00
2023-07-06T16:06:29
2023-04-10T14:21:27
11,503
1,618
240
73
Java
false
false
/** * Copyright 2012-2015 Niall Gallagher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.cqengine.index.support; import com.googlecode.cqengine.index.Index; import com.googlecode.cqengine.query.option.QueryOptions; /** * An index which allows the set of distinct keys to be queried, and which can return statistics on the number of * objects stored in the buckets for each key. * <p/> * Note that this interface reads statistics about keys and NOT about attribute values from the index. * Often those statistics will be the same, however if a {@link com.googlecode.cqengine.quantizer.Quantizer} is * configured for an index, then often objects for several attribute values may have the same key and may be stored * in the same bucket. * * Created by niall.gallagher on 09/01/2015. */ public interface KeyStatisticsIndex<A, O> extends Index<O> { /** * @return The distinct keys in the index * @param queryOptions Optional parameters for the query */ public CloseableIterable<A> getDistinctKeys(QueryOptions queryOptions); /** * @param key A key which may be contained in the index * @param queryOptions Optional parameters for the query * @return The number of objects stored in the bucket in the index with the given key */ public Integer getCountForKey(A key, QueryOptions queryOptions); /** * Returns the count of distinct keys in the index. * * @param queryOptions Optional parameters for the query * @return The count of distinct keys in the index. */ public Integer getCountOfDistinctKeys(QueryOptions queryOptions); /** * Returns the statistics {@link KeyStatistics} for all distinct keys in the index * * @param queryOptions Optional parameters for the query * @return The statistics {@link KeyStatistics} for all distinct keys in the index */ public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeys(QueryOptions queryOptions); /** * Returns the keys and corresponding values for those keys in the index. Note the same key * will be returned multiple times if more than one object has the same key. Also the same value might be returned * multiple times, each time for a different key, if the index is built on a multi-value attribute. * * @return The keys and corresponding values for those keys in the index * * @param queryOptions Optional parameters for the query */ public CloseableIterable<KeyValue<A, O>> getKeysAndValues(QueryOptions queryOptions); }
UTF-8
Java
3,103
java
KeyStatisticsIndex.java
Java
[ { "context": "/**\n * Copyright 2012-2015 Niall Gallagher\n *\n * Licensed under the Apache License, Version ", "end": 42, "score": 0.9998937845230103, "start": 27, "tag": "NAME", "value": "Niall Gallagher" }, { "context": " be stored\n * in the same bucket.\n *\n * Created by niall....
null
[]
/** * Copyright 2012-2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.cqengine.index.support; import com.googlecode.cqengine.index.Index; import com.googlecode.cqengine.query.option.QueryOptions; /** * An index which allows the set of distinct keys to be queried, and which can return statistics on the number of * objects stored in the buckets for each key. * <p/> * Note that this interface reads statistics about keys and NOT about attribute values from the index. * Often those statistics will be the same, however if a {@link com.googlecode.cqengine.quantizer.Quantizer} is * configured for an index, then often objects for several attribute values may have the same key and may be stored * in the same bucket. * * Created by niall.gallagher on 09/01/2015. */ public interface KeyStatisticsIndex<A, O> extends Index<O> { /** * @return The distinct keys in the index * @param queryOptions Optional parameters for the query */ public CloseableIterable<A> getDistinctKeys(QueryOptions queryOptions); /** * @param key A key which may be contained in the index * @param queryOptions Optional parameters for the query * @return The number of objects stored in the bucket in the index with the given key */ public Integer getCountForKey(A key, QueryOptions queryOptions); /** * Returns the count of distinct keys in the index. * * @param queryOptions Optional parameters for the query * @return The count of distinct keys in the index. */ public Integer getCountOfDistinctKeys(QueryOptions queryOptions); /** * Returns the statistics {@link KeyStatistics} for all distinct keys in the index * * @param queryOptions Optional parameters for the query * @return The statistics {@link KeyStatistics} for all distinct keys in the index */ public CloseableIterable<KeyStatistics<A>> getStatisticsForDistinctKeys(QueryOptions queryOptions); /** * Returns the keys and corresponding values for those keys in the index. Note the same key * will be returned multiple times if more than one object has the same key. Also the same value might be returned * multiple times, each time for a different key, if the index is built on a multi-value attribute. * * @return The keys and corresponding values for those keys in the index * * @param queryOptions Optional parameters for the query */ public CloseableIterable<KeyValue<A, O>> getKeysAndValues(QueryOptions queryOptions); }
3,094
0.730261
0.723816
74
40.932434
37.027866
118
false
false
0
0
0
0
0
0
0.283784
false
false
7
7100a2e1105a44635a8a393eacbdb250a2e1ba88
2,087,354,114,636
4a8abdb88ee8d7e9727884f880fa52cdd356356e
/src/main/java/com/ayhuli/web/manage/modules/account/dao/AccountRateUserLogDao.java
392ee039cc15593e0e9050f4dd49d903f7574937
[ "Apache-2.0" ]
permissive
c3h8moon/web-manage
https://github.com/c3h8moon/web-manage
3540159d90d895792dbd1ad86562301b07b07947
9f0382b4aa294d304804d8311fa32ec3cdcfcb47
refs/heads/master
2018-03-30T07:14:51.824000
2017-04-22T11:05:21
2017-04-22T11:05:21
87,880,509
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.ayhuli.web.manage.modules.account.dao; import com.ayhuli.web.manage.common.persistence.CrudDao; import com.ayhuli.web.manage.common.persistence.annotation.MyBatisDao; import com.ayhuli.web.manage.modules.account.entity.AccountRateUserLog; /** * 账户返率日志DAO接口 * @author cy * @version 2017-04-22 */ @MyBatisDao public interface AccountRateUserLogDao extends CrudDao<AccountRateUserLog> { }
UTF-8
Java
432
java
AccountRateUserLogDao.java
Java
[ { "context": "AccountRateUserLog;\n\n/**\n * 账户返率日志DAO接口\n * @author cy\n * @version 2017-04-22\n */\n@MyBatisDao\npublic int", "end": 296, "score": 0.9981058835983276, "start": 294, "tag": "USERNAME", "value": "cy" } ]
null
[]
/** * */ package com.ayhuli.web.manage.modules.account.dao; import com.ayhuli.web.manage.common.persistence.CrudDao; import com.ayhuli.web.manage.common.persistence.annotation.MyBatisDao; import com.ayhuli.web.manage.modules.account.entity.AccountRateUserLog; /** * 账户返率日志DAO接口 * @author cy * @version 2017-04-22 */ @MyBatisDao public interface AccountRateUserLogDao extends CrudDao<AccountRateUserLog> { }
432
0.78125
0.762019
18
22.166666
27.406914
76
false
false
0
0
0
0
0
0
0.277778
false
false
7
e23266484a2e3762bfd927e4dfc8e6414f72c16b
15,977,278,377,943
f0332dd41c7ce6a97ea987f832713a55b90121a5
/src/main/java/com/hxy/nzxy/stexam/system/domain/KnowledgeDO.java
3b4ae9014b624d5cb59d3293ed3ec5bcd064a76f
[]
no_license
tanghui11/workings
https://github.com/tanghui11/workings
ec363b972427b871f42cabdbe5e2fd3ed22ea2f8
cb7ad7c7c27a1636a6cbfaff3904581f7b1e8ef8
refs/heads/master
2022-01-23T09:46:59.060000
2019-08-27T08:33:55
2019-08-27T08:33:55
180,955,439
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hxy.nzxy.stexam.system.domain; import java.io.Serializable; import java.util.Date; /** * 考试知识 * * @author dragon * @email 330504176@qq.com * @date 2018-01-03 09:25:05 */ public class KnowledgeDO implements Serializable { private static final long serialVersionUID = 1L; //编号 private String id; //名称 private String name; //拼音 private String pinyin; //版本 private String version; //学段 private String gradeType; //科目编号 private String subjectid; //描述 private String intro; //发布状态 private String status; //操作员 private String operator; //操作日期 private String updateDate; /** * 设置:编号 */ public void setId(String id) { this.id = id; } /** * 获取:编号 */ public String getId() { return id; } /** * 设置:名称 */ public void setName(String name) { this.name = name; } /** * 获取:名称 */ public String getName() { return name; } /** * 设置:拼音 */ public void setPinyin(String pinyin) { this.pinyin = pinyin; } /** * 获取:拼音 */ public String getPinyin() { return pinyin; } /** * 设置:版本 */ public void setVersion(String version) { this.version = version; } /** * 获取:版本 */ public String getVersion() { return version; } /** * 设置:学段 */ public void setGradeType(String gradeType) { this.gradeType = gradeType; } /** * 获取:学段 */ public String getGradeType() { return gradeType; } /** * 设置:科目编号 */ public void setSubjectid(String subjectid) { this.subjectid = subjectid; } /** * 获取:科目编号 */ public String getSubjectid() { return subjectid; } /** * 设置:描述 */ public void setIntro(String intro) { this.intro = intro; } /** * 获取:描述 */ public String getIntro() { return intro; } /** * 设置:发布状态 */ public void setStatus(String status) { this.status = status; } /** * 获取:发布状态 */ public String getStatus() { return status; } /** * 设置:操作员 */ public void setOperator(String operator) { this.operator = operator; } /** * 获取:操作员 */ public String getOperator() { return operator; } /** * 设置:操作日期 */ public void setUpdateDate(String updateDate) { this.updateDate = updateDate; } /** * 获取:操作日期 */ public String getUpdateDate() { return updateDate; } }
UTF-8
Java
2,512
java
KnowledgeDO.java
Java
[ { "context": "port java.util.Date;\n\n\n\n/**\n * 考试知识\n * \n * @author dragon\n * @email 330504176@qq.com\n * @date 2018-01-03 09", "end": 132, "score": 0.8688062429428101, "start": 126, "tag": "USERNAME", "value": "dragon" }, { "context": "e;\n\n\n\n/**\n * 考试知识\n * \n * @author dr...
null
[]
package com.hxy.nzxy.stexam.system.domain; import java.io.Serializable; import java.util.Date; /** * 考试知识 * * @author dragon * @email <EMAIL> * @date 2018-01-03 09:25:05 */ public class KnowledgeDO implements Serializable { private static final long serialVersionUID = 1L; //编号 private String id; //名称 private String name; //拼音 private String pinyin; //版本 private String version; //学段 private String gradeType; //科目编号 private String subjectid; //描述 private String intro; //发布状态 private String status; //操作员 private String operator; //操作日期 private String updateDate; /** * 设置:编号 */ public void setId(String id) { this.id = id; } /** * 获取:编号 */ public String getId() { return id; } /** * 设置:名称 */ public void setName(String name) { this.name = name; } /** * 获取:名称 */ public String getName() { return name; } /** * 设置:拼音 */ public void setPinyin(String pinyin) { this.pinyin = pinyin; } /** * 获取:拼音 */ public String getPinyin() { return pinyin; } /** * 设置:版本 */ public void setVersion(String version) { this.version = version; } /** * 获取:版本 */ public String getVersion() { return version; } /** * 设置:学段 */ public void setGradeType(String gradeType) { this.gradeType = gradeType; } /** * 获取:学段 */ public String getGradeType() { return gradeType; } /** * 设置:科目编号 */ public void setSubjectid(String subjectid) { this.subjectid = subjectid; } /** * 获取:科目编号 */ public String getSubjectid() { return subjectid; } /** * 设置:描述 */ public void setIntro(String intro) { this.intro = intro; } /** * 获取:描述 */ public String getIntro() { return intro; } /** * 设置:发布状态 */ public void setStatus(String status) { this.status = status; } /** * 获取:发布状态 */ public String getStatus() { return status; } /** * 设置:操作员 */ public void setOperator(String operator) { this.operator = operator; } /** * 获取:操作员 */ public String getOperator() { return operator; } /** * 设置:操作日期 */ public void setUpdateDate(String updateDate) { this.updateDate = updateDate; } /** * 获取:操作日期 */ public String getUpdateDate() { return updateDate; } }
2,503
0.615212
0.60441
159
12.974843
12.56077
50
false
false
0
0
0
0
0
0
1.232704
false
false
7
9132afad169c5a3444a5a8b3b68fd465a1153a51
2,731,599,235,380
049d3148251dc48dfc2eb746a6a5b14295c0ee75
/src/main/java/uit/se06/scholarshipweb/model/ScholarshipType.java
38f2d005801035ed73e30ef5b91ece0482520930
[]
no_license
HueHaTran/ScholarshipWeb
https://github.com/HueHaTran/ScholarshipWeb
6b68ad8d21b5c6577b9643d18e520d96f48d91de
561c36bd0d15431374c0a1d16b15561df7bda987
refs/heads/master
2018-12-29T23:50:14.295000
2015-07-02T15:28:47
2015-07-02T15:28:47
35,366,144
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uit.se06.scholarshipweb.model; import static javax.persistence.GenerationType.IDENTITY; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.hibernate.search.annotations.Analyze; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.Store; @Entity @Table(name = "scholarship_type", catalog = "scholarshipdatabase", uniqueConstraints = { @UniqueConstraint(columnNames = "scholarship_type_name"), }) // index exception class @Indexed public class ScholarshipType implements ISimpleModel { // ============================================================ // PROPERTIES // ============================================================ @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "scholarship_type_id", unique = true, nullable = false) private int scholarshipTypeId; @Column(name = "scholarship_type_name", unique = true, nullable = false) @Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES) private String scholarshipTypeName; @OneToMany(fetch = FetchType.LAZY, mappedBy = "scholarshipType") private Set<ScholarshipSpecification> scholarships; // ============================================================ // CONSTRUCTORS // ============================================================ public ScholarshipType() { } public ScholarshipType(int scholarshipTypeId, String scholarshipTypeName) { setId(scholarshipTypeId); setName(scholarshipTypeName); } // ============================================================ // GETTERS & SETTERS // ============================================================ public int getId() { return scholarshipTypeId; } public void setId(int scholarshipTypeId) { this.scholarshipTypeId = scholarshipTypeId; } public String getName() { return scholarshipTypeName; } public void setName(String scholarshipTypeName) { this.scholarshipTypeName = scholarshipTypeName; } public Set<ScholarshipSpecification> getScholarships() { return scholarships; } public void setScholarships(Set<ScholarshipSpecification> scholarships) { this.scholarships = scholarships; } }
UTF-8
Java
2,559
java
ScholarshipType.java
Java
[]
null
[]
package uit.se06.scholarshipweb.model; import static javax.persistence.GenerationType.IDENTITY; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.hibernate.search.annotations.Analyze; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.Store; @Entity @Table(name = "scholarship_type", catalog = "scholarshipdatabase", uniqueConstraints = { @UniqueConstraint(columnNames = "scholarship_type_name"), }) // index exception class @Indexed public class ScholarshipType implements ISimpleModel { // ============================================================ // PROPERTIES // ============================================================ @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "scholarship_type_id", unique = true, nullable = false) private int scholarshipTypeId; @Column(name = "scholarship_type_name", unique = true, nullable = false) @Field(index = Index.YES, analyze = Analyze.NO, store = Store.YES) private String scholarshipTypeName; @OneToMany(fetch = FetchType.LAZY, mappedBy = "scholarshipType") private Set<ScholarshipSpecification> scholarships; // ============================================================ // CONSTRUCTORS // ============================================================ public ScholarshipType() { } public ScholarshipType(int scholarshipTypeId, String scholarshipTypeName) { setId(scholarshipTypeId); setName(scholarshipTypeName); } // ============================================================ // GETTERS & SETTERS // ============================================================ public int getId() { return scholarshipTypeId; } public void setId(int scholarshipTypeId) { this.scholarshipTypeId = scholarshipTypeId; } public String getName() { return scholarshipTypeName; } public void setName(String scholarshipTypeName) { this.scholarshipTypeName = scholarshipTypeName; } public Set<ScholarshipSpecification> getScholarships() { return scholarships; } public void setScholarships(Set<ScholarshipSpecification> scholarships) { this.scholarships = scholarships; } }
2,559
0.642048
0.641266
83
28.831326
27.642214
149
false
false
0
0
0
0
0
0
1.060241
false
false
7
f156683ebfa2605ce4b6233c771ef3785e9df58d
9,191,230,068,711
69eedf2f3e4eb57cd83504b45522c1eed1d8c33d
/org.promasi.server/src/org/promasi/server/clientstate/ChooseGameClientState.java
53072cd3df7e2848538c6b61614fe9ce9118ee3e
[]
no_license
eddiefullmetal/Promasi-V2
https://github.com/eddiefullmetal/Promasi-V2
dc2c4b4d689f9a8d688833fbd8a1e6587921ae75
aac373cbaeeae93f0b600539a1361049dc550285
refs/heads/master
2020-12-25T09:00:43.839000
2011-05-11T19:44:46
2011-05-11T19:44:46
2,239,481
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package org.promasi.server.clientstate; import java.beans.XMLDecoder; import java.io.ByteArrayInputStream; import java.util.LinkedList; import java.util.Queue; import org.promasi.game.SerializableGameModel; import org.promasi.game.company.SerializableCompany; import org.promasi.game.company.SerializableMarketPlace; import org.promasi.game.multiplayer.MultiPlayerGame; import org.promasi.game.project.Project; import org.promasi.game.project.SerializableProject; import org.promasi.protocol.messages.CreateGameFailedResponse; import org.promasi.protocol.messages.CreateGameRequest; import org.promasi.protocol.messages.CreateGameResponse; import org.promasi.protocol.messages.InternalErrorResponse; import org.promasi.protocol.messages.JoinGameFailedResponse; import org.promasi.protocol.messages.JoinGameRequest; import org.promasi.protocol.messages.JoinGameResponse; import org.promasi.protocol.messages.UpdateAvailableGameListRequest; import org.promasi.protocol.messages.UpdateGameListRequest; import org.promasi.protocol.messages.WrongProtocolResponse; import org.promasi.server.AbstractClientState; import org.promasi.server.ProMaSiClient; import org.promasi.server.ProMaSiServer; import org.promasi.utilities.exceptions.NullArgumentException; import org.promasi.utilities.serialization.SerializationException; /** * @author m1cRo * */ public class ChooseGameClientState extends AbstractClientState { /** * */ private ProMaSiServer _server; /** * */ private String _clientId; /** * * @param server * @throws NullArgumentException */ public ChooseGameClientState(ProMaSiServer server, String clientId)throws NullArgumentException{ if(server==null){ throw new NullArgumentException("Wrong argument server==null"); } if(clientId==null){ throw new NullArgumentException("Wrong argument clientId==null"); } _clientId=clientId; _server=server; } /* (non-Javadoc) * @see org.promasi.playmode.multiplayer.IClientState#onReceive(org.promasi.playmode.multiplayer.ProMaSiClient, java.lang.String) */ @Override public void onReceive(ProMaSiClient client, String recData) { try{ Object object=new XMLDecoder(new ByteArrayInputStream(recData.getBytes())).readObject(); if(object instanceof JoinGameRequest){ try{ JoinGameRequest request=(JoinGameRequest)object; MultiPlayerGame game=_server.joinGame(_clientId, request.getGameId()); JoinGameResponse response=new JoinGameResponse(game.getGameName(), game.getGameDescription(), game.getGamePlayers()); changeClientState(client, new WaitingGameClientState(_clientId,_server, client,request.getGameId(), game)); client.sendMessage(response.serialize()); }catch(IllegalArgumentException e){ client.sendMessage(new JoinGameFailedResponse().serialize()); } }else if(object instanceof CreateGameRequest){ CreateGameRequest request=(CreateGameRequest)object; SerializableGameModel gameModel=request.getGameModel(); if(gameModel==null){ client.sendMessage(new WrongProtocolResponse().serialize()); client.disconnect(); return; } SerializableMarketPlace marketPlace=gameModel.getMarketPlace(); if(marketPlace==null){ client.sendMessage(new WrongProtocolResponse().serialize()); client.disconnect(); } SerializableCompany company=gameModel.getCompany(); if(company==null){ client.sendMessage(new WrongProtocolResponse().serialize()); client.disconnect(); } Queue<SerializableProject> sProjects=gameModel.getProjects(); if(sProjects==null){ client.sendMessage(new WrongProtocolResponse().serialize()); client.disconnect(); } Queue<Project> projects=new LinkedList<Project>(); for(SerializableProject currentProject : sProjects){ projects.add(currentProject.getProject()); } MultiPlayerGame game=new MultiPlayerGame( _clientId, request.getGameId() , gameModel.getGameDescription() , marketPlace.getMarketPlace() , company.getCompany() , projects); if(_server.createGame(request.getGameId(), game)) { CreateGameResponse response=new CreateGameResponse(request.getGameId(), gameModel.getGameDescription(), game.getGamePlayers()); client.sendMessage(response.serialize()); changeClientState( client, new WaitingPlayersClientState(_clientId, request.getGameId(), client, game, _server) ); }else{ client.sendMessage(new CreateGameFailedResponse().serialize()); } }else if(object instanceof UpdateAvailableGameListRequest){ UpdateGameListRequest request=new UpdateGameListRequest(_server.getAvailableGames()); client.sendMessage(request.serialize()); }else{ client.sendMessage(new WrongProtocolResponse().serialize()); client.disconnect(); } }catch(NullArgumentException e){ client.sendMessage(new InternalErrorResponse().serialize()); client.disconnect(); }catch(IllegalArgumentException e){ client.sendMessage(new InternalErrorResponse().serialize()); client.disconnect(); }catch(SerializationException e){ client.sendMessage(new InternalErrorResponse().serialize()); client.disconnect(); } } @Override public void onSetState(ProMaSiClient client) { // TODO Auto-generated method stub } @Override public void onDisconnect(ProMaSiClient client) { // TODO Auto-generated method stub } @Override public void onConnect(ProMaSiClient client) { // TODO Auto-generated method stub } @Override public void onConnectionError(ProMaSiClient client) { // TODO Auto-generated method stub } }
UTF-8
Java
5,848
java
ChooseGameClientState.java
Java
[ { "context": "ization.SerializationException;\r\n\r\n/**\r\n * @author m1cRo\r\n *\r\n */\r\npublic class ChooseGameClientState exte", "end": 1386, "score": 0.9996273517608643, "start": 1381, "tag": "USERNAME", "value": "m1cRo" } ]
null
[]
/** * */ package org.promasi.server.clientstate; import java.beans.XMLDecoder; import java.io.ByteArrayInputStream; import java.util.LinkedList; import java.util.Queue; import org.promasi.game.SerializableGameModel; import org.promasi.game.company.SerializableCompany; import org.promasi.game.company.SerializableMarketPlace; import org.promasi.game.multiplayer.MultiPlayerGame; import org.promasi.game.project.Project; import org.promasi.game.project.SerializableProject; import org.promasi.protocol.messages.CreateGameFailedResponse; import org.promasi.protocol.messages.CreateGameRequest; import org.promasi.protocol.messages.CreateGameResponse; import org.promasi.protocol.messages.InternalErrorResponse; import org.promasi.protocol.messages.JoinGameFailedResponse; import org.promasi.protocol.messages.JoinGameRequest; import org.promasi.protocol.messages.JoinGameResponse; import org.promasi.protocol.messages.UpdateAvailableGameListRequest; import org.promasi.protocol.messages.UpdateGameListRequest; import org.promasi.protocol.messages.WrongProtocolResponse; import org.promasi.server.AbstractClientState; import org.promasi.server.ProMaSiClient; import org.promasi.server.ProMaSiServer; import org.promasi.utilities.exceptions.NullArgumentException; import org.promasi.utilities.serialization.SerializationException; /** * @author m1cRo * */ public class ChooseGameClientState extends AbstractClientState { /** * */ private ProMaSiServer _server; /** * */ private String _clientId; /** * * @param server * @throws NullArgumentException */ public ChooseGameClientState(ProMaSiServer server, String clientId)throws NullArgumentException{ if(server==null){ throw new NullArgumentException("Wrong argument server==null"); } if(clientId==null){ throw new NullArgumentException("Wrong argument clientId==null"); } _clientId=clientId; _server=server; } /* (non-Javadoc) * @see org.promasi.playmode.multiplayer.IClientState#onReceive(org.promasi.playmode.multiplayer.ProMaSiClient, java.lang.String) */ @Override public void onReceive(ProMaSiClient client, String recData) { try{ Object object=new XMLDecoder(new ByteArrayInputStream(recData.getBytes())).readObject(); if(object instanceof JoinGameRequest){ try{ JoinGameRequest request=(JoinGameRequest)object; MultiPlayerGame game=_server.joinGame(_clientId, request.getGameId()); JoinGameResponse response=new JoinGameResponse(game.getGameName(), game.getGameDescription(), game.getGamePlayers()); changeClientState(client, new WaitingGameClientState(_clientId,_server, client,request.getGameId(), game)); client.sendMessage(response.serialize()); }catch(IllegalArgumentException e){ client.sendMessage(new JoinGameFailedResponse().serialize()); } }else if(object instanceof CreateGameRequest){ CreateGameRequest request=(CreateGameRequest)object; SerializableGameModel gameModel=request.getGameModel(); if(gameModel==null){ client.sendMessage(new WrongProtocolResponse().serialize()); client.disconnect(); return; } SerializableMarketPlace marketPlace=gameModel.getMarketPlace(); if(marketPlace==null){ client.sendMessage(new WrongProtocolResponse().serialize()); client.disconnect(); } SerializableCompany company=gameModel.getCompany(); if(company==null){ client.sendMessage(new WrongProtocolResponse().serialize()); client.disconnect(); } Queue<SerializableProject> sProjects=gameModel.getProjects(); if(sProjects==null){ client.sendMessage(new WrongProtocolResponse().serialize()); client.disconnect(); } Queue<Project> projects=new LinkedList<Project>(); for(SerializableProject currentProject : sProjects){ projects.add(currentProject.getProject()); } MultiPlayerGame game=new MultiPlayerGame( _clientId, request.getGameId() , gameModel.getGameDescription() , marketPlace.getMarketPlace() , company.getCompany() , projects); if(_server.createGame(request.getGameId(), game)) { CreateGameResponse response=new CreateGameResponse(request.getGameId(), gameModel.getGameDescription(), game.getGamePlayers()); client.sendMessage(response.serialize()); changeClientState( client, new WaitingPlayersClientState(_clientId, request.getGameId(), client, game, _server) ); }else{ client.sendMessage(new CreateGameFailedResponse().serialize()); } }else if(object instanceof UpdateAvailableGameListRequest){ UpdateGameListRequest request=new UpdateGameListRequest(_server.getAvailableGames()); client.sendMessage(request.serialize()); }else{ client.sendMessage(new WrongProtocolResponse().serialize()); client.disconnect(); } }catch(NullArgumentException e){ client.sendMessage(new InternalErrorResponse().serialize()); client.disconnect(); }catch(IllegalArgumentException e){ client.sendMessage(new InternalErrorResponse().serialize()); client.disconnect(); }catch(SerializationException e){ client.sendMessage(new InternalErrorResponse().serialize()); client.disconnect(); } } @Override public void onSetState(ProMaSiClient client) { // TODO Auto-generated method stub } @Override public void onDisconnect(ProMaSiClient client) { // TODO Auto-generated method stub } @Override public void onConnect(ProMaSiClient client) { // TODO Auto-generated method stub } @Override public void onConnectionError(ProMaSiClient client) { // TODO Auto-generated method stub } }
5,848
0.729138
0.728967
174
31.609196
29.549629
132
false
false
0
0
0
0
0
0
2.936782
false
false
7
2796baec255411fe2e34f57377ae6959d9333949
24,979,529,846,920
c38c37b89489808077c7a5adefa764219170aea3
/evacuation-simulation/src/main/java/edu/utdallas/mavs/evacuation/simulation/sim/agent/knowledge/external/EnvObjectKnowledgeStorageObject.java
86f0e0fcaa9abed4f7ecb5638d4ddd7b34e815f0
[]
no_license
pragati99/DIVAS5
https://github.com/pragati99/DIVAS5
35a568af1a9c56a6c883cd076d3ad789dcf47107
714ba37c122e478e0494979ab7e08c16e50a5284
refs/heads/master
2021-08-11T19:32:27.038000
2017-11-14T03:32:03
2017-11-14T03:32:03
110,481,811
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.utdallas.mavs.evacuation.simulation.sim.agent.knowledge.external; import java.util.ArrayList; import java.util.List; import com.jme3.math.Vector3f; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import edu.utdallas.mavs.divas.core.sim.common.state.EnvObjectState; import edu.utdallas.mavs.evacuation.simulation.sim.agent.planning.PathFindingNode; import edu.utdallas.mavs.evacuation.simulation.sim.common.state.DoorObjectState; /** * Store critial information about environment objects */ public class EnvObjectKnowledgeStorageObject extends VirtualKnowledgeStorageObject { private static final long serialVersionUID = 1L; /** * The EnvObj's description */ protected String description = ""; /** * The EnvObj's Type */ protected String type = ""; protected boolean isOpen = true; /** * Create an KSO from an environment object State * * @param envObj * the env object state */ public EnvObjectKnowledgeStorageObject(EnvObjectState envObj) { super(envObj.getID(), envObj.getScale(), envObj.getPosition(), envObj.isCollidable(), envObj.getBoundingArea()); this.description = envObj.getDescription(); this.type = envObj.getType(); if(envObj instanceof DoorObjectState) { this.isOpen = ((DoorObjectState) envObj).isOpen(); } } public boolean updateValues(EnvObjectState envObj) { boolean changed = false; if(!this.scale.equals(envObj.getScale())) { this.scale = envObj.getScale(); changed = true; } if(!this.position.equals(envObj.getPosition())) { this.position = envObj.getPosition(); changed = true; } if(this.isCollidable != envObj.isCollidable()) { this.isCollidable = envObj.isCollidable(); changed = true; } if(!this.boundingArea.equals(envObj.getBoundingArea())) { this.boundingArea = envObj.getBoundingArea(); changed = true; } if(envObj instanceof DoorObjectState && this.isOpen != ((DoorObjectState) envObj).isOpen()) { this.isOpen = ((DoorObjectState) envObj).isOpen(); changed = true; } return changed; } /** * Get the KSO's description * * @return the description */ public String getDescription() { return description; } /** * Set the KSO's description * * @param description * the description */ public void setDescription(String description) { this.description = description; } /** * Get the KSO's type * * @return the type */ public String getType() { return type; } /** * Set the KSO's type * * @param type * the type */ public void setType(String type) { this.type = type; } /** * Calculate the four corner points of an env object. * * @param points * passed in empty ponts reference * @param space * space away from object to buffer space with * @return the points list filled */ public List<Vector3f> calcPoints(float space) { List<Vector3f> points = new ArrayList<Vector3f>(); points.add(new Vector3f((position.x - (scale.x + space)), 0, (position.z - (scale.z + space)))); points.add(new Vector3f((position.x - (scale.x + space)), 0, (position.z + (scale.z + space)))); points.add(new Vector3f((position.x + (scale.x + space)), 0, (position.z - (scale.z + space)))); points.add(new Vector3f((position.x + (scale.x + space)), 0, (position.z + (scale.z + space)))); points.add(position); return points; } /** * Calculate the four corner points of an env object. * * @param points * passed in empty ponts reference * @param space * space away from object to buffer space with * @param agentSize * @return the points list filled */ public List<PathFindingNode> calcNodesNoCenter(float space, float agentSize) { List<PathFindingNode> points = new ArrayList<PathFindingNode>(); points.add(new PathFindingNode(agentSize, new Vector3f((position.x - (scale.x + space)), 0, (position.z - (scale.z + space))), id)); points.add(new PathFindingNode(agentSize, new Vector3f((position.x - (scale.x + space)), 0, (position.z + (scale.z + space))), id)); points.add(new PathFindingNode(agentSize, new Vector3f((position.x + (scale.x + space)), 0, (position.z - (scale.z + space))), id)); points.add(new PathFindingNode(agentSize, new Vector3f((position.x + (scale.x + space)), 0, (position.z + (scale.z + space))), id)); return points; } /** * Calculate the nodes of a door. * @param space * @param agentSize * * @return the points list filled */ public List<PathFindingNode> calcNodesForDoor(float space, float agentSize) { List<PathFindingNode> points = new ArrayList<PathFindingNode>(); points.add(new PathFindingNode(agentSize, new Vector3f((position.x - (scale.x + space)), 0, position.z), id)); points.add(new PathFindingNode(agentSize, new Vector3f((position.x + (scale.x + space)), 0, position.z), id)); points.add(new PathFindingNode(agentSize, new Vector3f(position.x, 0, (position.z - (scale.z + space))), id)); points.add(new PathFindingNode(agentSize, new Vector3f(position.x, 0, (position.z + (scale.z + space))), id)); return points; } /** * Checks if this object is in between two points * * @param startPoint * start point * @param endPoint * end point * @param space * space away from object to buffer space with * @return true if object is in between. Otherwise, false. */ public boolean isInBetween(Vector3f startPoint, Vector3f endPoint, float space) { List<Vector3f> points = calcPoints(space); for(Vector3f point : points) { if(((point.x > startPoint.x) && (point.x < endPoint.x)) || ((point.x < startPoint.x) && (point.x > endPoint.x))) { return true; } else if(((point.z > startPoint.z) && (point.z < endPoint.z)) || ((point.z < startPoint.z) && (point.z > endPoint.z))) { return true; } } return false; } public boolean agentPathIntersectsObj2D(Vector3f agentPosition, Vector3f goalPoint, float agentSize) { if(intersects2DLine(goalPoint.add(1, 0, 1), agentPosition.add(1, 0, 1))) { return true; } if(intersects2DLine(goalPoint.add(-1, 0, 1), agentPosition.add(-1, 0, 1))) { return true; } if(intersects2DLine(goalPoint.add(1, 0, -1), agentPosition.add(1, 0, -1))) { return true; } if(intersects2DLine(goalPoint.add(-1, 0, -1), agentPosition.add(-1, 0, -1))) { return true; } if(intersects2DLine(goalPoint, agentPosition)) { return true; } // Vector3f agentHeading = goalPoint.subtract(agentPosition); // agentHeading.normalizeLocal(); // if(intersects2DLine(goalPoint, agentPosition)) // { // return true; // } // Vector3f headingNorm = new Vector3f(agentHeading.z, 0, -agentHeading.x); // headingNorm.multLocal(agentSize); // if(intersects2DLine(goalPoint.add(headingNorm).add(agentHeading), agentPosition.add(headingNorm).subtract(agentHeading))) // { // return true; // } // headingNorm = new Vector3f(-agentHeading.z, 0, agentHeading.x); // headingNorm.multLocal(agentSize); // if(intersects2DLine(goalPoint.add(headingNorm).add(agentHeading), agentPosition.add(headingNorm).subtract(agentHeading))) // { // return true; // } return false; } public boolean isOpen() { return isOpen; } public void setOpen(boolean isOpen) { this.isOpen = isOpen; } /** * Checks if its mini bounding area intersects the line determined by the given start and end points * * @param endPoint * end point of the line * @param startPoint * start point of the line * @return true if it intersects. Otherwise, false. */ public boolean miniBAIntersects2DLine(Vector3f endPoint, Vector3f startPoint) { return boundingArea.intersects(new GeometryFactory().createLineString(new Coordinate[] {new Coordinate(endPoint.x, endPoint.z), new Coordinate(startPoint.x, startPoint.z)})); } }
UTF-8
Java
9,136
java
EnvObjectKnowledgeStorageObject.java
Java
[]
null
[]
package edu.utdallas.mavs.evacuation.simulation.sim.agent.knowledge.external; import java.util.ArrayList; import java.util.List; import com.jme3.math.Vector3f; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import edu.utdallas.mavs.divas.core.sim.common.state.EnvObjectState; import edu.utdallas.mavs.evacuation.simulation.sim.agent.planning.PathFindingNode; import edu.utdallas.mavs.evacuation.simulation.sim.common.state.DoorObjectState; /** * Store critial information about environment objects */ public class EnvObjectKnowledgeStorageObject extends VirtualKnowledgeStorageObject { private static final long serialVersionUID = 1L; /** * The EnvObj's description */ protected String description = ""; /** * The EnvObj's Type */ protected String type = ""; protected boolean isOpen = true; /** * Create an KSO from an environment object State * * @param envObj * the env object state */ public EnvObjectKnowledgeStorageObject(EnvObjectState envObj) { super(envObj.getID(), envObj.getScale(), envObj.getPosition(), envObj.isCollidable(), envObj.getBoundingArea()); this.description = envObj.getDescription(); this.type = envObj.getType(); if(envObj instanceof DoorObjectState) { this.isOpen = ((DoorObjectState) envObj).isOpen(); } } public boolean updateValues(EnvObjectState envObj) { boolean changed = false; if(!this.scale.equals(envObj.getScale())) { this.scale = envObj.getScale(); changed = true; } if(!this.position.equals(envObj.getPosition())) { this.position = envObj.getPosition(); changed = true; } if(this.isCollidable != envObj.isCollidable()) { this.isCollidable = envObj.isCollidable(); changed = true; } if(!this.boundingArea.equals(envObj.getBoundingArea())) { this.boundingArea = envObj.getBoundingArea(); changed = true; } if(envObj instanceof DoorObjectState && this.isOpen != ((DoorObjectState) envObj).isOpen()) { this.isOpen = ((DoorObjectState) envObj).isOpen(); changed = true; } return changed; } /** * Get the KSO's description * * @return the description */ public String getDescription() { return description; } /** * Set the KSO's description * * @param description * the description */ public void setDescription(String description) { this.description = description; } /** * Get the KSO's type * * @return the type */ public String getType() { return type; } /** * Set the KSO's type * * @param type * the type */ public void setType(String type) { this.type = type; } /** * Calculate the four corner points of an env object. * * @param points * passed in empty ponts reference * @param space * space away from object to buffer space with * @return the points list filled */ public List<Vector3f> calcPoints(float space) { List<Vector3f> points = new ArrayList<Vector3f>(); points.add(new Vector3f((position.x - (scale.x + space)), 0, (position.z - (scale.z + space)))); points.add(new Vector3f((position.x - (scale.x + space)), 0, (position.z + (scale.z + space)))); points.add(new Vector3f((position.x + (scale.x + space)), 0, (position.z - (scale.z + space)))); points.add(new Vector3f((position.x + (scale.x + space)), 0, (position.z + (scale.z + space)))); points.add(position); return points; } /** * Calculate the four corner points of an env object. * * @param points * passed in empty ponts reference * @param space * space away from object to buffer space with * @param agentSize * @return the points list filled */ public List<PathFindingNode> calcNodesNoCenter(float space, float agentSize) { List<PathFindingNode> points = new ArrayList<PathFindingNode>(); points.add(new PathFindingNode(agentSize, new Vector3f((position.x - (scale.x + space)), 0, (position.z - (scale.z + space))), id)); points.add(new PathFindingNode(agentSize, new Vector3f((position.x - (scale.x + space)), 0, (position.z + (scale.z + space))), id)); points.add(new PathFindingNode(agentSize, new Vector3f((position.x + (scale.x + space)), 0, (position.z - (scale.z + space))), id)); points.add(new PathFindingNode(agentSize, new Vector3f((position.x + (scale.x + space)), 0, (position.z + (scale.z + space))), id)); return points; } /** * Calculate the nodes of a door. * @param space * @param agentSize * * @return the points list filled */ public List<PathFindingNode> calcNodesForDoor(float space, float agentSize) { List<PathFindingNode> points = new ArrayList<PathFindingNode>(); points.add(new PathFindingNode(agentSize, new Vector3f((position.x - (scale.x + space)), 0, position.z), id)); points.add(new PathFindingNode(agentSize, new Vector3f((position.x + (scale.x + space)), 0, position.z), id)); points.add(new PathFindingNode(agentSize, new Vector3f(position.x, 0, (position.z - (scale.z + space))), id)); points.add(new PathFindingNode(agentSize, new Vector3f(position.x, 0, (position.z + (scale.z + space))), id)); return points; } /** * Checks if this object is in between two points * * @param startPoint * start point * @param endPoint * end point * @param space * space away from object to buffer space with * @return true if object is in between. Otherwise, false. */ public boolean isInBetween(Vector3f startPoint, Vector3f endPoint, float space) { List<Vector3f> points = calcPoints(space); for(Vector3f point : points) { if(((point.x > startPoint.x) && (point.x < endPoint.x)) || ((point.x < startPoint.x) && (point.x > endPoint.x))) { return true; } else if(((point.z > startPoint.z) && (point.z < endPoint.z)) || ((point.z < startPoint.z) && (point.z > endPoint.z))) { return true; } } return false; } public boolean agentPathIntersectsObj2D(Vector3f agentPosition, Vector3f goalPoint, float agentSize) { if(intersects2DLine(goalPoint.add(1, 0, 1), agentPosition.add(1, 0, 1))) { return true; } if(intersects2DLine(goalPoint.add(-1, 0, 1), agentPosition.add(-1, 0, 1))) { return true; } if(intersects2DLine(goalPoint.add(1, 0, -1), agentPosition.add(1, 0, -1))) { return true; } if(intersects2DLine(goalPoint.add(-1, 0, -1), agentPosition.add(-1, 0, -1))) { return true; } if(intersects2DLine(goalPoint, agentPosition)) { return true; } // Vector3f agentHeading = goalPoint.subtract(agentPosition); // agentHeading.normalizeLocal(); // if(intersects2DLine(goalPoint, agentPosition)) // { // return true; // } // Vector3f headingNorm = new Vector3f(agentHeading.z, 0, -agentHeading.x); // headingNorm.multLocal(agentSize); // if(intersects2DLine(goalPoint.add(headingNorm).add(agentHeading), agentPosition.add(headingNorm).subtract(agentHeading))) // { // return true; // } // headingNorm = new Vector3f(-agentHeading.z, 0, agentHeading.x); // headingNorm.multLocal(agentSize); // if(intersects2DLine(goalPoint.add(headingNorm).add(agentHeading), agentPosition.add(headingNorm).subtract(agentHeading))) // { // return true; // } return false; } public boolean isOpen() { return isOpen; } public void setOpen(boolean isOpen) { this.isOpen = isOpen; } /** * Checks if its mini bounding area intersects the line determined by the given start and end points * * @param endPoint * end point of the line * @param startPoint * start point of the line * @return true if it intersects. Otherwise, false. */ public boolean miniBAIntersects2DLine(Vector3f endPoint, Vector3f startPoint) { return boundingArea.intersects(new GeometryFactory().createLineString(new Coordinate[] {new Coordinate(endPoint.x, endPoint.z), new Coordinate(startPoint.x, startPoint.z)})); } }
9,136
0.588879
0.580342
286
30.944056
34.300049
182
true
false
0
0
0
0
0
0
0.566434
false
false
7
03532a8e07501768c2c5ddddc41e48da37f4ae2e
16,836,271,833,175
a3fbd5161bde70b23903d968d99430141fd9d51b
/BD-POO/src/entity/Tipo.java
1c53e95042468734e3a2620765e7974562941b03
[]
no_license
pedrozuzi/BD---POO
https://github.com/pedrozuzi/BD---POO
44c88e68864e8af7f31847b756378cb933ed8dcb
61d2a01b470e29d7f71c51f0c80b7fcbf710e36f
refs/heads/master
2023-07-28T03:06:49.023000
2015-06-16T23:55:18
2015-06-16T23:55:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package entity; /** * Classe para os objetos do tipo Tipo, com seus valores * e métodos * @author Pedro Afonso * */ public class Tipo { private int id; private String descricao; /** * Método para retorno no id do tipo * @return valor do id */ public int getId() { return id; } /** * Método para setar o valor do id * @param id valor do id */ public void setId(int id) { this.id = id; } /** * Método para retorno da descrição do tipo * @return descrição do tipo */ public String getDescricao() { return descricao; } /** * Método para setar * @param descricao */ public void setDescricao(String descricao) { this.descricao = descricao; } }
ISO-8859-1
Java
753
java
Tipo.java
Java
[ { "context": "o Tipo, com seus valores\r\n * e métodos\r\n * @author Pedro Afonso\r\n *\r\n */\r\npublic class Tipo {\r\n\r\n\tprivate int id;", "end": 119, "score": 0.9998613595962524, "start": 107, "tag": "NAME", "value": "Pedro Afonso" } ]
null
[]
package entity; /** * Classe para os objetos do tipo Tipo, com seus valores * e métodos * @author <NAME> * */ public class Tipo { private int id; private String descricao; /** * Método para retorno no id do tipo * @return valor do id */ public int getId() { return id; } /** * Método para setar o valor do id * @param id valor do id */ public void setId(int id) { this.id = id; } /** * Método para retorno da descrição do tipo * @return descrição do tipo */ public String getDescricao() { return descricao; } /** * Método para setar * @param descricao */ public void setDescricao(String descricao) { this.descricao = descricao; } }
747
0.598118
0.598118
46
14.173913
14.381909
56
false
false
0
0
0
0
0
0
0.913043
false
false
7
75af5eaf64871a0b6659fba423e9c221b36f2a8e
12,154,757,456,888
8d7f65dac65a576816225723de441dad0bfa9327
/generator-core/src/main/java/com/mulesoft/jaxrs/raml/jaxb/JAXBElementProperty.java
4bfe6816cf11e63afb6a5b352033e5e2931c67fa
[ "Apache-2.0" ]
permissive
lanmolsz/raml
https://github.com/lanmolsz/raml
7b03d28e50faeb113a7af9f4f4799efdd248ece3
218695f41c7ac9a4fbf1623c902bcf278c4656f4
refs/heads/master
2021-01-17T12:52:14.540000
2016-07-18T07:50:20
2016-07-18T07:50:20
57,280,228
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mulesoft.jaxrs.raml.jaxb; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.mulesoft.jaxrs.raml.annotation.model.IMember; import com.mulesoft.jaxrs.raml.annotation.model.IMethodModel; import com.mulesoft.jaxrs.raml.annotation.model.ITypeModel; import com.mulesoft.jaxrs.raml.annotation.model.StructureType; import com.mulesoft.jaxrs.raml.annotation.model.reflection.ReflectionType; /** * <p>JAXBElementProperty class.</p> * * @author kor * @version $Id: $Id */ public class JAXBElementProperty extends JAXBProperty { /** * <p>Constructor for JAXBElementProperty.</p> * * @param model a {@link com.mulesoft.jaxrs.raml.annotation.model.IBasicModel} object. * @param r a {@link com.mulesoft.jaxrs.raml.jaxb.JAXBRegistry} object. * @param name a {@link java.lang.String} object. */ public JAXBElementProperty(IMember model, IMethodModel setter, ITypeModel ownerType, JAXBRegistry r, String name) { super(model, setter, ownerType, r, name); } /** * <p>asJavaType.</p> * * @return a {@link java.lang.Class} object. */ public Class<?> asJavaType() { if (originalModel instanceof IMember) { IMember or = (IMember) originalModel; return or.getJavaType(); } return null; } /** * {@inheritDoc} */ @Override protected String getPropertyAnnotation() { return XmlElement.class.getSimpleName(); } }
UTF-8
Java
1,734
java
JAXBElementProperty.java
Java
[ { "context": " * <p>JAXBElementProperty class.</p>\n *\n * @author kor\n * @version $Id: $Id\n */\npublic class JAXBElement", "end": 712, "score": 0.9906136989593506, "start": 709, "tag": "USERNAME", "value": "kor" } ]
null
[]
package com.mulesoft.jaxrs.raml.jaxb; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.mulesoft.jaxrs.raml.annotation.model.IMember; import com.mulesoft.jaxrs.raml.annotation.model.IMethodModel; import com.mulesoft.jaxrs.raml.annotation.model.ITypeModel; import com.mulesoft.jaxrs.raml.annotation.model.StructureType; import com.mulesoft.jaxrs.raml.annotation.model.reflection.ReflectionType; /** * <p>JAXBElementProperty class.</p> * * @author kor * @version $Id: $Id */ public class JAXBElementProperty extends JAXBProperty { /** * <p>Constructor for JAXBElementProperty.</p> * * @param model a {@link com.mulesoft.jaxrs.raml.annotation.model.IBasicModel} object. * @param r a {@link com.mulesoft.jaxrs.raml.jaxb.JAXBRegistry} object. * @param name a {@link java.lang.String} object. */ public JAXBElementProperty(IMember model, IMethodModel setter, ITypeModel ownerType, JAXBRegistry r, String name) { super(model, setter, ownerType, r, name); } /** * <p>asJavaType.</p> * * @return a {@link java.lang.Class} object. */ public Class<?> asJavaType() { if (originalModel instanceof IMember) { IMember or = (IMember) originalModel; return or.getJavaType(); } return null; } /** * {@inheritDoc} */ @Override protected String getPropertyAnnotation() { return XmlElement.class.getSimpleName(); } }
1,734
0.694348
0.694348
58
28.896551
27.127216
119
false
false
0
0
0
0
0
0
0.448276
false
false
7
5081e863d87163c384673405b929cd9e395e503e
34,626,026,390,873
03a311711b1013e4734d012941669557ca0a2279
/Circle.java
f7be61675a31b26822d4772b61232df46272df2c
[]
no_license
Abdul-Awal1/javalab
https://github.com/Abdul-Awal1/javalab
e53516f572631651513a4d23c77cd9a89dc6d7f4
42e47ae3aa23d55dce1cb8f19e0d9f00f410635f
refs/heads/master
2021-01-03T17:01:39.381000
2020-03-30T04:40:48
2020-03-30T04:40:48
240,162,002
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package beginerjava; import java.util.Scanner; public class Circle { public static void main (String args []) { double radius,pie=3.1416,area; Scanner input=new Scanner (System.in); System.out.print("Enter the radius :"); radius =input.nextDouble(); area=pie*radius*radius; System.out.println("the area of a circle is : "+area); } }
UTF-8
Java
458
java
Circle.java
Java
[]
null
[]
package beginerjava; import java.util.Scanner; public class Circle { public static void main (String args []) { double radius,pie=3.1416,area; Scanner input=new Scanner (System.in); System.out.print("Enter the radius :"); radius =input.nextDouble(); area=pie*radius*radius; System.out.println("the area of a circle is : "+area); } }
458
0.537118
0.526201
18
23.333334
17.907167
62
false
false
0
0
0
0
0
0
0.555556
false
false
7
d56b107eca4270f90289743dc0030487924276fb
34,626,026,393,308
ccd7af83526f944d76f7d861196673e63b9386ae
/mylibrary/src/main/java/com/goodie/sdk/android/data/response/MemberPointResponse.java
98c5a285edf6bde6018387c8fea76a081a014101
[]
no_license
goodie-id/sdk-android
https://github.com/goodie-id/sdk-android
d8fdbea0c79a9a16287e407de73399b42ce7e3fb
e0fff28707bc6111b661dc1ba40cc6a3f1b97f1b
refs/heads/master
2020-05-07T16:55:40.662000
2019-08-13T06:42:56
2019-08-13T06:42:56
180,705,050
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.goodie.sdk.android.data.response; import com.google.gson.annotations.SerializedName; /** * Created by Goodie on 13/02/2019. */ public class MemberPointResponse extends GenericResponse { @SerializedName("memberName") private String memberName; @SerializedName("memberId") private String memberId; @SerializedName("merchantId") private String merchantId; @SerializedName("tierName") private String tierName; @SerializedName("tierImage") private String tierImage; @SerializedName("nextTierName") private String nextTierName; @SerializedName("nextTierImage") private String nextTierImage; @SerializedName("reqPointNextTier") private int reqPointNextTier; @SerializedName("totalPoints") private int totalPoints; @SerializedName("nearestPointToBeExpire") private int nearestPointToBeExpire; @SerializedName("nearestExpiredDate") private String nearestExpiredDate; public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public String getTierName() { return tierName; } public void setTierName(String tierName) { this.tierName = tierName; } public String getTierImage() { return tierImage; } public void setTierImage(String tierImage) { this.tierImage = tierImage; } public String getNextTierName() { return nextTierName; } public void setNextTierName(String nextTierName) { this.nextTierName = nextTierName; } public String getNextTierImage() { return nextTierImage; } public void setNextTierImage(String nextTierImage) { this.nextTierImage = nextTierImage; } public int getReqPointNextTier() { return reqPointNextTier; } public void setReqPointNextTier(int reqPointNextTier) { this.reqPointNextTier = reqPointNextTier; } public int getTotalPoints() { return totalPoints; } public void setTotalPoints(int totalPoints) { this.totalPoints = totalPoints; } public int getNearestPointToBeExpire() { return nearestPointToBeExpire; } public void setNearestPointToBeExpire(int nearestPointToBeExpire) { this.nearestPointToBeExpire = nearestPointToBeExpire; } public String getNearestExpiredDate() { return nearestExpiredDate; } public void setNearestExpiredDate(String nearestExpiredDate) { this.nearestExpiredDate = nearestExpiredDate; } @Override public String toString(){ return "MemberPointResponse{" + "memberName = '" + memberName + '\'' + "memberId = '" + memberId + '\'' + "merchantId = '" + merchantId + '\'' + "tierName = '" + tierName + '\'' + "tierImage = '" + tierImage + '\'' + "nextTierName = '" + nextTierName + '\'' + "nextTierImage = '" + nextTierImage + '\'' + "reqPointNextTier = '" + reqPointNextTier + '\'' + "totalPoints = '" + totalPoints + '\'' + "nearestPointToBeExpire = '" + nearestPointToBeExpire + '\'' + ",nearestExpiredDate = '" + nearestExpiredDate + '\'' + "}"; } /*{ "memberName": "Macan Yohan", "memberId": "D6D321EB-3EB2-44DE-910B-04D58F2D6817", "merchantId": "5F773EA1-1E66-4F9E-B9C8-E1FA8156AD20", "tierName": "CLASSIC", "tierImage": "", "nextTierName": "SILVER", "nextTierImage": "", "reqPointNextTier": 4981, "totalPoints": 20, "nearestPointToBeExpire": 20, "nearestExpiredDate": "2020-02-03", "abstractResponse": { "responseStatus": "INQ000", "responseMessage": "Inquiry success" } }*/ }
UTF-8
Java
4,608
java
MemberPointResponse.java
Java
[ { "context": ".annotations.SerializedName;\r\n\r\n/**\r\n * Created by Goodie on 13/02/2019.\r\n */\r\n\r\npublic class MemberPointRe", "end": 128, "score": 0.8491412401199341, "start": 122, "tag": "NAME", "value": "Goodie" }, { "context": " \"}\";\r\n }\r\n\r\n /*{\r\n ...
null
[]
package com.goodie.sdk.android.data.response; import com.google.gson.annotations.SerializedName; /** * Created by Goodie on 13/02/2019. */ public class MemberPointResponse extends GenericResponse { @SerializedName("memberName") private String memberName; @SerializedName("memberId") private String memberId; @SerializedName("merchantId") private String merchantId; @SerializedName("tierName") private String tierName; @SerializedName("tierImage") private String tierImage; @SerializedName("nextTierName") private String nextTierName; @SerializedName("nextTierImage") private String nextTierImage; @SerializedName("reqPointNextTier") private int reqPointNextTier; @SerializedName("totalPoints") private int totalPoints; @SerializedName("nearestPointToBeExpire") private int nearestPointToBeExpire; @SerializedName("nearestExpiredDate") private String nearestExpiredDate; public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public String getTierName() { return tierName; } public void setTierName(String tierName) { this.tierName = tierName; } public String getTierImage() { return tierImage; } public void setTierImage(String tierImage) { this.tierImage = tierImage; } public String getNextTierName() { return nextTierName; } public void setNextTierName(String nextTierName) { this.nextTierName = nextTierName; } public String getNextTierImage() { return nextTierImage; } public void setNextTierImage(String nextTierImage) { this.nextTierImage = nextTierImage; } public int getReqPointNextTier() { return reqPointNextTier; } public void setReqPointNextTier(int reqPointNextTier) { this.reqPointNextTier = reqPointNextTier; } public int getTotalPoints() { return totalPoints; } public void setTotalPoints(int totalPoints) { this.totalPoints = totalPoints; } public int getNearestPointToBeExpire() { return nearestPointToBeExpire; } public void setNearestPointToBeExpire(int nearestPointToBeExpire) { this.nearestPointToBeExpire = nearestPointToBeExpire; } public String getNearestExpiredDate() { return nearestExpiredDate; } public void setNearestExpiredDate(String nearestExpiredDate) { this.nearestExpiredDate = nearestExpiredDate; } @Override public String toString(){ return "MemberPointResponse{" + "memberName = '" + memberName + '\'' + "memberId = '" + memberId + '\'' + "merchantId = '" + merchantId + '\'' + "tierName = '" + tierName + '\'' + "tierImage = '" + tierImage + '\'' + "nextTierName = '" + nextTierName + '\'' + "nextTierImage = '" + nextTierImage + '\'' + "reqPointNextTier = '" + reqPointNextTier + '\'' + "totalPoints = '" + totalPoints + '\'' + "nearestPointToBeExpire = '" + nearestPointToBeExpire + '\'' + ",nearestExpiredDate = '" + nearestExpiredDate + '\'' + "}"; } /*{ "memberName": "<NAME>", "memberId": "D6D321EB-3EB2-44DE-910B-04D58F2D6817", "merchantId": "5F773EA1-1E66-4F9E-B9C8-E1FA8156AD20", "tierName": "CLASSIC", "tierImage": "", "nextTierName": "SILVER", "nextTierImage": "", "reqPointNextTier": 4981, "totalPoints": 20, "nearestPointToBeExpire": 20, "nearestExpiredDate": "2020-02-03", "abstractResponse": { "responseStatus": "INQ000", "responseMessage": "Inquiry success" } }*/ }
4,603
0.573134
0.558811
169
25.266272
22.153181
86
false
false
0
0
0
0
0
0
0.289941
false
false
7
36990e1364dea576c579df36a21c230c46091fa5
39,522,289,058,634
4e8668427cbf13f80e0ee536dd93b34649b02fd0
/http-replay/src/test/java/br/com/objectos/http/replay/ZipFileTest.java
0ae8dc23772876ba4c1992971abdc1b9b4702307
[ "Apache-2.0" ]
permissive
objectos/http
https://github.com/objectos/http
f054d1b262503ae75aa60f0d1a58e9266c48023d
2c48c120e02baea69262c66256f689cd96896774
refs/heads/master
2022-03-19T08:49:55.228000
2022-02-27T13:11:39
2022-02-27T13:11:39
239,498,361
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (C) 2016-2022 Objectos Software LTDA. * * 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 br.com.objectos.http.replay; import br.com.objectos.core.io.Copy; import br.com.objectos.core.throwable.Try; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Enumeration; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.testng.annotations.Test; public class ZipFileTest { private final byte[] responseBuffer = new byte[128]; @Test(enabled = false) public void listEntries() throws IOException { Throwable rethrow; rethrow = Try.begin(); ZipFile zip; zip = null; try { File file; file = new File("/tmp/replay.zip"); zip = new ZipFile(file); Enumeration<? extends ZipEntry> entries; entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry request; request = entries.nextElement(); if (request.getName().endsWith("archive")) { continue; } if (!isRequest(request)) { throw new IOException("Not a request: "); } if (!entries.hasMoreElements()) { throw new IOException("No more elements..."); } ZipEntry response; response = entries.nextElement(); if (!isResponse(response)) { throw new IOException("Not a response"); } listEntry(zip, request, response); } } catch (IOException e) { rethrow = e; } finally { rethrow = Try.close(rethrow, zip); } Try.rethrowIfPossible(rethrow, IOException.class); } private boolean isRequest(ZipEntry entry) { String name; name = entry.getName(); return name.endsWith(".request"); } private boolean isResponse(ZipEntry entry) { String name; name = entry.getName(); return name.endsWith(".response"); } private void listEntry(ZipFile tar, ZipEntry request, ZipEntry response) throws IOException { Throwable rethrow; rethrow = Try.begin(); GZIPInputStream gzip; gzip = null; try { InputStream in; in = tar.getInputStream(request); gzip = new GZIPInputStream(in); String name; name = request.getName(); System.out.println(name); long time; time = request.getTime(); Date lastModifiedDate; lastModifiedDate = new Date(time); System.out.println(lastModifiedDate.toString()); ByteArrayOutputStream out; out = new ByteArrayOutputStream(); Copy.streams(in, out, responseBuffer); byte[] bytes; bytes = out.toByteArray(); String s; s = new String(bytes); System.out.println(s); } catch (IOException e) { rethrow = e; } finally { rethrow = Try.close(rethrow, gzip); } Try.rethrowIfPossible(rethrow, IOException.class); try { InputStream in; in = tar.getInputStream(response); gzip = new GZIPInputStream(in); String name; name = response.getName(); System.out.println(name); int read; read = gzip.read(responseBuffer); if (read > 0) { String s; s = new String(responseBuffer, 0, read); System.out.println(s); } } catch (IOException e) { rethrow = e; } finally { rethrow = Try.close(rethrow, gzip); } Try.rethrowIfPossible(rethrow, IOException.class); } }
UTF-8
Java
4,069
java
ZipFileTest.java
Java
[]
null
[]
/* * Copyright (C) 2016-2022 Objectos Software LTDA. * * 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 br.com.objectos.http.replay; import br.com.objectos.core.io.Copy; import br.com.objectos.core.throwable.Try; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Enumeration; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.testng.annotations.Test; public class ZipFileTest { private final byte[] responseBuffer = new byte[128]; @Test(enabled = false) public void listEntries() throws IOException { Throwable rethrow; rethrow = Try.begin(); ZipFile zip; zip = null; try { File file; file = new File("/tmp/replay.zip"); zip = new ZipFile(file); Enumeration<? extends ZipEntry> entries; entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry request; request = entries.nextElement(); if (request.getName().endsWith("archive")) { continue; } if (!isRequest(request)) { throw new IOException("Not a request: "); } if (!entries.hasMoreElements()) { throw new IOException("No more elements..."); } ZipEntry response; response = entries.nextElement(); if (!isResponse(response)) { throw new IOException("Not a response"); } listEntry(zip, request, response); } } catch (IOException e) { rethrow = e; } finally { rethrow = Try.close(rethrow, zip); } Try.rethrowIfPossible(rethrow, IOException.class); } private boolean isRequest(ZipEntry entry) { String name; name = entry.getName(); return name.endsWith(".request"); } private boolean isResponse(ZipEntry entry) { String name; name = entry.getName(); return name.endsWith(".response"); } private void listEntry(ZipFile tar, ZipEntry request, ZipEntry response) throws IOException { Throwable rethrow; rethrow = Try.begin(); GZIPInputStream gzip; gzip = null; try { InputStream in; in = tar.getInputStream(request); gzip = new GZIPInputStream(in); String name; name = request.getName(); System.out.println(name); long time; time = request.getTime(); Date lastModifiedDate; lastModifiedDate = new Date(time); System.out.println(lastModifiedDate.toString()); ByteArrayOutputStream out; out = new ByteArrayOutputStream(); Copy.streams(in, out, responseBuffer); byte[] bytes; bytes = out.toByteArray(); String s; s = new String(bytes); System.out.println(s); } catch (IOException e) { rethrow = e; } finally { rethrow = Try.close(rethrow, gzip); } Try.rethrowIfPossible(rethrow, IOException.class); try { InputStream in; in = tar.getInputStream(response); gzip = new GZIPInputStream(in); String name; name = response.getName(); System.out.println(name); int read; read = gzip.read(responseBuffer); if (read > 0) { String s; s = new String(responseBuffer, 0, read); System.out.println(s); } } catch (IOException e) { rethrow = e; } finally { rethrow = Try.close(rethrow, gzip); } Try.rethrowIfPossible(rethrow, IOException.class); } }
4,069
0.636766
0.632588
175
22.257143
20.006203
95
false
false
0
0
0
0
0
0
0.571429
false
false
7
e1c55aa9a1773652ba78aaa04f227e033c2f05de
35,527,969,514,464
7a23763f8575583ceaa866b1e3a02c5e31476be6
/app/src/main/java/com/meiji/toutiao/module/media/wip/tab/MediaTabPresenter.java
441b7787ba7d021ea85c3f63e1ab1e39da82d143
[ "Apache-2.0" ]
permissive
kyaky/Toutiao
https://github.com/kyaky/Toutiao
2feb9f15a7217c1e65de2bc411940dca52d6322f
071d61e88e686172d384ba8c8b4d627ef74330ab
refs/heads/master
2020-12-02T22:50:43.218000
2017-07-03T15:14:05
2017-07-03T15:14:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.meiji.toutiao.module.media.wip.tab; import android.text.TextUtils; import com.meiji.toutiao.ErrorAction; import com.meiji.toutiao.RetrofitFactory; import com.meiji.toutiao.api.IMobileMediaApi; import com.meiji.toutiao.bean.media.MultiMediaArticleBean; import com.meiji.toutiao.utils.TimeUtil; import java.util.ArrayList; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; /** * Created by Meiji on 2017/7/1. */ public class MediaTabPresenter implements IMediaProfile.Presenter { protected static final int TYPE_ARTICLE = 0; protected static final int TYPE_VIDEO = 1; protected static final int TYPE_WENDA = 2; private static final String TAG = "MediaTabPresenter"; private IMediaProfile.View view; private String mediaId; private String time; private List<MultiMediaArticleBean.DataBean> dataList = new ArrayList<>(); MediaTabPresenter(IMediaProfile.View view) { this.view = view; this.time = TimeUtil.getTimeStamp(); } @Override public void doRefresh() { if (dataList.size() > 0) { dataList.clear(); time = TimeUtil.getTimeStamp(); } doLoadArticle(); } @Override public void doShowNetError() { view.onHideLoading(); view.onShowNetError(); } @Override public void doLoadArticle(String... mediaId) { try { if (TextUtils.isEmpty(this.mediaId)) { this.mediaId = mediaId[0]; } } catch (Exception e) { ErrorAction.print(e); } RetrofitFactory.getRetrofit().create(IMobileMediaApi.class) .getMediaArticle(this.mediaId, this.time) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(view.<MultiMediaArticleBean>bindToLife()) .subscribe(new Consumer<MultiMediaArticleBean>() { @Override public void accept(@NonNull MultiMediaArticleBean bean) throws Exception { time = bean.getNext().getMax_behot_time(); doSetAdapter(bean.getData()); } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable throwable) throws Exception { doShowNetError(); ErrorAction.print(throwable); } }); } @Override public void doLoadVideo(String... mediaId) { try { if (TextUtils.isEmpty(this.mediaId)) { this.mediaId = mediaId[0]; } } catch (Exception e) { ErrorAction.print(e); } RetrofitFactory.getRetrofit().create(IMobileMediaApi.class) .getMediaVideo(this.mediaId, this.time) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(view.<MultiMediaArticleBean>bindToLife()) .subscribe(new Consumer<MultiMediaArticleBean>() { @Override public void accept(@NonNull MultiMediaArticleBean bean) throws Exception { time = bean.getNext().getMax_behot_time(); doSetAdapter(bean.getData()); } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable throwable) throws Exception { doShowNetError(); ErrorAction.print(throwable); } }); } @Override public void doLoadWenda(String... mediaId) { } @Override public void doLoadMoreData(int type) { switch (type) { case TYPE_ARTICLE: doLoadArticle(); break; case TYPE_VIDEO: doLoadVideo(); break; case TYPE_WENDA: doLoadWenda(); break; } } @Override public void doSetAdapter(List<MultiMediaArticleBean.DataBean> list) { dataList.addAll(list); view.onSetAdapter(dataList); view.onHideLoading(); } }
UTF-8
Java
4,489
java
MediaTabPresenter.java
Java
[ { "context": "eactivex.schedulers.Schedulers;\n\n/**\n * Created by Meiji on 2017/7/1.\n */\n\npublic class MediaTabPresenter ", "end": 566, "score": 0.9017577767372131, "start": 561, "tag": "USERNAME", "value": "Meiji" } ]
null
[]
package com.meiji.toutiao.module.media.wip.tab; import android.text.TextUtils; import com.meiji.toutiao.ErrorAction; import com.meiji.toutiao.RetrofitFactory; import com.meiji.toutiao.api.IMobileMediaApi; import com.meiji.toutiao.bean.media.MultiMediaArticleBean; import com.meiji.toutiao.utils.TimeUtil; import java.util.ArrayList; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; /** * Created by Meiji on 2017/7/1. */ public class MediaTabPresenter implements IMediaProfile.Presenter { protected static final int TYPE_ARTICLE = 0; protected static final int TYPE_VIDEO = 1; protected static final int TYPE_WENDA = 2; private static final String TAG = "MediaTabPresenter"; private IMediaProfile.View view; private String mediaId; private String time; private List<MultiMediaArticleBean.DataBean> dataList = new ArrayList<>(); MediaTabPresenter(IMediaProfile.View view) { this.view = view; this.time = TimeUtil.getTimeStamp(); } @Override public void doRefresh() { if (dataList.size() > 0) { dataList.clear(); time = TimeUtil.getTimeStamp(); } doLoadArticle(); } @Override public void doShowNetError() { view.onHideLoading(); view.onShowNetError(); } @Override public void doLoadArticle(String... mediaId) { try { if (TextUtils.isEmpty(this.mediaId)) { this.mediaId = mediaId[0]; } } catch (Exception e) { ErrorAction.print(e); } RetrofitFactory.getRetrofit().create(IMobileMediaApi.class) .getMediaArticle(this.mediaId, this.time) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(view.<MultiMediaArticleBean>bindToLife()) .subscribe(new Consumer<MultiMediaArticleBean>() { @Override public void accept(@NonNull MultiMediaArticleBean bean) throws Exception { time = bean.getNext().getMax_behot_time(); doSetAdapter(bean.getData()); } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable throwable) throws Exception { doShowNetError(); ErrorAction.print(throwable); } }); } @Override public void doLoadVideo(String... mediaId) { try { if (TextUtils.isEmpty(this.mediaId)) { this.mediaId = mediaId[0]; } } catch (Exception e) { ErrorAction.print(e); } RetrofitFactory.getRetrofit().create(IMobileMediaApi.class) .getMediaVideo(this.mediaId, this.time) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(view.<MultiMediaArticleBean>bindToLife()) .subscribe(new Consumer<MultiMediaArticleBean>() { @Override public void accept(@NonNull MultiMediaArticleBean bean) throws Exception { time = bean.getNext().getMax_behot_time(); doSetAdapter(bean.getData()); } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable throwable) throws Exception { doShowNetError(); ErrorAction.print(throwable); } }); } @Override public void doLoadWenda(String... mediaId) { } @Override public void doLoadMoreData(int type) { switch (type) { case TYPE_ARTICLE: doLoadArticle(); break; case TYPE_VIDEO: doLoadVideo(); break; case TYPE_WENDA: doLoadWenda(); break; } } @Override public void doSetAdapter(List<MultiMediaArticleBean.DataBean> list) { dataList.addAll(list); view.onSetAdapter(dataList); view.onHideLoading(); } }
4,489
0.568501
0.565828
138
31.528986
22.783222
94
false
false
0
0
0
0
0
0
0.398551
false
false
7
0462fe9cbbbba60bc16d40490dfef6ca0f5e1293
35,055,523,119,288
4832fe04a6e1dd7205a697a7a10a88ed10b1e469
/maze/cli/cli.java
12906164af4388402559af3cd6ae5b27f668fead
[]
no_license
tiagocyberduck/LPOO-Maze
https://github.com/tiagocyberduck/LPOO-Maze
686a41377dfad1d91a3943b2628569a89941bdd5
f70f02e7441d3fccf6beb0f898cd9a57ab2d3c63
refs/heads/master
2021-03-24T12:01:10.607000
2015-04-27T23:58:00
2015-04-27T23:58:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cli; import java.util.Scanner; import logic.Logic; public class cli { private static Logic game; private static boolean debug = false; private static boolean debugRandom = false; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); displayOptions(keyboard); while (!game.gameEnded()) { display(game.getMap()); char movement = keyboard.next().charAt(0); game.play(movement); } display(game.getMap()); System.out.println(game.getGameEndedMessage()); keyboard.close(); } private static void displayOptions(Scanner keyboard) { if(debug) { if( !debugRandom) game = new Logic(1); else game = new Logic(10, 2, 2); return; } while(true) { System.out.println("Amazing Maze"); System.out.println("Select Option:"); System.out.println(" 1- Default Maze"); System.out.println(" 2- Random Maze"); char option = keyboard.next().charAt(0); if(option == '1') { int dragonOptions = dragonMovementOptions(keyboard); game = new Logic(dragonOptions); break; }else if(option == '2') { while(true) { System.out.println("Amazing Maze"); System.out.print("Size of maze (min 10)? "); int mazeSize = keyboard.nextInt(); if(mazeSize >= 10) { int dragonOptions = dragonMovementOptions(keyboard); int dragonNumber = dragonNumber(keyboard); game = new Logic(mazeSize, dragonOptions, dragonNumber); break; } } break; } } } private static int dragonMovementOptions(Scanner keyboard) { while(true) { System.out.println("Amazing Maze"); System.out.println("Dragon Movement: "); System.out.println(" 1- Stopped"); System.out.println(" 2- Random Movement"); System.out.println(" 3- Random Movement Sleep Option"); int dragonMovement = keyboard.nextInt(); if(dragonMovement >= 1 && dragonMovement <= 3) { return dragonMovement; } } } private static int dragonNumber(Scanner keyboard) { while(true) { System.out.println("Amazing Maze"); System.out.print("Number of dragons (max 9)? "); int numberDragons = keyboard.nextInt(); if(numberDragons >= 1 && numberDragons <= 9) { return numberDragons; } } } public static void display(char[][] map) { for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { System.out.print(map[i][j]); System.out.print(" "); } System.out.println(); } System.out.println(game.getGameMessage()); System.out.println(game.heroDarts()+" darts in your backpack (f, g, h, t to launch them)"); } }
UTF-8
Java
2,677
java
cli.java
Java
[]
null
[]
package cli; import java.util.Scanner; import logic.Logic; public class cli { private static Logic game; private static boolean debug = false; private static boolean debugRandom = false; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); displayOptions(keyboard); while (!game.gameEnded()) { display(game.getMap()); char movement = keyboard.next().charAt(0); game.play(movement); } display(game.getMap()); System.out.println(game.getGameEndedMessage()); keyboard.close(); } private static void displayOptions(Scanner keyboard) { if(debug) { if( !debugRandom) game = new Logic(1); else game = new Logic(10, 2, 2); return; } while(true) { System.out.println("Amazing Maze"); System.out.println("Select Option:"); System.out.println(" 1- Default Maze"); System.out.println(" 2- Random Maze"); char option = keyboard.next().charAt(0); if(option == '1') { int dragonOptions = dragonMovementOptions(keyboard); game = new Logic(dragonOptions); break; }else if(option == '2') { while(true) { System.out.println("Amazing Maze"); System.out.print("Size of maze (min 10)? "); int mazeSize = keyboard.nextInt(); if(mazeSize >= 10) { int dragonOptions = dragonMovementOptions(keyboard); int dragonNumber = dragonNumber(keyboard); game = new Logic(mazeSize, dragonOptions, dragonNumber); break; } } break; } } } private static int dragonMovementOptions(Scanner keyboard) { while(true) { System.out.println("Amazing Maze"); System.out.println("Dragon Movement: "); System.out.println(" 1- Stopped"); System.out.println(" 2- Random Movement"); System.out.println(" 3- Random Movement Sleep Option"); int dragonMovement = keyboard.nextInt(); if(dragonMovement >= 1 && dragonMovement <= 3) { return dragonMovement; } } } private static int dragonNumber(Scanner keyboard) { while(true) { System.out.println("Amazing Maze"); System.out.print("Number of dragons (max 9)? "); int numberDragons = keyboard.nextInt(); if(numberDragons >= 1 && numberDragons <= 9) { return numberDragons; } } } public static void display(char[][] map) { for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { System.out.print(map[i][j]); System.out.print(" "); } System.out.println(); } System.out.println(game.getGameMessage()); System.out.println(game.heroDarts()+" darts in your backpack (f, g, h, t to launch them)"); } }
2,677
0.627568
0.618229
113
22.690266
20.40132
93
false
false
0
0
0
0
0
0
3.159292
false
false
7
48579283b276ea12c6e1154eaa689ac7c4feda7e
36,893,769,102,556
5cc735463ab824d8e50d8aea021f7ed3edbb3981
/holley-wxcharging-biz/src/main/java/com/holley/wxcharging/model/def/vo/ChargingRecordVo.java
dcfe01357735a1171627e04411b20d6727720204
[]
no_license
moutainhigh/wxcharging
https://github.com/moutainhigh/wxcharging
3611b85c37453ec13d1fadbbdc77055eba0ce74b
ac07bcf0bff0c059e83b187917cc0ced2ac83685
refs/heads/master
2020-09-21T10:02:45.601000
2018-09-13T08:22:02
2018-09-13T08:22:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.holley.wxcharging.model.def.vo; import java.math.BigDecimal; import java.util.Date; import com.holley.common.util.DateUtil; import com.holley.wxcharging.common.constants.BikePayStatusEnum; import com.holley.wxcharging.common.constants.ChargePayStatusEnum; import com.holley.wxcharging.common.constants.UseToTypeEnum; /** * 充电记录vo * * @author sc */ public class ChargingRecordVo { private Integer chargingRecordId;// 记录ID private String tradeNo; // 订单编号 private String stationName; // 充电站名称 private String pileName; // 充电桩名称 private Date date; // 数据时间 private BigDecimal chaMoney; // 充电金额 private int payStatus; // 支付状态 private int chargeType; public Integer getChargingRecordId() { return chargingRecordId; } public void setChargingRecordId(Integer chargingRecordId) { this.chargingRecordId = chargingRecordId; } public String getStationName() { return stationName; } public void setStationName(String stationName) { this.stationName = stationName; } public String getPileName() { return pileName; } public void setPileName(String pileName) { this.pileName = pileName; } public String getDateTime() { return DateUtil.DateToStr(date, DateUtil.TIME_LONG); } public BigDecimal getChaMoney() { return chaMoney; } public void setChaMoney(BigDecimal chaMoney) { this.chaMoney = chaMoney; } public int getPayStatus() { return payStatus; } public void setPayStatus(int payStatus) { this.payStatus = payStatus; } public String getPayStatusDesc() { if(UseToTypeEnum.CAR.getValue() == chargeType) { return ChargePayStatusEnum.getText(payStatus); }else { return BikePayStatusEnum.getText(payStatus); } } public String getTradeNo() { return tradeNo; } public void setTradeNo(String tradeNo) { this.tradeNo = tradeNo; } public int getChargeType() { return chargeType; } public void setChargeType(int chargeType) { this.chargeType = chargeType; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
UTF-8
Java
2,393
java
ChargingRecordVo.java
Java
[ { "context": "tants.UseToTypeEnum;\n\n/**\n * 充电记录vo\n * \n * @author sc\n */\npublic class ChargingRecordVo {\n\n private I", "end": 363, "score": 0.788527250289917, "start": 361, "tag": "USERNAME", "value": "sc" } ]
null
[]
package com.holley.wxcharging.model.def.vo; import java.math.BigDecimal; import java.util.Date; import com.holley.common.util.DateUtil; import com.holley.wxcharging.common.constants.BikePayStatusEnum; import com.holley.wxcharging.common.constants.ChargePayStatusEnum; import com.holley.wxcharging.common.constants.UseToTypeEnum; /** * 充电记录vo * * @author sc */ public class ChargingRecordVo { private Integer chargingRecordId;// 记录ID private String tradeNo; // 订单编号 private String stationName; // 充电站名称 private String pileName; // 充电桩名称 private Date date; // 数据时间 private BigDecimal chaMoney; // 充电金额 private int payStatus; // 支付状态 private int chargeType; public Integer getChargingRecordId() { return chargingRecordId; } public void setChargingRecordId(Integer chargingRecordId) { this.chargingRecordId = chargingRecordId; } public String getStationName() { return stationName; } public void setStationName(String stationName) { this.stationName = stationName; } public String getPileName() { return pileName; } public void setPileName(String pileName) { this.pileName = pileName; } public String getDateTime() { return DateUtil.DateToStr(date, DateUtil.TIME_LONG); } public BigDecimal getChaMoney() { return chaMoney; } public void setChaMoney(BigDecimal chaMoney) { this.chaMoney = chaMoney; } public int getPayStatus() { return payStatus; } public void setPayStatus(int payStatus) { this.payStatus = payStatus; } public String getPayStatusDesc() { if(UseToTypeEnum.CAR.getValue() == chargeType) { return ChargePayStatusEnum.getText(payStatus); }else { return BikePayStatusEnum.getText(payStatus); } } public String getTradeNo() { return tradeNo; } public void setTradeNo(String tradeNo) { this.tradeNo = tradeNo; } public int getChargeType() { return chargeType; } public void setChargeType(int chargeType) { this.chargeType = chargeType; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
2,393
0.653929
0.653929
102
21.833334
20.302652
66
false
false
0
0
0
0
0
0
0.568627
false
false
7
f56331ad4d2fe50bdf2b4aa96293fc56abae91a1
38,809,324,529,958
cab7d82bbd82e694bc96cad32836f4671c42b519
/PoolMyCarCode/PoolMyCarCode-ejb/src/java/facades/CommentoAutistaFacadeLocal.java
f76394348336843ce6f58a3e89f403ca8ce962ba
[]
no_license
Didba/poolmycar
https://github.com/Didba/poolmycar
1135da877d8a440b25b11d550cc7c62e1f0ab90f
a9e98d0b17b1e7866e43a41aa44508ad940a2408
refs/heads/master
2020-05-20T16:50:09.037000
2010-05-13T09:27:13
2010-05-13T09:27:13
40,829,130
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package facades; import java.util.List; import javax.ejb.Local; import utenti.CommentoAutista; /** Interfaccia di CommentoAutistaFacade * Interfaccia ad uso locale dell'oggetto che rende persistente l'oggetto CommentoAutista * @author berto */ @Local public interface CommentoAutistaFacadeLocal { void create(CommentoAutista commentoAutista); void edit(CommentoAutista commentoAutista); void remove(CommentoAutista commentoAutista); CommentoAutista find(Object id); List<CommentoAutista> findAll(); }
UTF-8
Java
633
java
CommentoAutistaFacadeLocal.java
Java
[ { "context": "e persistente l'oggetto CommentoAutista\n * @author berto\n */\n@Local\npublic interface CommentoAutistaFacade", "end": 345, "score": 0.9979920983314514, "start": 340, "tag": "USERNAME", "value": "berto" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package facades; import java.util.List; import javax.ejb.Local; import utenti.CommentoAutista; /** Interfaccia di CommentoAutistaFacade * Interfaccia ad uso locale dell'oggetto che rende persistente l'oggetto CommentoAutista * @author berto */ @Local public interface CommentoAutistaFacadeLocal { void create(CommentoAutista commentoAutista); void edit(CommentoAutista commentoAutista); void remove(CommentoAutista commentoAutista); CommentoAutista find(Object id); List<CommentoAutista> findAll(); }
633
0.764613
0.764613
29
20.827587
22.952829
89
false
false
0
0
0
0
0
0
0.37931
false
false
7
c5dcd68aa6e7af6efdc0fc68801b8eeec23026af
33,689,723,534,030
9480d020300a925ac18b1ad54ed81d553d1e0bc7
/product-core/src/main/java/com/ai/slp/product/service/business/interfaces/IProductManagerBusiSV.java
80491416ace304fd4c18ac9c935706421e27284d
[]
no_license
suevip/slp-product
https://github.com/suevip/slp-product
ffe134b5ae9129ba7b797bf48d0d349c6d9652e7
fec809753e2990454c3b842e6b80bf3013f0c601
refs/heads/master
2018-01-15T12:13:42.226000
2016-09-20T10:57:34
2016-09-20T10:57:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ai.slp.product.service.business.interfaces; import java.util.List; import com.ai.opt.base.vo.PageInfoResponse; import com.ai.slp.product.api.product.param.*; /** * 销售商品管理 * Created by jackieliu on 16/6/6. */ public interface IProductManagerBusiSV { /** * 商品管理中分页查询商品信息 * @param queryReq * @return */ public PageInfoResponse<ProductEditUp> queryPageForEdit(ProductEditQueryReq queryReq); /** * 查询商品的其他设置内容 * @param tenantId * @param supplierId * @param prodId * @return */ public OtherSetOfProduct queryOtherSetOfProd(String tenantId,String supplierId, String prodId); /** * 更新产品编辑信息 * @param productInfo */ public void updateProdEdit(ProductInfoForUpdate productInfo); /** * 根据状态查询仓库中商品 * @param productStorageSaleParam * @return */ public PageInfoResponse<ProductStorageSale> queryStorageProdByState(ProductStorageSaleParam productStorageSaleParam) ; /** * 商品管理中分页查询被拒绝商品信息 * @param productRefuseParam * @return */ public PageInfoResponse<ProductEditUp> queryProductRefuse(ProductEditQueryReq productRefuseParam); /** * 查询被拒绝原因 * @param productRefuseParam * @return */ public ProdStateLog queryRefuseByProdId(ProductInfoQuery queryInfo); /** * 查收商品的目标地域 * @return */ public PageInfoResponse<TargetAreaForProd> searchProdTargetArea(ProductEditQueryReq productEditParam); /** * 查询在售商品 -- 按上架时间排序 * @param queryInSale * @return */ public PageInfoResponse<ProductEditUp> queryInSale(ProductQueryInfo queryInSale); /** * 商品审核分页查询 * * @param queryReq * @return * @author jiawen */ public PageInfoResponse<ProductEditUp> queryPageForAudit(ProductQueryInfo queryReq); /** * 设置销售商品的路由组/配货组标识 * @param tenantId * @param supplierId * @param prodId * @param routeGroupId * @param operId */ public void changeRouteGroup(String tenantId,String supplierId,String prodId, String routeGroupId,Long operId); /** * 查询销售商品信息和配货组信息 * @param query * @return */ public PageInfoResponse<ProductRouteGroupInfo> queryProdAndRouteGroup(RouteGroupQuery query); /** * 审核商品 * @param productCheckParam * @return 待添加搜索中的商品ID集合 */ public List<String> auditProduct(ProductCheckParam productCheckParam); }
UTF-8
Java
2,751
java
IProductManagerBusiSV.java
Java
[ { "context": ".api.product.param.*;\n\n/**\n * 销售商品管理\n * Created by jackieliu on 16/6/6.\n */\npublic interface IProductManagerBu", "end": 210, "score": 0.9996082782745361, "start": 201, "tag": "USERNAME", "value": "jackieliu" }, { "context": "查询\n\t *\n\t * @param queryReq\n\t * @r...
null
[]
package com.ai.slp.product.service.business.interfaces; import java.util.List; import com.ai.opt.base.vo.PageInfoResponse; import com.ai.slp.product.api.product.param.*; /** * 销售商品管理 * Created by jackieliu on 16/6/6. */ public interface IProductManagerBusiSV { /** * 商品管理中分页查询商品信息 * @param queryReq * @return */ public PageInfoResponse<ProductEditUp> queryPageForEdit(ProductEditQueryReq queryReq); /** * 查询商品的其他设置内容 * @param tenantId * @param supplierId * @param prodId * @return */ public OtherSetOfProduct queryOtherSetOfProd(String tenantId,String supplierId, String prodId); /** * 更新产品编辑信息 * @param productInfo */ public void updateProdEdit(ProductInfoForUpdate productInfo); /** * 根据状态查询仓库中商品 * @param productStorageSaleParam * @return */ public PageInfoResponse<ProductStorageSale> queryStorageProdByState(ProductStorageSaleParam productStorageSaleParam) ; /** * 商品管理中分页查询被拒绝商品信息 * @param productRefuseParam * @return */ public PageInfoResponse<ProductEditUp> queryProductRefuse(ProductEditQueryReq productRefuseParam); /** * 查询被拒绝原因 * @param productRefuseParam * @return */ public ProdStateLog queryRefuseByProdId(ProductInfoQuery queryInfo); /** * 查收商品的目标地域 * @return */ public PageInfoResponse<TargetAreaForProd> searchProdTargetArea(ProductEditQueryReq productEditParam); /** * 查询在售商品 -- 按上架时间排序 * @param queryInSale * @return */ public PageInfoResponse<ProductEditUp> queryInSale(ProductQueryInfo queryInSale); /** * 商品审核分页查询 * * @param queryReq * @return * @author jiawen */ public PageInfoResponse<ProductEditUp> queryPageForAudit(ProductQueryInfo queryReq); /** * 设置销售商品的路由组/配货组标识 * @param tenantId * @param supplierId * @param prodId * @param routeGroupId * @param operId */ public void changeRouteGroup(String tenantId,String supplierId,String prodId, String routeGroupId,Long operId); /** * 查询销售商品信息和配货组信息 * @param query * @return */ public PageInfoResponse<ProductRouteGroupInfo> queryProdAndRouteGroup(RouteGroupQuery query); /** * 审核商品 * @param productCheckParam * @return 待添加搜索中的商品ID集合 */ public List<String> auditProduct(ProductCheckParam productCheckParam); }
2,751
0.671411
0.669784
103
22.873787
27.484392
122
false
false
0
0
0
0
0
0
0.398058
false
false
7
93419febd6bb6243a5c876349bd59612ef74cb86
37,168,647,011,852
13d8634c00f9679570732fd0f3d528ccfdd7b1db
/src/hello3D/test/HelloWorld.java
d5d580efc0c816eca9914d8c3bdc78a21ae3eeeb
[]
no_license
hasinichathu/SoftwareVisualization
https://github.com/hasinichathu/SoftwareVisualization
731dc6f442eb89fc47934c411ac767e8c40982ae
c4acfaac160d1d6fed6e932ce4140b5ec3559c08
refs/heads/master
2023-01-12T23:02:33.669000
2020-11-25T06:32:40
2020-11-25T06:32:40
312,970,017
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 hello3D.test; /** * * @author Hasini */ import com.jme3.app.SimpleApplication; import com.jme3.material.Material; import com.jme3.scene.Geometry; import com.jme3.scene.shape.Box; import com.jme3.math.ColorRGBA; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.system.AppSettings; import com.jme3.system.JmeCanvasContext; import com.jme3.util.JmeFormatter; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.concurrent.Callable; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Logger; import javax.swing.*; import com.jme3.util.SkyFactory; import com.jme3.terrain.geomipmap.TerrainLodControl; import com.jme3.terrain.heightmap.AbstractHeightMap; import com.jme3.terrain.geomipmap.TerrainQuad; import com.jme3.terrain.geomipmap.lodcalc.DistanceLodCalculator; import com.jme3.terrain.heightmap.HillHeightMap; // for exercise 2 import com.jme3.terrain.heightmap.ImageBasedHeightMap; import com.jme3.texture.Texture; import com.jme3.texture.Texture.WrapMode; /** * Sample 1 - how to get started with the most simple JME 3 application. Display * a blue 3D cube and view from all sides by moving the mouse and pressing the * WASD keys. */ public class HelloWorld extends SimpleApplication { private TerrainQuad terrain; Material mat_terrain; @Override public void simpleInitApp() { viewPort.setBackgroundColor(ColorRGBA.Gray); cam.setLocation(new Vector3f(3.3212643f, 4.484704f, 4.2812433f)); cam.setRotation(new Quaternion(-0.07680723f, 0.92299235f, -0.2564353f, -0.27645364f)); /** * 1. Create terrain material and load four textures into it. */ mat_terrain = new Material(assetManager, "Common/MatDefs/Terrain/Terrain.j3md"); /** * 1.1) Add ALPHA map (for red-blue-green coded splat textures) */ mat_terrain.setTexture("Alpha", assetManager.loadTexture( "Textures/Terrain/splat/alphamap.png")); /** * 1.2) Add GRASS texture into the red layer (Tex1). */ Texture grass = assetManager.loadTexture( "Textures/Terrain/splat/grass.jpg"); //grass.setWrap(WrapMode.Repeat); mat_terrain.setTexture("Tex1", grass); mat_terrain.setFloat("Tex1Scale", 64f); /** * 1.3) Add DIRT texture into the green layer (Tex2) */ Texture dirt = assetManager.loadTexture( "Textures/Terrain/splat/dirt.jpg"); //dirt.setWrap(WrapMode.); mat_terrain.setTexture("Tex2", dirt); mat_terrain.setFloat("Tex2Scale", 32f); /** * 1.4) Add ROAD texture into the blue layer (Tex3) */ Texture rock = assetManager.loadTexture( "Textures/Terrain/splat/road.jpg"); //rock.setWrap(WrapMode.Repeat); mat_terrain.setTexture("Tex3", rock); mat_terrain.setFloat("Tex3Scale", 128f); /** * 2. Create the height map */ AbstractHeightMap heightmap = null; Texture heightMapImage = assetManager.loadTexture( "Textures/Terrain/splat/mountains512.png"); heightmap = new ImageBasedHeightMap(heightMapImage.getImage()); heightmap.load(); /** * 3. We have prepared material and heightmap. Now we create the actual * terrain: 3.1) Create a TerrainQuad and name it "my terrain". 3.2) A * good value for terrain tiles is 64x64 -- so we supply 64+1=65. 3.3) * We prepared a heightmap of size 512x512 -- so we supply 512+1=513. * 3.4) As LOD step scale we supply Vector3f(1,1,1). 3.5) We supply the * prepared heightmap itself. */ int patchSize = 257; terrain = new TerrainQuad("my terrain", patchSize, 257, heightmap.getHeightMap()); /** * 4. We give the terrain its material, position & scale it, and attach * it. */ terrain.setMaterial(mat_terrain); terrain.setLocalTranslation(0, -100, 0); terrain.setLocalScale(2f, 1f, 2f); rootNode.attachChild(terrain); /** * 5. The LOD (level of detail) depends on were the camera is: */ TerrainLodControl control = new TerrainLodControl(terrain, getCamera()); terrain.addControl(control); } public static void main(String[] args) { Swing swing = new Swing(); swing.swingHandler(new HelloWorld()); } }
UTF-8
Java
5,110
java
HelloWorld.java
Java
[ { "context": "\n */\r\npackage hello3D.test;\r\n\r\n/**\r\n *\r\n * @author Hasini\r\n */\r\nimport com.jme3.app.SimpleApplication;\r\nimpor", "end": 241, "score": 0.9386710524559021, "start": 235, "tag": "NAME", "value": "Hasini" } ]
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 hello3D.test; /** * * @author Hasini */ import com.jme3.app.SimpleApplication; import com.jme3.material.Material; import com.jme3.scene.Geometry; import com.jme3.scene.shape.Box; import com.jme3.math.ColorRGBA; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.system.AppSettings; import com.jme3.system.JmeCanvasContext; import com.jme3.util.JmeFormatter; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.concurrent.Callable; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Logger; import javax.swing.*; import com.jme3.util.SkyFactory; import com.jme3.terrain.geomipmap.TerrainLodControl; import com.jme3.terrain.heightmap.AbstractHeightMap; import com.jme3.terrain.geomipmap.TerrainQuad; import com.jme3.terrain.geomipmap.lodcalc.DistanceLodCalculator; import com.jme3.terrain.heightmap.HillHeightMap; // for exercise 2 import com.jme3.terrain.heightmap.ImageBasedHeightMap; import com.jme3.texture.Texture; import com.jme3.texture.Texture.WrapMode; /** * Sample 1 - how to get started with the most simple JME 3 application. Display * a blue 3D cube and view from all sides by moving the mouse and pressing the * WASD keys. */ public class HelloWorld extends SimpleApplication { private TerrainQuad terrain; Material mat_terrain; @Override public void simpleInitApp() { viewPort.setBackgroundColor(ColorRGBA.Gray); cam.setLocation(new Vector3f(3.3212643f, 4.484704f, 4.2812433f)); cam.setRotation(new Quaternion(-0.07680723f, 0.92299235f, -0.2564353f, -0.27645364f)); /** * 1. Create terrain material and load four textures into it. */ mat_terrain = new Material(assetManager, "Common/MatDefs/Terrain/Terrain.j3md"); /** * 1.1) Add ALPHA map (for red-blue-green coded splat textures) */ mat_terrain.setTexture("Alpha", assetManager.loadTexture( "Textures/Terrain/splat/alphamap.png")); /** * 1.2) Add GRASS texture into the red layer (Tex1). */ Texture grass = assetManager.loadTexture( "Textures/Terrain/splat/grass.jpg"); //grass.setWrap(WrapMode.Repeat); mat_terrain.setTexture("Tex1", grass); mat_terrain.setFloat("Tex1Scale", 64f); /** * 1.3) Add DIRT texture into the green layer (Tex2) */ Texture dirt = assetManager.loadTexture( "Textures/Terrain/splat/dirt.jpg"); //dirt.setWrap(WrapMode.); mat_terrain.setTexture("Tex2", dirt); mat_terrain.setFloat("Tex2Scale", 32f); /** * 1.4) Add ROAD texture into the blue layer (Tex3) */ Texture rock = assetManager.loadTexture( "Textures/Terrain/splat/road.jpg"); //rock.setWrap(WrapMode.Repeat); mat_terrain.setTexture("Tex3", rock); mat_terrain.setFloat("Tex3Scale", 128f); /** * 2. Create the height map */ AbstractHeightMap heightmap = null; Texture heightMapImage = assetManager.loadTexture( "Textures/Terrain/splat/mountains512.png"); heightmap = new ImageBasedHeightMap(heightMapImage.getImage()); heightmap.load(); /** * 3. We have prepared material and heightmap. Now we create the actual * terrain: 3.1) Create a TerrainQuad and name it "my terrain". 3.2) A * good value for terrain tiles is 64x64 -- so we supply 64+1=65. 3.3) * We prepared a heightmap of size 512x512 -- so we supply 512+1=513. * 3.4) As LOD step scale we supply Vector3f(1,1,1). 3.5) We supply the * prepared heightmap itself. */ int patchSize = 257; terrain = new TerrainQuad("my terrain", patchSize, 257, heightmap.getHeightMap()); /** * 4. We give the terrain its material, position & scale it, and attach * it. */ terrain.setMaterial(mat_terrain); terrain.setLocalTranslation(0, -100, 0); terrain.setLocalScale(2f, 1f, 2f); rootNode.attachChild(terrain); /** * 5. The LOD (level of detail) depends on were the camera is: */ TerrainLodControl control = new TerrainLodControl(terrain, getCamera()); terrain.addControl(control); } public static void main(String[] args) { Swing swing = new Swing(); swing.swingHandler(new HelloWorld()); } }
5,110
0.6409
0.608219
145
33.241379
24.820536
94
false
false
0
0
0
0
0
0
0.648276
false
false
7
008a8330cddc334ae8cc00652d0c06a5f5838aeb
39,410,619,916,884
6b043d3c63b81ce9f4f624c9d4d4adf085364803
/src/com/Jarson/syn/ThreadSafe02.java
b99be945b5059e184a483e96e6311027d1481510
[]
no_license
codeJarson/Thread_study
https://github.com/codeJarson/Thread_study
a931b4c4a25f935ef15deb8859ba6d4523455234
0f4ef7e14533d06bf3a6688b4b7bde8345a7c890
refs/heads/master
2020-05-29T19:52:47.648000
2019-05-30T03:51:41
2019-05-30T03:51:41
189,341,851
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.Jarson.syn; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; /** * @author Jarson * @create 2019-05-26 20:43 */ /* 线程同步 synchronized (object) 同步块 作用: 使得当中object(任何对象)锁的对象更加明确,线程更安全 */ public class ThreadSafe02 { public static void main(String[] args) throws InterruptedException { List<String> list = new ArrayList<>(); for (int i = 0; i <1000; i++) { //循环创建线程 //lambda表达式 new Thread(()->{ synchronized(list){ list.add(Thread.currentThread().getName()); } }).start();//而start后的线程需要等待cpu取调度,所以需要时间 } //加上sleep的原因: 为了等待全部1000个线程执行完,才输出大小 Thread.sleep(2000); System.out.println(list.size()); } }
UTF-8
Java
1,012
java
ThreadSafe02.java
Java
[ { "context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author Jarson\n * @create 2019-05-26 20:43\n */\n/*\n 线程同步\n ", "end": 130, "score": 0.9995894432067871, "start": 124, "tag": "NAME", "value": "Jarson" } ]
null
[]
package com.Jarson.syn; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; /** * @author Jarson * @create 2019-05-26 20:43 */ /* 线程同步 synchronized (object) 同步块 作用: 使得当中object(任何对象)锁的对象更加明确,线程更安全 */ public class ThreadSafe02 { public static void main(String[] args) throws InterruptedException { List<String> list = new ArrayList<>(); for (int i = 0; i <1000; i++) { //循环创建线程 //lambda表达式 new Thread(()->{ synchronized(list){ list.add(Thread.currentThread().getName()); } }).start();//而start后的线程需要等待cpu取调度,所以需要时间 } //加上sleep的原因: 为了等待全部1000个线程执行完,才输出大小 Thread.sleep(2000); System.out.println(list.size()); } }
1,012
0.55119
0.519048
35
23
19.625057
72
false
false
0
0
0
0
0
0
0.314286
false
false
7
58503eb0d50fcd86424081b27a336f95649100e0
38,972,533,265,564
614580168b1fd1ebcf14059863764ff3d337e6ac
/src/com/thread/lesson6/c_6_1/MyObject.java
dcb3c54d208d1225b25d99eb8eba893901f4bc4c
[]
no_license
chenghaochen1993/thread-core
https://github.com/chenghaochen1993/thread-core
abcba5ac8a17771e6d224f6a91e0724ce04fb4f9
839881836665113b85709ff9cc0273952ccd767c
refs/heads/master
2021-09-13T21:07:44.999000
2018-05-04T06:27:26
2018-05-04T06:27:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.thread.lesson6.c_6_1; /** * Created by cch * 2018-04-24 10:12. */ public class MyObject { private static MyObject myObject = new MyObject(); private MyObject(){ } public static MyObject getInstance(){ //饿汉模式 //此代码缺点是不能有两个实例 //因为没有加同步可能出现非线程安全问题 return myObject; } }
UTF-8
Java
406
java
MyObject.java
Java
[ { "context": "ckage com.thread.lesson6.c_6_1;\n\n/**\n * Created by cch\n * 2018-04-24 10:12.\n */\n\npublic class MyObject {", "end": 56, "score": 0.9886476397514343, "start": 53, "tag": "USERNAME", "value": "cch" } ]
null
[]
package com.thread.lesson6.c_6_1; /** * Created by cch * 2018-04-24 10:12. */ public class MyObject { private static MyObject myObject = new MyObject(); private MyObject(){ } public static MyObject getInstance(){ //饿汉模式 //此代码缺点是不能有两个实例 //因为没有加同步可能出现非线程安全问题 return myObject; } }
406
0.607143
0.5625
19
16.68421
15.040481
54
false
false
0
0
0
0
0
0
0.157895
false
false
7
f4c3acdbd7d61284881ec4dc59cb3bef6744d5f3
36,687,610,685,661
b47ff426c237df22e01f272800841c72ee699893
/src/test/java/org/joda/primitives/list/impl/TestImmutableArrayByteList.java
7492ee14d171f972a99e58875fbe6dc5d37aac3d
[ "Apache-2.0" ]
permissive
mahmoudimus/joda-primitives
https://github.com/mahmoudimus/joda-primitives
9982c155201e26140dd4f9735c14f542944d9438
633d512728caa0bafd550810702899a2394c3c7b
refs/heads/master
2022-01-09T08:17:16.453000
2018-09-29T09:08:21
2018-09-29T09:08:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2001-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.primitives.list.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.joda.primitives.ByteUtils; import org.joda.primitives.iterator.ByteIterator; import org.joda.primitives.list.ByteList; /** * Tests for ImmutableArrayByteList. * * @author Stephen Colebourne * @version CODE GENERATED * @since 1.0 */ public class TestImmutableArrayByteList extends AbstractTestByteList { // This file is CODE GENERATED. Do not change manually. public TestImmutableArrayByteList(String name) { super(name); } //----------------------------------------------------------------------- public static void main(String[] args) { TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestImmutableArrayByteList.class); } //----------------------------------------------------------------------- public boolean isFailFastSupported() { return false; } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public boolean isSetSupported() { return false; } public List<Byte> makeEmptyList() { return ImmutableArrayByteList.empty(); } public List<Byte> makeFullList() { byte[] a = new byte[] {new Byte((byte)2),new Byte((byte)-2),new Byte((byte)38),new Byte((byte)0),new Byte((byte)126),new Byte((byte)202),new Byte(Byte.MIN_VALUE),new Byte(Byte.MAX_VALUE)}; return ImmutableArrayByteList.copyOf(a); } public List<Byte> makeConfirmedFullCollection() { byte[] a = new byte[] {new Byte((byte)2),new Byte((byte)-2),new Byte((byte)38),new Byte((byte)0),new Byte((byte)126),new Byte((byte)202),new Byte(Byte.MIN_VALUE),new Byte(Byte.MAX_VALUE)}; return ImmutableArrayByteList.copyOf(a); } public Object[] getFullElements() { byte[] a = new byte[] {new Byte((byte)2),new Byte((byte)-2),new Byte((byte)38),new Byte((byte)0),new Byte((byte)126),new Byte((byte)202),new Byte(Byte.MIN_VALUE),new Byte(Byte.MAX_VALUE)}; Object[] objs = new Object[a.length]; for (int i = 0; i < a.length; i++) { objs[i] = ByteUtils.toObject(a[i]); } return objs; } //----------------------------------------------------------------------- public void testUnsupportedAdd() { try { makeEmptyList().add((byte) 0); } catch (UnsupportedOperationException ex) { } } public void testUnsupportedSet() { try { makeEmptyList().set(0, (byte) 0); } catch (UnsupportedOperationException ex) { } } //----------------------------------------------------------------------- public void testConstructor() throws Exception { ImmutableArrayByteList c = ImmutableArrayByteList.empty(); assertEquals(0, c.size()); } public void testConstructor_array() throws Exception { byte[] a = new byte[] {new Byte((byte)2),new Byte((byte)-2),new Byte((byte)38),new Byte((byte)0),new Byte((byte)126),new Byte((byte)202),new Byte(Byte.MIN_VALUE),new Byte(Byte.MAX_VALUE)}; ImmutableArrayByteList c = ImmutableArrayByteList.copyOf(a); assertEquals(a.length, c.size()); assertEquals(true, Arrays.equals(c.toByteArray(), a)); c = ImmutableArrayByteList.copyOf((byte[]) null); assertEquals(0, c.size()); } public void testConstructor_Collection() throws Exception { ImmutableArrayByteList c = ImmutableArrayByteList.copyOf((Collection<Byte>) null); assertEquals(0, c.size()); Collection<Byte> coll = new ArrayList<Byte>(); coll.add((byte) 0); c = ImmutableArrayByteList.copyOf(coll); assertEquals(1, c.size()); assertEquals((byte) 0, c.iterator().nextByte()); ImmutableArrayByteList c2 = ImmutableArrayByteList.copyOf(c); assertSame(c, c2); } public void testIteratorIsNotModifiable() throws Exception { byte[] a = new byte[] {new Byte((byte)2),new Byte((byte)-2),new Byte((byte)38),new Byte((byte)0),new Byte((byte)126),new Byte((byte)202),new Byte(Byte.MIN_VALUE),new Byte(Byte.MAX_VALUE)}; ImmutableArrayByteList c = ImmutableArrayByteList.copyOf(a); assertEquals(false, c.iterator().isModifiable()); } public void testIteratorReset() throws Exception { byte[] a = new byte[] {(byte) 0, (byte) 6, (byte) 2}; ImmutableArrayByteList c = ImmutableArrayByteList.copyOf(a); ByteIterator it = c.iterator(); assertEquals(true, it.isResettable()); assertEquals((byte) 0, it.nextByte()); assertEquals((byte) 6, it.nextByte()); it.reset(); assertEquals((byte) 0, it.nextByte()); assertEquals((byte) 6, it.nextByte()); } //----------------------------------------------------------------------- public void testClone() { resetFull(); ByteList coll = (ByteList) collection; ByteList coll2 = (ByteList) coll.clone(); assertTrue(coll == coll2); } }
UTF-8
Java
6,123
java
TestImmutableArrayByteList.java
Java
[ { "context": "/*\r\n * Copyright 2001-present Stephen Colebourne\r\n *\r\n * Licensed under the Apache License, Versi", "end": 49, "score": 0.9998793601989746, "start": 31, "tag": "NAME", "value": "Stephen Colebourne" }, { "context": " Tests for ImmutableArrayByteList.\r\n *\r\n * ...
null
[]
/* * Copyright 2001-present <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 org.joda.primitives.list.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.joda.primitives.ByteUtils; import org.joda.primitives.iterator.ByteIterator; import org.joda.primitives.list.ByteList; /** * Tests for ImmutableArrayByteList. * * @author <NAME> * @version CODE GENERATED * @since 1.0 */ public class TestImmutableArrayByteList extends AbstractTestByteList { // This file is CODE GENERATED. Do not change manually. public TestImmutableArrayByteList(String name) { super(name); } //----------------------------------------------------------------------- public static void main(String[] args) { TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestImmutableArrayByteList.class); } //----------------------------------------------------------------------- public boolean isFailFastSupported() { return false; } public boolean isAddSupported() { return false; } public boolean isRemoveSupported() { return false; } public boolean isSetSupported() { return false; } public List<Byte> makeEmptyList() { return ImmutableArrayByteList.empty(); } public List<Byte> makeFullList() { byte[] a = new byte[] {new Byte((byte)2),new Byte((byte)-2),new Byte((byte)38),new Byte((byte)0),new Byte((byte)126),new Byte((byte)202),new Byte(Byte.MIN_VALUE),new Byte(Byte.MAX_VALUE)}; return ImmutableArrayByteList.copyOf(a); } public List<Byte> makeConfirmedFullCollection() { byte[] a = new byte[] {new Byte((byte)2),new Byte((byte)-2),new Byte((byte)38),new Byte((byte)0),new Byte((byte)126),new Byte((byte)202),new Byte(Byte.MIN_VALUE),new Byte(Byte.MAX_VALUE)}; return ImmutableArrayByteList.copyOf(a); } public Object[] getFullElements() { byte[] a = new byte[] {new Byte((byte)2),new Byte((byte)-2),new Byte((byte)38),new Byte((byte)0),new Byte((byte)126),new Byte((byte)202),new Byte(Byte.MIN_VALUE),new Byte(Byte.MAX_VALUE)}; Object[] objs = new Object[a.length]; for (int i = 0; i < a.length; i++) { objs[i] = ByteUtils.toObject(a[i]); } return objs; } //----------------------------------------------------------------------- public void testUnsupportedAdd() { try { makeEmptyList().add((byte) 0); } catch (UnsupportedOperationException ex) { } } public void testUnsupportedSet() { try { makeEmptyList().set(0, (byte) 0); } catch (UnsupportedOperationException ex) { } } //----------------------------------------------------------------------- public void testConstructor() throws Exception { ImmutableArrayByteList c = ImmutableArrayByteList.empty(); assertEquals(0, c.size()); } public void testConstructor_array() throws Exception { byte[] a = new byte[] {new Byte((byte)2),new Byte((byte)-2),new Byte((byte)38),new Byte((byte)0),new Byte((byte)126),new Byte((byte)202),new Byte(Byte.MIN_VALUE),new Byte(Byte.MAX_VALUE)}; ImmutableArrayByteList c = ImmutableArrayByteList.copyOf(a); assertEquals(a.length, c.size()); assertEquals(true, Arrays.equals(c.toByteArray(), a)); c = ImmutableArrayByteList.copyOf((byte[]) null); assertEquals(0, c.size()); } public void testConstructor_Collection() throws Exception { ImmutableArrayByteList c = ImmutableArrayByteList.copyOf((Collection<Byte>) null); assertEquals(0, c.size()); Collection<Byte> coll = new ArrayList<Byte>(); coll.add((byte) 0); c = ImmutableArrayByteList.copyOf(coll); assertEquals(1, c.size()); assertEquals((byte) 0, c.iterator().nextByte()); ImmutableArrayByteList c2 = ImmutableArrayByteList.copyOf(c); assertSame(c, c2); } public void testIteratorIsNotModifiable() throws Exception { byte[] a = new byte[] {new Byte((byte)2),new Byte((byte)-2),new Byte((byte)38),new Byte((byte)0),new Byte((byte)126),new Byte((byte)202),new Byte(Byte.MIN_VALUE),new Byte(Byte.MAX_VALUE)}; ImmutableArrayByteList c = ImmutableArrayByteList.copyOf(a); assertEquals(false, c.iterator().isModifiable()); } public void testIteratorReset() throws Exception { byte[] a = new byte[] {(byte) 0, (byte) 6, (byte) 2}; ImmutableArrayByteList c = ImmutableArrayByteList.copyOf(a); ByteIterator it = c.iterator(); assertEquals(true, it.isResettable()); assertEquals((byte) 0, it.nextByte()); assertEquals((byte) 6, it.nextByte()); it.reset(); assertEquals((byte) 0, it.nextByte()); assertEquals((byte) 6, it.nextByte()); } //----------------------------------------------------------------------- public void testClone() { resetFull(); ByteList coll = (ByteList) collection; ByteList coll2 = (ByteList) coll.clone(); assertTrue(coll == coll2); } }
6,099
0.582394
0.568349
168
34.44643
37.306927
196
false
false
0
0
0
0
0
0
0.720238
false
false
7
738ff171e4a1db6b1c9eb4d524874426f86f4669
34,634,616,332,747
4aaa1fde3b286de94b82ef17400ef48cf112faf9
/LeviCCurve/app/src/main/java/com/tirivashe/levic_curve/Fractal.java
e29c3608958c97bbab7ec65d6abf4cfde5449b99
[]
no_license
Tirivashe/Java_AndroidStudioProjects
https://github.com/Tirivashe/Java_AndroidStudioProjects
be98cfe41cdf8f49842f8f82b505bf055881bb85
62a9aff1201c7a0206872fe4c09a7249f31f76e9
refs/heads/master
2022-02-20T20:27:58.303000
2019-09-05T14:59:44
2019-09-05T14:59:44
206,587,883
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tirivashe.levic_curve; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Color; public class Fractal { public void drawCCurve (Canvas canvas, float x1, float y1, float x2, float y2, int level){ Paint paint = new Paint(); paint.setColor(Color.rgb(255,0,0)); paint.setStrokeWidth(1); if (level == 0){ canvas.drawLine(x1, y1, x2, y2, paint); }else{ float xn = (x1 + x2)/2 + (y1 - y2)/2; float yn = (x2 - x1)/2 + (y1 + y2)/2; drawCCurve(canvas, x1, y1, xn, yn, level-1); drawCCurve(canvas, xn, yn, x2, y2, level-1); } } }
UTF-8
Java
687
java
Fractal.java
Java
[]
null
[]
package com.tirivashe.levic_curve; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Color; public class Fractal { public void drawCCurve (Canvas canvas, float x1, float y1, float x2, float y2, int level){ Paint paint = new Paint(); paint.setColor(Color.rgb(255,0,0)); paint.setStrokeWidth(1); if (level == 0){ canvas.drawLine(x1, y1, x2, y2, paint); }else{ float xn = (x1 + x2)/2 + (y1 - y2)/2; float yn = (x2 - x1)/2 + (y1 + y2)/2; drawCCurve(canvas, x1, y1, xn, yn, level-1); drawCCurve(canvas, xn, yn, x2, y2, level-1); } } }
687
0.569141
0.521106
23
28.869566
23.452642
94
false
false
0
0
0
0
0
0
1.434783
false
false
7
ca0a4b641c68de56d99d060fa0281ed712112ee6
15,633,680,979,136
a93c699e06220f5ab249b0abd2be9206425a265d
/src/Main.java
927898ffe6c96150cd32f2e3bbb8e76470ce18ca
[]
no_license
skyflocodes/Order-Display-json-Java-Final-Exam
https://github.com/skyflocodes/Order-Display-json-Java-Final-Exam
a3f397be389efe1c931fa701ec9fe3cb906eac4a
2df9e07bb37b714b58c6b4abd93d6c2e6a90c2f4
refs/heads/main
2023-01-24T05:06:45.216000
2020-12-10T21:07:15
2020-12-10T21:07:15
320,352,697
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//Sky Florence 1109038 2020-12-10 import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("Views/tableview.fxml")); Scene scene = new Scene(root); scene.getStylesheets().add(getClass().getResource("style/style.css").toExternalForm()); stage.setScene(scene); stage.setTitle("Customer List"); stage.show(); } }
UTF-8
Java
715
java
Main.java
Java
[]
null
[]
//Sky Florence 1109038 2020-12-10 import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("Views/tableview.fxml")); Scene scene = new Scene(root); scene.getStylesheets().add(getClass().getResource("style/style.css").toExternalForm()); stage.setScene(scene); stage.setTitle("Customer List"); stage.show(); } }
715
0.667133
0.646154
22
30.5
24.10347
95
false
false
0
0
0
0
0
0
0.545455
false
false
7
0ce43bc8b7ca433ad3cf05fe083b8c7fed01f640
29,875,792,523,998
e730fdc97df16e1a21b39d4ebd8c3fd7c9da6f94
/app/src/main/java/com/mateusz/grabarski/myshoppinglist/views/activities/dashboard/dialogs/GetShoppingListDialog.java
5fbce3b0c437d4a53abf4a13fb3173353436e6c3
[]
no_license
mgrabarski/ShoppingListFB
https://github.com/mgrabarski/ShoppingListFB
206d5a6bd7fcd6aa70846b2e17297289ee7820d4
02dfd59b762425d960bfa42fd0ede6b4a6a3e5e3
refs/heads/master
2021-09-15T07:36:04.376000
2018-05-28T16:50:57
2018-05-28T16:50:57
114,893,618
0
0
null
false
2018-01-09T13:32:12
2017-12-20T14:01:14
2017-12-20T14:01:47
2018-01-09T13:32:06
9,286
0
0
0
Java
false
null
package com.mateusz.grabarski.myshoppinglist.views.activities.dashboard.dialogs; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.TextInputLayout; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import com.mateusz.grabarski.myshoppinglist.R; import com.mateusz.grabarski.myshoppinglist.utils.InputValidator; /** * Created by Mateusz Grabarski on 09.01.2018. */ public class GetShoppingListDialog extends DialogFragment { private EditText mNameEt; private TextInputLayout mTextInputL; private GetShoppingListDialogInterface mListener; public static GetShoppingListDialog newInstance() { Bundle args = new Bundle(); GetShoppingListDialog fragment = new GetShoppingListDialog(); fragment.setArguments(args); return fragment; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof GetShoppingListDialogInterface) mListener = (GetShoppingListDialogInterface) context; else throw new RuntimeException("Activity must implement GetShoppingListDialogInterface"); } @Override public void onStart() { super.onStart(); AlertDialog alertDialog = (AlertDialog) getDialog(); if (alertDialog != null) { alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputValidator inputValidator = new InputValidator(); if (!inputValidator.isShoppingListNameValid(mNameEt.getText().toString())) { mTextInputL.setError(getString(R.string.empty_shopping_list_name_error)); } else { dismiss(); mListener.onShoppingListNameTyped(mNameEt.getText().toString()); } } }); } } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.shopping_list_name); View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_shopping_list_name, null); mNameEt = view.findViewById(R.id.dialog_shopping_list_name_et); mTextInputL = view.findViewById(R.id.dialog_shopping_list_name_til); builder.setView(view); builder.setPositiveButton(R.string.ok, null); return builder.create(); } public interface GetShoppingListDialogInterface { void onShoppingListNameTyped(String shoppingListName); } }
UTF-8
Java
2,994
java
GetShoppingListDialog.java
Java
[ { "context": "ppinglist.utils.InputValidator;\n\n/**\n * Created by Mateusz Grabarski on 09.01.2018.\n */\n\npublic class GetShoppingListD", "end": 637, "score": 0.9998325705528259, "start": 620, "tag": "NAME", "value": "Mateusz Grabarski" } ]
null
[]
package com.mateusz.grabarski.myshoppinglist.views.activities.dashboard.dialogs; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.TextInputLayout; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import com.mateusz.grabarski.myshoppinglist.R; import com.mateusz.grabarski.myshoppinglist.utils.InputValidator; /** * Created by <NAME> on 09.01.2018. */ public class GetShoppingListDialog extends DialogFragment { private EditText mNameEt; private TextInputLayout mTextInputL; private GetShoppingListDialogInterface mListener; public static GetShoppingListDialog newInstance() { Bundle args = new Bundle(); GetShoppingListDialog fragment = new GetShoppingListDialog(); fragment.setArguments(args); return fragment; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof GetShoppingListDialogInterface) mListener = (GetShoppingListDialogInterface) context; else throw new RuntimeException("Activity must implement GetShoppingListDialogInterface"); } @Override public void onStart() { super.onStart(); AlertDialog alertDialog = (AlertDialog) getDialog(); if (alertDialog != null) { alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InputValidator inputValidator = new InputValidator(); if (!inputValidator.isShoppingListNameValid(mNameEt.getText().toString())) { mTextInputL.setError(getString(R.string.empty_shopping_list_name_error)); } else { dismiss(); mListener.onShoppingListNameTyped(mNameEt.getText().toString()); } } }); } } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.shopping_list_name); View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_shopping_list_name, null); mNameEt = view.findViewById(R.id.dialog_shopping_list_name_et); mTextInputL = view.findViewById(R.id.dialog_shopping_list_name_til); builder.setView(view); builder.setPositiveButton(R.string.ok, null); return builder.create(); } public interface GetShoppingListDialogInterface { void onShoppingListNameTyped(String shoppingListName); } }
2,983
0.681697
0.678357
93
31.193548
29.565767
110
false
false
0
0
0
0
0
0
0.451613
false
false
7
585c72edd95cb0f5ca5546d8dc92485e2b65a677
20,873,541,078,533
684732efc4909172df38ded729c0972349c58b67
/doc/src/main/java/net/sf/ahtutils/doc/loc/counter/MatlabCounter.java
c7ba14e7f9580c901eb74315cd54f5869304e1bb
[]
no_license
aht-group/jeesl
https://github.com/aht-group/jeesl
2c4683e8c1e9d9e9698d044c6a89a611b8dfe1e7
3f4bfca6cf33f60549cac23f3b90bf1218c9daf9
refs/heads/master
2023-08-13T20:06:38.593000
2023-08-12T06:59:51
2023-08-12T06:59:51
39,823,889
0
9
null
false
2022-12-13T18:35:24
2015-07-28T09:06:11
2022-01-07T14:59:23
2022-12-13T18:35:22
32,965
0
6
18
Java
false
false
/* * MatlabCounter.java * * Created on May 07, 2006, 9:48 AM * */ package net.sf.ahtutils.doc.loc.counter; import java.io.File; /* * An implementation of ILineCounter which can be used to process Matlab * source files. * @author Ekkehard Blanz */ public class MatlabCounter extends SimpleCounter implements LineCounter { /* Creates a new instance of MatlabCounter */ public MatlabCounter(File f) { super(f, "%"); } }
UTF-8
Java
454
java
MatlabCounter.java
Java
[ { "context": "used to process Matlab\n * source files.\n * @author Ekkehard Blanz\n */\npublic class MatlabCounter extends SimpleCoun", "end": 254, "score": 0.9998696446418762, "start": 240, "tag": "NAME", "value": "Ekkehard Blanz" } ]
null
[]
/* * MatlabCounter.java * * Created on May 07, 2006, 9:48 AM * */ package net.sf.ahtutils.doc.loc.counter; import java.io.File; /* * An implementation of ILineCounter which can be used to process Matlab * source files. * @author <NAME> */ public class MatlabCounter extends SimpleCounter implements LineCounter { /* Creates a new instance of MatlabCounter */ public MatlabCounter(File f) { super(f, "%"); } }
446
0.676211
0.656388
23
18.73913
21.968786
73
false
false
0
0
0
0
0
0
0.26087
false
false
7
f01cd898e4a51ace789000a0e47e83ad6bc5e1f9
28,759,101,052,890
1df85780bb4f20f1a39e1d8930493e97ff003e5e
/app/src/main/java/com/ladddd/myandroidarch/ui/activity/CollapseBarActivity.java
3e6af95922647cff7b629ae2904e913489c0d1c8
[]
no_license
ladddd/MyAndroidArch
https://github.com/ladddd/MyAndroidArch
fe9d6f3b5b4567d65a311b5f99312e179a6436a0
d76c45cec5b577d9635ab3d1188b7d278c7d002f
refs/heads/master
2021-01-17T21:12:04.238000
2017-11-30T07:27:25
2017-11-30T07:27:25
84,165,675
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ladddd.myandroidarch.ui.activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.ImageView; import com.bilibili.magicasakura.utils.ThemeUtils; import com.bumptech.glide.Glide; import com.ladddd.myandroidarch.R; import com.ladddd.myandroidarch.ui.adapter.TestAdapter; import com.ladddd.myandroidarch.utils.ThemeHelper; import com.ladddd.mylib.BaseActivity; import com.ladddd.mylib.config.AppConfig; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; /** * Created by 陈伟达 on 2017/7/4. */ public class CollapseBarActivity extends BaseActivity { @BindView(R.id.recycler) RecyclerView recycler; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.iv_header) ImageView iv_header; @BindView(R.id.collapsing_tool_bar) CollapsingToolbarLayout mCollapsingToolbarLayout; @OnClick(R.id.ib_change_theme) void goToChangeTheme() { ThemeActivity.launch(this); } TestAdapter adapter; public static void launch(Context context) { Intent intent = new Intent(context, CollapseBarActivity.class); context.startActivity(intent); } @Override protected void initView() { setContentView(R.layout.activity_collapse_bar); ButterKnife.bind(this); toolbar.setTitleTextColor(Color.WHITE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); window.setStatusBarColor(Color.TRANSPARENT); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4-5.0 WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes(); localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags); } Glide.with(AppConfig.getContext()) .load("https://c1.hoopchina.com.cn/uploads/star/event/images/170704/bmiddle-32494065ec92312c17b894158e242d532397960e.jpg?x-oss-process=image/resize,w_800/format,webp") .asBitmap() .placeholder(R.drawable.default_image) .error(R.drawable.default_image) .into(iv_header); mCollapsingToolbarLayout.setStatusBarScrimColor(ThemeUtils.getColorById(CollapseBarActivity.this, R.color.theme_color_primary_dark)); mCollapsingToolbarLayout.setContentScrimColor(ThemeUtils.getColorById(CollapseBarActivity.this, R.color.theme_color_primary)); } @Override protected void initData() { recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); recycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); recycler.setNestedScrollingEnabled(true); adapter = new TestAdapter(); recycler.setAdapter(adapter); Observable.create(new ObservableOnSubscribe<List<Integer>>() { @Override public void subscribe(ObservableEmitter<List<Integer>> e) throws Exception { List<Integer> testList = new ArrayList<>(); for (int i = 0; i < 100; i++) { testList.add(i); } e.onNext(testList); e.onComplete(); } }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<Integer>>() { @Override public void accept(List<Integer> integers) throws Exception { adapter.setNewData(integers); } }); } protected void initSubscription() { } }
UTF-8
Java
4,655
java
CollapseBarActivity.java
Java
[ { "context": "activex.schedulers.Schedulers;\n\n/**\n * Created by 陈伟达 on 2017/7/4.\n */\n\npublic class CollapseBarActivit", "end": 1310, "score": 0.9997220635414124, "start": 1307, "tag": "NAME", "value": "陈伟达" } ]
null
[]
package com.ladddd.myandroidarch.ui.activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.ImageView; import com.bilibili.magicasakura.utils.ThemeUtils; import com.bumptech.glide.Glide; import com.ladddd.myandroidarch.R; import com.ladddd.myandroidarch.ui.adapter.TestAdapter; import com.ladddd.myandroidarch.utils.ThemeHelper; import com.ladddd.mylib.BaseActivity; import com.ladddd.mylib.config.AppConfig; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; /** * Created by 陈伟达 on 2017/7/4. */ public class CollapseBarActivity extends BaseActivity { @BindView(R.id.recycler) RecyclerView recycler; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.iv_header) ImageView iv_header; @BindView(R.id.collapsing_tool_bar) CollapsingToolbarLayout mCollapsingToolbarLayout; @OnClick(R.id.ib_change_theme) void goToChangeTheme() { ThemeActivity.launch(this); } TestAdapter adapter; public static void launch(Context context) { Intent intent = new Intent(context, CollapseBarActivity.class); context.startActivity(intent); } @Override protected void initView() { setContentView(R.layout.activity_collapse_bar); ButterKnife.bind(this); toolbar.setTitleTextColor(Color.WHITE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); window.setStatusBarColor(Color.TRANSPARENT); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4-5.0 WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes(); localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags); } Glide.with(AppConfig.getContext()) .load("https://c1.hoopchina.com.cn/uploads/star/event/images/170704/bmiddle-32494065ec92312c17b894158e242d532397960e.jpg?x-oss-process=image/resize,w_800/format,webp") .asBitmap() .placeholder(R.drawable.default_image) .error(R.drawable.default_image) .into(iv_header); mCollapsingToolbarLayout.setStatusBarScrimColor(ThemeUtils.getColorById(CollapseBarActivity.this, R.color.theme_color_primary_dark)); mCollapsingToolbarLayout.setContentScrimColor(ThemeUtils.getColorById(CollapseBarActivity.this, R.color.theme_color_primary)); } @Override protected void initData() { recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); recycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); recycler.setNestedScrollingEnabled(true); adapter = new TestAdapter(); recycler.setAdapter(adapter); Observable.create(new ObservableOnSubscribe<List<Integer>>() { @Override public void subscribe(ObservableEmitter<List<Integer>> e) throws Exception { List<Integer> testList = new ArrayList<>(); for (int i = 0; i < 100; i++) { testList.add(i); } e.onNext(testList); e.onComplete(); } }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<Integer>>() { @Override public void accept(List<Integer> integers) throws Exception { adapter.setNewData(integers); } }); } protected void initSubscription() { } }
4,655
0.708109
0.694988
123
36.796749
32.533401
183
false
false
0
0
0
0
0
0
0.617886
false
false
7
79d6fa3ba3d531b7ec353f41876e37486b790685
35,794,257,451,820
1ef7a758aeddbca8f31a233cb723544062af8fbe
/src/piano/Server/PianoServer.java
a014e04ccdf0dfb46141d76b1b927beddcb9f73f
[]
no_license
rei2hu/cmdPiano
https://github.com/rei2hu/cmdPiano
46a2c42f73203ba8f16c322d40c4047222874864
1c41fa00d7c648032d90716b06038d941d6da513
refs/heads/master
2020-12-24T13:44:29.074000
2016-04-12T21:04:00
2016-04-12T21:04:00
37,402,984
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 piano.Server; /** * * @author Thomas * Main reference(s): https://www.youtube.com/watch?v=1a3TtPr_yvI Running: @echo off echo Server or client (s/c)? set /p var= if '%var%' == 's' goto Server if '%var%' == 'c' goto Client echo that's not a choice pause exit :Server java -cp Piano(noip).jar piano.PianoServer :Client java -cp Piano(noip).jar piano.PianoClient */ import java.io.*; import java.net.*; import java.util.Random; public class PianoServer { static ServerSocket serverSocket; static Socket socket; static DataOutputStream out; static Users[] user = new Users[10]; //max users 10 static DataInputStream in; public static void main(String[] args)throws Exception{ Random rand = new Random(); //get ip URL myip = new URL("http://checkip.amazonaws.com"); BufferedReader inBR = new BufferedReader(new InputStreamReader( myip.openStream())); String ip = inBR.readLine(); //start server System.out.println("Starting server on " + ip + ":7777"); try{ serverSocket = new ServerSocket(7777); }catch(IOException e){ System.out.println("Could not start server!"); System.in.read(); System.exit(0); } System.out.println("Server started!"); //constantly check for connections while(true){ boolean allowConnect = true; //wait for client to connect socket = serverSocket.accept(); System.out.println("Client Connected (" + socket.getInetAddress() + ") "); //check ip ban list try (BufferedReader br = new BufferedReader(new FileReader("ipban.txt"))) { String line; while ((line = br.readLine()) != null) { if(socket.getInetAddress().toString().equals(line)){ System.out.println("This ip is banned!"); allowConnect = false; } } } if(allowConnect){ while(true){ //PROBABLY NOT BEST WAY TO DO IT int i = rand.nextInt(10); System.out.println(i); if (user[i] == null){ out = new DataOutputStream(socket.getOutputStream()); in = new DataInputStream(socket.getInputStream()); user[i] = new Users(out, in, user, i); Thread thread = new Thread(user[i]); thread.start(); break; } } } } } }
UTF-8
Java
3,139
java
PianoServer.java
Java
[ { "context": "\n */\r\npackage piano.Server;\r\n\r\n/**\r\n *\r\n * @author Thomas\r\n * Main reference(s): https://www.youtube.com/wa", "end": 241, "score": 0.9987479448318481, "start": 235, "tag": "NAME", "value": "Thomas" } ]
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 piano.Server; /** * * @author Thomas * Main reference(s): https://www.youtube.com/watch?v=1a3TtPr_yvI Running: @echo off echo Server or client (s/c)? set /p var= if '%var%' == 's' goto Server if '%var%' == 'c' goto Client echo that's not a choice pause exit :Server java -cp Piano(noip).jar piano.PianoServer :Client java -cp Piano(noip).jar piano.PianoClient */ import java.io.*; import java.net.*; import java.util.Random; public class PianoServer { static ServerSocket serverSocket; static Socket socket; static DataOutputStream out; static Users[] user = new Users[10]; //max users 10 static DataInputStream in; public static void main(String[] args)throws Exception{ Random rand = new Random(); //get ip URL myip = new URL("http://checkip.amazonaws.com"); BufferedReader inBR = new BufferedReader(new InputStreamReader( myip.openStream())); String ip = inBR.readLine(); //start server System.out.println("Starting server on " + ip + ":7777"); try{ serverSocket = new ServerSocket(7777); }catch(IOException e){ System.out.println("Could not start server!"); System.in.read(); System.exit(0); } System.out.println("Server started!"); //constantly check for connections while(true){ boolean allowConnect = true; //wait for client to connect socket = serverSocket.accept(); System.out.println("Client Connected (" + socket.getInetAddress() + ") "); //check ip ban list try (BufferedReader br = new BufferedReader(new FileReader("ipban.txt"))) { String line; while ((line = br.readLine()) != null) { if(socket.getInetAddress().toString().equals(line)){ System.out.println("This ip is banned!"); allowConnect = false; } } } if(allowConnect){ while(true){ //PROBABLY NOT BEST WAY TO DO IT int i = rand.nextInt(10); System.out.println(i); if (user[i] == null){ out = new DataOutputStream(socket.getOutputStream()); in = new DataInputStream(socket.getInputStream()); user[i] = new Users(out, in, user, i); Thread thread = new Thread(user[i]); thread.start(); break; } } } } } }
3,139
0.498248
0.492832
105
27.87619
22.670179
87
false
false
0
0
0
0
0
0
0.371429
false
false
7
45129c44a422c230cea282aa4f558bb1ff839f56
35,510,789,615,375
64b9907a37a6b879947ee20121701534a1d9d16a
/src/test/java/therookies/thanhliem/fresh_foods/service/impl/PaymentServiceTest.java
beea065c64d6fb30461dc746abae7f0f0808ce1e
[]
no_license
ThanhLiemm/Fresh_Food_API
https://github.com/ThanhLiemm/Fresh_Food_API
caf8ba53d9f4d405fc5636d8b474516fc5567ec8
85b187038eb08bbaf8359c1fd43f12b7750156c1
refs/heads/main
2023-07-20T11:23:25.489000
2021-08-30T13:53:05
2021-08-30T13:53:05
381,043,960
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package therookies.thanhliem.fresh_foods.service.impl; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; import therookies.thanhliem.fresh_foods.dto.PaymentDTO; import therookies.thanhliem.fresh_foods.entity.OrderEntity; import therookies.thanhliem.fresh_foods.entity.PaymentEntity; import therookies.thanhliem.fresh_foods.exception.CanNotChangeDB; import therookies.thanhliem.fresh_foods.exception.IdNotFoundException; import therookies.thanhliem.fresh_foods.repository.PaymentRepository; @SpringBootTest class PaymentServiceTest { @Autowired PaymentService service; @Autowired ModelMapper mapper; @MockBean PaymentRepository repository; private static final List<PaymentEntity> listPayment = new ArrayList<>(); @BeforeAll public static void init() { PaymentEntity payment1 = new PaymentEntity(1L,"Thanh toan truc tuyen", "",new ArrayList<>()); PaymentEntity payment2 = new PaymentEntity(2L,"Thanh toan tk ngan hang", "", Stream.of(new OrderEntity()).collect(Collectors.toList())); listPayment.add(payment1); listPayment.add(payment2); } @Test void save() { when(repository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); when(repository.save(Mockito.anyObject())).thenReturn(listPayment.get(0)); PaymentDTO dto = mapper.map(listPayment.get(0),PaymentDTO.class); assertEquals(dto.getName(),service.save(dto).getName()); assertEquals(dto.getId(),service.save(dto).getId()); } @Test void Update() { PaymentEntity paymentOld = new PaymentEntity(1L,"Thanh Toan MoMo", "",null); PaymentEntity paymentNew = new PaymentEntity(100L,"Thanh Toan Bang The", "",null); PaymentEntity paymentUpdate = new PaymentEntity(1L,"Thanh Toan Bang The","",null); when(repository.findById(Mockito.anyLong())).thenReturn(Optional.of(paymentOld)); when(repository.save(paymentUpdate)).thenReturn(paymentUpdate); PaymentDTO dto = mapper.map(paymentNew,PaymentDTO.class); assertEquals(1L,service.save(dto).getId()); //old assertEquals("Thanh Toan Bang The",service.save(dto).getName()); } @Test void getById_Success() { when(repository.findById(Mockito.anyLong())).thenReturn(Optional.of(listPayment.get(0))); assertEquals(1L,service.getById(Mockito.anyLong()).getId()); assertEquals("Thanh toan truc tuyen",service.getById(Mockito.anyLong()).getName()); } @Test void getById_Fail() { when(repository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); Exception exception = assertThrows(IdNotFoundException.class,()-> service.getById(Mockito.anyLong())); String expectedMessage = "Can not found "; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); } @Test void getAll() { when(repository.findAll()).thenReturn(listPayment); assertEquals(2,service.getAll().size()); } @Test void delete_Success() { when(repository.existsById(Mockito.anyLong())).thenReturn(true); when(repository.getById(Mockito.anyLong())).thenReturn(listPayment.get(0)); Map<String,String> respone = new HashMap<>(); respone.put("Status","Success"); assertEquals(respone,service.delete(Mockito.anyLong())); } @Test void delete_Fail() { when(repository.existsById(Mockito.anyLong())).thenReturn(false); Exception exception = assertThrows(IdNotFoundException.class,()-> service.delete(Mockito.anyLong())); String expectedMessage = "Can not found "; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); } @Test void delete_HaveOrder() { when(repository.existsById(Mockito.anyLong())).thenReturn(true); when(repository.getById(Mockito.anyLong())).thenReturn(listPayment.get(1)); Exception exception = assertThrows(CanNotChangeDB.class,()-> service.delete(1L)); String expectedMessage = "Payment had order"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); } }
UTF-8
Java
4,786
java
PaymentServiceTest.java
Java
[ { "context": " PaymentEntity paymentOld = new PaymentEntity(1L,\"Thanh Toan MoMo\", \"\",null);\n PaymentEntity paymentNew = ne", "end": 2092, "score": 0.5954570770263672, "start": 2077, "tag": "NAME", "value": "Thanh Toan MoMo" }, { "context": "tEntity paymentNew = new Paymen...
null
[]
package therookies.thanhliem.fresh_foods.service.impl; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; import therookies.thanhliem.fresh_foods.dto.PaymentDTO; import therookies.thanhliem.fresh_foods.entity.OrderEntity; import therookies.thanhliem.fresh_foods.entity.PaymentEntity; import therookies.thanhliem.fresh_foods.exception.CanNotChangeDB; import therookies.thanhliem.fresh_foods.exception.IdNotFoundException; import therookies.thanhliem.fresh_foods.repository.PaymentRepository; @SpringBootTest class PaymentServiceTest { @Autowired PaymentService service; @Autowired ModelMapper mapper; @MockBean PaymentRepository repository; private static final List<PaymentEntity> listPayment = new ArrayList<>(); @BeforeAll public static void init() { PaymentEntity payment1 = new PaymentEntity(1L,"Thanh toan truc tuyen", "",new ArrayList<>()); PaymentEntity payment2 = new PaymentEntity(2L,"Thanh toan tk ngan hang", "", Stream.of(new OrderEntity()).collect(Collectors.toList())); listPayment.add(payment1); listPayment.add(payment2); } @Test void save() { when(repository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); when(repository.save(Mockito.anyObject())).thenReturn(listPayment.get(0)); PaymentDTO dto = mapper.map(listPayment.get(0),PaymentDTO.class); assertEquals(dto.getName(),service.save(dto).getName()); assertEquals(dto.getId(),service.save(dto).getId()); } @Test void Update() { PaymentEntity paymentOld = new PaymentEntity(1L,"<NAME>", "",null); PaymentEntity paymentNew = new PaymentEntity(100L,"Thanh Toan Bang The", "",null); PaymentEntity paymentUpdate = new PaymentEntity(1L,"Thanh Toan Bang The","",null); when(repository.findById(Mockito.anyLong())).thenReturn(Optional.of(paymentOld)); when(repository.save(paymentUpdate)).thenReturn(paymentUpdate); PaymentDTO dto = mapper.map(paymentNew,PaymentDTO.class); assertEquals(1L,service.save(dto).getId()); //old assertEquals("Thanh Toan Bang The",service.save(dto).getName()); } @Test void getById_Success() { when(repository.findById(Mockito.anyLong())).thenReturn(Optional.of(listPayment.get(0))); assertEquals(1L,service.getById(Mockito.anyLong()).getId()); assertEquals("Thanh toan truc tuyen",service.getById(Mockito.anyLong()).getName()); } @Test void getById_Fail() { when(repository.findById(Mockito.anyLong())).thenReturn(Optional.empty()); Exception exception = assertThrows(IdNotFoundException.class,()-> service.getById(Mockito.anyLong())); String expectedMessage = "Can not found "; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); } @Test void getAll() { when(repository.findAll()).thenReturn(listPayment); assertEquals(2,service.getAll().size()); } @Test void delete_Success() { when(repository.existsById(Mockito.anyLong())).thenReturn(true); when(repository.getById(Mockito.anyLong())).thenReturn(listPayment.get(0)); Map<String,String> respone = new HashMap<>(); respone.put("Status","Success"); assertEquals(respone,service.delete(Mockito.anyLong())); } @Test void delete_Fail() { when(repository.existsById(Mockito.anyLong())).thenReturn(false); Exception exception = assertThrows(IdNotFoundException.class,()-> service.delete(Mockito.anyLong())); String expectedMessage = "Can not found "; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); } @Test void delete_HaveOrder() { when(repository.existsById(Mockito.anyLong())).thenReturn(true); when(repository.getById(Mockito.anyLong())).thenReturn(listPayment.get(1)); Exception exception = assertThrows(CanNotChangeDB.class,()-> service.delete(1L)); String expectedMessage = "Payment had order"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); } }
4,777
0.696824
0.692645
129
36.108528
30.513496
101
false
false
0
0
0
0
0
0
0.744186
false
false
7
64b5d85ce1b88ca9e3f30c4b312e47a9a8549ba4
17,815,524,400,217
791cd4061e1358ec1c5174d13d93a2d4e9543772
/paymentOut/src/com/jrwp/core/help/QueryInfo.java
66d7f498c22f9edda228a36973782468d4842da7
[]
no_license
zhlxs/HslRep
https://github.com/zhlxs/HslRep
a0c0618cca25f85142a726ccfc3a9fc68b6fe002
aabc1a9a9605452be5960d2da70f320d31b8e543
refs/heads/master
2020-04-26T03:25:55.419000
2019-03-11T12:26:37
2019-03-11T12:26:37
173,267,064
0
0
null
false
2019-03-11T12:25:15
2019-03-01T08:45:34
2019-03-01T08:55:17
2019-03-11T12:25:14
0
0
0
0
null
false
null
package com.jrwp.core.help; import java.util.List; import java.util.Map; public class QueryInfo { private Map<String, String> selectFields; private List<WhereInfo> whereInfos; private List<FormTable> formTables; private Map<String, String> orderInfos; public Map<String, String> getSelectFields() { return selectFields; } public void setSelectFields(Map<String, String> selectFields) { this.selectFields = selectFields; } public List<WhereInfo> getWhereInfos() { return whereInfos; } public void setWhereInfos(List<WhereInfo> whereInfos) { this.whereInfos = whereInfos; } public List<FormTable> getFormTables() { return formTables; } public void setFormTables(List<FormTable> formTables) { this.formTables = formTables; } public Map<String, String> getOrderInfos() { return orderInfos; } public void setOrderInfos(Map<String, String> orderInfos) { this.orderInfos = orderInfos; } }
UTF-8
Java
929
java
QueryInfo.java
Java
[]
null
[]
package com.jrwp.core.help; import java.util.List; import java.util.Map; public class QueryInfo { private Map<String, String> selectFields; private List<WhereInfo> whereInfos; private List<FormTable> formTables; private Map<String, String> orderInfos; public Map<String, String> getSelectFields() { return selectFields; } public void setSelectFields(Map<String, String> selectFields) { this.selectFields = selectFields; } public List<WhereInfo> getWhereInfos() { return whereInfos; } public void setWhereInfos(List<WhereInfo> whereInfos) { this.whereInfos = whereInfos; } public List<FormTable> getFormTables() { return formTables; } public void setFormTables(List<FormTable> formTables) { this.formTables = formTables; } public Map<String, String> getOrderInfos() { return orderInfos; } public void setOrderInfos(Map<String, String> orderInfos) { this.orderInfos = orderInfos; } }
929
0.748116
0.748116
44
20.113636
20.098866
64
false
false
0
0
0
0
0
0
1.295455
false
false
7
1f1fbf77314e3d98c106ad76b0e6dee59101775e
1,786,706,448,634
644fcdaaacee7708c045162071d336ae52eeaa26
/14-regex/Main.java
3f377d264c89cd15a25b381d33519184c93d2f10
[]
no_license
sesteves/algos
https://github.com/sesteves/algos
d55e5f3bc154f3224d8c6a06686dd4cce0339dca
ea43711c9963941fce981820bb76aa460bd6acd5
refs/heads/master
2020-06-02T06:20:12.704000
2017-09-11T00:24:57
2017-09-11T00:24:57
16,813,068
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// a..z * ? public class Main { private static boolean match(String pattern, String text) { for(int i = 0; i < text.length(); i++) { if(pattern.charAt(0) == '*') { if(pattern.length() == 1 || match(pattern.substring(1), text.substring(i))) return true; } else if(pattern.length() > 1 && pattern.charAt(1) == '?') { if(pattern.length() == 2) return true; if(pattern.charAt(0) == text.charAt(i) && matchSequential(pattern.substring(2), text.substring(i + 1))) return true; if(matchSequential(pattern.substring(2), text.substring(i))) return true; } else if(pattern.charAt(0) == text.charAt(i)) { if(pattern.length() == 1 || matchSequential(pattern.substring(1), text.substring(i + 1))) return true; } } return false; } private static boolean matchSequential(String pattern, String text) { // System.out.println("Pattern: " + pattern + ", text: " + text); if(pattern.charAt(0) == '*') { if(pattern.length() == 1 || match(pattern.substring(1), text)) return true; } else if(pattern.length() > 1 && pattern.charAt(1) == '?') { if(pattern.length() == 2) return true; if(pattern.charAt(0) == text.charAt(0) && matchSequential(pattern.substring(2), text.substring(1))) return true; if(matchSequential(pattern.substring(2), text.substring(0))) return true; } else if(pattern.charAt(0) == text.charAt(0)) { if(pattern.length() == 1 || matchSequential(pattern.substring(1), text.substring(1))) return true; } return false; } public static void main(String[] args) { System.out.println("abc abc " + match("abc", "abc")); System.out.println("c abc " + match("c", "abc")); System.out.println("ab abc " + match("ab", "abc")); // System.out.println("abcd abc " + match("abcd", "abc")); System.out.println("a?c abc " + match("a?c", "abc")); System.out.println("a?c ac " + match("a?c", "ac")); System.out.println("a?ac aaac " + match("a?ac", "aaac")); System.out.println("a*bc abcd " + match("a*bc", "abcd")); System.out.println("a*e abcd " + match("a*e", "abcd")); System.out.println("aaa*aaabc* aaaaaaaabc " + match("aaa*aaabc*", "aaaaaaaabc")); System.out.println("bb?*d* bbbe " + match("bb?*d*", "bbbe")); } }
UTF-8
Java
2,498
java
Main.java
Java
[]
null
[]
// a..z * ? public class Main { private static boolean match(String pattern, String text) { for(int i = 0; i < text.length(); i++) { if(pattern.charAt(0) == '*') { if(pattern.length() == 1 || match(pattern.substring(1), text.substring(i))) return true; } else if(pattern.length() > 1 && pattern.charAt(1) == '?') { if(pattern.length() == 2) return true; if(pattern.charAt(0) == text.charAt(i) && matchSequential(pattern.substring(2), text.substring(i + 1))) return true; if(matchSequential(pattern.substring(2), text.substring(i))) return true; } else if(pattern.charAt(0) == text.charAt(i)) { if(pattern.length() == 1 || matchSequential(pattern.substring(1), text.substring(i + 1))) return true; } } return false; } private static boolean matchSequential(String pattern, String text) { // System.out.println("Pattern: " + pattern + ", text: " + text); if(pattern.charAt(0) == '*') { if(pattern.length() == 1 || match(pattern.substring(1), text)) return true; } else if(pattern.length() > 1 && pattern.charAt(1) == '?') { if(pattern.length() == 2) return true; if(pattern.charAt(0) == text.charAt(0) && matchSequential(pattern.substring(2), text.substring(1))) return true; if(matchSequential(pattern.substring(2), text.substring(0))) return true; } else if(pattern.charAt(0) == text.charAt(0)) { if(pattern.length() == 1 || matchSequential(pattern.substring(1), text.substring(1))) return true; } return false; } public static void main(String[] args) { System.out.println("abc abc " + match("abc", "abc")); System.out.println("c abc " + match("c", "abc")); System.out.println("ab abc " + match("ab", "abc")); // System.out.println("abcd abc " + match("abcd", "abc")); System.out.println("a?c abc " + match("a?c", "abc")); System.out.println("a?c ac " + match("a?c", "ac")); System.out.println("a?ac aaac " + match("a?ac", "aaac")); System.out.println("a*bc abcd " + match("a*bc", "abcd")); System.out.println("a*e abcd " + match("a*e", "abcd")); System.out.println("aaa*aaabc* aaaaaaaabc " + match("aaa*aaabc*", "aaaaaaaabc")); System.out.println("bb?*d* bbbe " + match("bb?*d*", "bbbe")); } }
2,498
0.549239
0.536429
91
26.45055
30.436121
111
false
false
0
0
0
0
0
0
0.615385
false
false
7
5d75c89eb0de98623262acfdd40a837e8b57069f
18,348,100,314,728
cd1414c8eaabaafbc60ac154e88f6578962f9537
/src/model/BaseChatIO.java
b67bf56be321f50f80342ddbfcbec19b02948d92
[]
no_license
StanleyKubrik/PochtiTelegram
https://github.com/StanleyKubrik/PochtiTelegram
5894d0c9eaac13db47bd48c50a378b7ea1bac566
bc5ae874e4f8690ea925e16e62c6be23ed6536cc
refs/heads/master
2020-04-15T23:09:02.935000
2019-01-27T19:27:54
2019-01-27T19:27:54
165,095,752
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; import io.reactivex.Observable; import io.reactivex.disposables.CompositeDisposable; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ConnectException; import java.net.Socket; import static javax.swing.JOptionPane.showMessageDialog; public abstract class BaseChatIO { protected Socket cs; protected DataInputStream in; protected DataOutputStream out; protected CompositeDisposable compositeDisposable; protected Observable<String> response; protected void writeUTF(String message){ if (cs != null && cs.isConnected() && out != null){ try { out.writeUTF(message); out.flush(); } catch (IOException e) { e.printStackTrace(); } } } protected void disconnect() { //throws IOException { if (cs != null && cs.isConnected()){ try { in.close(); out.close(); cs.close(); in = null; out = null; cs = null; } catch (IOException e) { e.printStackTrace(); } } } }
UTF-8
Java
1,230
java
BaseChatIO.java
Java
[]
null
[]
package model; import io.reactivex.Observable; import io.reactivex.disposables.CompositeDisposable; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ConnectException; import java.net.Socket; import static javax.swing.JOptionPane.showMessageDialog; public abstract class BaseChatIO { protected Socket cs; protected DataInputStream in; protected DataOutputStream out; protected CompositeDisposable compositeDisposable; protected Observable<String> response; protected void writeUTF(String message){ if (cs != null && cs.isConnected() && out != null){ try { out.writeUTF(message); out.flush(); } catch (IOException e) { e.printStackTrace(); } } } protected void disconnect() { //throws IOException { if (cs != null && cs.isConnected()){ try { in.close(); out.close(); cs.close(); in = null; out = null; cs = null; } catch (IOException e) { e.printStackTrace(); } } } }
1,230
0.572358
0.572358
45
26.355556
16.530315
59
false
false
0
0
0
0
0
0
0.533333
false
false
7
28328ea477223eb452da3b4e6a4343b60e0b9ee0
31,095,563,247,482
c476e82fc4d3e58be48c311f6ec3cabbe46d9893
/src/ninetynine/MonteCarloPlayer.java
25e7c33c3b3174943979584ec7cc9f02c0db4118
[ "BSD-2-Clause" ]
permissive
StrangerCoug/NinetyNine
https://github.com/StrangerCoug/NinetyNine
c0fa3fa54ef74e4d6f33e938d9bd4406b61b1a2b
f9a5cefb006499a5ec1211b3e127f2f2054ae76c
refs/heads/master
2020-04-24T05:48:45.443000
2019-02-22T00:50:58
2019-02-22T00:50:58
171,742,936
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2016-2017, Jeffrey Hope * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package ninetynine; import java.util.ArrayList; /** * * @author Jeffrey Hope */ public class MonteCarloPlayer extends Player { public MonteCarloPlayer(String name) { super(name); } @Override public void bid(CardSuit trump) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean wantsToDeclare() { return false; } @Override public boolean wantsToReveal() { return false; } @Override public Card selectCard(Card[] cardsPlayed, CardSuit trump) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } /* Code from Homework 4: should be modified Debating how to attack this: Multithread? Pass copies of the game? public static void run(ArrayList<State> map) { State currentState; double[] stateValues = new double[map.size() - 1]; boolean[] visited = new boolean [map.size() - 1]; ArrayList<Transition> possibleTransitions; int reward; int sumOfRewards = 0; double averageReward = 0; // initialize variables for (int i = 0; i < map.size() - 1; i++) { stateValues[i] = 0; } for (int i = 1; i <= 50; i++) { System.out.print(i + ".) "); //initialize for the episode reward = 0; for (int j = 0; j < stateValues.length; j++) visited[j] = false; currentState = map.get(0); printState(currentState); while (!currentState.isFinalState()) { visited[map.indexOf(currentState)] = true; possibleTransitions = currentState.getTransitions(); int rand = (int)(Math.random() * possibleTransitions.size()); printAction(possibleTransitions.get(rand).getAction()); sumOfRewards += reward += possibleTransitions.get(rand).getReward(); currentState = currentState.act (possibleTransitions.get(rand).getAction()); printState(currentState); } System.out.println(" (Reward: " + reward +")"); for (int j = 0; j < stateValues.length; j++) if (visited[j] == true) stateValues[j] = stateValues[j] + 0.1 * (reward - stateValues[j]); averageReward = sumOfRewards / i; } System.out.println("\nState values:"); for (int i = 0; i < stateValues.length; i++) { System.out.println("V(" + map.get(i).getName() + ") = " + stateValues[i]); } System.out.println("\nAverage reward: " + averageReward); } */ @Override public String getPlayerStrategy() { return "Monte Carlo"; } }
UTF-8
Java
4,589
java
MonteCarloPlayer.java
Java
[ { "context": "/*\n * Copyright (c) 2016-2017, Jeffrey Hope\n * All rights reserved.\n *\n * Redistribution and ", "end": 43, "score": 0.9998714923858643, "start": 31, "tag": "NAME", "value": "Jeffrey Hope" }, { "context": "e;\n\nimport java.util.ArrayList;\n\n/**\n *\n * @author Jeff...
null
[]
/* * Copyright (c) 2016-2017, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package ninetynine; import java.util.ArrayList; /** * * @author <NAME> */ public class MonteCarloPlayer extends Player { public MonteCarloPlayer(String name) { super(name); } @Override public void bid(CardSuit trump) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean wantsToDeclare() { return false; } @Override public boolean wantsToReveal() { return false; } @Override public Card selectCard(Card[] cardsPlayed, CardSuit trump) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } /* Code from Homework 4: should be modified Debating how to attack this: Multithread? Pass copies of the game? public static void run(ArrayList<State> map) { State currentState; double[] stateValues = new double[map.size() - 1]; boolean[] visited = new boolean [map.size() - 1]; ArrayList<Transition> possibleTransitions; int reward; int sumOfRewards = 0; double averageReward = 0; // initialize variables for (int i = 0; i < map.size() - 1; i++) { stateValues[i] = 0; } for (int i = 1; i <= 50; i++) { System.out.print(i + ".) "); //initialize for the episode reward = 0; for (int j = 0; j < stateValues.length; j++) visited[j] = false; currentState = map.get(0); printState(currentState); while (!currentState.isFinalState()) { visited[map.indexOf(currentState)] = true; possibleTransitions = currentState.getTransitions(); int rand = (int)(Math.random() * possibleTransitions.size()); printAction(possibleTransitions.get(rand).getAction()); sumOfRewards += reward += possibleTransitions.get(rand).getReward(); currentState = currentState.act (possibleTransitions.get(rand).getAction()); printState(currentState); } System.out.println(" (Reward: " + reward +")"); for (int j = 0; j < stateValues.length; j++) if (visited[j] == true) stateValues[j] = stateValues[j] + 0.1 * (reward - stateValues[j]); averageReward = sumOfRewards / i; } System.out.println("\nState values:"); for (int i = 0; i < stateValues.length; i++) { System.out.println("V(" + map.get(i).getName() + ") = " + stateValues[i]); } System.out.println("\nAverage reward: " + averageReward); } */ @Override public String getPlayerStrategy() { return "Monte Carlo"; } }
4,577
0.59294
0.587274
132
33.765152
28.430367
135
false
false
0
0
0
0
0
0
0.545455
false
false
7
39875270a57fac58c6614f4f13b50e1fac2cf2b4
27,693,949,159,162
92e74060c716b0940e1fa7d0c65a3e3434b1a2f1
/src/hx/model/DictionaryModel.java
22910f3c04a973b2b346d26bac84d514cb5add7b
[]
no_license
hadenhoo1994/yhtgw
https://github.com/hadenhoo1994/yhtgw
2b8414052d08be8d5be266ba8ea2adeb8a57150b
2f6111fc1460b71c9c13a925762e9fc9310dc231
refs/heads/master
2018-11-22T05:12:56.347000
2018-09-04T07:03:41
2018-09-04T07:03:41
147,296,054
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hx.model; /** * 数据字典-实体类 创建人:张振江 日期:2016-05-04 16:53:59 */ public class DictionaryModel { /** * 自动编号 */ private String DictionaryID; /** * 字典名称 */ private String DictionaryName; /** * 父级ID */ private String ParentID; /** * 子级数 */ private String ChildNum; /** * 排序号 */ private String ListID; /** * 创建人 */ private String AdminID; /** * 创建时间 */ private String AddTime; /** * 是否关闭 */ private String IsClose; /** * 图片 */ private String Pic; /** * 描述 */ private String Description; public String getDictionaryID() { return DictionaryID; } public void setDictionaryID(String dictionaryID) { DictionaryID = dictionaryID; } public String getDictionaryName() { return DictionaryName; } public void setDictionaryName(String dictionaryName) { DictionaryName = dictionaryName; } public String getParentID() { return ParentID; } public void setParentID(String parentID) { ParentID = parentID; } public String getChildNum() { return ChildNum; } public void setChildNum(String childNum) { ChildNum = childNum; } public String getListID() { return ListID; } public void setListID(String listID) { ListID = listID; } public String getAdminID() { return AdminID; } public void setAdminID(String adminID) { AdminID = adminID; } public String getAddTime() { return AddTime; } public void setAddTime(String addTime) { AddTime = addTime; } public String getIsClose() { return IsClose; } public void setIsClose(String isClose) { IsClose = isClose; } public String getDescription() { return Description; } public void setDescription(String description) { Description = description; } public String getPic() { return Pic; } public void setPic(String pic) { Pic = pic; } }
UTF-8
Java
1,909
java
DictionaryModel.java
Java
[ { "context": "package hx.model;\n\n/**\n * 数据字典-实体类 创建人:张振江 日期:2016-05-04 16:53:59\n */\npublic class Dictionar", "end": 42, "score": 0.9989699125289917, "start": 39, "tag": "NAME", "value": "张振江" } ]
null
[]
package hx.model; /** * 数据字典-实体类 创建人:张振江 日期:2016-05-04 16:53:59 */ public class DictionaryModel { /** * 自动编号 */ private String DictionaryID; /** * 字典名称 */ private String DictionaryName; /** * 父级ID */ private String ParentID; /** * 子级数 */ private String ChildNum; /** * 排序号 */ private String ListID; /** * 创建人 */ private String AdminID; /** * 创建时间 */ private String AddTime; /** * 是否关闭 */ private String IsClose; /** * 图片 */ private String Pic; /** * 描述 */ private String Description; public String getDictionaryID() { return DictionaryID; } public void setDictionaryID(String dictionaryID) { DictionaryID = dictionaryID; } public String getDictionaryName() { return DictionaryName; } public void setDictionaryName(String dictionaryName) { DictionaryName = dictionaryName; } public String getParentID() { return ParentID; } public void setParentID(String parentID) { ParentID = parentID; } public String getChildNum() { return ChildNum; } public void setChildNum(String childNum) { ChildNum = childNum; } public String getListID() { return ListID; } public void setListID(String listID) { ListID = listID; } public String getAdminID() { return AdminID; } public void setAdminID(String adminID) { AdminID = adminID; } public String getAddTime() { return AddTime; } public void setAddTime(String addTime) { AddTime = addTime; } public String getIsClose() { return IsClose; } public void setIsClose(String isClose) { IsClose = isClose; } public String getDescription() { return Description; } public void setDescription(String description) { Description = description; } public String getPic() { return Pic; } public void setPic(String pic) { Pic = pic; } }
1,909
0.667584
0.659879
127
13.307087
14.16523
55
false
false
0
0
0
0
0
0
1.188976
false
false
7
b3287afa15be4b5f2332c8cd300a158233f0e4c8
26,190,710,619,181
45b0dcc076eddad55a62014e51ce72d9b8d301c5
/app/src/main/java/innopolis/less/registration/models/Lesson.java
79a4957186bf6d47884b8ebf06736c63f79b3a84
[]
no_license
pashaigood/less-innopolis-android-students
https://github.com/pashaigood/less-innopolis-android-students
6e537686efb71b7392493c3d869b5a473910790a
0c49877439ae534933e3ba701eca4e752d70e077
refs/heads/master
2020-04-05T13:34:32.956000
2017-06-29T16:39:49
2017-06-29T16:39:49
94,893,037
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package innopolis.less.registration.models; import java.util.ArrayList; import java.util.Date; import java.util.List; import innopolis.less.db.Model; public class Lesson extends Model { private String name; private Date timeFrom; private Date timeTo; private String classRoom; private String description; private String subject; private String lectorName; private List<Group> groups = new ArrayList<>(); public Lesson(String name, Date timeFrom, Date timeTo, String classRoom, String description, String subject, String lectorName) { this.name = name; this.timeFrom = timeFrom; this.timeTo = timeTo; this.classRoom = classRoom; this.description = description; this.subject = subject; this.lectorName = lectorName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getTimeFrom() { return timeFrom; } public void setTimeFrom(Date timeFrom) { this.timeFrom = timeFrom; } public Date getTimeTo() { return timeTo; } public void setTimeTo(Date timeTo) { this.timeTo = timeTo; } public String getClassRoom() { return classRoom; } public void setClassRoom(String classRoom) { this.classRoom = classRoom; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getLectorName() { return lectorName; } public void setLectorName(String lectorName) { this.lectorName = lectorName; } }
UTF-8
Java
1,882
java
Lesson.java
Java
[]
null
[]
package innopolis.less.registration.models; import java.util.ArrayList; import java.util.Date; import java.util.List; import innopolis.less.db.Model; public class Lesson extends Model { private String name; private Date timeFrom; private Date timeTo; private String classRoom; private String description; private String subject; private String lectorName; private List<Group> groups = new ArrayList<>(); public Lesson(String name, Date timeFrom, Date timeTo, String classRoom, String description, String subject, String lectorName) { this.name = name; this.timeFrom = timeFrom; this.timeTo = timeTo; this.classRoom = classRoom; this.description = description; this.subject = subject; this.lectorName = lectorName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getTimeFrom() { return timeFrom; } public void setTimeFrom(Date timeFrom) { this.timeFrom = timeFrom; } public Date getTimeTo() { return timeTo; } public void setTimeTo(Date timeTo) { this.timeTo = timeTo; } public String getClassRoom() { return classRoom; } public void setClassRoom(String classRoom) { this.classRoom = classRoom; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getLectorName() { return lectorName; } public void setLectorName(String lectorName) { this.lectorName = lectorName; } }
1,882
0.638151
0.638151
84
21.404762
20.18375
133
false
false
0
0
0
0
0
0
0.47619
false
false
7
9d69e9926ecbbeb128940e844db6b8edee31173e
5,643,587,069,495
734141f8092740322e3e80368127df5b67f92e72
/src/nl/rubensten/texifyidea/action/insert/InsertSubSectionAction.java
f0bb69adba2a83774f3ad91a9af917785969172e
[ "MIT" ]
permissive
vatula/TeXiFy-IDEA
https://github.com/vatula/TeXiFy-IDEA
719307c660701d16a94c4875d132c38bba32b80d
07e887b649a5b83d45fb91dc2229ac08104429d3
refs/heads/master
2021-10-20T03:34:54.064000
2019-02-25T12:48:25
2019-02-25T12:48:25
104,471,402
0
0
MIT
true
2019-02-25T12:48:26
2017-09-22T12:21:46
2017-09-22T12:21:48
2019-02-25T12:48:26
1,208
0
0
0
Java
false
null
package nl.rubensten.texifyidea.action.insert; import nl.rubensten.texifyidea.TexifyIcons; import nl.rubensten.texifyidea.action.InsertEditorAction; /** * @author Ruben Schellekens */ public class InsertSubSectionAction extends InsertEditorAction { public InsertSubSectionAction() { super("Subsection", TexifyIcons.DOT_SUBSECTION, "\\subsection{", "}"); } }
UTF-8
Java
379
java
InsertSubSectionAction.java
Java
[ { "context": "ifyidea.action.InsertEditorAction;\n\n/**\n * @author Ruben Schellekens\n */\npublic class InsertSubSectionAction extends I", "end": 183, "score": 0.9998773336410522, "start": 166, "tag": "NAME", "value": "Ruben Schellekens" } ]
null
[]
package nl.rubensten.texifyidea.action.insert; import nl.rubensten.texifyidea.TexifyIcons; import nl.rubensten.texifyidea.action.InsertEditorAction; /** * @author <NAME> */ public class InsertSubSectionAction extends InsertEditorAction { public InsertSubSectionAction() { super("Subsection", TexifyIcons.DOT_SUBSECTION, "\\subsection{", "}"); } }
368
0.754617
0.754617
14
26.071428
26.826065
78
false
false
0
0
0
0
0
0
0.5
false
false
7
6e7c6b11d9e5b818b86f3f4f925926ee5bd539bc
4,174,708,218,922
ec1c22335cf536e33d0e91198a1111f015d45d9c
/app/src/main/java/com/example/usercollegeapp/ui/home/HomeFragment.java
19f56b717d0259537ce17bda1aed6680b5e8a9ea
[]
no_license
Mukesh2507/User-College-App
https://github.com/Mukesh2507/User-College-App
38add27db8d16ff3d0669220edb31bc2bf085dfb
fc78738d7df439b03d925f8ee3ea79ed1f7acd0b
refs/heads/master
2023-06-12T18:26:45.147000
2021-06-22T17:28:32
2021-06-22T17:28:32
379,347,914
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.usercollegeapp.ui.home; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.fragment.app.Fragment; import com.example.usercollegeapp.R; import com.smarteist.autoimageslider.IndicatorView.animation.type.IndicatorAnimationType; import com.smarteist.autoimageslider.SliderAnimations; import com.smarteist.autoimageslider.SliderView; public class HomeFragment extends Fragment { private int[] images; private String[] text; private SliderAdapter adapter; private SliderView sliderView; private ImageView map; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view =inflater.inflate(R.layout.fragment_home, container, false); sliderView = view.findViewById(R.id.sliderView); images =new int[]{R.drawable.s1,R.drawable.s2,R.drawable.s3,R.drawable.s4,R.drawable.s5}; text = new String[]{"Silveroak Campus", "Stars", "Industrial visit","Sports Events","Kabil"}; adapter = new SliderAdapter(images, text); sliderView.setSliderAdapter(adapter); sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION); sliderView.setIndicatorAnimation(IndicatorAnimationType.DROP); sliderView.startAutoCycle(); map = view.findViewById(R.id.map); map.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openMap(); } }); return view; } private void openMap() { Uri uri =Uri.parse("geo:0,0?q=Silveroak University Ahemadbad Gujarat India"); Intent intent = new Intent(Intent.ACTION_VIEW,uri); intent.setPackage("com.google.android.apps.maps"); startActivity(intent); } }
UTF-8
Java
2,067
java
HomeFragment.java
Java
[]
null
[]
package com.example.usercollegeapp.ui.home; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.fragment.app.Fragment; import com.example.usercollegeapp.R; import com.smarteist.autoimageslider.IndicatorView.animation.type.IndicatorAnimationType; import com.smarteist.autoimageslider.SliderAnimations; import com.smarteist.autoimageslider.SliderView; public class HomeFragment extends Fragment { private int[] images; private String[] text; private SliderAdapter adapter; private SliderView sliderView; private ImageView map; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view =inflater.inflate(R.layout.fragment_home, container, false); sliderView = view.findViewById(R.id.sliderView); images =new int[]{R.drawable.s1,R.drawable.s2,R.drawable.s3,R.drawable.s4,R.drawable.s5}; text = new String[]{"Silveroak Campus", "Stars", "Industrial visit","Sports Events","Kabil"}; adapter = new SliderAdapter(images, text); sliderView.setSliderAdapter(adapter); sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION); sliderView.setIndicatorAnimation(IndicatorAnimationType.DROP); sliderView.startAutoCycle(); map = view.findViewById(R.id.map); map.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openMap(); } }); return view; } private void openMap() { Uri uri =Uri.parse("geo:0,0?q=Silveroak University Ahemadbad Gujarat India"); Intent intent = new Intent(Intent.ACTION_VIEW,uri); intent.setPackage("com.google.android.apps.maps"); startActivity(intent); } }
2,067
0.703435
0.700048
57
35.245613
26.970602
101
false
false
0
0
0
0
0
0
0.877193
false
false
7
28545720ca969062f824d48203abf79c89bbcb4a
4,020,089,434,421
b22430bd4d55c89609fc53ea368941824997d0b3
/src/com/entity/Order.java
f713fe013bdbec684c772ddce0b18081841f80dc
[]
no_license
primitiveheart/ordermanage
https://github.com/primitiveheart/ordermanage
d652bdd48f6e3c525a7e4fc8b4cdddd374fbb421
bfb4770bc227e24c598e53aa7d8693e3141ed7c0
refs/heads/master
2021-05-09T23:06:11.132000
2018-04-20T01:35:30
2018-04-20T01:35:30
118,770,315
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.entity; import java.io.Serializable; import java.sql.Timestamp; /** * 该类主要是订单实体类 * @author admin * */ public class Order implements Serializable{ private String uuid;//订单号 private String number;//数量 private String price;//价格 private Timestamp date; private String state; private String scope; //选择的范围 private String shape; //选择的形状 private String username;//uses表的主键,order表中的外键 public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Timestamp getDate() { return date; } public void setDate(Timestamp date) { this.date = date; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getShape() { return shape; } public void setShape(String shape) { this.shape = shape; } }
UTF-8
Java
1,383
java
Order.java
Java
[ { "context": " java.sql.Timestamp;\n\n/**\n * 该类主要是订单实体类\n * @author admin\n *\n */\npublic class Order implements Serializable", "end": 112, "score": 0.9956697225570679, "start": 107, "tag": "USERNAME", "value": "admin" }, { "context": "d setUsername(String username) {\n\t\tthis.use...
null
[]
package com.entity; import java.io.Serializable; import java.sql.Timestamp; /** * 该类主要是订单实体类 * @author admin * */ public class Order implements Serializable{ private String uuid;//订单号 private String number;//数量 private String price;//价格 private Timestamp date; private String state; private String scope; //选择的范围 private String shape; //选择的形状 private String username;//uses表的主键,order表中的外键 public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Timestamp getDate() { return date; } public void setDate(Timestamp date) { this.date = date; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getShape() { return shape; } public void setShape(String shape) { this.shape = shape; } }
1,383
0.699007
0.699007
71
17.436619
13.481058
46
false
false
0
0
0
0
0
0
1.43662
false
false
7
173d24fc3bb9f6c60219654908fd3efbc3482287
27,814,208,220,694
30efc5b559a848049295c07d84502c464d3adcef
/app/synappease movil/DataService/src/com/comynt/launa/adapt/adaptIncidencia.java
489844f5f1629e0fe04d940e3f3f25661f4a690f
[]
no_license
WizelineHackathon2018/synapps-ease
https://github.com/WizelineHackathon2018/synapps-ease
651d6e19a2ff52dbf664daeba1a2e7ffe4406023
c979e754aca490d4e42ed0e4c9845f57f5dafddc
refs/heads/master
2020-03-19T05:19:21.447000
2018-06-03T16:31:10
2018-06-03T16:31:10
135,920,538
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.comynt.launa.adapt; import java.util.ArrayList; import java.util.List; import com.System.UI.ControlManager; import com.System.Utils.Logg; import com.System.Utils.Utils; import com.comynt.launa.R; import BO.*; import BO.BOItinerario; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.Filter; import android.widget.TextView; public class adaptIncidencia extends BaseAdapter { public List<BO> dataoriginal = new ArrayList<BO>(); public List<BO> data = new ArrayList<BO>(); private Activity activity; private LayoutInflater inflater = null; private View vi; public ControlManager UImanager = null; public adaptIncidencia(Activity a, List<BO> d) { activity = a; if(d != null) { for(int x = 0; x < d.size(); x++) { data.add(d.get(x)); dataoriginal.add(d.get(x)); } } inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); UImanager = new ControlManager(); } public int getCount() { return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public String getText() { for (int x = 0; x < UImanager.size(); x++) { if(!UImanager.getSelectedText(x).equals("")) { return UImanager.getSelectedText(x); } } return ""; } public void addBO(BO item) { dataoriginal.add(item); data.clear(); for(int x = 0; x < dataoriginal.size(); x++) { data.add(dataoriginal.get(x)); } notifyDataSetInvalidated(); } public void editBO(BO item, int index) { dataoriginal.set(index, item); data.clear(); for(int x = 0; x < dataoriginal.size(); x++) { data.add(dataoriginal.get(x)); } notifyDataSetInvalidated(); } public View getView(int position, View convertView, ViewGroup parent) { BOCuestionarioCliente Precuestionario = null; Precuestionario = (BOCuestionarioCliente)data.get(position); Logg.info("GENERAR Precuestionario ACTIVIDAD " + position); vi = convertView; //if( position >= UImanager.size() ) if( position >= 0 ) { vi = inflater.inflate(R.layout.itemcuelsrespuestaunica, null); UImanager.AgregarRadioGroup(vi, R.id.lblItemRespuestaUnica, R.id.rbItemRespuestaUnica, (position + 1) + "-" + data.size() + ")" + Precuestionario.Pregunta, Utils.Split(Precuestionario.Respuesta, "/")); } else { vi = UImanager.getView(position); } return vi; } }
UTF-8
Java
2,980
java
adaptIncidencia.java
Java
[]
null
[]
package com.comynt.launa.adapt; import java.util.ArrayList; import java.util.List; import com.System.UI.ControlManager; import com.System.Utils.Logg; import com.System.Utils.Utils; import com.comynt.launa.R; import BO.*; import BO.BOItinerario; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.Filter; import android.widget.TextView; public class adaptIncidencia extends BaseAdapter { public List<BO> dataoriginal = new ArrayList<BO>(); public List<BO> data = new ArrayList<BO>(); private Activity activity; private LayoutInflater inflater = null; private View vi; public ControlManager UImanager = null; public adaptIncidencia(Activity a, List<BO> d) { activity = a; if(d != null) { for(int x = 0; x < d.size(); x++) { data.add(d.get(x)); dataoriginal.add(d.get(x)); } } inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); UImanager = new ControlManager(); } public int getCount() { return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public String getText() { for (int x = 0; x < UImanager.size(); x++) { if(!UImanager.getSelectedText(x).equals("")) { return UImanager.getSelectedText(x); } } return ""; } public void addBO(BO item) { dataoriginal.add(item); data.clear(); for(int x = 0; x < dataoriginal.size(); x++) { data.add(dataoriginal.get(x)); } notifyDataSetInvalidated(); } public void editBO(BO item, int index) { dataoriginal.set(index, item); data.clear(); for(int x = 0; x < dataoriginal.size(); x++) { data.add(dataoriginal.get(x)); } notifyDataSetInvalidated(); } public View getView(int position, View convertView, ViewGroup parent) { BOCuestionarioCliente Precuestionario = null; Precuestionario = (BOCuestionarioCliente)data.get(position); Logg.info("GENERAR Precuestionario ACTIVIDAD " + position); vi = convertView; //if( position >= UImanager.size() ) if( position >= 0 ) { vi = inflater.inflate(R.layout.itemcuelsrespuestaunica, null); UImanager.AgregarRadioGroup(vi, R.id.lblItemRespuestaUnica, R.id.rbItemRespuestaUnica, (position + 1) + "-" + data.size() + ")" + Precuestionario.Pregunta, Utils.Split(Precuestionario.Respuesta, "/")); } else { vi = UImanager.getView(position); } return vi; } }
2,980
0.609396
0.607383
125
22.84
22.007418
122
false
false
0
0
0
0
0
0
0.912
false
false
7
86f28921371cf13799c569ac5666a06871d615cd
8,323,646,678,648
71834d895d8b43dab1e28f034943d5265ada2c9e
/Part3.java
0ebeff6b7e6e1b06be19db8e9e85dc01f527f203
[ "MIT" ]
permissive
GarrettDakin/Odom-s-Missing-Coffee
https://github.com/GarrettDakin/Odom-s-Missing-Coffee
53f8e8d0d2ca911f1475ef48788cb0d3fc74af57
25933934ff4cceba3e073e3cfbdbe0feb9289629
refs/heads/master
2021-07-07T07:10:39.569000
2017-10-03T21:15:17
2017-10-03T21:15:17
105,703,947
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class Part3 { public void partthree() { System.out.println("You hear glass breaking in your kitchen."); System.out.println("(1) You go to see what it was (2) Call the police"); Scanner input = new Scanner(System.in); int a = input.nextInt(); System.out.println(""); Part4 part = new Part4(); if (a == 1) { part.partfour(); } else if (a == 2) { part.part4v2(); } } public void part3v2() { System.out.println("You stumble across a broken window in your kitchen and hear large footsteps out your window."); System.out.println("(1) Grab a quidditch broom and chase the bastard who stole your delicious beverage (2) Jump head first out the window and embrace the sweet kiss of death "); Scanner input = new Scanner(System.in); int a = input.nextInt(); System.out.println(""); Part5 part = new Part5(); if (a == 1) { part.partfive(); } else if (a == 2) { System.out.println(""); System.out.println("You, the world's only saviour die because you never got a cup of coffee..."); System.out.println("Thanks for Playing!"); } } }
UTF-8
Java
1,201
java
Part3.java
Java
[]
null
[]
import java.util.Scanner; public class Part3 { public void partthree() { System.out.println("You hear glass breaking in your kitchen."); System.out.println("(1) You go to see what it was (2) Call the police"); Scanner input = new Scanner(System.in); int a = input.nextInt(); System.out.println(""); Part4 part = new Part4(); if (a == 1) { part.partfour(); } else if (a == 2) { part.part4v2(); } } public void part3v2() { System.out.println("You stumble across a broken window in your kitchen and hear large footsteps out your window."); System.out.println("(1) Grab a quidditch broom and chase the bastard who stole your delicious beverage (2) Jump head first out the window and embrace the sweet kiss of death "); Scanner input = new Scanner(System.in); int a = input.nextInt(); System.out.println(""); Part5 part = new Part5(); if (a == 1) { part.partfive(); } else if (a == 2) { System.out.println(""); System.out.println("You, the world's only saviour die because you never got a cup of coffee..."); System.out.println("Thanks for Playing!"); } } }
1,201
0.615321
0.601166
45
24.688889
35.149727
185
false
false
0
0
0
0
0
0
2.2
false
false
7
1631417f985d28c4c7bc31f7e3764a11bfbb3fb7
11,055,245,877,855
3a5c444c96dd32bd327d5fe2892b9277e107d621
/POS/app/src/main/java/com/cesaas/android/pos/activity/cashier/CashierHomeActivity.java
ffe819b7fd39f008208e085e70905825dd2ae265
[]
no_license
FlyBiao/POS
https://github.com/FlyBiao/POS
3bcb375536b62e9508361e5111ccfae7fd3e6a90
bd330b1842a6251224d940a93cae84418a9879d1
refs/heads/master
2020-03-22T21:14:01.062000
2018-07-12T07:06:18
2018-07-12T07:06:18
140,669,508
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cesaas.android.pos.activity.cashier; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.cesaas.android.pos.R; import com.cesaas.android.pos.activity.order.DownOrderActivity; import com.cesaas.android.pos.activity.order.OrderDetailActivity; import com.cesaas.android.pos.activity.order.WaitPayOrderDetailActivity; import com.cesaas.android.pos.activity.user.LoginActivity; import com.cesaas.android.pos.activity.user.SettingActivity; import com.cesaas.android.pos.base.BaseActivity; import com.cesaas.android.pos.base.BaseRecyclerView; import com.cesaas.android.pos.bean.PayCallbackBean; import com.cesaas.android.pos.bean.PayLogBean; import com.cesaas.android.pos.bean.PosBean; import com.cesaas.android.pos.bean.PosOrderIdBean; import com.cesaas.android.pos.bean.PosPayLogBean; import com.cesaas.android.pos.bean.ResultCreatePayBean; import com.cesaas.android.pos.bean.ResultGetOrderBean; import com.cesaas.android.pos.bean.ResultGetTokenBean; import com.cesaas.android.pos.bean.ResultHomeCreateFromStoreBean; import com.cesaas.android.pos.bean.ShopVipBean; import com.cesaas.android.pos.bean.UserInfoBean; import com.cesaas.android.pos.bean.printer.LatticePrinterBean; import com.cesaas.android.pos.db.bean.PosPayBean; import com.cesaas.android.pos.db.pay.PosSqliteDatabaseUtils; import com.cesaas.android.pos.db.pay.Task; import com.cesaas.android.pos.db.pay.TimerManager; import com.cesaas.android.pos.global.App; import com.cesaas.android.pos.global.Constant; import com.cesaas.android.pos.global.Urls; import com.cesaas.android.pos.gridview.CashierGridAdapter; import com.cesaas.android.pos.gridview.MyGridView; import com.cesaas.android.pos.inventory.activity.InventoryMainActivity; import com.cesaas.android.pos.listener.OnItemClickListener; import com.cesaas.android.pos.net.nohttp.HttpListener; import com.cesaas.android.pos.net.xutils.net.CreatePayNet; import com.cesaas.android.pos.net.xutils.net.GetTokenNet; import com.cesaas.android.pos.net.xutils.net.PayFormStoreNet; import com.cesaas.android.pos.net.xutils.net.PosPayLogNet; import com.cesaas.android.pos.pos.adapter.PosPayCategoryAdapter; import com.cesaas.android.pos.rongcloud.activity.ConversationListActivity; import com.cesaas.android.pos.rongcloud.bean.ReceiveMessageBean; import com.cesaas.android.pos.rongcloud.listener.InitListener; import com.cesaas.android.pos.storedvalue.bean.ResultPayCategoryBean; import com.cesaas.android.pos.storedvalue.ui.SummaryActivity; import com.cesaas.android.pos.test.utils.SlidingMenu; import com.cesaas.android.pos.utils.AbAppUtil; import com.cesaas.android.pos.utils.AbDateUtil; import com.cesaas.android.pos.utils.BankUtil; import com.cesaas.android.pos.utils.CheckUtil; import com.cesaas.android.pos.utils.DecimalFormatUtils; import com.cesaas.android.pos.utils.JsonUtils; import com.cesaas.android.pos.utils.OrderCashierPrinterTools; import com.cesaas.android.pos.utils.RandomUtils; import com.cesaas.android.pos.utils.SingleCashierPrinterTools; import com.cesaas.android.pos.utils.Skip; import com.cesaas.android.pos.utils.SoundPoolUtils; import com.cesaas.android.pos.utils.ToastUtils; import com.wangpos.pay.UnionPay.PosConfig; import com.wangpos.poscore.IPosCallBack; import com.wangpos.poscore.PosCore; import com.wangpos.poscore.impl.PosCoreFactory; import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView; import com.yolanda.nohttp.NoHttp; import com.yolanda.nohttp.RequestMethod; import com.yolanda.nohttp.rest.Request; import com.yolanda.nohttp.rest.Response; import com.zhl.cbdialog.CBDialogBuilder; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.TimerTask; import cn.weipass.pos.sdk.IPrint; import cn.weipass.pos.sdk.LatticePrinter; import cn.weipass.pos.sdk.impl.WeiposImpl; import io.rong.imkit.RongIM; import io.rong.imlib.RongIMClient; import scanner.CaptureActivity; /** * ================================================ * 作 者:FGB * 描 述:POS收银首页 * 创建日期:2016/10/26 * 版 本:1.0 * 修订历史: * ================================================ */ public class CashierHomeActivity extends BaseActivity implements View.OnClickListener{ private static final int CAMERA = 1;//相机权限 private byte[] lock = new byte[1]; int EVENT_NO_PAPER = 1; private final int LOCK_WAIT = 0; private final int LOCK_CONTINUE = 1; private int REQUEST_CONTACT = 20; final int RESULT_CODE = 101; private String scanCode; //8583协议中的参考号 private String refNum; private PosCore pCore; private PosCallBack callBack; private String amount; private Integer money; private double singleCashierMoney=0.0; private int orderStatus; private String orderId; private int curSelectedPos=1001;//当前选择的收银【1001:独立收银,1002:扫描订单收银】 private String vipMobile;//会员手机 private String mobile; private int point;//积分 private String orderShopId;//订单店铺ID private String userShopId;//用户店铺ID private String vipId;//vip ID private String icon; private int fansId; private String fansNickName; private String openId;//会员openId private double payMoney;//订单支付价格 private double totalPrice;//原价 private int mobilePayType;//移动支付类型 private String WxAliTraceAuditNumber;//微信&支付宝凭证号 private double mobilepayMoney;//移动支付金额 private String mobileOrderNo;//移动支付订单号 private int IsPractical; private String biao; private PosBean posBean; private String refNo; private PosOrderIdBean idBean; //独立收银订单号 private String orderNo; private double discount;//会员折扣 private double discountAfter;//折后金额 private double originalPrice;//原价 private String userName;//用户名【营业员】 private String shopNameNick;//店铺名 private int payType; private boolean isSuccess=false; PosCore.RXiaoFei rXiaoFei; private String referenceNumber;//参考号 private String traceAuditNumber;//凭证号 private String primaryAccountNumber;//卡号 private String cardName=null;//银行卡名称 private String bankName=null;////发卡行名称 private int cardCategory=100;//卡类型 private MyGridView gridView;//九宫格gridView private ImageView iv_add_vip,iv_add_scan_vip,iv_back_del; private EditText tv_show_amount,tv_show_discount,et_add_vip_mobile; private TextView tv_cashier_pay,tv_pos_more,tv_vip_name,tv_vip_mobile,tv_app_version, tv_vip_shop,tv_vip_point,tv_vip_discount,tv_vip_grade,tv_radix_point,tv_zero; private TextView tv_pay_success,tv_pay_trace_audit,tv_pay_original_price,tv_real_pay,tv_pay_discount,tv_pay_cad; private LinearLayout ll_weixin_pay,ll_ali_pay,ll_union_pay,ll_cash_pay,ll_query_vip,ll_query_info; private LinearLayout ll_single_weixin_pay,ll_single_ali_pay,ll_single_union_pay,ll_single_cash_pay,ll_cancel_cashier; private LinearLayout ll_pay_info,ll_pay_cashier_accounts,ll_vip_info_btn,ll_scan; private LinearLayout ll_check_accounts,ll_down_order,ll_settle_accounts,ll_inventory,llStoredValue,ll_app_setting,ll_convers; private LinearLayout rl_exit; private String st = ""; private CustomSingleCashierDialog singleCashierDialog; private CustomAddVipDialog addVipDialog; private SlidingMenu mMenu; private LatticePrinter latticePrinter;// 点阵打印 private LatticePrinterBean latticePrinterBean; private Handler handler; private int TIME = 2000; private PosPayLogBean posPayLogBean; private PosPayLogNet posPayLogNet; private CreatePayNet createPayNet; private String strJson; private ArrayList<ResultGetOrderBean.OrderDetailBean> orderList;//商品订单列表 private GetTokenNet getTokenNet; private ArrayList<TextView> tvs=new ArrayList<TextView>(); private Runnable mRunnable; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); mHandler.removeCallbacks(mRunnable); //调用pos打印机 setLatticePrinter(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cashier_home); mMenu = (SlidingMenu) findViewById(R.id.id_menu); //通过EventBus订阅事件 if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } if(prefs.getString("RongToken")!=null){ connect(prefs.getString("RongToken")); }else{ getTokenNet=new GetTokenNet(mContext); getTokenNet.setData(); } if(mCache.getAsString("isOpenSound")==null){ mCache.put("isOpenSound","true"); } getUserInfo(); checkAndRequestPermission(); //初始化CoreApp连接对象 initPosCore(); initView(); initGridView(); getMobilePay(); // initTask(); } // private void initTask(){ // //时间间隔(一天) // new TimerManager(24 * 60 * 60 * 1000); // } /** * 获取移动支付信息并且通过pos打印 */ public void getMobilePay(){ Bundle bundle=getIntent().getExtras(); if(bundle!=null){ mobilePayType=bundle.getInt("mobilePayType"); WxAliTraceAuditNumber=bundle.getString("WxAliTraceAuditNumber"); mobilepayMoney=bundle.getDouble("mobilepayMoney"); mobileOrderNo=bundle.getString("mobileOrderNo"); discount=bundle.getDouble("discount"); shopNameNick=bundle.getString("shopNameNick"); userName=bundle.getString("userName"); point=bundle.getInt("point"); originalPrice=bundle.getDouble("originalPrice"); discountAfter=bundle.getDouble("discountAfter"); mobile=bundle.getString("mobile"); isSuccess=bundle.getBoolean("isSuccess"); if(mobilePayType==2 || mobilePayType==3){//微信&支付宝 if(mobilePayType==2){ tv_pay_success.setText("微信消费成功"); }else{ tv_pay_success.setText("支付宝消费成功"); } ll_pay_cashier_accounts.setVisibility(View.GONE); ll_pay_info.setVisibility(View.VISIBLE); tv_pay_trace_audit.setText("凭证号:"+WxAliTraceAuditNumber); tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(originalPrice)); if(discount!=0.0){ //获取折后金额 tv_pay_discount.setVisibility(View.VISIBLE); tv_pay_discount.setText("折扣"+discount); tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(mobilepayMoney)); }else{ tv_pay_discount.setVisibility(View.GONE); tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(mobilepayMoney)); } posPayLogBean=new PosPayLogBean(); posPayLogBean.setOrderId(mobileOrderNo);//支付订单 posPayLogBean.setPayAmount(mobilepayMoney);//支付金额 posPayLogBean.setTraceAuditNumber(WxAliTraceAuditNumber);//支付凭证号 posPayLogBean.setPayType(mobilePayType);//支付类型 posPayLogBean.setRemark("独立收银"); posPayLogBean.setEnCode(prefs.getString("enCode"));//设备EN号 strJson=gson.toJson(posPayLogBean); getPayListener("",WxAliTraceAuditNumber,mobilepayMoney,mobileOrderNo,mobilePayType,"notFansVip",IsPractical); if(isSuccess==true){ //调用pos打印机 setLatticePrinter(); mRunnable = new Runnable() { @Override public void run() { mHandler.sendEmptyMessage(1); } }; mHandler .postDelayed(mRunnable, 3000); // 在Handler中执行子线程并延迟3s。 } } } } /** * 初始化视图控件 */ public void initView(){ tv_app_version= (TextView) findViewById(R.id.tv_app_version); tv_app_version.setText("V"+ AbAppUtil.getAppVersion(this)); ll_pay_cashier_accounts= (LinearLayout) findViewById(R.id.ll_pay_cashier_accounts); ll_pay_info= (LinearLayout) findViewById(R.id.ll_pay_info); ll_scan= (LinearLayout) findViewById(R.id.ll_scan); tv_pay_success= (TextView) findViewById(R.id.tv_pay_success); tv_pay_trace_audit= (TextView) findViewById(R.id.tv_pay_trace_audit); tv_pay_original_price= (TextView) findViewById(R.id.tv_pay_original_price); tv_real_pay= (TextView) findViewById(R.id.tv_real_pay); tv_pay_discount= (TextView) findViewById(R.id.tv_pay_discount); tv_pay_cad= (TextView) findViewById(R.id.tv_pay_cad); tv_radix_point= (TextView) findViewById(R.id.tv_radix_point); tv_zero= (TextView) findViewById(R.id.tv_zero); iv_back_del= (ImageView) findViewById(R.id.iv_back_del); tv_radix_point.setOnClickListener(this); tv_zero.setOnClickListener(this); iv_back_del.setOnClickListener(this); ll_scan.setOnClickListener(this); tv_show_amount= (EditText) findViewById(R.id.tv_show_amount); tv_show_discount= (EditText) findViewById(R.id.tv_show_discount); tv_cashier_pay= (TextView) findViewById(R.id.tv_cashier_pay); tv_pos_more= (TextView) findViewById(R.id.tv_pos_more); gridView= (MyGridView) findViewById(R.id.gridview); iv_add_vip= (ImageView) findViewById(R.id.iv_add_vip); tv_cashier_pay.setOnClickListener(this); tv_pos_more.setOnClickListener(this); rl_exit= (LinearLayout) findViewById(R.id.rl_exit); ll_inventory= (LinearLayout) findViewById(R.id.ll_inventory); ll_down_order= (LinearLayout) findViewById(R.id.ll_down_order); ll_check_accounts= (LinearLayout) findViewById(R.id.ll_check_accounts); ll_settle_accounts= (LinearLayout) findViewById(R.id.ll_settle_accounts); llStoredValue= (LinearLayout) findViewById(R.id.ll_stored_value); ll_app_setting= (LinearLayout) findViewById(R.id.ll_app_setting); ll_convers= (LinearLayout) findViewById(R.id.ll_convers); //设置点击监听 rl_exit.setOnClickListener(this); ll_inventory.setOnClickListener(this); ll_down_order.setOnClickListener(this); ll_check_accounts.setOnClickListener(this); iv_add_vip.setOnClickListener(this); ll_settle_accounts.setOnClickListener(this); llStoredValue.setOnClickListener(this); ll_app_setting.setOnClickListener(this); ll_convers.setOnClickListener(this); } /** * 检查权限【Android6.0动态申请运行时权限】 */ private void checkAndRequestPermission(){ if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { Log.i(Constant.TAG, "hi! everybody, I really need ths permission for better service. thx!"); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA); } } } /** * 处理授权请求回调 使用onRequestPermissionsResult(int ,String , int[])方法处理回调, 上面说到了根据requestPermissions()方法中的requestCode, 就可以在回调方法中区分授权请求 */ @SuppressLint("Override") @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case CAMERA: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.i(Constant.TAG, "PERMISSION_GRANTED: Thx, I will give u a better service!"); } else { Log.i(Constant.TAG, "PERMISSION_DENIED: Sorry, without this permission I can't do next work for u"); } return; } } } public void CONTENT(String number){ StringBuffer sb = new StringBuffer(st); // if (st.equals("0")){ // st = number; // }else { sb.append(number); st = sb.toString(); // } if (st.indexOf(".")!=-1){ String newSt = st.substring(st.indexOf("."),st.length()); if (newSt.length()>3){ st = st.substring(0,st.length()-1); } } } public void initGridView(){ gridView.setAdapter(new CashierGridAdapter(mContext)); //九宫格点击事件 gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: CONTENT("1"); hidAndShow(); break; case 1: CONTENT("2"); hidAndShow(); break; case 2: CONTENT("3"); hidAndShow(); break; case 3: CONTENT("4"); hidAndShow(); break; case 4: CONTENT("5"); hidAndShow(); break; case 5: CONTENT("6"); hidAndShow(); break; case 6: CONTENT("7"); hidAndShow(); break; case 7: CONTENT("8"); hidAndShow(); break; case 8: CONTENT("9"); hidAndShow(); break; case 9: if(TextUtils.isEmpty(tv_show_amount.getText().toString())){ }else{ CONTENT("."); } hidAndShow(); tv_show_amount.setText(st); break; case 10: CONTENT("0"); hidAndShow(); tv_show_amount.setText(st); break; case 11: if(st.equals("")){ }else{ st = st.substring(0,st.length()-1); } hidAndShow(); break; default: break; } tv_show_amount.setText(st); } }); } public void hidAndShow(){ if(isSuccess==true){ ll_pay_cashier_accounts.setVisibility(View.VISIBLE); ll_pay_info.setVisibility(View.GONE); } } /** * 接收支付流水结果信息 * @param bean */ @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 public void onDataSynEvent(ResultCreatePayBean bean) { if(bean.isSuccess()!=false){ if(payType==5){ isSuccess=true; ll_pay_cashier_accounts.setVisibility(View.GONE); ll_pay_info.setVisibility(View.VISIBLE); tv_pay_success.setText("现金消费成功"); tv_pay_trace_audit.setText("凭证号:"+traceAuditNumber); // if(curSelectedPos==1001){ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(Double.parseDouble(tv_show_amount.getText().toString()))); originalPrice=DecimalFormatUtils.decimalFormatRound(Double.parseDouble(tv_show_amount.getText().toString())); payMoney=DecimalFormatUtils.decimalFormatRound(Double.parseDouble(tv_show_amount.getText().toString())); totalPrice=DecimalFormatUtils.decimalFormatRound(Double.parseDouble(tv_show_amount.getText().toString())); posPayLogBean=new PosPayLogBean(); posPayLogBean.setOrderId(orderId);//支付订单 posPayLogBean.setPayAmount(totalPrice);//支付金额 posPayLogBean.setTraceAuditNumber(referenceNumber);//支付凭证号 posPayLogBean.setPayType(5);//支付类型 posPayLogBean.setRemark("独立收银"); posPayLogBean.setEnCode(prefs.getString("enCode"));//设备EN号 strJson=gson.toJson(posPayLogBean); tv_real_pay.setText("实付:" +DecimalFormatUtils.decimalFormatRound(Double.parseDouble(tv_show_amount.getText().toString()))); //调用pos打印机 setLatticePrinter(); mRunnable = new Runnable() { @Override public void run() { mHandler.sendEmptyMessage(1); } }; mHandler .postDelayed(mRunnable, 3000); // 在Handler中执行子线程并延迟3s。 }else if(payType==4){ if(payType==4){ isSuccess=true; PosPayBean bean1=new PosPayBean(prefs.getString("userShopId"),shopNameNick,userName,orderId,payMoney+"",rXiaoFei.retrievalReferenceNumber,"4","银联支付",IsPractical+"","3",AbDateUtil.getCurrentDate(),"消费成功...",prefs.getString("enCode"),rXiaoFei.primaryAccountNumber,"true","0","1"); insertData(bean1); tv_pay_success.setText("银联消费成功"); tv_pay_cad.setVisibility(View.VISIBLE); tv_pay_cad.setText("卡号:" + rXiaoFei.primaryAccountNumber ); tv_pay_trace_audit.setText("凭证号:" + rXiaoFei.systemTraceAuditNumber); if(curSelectedPos==1001){ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(Double.parseDouble(biao))); }else{ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(payMoney)); } if(discount!=0.0){ discountAfter=Double.parseDouble(biao)*(discount/10); tv_pay_discount.setVisibility(View.VISIBLE); tv_pay_discount.setText("折扣"+discount); tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(discountAfter)); }else{ tv_pay_discount.setVisibility(View.GONE); if(curSelectedPos==1001) {//独立收银 tv_real_pay.setText("实付:" + DecimalFormatUtils.decimalFormatRound(Double.parseDouble(biao))); }else{//扫描订单收银 tv_real_pay.setText("实付:" +DecimalFormatUtils.decimalFormatRound(payMoney)); } } } } }else{ // ToastUtils.getToast(mContext,"创建支付流水失败:"+bean.getMessage()); // Log.d(Constant.TAG,"支付error:"+bean.getMessage()); //记录pos 支付日志 if(payType==1){//积分支付退款回调 }else if(payType==2){//微信支付退款回调 payLog("PayFromStore",strJson,"微信支付"); }else if(payType==3){//支付宝退款回调 payLog("PayFromStore",strJson,"支付宝"); }else if(payType==4){//银联支付退款回调 payLog("PayFromStore",strJson,"银联支付"); auditOrder(); }else if(payType==5){//现金支付退款回调 payLog("PayFromStore",strJson,"现金支付"); ; } } } private void insertData(PosPayBean bean){ PosSqliteDatabaseUtils.insterData(mContext,bean); } public void auditOrder(){ new CBDialogBuilder(CashierHomeActivity.this) .setTouchOutSideCancelable(true) .showCancelButton(true) .setTitle("温馨提示!") .setMessage("该订单审核失败,请重新审核!") .setConfirmButtonText("审核") .setCancelButtonText("取消") .setDialogAnimation(CBDialogBuilder.DIALOG_ANIM_SLID_BOTTOM) .setButtonClickListener(true, new CBDialogBuilder.onDialogbtnClickListener() { @Override public void onDialogbtnClick(Context context, Dialog dialog, int whichBtn) { switch (whichBtn) { case BUTTON_CONFIRM: createPayNet=new CreatePayNet(mContext); if(mCache.getAsString("PayInfo")!=null){ createPayNet.setData(mCache.getAsString("PayInfo"),Double.parseDouble(biao),4,mCache.getAsString("PayInfo"),rXiaoFei.retrievalReferenceNumber,primaryAccountNumber,"银联刷卡",rXiaoFei.systemTraceAuditNumber,userShopId,bankName,2,cardCategory); }else{ createPayNet.setData(primaryAccountNumber,Double.parseDouble(biao),4,primaryAccountNumber,rXiaoFei.retrievalReferenceNumber,primaryAccountNumber,"银联刷卡",primaryAccountNumber,userShopId,bankName,2,cardCategory); } break; case BUTTON_CANCEL: ToastUtils.show("已取消审核,请联系管理员!"); break; default: break; } } }) .create().show(); } @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 public void onDataSynEvent(ResultHomeCreateFromStoreBean bean) { if(bean.isSuccess()==true && bean.TModel!=null){//订单号不为null,显示支付方式dialog orderNo=bean.TModel.RetailId+""; singleCashierDialog=new CustomSingleCashierDialog(mContext, R.style.dialog, R.layout.item_custom_single_cashier_dialog); singleCashierDialog.show(); singleCashierDialog.setCancelable(false); }else{ ToastUtils.show("下单失败!"+bean.getMessage()); } } /** * Called when a view has been clicked. * * @param v The view that was clicked. */ @Override public void onClick(View v) { switch (v.getId()){ case R.id.tv_radix_point://小数点 CONTENT("."); tv_show_amount.setText(st); break; case R.id.tv_zero://0 CONTENT("0"); tv_show_amount.setText(st); break; case R.id.iv_back_del://回删 if(st.equals("")){ }else{ st = st.substring(0,st.length()-1); } break; case R.id.iv_add_vip://添加会员 if(TextUtils.isEmpty(tv_show_amount.getText().toString()) || tv_show_amount.getText().toString().equals("¥0.0") || tv_show_amount.getText().toString().equals("0") || tv_show_amount.getText().toString().equals("0.0")){ ToastUtils.show("请先输入收款金额!"); }else{ addVipDialog=new CustomAddVipDialog(mContext,R.style.dialog,R.layout.item_custom_add_vip_dialog); addVipDialog.show(); addVipDialog.setCancelable(false); } break; case R.id.ll_scan://扫描支付订单 curSelectedPos=1002; Skip.mScanOrderActivityResult(mActivity, CaptureActivity.class, REQUEST_CONTACT); break; case R.id.tv_cashier_pay://独立收银 curSelectedPos=1001; if(!TextUtils.isEmpty(tv_show_amount.getText().toString()) && !tv_show_amount.getText().toString().equals("¥0.0")){ singleCashierDialog=new CustomSingleCashierDialog(mContext, R.style.dialog, R.layout.item_custom_single_cashier_dialog); singleCashierDialog.show(); singleCashierDialog.setCancelable(false); }else{ ToastUtils.show("请输入收款金额在收银!"); } break; case R.id.tv_pos_more://更多 mMenu.toggle(); break; case R.id.ll_check_accounts://查单 mMenu.closeMenu(); // Skip.mNext(mActivity, CheckAccountsActivity.class); Skip.mNext(mActivity, CheckAccountsListActivity.class); break; case R.id.ll_settle_accounts://结算对账 mMenu.closeMenu(); bundle.putString("shopName",shopNameNick); bundle.putString("userName",userName); Skip.mNextFroData(mActivity,SettleAccountsActivity.class,bundle); break; case R.id.ll_down_order://下单 mMenu.closeMenu(); bundle.putString("userName",userName); Skip.mNextFroData(mActivity, DownOrderActivity.class,bundle); break; case R.id.ll_stored_value://充值 Skip.mNext(mActivity, SummaryActivity.class); break; case R.id.ll_inventory://盘点 mMenu.closeMenu(); Skip.mNext(mActivity,InventoryMainActivity.class); break; case R.id.rl_exit://退出 mMenu.closeMenu(); exit(); break; case R.id.ll_app_setting: Skip.mNext(mActivity,SettingActivity.class); break; case R.id.ll_convers: Skip.mNext(mActivity,ConversationListActivity.class); break; } } /** * 退出 */ public void exit(){ new CBDialogBuilder(CashierHomeActivity.this) .setTouchOutSideCancelable(true) .showCancelButton(true) .setTitle("退出登录") .setMessage("是否退出登录,退出后将不能做任何操作!") .setConfirmButtonText("确定") .setCancelButtonText("取消") .setDialogAnimation(CBDialogBuilder.DIALOG_ANIM_SLID_BOTTOM) .setButtonClickListener(true, new CBDialogBuilder.onDialogbtnClickListener() { @Override public void onDialogbtnClick(Context context, Dialog dialog, int whichBtn) { switch (whichBtn) { case BUTTON_CONFIRM: prefs.cleanAll(); mCache.remove("GetPayCategory"); Skip.mNext(mActivity, LoginActivity.class, true); break; case BUTTON_CANCEL: ToastUtils.show("已取消退出"); break; default: break; } } }) .create().show(); } /** * 读取用户信息 */ public void getUserInfo(){ Request<String> request = NoHttp.createStringRequest(Urls.USER_INFO, RequestMethod.POST); commonNet.requestNetTask(request,userInfoListener); if(mCache.getAsString("GetPayCategory")!=null){ }else{ Request<String> requestPay = NoHttp.createStringRequest(Urls.GET_PAY_CATEGORY, RequestMethod.POST); commonNet.requestNetTask(requestPay, getPayList); } } //待支付订单详情回调监听 public HttpListener<String> getPayList = new HttpListener<String>() { @Override public void onSucceed(int what, Response<String> response) { Log.i("test","value:"+response.get()); mCache.put("GetPayCategory",response.get()); } @Override public void onFailed(int what, Response<String> response) { Log.d(Constant.TAG,"Failed:"+response.getException()); } }; //UserInfo回调监听 private HttpListener<String> userInfoListener = new HttpListener<String>() { @Override public void onSucceed(int what, Response<String> response) { UserInfoBean bean= gson.fromJson(response.get(),UserInfoBean.class); Log.i(Constant.TAG,"userinfo"+response.get().toString()); if(bean.TModel!=null){ shopNameNick=bean.TModel.getShopName(); userName=bean.TModel.getName(); userShopId=bean.TModel.getShopId(); icon=bean.TModel.getIcon(); vipId=bean.TModel.getVipId(); prefs.putString("userName",userName); prefs.putString("userShopId",userShopId); prefs.putString("shopNameNick",shopNameNick); prefs.putString("ShopAddress",bean.TModel.getShopAddress()); prefs.putString("ShopArea",bean.TModel.getShopArea()); }else{ ToastUtils.show(""+bean.getMessage()); } } @Override public void onFailed(int what, Response<String> response) { ToastUtils.show(response.getException().getMessage()); } }; /** * 会员监听 */ public void getVipListener(String mobile,int type){ Request<String> request = NoHttp.createStringRequest(Urls.QUERY_VIP, RequestMethod.POST); request.add("Type",type);//Type:0 手机号, 1:VIpId request.add("Val",mobile); commonNet.requestNetTask(request,getStatisticsListener,1); } /** * 会员监听回调 */ private HttpListener<String> getStatisticsListener = new HttpListener<String>() { @Override public void onSucceed(int what, Response<String> response) { // Log.i("info","会员result:"+response.get()); ShopVipBean bean=gson.fromJson(response.get(),ShopVipBean.class); if(bean.TModel!=null){ ll_query_vip.setVisibility(View.GONE); ll_query_info.setVisibility(View.VISIBLE); ll_vip_info_btn.setVisibility(View.VISIBLE); discount=bean.TModel.getFANS_DISCOUNT(); mobile=bean.TModel.getFANS_MOBILE(); point=bean.TModel.getFANS_POINT(); openId=bean.TModel.getFANS_OPENID(); fansId=bean.TModel.getFANS_ID(); fansNickName=bean.TModel.getFANS_NAME(); tv_vip_name.setText(bean.TModel.getFANS_NAME()); tv_vip_mobile.setText(bean.TModel.getFANS_MOBILE()); tv_vip_shop.setText(bean.TModel.getFANS_SHOPNAME()); tv_vip_point.setText(bean.TModel.getFANS_POINT()+""); tv_vip_discount.setText(bean.TModel.getFANS_DISCOUNT()+""); tv_vip_grade.setText(bean.TModel.getFANS_GRADE()); }else{ ToastUtils.show("未找到改会员,请核实输入信息!"); } } @Override public void onFailed(int what, Response<String> response) { ToastUtils.show(response.get()); } }; /** * 自定义添加会员Dialog */ public class CustomAddVipDialog extends Dialog implements View.OnClickListener{ int layoutRes;//布局文件 Context context; private LinearLayout ll_sure_query_vip,ll_cancel_back_cashier,ll_sure_add_vip,ll_cancel_back_query; /** * 自定义添加会员D主题及布局的构造方法 * @param context * @param theme * @param resLayout */ public CustomAddVipDialog(Context context, int theme,int resLayout){ super(context, theme); this.context = context; this.layoutRes=resLayout; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(layoutRes); initView(); } public void initView(){ ll_query_vip= (LinearLayout) findViewById(R.id.ll_query_vip); ll_query_info= (LinearLayout) findViewById(R.id.ll_query_info); ll_sure_query_vip= (LinearLayout) findViewById(R.id.ll_sure_query_vip); ll_cancel_back_cashier= (LinearLayout) findViewById(R.id.ll_cancel_back_cashier); ll_sure_add_vip= (LinearLayout) findViewById(R.id.ll_sure_add_vip); ll_cancel_back_query= (LinearLayout) findViewById(R.id.ll_cancel_back_query); ll_vip_info_btn= (LinearLayout) findViewById(R.id.ll_vip_info_btn); iv_add_scan_vip= (ImageView) findViewById(R.id.iv_add_scan_vip); et_add_vip_mobile= (EditText) findViewById(R.id.et_add_vip_mobile); tv_vip_name= (TextView) findViewById(R.id.tv_vip_name); tv_vip_mobile= (TextView) findViewById(R.id.tv_vip_mobile); tv_vip_shop= (TextView) findViewById(R.id.tv_vip_shop); tv_vip_point= (TextView) findViewById(R.id.tv_vip_point); tv_vip_discount= (TextView) findViewById(R.id.tv_vip_discount); tv_vip_grade= (TextView) findViewById(R.id.tv_vip_grade); ll_sure_query_vip.setOnClickListener(this); ll_cancel_back_cashier.setOnClickListener(this); ll_sure_add_vip.setOnClickListener(this); ll_cancel_back_query.setOnClickListener(this); iv_add_scan_vip.setOnClickListener(this); } /** * Called when a view has been clicked. * * @param v The view that was clicked. */ @Override public void onClick(View v) { switch (v.getId()){ case R.id.iv_add_scan_vip://扫描会员 Skip.mScanAddVipActivityResult(mActivity, CaptureActivity.class, REQUEST_CONTACT); break; case R.id.ll_sure_query_vip://查询会员 if(CheckUtil.phoneVerify(mContext,et_add_vip_mobile.getText().toString())){ vipMobile=et_add_vip_mobile.getText().toString(); getVipListener(vipMobile,0); } break; case R.id.ll_cancel_back_cashier://返回 ToastUtils.show("已取消查询会员"); addVipDialog.dismiss(); break; case R.id.ll_sure_add_vip://添加vip iv_add_vip.setImageResource(R.mipmap.vip02); addVipDialog.dismiss(); tv_show_discount.setVisibility(View.VISIBLE); //获取折后金额 discountAfter=Double.parseDouble(tv_show_amount.getText().toString())*(discount/10); tv_show_discount.setText(DecimalFormatUtils.decimalFormatRound(discountAfter)+""); //设置原价和折扣价不可编辑状态; tv_show_amount.setFocusable(false);tv_show_amount.setFocusableInTouchMode(false); tv_pay_discount.setFocusable(false);tv_pay_discount.setFocusableInTouchMode(false); break; case R.id.ll_cancel_back_query://返回 ToastUtils.show("已取消添加会员"); addVipDialog.dismiss(); break; } } } /** * 自定义独立收银dialog */ public class CustomSingleCashierDialog extends Dialog{ int layoutRes;//布局文件 Context context; SwipeMenuRecyclerView rvView; LinearLayout ll_cancel_pos_cashier; List<ResultPayCategoryBean.PayCategoryBea> categoryBeaList; PosPayCategoryAdapter posPayCategoryAdapter; /** * 自定义收银主题及布局的构造方法 * * @param context * @param theme * @param resLayout */ public CustomSingleCashierDialog(Context context, int theme, int resLayout) { super(context, theme); this.context = context; this.layoutRes = resLayout; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(layoutRes); initView(); initPayData(); } public void initPayData() { ResultPayCategoryBean bean = JsonUtils.fromJson(mCache.getAsString("GetPayCategory"), ResultPayCategoryBean.class); categoryBeaList = bean.TModel; posPayCategoryAdapter = new PosPayCategoryAdapter(categoryBeaList,100); posPayCategoryAdapter.setOnItemClickListener(onItemClickListener); rvView.setAdapter(posPayCategoryAdapter); } public void initView() { ll_cancel_pos_cashier = (LinearLayout) findViewById(R.id.ll_cancel_pos_cashier); rvView = (SwipeMenuRecyclerView) findViewById(R.id.rv_view); BaseRecyclerView.initRecyclerView(getContext(), rvView, false); ll_cancel_pos_cashier.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } private OnItemClickListener onItemClickListener = new OnItemClickListener() { @Override public void onItemClick(final int position) { switch (categoryBeaList.get(position).getCategoryType()) { case 2://微信支付 payType = categoryBeaList.get(position).getCategoryType(); if (!TextUtils.isEmpty(tv_show_discount.getText().toString())) {//折后价格非等于null bundle.putDouble("PayMoney", Double.parseDouble(tv_show_discount.getText().toString())); } else {//折后金额为空 bundle.putDouble("PayMoney", Double.parseDouble(tv_show_amount.getText().toString())); } //随机生成6位凭证号【规则:当月+4位随机数】 traceAuditNumber = RandomUtils.getCurrentTimeMM() + RandomUtils.getFourRandom(); bundle.putInt("Pay", categoryBeaList.get(position).getCategoryType()); bundle.putInt("IsPractical", categoryBeaList.get(position).getIsPractical()); bundle.putString("userShopId", userShopId); bundle.putString("OrderNo", traceAuditNumber); bundle.putDouble("discount", discount); bundle.putString("shopNameNick", shopNameNick); bundle.putString("userName", userName); bundle.putInt("point", point); bundle.putDouble("originalPrice", Double.parseDouble(tv_show_amount.getText().toString())); bundle.putDouble("discountAfter", discountAfter); bundle.putString("mobile", mobile); bundle.putBoolean("isSuccess", isSuccess); Skip.mNextFroData(mActivity, WeiXinAndAliPaySingleActivity.class, bundle); singleCashierDialog.dismiss(); break; case 3://支付宝 payType = categoryBeaList.get(position).getCategoryType(); if (!TextUtils.isEmpty(tv_show_discount.getText().toString())) {//折后价格非等于null bundle.putDouble("PayMoney", Double.parseDouble(tv_show_discount.getText().toString())); } else {//折后金额为空 bundle.putDouble("PayMoney", Double.parseDouble(tv_show_amount.getText().toString())); } //随机生成6位凭证号【规则:当月+4位随机数】 traceAuditNumber = RandomUtils.getCurrentTimeMM() + RandomUtils.getFourRandom(); bundle.putInt("IsPractical", categoryBeaList.get(position).getIsPractical()); bundle.putInt("Pay", categoryBeaList.get(position).getCategoryType()); bundle.putString("OrderNo", traceAuditNumber); bundle.putDouble("discount", discount); bundle.putString("shopNameNick", shopNameNick); bundle.putString("userShopId", userShopId); bundle.putString("userName", userName); bundle.putInt("point", point); bundle.putDouble("originalPrice", Double.parseDouble(tv_show_amount.getText().toString())); bundle.putDouble("discountAfter", discountAfter); bundle.putString("mobile", mobile); bundle.putBoolean("isSuccess", isSuccess); Skip.mNextFroData(mActivity, WeiXinAndAliPaySingleActivity.class, bundle); singleCashierDialog.dismiss(); break; case 4://银联支付 IsPractical=categoryBeaList.get(position).getIsPractical(); singleCashierDialog.dismiss(); payType = categoryBeaList.get(position).getCategoryType(); if (!TextUtils.isEmpty(tv_show_discount.getText().toString())) {//折后价格非等于null biao = tv_show_discount.getText().toString(); } else {//折后金额为空 biao = tv_show_amount.getText().toString(); } //启动银联收银 amount = "2"; lock[0] = LOCK_WAIT; doConsumeHasTemplate(amount, orderNo); break; case 5://现金支付 new CBDialogBuilder(CashierHomeActivity.this) .setTouchOutSideCancelable(true) .showCancelButton(true) .setTitle("温馨提示!") .setMessage("请确认该订单是否使用现金支付?") .setConfirmButtonText("确定") .setCancelButtonText("取消") .setDialogAnimation(CBDialogBuilder.DIALOG_ANIM_SLID_BOTTOM) .setButtonClickListener(true, new CBDialogBuilder.onDialogbtnClickListener() { @Override public void onDialogbtnClick(Context context, Dialog dialog, int whichBtn) { switch (whichBtn) { case BUTTON_CONFIRM: dismiss(); IsPractical=categoryBeaList.get(position).getIsPractical(); singleCashierDialog.dismiss(); payType = categoryBeaList.get(position).getCategoryType(); if (!TextUtils.isEmpty(tv_show_discount.getText().toString())) {//折后价格非等于null singleCashierMoney = Double.parseDouble(tv_show_discount.getText().toString()); } else {//折后金额为空 singleCashierMoney = Double.parseDouble(tv_show_amount.getText().toString()); } //随机生成12位参考号【规则:当前时间+2位随机数】 referenceNumber = RandomUtils.getCurrentTimeAsNumber() + RandomUtils.getToFourRandom(); //随机生成6位凭证号【规则:当月+4位随机数】 traceAuditNumber = RandomUtils.getCurrentTimeMM() + RandomUtils.getFourRandom(); orderNo=RandomUtils.getCurrentTimeMM() + RandomUtils.getFourRandom()+""; //getPayListener(referenceNumber, traceAuditNumber, singleCashierMoney, orderNo, 5, "notFansVip",IsPractical); double money=Double.parseDouble(tv_show_amount.getText().toString()); //订单号生成规则:LS+VipId+MMddHHmm+4位随机数 String orderNo="LS"+vipId+ AbDateUtil.getCurrentTimeAsNumber()+RandomUtils.getFourRandom(); createPayNet=new CreatePayNet(mContext); createPayNet.setData(orderNo,money,5,referenceNumber,"","","独立收银",orderNo,userShopId,"",2,100); break; case BUTTON_CANCEL: ToastUtils.show("已取消支付"); dismiss(); break; default: break; } } }) .create().show(); break; default: break; } } }; } /** * 初始化CoreApp连接对象 * * @return */ private void initPosCore() { if (pCore == null) { // 配置数据为开发阶段的数据 HashMap<String, String> init_params = new HashMap<String,String>(); init_params.put(PosConfig.Name_EX + "1053", shopNameNick);// 签购单小票台头 init_params.put(PosConfig.Name_EX + "1100", "cn.weipass.cashier");// 核心APP 包名 init_params.put(PosConfig.Name_EX + "1101", "com.wangpos.cashiercoreapp.services.CoreAppService");// 核心APP 类名 init_params.put(PosConfig.Name_EX + "1092", "1");// 是否开启订单生成,并且上报服务器 1.开启 0.不开启 init_params.put(PosConfig.Name_EX + "1093", "2");// 是否需要打印三联签购单 1.需要 2.不需要 init_params.put(PosConfig.Name_EX + "1012", "1");// 华势通道 init_params.put(PosConfig.Name_MerchantName, "coreApp"); pCore = PosCoreFactory.newInstance(this, init_params); callBack = new PosCallBack(pCore); } } /** * 消费 */ private void doConsumeHasTemplate(final String amount ,final String orderNo) { new Thread() { public void run() { try { HashMap<String, String> map = new HashMap<String, String>(); map.put("myOrderNo", orderNo); rXiaoFei= pCore.xiaoFei(amount, map, callBack); mActivity.runOnUiThread(new Runnable() { @Override public void run() { posPayLogBean=new PosPayLogBean(); posPayLogBean=new PosPayLogBean(); posPayLogBean.setOrderId(orderId);//支付订单 posPayLogBean.setTraceAuditNumber(rXiaoFei.retrievalReferenceNumber);//支付凭证号 posPayLogBean.setPayType(4);//支付类型 posPayLogBean.setRemark("零售单"); posPayLogBean.setEnCode(prefs.getString("enCode"));//设备EN号 posPayLogBean.setAccountNumber(primaryAccountNumber); posPayLogBean.setPayAmount(Double.parseDouble(biao));//支付金额 strJson=gson.toJson(posPayLogBean); ll_pay_cashier_accounts.setVisibility(View.GONE); ll_pay_info.setVisibility(View.VISIBLE); createPayNet=new CreatePayNet(mContext); if(rXiaoFei.systemTraceAuditNumber!=null && !"".equals(rXiaoFei.systemTraceAuditNumber)){ createPayNet.setData(rXiaoFei.retrievalReferenceNumber,Double.parseDouble(biao),4,rXiaoFei.retrievalReferenceNumber,rXiaoFei.retrievalReferenceNumber,primaryAccountNumber,"银联刷卡",rXiaoFei.systemTraceAuditNumber,userShopId,bankName,2,cardCategory); }else{ if(mCache.getAsString("PayInfo")!=null){ createPayNet.setData(mCache.getAsString("PayInfo"),Double.parseDouble(biao),4,mCache.getAsString("PayInfo"),rXiaoFei.retrievalReferenceNumber,primaryAccountNumber,"银联刷卡",rXiaoFei.systemTraceAuditNumber,userShopId,bankName,2,cardCategory); }else{ createPayNet.setData(primaryAccountNumber,Double.parseDouble(biao),4,primaryAccountNumber,rXiaoFei.retrievalReferenceNumber,primaryAccountNumber,"银联刷卡",primaryAccountNumber,userShopId,bankName,2,cardCategory); } } } }); } catch (Exception e) { e.printStackTrace(); showMsg(e.getLocalizedMessage()); Log.d(Constant.TAG,"银联ERROR:="+e.getLocalizedMessage()); } } }.start(); } /** * 处理扫描Activity返回的数据 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode==RESULT_CODE) { if(data.getStringExtra("mScanOrderResult")!=null && data.getStringExtra("mScanOrderResult").equals("012")){ scanCode= data.getStringExtra("resultCode"); bundle.putString("OrderId",scanCode); Skip.mNextFroData(mActivity, WaitPayOrderDetailActivity.class,bundle); } if(data.getStringExtra("mScanAddVipResult")!=null && data.getStringExtra("mScanAddVipResult").equals("016")){ scanCode= data.getStringExtra("resultCode"); if(scanCode!=null){ et_add_vip_mobile.setText(scanCode); } } } super.onActivityResult(requestCode, resultCode, data); } /** * 支付回调 * @param RetrievalReferenceNumber * @param TraceAuditNumber * @param ConsumeAmount * @param OrderId * @param PayType * @param OpenId */ public void getPayListener(String RetrievalReferenceNumber,String TraceAuditNumber,double ConsumeAmount,String OrderId,int PayType,String OpenId,int IsPractical){ Request<String> request = NoHttp.createStringRequest(Urls.PAY_FROM_STORE, RequestMethod.POST); request.add("RetrievalReferenceNumber",RetrievalReferenceNumber);//参考号 request.add("TraceAuditNumber",TraceAuditNumber);//凭证号 request.add("ConsumeAmount",ConsumeAmount);//消费金额 request.add("RetailId",OrderId);//支付订单号 request.add("IsPractical",IsPractical);//支付订单号 request.add("PayType",PayType); request.add("EnCode",prefs.getString("enCode"));//设备EN号 // request.add("OpenId",OpenId);// commonNet.requestNetTask(request,getPayListener,1); } //银联支付成功回调监听 private HttpListener<String> getPayListener = new HttpListener<String>() { @Override public void onSucceed(int what, Response<String> response) { PayCallbackBean callbackBean=gson.fromJson(response.get(),PayCallbackBean.class); if(callbackBean.isSuccess()==true){ if(payType==5){ isSuccess=true; ll_pay_cashier_accounts.setVisibility(View.GONE); tv_pay_cad.setVisibility(View.GONE); ll_pay_info.setVisibility(View.VISIBLE); tv_pay_success.setText("现金消费成功"); tv_pay_trace_audit.setText("凭证号:"+traceAuditNumber); if(curSelectedPos==1001){ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(payMoney)); } if(discount!=0.0){ //获取折后金额 discountAfter=originalPrice*(discount/10); tv_pay_discount.setVisibility(View.VISIBLE); tv_pay_discount.setText("折扣"+discount); tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(discountAfter)); }else{ tv_pay_discount.setVisibility(View.GONE); if(curSelectedPos==1001) { tv_real_pay.setText("实付:" + DecimalFormatUtils.decimalFormatRound(singleCashierMoney)); }else{ tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(payMoney)); } } //调用pos打印机 setLatticePrinter(); mRunnable = new Runnable() { @Override public void run() { mHandler.sendEmptyMessage(1); } }; mHandler .postDelayed(mRunnable, 3000); // 在Handler中执行子线程并延迟3s。 }else if(payType==4){ isSuccess=true; tv_pay_success.setText("银联消费成功"); tv_pay_cad.setVisibility(View.VISIBLE); tv_pay_cad.setText("卡号:" + rXiaoFei.primaryAccountNumber ); tv_pay_trace_audit.setText("凭证号:" + rXiaoFei.systemTraceAuditNumber); if(curSelectedPos==1001){ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(Double.parseDouble(biao))); }else{ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(payMoney)); } if(discount!=0.0){ discountAfter=Double.parseDouble(biao)*(discount/10); tv_pay_discount.setVisibility(View.VISIBLE); tv_pay_discount.setText("折扣"+discount); tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(discountAfter)); }else{ tv_pay_discount.setVisibility(View.GONE); if(curSelectedPos==1001) {//独立收银 tv_real_pay.setText("实付:" + DecimalFormatUtils.decimalFormatRound(Double.parseDouble(biao))); }else{//扫描订单收银 tv_real_pay.setText("实付:" +DecimalFormatUtils.decimalFormatRound(payMoney)); } } ll_pay_cashier_accounts.setVisibility(View.GONE); ll_pay_info.setVisibility(View.VISIBLE); } }else{ } } @Override public void onFailed(int what, Response<String> response) { ToastUtils.show(response.get()); } }; public void payLog(String LogType, String obj,String remark){ //Pay Log posPayLogNet=new PosPayLogNet(mContext); posPayLogNet.setData(LogType,obj,remark); } /** * 设置独立收银点阵打印方法 */ public void setLatticePrinter(){ try { // 设备可能没有打印机,open会抛异常 latticePrinter = WeiposImpl.as().openLatticePrinter(); } catch (Exception e) { // TODO: handle exception } //点阵打印 if (latticePrinter == null) { Toast.makeText(CashierHomeActivity.this, "尚未初始化点阵打印sdk,请稍后再试", Toast.LENGTH_SHORT).show(); return; }else{ // 打印内容赋值 latticePrinter.setOnEventListener(new IPrint.OnEventListener() { @Override public void onEvent(final int what, String in) { final String info = in; // 回调函数中不能做UI操作,所以可以使用runOnUiThread函数来包装一下代码块 runOnUiThread(new Runnable() { public void run() { final String message = SingleCashierPrinterTools.getPrintErrorInfo(what, info); if (message == null || message.length() < 1) { return; } showResultInfo("打印", "打印结果信息", message); } }); } }); //以下是设置pos打印信息 latticePrinterBean=new LatticePrinterBean(); if(payType==5){//现金 if (curSelectedPos==1001){ latticePrinterBean.setOrderId(orderNo); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ latticePrinterBean.setOrderId(scanCode); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } latticePrinterBean.setShopName(shopNameNick); latticePrinterBean.setCounterName(shopNameNick); latticePrinterBean.setShopClerkName(userName); latticePrinterBean.setTotalPoint(point); latticePrinterBean.setTraceAuditNumber(traceAuditNumber); latticePrinterBean.setPayTitleName("现金支付"); if(discount!=0.0){//折扣价格 latticePrinterBean .setVipMobile(mobile); if (curSelectedPos==1001){ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); }else{ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(payType)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } }else{//原价 latticePrinterBean .setVipMobile("非会员"); if (curSelectedPos==1001){ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); }else{ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); } } }else if(mobilePayType==2){//微信 if (curSelectedPos==1001){ latticePrinterBean.setOrderId(mobileOrderNo); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ latticePrinterBean.setOrderId(scanCode); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } latticePrinterBean.setShopName(shopNameNick); latticePrinterBean.setCounterName(shopNameNick); latticePrinterBean.setShopClerkName(userName); latticePrinterBean.setTotalPoint(point); latticePrinterBean.setTraceAuditNumber(WxAliTraceAuditNumber); latticePrinterBean.setPayTitleName("微信支付"); if(discount!=0.0){//折扣价格 latticePrinterBean .setVipMobile(mobile); latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(discountAfter)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(discountAfter)); }else{//原价 latticePrinterBean .setVipMobile("暂无会员"); if (curSelectedPos==1001){ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } } }else{//支付宝 if (curSelectedPos==1001){ latticePrinterBean.setOrderId(mobileOrderNo); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ latticePrinterBean.setOrderId(scanCode); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } latticePrinterBean.setShopName(shopNameNick); latticePrinterBean.setCounterName(shopNameNick); latticePrinterBean.setShopClerkName(userName); latticePrinterBean.setTotalPoint(point); latticePrinterBean.setTraceAuditNumber(WxAliTraceAuditNumber); latticePrinterBean.setPayTitleName("支付宝"); if(discount!=0.0){//折扣价格 latticePrinterBean .setVipMobile(mobile); latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(discountAfter)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(discountAfter)); }else{//原价 latticePrinterBean .setVipMobile("暂无会员"); if (curSelectedPos==1001){ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } } } if(curSelectedPos==1001){//独立收银打印 SingleCashierPrinterTools.printLattice(CashierHomeActivity.this, latticePrinter,latticePrinterBean,discount); }else{//扫描订单收银打印 OrderCashierPrinterTools.printLattice(CashierHomeActivity.this, latticePrinter,latticePrinterBean,orderList,discount); } //清空输入金额天和折扣金额 st=""; tv_show_discount.setText(""); } } /** * pos打印显示结果信息 * @param operInfo * @param titleHeader * @param info */ private void showResultInfo(String operInfo, String titleHeader, String info) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(titleHeader + ":" + info); builder.setTitle(operInfo); builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } public void showMsg(final String msg) { this.runOnUiThread(new Runnable() { @Override public void run() { tv_show_amount.setText(""); tv_show_amount.setTextSize(20); tv_show_amount.setText(msg); } }); } /** * 显示消费对话框 * @param core * @throws Exception */ private void showConsumeDialog(final PosCore core) throws Exception { lock[0] = LOCK_WAIT; runOnUiThread(new Runnable() { @Override public void run() { View view = getLayoutInflater().inflate(R.layout.consume_dialog, null); final AlertDialog dialog = new AlertDialog.Builder(CashierHomeActivity.this).setView(view).setCancelable(false).create(); dialog.show(); Button btn_confirm = (Button) view.findViewById(R.id.btn_consume_confiem); Button btn_cancel = (Button) view.findViewById(R.id.btn_consume_cancel); final EditText ed_consumen_amount = (EditText) view.findViewById(R.id.ed_consume_amount); ed_consumen_amount.setFocusable(false);ed_consumen_amount.setFocusableInTouchMode(false);//设置不可编辑状态; if(!TextUtils.isEmpty(ed_consumen_amount.getText().toString())){ ed_consumen_amount.setText("");//设置支付金额 } if(curSelectedPos==1001){ ed_consumen_amount.setText(biao);//设置支付金额 }else{ ed_consumen_amount.setText(payMoney+"");//设置支付金额 } btn_confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {//确定支付 synchronized (lock) { money=(int)(payMoney*100); lock[0] = LOCK_CONTINUE; lock.notify(); } dialog.dismiss(); } }); btn_cancel.setOnClickListener(new View.OnClickListener() {//取消支付 @Override public void onClick(View v) { synchronized (lock) { ed_consumen_amount.setText("");//设置支付金额 lock[0] = LOCK_CONTINUE; lock.notify(); } dialog.dismiss(); } }); } }); // 等待输入 synchronized (lock) { while (true) { if (lock[0] == LOCK_WAIT) { try { lock.wait(500); } catch (InterruptedException e) { e.printStackTrace(); } } else { break; } } } //判断是否独立收银金额和扫描订单金额 if(curSelectedPos==1001){ double money=Double.parseDouble(biao); Integer dd=(int)(money*100); core.setXiaoFeiAmount(dd+""); }else{ core.setXiaoFeiAmount(money+"");//设置消费金额 } } /** * 收银回调 */ public class PosCallBack implements IPosCallBack { private final PosCore core; PosCallBack(PosCore core) { this.core = core; } @Override public void onInfo(String s) { showMsg(s); } @Override public void onEvent(int eventID, Object[] params) throws Exception { switch (eventID) { case 110: showMsg("打印票据" + params[0]); break; case EVENT_Setting:{ core.reprint(refNum); showMsg("doSetting:完成"); break; } case EVENT_Task_start: { showMsg("任务进程开始执行"); break; } case EVENT_Task_end: { showMsg("任务进程执行结束"); break; } case EVENT_CardID_start: { Log.i("test", "读取银行卡信息" + params[0]); showMsg("读取银行卡信息"); break; } case EVENT_CardID_end: { String cardNum = (String) params[0]; if (!TextUtils.isEmpty(cardNum)) { Log.w(Constant.TAG, "卡号为:" + params[0]); try{ primaryAccountNumber=params[0]+""; //获取发卡行,卡种名称 cardName= BankUtil.getNameOfBank(primaryAccountNumber); bankName=cardName.substring(0, cardName.indexOf("·")); if(cardName.contains("贷记卡")){ cardCategory=3; }else if(cardName.contains("信用卡")){ cardCategory=2; }else{//借记卡 cardCategory=1; } showConsumeDialog(core); }catch (Exception e){ e.printStackTrace(); } }else{ ToastUtils.getLongToast(mContext,"获取银行卡号为空!"); } break; } case EVENT_Comm_start: { showMsg("开始网络通信"); break; } case EVENT_Comm_end: { showMsg("网络通信完成"); break; } case EVENT_DownloadPlugin_start: { showMsg("开始下载插件"); break; } case EVENT_DownloadPlugin_end: { showMsg("插件下载完成"); break; } case EVENT_InstallPlugin_start: { showMsg("开始安装插件"); break; } case EVENT_InstallPlugin_end: { showMsg("插件安装完成"); break; } case EVENT_RunPlugin_start: { showMsg("开始启动插件"); break; } case EVENT_RunPlugin_end: { showMsg("插件启动完成"); break; } case EVENT_AutoPrint_start:{ showMsg("参考号:" + params[0]); setCachePayInfo(params[0]+""); break; } case EVENT_AutoPrint_end://打印完成 break; case IPosCallBack.ERR_InTask:{ if ((Integer) params[0] == EVENT_NO_PAPER) { showRePrintDialog(); } } default: { showMsg("Event:" + eventID); break; } } } } /** * 缓存支付信息 * @param refNum */ private void setCachePayInfo(String refNum){ if(mCache.getAsString("PayInfo")!=null && !"".equals(mCache.getAsString("PayInfo"))){ mCache.remove("PayInfo"); mCache.put("PayInfo",refNum); }else{ mCache.put("PayInfo",refNum); } } private boolean needRePrint; /** * 显示重打印按钮 */ private void showRePrintDialog() { lock[0] = LOCK_WAIT; runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder dialog = new AlertDialog.Builder(CashierHomeActivity.this); dialog.setMessage("打印机缺纸"); dialog.setPositiveButton("重打印", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { synchronized (lock) { needRePrint = true; lock[0] = LOCK_CONTINUE; lock.notify(); } } }); dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { synchronized (lock) { needRePrint = false; lock[0] = LOCK_CONTINUE; lock.notify(); } } }); dialog.setCancelable(false); dialog.show(); } }); // 等待输入 synchronized (lock) { while (true) { if (lock[0] == LOCK_WAIT) { try { lock.wait(500); } catch (InterruptedException e) { e.printStackTrace(); } } else { break; } } } try { pCore.printContinue(needRePrint); } catch (Exception e) { e.printStackTrace(); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onDataSynEvent(ResultGetTokenBean msg) { if(msg.IsSuccess==true){ prefs.putString("RongToken", msg.TModel.token+""); connect(msg.TModel.token); }else{ ToastUtils.getLongToast(mContext,"获取融云ToKen失败!"); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onDataSynEvent(ReceiveMessageBean msg) { if(msg.getContent()!=null){ Log.i("test","新的消息"+msg.getContent()); if(mCache.getAsString("isOpenSound")!=null && mCache.getAsString("isOpenSound").equals("true")){ //初始化声音播放 SoundPoolUtils.initMediaPlayer(mContext); // Skip.mNext(mActivity,ConversationListActivity.class); Skip.mNext(mActivity, CheckAccountsListActivity.class); } } } /** * <p>连接服务器,在整个应用程序全局,只需要调用一次,需在 {@link #//init(Context)} 之后调用。</p> * <p>如果调用此接口遇到连接失败,SDK 会自动启动重连机制进行最多10次重连,分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。 * 在这之后如果仍没有连接成功,还会在当检测到设备网络状态变化时再次进行重连。</p> * * @param token 从服务端获取的用户身份令牌(Token)。 * @param //callback 连接回调。 * @return RongIM 客户端核心类的实例。 */ private void connect(String token) { if (getApplicationInfo().packageName.equals(App.getCurProcessName(getApplicationContext()))) { RongIM.connect(token, new RongIMClient.ConnectCallback() { /** * Token 错误。可以从下面两点检查 1. Token 是否过期,如果过期您需要向 App Server 重新请求一个新的 Token * 2. token 对应的 appKey 和工程里设置的 appKey 是否一致 */ @Override public void onTokenIncorrect() { Log.d(Constant.TAG, "--onTokenIncorrect" ); } /** * 连接融云成功 * @param userid 当前 token 对应的用户 id */ @Override public void onSuccess(String userid) { Log.d(Constant.TAG, "--连接融云成功" ); InitListener.init(userid,mContext,mActivity); } /** * 连接融云失败 * @param errorCode 错误码,可到官网 查看错误码对应的注释 */ @Override public void onError(RongIMClient.ErrorCode errorCode) { Log.d(Constant.TAG, "--ErrorCode" +errorCode); } }); } } /** * Author FGB * Description 任务管理 * Created at 2017/11/20 22:47 * Version 1.0 */ public class TimerManager { public TimerManager(final long PERIOD_DAY ) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 1); //凌晨1点 calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Date date=calendar.getTime(); //第一次执行定时任务的时间 //如果第一次执行定时任务的时间 小于当前的时间 //此时要在 第一次执行定时任务的时间加一天,以便此任务在下个时间点执行。如果不加一天,任务会立即执行。 if (date.before(new Date())) { date = this.addDay(date, 1); } Timer timer = new Timer(); Task task = new Task(); //安排指定的任务在指定的时间开始进行重复的固定延迟执行。 timer.schedule(task,date,PERIOD_DAY); } // 增加或减少天数 public Date addDay(Date date, int num) { Calendar startDT = Calendar.getInstance(); startDT.setTime(date); startDT.add(Calendar.DAY_OF_MONTH, num); return startDT.getTime(); } } // public class Task extends TimerTask { // public void run() { // //执行定时任务 查询当天订单数据 // PosSqliteDatabaseUtils.selectData(mContext); // } // } // private List<PosPayBean> posPayBeanList; // @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 // public void onDataSynEvent(List<PosPayBean> posPayBeanArrayList) { // if(posPayBeanArrayList.size()!=0){ // posPayBeanList=new ArrayList<>(); // posPayBeanList=posPayBeanArrayList; // strJson= JsonUtils.toJson(posPayBeanList); //// payLog("PayLog",strJson,AbDateUtil.getCurrentDate());//上线记得开启日志上传 // }else{ // ToastUtils.getLongToast(mContext,"当前没有订单记录可上传!"); // } // } // // @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 // public void onDataSynEvent(PayLogBean bean) { // if(bean.isSuccess()!=false){ // ToastUtils.getLongToast(mContext,"上传日志成功!"); // }else{ // ToastUtils.getLongToast(mContext,"上传日志失败!"); // } // } }
UTF-8
Java
87,974
java
CashierHomeActivity.java
Java
[ { "context": "=======================================\n * 作 者:FGB\n * 描 述:POS收银首页\n * 创建日期:2016/10/26\n * 版 本:1.", "end": 4854, "score": 0.9995543360710144, "start": 4851, "tag": "USERNAME", "value": "FGB" }, { "context": " originalPrice;//原价\n private String userName;//用...
null
[]
package com.cesaas.android.pos.activity.cashier; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.cesaas.android.pos.R; import com.cesaas.android.pos.activity.order.DownOrderActivity; import com.cesaas.android.pos.activity.order.OrderDetailActivity; import com.cesaas.android.pos.activity.order.WaitPayOrderDetailActivity; import com.cesaas.android.pos.activity.user.LoginActivity; import com.cesaas.android.pos.activity.user.SettingActivity; import com.cesaas.android.pos.base.BaseActivity; import com.cesaas.android.pos.base.BaseRecyclerView; import com.cesaas.android.pos.bean.PayCallbackBean; import com.cesaas.android.pos.bean.PayLogBean; import com.cesaas.android.pos.bean.PosBean; import com.cesaas.android.pos.bean.PosOrderIdBean; import com.cesaas.android.pos.bean.PosPayLogBean; import com.cesaas.android.pos.bean.ResultCreatePayBean; import com.cesaas.android.pos.bean.ResultGetOrderBean; import com.cesaas.android.pos.bean.ResultGetTokenBean; import com.cesaas.android.pos.bean.ResultHomeCreateFromStoreBean; import com.cesaas.android.pos.bean.ShopVipBean; import com.cesaas.android.pos.bean.UserInfoBean; import com.cesaas.android.pos.bean.printer.LatticePrinterBean; import com.cesaas.android.pos.db.bean.PosPayBean; import com.cesaas.android.pos.db.pay.PosSqliteDatabaseUtils; import com.cesaas.android.pos.db.pay.Task; import com.cesaas.android.pos.db.pay.TimerManager; import com.cesaas.android.pos.global.App; import com.cesaas.android.pos.global.Constant; import com.cesaas.android.pos.global.Urls; import com.cesaas.android.pos.gridview.CashierGridAdapter; import com.cesaas.android.pos.gridview.MyGridView; import com.cesaas.android.pos.inventory.activity.InventoryMainActivity; import com.cesaas.android.pos.listener.OnItemClickListener; import com.cesaas.android.pos.net.nohttp.HttpListener; import com.cesaas.android.pos.net.xutils.net.CreatePayNet; import com.cesaas.android.pos.net.xutils.net.GetTokenNet; import com.cesaas.android.pos.net.xutils.net.PayFormStoreNet; import com.cesaas.android.pos.net.xutils.net.PosPayLogNet; import com.cesaas.android.pos.pos.adapter.PosPayCategoryAdapter; import com.cesaas.android.pos.rongcloud.activity.ConversationListActivity; import com.cesaas.android.pos.rongcloud.bean.ReceiveMessageBean; import com.cesaas.android.pos.rongcloud.listener.InitListener; import com.cesaas.android.pos.storedvalue.bean.ResultPayCategoryBean; import com.cesaas.android.pos.storedvalue.ui.SummaryActivity; import com.cesaas.android.pos.test.utils.SlidingMenu; import com.cesaas.android.pos.utils.AbAppUtil; import com.cesaas.android.pos.utils.AbDateUtil; import com.cesaas.android.pos.utils.BankUtil; import com.cesaas.android.pos.utils.CheckUtil; import com.cesaas.android.pos.utils.DecimalFormatUtils; import com.cesaas.android.pos.utils.JsonUtils; import com.cesaas.android.pos.utils.OrderCashierPrinterTools; import com.cesaas.android.pos.utils.RandomUtils; import com.cesaas.android.pos.utils.SingleCashierPrinterTools; import com.cesaas.android.pos.utils.Skip; import com.cesaas.android.pos.utils.SoundPoolUtils; import com.cesaas.android.pos.utils.ToastUtils; import com.wangpos.pay.UnionPay.PosConfig; import com.wangpos.poscore.IPosCallBack; import com.wangpos.poscore.PosCore; import com.wangpos.poscore.impl.PosCoreFactory; import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView; import com.yolanda.nohttp.NoHttp; import com.yolanda.nohttp.RequestMethod; import com.yolanda.nohttp.rest.Request; import com.yolanda.nohttp.rest.Response; import com.zhl.cbdialog.CBDialogBuilder; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.TimerTask; import cn.weipass.pos.sdk.IPrint; import cn.weipass.pos.sdk.LatticePrinter; import cn.weipass.pos.sdk.impl.WeiposImpl; import io.rong.imkit.RongIM; import io.rong.imlib.RongIMClient; import scanner.CaptureActivity; /** * ================================================ * 作 者:FGB * 描 述:POS收银首页 * 创建日期:2016/10/26 * 版 本:1.0 * 修订历史: * ================================================ */ public class CashierHomeActivity extends BaseActivity implements View.OnClickListener{ private static final int CAMERA = 1;//相机权限 private byte[] lock = new byte[1]; int EVENT_NO_PAPER = 1; private final int LOCK_WAIT = 0; private final int LOCK_CONTINUE = 1; private int REQUEST_CONTACT = 20; final int RESULT_CODE = 101; private String scanCode; //8583协议中的参考号 private String refNum; private PosCore pCore; private PosCallBack callBack; private String amount; private Integer money; private double singleCashierMoney=0.0; private int orderStatus; private String orderId; private int curSelectedPos=1001;//当前选择的收银【1001:独立收银,1002:扫描订单收银】 private String vipMobile;//会员手机 private String mobile; private int point;//积分 private String orderShopId;//订单店铺ID private String userShopId;//用户店铺ID private String vipId;//vip ID private String icon; private int fansId; private String fansNickName; private String openId;//会员openId private double payMoney;//订单支付价格 private double totalPrice;//原价 private int mobilePayType;//移动支付类型 private String WxAliTraceAuditNumber;//微信&支付宝凭证号 private double mobilepayMoney;//移动支付金额 private String mobileOrderNo;//移动支付订单号 private int IsPractical; private String biao; private PosBean posBean; private String refNo; private PosOrderIdBean idBean; //独立收银订单号 private String orderNo; private double discount;//会员折扣 private double discountAfter;//折后金额 private double originalPrice;//原价 private String userName;//用户名【营业员】 private String shopNameNick;//店铺名 private int payType; private boolean isSuccess=false; PosCore.RXiaoFei rXiaoFei; private String referenceNumber;//参考号 private String traceAuditNumber;//凭证号 private String primaryAccountNumber;//卡号 private String cardName=null;//银行卡名称 private String bankName=null;////发卡行名称 private int cardCategory=100;//卡类型 private MyGridView gridView;//九宫格gridView private ImageView iv_add_vip,iv_add_scan_vip,iv_back_del; private EditText tv_show_amount,tv_show_discount,et_add_vip_mobile; private TextView tv_cashier_pay,tv_pos_more,tv_vip_name,tv_vip_mobile,tv_app_version, tv_vip_shop,tv_vip_point,tv_vip_discount,tv_vip_grade,tv_radix_point,tv_zero; private TextView tv_pay_success,tv_pay_trace_audit,tv_pay_original_price,tv_real_pay,tv_pay_discount,tv_pay_cad; private LinearLayout ll_weixin_pay,ll_ali_pay,ll_union_pay,ll_cash_pay,ll_query_vip,ll_query_info; private LinearLayout ll_single_weixin_pay,ll_single_ali_pay,ll_single_union_pay,ll_single_cash_pay,ll_cancel_cashier; private LinearLayout ll_pay_info,ll_pay_cashier_accounts,ll_vip_info_btn,ll_scan; private LinearLayout ll_check_accounts,ll_down_order,ll_settle_accounts,ll_inventory,llStoredValue,ll_app_setting,ll_convers; private LinearLayout rl_exit; private String st = ""; private CustomSingleCashierDialog singleCashierDialog; private CustomAddVipDialog addVipDialog; private SlidingMenu mMenu; private LatticePrinter latticePrinter;// 点阵打印 private LatticePrinterBean latticePrinterBean; private Handler handler; private int TIME = 2000; private PosPayLogBean posPayLogBean; private PosPayLogNet posPayLogNet; private CreatePayNet createPayNet; private String strJson; private ArrayList<ResultGetOrderBean.OrderDetailBean> orderList;//商品订单列表 private GetTokenNet getTokenNet; private ArrayList<TextView> tvs=new ArrayList<TextView>(); private Runnable mRunnable; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); mHandler.removeCallbacks(mRunnable); //调用pos打印机 setLatticePrinter(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cashier_home); mMenu = (SlidingMenu) findViewById(R.id.id_menu); //通过EventBus订阅事件 if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } if(prefs.getString("RongToken")!=null){ connect(prefs.getString("RongToken")); }else{ getTokenNet=new GetTokenNet(mContext); getTokenNet.setData(); } if(mCache.getAsString("isOpenSound")==null){ mCache.put("isOpenSound","true"); } getUserInfo(); checkAndRequestPermission(); //初始化CoreApp连接对象 initPosCore(); initView(); initGridView(); getMobilePay(); // initTask(); } // private void initTask(){ // //时间间隔(一天) // new TimerManager(24 * 60 * 60 * 1000); // } /** * 获取移动支付信息并且通过pos打印 */ public void getMobilePay(){ Bundle bundle=getIntent().getExtras(); if(bundle!=null){ mobilePayType=bundle.getInt("mobilePayType"); WxAliTraceAuditNumber=bundle.getString("WxAliTraceAuditNumber"); mobilepayMoney=bundle.getDouble("mobilepayMoney"); mobileOrderNo=bundle.getString("mobileOrderNo"); discount=bundle.getDouble("discount"); shopNameNick=bundle.getString("shopNameNick"); userName=bundle.getString("userName"); point=bundle.getInt("point"); originalPrice=bundle.getDouble("originalPrice"); discountAfter=bundle.getDouble("discountAfter"); mobile=bundle.getString("mobile"); isSuccess=bundle.getBoolean("isSuccess"); if(mobilePayType==2 || mobilePayType==3){//微信&支付宝 if(mobilePayType==2){ tv_pay_success.setText("微信消费成功"); }else{ tv_pay_success.setText("支付宝消费成功"); } ll_pay_cashier_accounts.setVisibility(View.GONE); ll_pay_info.setVisibility(View.VISIBLE); tv_pay_trace_audit.setText("凭证号:"+WxAliTraceAuditNumber); tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(originalPrice)); if(discount!=0.0){ //获取折后金额 tv_pay_discount.setVisibility(View.VISIBLE); tv_pay_discount.setText("折扣"+discount); tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(mobilepayMoney)); }else{ tv_pay_discount.setVisibility(View.GONE); tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(mobilepayMoney)); } posPayLogBean=new PosPayLogBean(); posPayLogBean.setOrderId(mobileOrderNo);//支付订单 posPayLogBean.setPayAmount(mobilepayMoney);//支付金额 posPayLogBean.setTraceAuditNumber(WxAliTraceAuditNumber);//支付凭证号 posPayLogBean.setPayType(mobilePayType);//支付类型 posPayLogBean.setRemark("独立收银"); posPayLogBean.setEnCode(prefs.getString("enCode"));//设备EN号 strJson=gson.toJson(posPayLogBean); getPayListener("",WxAliTraceAuditNumber,mobilepayMoney,mobileOrderNo,mobilePayType,"notFansVip",IsPractical); if(isSuccess==true){ //调用pos打印机 setLatticePrinter(); mRunnable = new Runnable() { @Override public void run() { mHandler.sendEmptyMessage(1); } }; mHandler .postDelayed(mRunnable, 3000); // 在Handler中执行子线程并延迟3s。 } } } } /** * 初始化视图控件 */ public void initView(){ tv_app_version= (TextView) findViewById(R.id.tv_app_version); tv_app_version.setText("V"+ AbAppUtil.getAppVersion(this)); ll_pay_cashier_accounts= (LinearLayout) findViewById(R.id.ll_pay_cashier_accounts); ll_pay_info= (LinearLayout) findViewById(R.id.ll_pay_info); ll_scan= (LinearLayout) findViewById(R.id.ll_scan); tv_pay_success= (TextView) findViewById(R.id.tv_pay_success); tv_pay_trace_audit= (TextView) findViewById(R.id.tv_pay_trace_audit); tv_pay_original_price= (TextView) findViewById(R.id.tv_pay_original_price); tv_real_pay= (TextView) findViewById(R.id.tv_real_pay); tv_pay_discount= (TextView) findViewById(R.id.tv_pay_discount); tv_pay_cad= (TextView) findViewById(R.id.tv_pay_cad); tv_radix_point= (TextView) findViewById(R.id.tv_radix_point); tv_zero= (TextView) findViewById(R.id.tv_zero); iv_back_del= (ImageView) findViewById(R.id.iv_back_del); tv_radix_point.setOnClickListener(this); tv_zero.setOnClickListener(this); iv_back_del.setOnClickListener(this); ll_scan.setOnClickListener(this); tv_show_amount= (EditText) findViewById(R.id.tv_show_amount); tv_show_discount= (EditText) findViewById(R.id.tv_show_discount); tv_cashier_pay= (TextView) findViewById(R.id.tv_cashier_pay); tv_pos_more= (TextView) findViewById(R.id.tv_pos_more); gridView= (MyGridView) findViewById(R.id.gridview); iv_add_vip= (ImageView) findViewById(R.id.iv_add_vip); tv_cashier_pay.setOnClickListener(this); tv_pos_more.setOnClickListener(this); rl_exit= (LinearLayout) findViewById(R.id.rl_exit); ll_inventory= (LinearLayout) findViewById(R.id.ll_inventory); ll_down_order= (LinearLayout) findViewById(R.id.ll_down_order); ll_check_accounts= (LinearLayout) findViewById(R.id.ll_check_accounts); ll_settle_accounts= (LinearLayout) findViewById(R.id.ll_settle_accounts); llStoredValue= (LinearLayout) findViewById(R.id.ll_stored_value); ll_app_setting= (LinearLayout) findViewById(R.id.ll_app_setting); ll_convers= (LinearLayout) findViewById(R.id.ll_convers); //设置点击监听 rl_exit.setOnClickListener(this); ll_inventory.setOnClickListener(this); ll_down_order.setOnClickListener(this); ll_check_accounts.setOnClickListener(this); iv_add_vip.setOnClickListener(this); ll_settle_accounts.setOnClickListener(this); llStoredValue.setOnClickListener(this); ll_app_setting.setOnClickListener(this); ll_convers.setOnClickListener(this); } /** * 检查权限【Android6.0动态申请运行时权限】 */ private void checkAndRequestPermission(){ if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { Log.i(Constant.TAG, "hi! everybody, I really need ths permission for better service. thx!"); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA); } } } /** * 处理授权请求回调 使用onRequestPermissionsResult(int ,String , int[])方法处理回调, 上面说到了根据requestPermissions()方法中的requestCode, 就可以在回调方法中区分授权请求 */ @SuppressLint("Override") @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case CAMERA: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.i(Constant.TAG, "PERMISSION_GRANTED: Thx, I will give u a better service!"); } else { Log.i(Constant.TAG, "PERMISSION_DENIED: Sorry, without this permission I can't do next work for u"); } return; } } } public void CONTENT(String number){ StringBuffer sb = new StringBuffer(st); // if (st.equals("0")){ // st = number; // }else { sb.append(number); st = sb.toString(); // } if (st.indexOf(".")!=-1){ String newSt = st.substring(st.indexOf("."),st.length()); if (newSt.length()>3){ st = st.substring(0,st.length()-1); } } } public void initGridView(){ gridView.setAdapter(new CashierGridAdapter(mContext)); //九宫格点击事件 gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: CONTENT("1"); hidAndShow(); break; case 1: CONTENT("2"); hidAndShow(); break; case 2: CONTENT("3"); hidAndShow(); break; case 3: CONTENT("4"); hidAndShow(); break; case 4: CONTENT("5"); hidAndShow(); break; case 5: CONTENT("6"); hidAndShow(); break; case 6: CONTENT("7"); hidAndShow(); break; case 7: CONTENT("8"); hidAndShow(); break; case 8: CONTENT("9"); hidAndShow(); break; case 9: if(TextUtils.isEmpty(tv_show_amount.getText().toString())){ }else{ CONTENT("."); } hidAndShow(); tv_show_amount.setText(st); break; case 10: CONTENT("0"); hidAndShow(); tv_show_amount.setText(st); break; case 11: if(st.equals("")){ }else{ st = st.substring(0,st.length()-1); } hidAndShow(); break; default: break; } tv_show_amount.setText(st); } }); } public void hidAndShow(){ if(isSuccess==true){ ll_pay_cashier_accounts.setVisibility(View.VISIBLE); ll_pay_info.setVisibility(View.GONE); } } /** * 接收支付流水结果信息 * @param bean */ @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 public void onDataSynEvent(ResultCreatePayBean bean) { if(bean.isSuccess()!=false){ if(payType==5){ isSuccess=true; ll_pay_cashier_accounts.setVisibility(View.GONE); ll_pay_info.setVisibility(View.VISIBLE); tv_pay_success.setText("现金消费成功"); tv_pay_trace_audit.setText("凭证号:"+traceAuditNumber); // if(curSelectedPos==1001){ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(Double.parseDouble(tv_show_amount.getText().toString()))); originalPrice=DecimalFormatUtils.decimalFormatRound(Double.parseDouble(tv_show_amount.getText().toString())); payMoney=DecimalFormatUtils.decimalFormatRound(Double.parseDouble(tv_show_amount.getText().toString())); totalPrice=DecimalFormatUtils.decimalFormatRound(Double.parseDouble(tv_show_amount.getText().toString())); posPayLogBean=new PosPayLogBean(); posPayLogBean.setOrderId(orderId);//支付订单 posPayLogBean.setPayAmount(totalPrice);//支付金额 posPayLogBean.setTraceAuditNumber(referenceNumber);//支付凭证号 posPayLogBean.setPayType(5);//支付类型 posPayLogBean.setRemark("独立收银"); posPayLogBean.setEnCode(prefs.getString("enCode"));//设备EN号 strJson=gson.toJson(posPayLogBean); tv_real_pay.setText("实付:" +DecimalFormatUtils.decimalFormatRound(Double.parseDouble(tv_show_amount.getText().toString()))); //调用pos打印机 setLatticePrinter(); mRunnable = new Runnable() { @Override public void run() { mHandler.sendEmptyMessage(1); } }; mHandler .postDelayed(mRunnable, 3000); // 在Handler中执行子线程并延迟3s。 }else if(payType==4){ if(payType==4){ isSuccess=true; PosPayBean bean1=new PosPayBean(prefs.getString("userShopId"),shopNameNick,userName,orderId,payMoney+"",rXiaoFei.retrievalReferenceNumber,"4","银联支付",IsPractical+"","3",AbDateUtil.getCurrentDate(),"消费成功...",prefs.getString("enCode"),rXiaoFei.primaryAccountNumber,"true","0","1"); insertData(bean1); tv_pay_success.setText("银联消费成功"); tv_pay_cad.setVisibility(View.VISIBLE); tv_pay_cad.setText("卡号:" + rXiaoFei.primaryAccountNumber ); tv_pay_trace_audit.setText("凭证号:" + rXiaoFei.systemTraceAuditNumber); if(curSelectedPos==1001){ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(Double.parseDouble(biao))); }else{ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(payMoney)); } if(discount!=0.0){ discountAfter=Double.parseDouble(biao)*(discount/10); tv_pay_discount.setVisibility(View.VISIBLE); tv_pay_discount.setText("折扣"+discount); tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(discountAfter)); }else{ tv_pay_discount.setVisibility(View.GONE); if(curSelectedPos==1001) {//独立收银 tv_real_pay.setText("实付:" + DecimalFormatUtils.decimalFormatRound(Double.parseDouble(biao))); }else{//扫描订单收银 tv_real_pay.setText("实付:" +DecimalFormatUtils.decimalFormatRound(payMoney)); } } } } }else{ // ToastUtils.getToast(mContext,"创建支付流水失败:"+bean.getMessage()); // Log.d(Constant.TAG,"支付error:"+bean.getMessage()); //记录pos 支付日志 if(payType==1){//积分支付退款回调 }else if(payType==2){//微信支付退款回调 payLog("PayFromStore",strJson,"微信支付"); }else if(payType==3){//支付宝退款回调 payLog("PayFromStore",strJson,"支付宝"); }else if(payType==4){//银联支付退款回调 payLog("PayFromStore",strJson,"银联支付"); auditOrder(); }else if(payType==5){//现金支付退款回调 payLog("PayFromStore",strJson,"现金支付"); ; } } } private void insertData(PosPayBean bean){ PosSqliteDatabaseUtils.insterData(mContext,bean); } public void auditOrder(){ new CBDialogBuilder(CashierHomeActivity.this) .setTouchOutSideCancelable(true) .showCancelButton(true) .setTitle("温馨提示!") .setMessage("该订单审核失败,请重新审核!") .setConfirmButtonText("审核") .setCancelButtonText("取消") .setDialogAnimation(CBDialogBuilder.DIALOG_ANIM_SLID_BOTTOM) .setButtonClickListener(true, new CBDialogBuilder.onDialogbtnClickListener() { @Override public void onDialogbtnClick(Context context, Dialog dialog, int whichBtn) { switch (whichBtn) { case BUTTON_CONFIRM: createPayNet=new CreatePayNet(mContext); if(mCache.getAsString("PayInfo")!=null){ createPayNet.setData(mCache.getAsString("PayInfo"),Double.parseDouble(biao),4,mCache.getAsString("PayInfo"),rXiaoFei.retrievalReferenceNumber,primaryAccountNumber,"银联刷卡",rXiaoFei.systemTraceAuditNumber,userShopId,bankName,2,cardCategory); }else{ createPayNet.setData(primaryAccountNumber,Double.parseDouble(biao),4,primaryAccountNumber,rXiaoFei.retrievalReferenceNumber,primaryAccountNumber,"银联刷卡",primaryAccountNumber,userShopId,bankName,2,cardCategory); } break; case BUTTON_CANCEL: ToastUtils.show("已取消审核,请联系管理员!"); break; default: break; } } }) .create().show(); } @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 public void onDataSynEvent(ResultHomeCreateFromStoreBean bean) { if(bean.isSuccess()==true && bean.TModel!=null){//订单号不为null,显示支付方式dialog orderNo=bean.TModel.RetailId+""; singleCashierDialog=new CustomSingleCashierDialog(mContext, R.style.dialog, R.layout.item_custom_single_cashier_dialog); singleCashierDialog.show(); singleCashierDialog.setCancelable(false); }else{ ToastUtils.show("下单失败!"+bean.getMessage()); } } /** * Called when a view has been clicked. * * @param v The view that was clicked. */ @Override public void onClick(View v) { switch (v.getId()){ case R.id.tv_radix_point://小数点 CONTENT("."); tv_show_amount.setText(st); break; case R.id.tv_zero://0 CONTENT("0"); tv_show_amount.setText(st); break; case R.id.iv_back_del://回删 if(st.equals("")){ }else{ st = st.substring(0,st.length()-1); } break; case R.id.iv_add_vip://添加会员 if(TextUtils.isEmpty(tv_show_amount.getText().toString()) || tv_show_amount.getText().toString().equals("¥0.0") || tv_show_amount.getText().toString().equals("0") || tv_show_amount.getText().toString().equals("0.0")){ ToastUtils.show("请先输入收款金额!"); }else{ addVipDialog=new CustomAddVipDialog(mContext,R.style.dialog,R.layout.item_custom_add_vip_dialog); addVipDialog.show(); addVipDialog.setCancelable(false); } break; case R.id.ll_scan://扫描支付订单 curSelectedPos=1002; Skip.mScanOrderActivityResult(mActivity, CaptureActivity.class, REQUEST_CONTACT); break; case R.id.tv_cashier_pay://独立收银 curSelectedPos=1001; if(!TextUtils.isEmpty(tv_show_amount.getText().toString()) && !tv_show_amount.getText().toString().equals("¥0.0")){ singleCashierDialog=new CustomSingleCashierDialog(mContext, R.style.dialog, R.layout.item_custom_single_cashier_dialog); singleCashierDialog.show(); singleCashierDialog.setCancelable(false); }else{ ToastUtils.show("请输入收款金额在收银!"); } break; case R.id.tv_pos_more://更多 mMenu.toggle(); break; case R.id.ll_check_accounts://查单 mMenu.closeMenu(); // Skip.mNext(mActivity, CheckAccountsActivity.class); Skip.mNext(mActivity, CheckAccountsListActivity.class); break; case R.id.ll_settle_accounts://结算对账 mMenu.closeMenu(); bundle.putString("shopName",shopNameNick); bundle.putString("userName",userName); Skip.mNextFroData(mActivity,SettleAccountsActivity.class,bundle); break; case R.id.ll_down_order://下单 mMenu.closeMenu(); bundle.putString("userName",userName); Skip.mNextFroData(mActivity, DownOrderActivity.class,bundle); break; case R.id.ll_stored_value://充值 Skip.mNext(mActivity, SummaryActivity.class); break; case R.id.ll_inventory://盘点 mMenu.closeMenu(); Skip.mNext(mActivity,InventoryMainActivity.class); break; case R.id.rl_exit://退出 mMenu.closeMenu(); exit(); break; case R.id.ll_app_setting: Skip.mNext(mActivity,SettingActivity.class); break; case R.id.ll_convers: Skip.mNext(mActivity,ConversationListActivity.class); break; } } /** * 退出 */ public void exit(){ new CBDialogBuilder(CashierHomeActivity.this) .setTouchOutSideCancelable(true) .showCancelButton(true) .setTitle("退出登录") .setMessage("是否退出登录,退出后将不能做任何操作!") .setConfirmButtonText("确定") .setCancelButtonText("取消") .setDialogAnimation(CBDialogBuilder.DIALOG_ANIM_SLID_BOTTOM) .setButtonClickListener(true, new CBDialogBuilder.onDialogbtnClickListener() { @Override public void onDialogbtnClick(Context context, Dialog dialog, int whichBtn) { switch (whichBtn) { case BUTTON_CONFIRM: prefs.cleanAll(); mCache.remove("GetPayCategory"); Skip.mNext(mActivity, LoginActivity.class, true); break; case BUTTON_CANCEL: ToastUtils.show("已取消退出"); break; default: break; } } }) .create().show(); } /** * 读取用户信息 */ public void getUserInfo(){ Request<String> request = NoHttp.createStringRequest(Urls.USER_INFO, RequestMethod.POST); commonNet.requestNetTask(request,userInfoListener); if(mCache.getAsString("GetPayCategory")!=null){ }else{ Request<String> requestPay = NoHttp.createStringRequest(Urls.GET_PAY_CATEGORY, RequestMethod.POST); commonNet.requestNetTask(requestPay, getPayList); } } //待支付订单详情回调监听 public HttpListener<String> getPayList = new HttpListener<String>() { @Override public void onSucceed(int what, Response<String> response) { Log.i("test","value:"+response.get()); mCache.put("GetPayCategory",response.get()); } @Override public void onFailed(int what, Response<String> response) { Log.d(Constant.TAG,"Failed:"+response.getException()); } }; //UserInfo回调监听 private HttpListener<String> userInfoListener = new HttpListener<String>() { @Override public void onSucceed(int what, Response<String> response) { UserInfoBean bean= gson.fromJson(response.get(),UserInfoBean.class); Log.i(Constant.TAG,"userinfo"+response.get().toString()); if(bean.TModel!=null){ shopNameNick=bean.TModel.getShopName(); userName=bean.TModel.getName(); userShopId=bean.TModel.getShopId(); icon=bean.TModel.getIcon(); vipId=bean.TModel.getVipId(); prefs.putString("userName",userName); prefs.putString("userShopId",userShopId); prefs.putString("shopNameNick",shopNameNick); prefs.putString("ShopAddress",bean.TModel.getShopAddress()); prefs.putString("ShopArea",bean.TModel.getShopArea()); }else{ ToastUtils.show(""+bean.getMessage()); } } @Override public void onFailed(int what, Response<String> response) { ToastUtils.show(response.getException().getMessage()); } }; /** * 会员监听 */ public void getVipListener(String mobile,int type){ Request<String> request = NoHttp.createStringRequest(Urls.QUERY_VIP, RequestMethod.POST); request.add("Type",type);//Type:0 手机号, 1:VIpId request.add("Val",mobile); commonNet.requestNetTask(request,getStatisticsListener,1); } /** * 会员监听回调 */ private HttpListener<String> getStatisticsListener = new HttpListener<String>() { @Override public void onSucceed(int what, Response<String> response) { // Log.i("info","会员result:"+response.get()); ShopVipBean bean=gson.fromJson(response.get(),ShopVipBean.class); if(bean.TModel!=null){ ll_query_vip.setVisibility(View.GONE); ll_query_info.setVisibility(View.VISIBLE); ll_vip_info_btn.setVisibility(View.VISIBLE); discount=bean.TModel.getFANS_DISCOUNT(); mobile=bean.TModel.getFANS_MOBILE(); point=bean.TModel.getFANS_POINT(); openId=bean.TModel.getFANS_OPENID(); fansId=bean.TModel.getFANS_ID(); fansNickName=bean.TModel.getFANS_NAME(); tv_vip_name.setText(bean.TModel.getFANS_NAME()); tv_vip_mobile.setText(bean.TModel.getFANS_MOBILE()); tv_vip_shop.setText(bean.TModel.getFANS_SHOPNAME()); tv_vip_point.setText(bean.TModel.getFANS_POINT()+""); tv_vip_discount.setText(bean.TModel.getFANS_DISCOUNT()+""); tv_vip_grade.setText(bean.TModel.getFANS_GRADE()); }else{ ToastUtils.show("未找到改会员,请核实输入信息!"); } } @Override public void onFailed(int what, Response<String> response) { ToastUtils.show(response.get()); } }; /** * 自定义添加会员Dialog */ public class CustomAddVipDialog extends Dialog implements View.OnClickListener{ int layoutRes;//布局文件 Context context; private LinearLayout ll_sure_query_vip,ll_cancel_back_cashier,ll_sure_add_vip,ll_cancel_back_query; /** * 自定义添加会员D主题及布局的构造方法 * @param context * @param theme * @param resLayout */ public CustomAddVipDialog(Context context, int theme,int resLayout){ super(context, theme); this.context = context; this.layoutRes=resLayout; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(layoutRes); initView(); } public void initView(){ ll_query_vip= (LinearLayout) findViewById(R.id.ll_query_vip); ll_query_info= (LinearLayout) findViewById(R.id.ll_query_info); ll_sure_query_vip= (LinearLayout) findViewById(R.id.ll_sure_query_vip); ll_cancel_back_cashier= (LinearLayout) findViewById(R.id.ll_cancel_back_cashier); ll_sure_add_vip= (LinearLayout) findViewById(R.id.ll_sure_add_vip); ll_cancel_back_query= (LinearLayout) findViewById(R.id.ll_cancel_back_query); ll_vip_info_btn= (LinearLayout) findViewById(R.id.ll_vip_info_btn); iv_add_scan_vip= (ImageView) findViewById(R.id.iv_add_scan_vip); et_add_vip_mobile= (EditText) findViewById(R.id.et_add_vip_mobile); tv_vip_name= (TextView) findViewById(R.id.tv_vip_name); tv_vip_mobile= (TextView) findViewById(R.id.tv_vip_mobile); tv_vip_shop= (TextView) findViewById(R.id.tv_vip_shop); tv_vip_point= (TextView) findViewById(R.id.tv_vip_point); tv_vip_discount= (TextView) findViewById(R.id.tv_vip_discount); tv_vip_grade= (TextView) findViewById(R.id.tv_vip_grade); ll_sure_query_vip.setOnClickListener(this); ll_cancel_back_cashier.setOnClickListener(this); ll_sure_add_vip.setOnClickListener(this); ll_cancel_back_query.setOnClickListener(this); iv_add_scan_vip.setOnClickListener(this); } /** * Called when a view has been clicked. * * @param v The view that was clicked. */ @Override public void onClick(View v) { switch (v.getId()){ case R.id.iv_add_scan_vip://扫描会员 Skip.mScanAddVipActivityResult(mActivity, CaptureActivity.class, REQUEST_CONTACT); break; case R.id.ll_sure_query_vip://查询会员 if(CheckUtil.phoneVerify(mContext,et_add_vip_mobile.getText().toString())){ vipMobile=et_add_vip_mobile.getText().toString(); getVipListener(vipMobile,0); } break; case R.id.ll_cancel_back_cashier://返回 ToastUtils.show("已取消查询会员"); addVipDialog.dismiss(); break; case R.id.ll_sure_add_vip://添加vip iv_add_vip.setImageResource(R.mipmap.vip02); addVipDialog.dismiss(); tv_show_discount.setVisibility(View.VISIBLE); //获取折后金额 discountAfter=Double.parseDouble(tv_show_amount.getText().toString())*(discount/10); tv_show_discount.setText(DecimalFormatUtils.decimalFormatRound(discountAfter)+""); //设置原价和折扣价不可编辑状态; tv_show_amount.setFocusable(false);tv_show_amount.setFocusableInTouchMode(false); tv_pay_discount.setFocusable(false);tv_pay_discount.setFocusableInTouchMode(false); break; case R.id.ll_cancel_back_query://返回 ToastUtils.show("已取消添加会员"); addVipDialog.dismiss(); break; } } } /** * 自定义独立收银dialog */ public class CustomSingleCashierDialog extends Dialog{ int layoutRes;//布局文件 Context context; SwipeMenuRecyclerView rvView; LinearLayout ll_cancel_pos_cashier; List<ResultPayCategoryBean.PayCategoryBea> categoryBeaList; PosPayCategoryAdapter posPayCategoryAdapter; /** * 自定义收银主题及布局的构造方法 * * @param context * @param theme * @param resLayout */ public CustomSingleCashierDialog(Context context, int theme, int resLayout) { super(context, theme); this.context = context; this.layoutRes = resLayout; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(layoutRes); initView(); initPayData(); } public void initPayData() { ResultPayCategoryBean bean = JsonUtils.fromJson(mCache.getAsString("GetPayCategory"), ResultPayCategoryBean.class); categoryBeaList = bean.TModel; posPayCategoryAdapter = new PosPayCategoryAdapter(categoryBeaList,100); posPayCategoryAdapter.setOnItemClickListener(onItemClickListener); rvView.setAdapter(posPayCategoryAdapter); } public void initView() { ll_cancel_pos_cashier = (LinearLayout) findViewById(R.id.ll_cancel_pos_cashier); rvView = (SwipeMenuRecyclerView) findViewById(R.id.rv_view); BaseRecyclerView.initRecyclerView(getContext(), rvView, false); ll_cancel_pos_cashier.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } private OnItemClickListener onItemClickListener = new OnItemClickListener() { @Override public void onItemClick(final int position) { switch (categoryBeaList.get(position).getCategoryType()) { case 2://微信支付 payType = categoryBeaList.get(position).getCategoryType(); if (!TextUtils.isEmpty(tv_show_discount.getText().toString())) {//折后价格非等于null bundle.putDouble("PayMoney", Double.parseDouble(tv_show_discount.getText().toString())); } else {//折后金额为空 bundle.putDouble("PayMoney", Double.parseDouble(tv_show_amount.getText().toString())); } //随机生成6位凭证号【规则:当月+4位随机数】 traceAuditNumber = RandomUtils.getCurrentTimeMM() + RandomUtils.getFourRandom(); bundle.putInt("Pay", categoryBeaList.get(position).getCategoryType()); bundle.putInt("IsPractical", categoryBeaList.get(position).getIsPractical()); bundle.putString("userShopId", userShopId); bundle.putString("OrderNo", traceAuditNumber); bundle.putDouble("discount", discount); bundle.putString("shopNameNick", shopNameNick); bundle.putString("userName", userName); bundle.putInt("point", point); bundle.putDouble("originalPrice", Double.parseDouble(tv_show_amount.getText().toString())); bundle.putDouble("discountAfter", discountAfter); bundle.putString("mobile", mobile); bundle.putBoolean("isSuccess", isSuccess); Skip.mNextFroData(mActivity, WeiXinAndAliPaySingleActivity.class, bundle); singleCashierDialog.dismiss(); break; case 3://支付宝 payType = categoryBeaList.get(position).getCategoryType(); if (!TextUtils.isEmpty(tv_show_discount.getText().toString())) {//折后价格非等于null bundle.putDouble("PayMoney", Double.parseDouble(tv_show_discount.getText().toString())); } else {//折后金额为空 bundle.putDouble("PayMoney", Double.parseDouble(tv_show_amount.getText().toString())); } //随机生成6位凭证号【规则:当月+4位随机数】 traceAuditNumber = RandomUtils.getCurrentTimeMM() + RandomUtils.getFourRandom(); bundle.putInt("IsPractical", categoryBeaList.get(position).getIsPractical()); bundle.putInt("Pay", categoryBeaList.get(position).getCategoryType()); bundle.putString("OrderNo", traceAuditNumber); bundle.putDouble("discount", discount); bundle.putString("shopNameNick", shopNameNick); bundle.putString("userShopId", userShopId); bundle.putString("userName", userName); bundle.putInt("point", point); bundle.putDouble("originalPrice", Double.parseDouble(tv_show_amount.getText().toString())); bundle.putDouble("discountAfter", discountAfter); bundle.putString("mobile", mobile); bundle.putBoolean("isSuccess", isSuccess); Skip.mNextFroData(mActivity, WeiXinAndAliPaySingleActivity.class, bundle); singleCashierDialog.dismiss(); break; case 4://银联支付 IsPractical=categoryBeaList.get(position).getIsPractical(); singleCashierDialog.dismiss(); payType = categoryBeaList.get(position).getCategoryType(); if (!TextUtils.isEmpty(tv_show_discount.getText().toString())) {//折后价格非等于null biao = tv_show_discount.getText().toString(); } else {//折后金额为空 biao = tv_show_amount.getText().toString(); } //启动银联收银 amount = "2"; lock[0] = LOCK_WAIT; doConsumeHasTemplate(amount, orderNo); break; case 5://现金支付 new CBDialogBuilder(CashierHomeActivity.this) .setTouchOutSideCancelable(true) .showCancelButton(true) .setTitle("温馨提示!") .setMessage("请确认该订单是否使用现金支付?") .setConfirmButtonText("确定") .setCancelButtonText("取消") .setDialogAnimation(CBDialogBuilder.DIALOG_ANIM_SLID_BOTTOM) .setButtonClickListener(true, new CBDialogBuilder.onDialogbtnClickListener() { @Override public void onDialogbtnClick(Context context, Dialog dialog, int whichBtn) { switch (whichBtn) { case BUTTON_CONFIRM: dismiss(); IsPractical=categoryBeaList.get(position).getIsPractical(); singleCashierDialog.dismiss(); payType = categoryBeaList.get(position).getCategoryType(); if (!TextUtils.isEmpty(tv_show_discount.getText().toString())) {//折后价格非等于null singleCashierMoney = Double.parseDouble(tv_show_discount.getText().toString()); } else {//折后金额为空 singleCashierMoney = Double.parseDouble(tv_show_amount.getText().toString()); } //随机生成12位参考号【规则:当前时间+2位随机数】 referenceNumber = RandomUtils.getCurrentTimeAsNumber() + RandomUtils.getToFourRandom(); //随机生成6位凭证号【规则:当月+4位随机数】 traceAuditNumber = RandomUtils.getCurrentTimeMM() + RandomUtils.getFourRandom(); orderNo=RandomUtils.getCurrentTimeMM() + RandomUtils.getFourRandom()+""; //getPayListener(referenceNumber, traceAuditNumber, singleCashierMoney, orderNo, 5, "notFansVip",IsPractical); double money=Double.parseDouble(tv_show_amount.getText().toString()); //订单号生成规则:LS+VipId+MMddHHmm+4位随机数 String orderNo="LS"+vipId+ AbDateUtil.getCurrentTimeAsNumber()+RandomUtils.getFourRandom(); createPayNet=new CreatePayNet(mContext); createPayNet.setData(orderNo,money,5,referenceNumber,"","","独立收银",orderNo,userShopId,"",2,100); break; case BUTTON_CANCEL: ToastUtils.show("已取消支付"); dismiss(); break; default: break; } } }) .create().show(); break; default: break; } } }; } /** * 初始化CoreApp连接对象 * * @return */ private void initPosCore() { if (pCore == null) { // 配置数据为开发阶段的数据 HashMap<String, String> init_params = new HashMap<String,String>(); init_params.put(PosConfig.Name_EX + "1053", shopNameNick);// 签购单小票台头 init_params.put(PosConfig.Name_EX + "1100", "cn.weipass.cashier");// 核心APP 包名 init_params.put(PosConfig.Name_EX + "1101", "com.wangpos.cashiercoreapp.services.CoreAppService");// 核心APP 类名 init_params.put(PosConfig.Name_EX + "1092", "1");// 是否开启订单生成,并且上报服务器 1.开启 0.不开启 init_params.put(PosConfig.Name_EX + "1093", "2");// 是否需要打印三联签购单 1.需要 2.不需要 init_params.put(PosConfig.Name_EX + "1012", "1");// 华势通道 init_params.put(PosConfig.Name_MerchantName, "coreApp"); pCore = PosCoreFactory.newInstance(this, init_params); callBack = new PosCallBack(pCore); } } /** * 消费 */ private void doConsumeHasTemplate(final String amount ,final String orderNo) { new Thread() { public void run() { try { HashMap<String, String> map = new HashMap<String, String>(); map.put("myOrderNo", orderNo); rXiaoFei= pCore.xiaoFei(amount, map, callBack); mActivity.runOnUiThread(new Runnable() { @Override public void run() { posPayLogBean=new PosPayLogBean(); posPayLogBean=new PosPayLogBean(); posPayLogBean.setOrderId(orderId);//支付订单 posPayLogBean.setTraceAuditNumber(rXiaoFei.retrievalReferenceNumber);//支付凭证号 posPayLogBean.setPayType(4);//支付类型 posPayLogBean.setRemark("零售单"); posPayLogBean.setEnCode(prefs.getString("enCode"));//设备EN号 posPayLogBean.setAccountNumber(primaryAccountNumber); posPayLogBean.setPayAmount(Double.parseDouble(biao));//支付金额 strJson=gson.toJson(posPayLogBean); ll_pay_cashier_accounts.setVisibility(View.GONE); ll_pay_info.setVisibility(View.VISIBLE); createPayNet=new CreatePayNet(mContext); if(rXiaoFei.systemTraceAuditNumber!=null && !"".equals(rXiaoFei.systemTraceAuditNumber)){ createPayNet.setData(rXiaoFei.retrievalReferenceNumber,Double.parseDouble(biao),4,rXiaoFei.retrievalReferenceNumber,rXiaoFei.retrievalReferenceNumber,primaryAccountNumber,"银联刷卡",rXiaoFei.systemTraceAuditNumber,userShopId,bankName,2,cardCategory); }else{ if(mCache.getAsString("PayInfo")!=null){ createPayNet.setData(mCache.getAsString("PayInfo"),Double.parseDouble(biao),4,mCache.getAsString("PayInfo"),rXiaoFei.retrievalReferenceNumber,primaryAccountNumber,"银联刷卡",rXiaoFei.systemTraceAuditNumber,userShopId,bankName,2,cardCategory); }else{ createPayNet.setData(primaryAccountNumber,Double.parseDouble(biao),4,primaryAccountNumber,rXiaoFei.retrievalReferenceNumber,primaryAccountNumber,"银联刷卡",primaryAccountNumber,userShopId,bankName,2,cardCategory); } } } }); } catch (Exception e) { e.printStackTrace(); showMsg(e.getLocalizedMessage()); Log.d(Constant.TAG,"银联ERROR:="+e.getLocalizedMessage()); } } }.start(); } /** * 处理扫描Activity返回的数据 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode==RESULT_CODE) { if(data.getStringExtra("mScanOrderResult")!=null && data.getStringExtra("mScanOrderResult").equals("012")){ scanCode= data.getStringExtra("resultCode"); bundle.putString("OrderId",scanCode); Skip.mNextFroData(mActivity, WaitPayOrderDetailActivity.class,bundle); } if(data.getStringExtra("mScanAddVipResult")!=null && data.getStringExtra("mScanAddVipResult").equals("016")){ scanCode= data.getStringExtra("resultCode"); if(scanCode!=null){ et_add_vip_mobile.setText(scanCode); } } } super.onActivityResult(requestCode, resultCode, data); } /** * 支付回调 * @param RetrievalReferenceNumber * @param TraceAuditNumber * @param ConsumeAmount * @param OrderId * @param PayType * @param OpenId */ public void getPayListener(String RetrievalReferenceNumber,String TraceAuditNumber,double ConsumeAmount,String OrderId,int PayType,String OpenId,int IsPractical){ Request<String> request = NoHttp.createStringRequest(Urls.PAY_FROM_STORE, RequestMethod.POST); request.add("RetrievalReferenceNumber",RetrievalReferenceNumber);//参考号 request.add("TraceAuditNumber",TraceAuditNumber);//凭证号 request.add("ConsumeAmount",ConsumeAmount);//消费金额 request.add("RetailId",OrderId);//支付订单号 request.add("IsPractical",IsPractical);//支付订单号 request.add("PayType",PayType); request.add("EnCode",prefs.getString("enCode"));//设备EN号 // request.add("OpenId",OpenId);// commonNet.requestNetTask(request,getPayListener,1); } //银联支付成功回调监听 private HttpListener<String> getPayListener = new HttpListener<String>() { @Override public void onSucceed(int what, Response<String> response) { PayCallbackBean callbackBean=gson.fromJson(response.get(),PayCallbackBean.class); if(callbackBean.isSuccess()==true){ if(payType==5){ isSuccess=true; ll_pay_cashier_accounts.setVisibility(View.GONE); tv_pay_cad.setVisibility(View.GONE); ll_pay_info.setVisibility(View.VISIBLE); tv_pay_success.setText("现金消费成功"); tv_pay_trace_audit.setText("凭证号:"+traceAuditNumber); if(curSelectedPos==1001){ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(payMoney)); } if(discount!=0.0){ //获取折后金额 discountAfter=originalPrice*(discount/10); tv_pay_discount.setVisibility(View.VISIBLE); tv_pay_discount.setText("折扣"+discount); tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(discountAfter)); }else{ tv_pay_discount.setVisibility(View.GONE); if(curSelectedPos==1001) { tv_real_pay.setText("实付:" + DecimalFormatUtils.decimalFormatRound(singleCashierMoney)); }else{ tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(payMoney)); } } //调用pos打印机 setLatticePrinter(); mRunnable = new Runnable() { @Override public void run() { mHandler.sendEmptyMessage(1); } }; mHandler .postDelayed(mRunnable, 3000); // 在Handler中执行子线程并延迟3s。 }else if(payType==4){ isSuccess=true; tv_pay_success.setText("银联消费成功"); tv_pay_cad.setVisibility(View.VISIBLE); tv_pay_cad.setText("卡号:" + rXiaoFei.primaryAccountNumber ); tv_pay_trace_audit.setText("凭证号:" + rXiaoFei.systemTraceAuditNumber); if(curSelectedPos==1001){ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(Double.parseDouble(biao))); }else{ tv_pay_original_price.setText("原价:"+DecimalFormatUtils.decimalFormatRound(payMoney)); } if(discount!=0.0){ discountAfter=Double.parseDouble(biao)*(discount/10); tv_pay_discount.setVisibility(View.VISIBLE); tv_pay_discount.setText("折扣"+discount); tv_real_pay.setText("实付:"+DecimalFormatUtils.decimalFormatRound(discountAfter)); }else{ tv_pay_discount.setVisibility(View.GONE); if(curSelectedPos==1001) {//独立收银 tv_real_pay.setText("实付:" + DecimalFormatUtils.decimalFormatRound(Double.parseDouble(biao))); }else{//扫描订单收银 tv_real_pay.setText("实付:" +DecimalFormatUtils.decimalFormatRound(payMoney)); } } ll_pay_cashier_accounts.setVisibility(View.GONE); ll_pay_info.setVisibility(View.VISIBLE); } }else{ } } @Override public void onFailed(int what, Response<String> response) { ToastUtils.show(response.get()); } }; public void payLog(String LogType, String obj,String remark){ //Pay Log posPayLogNet=new PosPayLogNet(mContext); posPayLogNet.setData(LogType,obj,remark); } /** * 设置独立收银点阵打印方法 */ public void setLatticePrinter(){ try { // 设备可能没有打印机,open会抛异常 latticePrinter = WeiposImpl.as().openLatticePrinter(); } catch (Exception e) { // TODO: handle exception } //点阵打印 if (latticePrinter == null) { Toast.makeText(CashierHomeActivity.this, "尚未初始化点阵打印sdk,请稍后再试", Toast.LENGTH_SHORT).show(); return; }else{ // 打印内容赋值 latticePrinter.setOnEventListener(new IPrint.OnEventListener() { @Override public void onEvent(final int what, String in) { final String info = in; // 回调函数中不能做UI操作,所以可以使用runOnUiThread函数来包装一下代码块 runOnUiThread(new Runnable() { public void run() { final String message = SingleCashierPrinterTools.getPrintErrorInfo(what, info); if (message == null || message.length() < 1) { return; } showResultInfo("打印", "打印结果信息", message); } }); } }); //以下是设置pos打印信息 latticePrinterBean=new LatticePrinterBean(); if(payType==5){//现金 if (curSelectedPos==1001){ latticePrinterBean.setOrderId(orderNo); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ latticePrinterBean.setOrderId(scanCode); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } latticePrinterBean.setShopName(shopNameNick); latticePrinterBean.setCounterName(shopNameNick); latticePrinterBean.setShopClerkName(userName); latticePrinterBean.setTotalPoint(point); latticePrinterBean.setTraceAuditNumber(traceAuditNumber); latticePrinterBean.setPayTitleName("现金支付"); if(discount!=0.0){//折扣价格 latticePrinterBean .setVipMobile(mobile); if (curSelectedPos==1001){ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); }else{ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(payType)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } }else{//原价 latticePrinterBean .setVipMobile("非会员"); if (curSelectedPos==1001){ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); }else{ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(payMoney)); } } }else if(mobilePayType==2){//微信 if (curSelectedPos==1001){ latticePrinterBean.setOrderId(mobileOrderNo); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ latticePrinterBean.setOrderId(scanCode); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } latticePrinterBean.setShopName(shopNameNick); latticePrinterBean.setCounterName(shopNameNick); latticePrinterBean.setShopClerkName(userName); latticePrinterBean.setTotalPoint(point); latticePrinterBean.setTraceAuditNumber(WxAliTraceAuditNumber); latticePrinterBean.setPayTitleName("微信支付"); if(discount!=0.0){//折扣价格 latticePrinterBean .setVipMobile(mobile); latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(discountAfter)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(discountAfter)); }else{//原价 latticePrinterBean .setVipMobile("暂无会员"); if (curSelectedPos==1001){ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } } }else{//支付宝 if (curSelectedPos==1001){ latticePrinterBean.setOrderId(mobileOrderNo); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ latticePrinterBean.setOrderId(scanCode); latticePrinterBean.setOriginalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } latticePrinterBean.setShopName(shopNameNick); latticePrinterBean.setCounterName(shopNameNick); latticePrinterBean.setShopClerkName(userName); latticePrinterBean.setTotalPoint(point); latticePrinterBean.setTraceAuditNumber(WxAliTraceAuditNumber); latticePrinterBean.setPayTitleName("支付宝"); if(discount!=0.0){//折扣价格 latticePrinterBean .setVipMobile(mobile); latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(discountAfter)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(discountAfter)); }else{//原价 latticePrinterBean .setVipMobile("暂无会员"); if (curSelectedPos==1001){ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(originalPrice)); }else{ latticePrinterBean.setDiscountPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); latticePrinterBean.setTotalPrice(DecimalFormatUtils.decimalFormatRound(totalPrice)); } } } if(curSelectedPos==1001){//独立收银打印 SingleCashierPrinterTools.printLattice(CashierHomeActivity.this, latticePrinter,latticePrinterBean,discount); }else{//扫描订单收银打印 OrderCashierPrinterTools.printLattice(CashierHomeActivity.this, latticePrinter,latticePrinterBean,orderList,discount); } //清空输入金额天和折扣金额 st=""; tv_show_discount.setText(""); } } /** * pos打印显示结果信息 * @param operInfo * @param titleHeader * @param info */ private void showResultInfo(String operInfo, String titleHeader, String info) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(titleHeader + ":" + info); builder.setTitle(operInfo); builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } public void showMsg(final String msg) { this.runOnUiThread(new Runnable() { @Override public void run() { tv_show_amount.setText(""); tv_show_amount.setTextSize(20); tv_show_amount.setText(msg); } }); } /** * 显示消费对话框 * @param core * @throws Exception */ private void showConsumeDialog(final PosCore core) throws Exception { lock[0] = LOCK_WAIT; runOnUiThread(new Runnable() { @Override public void run() { View view = getLayoutInflater().inflate(R.layout.consume_dialog, null); final AlertDialog dialog = new AlertDialog.Builder(CashierHomeActivity.this).setView(view).setCancelable(false).create(); dialog.show(); Button btn_confirm = (Button) view.findViewById(R.id.btn_consume_confiem); Button btn_cancel = (Button) view.findViewById(R.id.btn_consume_cancel); final EditText ed_consumen_amount = (EditText) view.findViewById(R.id.ed_consume_amount); ed_consumen_amount.setFocusable(false);ed_consumen_amount.setFocusableInTouchMode(false);//设置不可编辑状态; if(!TextUtils.isEmpty(ed_consumen_amount.getText().toString())){ ed_consumen_amount.setText("");//设置支付金额 } if(curSelectedPos==1001){ ed_consumen_amount.setText(biao);//设置支付金额 }else{ ed_consumen_amount.setText(payMoney+"");//设置支付金额 } btn_confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {//确定支付 synchronized (lock) { money=(int)(payMoney*100); lock[0] = LOCK_CONTINUE; lock.notify(); } dialog.dismiss(); } }); btn_cancel.setOnClickListener(new View.OnClickListener() {//取消支付 @Override public void onClick(View v) { synchronized (lock) { ed_consumen_amount.setText("");//设置支付金额 lock[0] = LOCK_CONTINUE; lock.notify(); } dialog.dismiss(); } }); } }); // 等待输入 synchronized (lock) { while (true) { if (lock[0] == LOCK_WAIT) { try { lock.wait(500); } catch (InterruptedException e) { e.printStackTrace(); } } else { break; } } } //判断是否独立收银金额和扫描订单金额 if(curSelectedPos==1001){ double money=Double.parseDouble(biao); Integer dd=(int)(money*100); core.setXiaoFeiAmount(dd+""); }else{ core.setXiaoFeiAmount(money+"");//设置消费金额 } } /** * 收银回调 */ public class PosCallBack implements IPosCallBack { private final PosCore core; PosCallBack(PosCore core) { this.core = core; } @Override public void onInfo(String s) { showMsg(s); } @Override public void onEvent(int eventID, Object[] params) throws Exception { switch (eventID) { case 110: showMsg("打印票据" + params[0]); break; case EVENT_Setting:{ core.reprint(refNum); showMsg("doSetting:完成"); break; } case EVENT_Task_start: { showMsg("任务进程开始执行"); break; } case EVENT_Task_end: { showMsg("任务进程执行结束"); break; } case EVENT_CardID_start: { Log.i("test", "读取银行卡信息" + params[0]); showMsg("读取银行卡信息"); break; } case EVENT_CardID_end: { String cardNum = (String) params[0]; if (!TextUtils.isEmpty(cardNum)) { Log.w(Constant.TAG, "卡号为:" + params[0]); try{ primaryAccountNumber=params[0]+""; //获取发卡行,卡种名称 cardName= BankUtil.getNameOfBank(primaryAccountNumber); bankName=cardName.substring(0, cardName.indexOf("·")); if(cardName.contains("贷记卡")){ cardCategory=3; }else if(cardName.contains("信用卡")){ cardCategory=2; }else{//借记卡 cardCategory=1; } showConsumeDialog(core); }catch (Exception e){ e.printStackTrace(); } }else{ ToastUtils.getLongToast(mContext,"获取银行卡号为空!"); } break; } case EVENT_Comm_start: { showMsg("开始网络通信"); break; } case EVENT_Comm_end: { showMsg("网络通信完成"); break; } case EVENT_DownloadPlugin_start: { showMsg("开始下载插件"); break; } case EVENT_DownloadPlugin_end: { showMsg("插件下载完成"); break; } case EVENT_InstallPlugin_start: { showMsg("开始安装插件"); break; } case EVENT_InstallPlugin_end: { showMsg("插件安装完成"); break; } case EVENT_RunPlugin_start: { showMsg("开始启动插件"); break; } case EVENT_RunPlugin_end: { showMsg("插件启动完成"); break; } case EVENT_AutoPrint_start:{ showMsg("参考号:" + params[0]); setCachePayInfo(params[0]+""); break; } case EVENT_AutoPrint_end://打印完成 break; case IPosCallBack.ERR_InTask:{ if ((Integer) params[0] == EVENT_NO_PAPER) { showRePrintDialog(); } } default: { showMsg("Event:" + eventID); break; } } } } /** * 缓存支付信息 * @param refNum */ private void setCachePayInfo(String refNum){ if(mCache.getAsString("PayInfo")!=null && !"".equals(mCache.getAsString("PayInfo"))){ mCache.remove("PayInfo"); mCache.put("PayInfo",refNum); }else{ mCache.put("PayInfo",refNum); } } private boolean needRePrint; /** * 显示重打印按钮 */ private void showRePrintDialog() { lock[0] = LOCK_WAIT; runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder dialog = new AlertDialog.Builder(CashierHomeActivity.this); dialog.setMessage("打印机缺纸"); dialog.setPositiveButton("重打印", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { synchronized (lock) { needRePrint = true; lock[0] = LOCK_CONTINUE; lock.notify(); } } }); dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { synchronized (lock) { needRePrint = false; lock[0] = LOCK_CONTINUE; lock.notify(); } } }); dialog.setCancelable(false); dialog.show(); } }); // 等待输入 synchronized (lock) { while (true) { if (lock[0] == LOCK_WAIT) { try { lock.wait(500); } catch (InterruptedException e) { e.printStackTrace(); } } else { break; } } } try { pCore.printContinue(needRePrint); } catch (Exception e) { e.printStackTrace(); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onDataSynEvent(ResultGetTokenBean msg) { if(msg.IsSuccess==true){ prefs.putString("RongToken", msg.TModel.token+""); connect(msg.TModel.token); }else{ ToastUtils.getLongToast(mContext,"获取融云ToKen失败!"); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onDataSynEvent(ReceiveMessageBean msg) { if(msg.getContent()!=null){ Log.i("test","新的消息"+msg.getContent()); if(mCache.getAsString("isOpenSound")!=null && mCache.getAsString("isOpenSound").equals("true")){ //初始化声音播放 SoundPoolUtils.initMediaPlayer(mContext); // Skip.mNext(mActivity,ConversationListActivity.class); Skip.mNext(mActivity, CheckAccountsListActivity.class); } } } /** * <p>连接服务器,在整个应用程序全局,只需要调用一次,需在 {@link #//init(Context)} 之后调用。</p> * <p>如果调用此接口遇到连接失败,SDK 会自动启动重连机制进行最多10次重连,分别是1, 2, 4, 8, 16, 32, 64, 128, 256, 512秒后。 * 在这之后如果仍没有连接成功,还会在当检测到设备网络状态变化时再次进行重连。</p> * * @param token 从服务端获取的用户身份令牌(Token)。 * @param //callback 连接回调。 * @return RongIM 客户端核心类的实例。 */ private void connect(String token) { if (getApplicationInfo().packageName.equals(App.getCurProcessName(getApplicationContext()))) { RongIM.connect(token, new RongIMClient.ConnectCallback() { /** * Token 错误。可以从下面两点检查 1. Token 是否过期,如果过期您需要向 App Server 重新请求一个新的 Token * 2. token 对应的 appKey 和工程里设置的 appKey 是否一致 */ @Override public void onTokenIncorrect() { Log.d(Constant.TAG, "--onTokenIncorrect" ); } /** * 连接融云成功 * @param userid 当前 token 对应的用户 id */ @Override public void onSuccess(String userid) { Log.d(Constant.TAG, "--连接融云成功" ); InitListener.init(userid,mContext,mActivity); } /** * 连接融云失败 * @param errorCode 错误码,可到官网 查看错误码对应的注释 */ @Override public void onError(RongIMClient.ErrorCode errorCode) { Log.d(Constant.TAG, "--ErrorCode" +errorCode); } }); } } /** * Author FGB * Description 任务管理 * Created at 2017/11/20 22:47 * Version 1.0 */ public class TimerManager { public TimerManager(final long PERIOD_DAY ) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 1); //凌晨1点 calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Date date=calendar.getTime(); //第一次执行定时任务的时间 //如果第一次执行定时任务的时间 小于当前的时间 //此时要在 第一次执行定时任务的时间加一天,以便此任务在下个时间点执行。如果不加一天,任务会立即执行。 if (date.before(new Date())) { date = this.addDay(date, 1); } Timer timer = new Timer(); Task task = new Task(); //安排指定的任务在指定的时间开始进行重复的固定延迟执行。 timer.schedule(task,date,PERIOD_DAY); } // 增加或减少天数 public Date addDay(Date date, int num) { Calendar startDT = Calendar.getInstance(); startDT.setTime(date); startDT.add(Calendar.DAY_OF_MONTH, num); return startDT.getTime(); } } // public class Task extends TimerTask { // public void run() { // //执行定时任务 查询当天订单数据 // PosSqliteDatabaseUtils.selectData(mContext); // } // } // private List<PosPayBean> posPayBeanList; // @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 // public void onDataSynEvent(List<PosPayBean> posPayBeanArrayList) { // if(posPayBeanArrayList.size()!=0){ // posPayBeanList=new ArrayList<>(); // posPayBeanList=posPayBeanArrayList; // strJson= JsonUtils.toJson(posPayBeanList); //// payLog("PayLog",strJson,AbDateUtil.getCurrentDate());//上线记得开启日志上传 // }else{ // ToastUtils.getLongToast(mContext,"当前没有订单记录可上传!"); // } // } // // @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行 // public void onDataSynEvent(PayLogBean bean) { // if(bean.isSuccess()!=false){ // ToastUtils.getLongToast(mContext,"上传日志成功!"); // }else{ // ToastUtils.getLongToast(mContext,"上传日志失败!"); // } // } }
87,974
0.544491
0.53969
2,022
40.412956
32.662682
298
false
false
0
0
0
0
0
0
0.672601
false
false
7
01ed179431ee62cf6fea482ca6f9a13008014c85
33,294,586,513,277
8a01d97273718ee832e88407dfffe5ef85310c33
/JustThink/WalkThrough/src/org/srm/comp/ComparatorTest.java
ca2b9ab29a7237b7958f5d1e3f339f1f4af07175
[]
no_license
sklrsn/DevWorks
https://github.com/sklrsn/DevWorks
676b77463ca41dca4b89ace163178bdd71cf01ce
00cd451f8a0ccb97691c1bff217e593b660b87c5
refs/heads/master
2016-08-09T06:50:05.744000
2015-10-07T18:16:25
2015-10-07T18:16:25
43,252,241
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package org.srm.comp; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author ANBU * */ @SuppressWarnings("unchecked") public class ComparatorTest { public static void main(String[] args) { @SuppressWarnings("rawtypes") List list = new ArrayList<String>(); list.add("Anbu"); list.add("anbu"); list.add("Love"); list.add("love"); Collections.sort(list, new NameSorter()); System.out.println(list); } }
UTF-8
Java
476
java
ComparatorTest.java
Java
[ { "context": "ollections;\nimport java.util.List;\n\n/**\n * @author ANBU\n * \n */\n@SuppressWarnings(\"unchecked\")\npublic cla", "end": 136, "score": 0.7577300071716309, "start": 132, "tag": "USERNAME", "value": "ANBU" }, { "context": "\tList list = new ArrayList<String>();\n\t\tl...
null
[]
/** * */ package org.srm.comp; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author ANBU * */ @SuppressWarnings("unchecked") public class ComparatorTest { public static void main(String[] args) { @SuppressWarnings("rawtypes") List list = new ArrayList<String>(); list.add("Anbu"); list.add("anbu"); list.add("Love"); list.add("love"); Collections.sort(list, new NameSorter()); System.out.println(list); } }
476
0.670168
0.670168
26
17.307692
13.64317
43
false
false
0
0
0
0
0
0
1.153846
false
false
7
d5b6630c9a724357f91a1d2844a78196bc9856dc
7,043,746,431,688
52c5cbea9a383f12807e9c6af28446780e64709f
/Kanabun.java
6c88ed9ee114737ec93f12de9f5ce8c44827d5f0
[]
no_license
yume-yu/SIGA
https://github.com/yume-yu/SIGA
d862bb5be2cf9673650f8ae67f04792b50349bb8
fc31a145dc7a6a3b8af508c2a52bf5899f6d2abc
refs/heads/master
2021-01-01T18:39:20.240000
2017-09-01T08:00:47
2017-09-01T08:00:47
98,393,348
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Kanabun here. * * @author (your name) * @version (a version number or a date) */ public class Kanabun extends Enemies { int speed = 5; public Kanabun() { hitpoint = 3; giveScore = 10; int[] items = {0, 1}; this.items = items; img = new GreenfootImage("./images/kanabun.png"); setImage(img); turn(90); } public void act() { if(Stage.inPause){ } else{ super.act(); move(speed); } } }
UTF-8
Java
681
java
Kanabun.java
Java
[]
null
[]
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Kanabun here. * * @author (your name) * @version (a version number or a date) */ public class Kanabun extends Enemies { int speed = 5; public Kanabun() { hitpoint = 3; giveScore = 10; int[] items = {0, 1}; this.items = items; img = new GreenfootImage("./images/kanabun.png"); setImage(img); turn(90); } public void act() { if(Stage.inPause){ } else{ super.act(); move(speed); } } }
681
0.493392
0.481645
32
19.21875
17.833841
79
false
false
0
0
0
0
0
0
0.46875
false
false
7
6ab025af913216f8b42d228f873701c380f7b5fa
23,716,809,428,699
6f0eb4635de4a5eaf905ac58e2aad4afd9604178
/programmers/sort/sort_42746.java
95daa12a5e4acc7fdb5ddd960f0b7940126c1c6a
[ "MIT" ]
permissive
hoon0912/algoroom
https://github.com/hoon0912/algoroom
ddd48a68017cc5dc1fd8a9d95147b450de25aa37
6f3967f2ac6080540f1970435c36fb385ee1f39a
refs/heads/master
2022-12-15T03:02:43.250000
2020-09-06T14:32:04
2020-09-06T14:32:04
260,631,263
3
3
MIT
false
2020-08-30T09:17:09
2020-05-02T06:51:50
2020-08-29T15:32:47
2020-08-30T09:17:08
112
2
2
0
Java
false
false
import java.util.*; public class sort_42746 { public static void main(String[] args) { int[] numbers = {6,10,2}; String result = solution(numbers); System.out.println(result); } public static String solution(int[] numbers) { String answer = ""; PriorityQueue<String> pq = new PriorityQueue<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return -o1.concat(o2).compareTo(o2.concat(o1)); } }); for(int num : numbers) pq.add(String.valueOf(num)); while(!pq.isEmpty()) { String temp = pq.poll(); if (!answer.equals("0")) { answer += temp; } } return answer; } }
UTF-8
Java
794
java
sort_42746.java
Java
[]
null
[]
import java.util.*; public class sort_42746 { public static void main(String[] args) { int[] numbers = {6,10,2}; String result = solution(numbers); System.out.println(result); } public static String solution(int[] numbers) { String answer = ""; PriorityQueue<String> pq = new PriorityQueue<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return -o1.concat(o2).compareTo(o2.concat(o1)); } }); for(int num : numbers) pq.add(String.valueOf(num)); while(!pq.isEmpty()) { String temp = pq.poll(); if (!answer.equals("0")) { answer += temp; } } return answer; } }
794
0.516373
0.496222
27
28.407408
20.624077
81
false
false
0
0
0
0
0
0
0.518519
false
false
7