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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bd1bb13d0e6594c3995da81664085d43f0e76f17 | 29,016,799,075,085 | 359fcdc732b36a9f702a5ad0441fc953efac3125 | /Collection/src/HeapL/Heap.java | 6521b815ff5125026b0aff1421c1e53a0f28bd14 | []
| no_license | s11235218/LJava | https://github.com/s11235218/LJava | a1937ad54baf054861d2f2306b68601635279ba7 | d9c7a754efc38fafa2b1e9541571b341719c7e09 | refs/heads/master | 2022-12-03T13:42:55.116000 | 2021-08-07T02:30:40 | 2021-08-07T02:30:40 | 222,437,674 | 3 | 0 | null | false | 2022-11-16T08:38:08 | 2019-11-18T11:53:36 | 2021-08-07T02:32:47 | 2022-11-16T08:38:05 | 15,670 | 1 | 0 | 17 | JavaScript | false | false | package HeapL;
// 大堆
public class Heap {
// 向下调整
public static void shiftDown(int[] array, int size, int index) {
int parent = index;
int child = 2 * parent + 1;
while(child < size) {
if(child + 1 < size && array[child + 1] > array[child]) {
child = child + 1;
}
if(array[child] > array[parent]) {
int tmp = array[child];
array[child] = array[parent];
array[parent] = tmp;
} else {
break;
}
parent = child;
child = 2 * parent + 1;
}
}
public static void createHeap(int[] array, int size) {
// 基于向下调整建堆 从后往前遍历
for (int i = (size - 1 - 1) / 2; i >= 0; i++) {
shiftDown(array, size, i);
}
}
public static void main(String[] args) {
int[] array = {9, 5, 2, 7, 3, 6, 8};
createHeap(array, array.length);
}
}
| UTF-8 | Java | 1,022 | java | Heap.java | Java | []
| null | []
| package HeapL;
// 大堆
public class Heap {
// 向下调整
public static void shiftDown(int[] array, int size, int index) {
int parent = index;
int child = 2 * parent + 1;
while(child < size) {
if(child + 1 < size && array[child + 1] > array[child]) {
child = child + 1;
}
if(array[child] > array[parent]) {
int tmp = array[child];
array[child] = array[parent];
array[parent] = tmp;
} else {
break;
}
parent = child;
child = 2 * parent + 1;
}
}
public static void createHeap(int[] array, int size) {
// 基于向下调整建堆 从后往前遍历
for (int i = (size - 1 - 1) / 2; i >= 0; i++) {
shiftDown(array, size, i);
}
}
public static void main(String[] args) {
int[] array = {9, 5, 2, 7, 3, 6, 8};
createHeap(array, array.length);
}
}
| 1,022 | 0.446029 | 0.427699 | 36 | 26.277779 | 19.388729 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 3 |
571f596907e1ad8c85242fdd576b3e216a3436b1 | 5,059,471,514,138 | c4a165562100bf017153ee609e7cba2bf82f156f | /src/main/java/com/example/ConcatWithIterable.java | a50bd93d1e1b9180293b96c95184e06ff015aad0 | []
| no_license | reta-ygs/string-concat | https://github.com/reta-ygs/string-concat | daa5481942587cf136a0d2e6c5cf92f6540834d5 | e1975a51a9e44b67f7663b67b4262bafb80d6dde | refs/heads/main | 2023-08-21T01:22:59.278000 | 2021-10-02T15:11:02 | 2021-10-02T15:11:02 | 412,830,103 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example;
import java.util.ArrayList;
public class ConcatWithIterable {
static String concat(String s, int count) {
ArrayList<String> result = new ArrayList<>();
result.add(s);
for (int i = 0; i < count; i++) {
result.add(s);
}
return String.join("", result);
}
}
| UTF-8 | Java | 293 | java | ConcatWithIterable.java | Java | []
| null | []
| package com.example;
import java.util.ArrayList;
public class ConcatWithIterable {
static String concat(String s, int count) {
ArrayList<String> result = new ArrayList<>();
result.add(s);
for (int i = 0; i < count; i++) {
result.add(s);
}
return String.join("", result);
}
}
| 293 | 0.65529 | 0.651877 | 15 | 18.533333 | 16.499966 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 3 |
f2734e806fb494cf62f0e722cb0eacca78c957e2 | 25,409,026,561,184 | cadd19c25c5c35d2d6709e17526585e8a5f33d05 | /src/main/API/Door.java | 681d3284a0cb6db4919ed081045a84e748ceecae | []
| no_license | ViRb3/iddqdBot | https://github.com/ViRb3/iddqdBot | c96c93bc6ff82cd4d9a5ef23695dbc6d2bbfb8a0 | 5ab580d8b884580cb607328ecb795137466ecde7 | refs/heads/master | 2023-03-09T14:26:40.696000 | 2017-10-31T21:24:23 | 2017-10-31T21:24:23 | 109,022,023 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.API;
public class Door
{
private Boolean open;
private Boolean red = false;
private Boolean blue = false;
private Boolean yellow = false;
private int x1;
private int y1;
private int x2;
private int y2;
Door(Boolean open, String keyReqd, int x1, int x2, int y1, int y2)
{
this.open = open;
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
if (keyReqd.equals("blue"))
blue = true;
else if (keyReqd.equals("red"))
red = true;
else if (keyReqd.equals("yellow"))
yellow = true;
}
public Boolean isOpen()
{
return open;
}
public int getX1()
{
return x1;
}
public int getX2()
{
return x2;
}
public int getY1()
{
return y1;
}
public int getY2()
{
return y2;
}
public Boolean isRed()
{
return red;
}
public Boolean isBlue()
{
return blue;
}
public Boolean isYellow()
{
return yellow;
}
}
| UTF-8 | Java | 1,117 | java | Door.java | Java | []
| null | []
| package main.API;
public class Door
{
private Boolean open;
private Boolean red = false;
private Boolean blue = false;
private Boolean yellow = false;
private int x1;
private int y1;
private int x2;
private int y2;
Door(Boolean open, String keyReqd, int x1, int x2, int y1, int y2)
{
this.open = open;
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
if (keyReqd.equals("blue"))
blue = true;
else if (keyReqd.equals("red"))
red = true;
else if (keyReqd.equals("yellow"))
yellow = true;
}
public Boolean isOpen()
{
return open;
}
public int getX1()
{
return x1;
}
public int getX2()
{
return x2;
}
public int getY1()
{
return y1;
}
public int getY2()
{
return y2;
}
public Boolean isRed()
{
return red;
}
public Boolean isBlue()
{
return blue;
}
public Boolean isYellow()
{
return yellow;
}
}
| 1,117 | 0.495971 | 0.474485 | 72 | 14.513889 | 13.282187 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 3 |
d9486cf0ba944860bc26ea0a527d43b2954ee6a6 | 15,144,054,727,764 | cc3431a688ae5d6a4560e22da642f3881525726a | /src/文件管理/FileCopy.java | e441014c22df27cc50e633ce91360d519ec0be8b | []
| no_license | bossikill/Java | https://github.com/bossikill/Java | 1f1db93071d55dc3d49fb57bd126e31637d5787b | 993e562fa79367b86c0d0dad83a7de4b0b184818 | refs/heads/master | 2020-11-24T07:15:51.058000 | 2020-02-08T05:51:12 | 2020-02-08T05:51:12 | 228,024,967 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package 文件管理;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//文件复制
public class FileCopy {
public static void main(String[] args) {
try (FileInputStream in = new FileInputStream("./TestDir/build.txt");
FileOutputStream out = new FileOutputStream("./TestDir/subDir/build.txt")
) {
byte[] buffer = new byte[10];
int len = in.read(buffer);
while (len != -1) {
String copyStr = new String(buffer);
System.out.println(copyStr);
out.write(buffer, 0, len);
len = in.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 771 | java | FileCopy.java | Java | []
| null | []
| package 文件管理;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//文件复制
public class FileCopy {
public static void main(String[] args) {
try (FileInputStream in = new FileInputStream("./TestDir/build.txt");
FileOutputStream out = new FileOutputStream("./TestDir/subDir/build.txt")
) {
byte[] buffer = new byte[10];
int len = in.read(buffer);
while (len != -1) {
String copyStr = new String(buffer);
System.out.println(copyStr);
out.write(buffer, 0, len);
len = in.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 771 | 0.552318 | 0.54702 | 26 | 28.038462 | 22.112442 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 3 |
c17ffd548f0cc4e6028fb8e392cce844ea672bcd | 12,171,937,358,378 | 77f61364b90b1b1e2919db2e50c66a21782b1923 | /Java Practice/src/chapter_9/DateTest.java | 69e0428b7d9e1905a1a654ef8f43a15c0b8549a5 | []
| no_license | msalaterski/Java-Practice | https://github.com/msalaterski/Java-Practice | bbdf397d0110104e45bda2be85fd0b14ad3643ba | ed0487e88a3c8b9557ef5c2adbf58bbfcaccd501 | refs/heads/master | 2021-01-22T06:27:36.009000 | 2017-02-12T23:32:13 | 2017-02-12T23:32:13 | 81,760,254 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chapter_9;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Date theDate = new Date(10000);
for (int i = 0; i < 8; i++) {
System.out.println("During iteration " + (i + 1) + ", the date is " + theDate.toString() + ".");
theDate.setTime(theDate.getTime() * 10);
}
}
}
| UTF-8 | Java | 332 | java | DateTest.java | Java | []
| null | []
| package chapter_9;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Date theDate = new Date(10000);
for (int i = 0; i < 8; i++) {
System.out.println("During iteration " + (i + 1) + ", the date is " + theDate.toString() + ".");
theDate.setTime(theDate.getTime() * 10);
}
}
}
| 332 | 0.611446 | 0.578313 | 15 | 21.133333 | 25.974005 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.533333 | false | false | 3 |
ac8bc432b1daa23d2dbb1f31712e082bf0306ebd | 9,921,374,513,221 | 6f5dddfa2a1270911f984c1855da741b7b9a18ac | /Ch5P6Steven/app/src/main/java/com/example/steven/ch5p6steven/MainActivity.java | 1e9959a3f340068ca43e151cf5c5a0b65df7dcca | []
| no_license | struongm/Android2018 | https://github.com/struongm/Android2018 | 3590ef5f36494c60c87c26ae975b32130ea11eeb | cff917f4cb12bc8ab6ad292a2e108afddbee4e2a | refs/heads/master | 2018-10-24T11:42:22.559000 | 2018-08-23T00:11:50 | 2018-08-23T00:11:50 | 142,729,953 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.steven.ch5p6steven;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] game = {"League of Legends", "Monster Hunter World", "Overwatch", "Tom Clancy's Rainbow Six Siege"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_main, R.id.games, game));
}
protected void onListItemClick(ListView l, View v, int position, long id){
switch(position){
case 0:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.na.leagueoflegends.com/en_US")));
break;
case 1:
startActivity(new Intent(MainActivity.this, MonsterHunter.class));
break;
case 2:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://playoverwatch.com/en-us/")));
break;
case 3:
startActivity(new Intent(MainActivity.this, SixSiege.class));
break;
default:
}
}
}
| UTF-8 | Java | 1,393 | java | MainActivity.java | Java | [
{
"context": "package com.example.steven.ch5p6steven;\n\nimport android.app.ListActivity;\nim",
"end": 26,
"score": 0.947909951210022,
"start": 20,
"tag": "USERNAME",
"value": "steven"
},
{
"context": "f Legends\", \"Monster Hunter World\", \"Overwatch\", \"Tom Clancy's Rainbow Six Siege\"};\n setListAdapter(new",
"end": 559,
"score": 0.9914579391479492,
"start": 549,
"tag": "NAME",
"value": "Tom Clancy"
}
]
| null | []
| package com.example.steven.ch5p6steven;
import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] game = {"League of Legends", "Monster Hunter World", "Overwatch", "<NAME>'s Rainbow Six Siege"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_main, R.id.games, game));
}
protected void onListItemClick(ListView l, View v, int position, long id){
switch(position){
case 0:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.na.leagueoflegends.com/en_US")));
break;
case 1:
startActivity(new Intent(MainActivity.this, MonsterHunter.class));
break;
case 2:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://playoverwatch.com/en-us/")));
break;
case 3:
startActivity(new Intent(MainActivity.this, SixSiege.class));
break;
default:
}
}
}
| 1,389 | 0.64537 | 0.640345 | 38 | 35.657894 | 32.860371 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.868421 | false | false | 3 |
2ee8beac488c358e9097d618bdb1515690dee37c | 23,175,643,587,050 | 69de0f7f23943694f7cf0407355b7a61ad019e9a | /gdpr_android/src/main/java/com/iab/gdpr_android/exception/VendorConsentParseException.java | ed7f98c03481d64841ef7c81347734d84ff3244a | [
"MIT"
]
| permissive | didomi/Consent-String-SDK-Android | https://github.com/didomi/Consent-String-SDK-Android | 7b66d2c89e2061643a83772f7235d5ade2ca782c | 362e6b4f015ffd7d3b406a772e316b67f60de15b | refs/heads/master | 2020-03-27T22:27:10.224000 | 2018-09-05T15:42:27 | 2018-09-05T15:42:27 | 147,232,355 | 1 | 1 | null | false | 2018-09-03T19:53:58 | 2018-09-03T17:01:35 | 2018-09-03T17:01:38 | 2018-09-03T19:53:58 | 176 | 0 | 0 | 0 | null | false | null | package com.iab.gdpr_android.exception;
public class VendorConsentParseException extends VendorConsentException {
public VendorConsentParseException(String message, Throwable cause) {
super(message, cause);
}
public VendorConsentParseException(String message) {
super(message);
}
}
| UTF-8 | Java | 316 | java | VendorConsentParseException.java | Java | []
| null | []
| package com.iab.gdpr_android.exception;
public class VendorConsentParseException extends VendorConsentException {
public VendorConsentParseException(String message, Throwable cause) {
super(message, cause);
}
public VendorConsentParseException(String message) {
super(message);
}
}
| 316 | 0.743671 | 0.743671 | 11 | 27.727272 | 27.532101 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 3 |
ffd64ec9b2b38e017ebe1ca36d6643fe320f02cf | 20,229,296,006,681 | f2e5f0c74cca281000e5b0a47044a84b49d5cb87 | /Comp401/Comp 401 Workspace/Assignment8/src/view/AdventureView.java | 2d06e9ec2529cc2f9551c7796c7a82ad7cfaa781 | []
| no_license | AaronZhangGitHub/Archive | https://github.com/AaronZhangGitHub/Archive | 7ad351831c7d1d197471213a2b483696ee38f426 | e803443d5333f7f8f99e99e257735d5440ca8df7 | refs/heads/master | 2021-01-16T19:06:45.637000 | 2017-08-12T20:49:55 | 2017-08-12T20:49:55 | 100,136,627 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package view;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import model.Adventure;
public class AdventureView extends JPanel {
private Adventure adventure;
public AdventureView(Adventure adventure) {
this.adventure = adventure;
setLayout(new BorderLayout());
add(new JLabel("Your UI Here"), BorderLayout.CENTER);
}
}
| UTF-8 | Java | 378 | java | AdventureView.java | Java | []
| null | []
| package view;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import model.Adventure;
public class AdventureView extends JPanel {
private Adventure adventure;
public AdventureView(Adventure adventure) {
this.adventure = adventure;
setLayout(new BorderLayout());
add(new JLabel("Your UI Here"), BorderLayout.CENTER);
}
}
| 378 | 0.753968 | 0.753968 | 21 | 17 | 17.391842 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.142857 | false | false | 3 |
f66caf1ee7d17465538e35da84984ed2fab1a0fb | 34,230,889,368,316 | 6114c6cd4d7c2db754b6af30557bf23041412b8b | /xoai-common/src/main/java/com/lyncode/xoai/model/oaipmh/DeletedRecord.java | 54ae26e4976f17f561a03de50c6de0f85a455cd3 | [
"Apache-2.0"
]
| permissive | andrefgomes/xoai | https://github.com/andrefgomes/xoai | 342785c54860c1090231a644f95f2f9a971c92f1 | 13233a4e8419f50d48df5bea5c1f9e901b0f846c | refs/heads/master | 2021-01-16T20:33:09.554000 | 2015-06-12T17:50:23 | 2015-06-12T17:50:23 | 21,691,112 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lyncode.xoai.model.oaipmh;
public enum DeletedRecord {
NO("no"),
PERSISTENT("persistent"),
TRANSIENT("transient");
public static DeletedRecord fromValue(String value) {
for (DeletedRecord c : DeletedRecord.values()) {
if (c.value.equals(value)) {
return c;
}
}
throw new IllegalArgumentException(value);
}
private final String value;
DeletedRecord(String value) {
this.value = value;
}
public String value() {
return value;
}
@Override
public String toString() {
return value();
}
}
| UTF-8 | Java | 607 | java | DeletedRecord.java | Java | []
| null | []
| package com.lyncode.xoai.model.oaipmh;
public enum DeletedRecord {
NO("no"),
PERSISTENT("persistent"),
TRANSIENT("transient");
public static DeletedRecord fromValue(String value) {
for (DeletedRecord c : DeletedRecord.values()) {
if (c.value.equals(value)) {
return c;
}
}
throw new IllegalArgumentException(value);
}
private final String value;
DeletedRecord(String value) {
this.value = value;
}
public String value() {
return value;
}
@Override
public String toString() {
return value();
}
}
| 607 | 0.607908 | 0.607908 | 33 | 17.39394 | 16.952589 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 3 |
724edcb35b6511df31cde7fcb8c1e9bb0f36c8d1 | 7,352,984,050,704 | 75da98a9682b2d76370dea5c2102f69c66b4cba5 | /src/customer/DaoCustomerManager.java | 3777fa9b478b2d36b60ad7594ba874a18cccaea4 | []
| no_license | SE-moustakim/store-management-javafx | https://github.com/SE-moustakim/store-management-javafx | 0fc552323557b5430568dc0b2ab8b2230a216ff9 | daef04d661326ce0579a610a7ad4bbb730a0cfb6 | refs/heads/master | 2022-12-30T03:40:48.198000 | 2020-10-20T19:10:55 | 2020-10-20T19:10:55 | 305,740,500 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package customer;
import java.util.List;
public interface DaoCustomerManager {
public void insert(Customer customer);
public void edit(int id, String firstName, String lastName, String phone);
public Customer search(int id);
public void delete(int id);
public List<Customer> getAll();
}
| UTF-8 | Java | 296 | java | DaoCustomerManager.java | Java | [
{
"context": "ustomer customer);\npublic void edit(int id, String firstName, String lastName, String phone);\npublic Customer ",
"end": 163,
"score": 0.998860239982605,
"start": 154,
"tag": "NAME",
"value": "firstName"
},
{
"context": "\npublic void edit(int id, String firstName, String lastName, String phone);\npublic Customer search(int id);\np",
"end": 180,
"score": 0.9987072944641113,
"start": 172,
"tag": "NAME",
"value": "lastName"
}
]
| null | []
|
package customer;
import java.util.List;
public interface DaoCustomerManager {
public void insert(Customer customer);
public void edit(int id, String firstName, String lastName, String phone);
public Customer search(int id);
public void delete(int id);
public List<Customer> getAll();
}
| 296 | 0.766892 | 0.766892 | 13 | 21.692308 | 20.778631 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.769231 | false | false | 3 |
c485d51c886d6bb8fc2fb2c2b7e2e1791f815fcb | 34,557,306,883,717 | 13fcadb602671b9ef2d19fea6a51a498b9d953d4 | /JAVA/src/Algorithms/Mathematics/SumOfConsecutiveSquares.java | 7ea6c1b8aee20f4de9fd8dab4f5c9dc170397a02 | [
"MIT"
]
| permissive | argshub/Algorithmics | https://github.com/argshub/Algorithmics | bf815093c3bb80e5749695d6d738377b213e1ba4 | 98999205782083acbcdd2397288508779fdf332e | refs/heads/master | 2021-04-30T15:07:26.104000 | 2018-07-26T16:36:12 | 2018-07-26T16:36:12 | 121,232,181 | 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 Algorithms.Mathematics;
/**
*
* @author argshub
*/
public class SumOfConsecutiveSquares {
public static int sum(int n) {
return (n * (n + 1) * (2 * n + 1)) / 6;
}
public static int sumOfRange(int x, int y) {
return sum(y) - sum(x - 1);
}
public static void main(String arg[]) {
System.out.println(sum(10));
System.out.println(sumOfRange(6, 10));
}
}
| UTF-8 | Java | 628 | java | SumOfConsecutiveSquares.java | Java | [
{
"context": "package Algorithms.Mathematics;\n\n/**\n *\n * @author argshub\n */\npublic class SumOfConsecutiveSquares {\n \n ",
"end": 243,
"score": 0.9973006248474121,
"start": 236,
"tag": "USERNAME",
"value": "argshub"
}
]
| 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 Algorithms.Mathematics;
/**
*
* @author argshub
*/
public class SumOfConsecutiveSquares {
public static int sum(int n) {
return (n * (n + 1) * (2 * n + 1)) / 6;
}
public static int sumOfRange(int x, int y) {
return sum(y) - sum(x - 1);
}
public static void main(String arg[]) {
System.out.println(sum(10));
System.out.println(sumOfRange(6, 10));
}
}
| 628 | 0.595541 | 0.579618 | 28 | 21.428572 | 21.736126 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 3 |
4996f946304ac2d3996cb7edf0837efd59071abd | 3,779,571,269,840 | 75ee16ee423e272ac123edf9537451606f6fcdd2 | /src/it/unitn/ing/rista/diffr/data/ILLDataFile.java | c28f6eed0153027384cfa0e3392d3b21b18e0978 | [
"BSD-3-Clause"
]
| permissive | luttero/Maud | https://github.com/luttero/Maud | 0b031a40f94b3f6519ef3b74f883a19c8b82788b | 51b07e0c36011c68d71c6d0dfbfb6a1992c18eec | refs/heads/version2 | 2023-06-21T20:13:03.621000 | 2023-06-19T15:37:29 | 2023-06-19T15:37:29 | 81,939,182 | 5 | 5 | BSD-3-Clause | false | 2022-08-05T16:26:19 | 2017-02-14T11:36:38 | 2022-05-25T22:53:06 | 2022-08-05T16:26:18 | 180,699 | 2 | 4 | 2 | Java | false | false | /*
* @(#)ILLDataFile.java created 08/07/1998 ILL, Grenoble
*
* Copyright (c) 1998 Luca Lutterotti All Rights Reserved.
*
* This software is the research result of Luca Lutterotti and it is
* provided as it is as confidential and proprietary information.
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with Luca Lutterotti.
*
* THE AUTHOR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. THE AUTHOR SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*
*/
package it.unitn.ing.rista.diffr.data;
import it.unitn.ing.rista.diffr.*;
import it.unitn.ing.rista.util.Misc;
import java.io.*;
import java.lang.*;
import java.util.*;
/**
* The ILLDataFile is a class
*
*
* @version $Revision: 1.9 $, $Date: 2006/01/19 14:45:55 $
* @author Luca Lutterotti
* @since JDK1.1
*/
public class ILLDataFile extends it.unitn.ing.rista.diffr.MultDiffrDataFile {
public ILLDataFile(XRDcat aobj, String alabel) {
super(aobj, alabel);
identifier = ".ill";
}
public ILLDataFile() {
identifier = ".ill";
}
public boolean readallSpectra() {
boolean loadSuccessfull = false;
boolean tmpB = isAbilitatetoRefresh;
isAbilitatetoRefresh = false;
BufferedReader reader = getReader();
if (reader != null) {
try {
String token = new String("");
StringTokenizer st = null;
String linedata = null;
boolean endoffile = false;
while (!endoffile) {
while (!token.toLowerCase().startsWith("sssss")) {
linedata = reader.readLine();
linedata = Misc.removeUTF8BOM(linedata);
if (linedata == null) {
endoffile = true;
break;
}
st = new StringTokenizer(linedata, " ,\t\r\n");
token = st.nextToken();
}
if (endoffile)
break;
linedata = reader.readLine();
linedata = Misc.removeUTF8BOM(linedata);
if (linedata == null) {
endoffile = true;
break;
}
st = new StringTokenizer(linedata, " ,\t\r\n");
token = st.nextToken();
// System.out.println( "Reading spectrum number: " + token +
// " ," + st.nextToken() + " to the end");
DiffrDataFile datafile = addDiffrDatafile(token);
boolean atmpB = datafile.isAbilitatetoRefresh;
datafile.isAbilitatetoRefresh = false;
linedata = reader.readLine();
linedata = reader.readLine();
st = new StringTokenizer(linedata, " ,\t\r\n");
int nfields = Integer.valueOf(token = st.nextToken()).intValue();
int nlines = Integer.valueOf(token = st.nextToken()).intValue();
for (int i = 0; i < nlines; i++)
linedata = reader.readLine();
int i = 0;
while (i < nfields) {
linedata = reader.readLine();
st = new StringTokenizer(linedata, " ,\t\r\n");
while (st.hasMoreTokens()) {
token = st.nextToken();
if (i == 15)
datafile.setString(1, token);
if (i == 16)
datafile.setString(2, token);
if (i == 17)
datafile.setString(3, token);
i++;
}
}
linedata = reader.readLine();
linedata = reader.readLine();
st = new StringTokenizer(linedata, " ,\t\r\n");
int nchannel = Integer.valueOf(token = st.nextToken()).intValue();
// System.out.println(nchannel);
datafile.initData(nchannel);
datafile.constantstep = false;
datafile.datanumber = nchannel;
datafile.dspacingbase = false;
i = 0;
while (i < nchannel) {
linedata = reader.readLine();
if (linedata == null) {
endoffile = true;
datafile.isAbilitatetoRefresh = atmpB;
datafile.dataLoaded = true;
break;
}
st = new StringTokenizer(linedata, " ,\t\r\n");
while (st.hasMoreTokens()) {
datafile.setXData(i, (double) i);
datafile.setYData(i, Double.valueOf(token = st.nextToken()).doubleValue());
double tmpweight = Math.sqrt(datafile.getYData(i));
if (tmpweight != 0.0)
datafile.setWeight(i, 1.0 / tmpweight);
else
datafile.setWeight(i, 1.0);
i++;
}
}
datafile.isAbilitatetoRefresh = atmpB;
datafile.dataLoaded = true;
loadSuccessfull = true;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in loading the data file! Try to remove this data file");
}
try {
reader.close();
} catch (IOException e) {
}
}
isAbilitatetoRefresh = tmpB;
return loadSuccessfull;
}
}
| UTF-8 | Java | 5,344 | java | ILLDataFile.java | Java | [
{
"context": " 08/07/1998 ILL, Grenoble\n *\n * Copyright (c) 1998 Luca Lutterotti All Rights Reserved.\n *\n * This software is the r",
"end": 100,
"score": 0.9998801350593567,
"start": 85,
"tag": "NAME",
"value": "Luca Lutterotti"
},
{
"context": "ved.\n *\n * This software is the research result of Luca Lutterotti and it is\n * provided as it is as conf",
"end": 172,
"score": 0.9393703937530518,
"start": 168,
"tag": "NAME",
"value": "Luca"
},
{
"context": "\n * This software is the research result of Luca Lutterotti and it is\n * provided as it is as confidential an",
"end": 183,
"score": 0.9861370921134949,
"start": 174,
"tag": "NAME",
"value": "utterotti"
},
{
"context": "on: 1.9 $, $Date: 2006/01/19 14:45:55 $\n * @author Luca Lutterotti\n * @since JDK1.1\n */\n\npublic class ILLDataFile ex",
"end": 1158,
"score": 0.9998733401298523,
"start": 1143,
"tag": "NAME",
"value": "Luca Lutterotti"
}
]
| null | []
| /*
* @(#)ILLDataFile.java created 08/07/1998 ILL, Grenoble
*
* Copyright (c) 1998 <NAME> All Rights Reserved.
*
* This software is the research result of Luca Lutterotti and it is
* provided as it is as confidential and proprietary information.
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with Luca Lutterotti.
*
* THE AUTHOR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. THE AUTHOR SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*
*/
package it.unitn.ing.rista.diffr.data;
import it.unitn.ing.rista.diffr.*;
import it.unitn.ing.rista.util.Misc;
import java.io.*;
import java.lang.*;
import java.util.*;
/**
* The ILLDataFile is a class
*
*
* @version $Revision: 1.9 $, $Date: 2006/01/19 14:45:55 $
* @author <NAME>
* @since JDK1.1
*/
public class ILLDataFile extends it.unitn.ing.rista.diffr.MultDiffrDataFile {
public ILLDataFile(XRDcat aobj, String alabel) {
super(aobj, alabel);
identifier = ".ill";
}
public ILLDataFile() {
identifier = ".ill";
}
public boolean readallSpectra() {
boolean loadSuccessfull = false;
boolean tmpB = isAbilitatetoRefresh;
isAbilitatetoRefresh = false;
BufferedReader reader = getReader();
if (reader != null) {
try {
String token = new String("");
StringTokenizer st = null;
String linedata = null;
boolean endoffile = false;
while (!endoffile) {
while (!token.toLowerCase().startsWith("sssss")) {
linedata = reader.readLine();
linedata = Misc.removeUTF8BOM(linedata);
if (linedata == null) {
endoffile = true;
break;
}
st = new StringTokenizer(linedata, " ,\t\r\n");
token = st.nextToken();
}
if (endoffile)
break;
linedata = reader.readLine();
linedata = Misc.removeUTF8BOM(linedata);
if (linedata == null) {
endoffile = true;
break;
}
st = new StringTokenizer(linedata, " ,\t\r\n");
token = st.nextToken();
// System.out.println( "Reading spectrum number: " + token +
// " ," + st.nextToken() + " to the end");
DiffrDataFile datafile = addDiffrDatafile(token);
boolean atmpB = datafile.isAbilitatetoRefresh;
datafile.isAbilitatetoRefresh = false;
linedata = reader.readLine();
linedata = reader.readLine();
st = new StringTokenizer(linedata, " ,\t\r\n");
int nfields = Integer.valueOf(token = st.nextToken()).intValue();
int nlines = Integer.valueOf(token = st.nextToken()).intValue();
for (int i = 0; i < nlines; i++)
linedata = reader.readLine();
int i = 0;
while (i < nfields) {
linedata = reader.readLine();
st = new StringTokenizer(linedata, " ,\t\r\n");
while (st.hasMoreTokens()) {
token = st.nextToken();
if (i == 15)
datafile.setString(1, token);
if (i == 16)
datafile.setString(2, token);
if (i == 17)
datafile.setString(3, token);
i++;
}
}
linedata = reader.readLine();
linedata = reader.readLine();
st = new StringTokenizer(linedata, " ,\t\r\n");
int nchannel = Integer.valueOf(token = st.nextToken()).intValue();
// System.out.println(nchannel);
datafile.initData(nchannel);
datafile.constantstep = false;
datafile.datanumber = nchannel;
datafile.dspacingbase = false;
i = 0;
while (i < nchannel) {
linedata = reader.readLine();
if (linedata == null) {
endoffile = true;
datafile.isAbilitatetoRefresh = atmpB;
datafile.dataLoaded = true;
break;
}
st = new StringTokenizer(linedata, " ,\t\r\n");
while (st.hasMoreTokens()) {
datafile.setXData(i, (double) i);
datafile.setYData(i, Double.valueOf(token = st.nextToken()).doubleValue());
double tmpweight = Math.sqrt(datafile.getYData(i));
if (tmpweight != 0.0)
datafile.setWeight(i, 1.0 / tmpweight);
else
datafile.setWeight(i, 1.0);
i++;
}
}
datafile.isAbilitatetoRefresh = atmpB;
datafile.dataLoaded = true;
loadSuccessfull = true;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error in loading the data file! Try to remove this data file");
}
try {
reader.close();
} catch (IOException e) {
}
}
isAbilitatetoRefresh = tmpB;
return loadSuccessfull;
}
}
| 5,326 | 0.568114 | 0.558757 | 174 | 29.712645 | 23.135735 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.718391 | false | false | 3 |
06a44fab7014266dfe2cc2b88c2bb88046ff8447 | 10,170,482,627,877 | b5816dad5ee6a5236377bc9cb9dfcbf1ecc926cd | /src/main/java/com/example/demo/support/Support.java | 10fe0a60e6df4567f25ec9722efd4704da9e74ab | []
| no_license | Pruspat/Biblioteka-testowa | https://github.com/Pruspat/Biblioteka-testowa | ee7a0ff79e629528b1f94db410549cefc1bfb12a | ca5722de13535e35e0f60189c9a172305d7532e0 | refs/heads/master | 2020-04-18T20:03:09.937000 | 2019-05-15T18:29:56 | 2019-05-15T18:29:56 | 167,727,828 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.support;
public class Support {
private Integer id;
private Integer customerId;
private String customerName;
private String customerSurname;
private String content;
private String replay;
private boolean status;
private Integer workerId;
public Support() {
}
public Support(Integer id, Integer customerId, String customerName, String customerSurname, String content, boolean status, String replay) {
this.id = id;
this.customerId = customerId;
this.customerName = customerName;
this.customerSurname = customerSurname;
this.content = content;
this.status = status;
this.replay = replay;
}
public Support(Integer id,Integer customerId, String customerName, String customerSurname, String content, String replay, boolean status) {
this.id = id;
this.customerId = customerId;
this.customerName = customerName;
this.customerSurname = customerSurname;
this.content = content;
this.replay = replay;
this.status = status;
}
public Support(Integer id, Integer customerId, String customerName, String customerSurname, String content, String replay, boolean status, Integer workerId) {
this.id = id;
this.customerId = customerId;
this.customerName = customerName;
this.customerSurname = customerSurname;
this.content = content;
this.replay = replay;
this.status = status;
this.workerId = workerId;
}
public Support(Integer id, String replay) {
this.id = id;
this.replay = replay;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerSurname() {
return customerSurname;
}
public void setCustomerSurname(String customerSurname) {
this.customerSurname = customerSurname;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getReplay() {
return replay;
}
public void setReplay(String replay) {
this.replay = replay;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public Integer getWorkerId() {
return workerId;
}
public void setWorkerId(Integer workerId) {
this.workerId = workerId;
}
}
| UTF-8 | Java | 2,921 | java | Support.java | Java | [
{
"context": "stomerId = customerId;\n this.customerName = customerName;\n this.customerSurname = customerSurname;\n",
"end": 966,
"score": 0.9600800275802612,
"start": 954,
"tag": "NAME",
"value": "customerName"
},
{
"context": "stomerId = customerId;\n this.customerName = customerName;\n this.customerSurname = customerSurname;\n",
"end": 1378,
"score": 0.9507749080657959,
"start": 1366,
"tag": "NAME",
"value": "customerName"
}
]
| null | []
| package com.example.demo.support;
public class Support {
private Integer id;
private Integer customerId;
private String customerName;
private String customerSurname;
private String content;
private String replay;
private boolean status;
private Integer workerId;
public Support() {
}
public Support(Integer id, Integer customerId, String customerName, String customerSurname, String content, boolean status, String replay) {
this.id = id;
this.customerId = customerId;
this.customerName = customerName;
this.customerSurname = customerSurname;
this.content = content;
this.status = status;
this.replay = replay;
}
public Support(Integer id,Integer customerId, String customerName, String customerSurname, String content, String replay, boolean status) {
this.id = id;
this.customerId = customerId;
this.customerName = customerName;
this.customerSurname = customerSurname;
this.content = content;
this.replay = replay;
this.status = status;
}
public Support(Integer id, Integer customerId, String customerName, String customerSurname, String content, String replay, boolean status, Integer workerId) {
this.id = id;
this.customerId = customerId;
this.customerName = customerName;
this.customerSurname = customerSurname;
this.content = content;
this.replay = replay;
this.status = status;
this.workerId = workerId;
}
public Support(Integer id, String replay) {
this.id = id;
this.replay = replay;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerSurname() {
return customerSurname;
}
public void setCustomerSurname(String customerSurname) {
this.customerSurname = customerSurname;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getReplay() {
return replay;
}
public void setReplay(String replay) {
this.replay = replay;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public Integer getWorkerId() {
return workerId;
}
public void setWorkerId(Integer workerId) {
this.workerId = workerId;
}
}
| 2,921 | 0.637111 | 0.637111 | 117 | 23.965813 | 26.252531 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.589744 | false | false | 3 |
f52002500c6d1783a9a4a673e88675676d760766 | 15,522,011,847,086 | d894da4b380fb2fb8f4f73f252c782ed7a961b22 | /src/main/java/org/klems/spark/example/css/CSS.java | adaad6db42491330acd0d769bc23c9c316df240d | []
| no_license | Klemsus/kultprosvet | https://github.com/Klemsus/kultprosvet | 6d44459562b33d0cf3ae0bbc3db7b56fa68358eb | e1d5fe13c41fab5c7cc5815505ccca8d15d735bb | refs/heads/master | 2021-01-13T09:04:51.293000 | 2016-04-08T08:11:36 | 2016-04-08T08:11:36 | 72,516,217 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.klems.spark.example.css;
public interface CSS {
String getHref();
}
| UTF-8 | Java | 83 | java | CSS.java | Java | []
| null | []
| package org.klems.spark.example.css;
public interface CSS {
String getHref();
}
| 83 | 0.73494 | 0.73494 | 5 | 15.6 | 13.602941 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 3 |
1aff701ca321bd86eeb45ce2d4cd5736229d2779 | 35,373,350,663,378 | 23a83f9642706c0e2da718c6ede2aa7bea886d84 | /src/test/java/com/softswiss/go/dev/pages/SearchResultsPage.java | bd5427f799b09ab0594c8bc1c8067bb5a182f772 | []
| no_license | vmorochkovskaya/go.dev | https://github.com/vmorochkovskaya/go.dev | f7b9a32dd70e282c0c36743163e982c8cd3feb7b | 1636c04827cb0d6d4a10f550a7b16f303f062b41 | refs/heads/master | 2023-05-10T01:42:29.770000 | 2020-06-08T22:53:44 | 2020-06-08T22:53:44 | 270,823,869 | 0 | 0 | null | false | 2023-05-09T18:50:05 | 2020-06-08T20:52:01 | 2020-06-08T22:53:44 | 2023-05-09T18:50:01 | 33 | 0 | 0 | 2 | Java | false | false | package com.softswiss.go.dev.pages;
import com.softswiss.go.dev.models.Package;
import framework.elements.Button;
import framework.elements.Label;
import framework.elements.Link;
import framework.enums.Setting;
import framework.webdriver.BaseForm;
import org.openqa.selenium.By;
import static com.softswiss.go.dev.functions.PackageFunctions.getPublishedFromInfo;
import static com.softswiss.go.dev.functions.PackageFunctions.getVersionFromInfo;
public class SearchResultsPage extends BaseForm {
private static final String PACKAGE_LOCATOR = "//a[@href='/%1$s']";
private static final String PACKAGE_INFO_LOCATOR = "//div[contains(@class, 'SearchSnippet')][.%1$s]//div[contains(@class,'infoLabel')]";
private Button btnPaginationNext = new Button(By.xpath("//div[contains(@class,'resultCount')]//a[contains(@class,'Pagination-next')]"), "Next");
public SearchResultsPage() {
super(By.xpath("//div[@class='SearchResults']"), "Results page");
}
public boolean isPackageFoundAmongAllPages(String pack) {
while (!isPackageFoundOnCurrentPage(pack) && btnPaginationNext.isEnabled()) {
btnPaginationNext.hover();
btnPaginationNext.click();
}
return isPackageFoundOnCurrentPage(pack);
}
public Package getPackageInfo(String pack) {
Package packInfo = new Package();
Label packageInfo = new Label(By.xpath(String.format(PACKAGE_INFO_LOCATOR, String.format(PACKAGE_LOCATOR, pack))), "Package info");
String packInfoText = packageInfo.getText();
packInfo.setVersion(getVersionFromInfo(packInfoText));
packInfo.setPublishedDate(getPublishedFromInfo(packInfoText));
return packInfo;
}
private boolean isPackageFoundOnCurrentPage(String pack) {
return getPackageLink(pack).waitForIsPresent(Setting.TINY_WAIT.getLongValue());
}
private Link getPackageLink(String pack) {
return new Link(By.xpath(String.format(PACKAGE_LOCATOR, pack)), pack);
}
public void clickOnPackage(String pack) {
getPackageLink(pack).hover();
getPackageLink(pack).waitAndClick();
}
} | UTF-8 | Java | 2,146 | java | SearchResultsPage.java | Java | []
| null | []
| package com.softswiss.go.dev.pages;
import com.softswiss.go.dev.models.Package;
import framework.elements.Button;
import framework.elements.Label;
import framework.elements.Link;
import framework.enums.Setting;
import framework.webdriver.BaseForm;
import org.openqa.selenium.By;
import static com.softswiss.go.dev.functions.PackageFunctions.getPublishedFromInfo;
import static com.softswiss.go.dev.functions.PackageFunctions.getVersionFromInfo;
public class SearchResultsPage extends BaseForm {
private static final String PACKAGE_LOCATOR = "//a[@href='/%1$s']";
private static final String PACKAGE_INFO_LOCATOR = "//div[contains(@class, 'SearchSnippet')][.%1$s]//div[contains(@class,'infoLabel')]";
private Button btnPaginationNext = new Button(By.xpath("//div[contains(@class,'resultCount')]//a[contains(@class,'Pagination-next')]"), "Next");
public SearchResultsPage() {
super(By.xpath("//div[@class='SearchResults']"), "Results page");
}
public boolean isPackageFoundAmongAllPages(String pack) {
while (!isPackageFoundOnCurrentPage(pack) && btnPaginationNext.isEnabled()) {
btnPaginationNext.hover();
btnPaginationNext.click();
}
return isPackageFoundOnCurrentPage(pack);
}
public Package getPackageInfo(String pack) {
Package packInfo = new Package();
Label packageInfo = new Label(By.xpath(String.format(PACKAGE_INFO_LOCATOR, String.format(PACKAGE_LOCATOR, pack))), "Package info");
String packInfoText = packageInfo.getText();
packInfo.setVersion(getVersionFromInfo(packInfoText));
packInfo.setPublishedDate(getPublishedFromInfo(packInfoText));
return packInfo;
}
private boolean isPackageFoundOnCurrentPage(String pack) {
return getPackageLink(pack).waitForIsPresent(Setting.TINY_WAIT.getLongValue());
}
private Link getPackageLink(String pack) {
return new Link(By.xpath(String.format(PACKAGE_LOCATOR, pack)), pack);
}
public void clickOnPackage(String pack) {
getPackageLink(pack).hover();
getPackageLink(pack).waitAndClick();
}
} | 2,146 | 0.718546 | 0.717614 | 53 | 39.509434 | 36.873379 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.716981 | false | false | 3 |
3a70c466cc6e730be19ba5d7d706e193e3b6c0aa | 2,705,829,397,543 | 5b8ad3f95518abc227c417a2486520f761d96e72 | /1029. Two City Scheduling.Java | e1e5da9a97b3fb9860f152f0a4b03cfbdb05855a | []
| no_license | SaoriKaku/LeetCode | https://github.com/SaoriKaku/LeetCode | cb77eae65db2017d45bdd505974c41eed72fecf4 | 815dc0819736cbf6ac65c3cca6481bef48628c83 | refs/heads/master | 2021-08-28T01:40:13.241000 | 2021-08-25T01:12:29 | 2021-08-25T01:12:29 | 208,539,948 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1].
Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.
Example 1:
Input: [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation:
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
Note:
1 <= costs.length <= 100
It is guaranteed that costs.length is even.
1 <= costs[i][0], costs[i][1] <= 1000
*/
// method 1: sort
// time complexity: O(nlogn + n), space complexity: O(1)
class Solution {
public int twoCitySchedCost(int[][] costs) {
if(costs == null || costs.length == 0) {
return 0;
}
Arrays.sort(costs, (a, b) -> {
return a[0] - a[1] - b[0] + b[1];
});
int n = costs.length / 2, result = 0;
for(int i = 0; i < n; i++) {
result += costs[i][0] + costs[2 * n - 1 - i][1];
}
return result;
}
}
| UTF-8 | Java | 1,300 | java | 1029. Two City Scheduling.Java | Java | []
| null | []
|
/*
There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1].
Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.
Example 1:
Input: [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation:
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
Note:
1 <= costs.length <= 100
It is guaranteed that costs.length is even.
1 <= costs[i][0], costs[i][1] <= 1000
*/
// method 1: sort
// time complexity: O(nlogn + n), space complexity: O(1)
class Solution {
public int twoCitySchedCost(int[][] costs) {
if(costs == null || costs.length == 0) {
return 0;
}
Arrays.sort(costs, (a, b) -> {
return a[0] - a[1] - b[0] + b[1];
});
int n = costs.length / 2, result = 0;
for(int i = 0; i < n; i++) {
result += costs[i][0] + costs[2 * n - 1 - i][1];
}
return result;
}
}
| 1,300 | 0.605385 | 0.551538 | 38 | 33.052631 | 35.222561 | 181 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.605263 | false | false | 3 |
00581c7d8d414bdd7f734038bf1f803940562098 | 2,705,829,396,484 | 6da40f85d77584a14449b8975924c26e4e5b37bf | /shop1/src/main/java/service/impl/FacebookSocialService.java | f78112831192a65938b049ab345ef069acf169f4 | []
| no_license | kardinaldon/ext-systems | https://github.com/kardinaldon/ext-systems | cf0c4672a2a30f13ad47eb7b66d05f787aa697fb | 37f9b1f09c7eb277c8db59f72042825d36ff13d1 | refs/heads/master | 2022-03-04T05:00:06.168000 | 2020-01-02T20:03:23 | 2020-01-02T20:03:23 | 185,272,545 | 1 | 0 | null | false | 2022-02-16T01:07:12 | 2019-05-06T21:11:00 | 2021-05-19T16:02:13 | 2022-02-16T01:07:12 | 9,687 | 0 | 0 | 17 | Java | false | false | package service.impl;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.Version;
import com.restfb.scope.ExtendedPermissions;
import com.restfb.scope.ScopeBuilder;
import com.restfb.types.User;
import model.SocialAccount;
import service.SocialService;
class FacebookSocialService implements SocialService {
private final String idClient;
private final String secret;
private final String redirectUrl;
FacebookSocialService(ServiceManager serviceManager) {
super();
idClient = serviceManager.getApplicationProperty("social.facebook.idClient");
secret = serviceManager.getApplicationProperty("social.facebook.secret");
redirectUrl = serviceManager.getApplicationProperty("app.host") + "/from-social";
}
@Override
public String getAuthorizeUrl() {
ScopeBuilder scopeBuilder = new ScopeBuilder();
scopeBuilder.addPermission(ExtendedPermissions.EMAIL);
FacebookClient client = new DefaultFacebookClient(Version.VERSION_2_5);
return client.getLoginDialogUrl(idClient, redirectUrl, scopeBuilder);
}
@Override
public SocialAccount getSocialAccount(String authToken) {
FacebookClient client = new DefaultFacebookClient(Version.VERSION_2_5);
FacebookClient.AccessToken accessToken = client.obtainUserAccessToken(idClient, secret, redirectUrl, authToken);
client = new DefaultFacebookClient(accessToken.getAccessToken(), Version.VERSION_2_5);
User user = client.fetchObject("me", User.class, Parameter.with("fields", "name,email,first_name,last_name"));
return new SocialAccount(user.getFirstName(), user.getEmail());
}
}
| UTF-8 | Java | 1,736 | java | FacebookSocialService.java | Java | []
| null | []
| package service.impl;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.Version;
import com.restfb.scope.ExtendedPermissions;
import com.restfb.scope.ScopeBuilder;
import com.restfb.types.User;
import model.SocialAccount;
import service.SocialService;
class FacebookSocialService implements SocialService {
private final String idClient;
private final String secret;
private final String redirectUrl;
FacebookSocialService(ServiceManager serviceManager) {
super();
idClient = serviceManager.getApplicationProperty("social.facebook.idClient");
secret = serviceManager.getApplicationProperty("social.facebook.secret");
redirectUrl = serviceManager.getApplicationProperty("app.host") + "/from-social";
}
@Override
public String getAuthorizeUrl() {
ScopeBuilder scopeBuilder = new ScopeBuilder();
scopeBuilder.addPermission(ExtendedPermissions.EMAIL);
FacebookClient client = new DefaultFacebookClient(Version.VERSION_2_5);
return client.getLoginDialogUrl(idClient, redirectUrl, scopeBuilder);
}
@Override
public SocialAccount getSocialAccount(String authToken) {
FacebookClient client = new DefaultFacebookClient(Version.VERSION_2_5);
FacebookClient.AccessToken accessToken = client.obtainUserAccessToken(idClient, secret, redirectUrl, authToken);
client = new DefaultFacebookClient(accessToken.getAccessToken(), Version.VERSION_2_5);
User user = client.fetchObject("me", User.class, Parameter.with("fields", "name,email,first_name,last_name"));
return new SocialAccount(user.getFirstName(), user.getEmail());
}
}
| 1,736 | 0.753456 | 0.75 | 41 | 41.341465 | 33.132851 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.951219 | false | false | 3 |
34548fafbc3ea7cd5ac9a857239e1abe62e48364 | 21,045,339,780,326 | d7de50fc318ff59444caabc38d274f3931349f19 | /src/com/facebook/stetho/Stetho$Initializer.java | 8540e5a743156280b4a7d004bbacb8cf49613038 | []
| no_license | reverseengineeringer/fr.dvilleneuve.lockito | https://github.com/reverseengineeringer/fr.dvilleneuve.lockito | 7bbd077724d61e9a6eab4ff85ace35d9219a0246 | ad5dbd7eea9a802e5f7bc77e4179424a611d3c5b | refs/heads/master | 2021-01-20T17:21:27.500000 | 2016-07-19T16:23:04 | 2016-07-19T16:23:04 | 63,709,932 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook.stetho;
import android.content.Context;
import com.facebook.stetho.common.LogUtil;
import com.facebook.stetho.dumpapp.Dumper;
import com.facebook.stetho.dumpapp.DumperPlugin;
import com.facebook.stetho.dumpapp.RawDumpappHandler;
import com.facebook.stetho.dumpapp.StreamingDumpappHandler;
import com.facebook.stetho.inspector.ChromeDevtoolsServer;
import com.facebook.stetho.inspector.ChromeDiscoveryHandler;
import com.facebook.stetho.inspector.protocol.ChromeDevtoolsDomain;
import com.facebook.stetho.server.RegistryInitializer;
import com.facebook.stetho.websocket.WebSocketHandler;
import java.io.IOException;
import javax.annotation.Nullable;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
public abstract class Stetho$Initializer
implements RegistryInitializer
{
private final Context mContext;
protected Stetho$Initializer(Context paramContext)
{
mContext = paramContext.getApplicationContext();
}
protected void addCustomEntries(HttpRequestHandlerRegistry paramHttpRequestHandlerRegistry) {}
@Nullable
protected abstract Iterable<DumperPlugin> getDumperPlugins();
@Nullable
protected abstract Iterable<ChromeDevtoolsDomain> getInspectorModules();
public final HttpRequestHandlerRegistry getRegistry()
{
HttpRequestHandlerRegistry localHttpRequestHandlerRegistry = new HttpRequestHandlerRegistry();
Object localObject = getDumperPlugins();
if (localObject != null)
{
localObject = new Dumper((Iterable)localObject);
localHttpRequestHandlerRegistry.register("/dumpapp", new StreamingDumpappHandler(mContext, (Dumper)localObject));
localHttpRequestHandlerRegistry.register("/dumpapp-raw", new RawDumpappHandler(mContext, (Dumper)localObject));
}
localObject = getInspectorModules();
if (localObject != null)
{
new ChromeDiscoveryHandler(mContext, "/inspector").register(localHttpRequestHandlerRegistry);
localHttpRequestHandlerRegistry.register("/inspector", new WebSocketHandler(mContext, new ChromeDevtoolsServer((Iterable)localObject)));
}
addCustomEntries(localHttpRequestHandlerRegistry);
localHttpRequestHandlerRegistry.register("/*", new LoggingCatchAllHandler(null));
return localHttpRequestHandlerRegistry;
}
private static class LoggingCatchAllHandler
implements HttpRequestHandler
{
public void handle(HttpRequest paramHttpRequest, HttpResponse paramHttpResponse, HttpContext paramHttpContext)
throws HttpException, IOException
{
LogUtil.w("Unsupported request received: " + paramHttpRequest.getRequestLine());
paramHttpResponse.setStatusCode(404);
paramHttpResponse.setReasonPhrase("Not Found");
paramHttpResponse.setEntity(new StringEntity("Endpoint not implemented\n", "UTF-8"));
}
}
}
/* Location:
* Qualified Name: com.facebook.stetho.Stetho.Initializer
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 3,212 | java | Stetho$Initializer.java | Java | []
| null | []
| package com.facebook.stetho;
import android.content.Context;
import com.facebook.stetho.common.LogUtil;
import com.facebook.stetho.dumpapp.Dumper;
import com.facebook.stetho.dumpapp.DumperPlugin;
import com.facebook.stetho.dumpapp.RawDumpappHandler;
import com.facebook.stetho.dumpapp.StreamingDumpappHandler;
import com.facebook.stetho.inspector.ChromeDevtoolsServer;
import com.facebook.stetho.inspector.ChromeDiscoveryHandler;
import com.facebook.stetho.inspector.protocol.ChromeDevtoolsDomain;
import com.facebook.stetho.server.RegistryInitializer;
import com.facebook.stetho.websocket.WebSocketHandler;
import java.io.IOException;
import javax.annotation.Nullable;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
public abstract class Stetho$Initializer
implements RegistryInitializer
{
private final Context mContext;
protected Stetho$Initializer(Context paramContext)
{
mContext = paramContext.getApplicationContext();
}
protected void addCustomEntries(HttpRequestHandlerRegistry paramHttpRequestHandlerRegistry) {}
@Nullable
protected abstract Iterable<DumperPlugin> getDumperPlugins();
@Nullable
protected abstract Iterable<ChromeDevtoolsDomain> getInspectorModules();
public final HttpRequestHandlerRegistry getRegistry()
{
HttpRequestHandlerRegistry localHttpRequestHandlerRegistry = new HttpRequestHandlerRegistry();
Object localObject = getDumperPlugins();
if (localObject != null)
{
localObject = new Dumper((Iterable)localObject);
localHttpRequestHandlerRegistry.register("/dumpapp", new StreamingDumpappHandler(mContext, (Dumper)localObject));
localHttpRequestHandlerRegistry.register("/dumpapp-raw", new RawDumpappHandler(mContext, (Dumper)localObject));
}
localObject = getInspectorModules();
if (localObject != null)
{
new ChromeDiscoveryHandler(mContext, "/inspector").register(localHttpRequestHandlerRegistry);
localHttpRequestHandlerRegistry.register("/inspector", new WebSocketHandler(mContext, new ChromeDevtoolsServer((Iterable)localObject)));
}
addCustomEntries(localHttpRequestHandlerRegistry);
localHttpRequestHandlerRegistry.register("/*", new LoggingCatchAllHandler(null));
return localHttpRequestHandlerRegistry;
}
private static class LoggingCatchAllHandler
implements HttpRequestHandler
{
public void handle(HttpRequest paramHttpRequest, HttpResponse paramHttpResponse, HttpContext paramHttpContext)
throws HttpException, IOException
{
LogUtil.w("Unsupported request received: " + paramHttpRequest.getRequestLine());
paramHttpResponse.setStatusCode(404);
paramHttpResponse.setReasonPhrase("Not Found");
paramHttpResponse.setEntity(new StringEntity("Endpoint not implemented\n", "UTF-8"));
}
}
}
/* Location:
* Qualified Name: com.facebook.stetho.Stetho.Initializer
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 3,212 | 0.792653 | 0.789228 | 81 | 38.666668 | 32.945148 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.641975 | false | false | 3 |
4f7e5903b9d8b6a3b023904a637bba5d0e8bdeb2 | 13,606,456,429,152 | c71405c6858807f6bb0847980e7711b23c8f7fad | /app/src/main/java/com/andrezacampbell/adidevhighlanders/view/activity/PopInterestsGridActivity.java | 20737cfac2c36ced4fe02a95328651e01bffd0d6 | []
| no_license | francorufino/highlandersCode | https://github.com/francorufino/highlandersCode | ee990f67e3122f75d3c02c3e3c00760d230cfb51 | da713eb984a109d2b87c36e6f801227ab80b1ef2 | refs/heads/master | 2020-12-26T20:14:05.955000 | 2020-02-04T19:50:30 | 2020-02-04T19:50:30 | 237,628,482 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.andrezacampbell.adidevhighlanders.view.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.andrezacampbell.adidevhighlanders.R;
import com.andrezacampbell.adidevhighlanders.model.PublicStoriesModel;
import static com.andrezacampbell.adidevhighlanders.R.drawable.alexa;
import static com.andrezacampbell.adidevhighlanders.view.activity.MainActivity.POPSTORIES;
public class PopInterestsGridActivity extends AppCompatActivity {
private TextView t1;
private TextView t2;
private TextView t3;
private TextView t4;
// private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_interests_grid_expand);
initViews();
if (getIntent() !=null && getIntent().getExtras() !=null){
PublicStoriesModel publicStoriesModel = getIntent().getExtras().getParcelable(POPSTORIES);
// Drawable drawable = getResources().getDrawable(publicStoriesModel.getPhoto());
// imageView.setImageDrawable(drawable);
}
t1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToLoginActivity();
}
});
t2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToLoginActivity();
}
});
t3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToLoginActivity();
}
});
t4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToLoginActivity();
}
});
}
private void initViews() {
t1 = findViewById(R.id.actvt_popInt_grid_exp_tv_follow_id);
t2 = findViewById(R.id.actvt_popInt_grid_exp_tv_dairy_id);
t3 = findViewById(R.id.actvt_popInt_grid_exp_tv_followers_id);
t4 = findViewById(R.id.actvt_popInt_grid_exp_tv_similar_id);
// imageView = findViewById(R.id.actvt_popInt_grid_exp_image_view_id);
}
public void goToLoginActivity(){
Intent intent = new Intent(PopInterestsGridActivity.this, LoginActivity.class);
startActivity(intent);
}
}
| UTF-8 | Java | 2,643 | java | PopInterestsGridActivity.java | Java | []
| null | []
| package com.andrezacampbell.adidevhighlanders.view.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.andrezacampbell.adidevhighlanders.R;
import com.andrezacampbell.adidevhighlanders.model.PublicStoriesModel;
import static com.andrezacampbell.adidevhighlanders.R.drawable.alexa;
import static com.andrezacampbell.adidevhighlanders.view.activity.MainActivity.POPSTORIES;
public class PopInterestsGridActivity extends AppCompatActivity {
private TextView t1;
private TextView t2;
private TextView t3;
private TextView t4;
// private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_interests_grid_expand);
initViews();
if (getIntent() !=null && getIntent().getExtras() !=null){
PublicStoriesModel publicStoriesModel = getIntent().getExtras().getParcelable(POPSTORIES);
// Drawable drawable = getResources().getDrawable(publicStoriesModel.getPhoto());
// imageView.setImageDrawable(drawable);
}
t1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToLoginActivity();
}
});
t2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToLoginActivity();
}
});
t3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToLoginActivity();
}
});
t4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToLoginActivity();
}
});
}
private void initViews() {
t1 = findViewById(R.id.actvt_popInt_grid_exp_tv_follow_id);
t2 = findViewById(R.id.actvt_popInt_grid_exp_tv_dairy_id);
t3 = findViewById(R.id.actvt_popInt_grid_exp_tv_followers_id);
t4 = findViewById(R.id.actvt_popInt_grid_exp_tv_similar_id);
// imageView = findViewById(R.id.actvt_popInt_grid_exp_image_view_id);
}
public void goToLoginActivity(){
Intent intent = new Intent(PopInterestsGridActivity.this, LoginActivity.class);
startActivity(intent);
}
}
| 2,643 | 0.662126 | 0.657586 | 80 | 32.037498 | 26.873985 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4875 | false | false | 3 |
c270620e867dddaedfcb9052c14de1dea00bfb2d | 25,941,602,538,246 | 444cc3416f9852542b137cc2a3d204f456af74a4 | /src/test/java/org/bioinfo/cellbase/parser/GtfParserTest.java | 3a06c24989ca6f43b69d7ec3bf636fc427b4d7f4 | []
| no_license | Echirivella/cellbase | https://github.com/Echirivella/cellbase | d3054c77936befe60c4b624480ec38f0f36dac48 | f657f5072bfc275238bd7fecc1454edd72c873c6 | refs/heads/master | 2021-01-15T21:15:12.798000 | 2013-02-21T18:49:53 | 2013-02-21T18:49:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.bioinfo.cellbase.parser;
import java.io.File;
import java.io.IOException;
import org.bioinfo.formats.exception.FileFormatException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class GtfParserTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testParseToJson() {
// GtfParser coreParser = new GtfParser();
// try {
// File file = new File("/home/imedina/cellbase_v3/hsapiens/hsapiens_core.json");
// file.createNewFile();
//// String jsonString =
// coreParser.parseToJson(new File("/home/imedina/cellbase_v3/hsapiens/Homo_sapiens.GRCh37.69.gtf"), new File("/home/imedina/cellbase_v3/hsapiens/gene_description.txt"), new File("/home/imedina/cellbase_v3/hsapiens/xrefs.txt"), file);
//// IOUtils.write(file, jsonString);
//
// } catch (SecurityException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (FileFormatException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
| UTF-8 | Java | 1,295 | java | GtfParserTest.java | Java | []
| null | []
| package org.bioinfo.cellbase.parser;
import java.io.File;
import java.io.IOException;
import org.bioinfo.formats.exception.FileFormatException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class GtfParserTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testParseToJson() {
// GtfParser coreParser = new GtfParser();
// try {
// File file = new File("/home/imedina/cellbase_v3/hsapiens/hsapiens_core.json");
// file.createNewFile();
//// String jsonString =
// coreParser.parseToJson(new File("/home/imedina/cellbase_v3/hsapiens/Homo_sapiens.GRCh37.69.gtf"), new File("/home/imedina/cellbase_v3/hsapiens/gene_description.txt"), new File("/home/imedina/cellbase_v3/hsapiens/xrefs.txt"), file);
//// IOUtils.write(file, jsonString);
//
// } catch (SecurityException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (NoSuchMethodException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (FileFormatException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
| 1,295 | 0.697297 | 0.69112 | 47 | 26.553192 | 35.836987 | 236 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.851064 | false | false | 3 |
2ca619c135c9d7b0c3528fe5bdab9f02157861b2 | 28,355,374,155,929 | 4a34a1d734bae72782919b11d0ebd1b41c6233c0 | /src/main/java/com/solvd/companystructure/Main.java | 6bc4bcc87c97b64e302f163f76bc33582a08789a | []
| no_license | jovchinnikova/company-structure | https://github.com/jovchinnikova/company-structure | ff57f4ecde7226e88f1d5cc82e194ab04dd83404 | d37a1c17035ea2b6f3edd0bd00756ece19bb8374 | refs/heads/master | 2023-08-24T06:05:45.699000 | 2021-11-01T10:57:18 | 2021-11-01T10:57:18 | 420,593,758 | 0 | 0 | null | false | 2021-11-01T10:57:19 | 2021-10-24T05:16:09 | 2021-10-29T22:04:43 | 2021-11-01T10:57:18 | 72 | 0 | 0 | 0 | Java | false | false | package com.solvd.companystructure;
import com.solvd.companystructure.companyinfo.*;
import com.solvd.companystructure.companyinfo.impl.AccountingImpl;
import com.solvd.companystructure.exception.InvalidPhoneException;
import com.solvd.companystructure.exception.TillProjException;
import com.solvd.companystructure.infrastructure.*;
import com.solvd.companystructure.people.*;
import com.solvd.companystructure.people.impl.ActionImpl;
import com.solvd.companystructure.people.impl.CountPeopleServiceImpl;
import com.solvd.companystructure.services.*;
import com.solvd.companystructure.services.impl.CountCostServiceImpl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Main {
private static final Logger LOGGER = LogManager.getLogger(Main.class);
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchFieldException,
IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalArgumentException {
Company solvd = new Company("Solvd Inc");
CEO director = new CEO("Ivan", "Ivanov");
director.setDob(LocalDateTime.of(1980, 11, 16, 0, 0));
solvd.setDirector(director);
try {
solvd.setPhoneNumber(12345);
} catch (InvalidPhoneException exp) {
LOGGER.error(exp.getMessage(), exp);
} finally {
LOGGER.debug("The end of phone number exception");
}
System.out.println();
solvd.setSite("solvd.com");
Service manualTest = new Service("manual testing", 200.00);
Service autoTest = new Service("automated testing", 300.00);
List<Service> qaServices = new ArrayList<>();
qaServices.add(manualTest);
qaServices.add(autoTest);
Department.QA.setServices(qaServices);
Worker vasya = new Worker("Vasiliy", "Petrov", 30.00);
vasya.setStartVacation(LocalDateTime.of(2021, 10, 20, 0, 0));
vasya.setDob(LocalDateTime.of(1980, 8, 25, 0, 0));
Worker petia = new Worker("Petr", "Pypkin", 25.00);
petia.setDob(LocalDateTime.of(1977, 01, 28, 0, 0));
petia.setTillProjectEnd(20);
Worker igor = new Worker("Igor", "Lastochkin", 40.00);
igor.setStartVacation(LocalDateTime.of(2021, 10, 21, 0, 0));
Worker tolik = new Worker("Anatoliy", "Peskov", 80.00);
tolik.setTillProjectEnd(15);
Worker vlad = new Worker("Vladislav", "Baranov", 39.50);
Set<Worker> solvdWorkers = new HashSet<>();
solvdWorkers.add(vasya);
solvdWorkers.add(petia);
solvdWorkers.add(igor);
solvdWorkers.add(tolik);
solvdWorkers.add(vlad);
solvd.setWorkers(solvdWorkers);
Client client1 = new Client("Sergey", "Novik");
client1.setDob(LocalDateTime.of(2000, 05, 15, 0, 0));
Client client2 = new Client("Saveliy", "Martynov");
Client client3 = new Client("Valeriy", "Martynov");
Client client4 = new Client("Valeriy", "Mogilev");
Set<Client> solvdClients = new TreeSet<>();
solvdClients.add(client1);
solvdClients.add(client2);
solvdClients.add(client3);
solvdClients.add(client4);
Order order1 = new Order(1, petia, autoTest, LocalDate.of(2021, 10, 1), client1);
Order order100 = new Order(100, vasya, manualTest, LocalDate.of(2021, 10, 12), client1);
Map<Integer, Order> allOrders = new HashMap<>();
allOrders.put(order1.getOrderNumber(), order1);
allOrders.put(order100.getOrderNumber(), order100);
LOGGER.info(solvd);
System.out.println();
Worker.printVacDur();
System.out.println();
petia.countAge();
vasya.countAge();
director.countAge();
client1.countAge();
System.out.println();
petia.performAction();
director.performAction();
client1.performAction();
System.out.println();
Function<Worker, Integer> days = worker -> {
LocalDateTime currentDate = LocalDateTime.now();
Integer daysPassed = currentDate.getDayOfYear() - worker.getStartVacation().getDayOfYear();
return daysPassed;
};
AccountingImpl accounting = AccountingImpl.createInstance();
solvd.setAccountingImpl(accounting);
accounting.setWorkers(solvdWorkers);
accounting.vacationCount(vasya, days);
accounting.vacationCount(igor, days);
accounting.startCount(petia);
System.out.println();
Set<Worker> workersOnVacation = new HashSet<>();
workersOnVacation.add(vasya);
workersOnVacation.add(igor);
accounting.allVacationCount(workersOnVacation, days);
System.out.println();
client1.makeOrder(solvd, 12345);
client1.makeOrder(solvd, "solv.com");
System.out.println();
LOGGER.info(order1);
order1.salaryPenalty(petia);
order100.countCost();
System.out.println();
Cleaning generalClean = new Cleaning("general cleaning", 20.00,
LocalDateTime.of(2021, 10, 6, 0, 0));
Cleaning plainClean = new Cleaning("plain cleaning", 10.00,
LocalDateTime.of(2021, 10, 16, 0, 0));
List<Cleaning> allCleaning = new ArrayList<>();
allCleaning.add(generalClean);
allCleaning.add(plainClean);
solvd.setCleanings(allCleaning);
generalClean.finishCleaning();
plainClean.finishCleaning();
System.out.println();
FoodSupply applesSupply = new FoodSupply("apples supply", 5.00, 100,
java.sql.Date.valueOf(LocalDate.of(2021, 10, 9)));
FoodSupply bananasSupply = new FoodSupply("bananas supply", 4.00, 200,
Date.valueOf(LocalDate.of(2021, 10, 20)));
List<FoodSupply> foodSupplies = new ArrayList<>();
foodSupplies.add(applesSupply);
foodSupplies.add(bananasSupply);
solvd.setFoodSupplies(foodSupplies);
applesSupply.bringFood();
bananasSupply.bringFood();
applesSupply.countCost();
bananasSupply.countCost();
System.out.println();
Set<Worker> tripParticip = new HashSet<>();
tripParticip.add(petia);
tripParticip.add(vasya);
tripParticip.add(vlad);
Set<Worker> engCourseParticip = new HashSet<>();
engCourseParticip.addAll(tripParticip);
engCourseParticip.add(igor);
engCourseParticip.add(tolik);
Activity sportTrip = new Activity("sport trip", Location.FOREST, tripParticip);
Course engCourse = new Course("English course", Location.OFFICE, engCourseParticip);
Course qaCourse = new Course("QA course", Location.OFFICE, engCourseParticip);
List<Activity> solvdActivities = new ArrayList<>();
solvdActivities.add(sportTrip);
solvdActivities.add(engCourse);
solvdActivities.add(qaCourse);
solvd.setActivities(solvdActivities);
LOGGER.info(sportTrip);
LOGGER.info(engCourse);
sportTrip.countPeople();
engCourse.countPeople();
System.out.println();
Set<Worker> belWorkers = new HashSet<>();
belWorkers.add(igor);
belWorkers.add(petia);
belWorkers.add(vlad);
Set<Worker> mainWorkers = new HashSet<>();
mainWorkers.add(vasya);
mainWorkers.add(igor);
Office belOffice = new Office("Roxoft", "Belarus", belWorkers);
Office mainOffice = new Office("Solvd", "USA", mainWorkers);
List<Office> offices = new ArrayList<>();
offices.add(belOffice);
offices.add(mainOffice);
solvd.setOffices(offices);
WorkSpace space1 = new WorkSpace("Venera", "3rd floor", belWorkers, 2);
WorkSpace space2 = new WorkSpace("Saturn", "2nd floor", mainWorkers, 2);
LOGGER.info(belOffice);
belOffice.countPeople();
LOGGER.info(mainOffice);
mainOffice.countPeople();
LOGGER.info(space1);
space1.countPeople();
LOGGER.info(space2);
space2.countPeople();
System.out.println();
Human oleg = new Worker("Oleg", "Trofimov", 32.00);
ControlClass.doAction(oleg);
Human lev = new CEO("Lev", "Ivanov");
ControlClass.doAction(lev);
Human albert = new Client("Albert", "Petrov");
ControlClass.doAction(albert);
System.out.println();
Laptop lap1 = new Laptop(Equipment.Mark.APPLE, 14);
Laptop lap2 = new Laptop(Equipment.Mark.LENOVO, 10);
Computer comp1 = new Computer(Equipment.Mark.IBM, 20);
List<Equipment> belEquipment = new ArrayList<>();
belEquipment.add(lap1);
belEquipment.add(lap2);
belEquipment.add(comp1);
belOffice.setAllEquipment(belEquipment);
belOffice.countEquipment();
System.out.println();
LOGGER.info("Interfaces");
System.out.println();
CountPeopleServiceImpl countPeopleService = new CountPeopleServiceImpl();
countPeopleService.count(belOffice);
countPeopleService.count(engCourse);
System.out.println();
CountCostServiceImpl countCostService = new CountCostServiceImpl();
countCostService.countPrice(order100);
countCostService.countPrice(applesSupply);
countCostService.countPrice(generalClean);
System.out.println();
ActionImpl action = new ActionImpl();
action.takeAction(igor);
action.takeAction(director);
action.takeAction(client1);
System.out.println();
try (AccessGranting access1 = new AccessGranting(director)) {
access1.grantAccess();
}
System.out.println();
LOGGER.info("All " + solvd.getTitle() + " clients alphabetically" + System.lineSeparator() + solvdClients);
System.out.println();
solvd.setOrders(allOrders);
solvd.countIncome();
System.out.println();
LOGGER.info("Calculations using generic class");
System.out.println();
AllCalculations<Countable, Costable> allCalculations = new AllCalculations<>();
allCalculations.setElement(engCourse);
allCalculations.setOtherElement(applesSupply);
allCalculations.getElement().countPeople();
allCalculations.getOtherElement().countCost();
System.out.println();
LOGGER.info("Calculations using generic methods");
System.out.println();
AllCalculations<?, ?> calculation = new AllCalculations<>();
calculation.calculate(sportTrip);
calculation.calculate(order1);
System.out.println();
Distribution<Client, Laptop, WorkSpace> distrib1 = new Distribution<>(client1, lap1, space1);
Distribution<CEO, Laptop, WorkSpace> distrib2 = new Distribution<>(director, lap1, space1);
Distribution<Worker, Laptop, WorkSpace> distrib3 = new Distribution<>(vasya, lap2, space2);
Distribution<Worker, Computer, WorkSpace> distrib4 = new Distribution<>(petia, comp1, space2);
distrib2.print();
distrib3.print();
distrib4.print();
System.out.println();
Worker zina = new Worker("Zinaida", "Ivanova", 5.00);
Worker fedya = new Worker("Fedor", "Petrov", 7.00);
Worker egor = new Worker("Egor", "Melnikov", 6.00);
List<Cleaning> zinaWork = new ArrayList<>();
zinaWork.add(plainClean);
List<Cleaning> fedyaWork = new ArrayList<>();
fedyaWork.add(plainClean);
fedyaWork.add(generalClean);
List<FoodSupply> egorWork = new ArrayList<>();
egorWork.add(applesSupply);
egorWork.add(bananasSupply);
Fulfillment<Worker, List<Cleaning>> zinaPerformance = new Fulfillment<>(zina, zinaWork);
zinaPerformance.print();
Fulfillment<Worker, List<Cleaning>> fedyaPerformance = new Fulfillment<>(fedya, fedyaWork);
fedyaPerformance.print();
Fulfillment<Worker, List<FoodSupply>> egorPerformance = new Fulfillment<>(egor, egorWork);
egorPerformance.print();
System.out.println();
File file = new File("src/main/resources/article.txt");
WordsCount count1 = new WordsCount(file);
count1.countWords();
System.out.println();
lap1.writeCharacteristic();
lap1.writeOrigin();
lap2.writeOrigin();
comp1.writeCharacteristic();
System.out.println();
solvd.printDepartments();
System.out.println();
String message = "There are no activities in the location";
LOGGER.info(Location.OFFICE.findActivity(solvdActivities)
.orElse(message));
LOGGER.info(Location.CINEMA.findActivity(solvdActivities)
.orElse(message));
System.out.println();
LOGGER.info("Workers with high salary:");
solvdWorkers.stream()
.filter(worker -> worker.getAverageSalary() > 30)
.sorted()
.forEach(worker -> LOGGER.info(worker + " earns " + worker.getAverageSalary() + "$ a day"));
System.out.println();
List<AdditionalService> addServices = new ArrayList<>();
addServices.add(plainClean);
addServices.add(generalClean);
addServices.add(applesSupply);
addServices.add(bananasSupply);
Double addServicePrice = addServices.stream()
.mapToDouble(addService -> addService.getPrice())
.sum();
LOGGER.info("All additional services will cost " + addServicePrice);
System.out.println();
List<Worker> participatingWorkers = solvdActivities.stream()
.flatMap(activity -> activity.getWorkers().stream())
.distinct()
.collect(Collectors.toList());
LOGGER.info("Participating workers:");
LOGGER.info(participatingWorkers);
System.out.println();
Integer firstTillProj = solvdWorkers.stream()
.map(worker -> worker.getTillProjectEnd())
.findFirst()
.orElseThrow(() -> new TillProjException("There is no info about time till project end"));
LOGGER.info("First time till project end in list is " + firstTillProj);
System.out.println();
solvdWorkers.stream()
.filter(worker -> worker.getDob() != null)
.peek(worker -> LOGGER.info("There is info about age of " + worker))
.forEach(worker -> worker.countAge());
System.out.println();
Class<?>[] paramTypes = {String.class, String.class};
Dog dog1 = Dog.class.getConstructor(paramTypes).newInstance("igor", "buldog");
Field name = Dog.class.getDeclaredField("name");
name.setAccessible(true);
LOGGER.info(name.get(dog1));
Method bark = Dog.class.getDeclaredMethod("bark");
bark.setAccessible(true);
bark.invoke(dog1);
System.out.println();
Class<?> otherDog = Class.forName(OtherDog.class.getName());
OtherDog otherDog1 = (OtherDog) otherDog.newInstance();
Field otherName = OtherDog.class.getDeclaredField("name");
otherName.setAccessible(true);
otherName.set(otherDog1, "fedor");
String oName = (String) otherName.get(otherDog1);
Field otherBreed = OtherDog.class.getDeclaredField("breed");
otherBreed.setAccessible(true);
otherBreed.set(otherDog1, "mops");
String oBreed = (String) otherBreed.get(otherDog1);
Method otherBark = OtherDog.class.getDeclaredMethod("bark", paramTypes);
otherBark.setAccessible(true);
otherBark.invoke(otherDog1, oName, oBreed);
}
}
| UTF-8 | Java | 16,155 | java | Main.java | Java | [
{
"context": "any(\"Solvd Inc\");\n CEO director = new CEO(\"Ivan\", \"Ivanov\");\n director.setDob(LocalDateTim",
"end": 1479,
"score": 0.9997743368148804,
"start": 1475,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "vd Inc\");\n CEO director = new CEO(\"Ivan\", \"Ivanov\");\n director.setDob(LocalDateTime.of(1980,",
"end": 1489,
"score": 0.9996633529663086,
"start": 1483,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "(qaServices);\n\n Worker vasya = new Worker(\"Vasiliy\", \"Petrov\", 30.00);\n vasya.setStartVacatio",
"end": 2255,
"score": 0.9998158812522888,
"start": 2248,
"tag": "NAME",
"value": "Vasiliy"
},
{
"context": ");\n\n Worker vasya = new Worker(\"Vasiliy\", \"Petrov\", 30.00);\n vasya.setStartVacation(LocalDat",
"end": 2265,
"score": 0.9997493624687195,
"start": 2259,
"tag": "NAME",
"value": "Petrov"
},
{
"context": ", 25, 0, 0));\n\n Worker petia = new Worker(\"Petr\", \"Pypkin\", 25.00);\n petia.setDob(LocalDat",
"end": 2445,
"score": 0.9998297691345215,
"start": 2441,
"tag": "NAME",
"value": "Petr"
},
{
"context": " 0));\n\n Worker petia = new Worker(\"Petr\", \"Pypkin\", 25.00);\n petia.setDob(LocalDateTime.of(1",
"end": 2455,
"score": 0.9997713565826416,
"start": 2449,
"tag": "NAME",
"value": "Pypkin"
},
{
"context": "rojectEnd(20);\n\n Worker igor = new Worker(\"Igor\", \"Lastochkin\", 40.00);\n igor.setStartVaca",
"end": 2602,
"score": 0.9998174905776978,
"start": 2598,
"tag": "NAME",
"value": "Igor"
},
{
"context": "d(20);\n\n Worker igor = new Worker(\"Igor\", \"Lastochkin\", 40.00);\n igor.setStartVacation(LocalDate",
"end": 2616,
"score": 0.99977046251297,
"start": 2606,
"tag": "NAME",
"value": "Lastochkin"
},
{
"context": ", 21, 0, 0));\n\n Worker tolik = new Worker(\"Anatoliy\", \"Peskov\", 80.00);\n tolik.setTillProjectE",
"end": 2740,
"score": 0.9997885823249817,
"start": 2732,
"tag": "NAME",
"value": "Anatoliy"
},
{
"context": ";\n\n Worker tolik = new Worker(\"Anatoliy\", \"Peskov\", 80.00);\n tolik.setTillProjectEnd(15);\n ",
"end": 2750,
"score": 0.9997289180755615,
"start": 2744,
"tag": "NAME",
"value": "Peskov"
},
{
"context": "ProjectEnd(15);\n Worker vlad = new Worker(\"Vladislav\", \"Baranov\", 39.50);\n Set<Worker> solvdWor",
"end": 2841,
"score": 0.9997633695602417,
"start": 2832,
"tag": "NAME",
"value": "Vladislav"
},
{
"context": ");\n Worker vlad = new Worker(\"Vladislav\", \"Baranov\", 39.50);\n Set<Worker> solvdWorkers = new ",
"end": 2852,
"score": 0.9996280074119568,
"start": 2845,
"tag": "NAME",
"value": "Baranov"
},
{
"context": "vdWorkers);\n\n Client client1 = new Client(\"Sergey\", \"Novik\");\n client1.setDob(LocalDateTime.",
"end": 3162,
"score": 0.9998108744621277,
"start": 3156,
"tag": "NAME",
"value": "Sergey"
},
{
"context": ";\n\n Client client1 = new Client(\"Sergey\", \"Novik\");\n client1.setDob(LocalDateTime.of(2000, ",
"end": 3171,
"score": 0.9997438192367554,
"start": 3166,
"tag": "NAME",
"value": "Novik"
},
{
"context": " 15, 0, 0));\n Client client2 = new Client(\"Saveliy\", \"Martynov\");\n Client client3 = new Clien",
"end": 3281,
"score": 0.9997892379760742,
"start": 3274,
"tag": "NAME",
"value": "Saveliy"
},
{
"context": ";\n Client client2 = new Client(\"Saveliy\", \"Martynov\");\n Client client3 = new Client(\"Valeriy\",",
"end": 3293,
"score": 0.9997465014457703,
"start": 3285,
"tag": "NAME",
"value": "Martynov"
},
{
"context": "\"Martynov\");\n Client client3 = new Client(\"Valeriy\", \"Martynov\");\n Client client4 = new Clien",
"end": 3341,
"score": 0.9997863173484802,
"start": 3334,
"tag": "NAME",
"value": "Valeriy"
},
{
"context": ";\n Client client3 = new Client(\"Valeriy\", \"Martynov\");\n Client client4 = new Client(\"Valeriy\",",
"end": 3353,
"score": 0.9997205138206482,
"start": 3345,
"tag": "NAME",
"value": "Martynov"
},
{
"context": "\"Martynov\");\n Client client4 = new Client(\"Valeriy\", \"Mogilev\");\n Set<Client> solvdClients = ",
"end": 3401,
"score": 0.9997663497924805,
"start": 3394,
"tag": "NAME",
"value": "Valeriy"
},
{
"context": ";\n Client client4 = new Client(\"Valeriy\", \"Mogilev\");\n Set<Client> solvdClients = new TreeSet",
"end": 3412,
"score": 0.9997363686561584,
"start": 3405,
"tag": "NAME",
"value": "Mogilev"
},
{
"context": "add(client4);\n\n Order order1 = new Order(1, petia, autoTest, LocalDate.of(2021, 10, 1), client1);",
"end": 3648,
"score": 0.8234750032424927,
"start": 3645,
"tag": "NAME",
"value": "pet"
},
{
"context": " client1);\n Order order100 = new Order(100, vasya, manualTest, LocalDate.of(2021, 10, 12), clie",
"end": 3740,
"score": 0.7638806104660034,
"start": 3739,
"tag": "NAME",
"value": "v"
},
{
"context": "s(solvdWorkers);\n accounting.vacationCount(vasya, days);\n accounting.vacationCount(igor, ",
"end": 4814,
"score": 0.6899537444114685,
"start": 4811,
"tag": "NAME",
"value": "vas"
},
{
"context": " = new HashSet<>();\n workersOnVacation.add(vasya);\n workersOnVacation.add(igor);\n ac",
"end": 5032,
"score": 0.9706858396530151,
"start": 5027,
"tag": "NAME",
"value": "vasya"
},
{
"context": "acation.add(vasya);\n workersOnVacation.add(igor);\n accounting.allVacationCount(workersOnVa",
"end": 5069,
"score": 0.6513240933418274,
"start": 5065,
"tag": "NAME",
"value": "igor"
},
{
"context": "ticip = new HashSet<>();\n tripParticip.add(petia);\n tripParticip.add(vasya);\n tripPa",
"end": 6657,
"score": 0.9496253132820129,
"start": 6652,
"tag": "NAME",
"value": "petia"
},
{
"context": "tripParticip.add(petia);\n tripParticip.add(vasya);\n tripParticip.add(vlad);\n Set<Wor",
"end": 6690,
"score": 0.9780271053314209,
"start": 6685,
"tag": "NAME",
"value": "vasya"
},
{
"context": "tripParticip.add(vasya);\n tripParticip.add(vlad);\n Set<Worker> engCourseParticip = new Has",
"end": 6722,
"score": 0.9776401519775391,
"start": 6718,
"tag": "NAME",
"value": "vlad"
},
{
"context": "dAll(tripParticip);\n engCourseParticip.add(igor);\n engCourseParticip.add(tolik);\n A",
"end": 6864,
"score": 0.9540767073631287,
"start": 6860,
"tag": "NAME",
"value": "igor"
},
{
"context": "Particip.add(igor);\n engCourseParticip.add(tolik);\n Activity sportTrip = new Activity(\"spor",
"end": 6902,
"score": 0.924915075302124,
"start": 6897,
"tag": "NAME",
"value": "tolik"
},
{
"context": ".out.println();\n\n Human oleg = new Worker(\"Oleg\", \"Trofimov\", 32.00);\n ControlClass.doActi",
"end": 8586,
"score": 0.999801516532898,
"start": 8582,
"tag": "NAME",
"value": "Oleg"
},
{
"context": "ntln();\n\n Human oleg = new Worker(\"Oleg\", \"Trofimov\", 32.00);\n ControlClass.doAction(oleg);\n\n ",
"end": 8598,
"score": 0.999819278717041,
"start": 8590,
"tag": "NAME",
"value": "Trofimov"
},
{
"context": "ass.doAction(oleg);\n\n Human lev = new CEO(\"Lev\", \"Ivanov\");\n ControlClass.doAction(lev);\n",
"end": 8679,
"score": 0.9995368719100952,
"start": 8676,
"tag": "NAME",
"value": "Lev"
},
{
"context": "ction(oleg);\n\n Human lev = new CEO(\"Lev\", \"Ivanov\");\n ControlClass.doAction(lev);\n\n H",
"end": 8689,
"score": 0.9997568726539612,
"start": 8683,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "oAction(lev);\n\n Human albert = new Client(\"Albert\", \"Petrov\");\n ControlClass.doAction(albert",
"end": 8771,
"score": 0.9998161792755127,
"start": 8765,
"tag": "NAME",
"value": "Albert"
},
{
"context": "v);\n\n Human albert = new Client(\"Albert\", \"Petrov\");\n ControlClass.doAction(albert);\n ",
"end": 8781,
"score": 0.9997918605804443,
"start": 8775,
"tag": "NAME",
"value": "Petrov"
},
{
"context": "out.println();\n\n Worker zina = new Worker(\"Zinaida\", \"Ivanova\", 5.00);\n Worker fedya = new Wo",
"end": 11646,
"score": 0.99980229139328,
"start": 11639,
"tag": "NAME",
"value": "Zinaida"
},
{
"context": "();\n\n Worker zina = new Worker(\"Zinaida\", \"Ivanova\", 5.00);\n Worker fedya = new Worker(\"Fedor",
"end": 11657,
"score": 0.9997718930244446,
"start": 11650,
"tag": "NAME",
"value": "Ivanova"
},
{
"context": "anova\", 5.00);\n Worker fedya = new Worker(\"Fedor\", \"Petrov\", 7.00);\n Worker egor = new Work",
"end": 11707,
"score": 0.9998252391815186,
"start": 11702,
"tag": "NAME",
"value": "Fedor"
},
{
"context": ".00);\n Worker fedya = new Worker(\"Fedor\", \"Petrov\", 7.00);\n Worker egor = new Worker(\"Egor\",",
"end": 11717,
"score": 0.999728798866272,
"start": 11711,
"tag": "NAME",
"value": "Petrov"
},
{
"context": "Petrov\", 7.00);\n Worker egor = new Worker(\"Egor\", \"Melnikov\", 6.00);\n List<Cleaning> zinaW",
"end": 11765,
"score": 0.9997891187667847,
"start": 11761,
"tag": "NAME",
"value": "Egor"
},
{
"context": " 7.00);\n Worker egor = new Worker(\"Egor\", \"Melnikov\", 6.00);\n List<Cleaning> zinaWork = new Ar",
"end": 11777,
"score": 0.999652087688446,
"start": 11769,
"tag": "NAME",
"value": "Melnikov"
},
{
"context": "cessible(true);\n otherName.set(otherDog1, \"fedor\");\n String oName = (String) otherName.get(",
"end": 15701,
"score": 0.9762498140335083,
"start": 15696,
"tag": "NAME",
"value": "fedor"
}
]
| null | []
| package com.solvd.companystructure;
import com.solvd.companystructure.companyinfo.*;
import com.solvd.companystructure.companyinfo.impl.AccountingImpl;
import com.solvd.companystructure.exception.InvalidPhoneException;
import com.solvd.companystructure.exception.TillProjException;
import com.solvd.companystructure.infrastructure.*;
import com.solvd.companystructure.people.*;
import com.solvd.companystructure.people.impl.ActionImpl;
import com.solvd.companystructure.people.impl.CountPeopleServiceImpl;
import com.solvd.companystructure.services.*;
import com.solvd.companystructure.services.impl.CountCostServiceImpl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Main {
private static final Logger LOGGER = LogManager.getLogger(Main.class);
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchFieldException,
IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalArgumentException {
Company solvd = new Company("Solvd Inc");
CEO director = new CEO("Ivan", "Ivanov");
director.setDob(LocalDateTime.of(1980, 11, 16, 0, 0));
solvd.setDirector(director);
try {
solvd.setPhoneNumber(12345);
} catch (InvalidPhoneException exp) {
LOGGER.error(exp.getMessage(), exp);
} finally {
LOGGER.debug("The end of phone number exception");
}
System.out.println();
solvd.setSite("solvd.com");
Service manualTest = new Service("manual testing", 200.00);
Service autoTest = new Service("automated testing", 300.00);
List<Service> qaServices = new ArrayList<>();
qaServices.add(manualTest);
qaServices.add(autoTest);
Department.QA.setServices(qaServices);
Worker vasya = new Worker("Vasiliy", "Petrov", 30.00);
vasya.setStartVacation(LocalDateTime.of(2021, 10, 20, 0, 0));
vasya.setDob(LocalDateTime.of(1980, 8, 25, 0, 0));
Worker petia = new Worker("Petr", "Pypkin", 25.00);
petia.setDob(LocalDateTime.of(1977, 01, 28, 0, 0));
petia.setTillProjectEnd(20);
Worker igor = new Worker("Igor", "Lastochkin", 40.00);
igor.setStartVacation(LocalDateTime.of(2021, 10, 21, 0, 0));
Worker tolik = new Worker("Anatoliy", "Peskov", 80.00);
tolik.setTillProjectEnd(15);
Worker vlad = new Worker("Vladislav", "Baranov", 39.50);
Set<Worker> solvdWorkers = new HashSet<>();
solvdWorkers.add(vasya);
solvdWorkers.add(petia);
solvdWorkers.add(igor);
solvdWorkers.add(tolik);
solvdWorkers.add(vlad);
solvd.setWorkers(solvdWorkers);
Client client1 = new Client("Sergey", "Novik");
client1.setDob(LocalDateTime.of(2000, 05, 15, 0, 0));
Client client2 = new Client("Saveliy", "Martynov");
Client client3 = new Client("Valeriy", "Martynov");
Client client4 = new Client("Valeriy", "Mogilev");
Set<Client> solvdClients = new TreeSet<>();
solvdClients.add(client1);
solvdClients.add(client2);
solvdClients.add(client3);
solvdClients.add(client4);
Order order1 = new Order(1, petia, autoTest, LocalDate.of(2021, 10, 1), client1);
Order order100 = new Order(100, vasya, manualTest, LocalDate.of(2021, 10, 12), client1);
Map<Integer, Order> allOrders = new HashMap<>();
allOrders.put(order1.getOrderNumber(), order1);
allOrders.put(order100.getOrderNumber(), order100);
LOGGER.info(solvd);
System.out.println();
Worker.printVacDur();
System.out.println();
petia.countAge();
vasya.countAge();
director.countAge();
client1.countAge();
System.out.println();
petia.performAction();
director.performAction();
client1.performAction();
System.out.println();
Function<Worker, Integer> days = worker -> {
LocalDateTime currentDate = LocalDateTime.now();
Integer daysPassed = currentDate.getDayOfYear() - worker.getStartVacation().getDayOfYear();
return daysPassed;
};
AccountingImpl accounting = AccountingImpl.createInstance();
solvd.setAccountingImpl(accounting);
accounting.setWorkers(solvdWorkers);
accounting.vacationCount(vasya, days);
accounting.vacationCount(igor, days);
accounting.startCount(petia);
System.out.println();
Set<Worker> workersOnVacation = new HashSet<>();
workersOnVacation.add(vasya);
workersOnVacation.add(igor);
accounting.allVacationCount(workersOnVacation, days);
System.out.println();
client1.makeOrder(solvd, 12345);
client1.makeOrder(solvd, "solv.com");
System.out.println();
LOGGER.info(order1);
order1.salaryPenalty(petia);
order100.countCost();
System.out.println();
Cleaning generalClean = new Cleaning("general cleaning", 20.00,
LocalDateTime.of(2021, 10, 6, 0, 0));
Cleaning plainClean = new Cleaning("plain cleaning", 10.00,
LocalDateTime.of(2021, 10, 16, 0, 0));
List<Cleaning> allCleaning = new ArrayList<>();
allCleaning.add(generalClean);
allCleaning.add(plainClean);
solvd.setCleanings(allCleaning);
generalClean.finishCleaning();
plainClean.finishCleaning();
System.out.println();
FoodSupply applesSupply = new FoodSupply("apples supply", 5.00, 100,
java.sql.Date.valueOf(LocalDate.of(2021, 10, 9)));
FoodSupply bananasSupply = new FoodSupply("bananas supply", 4.00, 200,
Date.valueOf(LocalDate.of(2021, 10, 20)));
List<FoodSupply> foodSupplies = new ArrayList<>();
foodSupplies.add(applesSupply);
foodSupplies.add(bananasSupply);
solvd.setFoodSupplies(foodSupplies);
applesSupply.bringFood();
bananasSupply.bringFood();
applesSupply.countCost();
bananasSupply.countCost();
System.out.println();
Set<Worker> tripParticip = new HashSet<>();
tripParticip.add(petia);
tripParticip.add(vasya);
tripParticip.add(vlad);
Set<Worker> engCourseParticip = new HashSet<>();
engCourseParticip.addAll(tripParticip);
engCourseParticip.add(igor);
engCourseParticip.add(tolik);
Activity sportTrip = new Activity("sport trip", Location.FOREST, tripParticip);
Course engCourse = new Course("English course", Location.OFFICE, engCourseParticip);
Course qaCourse = new Course("QA course", Location.OFFICE, engCourseParticip);
List<Activity> solvdActivities = new ArrayList<>();
solvdActivities.add(sportTrip);
solvdActivities.add(engCourse);
solvdActivities.add(qaCourse);
solvd.setActivities(solvdActivities);
LOGGER.info(sportTrip);
LOGGER.info(engCourse);
sportTrip.countPeople();
engCourse.countPeople();
System.out.println();
Set<Worker> belWorkers = new HashSet<>();
belWorkers.add(igor);
belWorkers.add(petia);
belWorkers.add(vlad);
Set<Worker> mainWorkers = new HashSet<>();
mainWorkers.add(vasya);
mainWorkers.add(igor);
Office belOffice = new Office("Roxoft", "Belarus", belWorkers);
Office mainOffice = new Office("Solvd", "USA", mainWorkers);
List<Office> offices = new ArrayList<>();
offices.add(belOffice);
offices.add(mainOffice);
solvd.setOffices(offices);
WorkSpace space1 = new WorkSpace("Venera", "3rd floor", belWorkers, 2);
WorkSpace space2 = new WorkSpace("Saturn", "2nd floor", mainWorkers, 2);
LOGGER.info(belOffice);
belOffice.countPeople();
LOGGER.info(mainOffice);
mainOffice.countPeople();
LOGGER.info(space1);
space1.countPeople();
LOGGER.info(space2);
space2.countPeople();
System.out.println();
Human oleg = new Worker("Oleg", "Trofimov", 32.00);
ControlClass.doAction(oleg);
Human lev = new CEO("Lev", "Ivanov");
ControlClass.doAction(lev);
Human albert = new Client("Albert", "Petrov");
ControlClass.doAction(albert);
System.out.println();
Laptop lap1 = new Laptop(Equipment.Mark.APPLE, 14);
Laptop lap2 = new Laptop(Equipment.Mark.LENOVO, 10);
Computer comp1 = new Computer(Equipment.Mark.IBM, 20);
List<Equipment> belEquipment = new ArrayList<>();
belEquipment.add(lap1);
belEquipment.add(lap2);
belEquipment.add(comp1);
belOffice.setAllEquipment(belEquipment);
belOffice.countEquipment();
System.out.println();
LOGGER.info("Interfaces");
System.out.println();
CountPeopleServiceImpl countPeopleService = new CountPeopleServiceImpl();
countPeopleService.count(belOffice);
countPeopleService.count(engCourse);
System.out.println();
CountCostServiceImpl countCostService = new CountCostServiceImpl();
countCostService.countPrice(order100);
countCostService.countPrice(applesSupply);
countCostService.countPrice(generalClean);
System.out.println();
ActionImpl action = new ActionImpl();
action.takeAction(igor);
action.takeAction(director);
action.takeAction(client1);
System.out.println();
try (AccessGranting access1 = new AccessGranting(director)) {
access1.grantAccess();
}
System.out.println();
LOGGER.info("All " + solvd.getTitle() + " clients alphabetically" + System.lineSeparator() + solvdClients);
System.out.println();
solvd.setOrders(allOrders);
solvd.countIncome();
System.out.println();
LOGGER.info("Calculations using generic class");
System.out.println();
AllCalculations<Countable, Costable> allCalculations = new AllCalculations<>();
allCalculations.setElement(engCourse);
allCalculations.setOtherElement(applesSupply);
allCalculations.getElement().countPeople();
allCalculations.getOtherElement().countCost();
System.out.println();
LOGGER.info("Calculations using generic methods");
System.out.println();
AllCalculations<?, ?> calculation = new AllCalculations<>();
calculation.calculate(sportTrip);
calculation.calculate(order1);
System.out.println();
Distribution<Client, Laptop, WorkSpace> distrib1 = new Distribution<>(client1, lap1, space1);
Distribution<CEO, Laptop, WorkSpace> distrib2 = new Distribution<>(director, lap1, space1);
Distribution<Worker, Laptop, WorkSpace> distrib3 = new Distribution<>(vasya, lap2, space2);
Distribution<Worker, Computer, WorkSpace> distrib4 = new Distribution<>(petia, comp1, space2);
distrib2.print();
distrib3.print();
distrib4.print();
System.out.println();
Worker zina = new Worker("Zinaida", "Ivanova", 5.00);
Worker fedya = new Worker("Fedor", "Petrov", 7.00);
Worker egor = new Worker("Egor", "Melnikov", 6.00);
List<Cleaning> zinaWork = new ArrayList<>();
zinaWork.add(plainClean);
List<Cleaning> fedyaWork = new ArrayList<>();
fedyaWork.add(plainClean);
fedyaWork.add(generalClean);
List<FoodSupply> egorWork = new ArrayList<>();
egorWork.add(applesSupply);
egorWork.add(bananasSupply);
Fulfillment<Worker, List<Cleaning>> zinaPerformance = new Fulfillment<>(zina, zinaWork);
zinaPerformance.print();
Fulfillment<Worker, List<Cleaning>> fedyaPerformance = new Fulfillment<>(fedya, fedyaWork);
fedyaPerformance.print();
Fulfillment<Worker, List<FoodSupply>> egorPerformance = new Fulfillment<>(egor, egorWork);
egorPerformance.print();
System.out.println();
File file = new File("src/main/resources/article.txt");
WordsCount count1 = new WordsCount(file);
count1.countWords();
System.out.println();
lap1.writeCharacteristic();
lap1.writeOrigin();
lap2.writeOrigin();
comp1.writeCharacteristic();
System.out.println();
solvd.printDepartments();
System.out.println();
String message = "There are no activities in the location";
LOGGER.info(Location.OFFICE.findActivity(solvdActivities)
.orElse(message));
LOGGER.info(Location.CINEMA.findActivity(solvdActivities)
.orElse(message));
System.out.println();
LOGGER.info("Workers with high salary:");
solvdWorkers.stream()
.filter(worker -> worker.getAverageSalary() > 30)
.sorted()
.forEach(worker -> LOGGER.info(worker + " earns " + worker.getAverageSalary() + "$ a day"));
System.out.println();
List<AdditionalService> addServices = new ArrayList<>();
addServices.add(plainClean);
addServices.add(generalClean);
addServices.add(applesSupply);
addServices.add(bananasSupply);
Double addServicePrice = addServices.stream()
.mapToDouble(addService -> addService.getPrice())
.sum();
LOGGER.info("All additional services will cost " + addServicePrice);
System.out.println();
List<Worker> participatingWorkers = solvdActivities.stream()
.flatMap(activity -> activity.getWorkers().stream())
.distinct()
.collect(Collectors.toList());
LOGGER.info("Participating workers:");
LOGGER.info(participatingWorkers);
System.out.println();
Integer firstTillProj = solvdWorkers.stream()
.map(worker -> worker.getTillProjectEnd())
.findFirst()
.orElseThrow(() -> new TillProjException("There is no info about time till project end"));
LOGGER.info("First time till project end in list is " + firstTillProj);
System.out.println();
solvdWorkers.stream()
.filter(worker -> worker.getDob() != null)
.peek(worker -> LOGGER.info("There is info about age of " + worker))
.forEach(worker -> worker.countAge());
System.out.println();
Class<?>[] paramTypes = {String.class, String.class};
Dog dog1 = Dog.class.getConstructor(paramTypes).newInstance("igor", "buldog");
Field name = Dog.class.getDeclaredField("name");
name.setAccessible(true);
LOGGER.info(name.get(dog1));
Method bark = Dog.class.getDeclaredMethod("bark");
bark.setAccessible(true);
bark.invoke(dog1);
System.out.println();
Class<?> otherDog = Class.forName(OtherDog.class.getName());
OtherDog otherDog1 = (OtherDog) otherDog.newInstance();
Field otherName = OtherDog.class.getDeclaredField("name");
otherName.setAccessible(true);
otherName.set(otherDog1, "fedor");
String oName = (String) otherName.get(otherDog1);
Field otherBreed = OtherDog.class.getDeclaredField("breed");
otherBreed.setAccessible(true);
otherBreed.set(otherDog1, "mops");
String oBreed = (String) otherBreed.get(otherDog1);
Method otherBark = OtherDog.class.getDeclaredMethod("bark", paramTypes);
otherBark.setAccessible(true);
otherBark.invoke(otherDog1, oName, oBreed);
}
}
| 16,155 | 0.642278 | 0.624636 | 397 | 39.692696 | 24.608599 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166247 | false | false | 3 |
f5971340c4eaf7ddfb4263db5351d73384043e61 | 541,165,890,641 | 3fc3cbf6a831ee64555e21020df0b4e698822055 | /src/main/java/com/webcheckers/ui/PostSignInRoute.java | 06aa7f1d6f74c7594991ae299694712ddc828bb1 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | jgoneil/Checkers | https://github.com/jgoneil/Checkers | eed614254adb335a41e04f3179e048b6d9f5f224 | 54b959191bab8fae8f7e81fabf351f281cec5ec8 | refs/heads/master | 2020-04-21T19:20:45.536000 | 2019-02-13T19:25:29 | 2019-02-13T19:25:29 | 169,803,181 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.webcheckers.ui;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import spark.ModelAndView;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.TemplateEngine;
import spark.Session;
import static spark.Spark.halt;
import com.webcheckers.appl.PlayerLobby;
/**
* This is {@code POST /signin } route handler. Handles user signin. Checks user input to ensure the
* username is not already in use
*/
public class PostSignInRoute implements Route {
//Static final variables (constants)
static final String REVERT_VIEW = "signin.ftl";
static final String USER_PARAM = "username";
//HTML template loader for freemarker pages
private final TemplateEngine templateEngine;
//List of playerLobby connected to the game
private final PlayerLobby playerLobby;
/**
* Constructor for class. Ensures both parameters are included in the declaration for use
*
* @param templateEngine the formatting definition for spark to java messaging
* @param playerLobby the class holding all of the currently connected playerLobby
*/
public PostSignInRoute(final TemplateEngine templateEngine, final PlayerLobby playerLobby) {
Objects.requireNonNull(templateEngine, "templateEngine must not be null");
Objects.requireNonNull(playerLobby, "playerLobby must not be null");
this.templateEngine = templateEngine;
this.playerLobby = playerLobby;
}
/**
* Main connection for playerLobby attempting to sign in Handles error checking on input to ensure
* validity and that the input follows guidelines
*
* @param request the messages coming from the from the frontend
* @param response the messages the backend (this class) are responding with
* @return the rendered view page for the user
*/
@Override
public String handle(Request request, Response response) {
final Map<String, Object> vm = new HashMap<>();
final String username = request.queryParams(USER_PARAM);
final Session httpSession = request.session();
if (username != null) {
ModelAndView mv;
if (playerLobby.addPlayer(username)) {
httpSession.attribute(GetHomeRoute.PLAYERSERVICES_KEY, username.trim());
response.redirect(WebServer.HOME_URL);
return null;
} else {
vm.put("title", GetSigninRoute.TITLE);
vm.put("header", GetSigninRoute.HEADER);
vm.put(GetSigninRoute.ATTEMPT_FAILED, true);
mv = new ModelAndView(vm, REVERT_VIEW);
return templateEngine.render(mv);
}
} else {
response.redirect(WebServer.HOME_URL);
halt();
return null;
}
}
}
| UTF-8 | Java | 2,654 | java | PostSignInRoute.java | Java | [
{
"context": "\"signin.ftl\";\n static final String USER_PARAM = \"username\";\n\n //HTML template loader for freemarker pages\n",
"end": 648,
"score": 0.628452479839325,
"start": 640,
"tag": "USERNAME",
"value": "username"
}
]
| null | []
| package com.webcheckers.ui;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import spark.ModelAndView;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.TemplateEngine;
import spark.Session;
import static spark.Spark.halt;
import com.webcheckers.appl.PlayerLobby;
/**
* This is {@code POST /signin } route handler. Handles user signin. Checks user input to ensure the
* username is not already in use
*/
public class PostSignInRoute implements Route {
//Static final variables (constants)
static final String REVERT_VIEW = "signin.ftl";
static final String USER_PARAM = "username";
//HTML template loader for freemarker pages
private final TemplateEngine templateEngine;
//List of playerLobby connected to the game
private final PlayerLobby playerLobby;
/**
* Constructor for class. Ensures both parameters are included in the declaration for use
*
* @param templateEngine the formatting definition for spark to java messaging
* @param playerLobby the class holding all of the currently connected playerLobby
*/
public PostSignInRoute(final TemplateEngine templateEngine, final PlayerLobby playerLobby) {
Objects.requireNonNull(templateEngine, "templateEngine must not be null");
Objects.requireNonNull(playerLobby, "playerLobby must not be null");
this.templateEngine = templateEngine;
this.playerLobby = playerLobby;
}
/**
* Main connection for playerLobby attempting to sign in Handles error checking on input to ensure
* validity and that the input follows guidelines
*
* @param request the messages coming from the from the frontend
* @param response the messages the backend (this class) are responding with
* @return the rendered view page for the user
*/
@Override
public String handle(Request request, Response response) {
final Map<String, Object> vm = new HashMap<>();
final String username = request.queryParams(USER_PARAM);
final Session httpSession = request.session();
if (username != null) {
ModelAndView mv;
if (playerLobby.addPlayer(username)) {
httpSession.attribute(GetHomeRoute.PLAYERSERVICES_KEY, username.trim());
response.redirect(WebServer.HOME_URL);
return null;
} else {
vm.put("title", GetSigninRoute.TITLE);
vm.put("header", GetSigninRoute.HEADER);
vm.put(GetSigninRoute.ATTEMPT_FAILED, true);
mv = new ModelAndView(vm, REVERT_VIEW);
return templateEngine.render(mv);
}
} else {
response.redirect(WebServer.HOME_URL);
halt();
return null;
}
}
}
| 2,654 | 0.721929 | 0.721929 | 82 | 31.365854 | 27.745583 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548781 | false | false | 3 |
166c4c71c5a76dcff45c5effd7bf478e36e6d3eb | 764,504,235,531 | 638668b2e053972f47bf1c04d886acdbd6c1b537 | /beige-logging-base/src/main/java/org/beigesoft/log/PrnThr.java | fa8f472316d483982d6bdb778fb34e75e7dbbc43 | [
"BSD-2-Clause",
"MIT",
"Apache-2.0"
]
| permissive | demidenko05/beige-logging | https://github.com/demidenko05/beige-logging | 5cc92a35d46c381343895ec62cbe36544abc0c41 | 3e1d2ef852da7813815c68ab75bbef73fe4647b2 | refs/heads/master | 2021-06-03T07:30:17.494000 | 2020-10-13T11:12:31 | 2020-10-13T11:12:31 | 104,195,013 | 0 | 0 | BSD-2-Clause | false | 2020-10-13T00:22:01 | 2017-09-20T09:31:08 | 2020-09-13T08:43:17 | 2020-10-13T00:22:00 | 135 | 0 | 0 | 1 | Java | false | false | /*
BSD 2-Clause License
Copyright (c) 2019, Beigesoft™
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 org.beigesoft.log;
/**
* <p>Throwable printer.</p>
*
* @author Yury Demidenko
*/
public class PrnThr {
/**
* <p>Line separator.</p>
**/
private String lnSp = System.getProperty("line.separator");
//Utils:
/**
* <p>Append thrown message to the buffer.</p>
* @param pBuf Buffer
* @param pThrown throwable
**/
public final void excStr(final StringBuffer pBuf, final Throwable pThrown) {
if (pThrown == null) {
pBuf.append(" ex-null");
} else {
pBuf.append(pThrown.toString());
StackTraceElement[] stes = pThrown.getStackTrace();
for (int i = 0; stes != null && i < stes.length; i++) {
pBuf.append(this.lnSp + "\tat ");
pBuf.append(stes[i].toString());
}
for (Throwable sprd : pThrown.getSuppressed()) {
pBuf.append(this.lnSp + "Suppressed: ");
pBuf.append(sprd.toString() + "\t|");
}
Throwable thr = pThrown.getCause();
if (thr != null && thr != pThrown) { //2-nd, ... levels
excStrNxt(pBuf, thr);
}
}
pBuf.append(this.lnSp);
}
/**
* <p>Append thrown next level message to the buffer.</p>
* @param pBuf Buffer
* @param pThr throwable
**/
public final void excStrNxt(final StringBuffer pBuf, final Throwable pThr) {
pBuf.append(this.lnSp).append("Caused by: ");
pBuf.append(pThr);
StackTraceElement[] stes = pThr.getStackTrace();
for (int i = 0; stes != null && i < stes.length; i++) {
pBuf.append(this.lnSp + "\tat ");
pBuf.append(stes[i].toString());
}
for (Throwable sprd : pThr.getSuppressed()) {
pBuf.append(this.lnSp + "Suppressed: ");
pBuf.append(sprd.toString() + "\t|");
}
Throwable thrNxt = pThr.getCause();
if (thrNxt != null && thrNxt != pThr) { //next level
excStrNxt(pBuf, thrNxt);
}
}
//Simple getters and setters:
/**
* <p>Getter for lnSp.</p>
* @return String
**/
public final String getLnSp() {
return this.lnSp;
}
/**
* <p>Setter for lnSp.</p>
* @param pLnSp reference
**/
public final void setLnSp(final String pLnSp) {
this.lnSp = pLnSp;
}
}
| UTF-8 | Java | 3,479 | java | PrnThr.java | Java | [
{
"context": "g;\n\n/**\n * <p>Throwable printer.</p>\n *\n * @author Yury Demidenko\n */\npublic class PrnThr {\n\n /**\n * <p>Line sep",
"end": 1412,
"score": 0.9996966123580933,
"start": 1398,
"tag": "NAME",
"value": "Yury Demidenko"
}
]
| null | []
| /*
BSD 2-Clause License
Copyright (c) 2019, Beigesoft™
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 org.beigesoft.log;
/**
* <p>Throwable printer.</p>
*
* @author <NAME>
*/
public class PrnThr {
/**
* <p>Line separator.</p>
**/
private String lnSp = System.getProperty("line.separator");
//Utils:
/**
* <p>Append thrown message to the buffer.</p>
* @param pBuf Buffer
* @param pThrown throwable
**/
public final void excStr(final StringBuffer pBuf, final Throwable pThrown) {
if (pThrown == null) {
pBuf.append(" ex-null");
} else {
pBuf.append(pThrown.toString());
StackTraceElement[] stes = pThrown.getStackTrace();
for (int i = 0; stes != null && i < stes.length; i++) {
pBuf.append(this.lnSp + "\tat ");
pBuf.append(stes[i].toString());
}
for (Throwable sprd : pThrown.getSuppressed()) {
pBuf.append(this.lnSp + "Suppressed: ");
pBuf.append(sprd.toString() + "\t|");
}
Throwable thr = pThrown.getCause();
if (thr != null && thr != pThrown) { //2-nd, ... levels
excStrNxt(pBuf, thr);
}
}
pBuf.append(this.lnSp);
}
/**
* <p>Append thrown next level message to the buffer.</p>
* @param pBuf Buffer
* @param pThr throwable
**/
public final void excStrNxt(final StringBuffer pBuf, final Throwable pThr) {
pBuf.append(this.lnSp).append("Caused by: ");
pBuf.append(pThr);
StackTraceElement[] stes = pThr.getStackTrace();
for (int i = 0; stes != null && i < stes.length; i++) {
pBuf.append(this.lnSp + "\tat ");
pBuf.append(stes[i].toString());
}
for (Throwable sprd : pThr.getSuppressed()) {
pBuf.append(this.lnSp + "Suppressed: ");
pBuf.append(sprd.toString() + "\t|");
}
Throwable thrNxt = pThr.getCause();
if (thrNxt != null && thrNxt != pThr) { //next level
excStrNxt(pBuf, thrNxt);
}
}
//Simple getters and setters:
/**
* <p>Getter for lnSp.</p>
* @return String
**/
public final String getLnSp() {
return this.lnSp;
}
/**
* <p>Setter for lnSp.</p>
* @param pLnSp reference
**/
public final void setLnSp(final String pLnSp) {
this.lnSp = pLnSp;
}
}
| 3,471 | 0.665804 | 0.663503 | 111 | 30.324324 | 26.187874 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.513514 | false | false | 3 |
697e8d6fe603715aa642840ade6545d3b01d76fe | 30,992,484,049,318 | 1e9c9f2a9639db7cdb032aae69cb4d99aef1d3a5 | /pluralSight/javaFundamentalsPart2/4_io/printing/ICartridge.java | b093289ae31e16b50c804f388a0a85b4e29ae42d | [
"MIT"
]
| permissive | sagarnikam123/learnNPractice | https://github.com/sagarnikam123/learnNPractice | f0da3f8acf653e56c591353ab342765a6831698c | 1b3b0cb2cff2f478006626a4c37a99102acbb628 | refs/heads/master | 2023-02-04T11:21:18.211000 | 2023-01-24T14:47:52 | 2023-01-24T14:47:52 | 61,184,927 | 2 | 1 | MIT | false | 2022-03-06T11:07:18 | 2016-06-15T06:57:19 | 2022-01-09T16:47:26 | 2022-03-06T11:07:18 | 33,448 | 0 | 1 | 0 | Python | false | false | package printing;
public interface ICartridge
{
public String getFillPercentage();
public String printColor();
}
| UTF-8 | Java | 123 | java | ICartridge.java | Java | []
| null | []
| package printing;
public interface ICartridge
{
public String getFillPercentage();
public String printColor();
}
| 123 | 0.739837 | 0.739837 | 7 | 15.571428 | 13.79293 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 3 |
bb5a4f3352f4dec6852c8783eca374b2c9027c4e | 16,612,933,550,030 | d7b38d8aeb27dcb8e1b1191a0da1adf66a666545 | /build/project/src/sudoku/BoardController.java | 312f426a9ab7766b4eb95caf5898c1c96cd3358d | []
| no_license | MrKhantee/SudokuGameJava | https://github.com/MrKhantee/SudokuGameJava | 2bea288b703cea750cd892559a06f6a6155dd2ca | eb633e2124528db7c478a6c7fa06c7fd88daee4d | refs/heads/master | 2020-06-29T05:49:03.392000 | 2017-04-09T09:37:11 | 2017-04-09T09:37:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sudoku;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;
public class BoardController implements Initializable {
//Injectable Fields for FXML Document
@FXML AnchorPane mainPane;
//Developer added panes.
GridPane gridPane = new GridPane();
SidePane sidePane = null;
BottomPane bottomPane = null;
//Buttons for user interaction.
BoardButton submitButton = null;
BoardButton resetButton = null;
BoardButton checkButton = null;
BoardButton solveButton = null;
//PANE SIZE
final double PANE_WIDTH = 1024;
final double PANE_HEIGHT = 768;
final static int BOARD_WIDE = 9;
final static int BOARD_TALL = 9;
final static int SIZE_SQUARE = 3;
private final double BOARD_HEIGHT = (double)(5D/7D)*PANE_HEIGHT;
private final double BOARD_WIDTH = (double)(5D/7D)*PANE_WIDTH;
private Square sudokuBoard[][] = null;
ReadFile rf = null;
//Is the board valid?
boolean isBoardValid = false;
//private String filename = "board1.txt";
@Override
public void initialize(URL location, ResourceBundle resources)
{
try
{
rf = new ReadFile(FrontPageController.filename);
this.sudokuBoard = rf.getBoard();
rf = null; //Reset file pointer.
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoMoreContentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
initialiseGridPane(BOARD_WIDTH, BOARD_HEIGHT);
addPanes();
initialiseBoard();
addButtons();
}
private void initialiseGridPane(double width, double height){
this.gridPane.setPrefSize(width, height);
this.gridPane.setMinSize(width, height);
for(int i = 0; i < BOARD_WIDE; i++){
//System.err.println( (double)(BOARD_WIDTH/9.0D) );
gridPane.getColumnConstraints().add(new ColumnConstraints((double)(BOARD_WIDTH/9)));
}
for(int j = 0; j < BOARD_TALL; j++){
gridPane.getRowConstraints().add(new RowConstraints((double)(BOARD_HEIGHT/9)));
}
this.gridPane.setLayoutX(5);
this.gridPane.setLayoutY(5);
mainPane.getChildren().add(gridPane);
}
private void initialiseBoard(){
for(int i = 0; i <BOARD_WIDE ; i++){
for(int j = 0; j < BOARD_TALL; j++){
this.gridPane.add(sudokuBoard[i][j], j, i);
}
}
}
private void addPanes(){
//Add side-pane onto board.
sidePane = new SidePane(PANE_WIDTH-BOARD_WIDTH-10, PANE_HEIGHT-4, BOARD_WIDTH+18, 4);
mainPane.getChildren().add(sidePane);
//Add bottom-pane onto board
bottomPane = new BottomPane(BOARD_WIDTH+3, PANE_HEIGHT-BOARD_HEIGHT-10,0+6,BOARD_HEIGHT+10);
mainPane.getChildren().add(bottomPane);
}
private void addButtons(){
//Add the submit button to the board.
submitButton = new BoardButton(100, 20, 620, 165, "Submit");
resetButton = new BoardButton(100, 20, 500, 165, "Reset");
checkButton = new BoardButton(100, 20, 380, 165, "Check");
solveButton = new BoardButton(100, 20, 260, 165, "Solve");
bottomPane.getChildren().addAll(resetButton, submitButton, checkButton, solveButton);
//Add Event Handlers for buttons.
submitButton.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
if(!isBoardValid){
System.out.println("Please check that your board is valid and complete!");
}
}
});
//Reset button event handler.
resetButton.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirm Reset Event");
String s = "Do you really want to reset the board?";
bottomPane.setText("The Reset Button has been pressed");
alert.setContentText(s);
Optional<ButtonType> result = alert.showAndWait();
if ((result.isPresent()) && (result.get() == ButtonType.OK)) {
try {
rf = new ReadFile(FrontPageController.filename);
sudokuBoard = rf.getBoard();
initialiseBoard();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
System.err.println("File Not Found");
} catch (NoMoreContentException e1) {
System.err.println("There inputted board is not 9x9.");
}
}
}
});
//Check Button
checkButton.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
BoardChecker bc = new BoardChecker();
boolean[] res = bc.checkBoard(sudokuBoard);
isBoardValid = res[0] & res[1] & res[2];
if(isBoardValid)
{
bottomPane.setText("");
bottomPane.setText("Check Complete: Board Is Valid \n Submit your solution!");
}
else
{
bottomPane.setText("");
bottomPane.setText("Check Complete: Board is Invalid");
}
}
});
//Solve button action listener.
solveButton.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
bottomPane.setText("Attempting to Solve Board!!");
//BoardSolver bs = new BoardSolver(sudokuBoard);
}
});
}
}
| UTF-8 | Java | 5,685 | java | BoardController.java | Java | []
| null | []
| package sudoku;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;
public class BoardController implements Initializable {
//Injectable Fields for FXML Document
@FXML AnchorPane mainPane;
//Developer added panes.
GridPane gridPane = new GridPane();
SidePane sidePane = null;
BottomPane bottomPane = null;
//Buttons for user interaction.
BoardButton submitButton = null;
BoardButton resetButton = null;
BoardButton checkButton = null;
BoardButton solveButton = null;
//PANE SIZE
final double PANE_WIDTH = 1024;
final double PANE_HEIGHT = 768;
final static int BOARD_WIDE = 9;
final static int BOARD_TALL = 9;
final static int SIZE_SQUARE = 3;
private final double BOARD_HEIGHT = (double)(5D/7D)*PANE_HEIGHT;
private final double BOARD_WIDTH = (double)(5D/7D)*PANE_WIDTH;
private Square sudokuBoard[][] = null;
ReadFile rf = null;
//Is the board valid?
boolean isBoardValid = false;
//private String filename = "board1.txt";
@Override
public void initialize(URL location, ResourceBundle resources)
{
try
{
rf = new ReadFile(FrontPageController.filename);
this.sudokuBoard = rf.getBoard();
rf = null; //Reset file pointer.
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoMoreContentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
initialiseGridPane(BOARD_WIDTH, BOARD_HEIGHT);
addPanes();
initialiseBoard();
addButtons();
}
private void initialiseGridPane(double width, double height){
this.gridPane.setPrefSize(width, height);
this.gridPane.setMinSize(width, height);
for(int i = 0; i < BOARD_WIDE; i++){
//System.err.println( (double)(BOARD_WIDTH/9.0D) );
gridPane.getColumnConstraints().add(new ColumnConstraints((double)(BOARD_WIDTH/9)));
}
for(int j = 0; j < BOARD_TALL; j++){
gridPane.getRowConstraints().add(new RowConstraints((double)(BOARD_HEIGHT/9)));
}
this.gridPane.setLayoutX(5);
this.gridPane.setLayoutY(5);
mainPane.getChildren().add(gridPane);
}
private void initialiseBoard(){
for(int i = 0; i <BOARD_WIDE ; i++){
for(int j = 0; j < BOARD_TALL; j++){
this.gridPane.add(sudokuBoard[i][j], j, i);
}
}
}
private void addPanes(){
//Add side-pane onto board.
sidePane = new SidePane(PANE_WIDTH-BOARD_WIDTH-10, PANE_HEIGHT-4, BOARD_WIDTH+18, 4);
mainPane.getChildren().add(sidePane);
//Add bottom-pane onto board
bottomPane = new BottomPane(BOARD_WIDTH+3, PANE_HEIGHT-BOARD_HEIGHT-10,0+6,BOARD_HEIGHT+10);
mainPane.getChildren().add(bottomPane);
}
private void addButtons(){
//Add the submit button to the board.
submitButton = new BoardButton(100, 20, 620, 165, "Submit");
resetButton = new BoardButton(100, 20, 500, 165, "Reset");
checkButton = new BoardButton(100, 20, 380, 165, "Check");
solveButton = new BoardButton(100, 20, 260, 165, "Solve");
bottomPane.getChildren().addAll(resetButton, submitButton, checkButton, solveButton);
//Add Event Handlers for buttons.
submitButton.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
if(!isBoardValid){
System.out.println("Please check that your board is valid and complete!");
}
}
});
//Reset button event handler.
resetButton.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirm Reset Event");
String s = "Do you really want to reset the board?";
bottomPane.setText("The Reset Button has been pressed");
alert.setContentText(s);
Optional<ButtonType> result = alert.showAndWait();
if ((result.isPresent()) && (result.get() == ButtonType.OK)) {
try {
rf = new ReadFile(FrontPageController.filename);
sudokuBoard = rf.getBoard();
initialiseBoard();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
System.err.println("File Not Found");
} catch (NoMoreContentException e1) {
System.err.println("There inputted board is not 9x9.");
}
}
}
});
//Check Button
checkButton.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
BoardChecker bc = new BoardChecker();
boolean[] res = bc.checkBoard(sudokuBoard);
isBoardValid = res[0] & res[1] & res[2];
if(isBoardValid)
{
bottomPane.setText("");
bottomPane.setText("Check Complete: Board Is Valid \n Submit your solution!");
}
else
{
bottomPane.setText("");
bottomPane.setText("Check Complete: Board is Invalid");
}
}
});
//Solve button action listener.
solveButton.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
bottomPane.setText("Attempting to Solve Board!!");
//BoardSolver bs = new BoardSolver(sudokuBoard);
}
});
}
}
| 5,685 | 0.671592 | 0.655937 | 198 | 27.712122 | 22.953245 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.691919 | false | false | 3 |
fb824b43f7ae29011402b44ab30eac2682484052 | 33,964,601,387,736 | ccebc68dadc76a41ee9b912cbc13700264c3d011 | /hl-common/src/main/java/com/hualongdata/springstarter/common/domain/UserSex.java | 35e2bf1973fcad9d1b89219339169c7ce0c9c3d8 | []
| no_license | Syngain/spring-starter | https://github.com/Syngain/spring-starter | 85da710eb5b84e0053894e3ad1422b5437f59fb8 | 5cef0efc9218bd4478e1d2c7b8aed89a3d5ad17f | refs/heads/master | 2020-07-03T07:16:47.635000 | 2016-09-27T09:45:09 | 2016-09-27T09:45:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hualongdata.springstarter.common.domain;
/**
* Created by yangbajing on 16-9-9.
*/
public enum UserSex {
F, // 女
M, // 男
U // 未知
}
| UTF-8 | Java | 166 | java | UserSex.java | Java | [
{
"context": "ta.springstarter.common.domain;\n\n/**\n * Created by yangbajing on 16-9-9.\n */\npublic enum UserSex {\n F, // 女\n",
"end": 82,
"score": 0.9995942711830139,
"start": 72,
"tag": "USERNAME",
"value": "yangbajing"
}
]
| null | []
| package com.hualongdata.springstarter.common.domain;
/**
* Created by yangbajing on 16-9-9.
*/
public enum UserSex {
F, // 女
M, // 男
U // 未知
}
| 166 | 0.601266 | 0.575949 | 10 | 14.8 | 16.004999 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 3 |
505b02d3842f556d321d80e2c78d21d6a626d9ab | 13,211,319,451,398 | 7f2f94365ffec4866446d97adc05e67f42c1b5dd | /components-c3p0/src/main/java/com/libo/c3p0/util/DBPropUtil.java | d6dce29a6e5c6d960139cbf54742a61228325aaf | [
"Apache-2.0"
]
| permissive | alex4java/coffice-components | https://github.com/alex4java/coffice-components | 7d85ab6c89f7cda1ddd6d1878f24c64c7d513920 | b0b42f38feccfe529d32188d731d616444c405d9 | refs/heads/master | 2020-03-14T12:20:50.140000 | 2018-04-30T16:03:39 | 2018-04-30T16:03:39 | 131,609,855 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.libo.c3p0.util;
import java.io.IOException;
import java.util.Properties;
import com.libo.c3p0.constant.DBConnKey;
import com.libo.c3p0.constant.DBConstant;
/**
* @author libo
* @date 2015-12-28
* @description 专门用于读取数据库DB信息Properties文件
*/
public class DBPropUtil {
//系统数据库的映射对象
private static Properties dbProp;
/**
* 静态代码 直接执行
*/
static {
dbProp = new Properties();
try {
dbProp.load(DBPropUtil.class.getClassLoader().getResourceAsStream(DBConstant.DB_PROP_CONFIG));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @description 获取对应的value数值根据key
* @param key
* @return
*/
public static String getValueByKey(String key){
//判断字符串是否为空
if(StringUtil.isNotEmpty(key))
return dbProp.getProperty(key);
return null;
}
/**
* @date 2015-12-28
* @description 获取数据连接url
* @return
*/
public static String getConnectionUrl(){
return DBPropUtil.getValueByKey(DBConnKey.DB_CONN_URL.toString());
}
/**
* @date 2015-12-28
* @description 获取数据库驱动类
* @return
*/
public static String getConnectionDriver(){
return DBPropUtil.getValueByKey(DBConnKey.DB_DRIVER_CLASS.toString());
}
/**
* @date 2015-12-28
* @description 获取数据库连接用户名
* @return
*/
public static String getConnectionUserName(){
return DBPropUtil.getValueByKey(DBConnKey.DB_CONN_USER.toString());
}
/**
* @date 2015-12-28
* @description 获取数据库密码
* @return
*/
public static String getConnectionPassword(){
return DBPropUtil.getValueByKey(DBConnKey.DB_CONN_PASSWORD.toString());
}
/**
* @date 2015-12-28
* @description 获取数据库初始化连接池
* @return
*/
public static Integer getConnectionPoolInitSize(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_INIT_CONN_POOL_NUM.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库最小连接池
* @return
*/
public static Integer getConnectionPoolMinSize(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_MIN_CONN_POOL_NUM.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库最大连接池
* @return
*/
public static Integer getConnectionPoolMaxSize(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_MAX_CONN_POOL_NUM.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库最大statement数量
* @return
*/
public static Integer getConnectionMaxStatement(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_MAX_STATE_POOL_NUM.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库最大间隔时间
* @return
*/
public static Integer getConnectionMaxIdleTime(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_MAX_IDLE_TIME_NUM.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库自增长连接个数
* @return
*/
public static Integer getConnectionAccquireIncrement(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_ACQUIRE_INCREMENT.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库自增长连接个数
* @return
*/
public static boolean getConnectionCommitOnClose(){
return Boolean.parseBoolean(DBPropUtil.getValueByKey(DBConnKey.DB_COMMIT_ON_CLOSE.toString()));
}
public static void main(String[] args) {
System.out.println(DBPropUtil.getConnectionUrl());
}
}
| UTF-8 | Java | 3,563 | java | DBPropUtil.java | Java | [
{
"context": "om.libo.c3p0.constant.DBConstant;\n\n\n/**\n * @author libo\n * @date 2015-12-28\n * @description 专门用于读取数据库DB信息",
"end": 191,
"score": 0.999518632888794,
"start": 187,
"tag": "USERNAME",
"value": "libo"
}
]
| null | []
| package com.libo.c3p0.util;
import java.io.IOException;
import java.util.Properties;
import com.libo.c3p0.constant.DBConnKey;
import com.libo.c3p0.constant.DBConstant;
/**
* @author libo
* @date 2015-12-28
* @description 专门用于读取数据库DB信息Properties文件
*/
public class DBPropUtil {
//系统数据库的映射对象
private static Properties dbProp;
/**
* 静态代码 直接执行
*/
static {
dbProp = new Properties();
try {
dbProp.load(DBPropUtil.class.getClassLoader().getResourceAsStream(DBConstant.DB_PROP_CONFIG));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @description 获取对应的value数值根据key
* @param key
* @return
*/
public static String getValueByKey(String key){
//判断字符串是否为空
if(StringUtil.isNotEmpty(key))
return dbProp.getProperty(key);
return null;
}
/**
* @date 2015-12-28
* @description 获取数据连接url
* @return
*/
public static String getConnectionUrl(){
return DBPropUtil.getValueByKey(DBConnKey.DB_CONN_URL.toString());
}
/**
* @date 2015-12-28
* @description 获取数据库驱动类
* @return
*/
public static String getConnectionDriver(){
return DBPropUtil.getValueByKey(DBConnKey.DB_DRIVER_CLASS.toString());
}
/**
* @date 2015-12-28
* @description 获取数据库连接用户名
* @return
*/
public static String getConnectionUserName(){
return DBPropUtil.getValueByKey(DBConnKey.DB_CONN_USER.toString());
}
/**
* @date 2015-12-28
* @description 获取数据库密码
* @return
*/
public static String getConnectionPassword(){
return DBPropUtil.getValueByKey(DBConnKey.DB_CONN_PASSWORD.toString());
}
/**
* @date 2015-12-28
* @description 获取数据库初始化连接池
* @return
*/
public static Integer getConnectionPoolInitSize(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_INIT_CONN_POOL_NUM.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库最小连接池
* @return
*/
public static Integer getConnectionPoolMinSize(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_MIN_CONN_POOL_NUM.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库最大连接池
* @return
*/
public static Integer getConnectionPoolMaxSize(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_MAX_CONN_POOL_NUM.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库最大statement数量
* @return
*/
public static Integer getConnectionMaxStatement(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_MAX_STATE_POOL_NUM.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库最大间隔时间
* @return
*/
public static Integer getConnectionMaxIdleTime(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_MAX_IDLE_TIME_NUM.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库自增长连接个数
* @return
*/
public static Integer getConnectionAccquireIncrement(){
return Integer.parseInt(DBPropUtil.getValueByKey(DBConnKey.DB_ACQUIRE_INCREMENT.toString()));
}
/**
* @date 2015-12-28
* @description 获取数据库自增长连接个数
* @return
*/
public static boolean getConnectionCommitOnClose(){
return Boolean.parseBoolean(DBPropUtil.getValueByKey(DBConnKey.DB_COMMIT_ON_CLOSE.toString()));
}
public static void main(String[] args) {
System.out.println(DBPropUtil.getConnectionUrl());
}
}
| 3,563 | 0.707654 | 0.676299 | 151 | 20.543047 | 24.882702 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.205298 | false | false | 3 |
9b3b2c38c5be1f5df0f0337a9941d3099bc8c6c8 | 10,840,497,467,350 | cd5e032a8db1c3cd7acc09798017b600120988eb | /app/src/main/java/com/a7552_2c_2018/melliapp/fragment/CCSecureCodeFragment.java | fa1442bab8030a679dd0728b46b3d3320be44113 | [
"Apache-2.0"
]
| permissive | 7552-2C-2018/MelliApp | https://github.com/7552-2C-2018/MelliApp | ce3de2f381ebdce9e866944d85c713aa3f4f80f6 | c9b261466f5a22bd81f1c02e791669b33b744ef7 | refs/heads/master | 2020-03-27T05:55:07.853000 | 2018-12-13T05:47:39 | 2018-12-13T05:47:39 | 146,061,853 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.a7552_2c_2018.melliapp.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import com.a7552_2c_2018.melliapp.R;
import com.a7552_2c_2018.melliapp.activity.CheckOutActivity;
import com.a7552_2c_2018.melliapp.model.ActualBuy;
import com.a7552_2c_2018.melliapp.singletons.SingletonUser;
import com.a7552_2c_2018.melliapp.utils.CreditCardEditText;
import java.util.Objects;
import butterknife.BindView;
import butterknife.ButterKnife;
import static android.content.ContentValues.TAG;
/**
* A simple {@link Fragment} subclass.
*/
public class CCSecureCodeFragment extends Fragment {
@BindView(R.id.et_cvv)
CreditCardEditText et_cvv;
private TextView tv_cvv;
private CheckOutActivity activity;
public CCSecureCodeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_ccsecure_code, container, false);
ButterKnife.bind(this, view);
activity = (CheckOutActivity) getActivity();
et_cvv.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (tv_cvv != null) {
if (TextUtils.isEmpty(editable.toString().trim()))
tv_cvv.setText(getString(R.string.card_cvv_sample));
else
tv_cvv.setText(editable.toString());
} else
Log.d(TAG, "afterTextChanged: cvv null");
}
});
et_cvv.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
if(activity!=null)
{
activity.nextClick();
return true;
}
}
return false;
});
et_cvv.setOnBackButtonListener(() -> {
if(activity!=null)
activity.onBackPressed();
});
return view;
}
public void setCvv(TextView tv) {
tv_cvv = tv;
}
public String getValue() {
String getValue = "";
if (et_cvv != null) {
getValue = Objects.requireNonNull(et_cvv.getText()).toString().trim();
}
return getValue;
}
}
| UTF-8 | Java | 3,125 | java | CCSecureCodeFragment.java | Java | []
| null | []
| package com.a7552_2c_2018.melliapp.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import com.a7552_2c_2018.melliapp.R;
import com.a7552_2c_2018.melliapp.activity.CheckOutActivity;
import com.a7552_2c_2018.melliapp.model.ActualBuy;
import com.a7552_2c_2018.melliapp.singletons.SingletonUser;
import com.a7552_2c_2018.melliapp.utils.CreditCardEditText;
import java.util.Objects;
import butterknife.BindView;
import butterknife.ButterKnife;
import static android.content.ContentValues.TAG;
/**
* A simple {@link Fragment} subclass.
*/
public class CCSecureCodeFragment extends Fragment {
@BindView(R.id.et_cvv)
CreditCardEditText et_cvv;
private TextView tv_cvv;
private CheckOutActivity activity;
public CCSecureCodeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_ccsecure_code, container, false);
ButterKnife.bind(this, view);
activity = (CheckOutActivity) getActivity();
et_cvv.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (tv_cvv != null) {
if (TextUtils.isEmpty(editable.toString().trim()))
tv_cvv.setText(getString(R.string.card_cvv_sample));
else
tv_cvv.setText(editable.toString());
} else
Log.d(TAG, "afterTextChanged: cvv null");
}
});
et_cvv.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
if(activity!=null)
{
activity.nextClick();
return true;
}
}
return false;
});
et_cvv.setOnBackButtonListener(() -> {
if(activity!=null)
activity.onBackPressed();
});
return view;
}
public void setCvv(TextView tv) {
tv_cvv = tv;
}
public String getValue() {
String getValue = "";
if (et_cvv != null) {
getValue = Objects.requireNonNull(et_cvv.getText()).toString().trim();
}
return getValue;
}
}
| 3,125 | 0.6144 | 0.59552 | 121 | 24.826447 | 24.153667 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.471074 | false | false | 3 |
4c92b08dea051a3b5619b98f136a5d8f3cdb1d06 | 4,475,355,925,324 | f4e7664d21a4c89d3f4fae7258d5a75f3ceeefec | /src/paczka/CleanTemp.java | 2d15ffbebecb0aba5bb3eb26716acc751e9770e0 | []
| no_license | simsonek/tipp | https://github.com/simsonek/tipp | dcb901c687e1b20c8c8ecf34cdfe9a6753aa8a49 | e987df613656431023e1ef5b347c594cfbd4b599 | refs/heads/master | 2016-07-30T22:05:33.163000 | 2014-08-11T17:15:10 | 2014-08-11T17:15:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package paczka;
import java.io.File;
public class CleanTemp {
public void Run(String filePath){
//FileUtils.deleteDirectory(new File("directory"));
File plik = new File(filePath);
if(plik.isDirectory()){
File[] pliki = plik.listFiles();
for(File file : pliki){
Run(file.getAbsolutePath());
}
plik.delete();
}
else{
plik.delete();
}
}
}
| UTF-8 | Java | 375 | java | CleanTemp.java | Java | []
| null | []
| package paczka;
import java.io.File;
public class CleanTemp {
public void Run(String filePath){
//FileUtils.deleteDirectory(new File("directory"));
File plik = new File(filePath);
if(plik.isDirectory()){
File[] pliki = plik.listFiles();
for(File file : pliki){
Run(file.getAbsolutePath());
}
plik.delete();
}
else{
plik.delete();
}
}
}
| 375 | 0.64 | 0.64 | 24 | 14.625 | 14.913116 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.708333 | false | false | 3 |
eeb00f49e9dbfc7c4d6887d018af50e42262ab34 | 14,637,248,610,259 | dcfc7a4bb293fb1ef9e9700585b741ea7b673bd4 | /TrabajoPW/src/main/java/pe/edu/upc/entity/Rent.java | 69ac83d2f1ca9f88a56ebd124397e2373cbec393 | []
| no_license | RonalManuel/TrabajoPW | https://github.com/RonalManuel/TrabajoPW | 7cdbc2d1b2376b15bc0c4e94f1b2cc7642e86709 | 0eef6a264a2a5082a50bb49c735a40bdab965e83 | refs/heads/master | 2022-11-13T09:37:28.387000 | 2020-06-30T10:47:49 | 2020-06-30T10:47:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pe.edu.upc.entity;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name = "rents")
public class Rent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long idRent;
@Column(name = "requestDate")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.TIMESTAMP)
private Date requestDate;// cuando se pidio
@NotNull(message = "La fecha es obligatoria")
@Future(message = "La fecha debe estar en el futuro")
@Column(name = "startDate")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.TIMESTAMP)
private Date startDate;
@NotNull(message = "La fecha es obligatoria")
@Future(message = "La fecha debe estar en el futuro")
@Column(name = "endDate")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.TIMESTAMP)
private Date endDate;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "idRent", nullable = true)
private List<RentDetails> rentDetails;
@ManyToOne
@JoinColumn(name = "id")
private User user;
@PrePersist
public void prePersist() {
this.requestDate = new Date();
}
public Double getTotal() {
return rentDetails.stream().collect(Collectors.summingDouble(RentDetails::calcularSubTotal));
}
public void addDetailRentation(RentDetails item) {
this.rentDetails.add(item);
}
public long getIdRent() {
return idRent;
}
public void setIdRent(long idRent) {
this.idRent = idRent;
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
public List<RentDetails> getRentDetails() {
return rentDetails;
}
public void setRentDetails(List<RentDetails> RentDetails) {
this.rentDetails = RentDetails;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}
| UTF-8 | Java | 2,932 | java | Rent.java | Java | []
| null | []
| package pe.edu.upc.entity;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name = "rents")
public class Rent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long idRent;
@Column(name = "requestDate")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.TIMESTAMP)
private Date requestDate;// cuando se pidio
@NotNull(message = "La fecha es obligatoria")
@Future(message = "La fecha debe estar en el futuro")
@Column(name = "startDate")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.TIMESTAMP)
private Date startDate;
@NotNull(message = "La fecha es obligatoria")
@Future(message = "La fecha debe estar en el futuro")
@Column(name = "endDate")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.TIMESTAMP)
private Date endDate;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "idRent", nullable = true)
private List<RentDetails> rentDetails;
@ManyToOne
@JoinColumn(name = "id")
private User user;
@PrePersist
public void prePersist() {
this.requestDate = new Date();
}
public Double getTotal() {
return rentDetails.stream().collect(Collectors.summingDouble(RentDetails::calcularSubTotal));
}
public void addDetailRentation(RentDetails item) {
this.rentDetails.add(item);
}
public long getIdRent() {
return idRent;
}
public void setIdRent(long idRent) {
this.idRent = idRent;
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
public List<RentDetails> getRentDetails() {
return rentDetails;
}
public void setRentDetails(List<RentDetails> RentDetails) {
this.rentDetails = RentDetails;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}
| 2,932 | 0.722715 | 0.722715 | 124 | 21.645161 | 18.997536 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.096774 | false | false | 3 |
3d2048b6dceb2ef4fc3534a022369dfc39172244 | 15,745,350,174,613 | 7758a313719d8632480b294c138d9ce9d68e2cbd | /dont-wreck-my-house/src/main/java/learn/dontwreck/data/ReservationFileRepository.java | 7c6021096ba752aea191ba6640862f9c78d3dfa3 | []
| no_license | isaaceriya/dont-wreck-my-house-updated | https://github.com/isaaceriya/dont-wreck-my-house-updated | ce91bc1455434f12b891c1811e267f9ceab0a54e | a22e374c0dd0c143c8ab48c764075701cb71e27e | refs/heads/main | 2023-07-06T12:01:40.083000 | 2021-08-13T14:27:30 | 2021-08-13T14:27:30 | 395,681,774 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package learn.dontwreck.data;
import learn.dontwreck.models.Guest;
import learn.dontwreck.models.Host;
import learn.dontwreck.models.Reservation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Repository
public class ReservationFileRepository implements ReservationRepository{
private static final String HEADER = "id,start_date,end_date,guest_id,total";
private final String filePath;
public ReservationFileRepository (@Value("${reservationFilePath}") String filePath) { this.filePath = filePath; }
private String getFilePath(String hostId) {
return Paths.get(filePath, hostId + ".csv").toString();
}
public List<Reservation> findByHost(String hostId) {
ArrayList<Reservation> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(getFilePath(hostId)))) {
reader.readLine(); // read header
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
String[] fields = line.split(",", -1);
if (fields.length == 5) {
result.add(deserialize(fields, hostId));
}
}
} catch (IOException ex) {
// don't throw on read
}
return result;
}
/*public Reservation findByGuest(String hostId, int guest_id) {
return findByHost(hostId).stream()
.filter(i -> i.getId() == (guest_id))
.findFirst()
.orElse(null);
}*/
public Reservation add(Reservation reservation) throws DataAccessException {
List<Reservation> all = findByHost(reservation.getHost().getId());
int nextId = 0;
for (Reservation r : all) {
nextId = Math.max(nextId, r.getId());
}
reservation.setId(nextId + 1);
all.add(reservation);
writeAll(all, reservation.getHost().getId());
return reservation;
}
public boolean update(Reservation reservation) throws DataAccessException {
List<Reservation> all = findByHost(reservation.getHost().getId());
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getId() == reservation.getId()) {
all.set(i, reservation);
writeAll(all, reservation.getHost().getId());
return true;
}
}
return false;
}
public boolean deleteByReservation(String hostId, int id) throws DataAccessException {
List<Reservation> all = findByHost(hostId);
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getId() == id) {
all.remove(i);
writeAll(all, hostId);
return true;
}
}
return false;
}
private Reservation deserialize(String[] fields, String hostId) {
Reservation result = new Reservation();
result.setId(Integer.parseInt(fields[0]));
result.setStart_date(LocalDate.parse(fields[1]));
result.setEnd_date(LocalDate.parse(fields[2]));
Guest guest = new Guest();
guest.setGuest_id(Integer.parseInt(fields[3]));
result.setGuest(guest);
result.setTotal(new BigDecimal(fields[4]));
Host host = new Host();
host.setId(hostId);
result.setHost(host);
return result;
}
private String serialize(Reservation reservation) {
return String.format("%s,%s,%s,%s,%s",
reservation.getId(),
reservation.getStart_date(),
reservation.getEnd_date(),
reservation.getGuest().getGuest_id(),
reservation.getTotal());
}
// id,start_date,end_date,guest_id,total"
protected void writeAll(List<Reservation> reservations, String hostId) throws DataAccessException {
try (PrintWriter writer = new PrintWriter(getFilePath(hostId))) {
writer.println(HEADER);
if (reservations == null) {
return;
}
for (Reservation reservation : reservations) {
writer.println(serialize(reservation));
}
} catch (FileNotFoundException ex) {
throw new DataAccessException(ex);
}
}
}
| UTF-8 | Java | 4,513 | java | ReservationFileRepository.java | Java | []
| null | []
| package learn.dontwreck.data;
import learn.dontwreck.models.Guest;
import learn.dontwreck.models.Host;
import learn.dontwreck.models.Reservation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Repository
public class ReservationFileRepository implements ReservationRepository{
private static final String HEADER = "id,start_date,end_date,guest_id,total";
private final String filePath;
public ReservationFileRepository (@Value("${reservationFilePath}") String filePath) { this.filePath = filePath; }
private String getFilePath(String hostId) {
return Paths.get(filePath, hostId + ".csv").toString();
}
public List<Reservation> findByHost(String hostId) {
ArrayList<Reservation> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(getFilePath(hostId)))) {
reader.readLine(); // read header
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
String[] fields = line.split(",", -1);
if (fields.length == 5) {
result.add(deserialize(fields, hostId));
}
}
} catch (IOException ex) {
// don't throw on read
}
return result;
}
/*public Reservation findByGuest(String hostId, int guest_id) {
return findByHost(hostId).stream()
.filter(i -> i.getId() == (guest_id))
.findFirst()
.orElse(null);
}*/
public Reservation add(Reservation reservation) throws DataAccessException {
List<Reservation> all = findByHost(reservation.getHost().getId());
int nextId = 0;
for (Reservation r : all) {
nextId = Math.max(nextId, r.getId());
}
reservation.setId(nextId + 1);
all.add(reservation);
writeAll(all, reservation.getHost().getId());
return reservation;
}
public boolean update(Reservation reservation) throws DataAccessException {
List<Reservation> all = findByHost(reservation.getHost().getId());
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getId() == reservation.getId()) {
all.set(i, reservation);
writeAll(all, reservation.getHost().getId());
return true;
}
}
return false;
}
public boolean deleteByReservation(String hostId, int id) throws DataAccessException {
List<Reservation> all = findByHost(hostId);
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getId() == id) {
all.remove(i);
writeAll(all, hostId);
return true;
}
}
return false;
}
private Reservation deserialize(String[] fields, String hostId) {
Reservation result = new Reservation();
result.setId(Integer.parseInt(fields[0]));
result.setStart_date(LocalDate.parse(fields[1]));
result.setEnd_date(LocalDate.parse(fields[2]));
Guest guest = new Guest();
guest.setGuest_id(Integer.parseInt(fields[3]));
result.setGuest(guest);
result.setTotal(new BigDecimal(fields[4]));
Host host = new Host();
host.setId(hostId);
result.setHost(host);
return result;
}
private String serialize(Reservation reservation) {
return String.format("%s,%s,%s,%s,%s",
reservation.getId(),
reservation.getStart_date(),
reservation.getEnd_date(),
reservation.getGuest().getGuest_id(),
reservation.getTotal());
}
// id,start_date,end_date,guest_id,total"
protected void writeAll(List<Reservation> reservations, String hostId) throws DataAccessException {
try (PrintWriter writer = new PrintWriter(getFilePath(hostId))) {
writer.println(HEADER);
if (reservations == null) {
return;
}
for (Reservation reservation : reservations) {
writer.println(serialize(reservation));
}
} catch (FileNotFoundException ex) {
throw new DataAccessException(ex);
}
}
}
| 4,513 | 0.594948 | 0.592511 | 148 | 29.493244 | 26.616774 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.621622 | false | false | 3 |
df73887258b65fcdb21f894d84d5a40fa6625ea6 | 1,099,511,647,234 | 129839e3017392a2eeee8c37e8cf7224e1427910 | /src/Bishop.java | 18888c16e5676e653065eeda07211bb4ffbaa655 | []
| no_license | MuirDH/ChessGame | https://github.com/MuirDH/ChessGame | 53c1c75a21bcd127e79482fbe04a8bf7b0cb4e7b | e4bf14b86fe854332b5b6169d8df8eead9abe6b9 | refs/heads/master | 2021-01-20T01:30:41.606000 | 2017-08-24T12:31:43 | 2017-08-24T12:31:43 | 101,292,783 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// child class, parent class is Piece
public class Bishop extends Piece{
public Bishop() {
super();
this.name = "bishop";
}
@Override
boolean isValidMove(Position newPosition) {
// First check the parent's isValidMove test, then move on to the Bishop's movement rules test.
// A Bishop can only move diagonally, so check that the number of vertical steps is equal to the number of
// horizontal steps. That is, the difference between the current and new column positions is the same as the
// difference between the current and new row positions.
return super.isValidMove(newPosition) && Math.abs(newPosition.column - this.position.column)
== Math.abs(newPosition.row - this.position.row);
}
}
| UTF-8 | Java | 789 | java | Bishop.java | Java | [
{
"context": " Bishop() {\n super();\n this.name = \"bishop\";\n }\n\n @Override\n boolean isValidMove(Po",
"end": 141,
"score": 0.989709198474884,
"start": 135,
"tag": "NAME",
"value": "bishop"
}
]
| null | []
|
// child class, parent class is Piece
public class Bishop extends Piece{
public Bishop() {
super();
this.name = "bishop";
}
@Override
boolean isValidMove(Position newPosition) {
// First check the parent's isValidMove test, then move on to the Bishop's movement rules test.
// A Bishop can only move diagonally, so check that the number of vertical steps is equal to the number of
// horizontal steps. That is, the difference between the current and new column positions is the same as the
// difference between the current and new row positions.
return super.isValidMove(newPosition) && Math.abs(newPosition.column - this.position.column)
== Math.abs(newPosition.row - this.position.row);
}
}
| 789 | 0.674271 | 0.674271 | 18 | 42.777779 | 40.093716 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 3 |
ae6c37d2e9c7acfe5ca61f661b7e5b925da6bdf0 | 22,136,261,512,625 | 71dd5a62896d88ef3d1a8b383d6964408d7d239f | /javastudy/part16-interface/src/com/koreait/ex2/TV.java | 91c4e480259f5bef0a1020d64d06d3a146649934 | []
| no_license | hwangseokjin94/java_web_0224 | https://github.com/hwangseokjin94/java_web_0224 | 42df3f57b3b50598e2ca8b12d27e20a284670ca7 | 6c9ab05ac743763db8264c42c814b79cada95458 | refs/heads/master | 2022-11-13T08:23:36.271000 | 2020-07-02T08:26:19 | 2020-07-02T08:26:19 | 250,546,467 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.koreait.ex2;
public class TV implements Product {
@Override
public void info() {
System.out.println("TV정보");
}
}
| UTF-8 | Java | 142 | java | TV.java | Java | []
| null | []
| package com.koreait.ex2;
public class TV implements Product {
@Override
public void info() {
System.out.println("TV정보");
}
}
| 142 | 0.666667 | 0.65942 | 14 | 8.857142 | 12.426108 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 3 |
d7485b21a9be4244838ccd9ae164df9a51403ccb | 3,186,865,775,774 | 2015eb8f016270456f201ae67f2e1d4c0dc83451 | /src/test/java/com/vortex/MergeSortTest.java | 99be0a9882c268c96397be4475cc951b4a35cb3f | []
| no_license | OleksandrMatiash/algorithms | https://github.com/OleksandrMatiash/algorithms | ba61097284655a802deacc6010ad6331e5d5d3f4 | 99086f7adb305d298f6f5f005887f79419d16c0b | refs/heads/master | 2021-07-08T04:12:22.776000 | 2019-06-19T10:37:27 | 2019-06-19T10:37:27 | 192,711,303 | 0 | 0 | null | false | 2020-10-13T14:01:15 | 2019-06-19T10:31:13 | 2019-06-19T10:37:38 | 2020-10-13T14:01:14 | 37 | 0 | 0 | 1 | Java | false | false | package com.vortex;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
public class MergeSortTest {
@Test
public void sort() {
for (int j = 0; j < 10000; j++) {
Random rng = new Random(System.currentTimeMillis());
int numOfElements = rng.nextInt(10);
int[] toSort = new int[numOfElements];
for (int i = 0; i < numOfElements; i++) {
toSort[i] = rng.nextInt(10) - 5;
}
int[] expectedSorted = Arrays.stream(toSort).sorted().toArray();
MergeSort.sort(toSort);
Assert.assertArrayEquals(expectedSorted, toSort);
}
}
} | UTF-8 | Java | 805 | java | MergeSortTest.java | Java | []
| null | []
| package com.vortex;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
public class MergeSortTest {
@Test
public void sort() {
for (int j = 0; j < 10000; j++) {
Random rng = new Random(System.currentTimeMillis());
int numOfElements = rng.nextInt(10);
int[] toSort = new int[numOfElements];
for (int i = 0; i < numOfElements; i++) {
toSort[i] = rng.nextInt(10) - 5;
}
int[] expectedSorted = Arrays.stream(toSort).sorted().toArray();
MergeSort.sort(toSort);
Assert.assertArrayEquals(expectedSorted, toSort);
}
}
} | 805 | 0.598758 | 0.583851 | 31 | 25 | 21.616899 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.645161 | false | false | 3 |
67e3e480e77fde9fe066d7438286e6fb13921882 | 3,186,865,773,697 | a437746afe3163a8392f06188e48c41822a3fbfb | /support/ok/okhttp/src/main/java/sparkles/support/okhttp/LoggingInterceptor.java | 182729650c1fd7f5e9dbca4850c3f8a47040838b | [
"MIT"
]
| permissive | sparkles-dev/sparkles | https://github.com/sparkles-dev/sparkles | e659826eeb5311c531c12e28f00ffd8a2a4589d1 | 5bc6b7fe922cfb4548404f8e6834151a88f560bd | refs/heads/master | 2023-08-31T20:32:53.714000 | 2019-12-16T15:40:06 | 2019-12-16T15:40:06 | 127,345,659 | 1 | 0 | MIT | false | 2023-05-28T08:45:17 | 2018-03-29T20:45:57 | 2020-03-06T14:54:18 | 2023-05-28T08:45:14 | 2,563 | 2 | 0 | 37 | Java | false | false | package sparkles.support.okhttp;
import org.slf4j.Logger;
import okhttp3.logging.HttpLoggingInterceptor;
public final class LoggingInterceptor {
public static HttpLoggingInterceptor slf4j(Logger logger) {
return create(logger::info);
}
public static HttpLoggingInterceptor create(HttpLoggingInterceptor.Logger logger) {
return create(logger, HttpLoggingInterceptor.Level.BASIC);
}
public static HttpLoggingInterceptor create(HttpLoggingInterceptor.Logger logger, HttpLoggingInterceptor.Level level) {
return new HttpLoggingInterceptor(logger).setLevel(level);
}
}
| UTF-8 | Java | 594 | java | LoggingInterceptor.java | Java | []
| null | []
| package sparkles.support.okhttp;
import org.slf4j.Logger;
import okhttp3.logging.HttpLoggingInterceptor;
public final class LoggingInterceptor {
public static HttpLoggingInterceptor slf4j(Logger logger) {
return create(logger::info);
}
public static HttpLoggingInterceptor create(HttpLoggingInterceptor.Logger logger) {
return create(logger, HttpLoggingInterceptor.Level.BASIC);
}
public static HttpLoggingInterceptor create(HttpLoggingInterceptor.Logger logger, HttpLoggingInterceptor.Level level) {
return new HttpLoggingInterceptor(logger).setLevel(level);
}
}
| 594 | 0.80303 | 0.79798 | 20 | 28.700001 | 33.978081 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 3 |
12ef3bf06e59a4510a9b442fce269db4768e0422 | 24,438,363,985,228 | 5fbc6b2215f25b0b725ad4e0f793eedf81322030 | /train-booking-service/src/main/java/com/train/bookingservice/repository/PaymentInformationRepository.java | e4f377ccf6546dde41850f2dab78bd833ff19ea9 | []
| no_license | anils15/TicketBooking | https://github.com/anils15/TicketBooking | 07c193851b5dee3b908b6ce4851a742419172d7a | da7bf8da2be1cf77dcf5b50f02fd63a8820c8c9c | refs/heads/main | 2023-08-27T14:02:39.018000 | 2021-11-05T12:12:23 | 2021-11-05T12:12:23 | 344,490,088 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.train.bookingservice.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.train.bookingservice.entity.PaymentInformation;
@Repository
public interface PaymentInformationRepository extends JpaRepository <PaymentInformation, String>{
}
| UTF-8 | Java | 331 | java | PaymentInformationRepository.java | Java | []
| null | []
| package com.train.bookingservice.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.train.bookingservice.entity.PaymentInformation;
@Repository
public interface PaymentInformationRepository extends JpaRepository <PaymentInformation, String>{
}
| 331 | 0.864048 | 0.864048 | 10 | 32.099998 | 32.632652 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
94dd32e6c94f39e8b03260cd2082ae96194e6816 | 24,446,953,850,437 | b251171516581875765f52ae82a3d571bf58ebe5 | /src/main/java/problems/google/odd_man_out.java | 1e7f4913c4e81758c8ec8822cfddfdc8f4d70edd | []
| no_license | brrcat/DefensiveCoding | https://github.com/brrcat/DefensiveCoding | 21605f2d280b490dbebdf75c9ab9d37da595ec8f | 797f33e281af463869ffb21c42c7a3acc6ae82e5 | refs/heads/master | 2016-08-08T16:17:19.089000 | 2014-11-15T02:07:55 | 2014-11-15T02:07:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package problems.google;
import java.util.HashSet;
/**
* Class: odd_man_out
* Date: 5/22/13
* Author: Kelvin Lai
*
* Find integer where every integer appears exactly twice except one integer which appears only once.
* takes O(n) time and O(n) space
*/
public class odd_man_out {
public int oddManOut(int [] array) {
HashSet<Integer> s = new HashSet<Integer>();
int sum = 0;
for (int i=0; i < array.length; i++) {
if (s.contains(array[i])) {
sum = sum - array[i];
}
else {
s.add(array[i]);
sum = sum + array[i];
}
}
return sum;
}
//take O(n) time and O(1) space
public int oddManOut_xor(int [] array) {
int val = 0;
for (int i = 0; i < array.length; i++) {
val ^= array[i]; //xor is commutative and is own inverse, integer that appears twice will cancel itself
// out
}
return val;
}
}
| UTF-8 | Java | 993 | java | odd_man_out.java | Java | [
{
"context": "\n * Class: odd_man_out\n * Date: 5/22/13\n * Author: Kelvin Lai\n *\n * Find integer where every integer appears ex",
"end": 117,
"score": 0.9998669624328613,
"start": 107,
"tag": "NAME",
"value": "Kelvin Lai"
}
]
| null | []
| package problems.google;
import java.util.HashSet;
/**
* Class: odd_man_out
* Date: 5/22/13
* Author: <NAME>
*
* Find integer where every integer appears exactly twice except one integer which appears only once.
* takes O(n) time and O(n) space
*/
public class odd_man_out {
public int oddManOut(int [] array) {
HashSet<Integer> s = new HashSet<Integer>();
int sum = 0;
for (int i=0; i < array.length; i++) {
if (s.contains(array[i])) {
sum = sum - array[i];
}
else {
s.add(array[i]);
sum = sum + array[i];
}
}
return sum;
}
//take O(n) time and O(1) space
public int oddManOut_xor(int [] array) {
int val = 0;
for (int i = 0; i < array.length; i++) {
val ^= array[i]; //xor is commutative and is own inverse, integer that appears twice will cancel itself
// out
}
return val;
}
}
| 989 | 0.52568 | 0.515609 | 39 | 24.461538 | 24.515663 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.410256 | false | false | 3 |
a845003cf62143c26b4295f9b1651e984fdfb181 | 25,168,508,365,443 | 964b858f099b40572f4879c02edbb6b85ca76053 | /Example/nrf-mesh/app/src/main/java/no/nordicsemi/android/nrfmeshprovisioner/NetworkFragment.java | 00cbc12870aed3c16df86c47171b972fa29ce7cf | [
"BSD-3-Clause",
"BSD-2-Clause"
]
| permissive | insoonior/Android-nRF-Mesh-Library | https://github.com/insoonior/Android-nRF-Mesh-Library | c1b1db07657df2ea7b6f939f38d8dbbe000d46ca | 198a4a7554c3d2c15b0a92983d1a9aa6b254ee89 | refs/heads/master | 2020-04-07T07:50:31.898000 | 2018-09-27T08:03:54 | 2018-09-27T08:03:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2018, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 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 no.nordicsemi.android.nrfmeshprovisioner;
import android.arch.lifecycle.ViewModelProvider;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import javax.inject.Inject;
import no.nordicsemi.android.meshprovisioner.configuration.ProvisionedMeshNode;
import no.nordicsemi.android.nrfmeshprovisioner.adapter.NodeAdapter;
import no.nordicsemi.android.nrfmeshprovisioner.di.Injectable;
import no.nordicsemi.android.nrfmeshprovisioner.utils.Utils;
import no.nordicsemi.android.nrfmeshprovisioner.viewmodels.SharedViewModel;
public class NetworkFragment extends Fragment implements Injectable,
NodeAdapter.OnItemClickListener {
SharedViewModel mViewModel;
@Inject
ViewModelProvider.Factory mViewModelFactory;
private NodeAdapter mAdapter;
public interface NetworkFragmentListener {
void onProvisionedMeshNodeSelected();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_network, null);
// Configure the recycler view
final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view_provisioned_nodes);
final View noNetworksConfiguredView = rootView.findViewById(R.id.no_networks_configured);
mViewModel = ViewModelProviders.of(getActivity(), mViewModelFactory).get(SharedViewModel.class);
boolean isTablet = getResources().getBoolean(R.bool.isTablet);
if(isTablet){
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2)); //If its a tablet we use a grid layout with 2 columns
} else {
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
mAdapter = new NodeAdapter(getActivity(), mViewModel.getMeshRepository().getProvisionedNodesLiveData());
mAdapter.setOnItemClickListener(this);
recyclerView.setAdapter(mAdapter);
// Create view model containing utility methods for scanning
mViewModel.getMeshRepository().getProvisionedNodesLiveData().observe(this, provisionedNodesLiveData -> {
if(mAdapter.getItemCount() > 0) {
noNetworksConfiguredView.setVisibility(View.GONE);
} else {
noNetworksConfiguredView.setVisibility(View.VISIBLE);
}
mAdapter.notifyDataSetChanged();
});
return rootView;
}
@Override
public void onStart() {
super.onStart();
mViewModel.refreshProvisionedNodes();
}
@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
if(!mViewModel.getProvisionedNodesLiveData().getProvisionedNodes().isEmpty()){
if (!mViewModel.isConenctedToMesh()) {
inflater.inflate(R.menu.connect, menu);
} else {
inflater.inflate(R.menu.disconnect, menu);
}
}
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
final int id = item.getItemId();
switch (id) {
case R.id.action_connect:
final Intent scannerActivity = new Intent(getContext(), ProvisionedNodesScannerActivity.class);
scannerActivity.putExtra(ProvisionedNodesScannerActivity.NETWORK_ID, mViewModel.getNetworkId());
startActivity(scannerActivity);
return true;
case R.id.action_disconnect:
mViewModel.disconnect();
return true;
}
return false;
}
@Override
public void onConfigureClicked(final ProvisionedMeshNode node) {
if(mViewModel.isConenctedToMesh()) {
((NetworkFragmentListener) getActivity()).onProvisionedMeshNodeSelected();
final Intent meshConfigurationIntent = new Intent(getActivity(), NodeConfigurationActivity.class);
meshConfigurationIntent.putExtra(Utils.EXTRA_DEVICE, node);
getActivity().startActivity(meshConfigurationIntent);
} else {
Toast.makeText(getActivity(), R.string.disconnected_network_rationale, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDetailsClicked(final ProvisionedMeshNode node) {
final Intent meshConfigurationIntent = new Intent(getActivity(), NodeDetailsActivity.class);
meshConfigurationIntent.putExtra(Utils.EXTRA_DEVICE, node);
getActivity().startActivity(meshConfigurationIntent);
}
}
| UTF-8 | Java | 6,861 | java | NetworkFragment.java | Java | []
| null | []
| /*
* Copyright (c) 2018, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 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 no.nordicsemi.android.nrfmeshprovisioner;
import android.arch.lifecycle.ViewModelProvider;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import javax.inject.Inject;
import no.nordicsemi.android.meshprovisioner.configuration.ProvisionedMeshNode;
import no.nordicsemi.android.nrfmeshprovisioner.adapter.NodeAdapter;
import no.nordicsemi.android.nrfmeshprovisioner.di.Injectable;
import no.nordicsemi.android.nrfmeshprovisioner.utils.Utils;
import no.nordicsemi.android.nrfmeshprovisioner.viewmodels.SharedViewModel;
public class NetworkFragment extends Fragment implements Injectable,
NodeAdapter.OnItemClickListener {
SharedViewModel mViewModel;
@Inject
ViewModelProvider.Factory mViewModelFactory;
private NodeAdapter mAdapter;
public interface NetworkFragmentListener {
void onProvisionedMeshNodeSelected();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_network, null);
// Configure the recycler view
final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view_provisioned_nodes);
final View noNetworksConfiguredView = rootView.findViewById(R.id.no_networks_configured);
mViewModel = ViewModelProviders.of(getActivity(), mViewModelFactory).get(SharedViewModel.class);
boolean isTablet = getResources().getBoolean(R.bool.isTablet);
if(isTablet){
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2)); //If its a tablet we use a grid layout with 2 columns
} else {
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
mAdapter = new NodeAdapter(getActivity(), mViewModel.getMeshRepository().getProvisionedNodesLiveData());
mAdapter.setOnItemClickListener(this);
recyclerView.setAdapter(mAdapter);
// Create view model containing utility methods for scanning
mViewModel.getMeshRepository().getProvisionedNodesLiveData().observe(this, provisionedNodesLiveData -> {
if(mAdapter.getItemCount() > 0) {
noNetworksConfiguredView.setVisibility(View.GONE);
} else {
noNetworksConfiguredView.setVisibility(View.VISIBLE);
}
mAdapter.notifyDataSetChanged();
});
return rootView;
}
@Override
public void onStart() {
super.onStart();
mViewModel.refreshProvisionedNodes();
}
@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
if(!mViewModel.getProvisionedNodesLiveData().getProvisionedNodes().isEmpty()){
if (!mViewModel.isConenctedToMesh()) {
inflater.inflate(R.menu.connect, menu);
} else {
inflater.inflate(R.menu.disconnect, menu);
}
}
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
final int id = item.getItemId();
switch (id) {
case R.id.action_connect:
final Intent scannerActivity = new Intent(getContext(), ProvisionedNodesScannerActivity.class);
scannerActivity.putExtra(ProvisionedNodesScannerActivity.NETWORK_ID, mViewModel.getNetworkId());
startActivity(scannerActivity);
return true;
case R.id.action_disconnect:
mViewModel.disconnect();
return true;
}
return false;
}
@Override
public void onConfigureClicked(final ProvisionedMeshNode node) {
if(mViewModel.isConenctedToMesh()) {
((NetworkFragmentListener) getActivity()).onProvisionedMeshNodeSelected();
final Intent meshConfigurationIntent = new Intent(getActivity(), NodeConfigurationActivity.class);
meshConfigurationIntent.putExtra(Utils.EXTRA_DEVICE, node);
getActivity().startActivity(meshConfigurationIntent);
} else {
Toast.makeText(getActivity(), R.string.disconnected_network_rationale, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDetailsClicked(final ProvisionedMeshNode node) {
final Intent meshConfigurationIntent = new Intent(getActivity(), NodeDetailsActivity.class);
meshConfigurationIntent.putExtra(Utils.EXTRA_DEVICE, node);
getActivity().startActivity(meshConfigurationIntent);
}
}
| 6,861 | 0.728174 | 0.726133 | 159 | 42.150944 | 40.353344 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672956 | false | false | 3 |
91f8be8d6d870c3d101db46afb10e7d92a28b8d1 | 11,931,419,155,517 | 1ff30c370ddbedcd069826177b7957fde7152383 | /ehwork/src/main/java/com/ehwork/dao/impl/ShippingMethodDaoImpl.java | 61c825af63f11a1e6d82425d158b0e3d0b9a8ed3 | []
| no_license | alfredsu123/ehwork | https://github.com/alfredsu123/ehwork | 3d61c8ceaf769d10b887120a7d4d5372db6e8dd1 | bc110285b223aad9e750af1859769509a2d0b105 | refs/heads/master | 2016-08-04T22:41:36.123000 | 2014-06-01T07:20:06 | 2014-06-01T07:20:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2005-2013 ehwork.com. All rights reserved.
* Support: http://www.ehwork.com
* License: http://www.ehwork.com/license
*/
package com.ehwork.dao.impl;
import com.ehwork.dao.ShippingMethodDao;
import com.ehwork.entity.ShippingMethod;
import org.springframework.stereotype.Repository;
/**
* Dao - 配送方式
*
* @author ehwork Team
* @version 3.0
*/
@Repository("shippingMethodDaoImpl")
public class ShippingMethodDaoImpl extends BaseDaoImpl<ShippingMethod, Long> implements ShippingMethodDao {
} | UTF-8 | Java | 523 | java | ShippingMethodDaoImpl.java | Java | []
| null | []
| /*
* Copyright 2005-2013 ehwork.com. All rights reserved.
* Support: http://www.ehwork.com
* License: http://www.ehwork.com/license
*/
package com.ehwork.dao.impl;
import com.ehwork.dao.ShippingMethodDao;
import com.ehwork.entity.ShippingMethod;
import org.springframework.stereotype.Repository;
/**
* Dao - 配送方式
*
* @author ehwork Team
* @version 3.0
*/
@Repository("shippingMethodDaoImpl")
public class ShippingMethodDaoImpl extends BaseDaoImpl<ShippingMethod, Long> implements ShippingMethodDao {
} | 523 | 0.759223 | 0.739806 | 22 | 22.454546 | 25.894413 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.227273 | false | false | 3 |
492e30fe65d181ce6d6403d615ae4573994ea183 | 3,977,139,727,770 | 1607b379816531e192393f576ade70cfe3d90bb7 | /src/main/java/com/coastcapitalsavings/mvc/repositories/RequestRepository.java | 8b48c4b1cabae28b075fa19ef73696931f51f80d | []
| no_license | UBC-CPSC319/team-6 | https://github.com/UBC-CPSC319/team-6 | 29a04a75a7f9097dc634045700037eb143c38ce2 | 61596d348e75dc4d2d22f918cd79c09237dde89b | refs/heads/master | 2017-12-13T17:10:58.868000 | 2017-04-20T06:35:40 | 2017-04-20T06:35:40 | 78,295,826 | 1 | 0 | null | false | 2017-04-20T05:55:28 | 2017-01-07T18:22:10 | 2017-03-10T06:20:26 | 2017-04-20T05:55:28 | 14,245 | 1 | 0 | 2 | Java | null | null | package com.coastcapitalsavings.mvc.repositories;
import com.coastcapitalsavings.util.RequestStatusCodes;
import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import com.coastcapitalsavings.mvc.models.Request;
import com.coastcapitalsavings.mvc.models.RequestStatus;
import com.coastcapitalsavings.mvc.repositories.extractor.RequestWithProductsExtractor;
import com.coastcapitalsavings.mvc.repositories.mapper.RequestSummaryMapper;
import com.coastcapitalsavings.mvc.repositories.mapper.RequestStatusMapper;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.dao.TypeMismatchDataAccessException;
import org.springframework.jdbc.object.StoredProcedure;
import org.springframework.jdbc.core.*;
import java.sql.Date;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Database access object for the requests endpoint
*/
@Repository
public class RequestRepository {
JdbcTemplate jdbcTemplate;
// Store stored procedures so that they don't have to be recompiled for every use;
GetRequestByIdStoredProc getRequestByIdStoredProc;
PostNewRequestStoredProc postNewRequestStoredProc;
PutRequestUpdateStatusStoredProc putRequestUpdateStatusStoredProc;
CheckRequestExistsStoredProc checkRequestExistsStoredProc;
GetRequestsBetweenDateRangeStoredProc getRequestBetweenDateRangeStoredProc;
PutApproverRequestStatusStoredProc putApproverRequestStatusStoredProc;
PutRequestProductStatusCodeStoredProc putRequestProductStatusCodeStoredProc;
GetUserRequestBetweenDateRangeStoredProc getUserRequestBetweenDateRangeStoredProc;
GetFullRequestBetweenDateRangeCostCenterStoredProc getFullRequestBetweenDateRangeCostCenterStoredProc;
GetRequestsByStatusCodeAndApproverStoredProc getRequestsByStatusCodeAndApproverStoredProc;
GetPendingRequestsByApproverStoredProc getPendingRequestsByApproverStoredProc;
@Autowired
/*
Tricky: Need to do this instead of autowiring the Jdbc template so that we can ensure that the
template is up before the stored procedures are initialized.
*/
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
getRequestByIdStoredProc = new GetRequestByIdStoredProc();
postNewRequestStoredProc = new PostNewRequestStoredProc();
putRequestUpdateStatusStoredProc = new PutRequestUpdateStatusStoredProc();
checkRequestExistsStoredProc = new CheckRequestExistsStoredProc();
getRequestBetweenDateRangeStoredProc = new GetRequestsBetweenDateRangeStoredProc();
putApproverRequestStatusStoredProc = new PutApproverRequestStatusStoredProc();
putRequestProductStatusCodeStoredProc = new PutRequestProductStatusCodeStoredProc();
getUserRequestBetweenDateRangeStoredProc = new GetUserRequestBetweenDateRangeStoredProc();
getFullRequestBetweenDateRangeCostCenterStoredProc = new GetFullRequestBetweenDateRangeCostCenterStoredProc();
getRequestsByStatusCodeAndApproverStoredProc = new GetRequestsByStatusCodeAndApproverStoredProc();
getPendingRequestsByApproverStoredProc = new GetPendingRequestsByApproverStoredProc();
}
/**
* Verifies if there is a request record with a particular id in the database
* @param reqId id of Request to verify
* @return true if exists, false otherwise
*/
public Boolean checkRequestExists(long reqId) {
return checkRequestExistsStoredProc.execute(reqId);
}
public Request getRequestById(long reqId) {
return getRequestByIdStoredProc.execute(reqId);
}
/**
* Handles request posts by invoking a stored procedure
* @param reqToPost request object to post without id set
* @return posted request object without products set, with request status set to pending.
*/
public Request postNewRequest(Request reqToPost) {
return postNewRequestStoredProc.execute(reqToPost);
}
public List<String> putRequestStatusByApprover(long reqId, String approverId, String statusCode) {
return putApproverRequestStatusStoredProc.execute(reqId, approverId, statusCode);
}
public Request putRequestNewStatusId(long reqId, String statusCode, String approverId, Timestamp now, java.sql.Date expectedDate) {
return putRequestUpdateStatusStoredProc.execute(reqId, statusCode, approverId, now, expectedDate);
}
public void putRequestProductStatusCode(long reqId, String productCode, String productStatus, Timestamp timestamp, String approverId) {
putRequestProductStatusCodeStoredProc.execute(reqId, productCode, productStatus, timestamp, approverId);
}
public List<Request> getRequestsByDateRange(Timestamp tsFrom, Timestamp tsTo) {
return getRequestBetweenDateRangeStoredProc.execute(tsFrom, tsTo);
}
public List<Request> getUserRequestsByDateRange(Timestamp tsFrom, Timestamp tsTo, String userId) {
return getUserRequestBetweenDateRangeStoredProc.execute(tsFrom, tsTo, userId);
}
public List<Request> getFullRequestsByDateRangeCostCenter(Timestamp tsFrom, Timestamp tsTo, String costCenterCode) {
return getFullRequestBetweenDateRangeCostCenterStoredProc.execute(tsFrom, tsTo, costCenterCode);
}
public List<Request> getPendingRequestByApprover(String apprId) {
return getPendingRequestsByApproverStoredProc.execute(apprId);
}
public List<Request> getRequestsByStatusCodeAndApprover(RequestStatusCodes statusCode, String apprId) {
return getRequestsByStatusCodeAndApproverStoredProc.execute(statusCode, apprId);
}
private class CheckRequestExistsStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookupExists";
private CheckRequestExistsStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_requestId", Types.BIGINT));
declareParameter(new SqlOutParameter("out_exists", Types.BOOLEAN));
compile();
}
private boolean execute(long reqId) {
HashMap<String, Object> inputs = new HashMap<>();
inputs.put("in_requestId",reqId);
Map<String, Object> outputs = execute(inputs);
return (boolean) outputs.get("out_exists");
}
}
private class GetRequestByIdStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookupById";
private GetRequestByIdStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlInOutParameter("inout_requestId", Types.BIGINT));
declareParameter(new SqlOutParameter("out_notes", Types.VARCHAR));
declareParameter(new SqlOutParameter("out_dateCreated", Types.TIMESTAMP));
declareParameter(new SqlOutParameter("out_submittedBy", Types.CHAR));
declareParameter(new SqlOutParameter("out_lastModified", Types.TIMESTAMP));
declareParameter(new SqlOutParameter("out_lastModifiedBy", Types.CHAR));
declareParameter(new SqlOutParameter("out_statusCode", Types.CHAR));
declareParameter(new SqlOutParameter("out_expectedDate", Types.DATE));
compile();
}
/**
* Perform the stored procedure to get a request.
* @param reqId Request object to get.
* @return Request object with the reqId.
*/
private Request execute(long reqId) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("inout_requestId", reqId);
Map<String, Object> outputs= execute(inputs);
return mapResponseToRequest(outputs);
}
/**
* Parse out a new Request object from a HashMap
* @param responseMap Keys and values from the stored procedure response
* @return new Request object with id set
*/
private Request mapResponseToRequest(Map<String, Object> responseMap) {
try {
Request req = new Request();
req.setId((long)responseMap.get("inout_requestId"));
req.setNotes((String)responseMap.get("out_notes"));
req.setDateCreated((Timestamp)responseMap.get("out_dateCreated"));
req.setSubmittedBy((String)responseMap.get("out_submittedBy"));
req.setDateModified((Timestamp)responseMap.get("out_lastModified"));
req.setLastModifiedBy((String)responseMap.get("out_lastModifiedBy"));
req.setStatusCode(RequestStatusCodes.valueOf((String) responseMap.get("out_statusCode")));
req.setExpectedDate((Date) responseMap.get("out_expectedDate"));
req.setStatusCode(RequestStatusCodes.valueOf((String) responseMap.get("out_statusCode")));
return req;
} catch (ClassCastException e) {
System.err.println("Class cast exception in getRequestById.mapResponseToRequest, check DB");
throw new TypeMismatchDataAccessException(e.getMessage());
}
}
}
private class PutApproverRequestStatusStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_updateApproverStatus";
private PutApproverRequestStatusStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlInOutParameter("inout_requestId", Types.BIGINT));
declareParameter(new SqlInOutParameter("inout_approverId", Types.CHAR));
declareParameter(new SqlInOutParameter("inout_statusCode", Types.CHAR));
declareParameter(new SqlReturnResultSet("results", new RequestStatusMapper()));
compile();
}
private List<String> execute(long reqId, String approverId, String statusCode) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("inout_requestId", reqId);
inputs.put("inout_approverId", approverId);
inputs.put("inout_statusCode", statusCode);
Map<String, Object> outputs = execute(inputs);
List<RequestStatus> rows = (List<RequestStatus>) outputs.get("results");
List<String> statuses = new ArrayList<>();
for (RequestStatus r : rows) statuses.add(r.getStatusCode().name());
return statuses;
}
}
private class PutRequestUpdateStatusStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_updateStatus";
// NOTE: The expected date param is split into in_expectedDate and out_expectedDate because
// the former can be null when a status is being updated while it is already set in the db
// (in which case it will be picked up by the latter)
private PutRequestUpdateStatusStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_expectedDate", Types.DATE));
declareParameter(new SqlInOutParameter("inout_requestId", Types.BIGINT));
declareParameter(new SqlInOutParameter("inout_statusCode", Types.CHAR));
declareParameter(new SqlInOutParameter("inout_lastModified", Types.TIMESTAMP));
declareParameter(new SqlInOutParameter("inout_lastModifiedBy", Types.CHAR));
declareParameter(new SqlOutParameter("out_notes", Types.VARCHAR));
declareParameter(new SqlOutParameter("out_dateCreated", Types.TIMESTAMP));
declareParameter(new SqlOutParameter("out_submittedBy", Types.CHAR));
declareParameter(new SqlOutParameter("out_expectedDate", Types.DATE));
compile();
}
private Request execute(long reqId, String statusCode, String approverId, Timestamp now, java.sql.Date expectedDate) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_expectedDate", expectedDate);
inputs.put("inout_requestId", reqId);
inputs.put("inout_statusCode", statusCode);
inputs.put("inout_lastModified", now);
inputs.put("inout_lastModifiedBy", approverId);
Map<String, Object> outputs = execute(inputs);
return mapResponseToRequest(outputs);
}
private Request mapResponseToRequest(Map<String, Object> responseMap) {
try {
Request req = new Request();
req.setId((long) responseMap.get("inout_requestId"));
req.setStatusCode(RequestStatusCodes.valueOf((String) responseMap.get("inout_statusCode")));
req.setDateModified((Timestamp) responseMap.get("inout_lastModified"));
req.setLastModifiedBy((String) responseMap.get("inout_lastModifiedBy"));
req.setNotes((String) responseMap.get("out_notes"));
req.setDateCreated((Timestamp) responseMap.get("out_dateCreated"));
req.setSubmittedBy((String) responseMap.get("out_submittedBy"));
req.setExpectedDate((Date) responseMap.get("out_expectedDate"));
return req;
} catch (ClassCastException e) {
System.err.println("Class cast exception in PutRequestNewStatusId.mapResponseToRequest, check DB");
throw new TypeMismatchDataAccessException(e.getMessage());
}
}
}
private class PutRequestProductStatusCodeStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_updateProductStatus";
private PutRequestProductStatusCodeStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_requestId", Types.BIGINT));
declareParameter(new SqlParameter("in_productCode", Types.VARCHAR));
declareParameter(new SqlParameter("in_statusCode", Types.CHAR));
declareParameter(new SqlParameter("in_lastModified", Types.TIMESTAMP));
declareParameter(new SqlParameter("in_lastModifiedBy", Types.VARCHAR));
compile();
}
private void execute(long reqId, String productCode, String statusCode, Timestamp ts, String approverId) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_requestId", reqId);
inputs.put("in_productCode", productCode);
inputs.put("in_statusCode", statusCode);
inputs.put("in_lastModified", ts);
inputs.put("in_lastModifiedBy", approverId);
execute(inputs);
}
}
/**
* Responsible for calling the stored procedure used to create a request in the database.
* The input request object should NOT have an id set as it will be overwritten by the
* database using autoincrement.
*/
private class PostNewRequestStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_insert";
private PostNewRequestStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlInOutParameter("inout_notes", Types.VARCHAR));
declareParameter(new SqlInOutParameter("inout_dateCreated", Types.TIMESTAMP));
declareParameter(new SqlInOutParameter("inout_submittedBy", Types.CHAR));
declareParameter(new SqlInOutParameter("inout_lastModified", Types.TIMESTAMP));
declareParameter(new SqlInOutParameter("inout_lastModifiedBy", Types.CHAR));
declareParameter(new SqlInOutParameter("inout_statusCode", Types.CHAR));
declareParameter(new SqlOutParameter("out_requestId", Types.BIGINT));
declareParameter(new SqlOutParameter("out_expectedDate", Types.DATE));
compile();
}
/**
* Perform the stored procedure to post a request.
* @param req Request object to post. The id value should be null as it will be
* set by the database using autoincrement.
* @return posted Request object with id set.
*/
private Request execute(Request req) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("inout_notes", req.getNotes());
inputs.put("inout_dateCreated", req.getDateCreated());
inputs.put("inout_submittedBy", req.getSubmittedBy());
inputs.put("inout_lastModified", req.getDateModified());
inputs.put("inout_lastModifiedBy", req.getLastModifiedBy());
inputs.put("inout_statusCode", req.getStatusCode().name());
Map<String, Object> outputs= execute(inputs);
return mapResponseToRequest(outputs);
}
/**
* Parse out a new Request object from a HashMap
* @param responseMap Keys and values from the stored procedure response
* @return new Request object with id set
*/
private Request mapResponseToRequest(Map<String, Object> responseMap) {
try {
Request req = new Request();
req.setId((long) responseMap.get("out_requestId"));
req.setNotes((String) responseMap.get("inout_notes"));
req.setDateCreated((Timestamp) responseMap.get("inout_dateCreated"));
req.setSubmittedBy((String) responseMap.get("inout_submittedBy"));
req.setDateModified((Timestamp) responseMap.get("inout_lastModified"));
req.setLastModifiedBy((String) responseMap.get("inout_lastModifiedBy"));
req.setStatusCode(RequestStatusCodes.valueOf((String) responseMap.get("inout_statusCode")));
return req;
} catch (ClassCastException e) {
System.err.println("Class cast exception in addProductToRequest.mapResponseToRequest, check DB");
throw new TypeMismatchDataAccessException(e.getMessage());
}
}
}
private class GetRequestsBetweenDateRangeStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookUpByDateRange";
private GetRequestsBetweenDateRangeStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_fromDate", Types.TIMESTAMP));
declareParameter(new SqlParameter("in_toDate", Types.TIMESTAMP));
declareParameter(new SqlReturnResultSet("requests", new RequestSummaryMapper()));
compile();
}
private List<Request> execute(Timestamp from, Timestamp to) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_fromDate", from);
inputs.put("in_toDate", to);
Map<String, Object> outputs = execute(inputs);
return (List<Request>) outputs.get("requests");
}
}
/**
* Look up requests that an approver has yet to approve or deny in their cost center
*/
private class GetPendingRequestsByApproverStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookUpByPendingAndEmployeeCostCenter";
private GetPendingRequestsByApproverStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_employeeId", Types.CHAR));
declareParameter(new SqlReturnResultSet("requests", new RequestSummaryMapper()));
}
private List<Request> execute(String employeeId) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_employeeId", employeeId);
Map<String, Object> outputs = execute(inputs);
return (List<Request>) outputs.get("requests");
}
}
/**
* Look up requests that an approver has either approved, or denied, in their cost center.
*/
private class GetUserRequestBetweenDateRangeStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookUpByUserAndDateRange";
private GetUserRequestBetweenDateRangeStoredProc() {
super (jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_submittedBy", Types.CHAR));
declareParameter(new SqlParameter("in_fromDate", Types.TIMESTAMP));
declareParameter(new SqlParameter("in_toDate", Types.TIMESTAMP));
declareParameter(new SqlReturnResultSet("requests", new RequestSummaryMapper()));
}
private List<Request> execute (Timestamp from, Timestamp to, String userId) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_submittedBy", userId);
inputs.put("in_fromDate", from);
inputs.put("in_toDate", to);
Map<String, Object> outputs = execute(inputs);
return (List<Request>) outputs.get("requests");
}
}
private class GetFullRequestBetweenDateRangeCostCenterStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookUpByDateRangeAndCostCenterIncludeProducts";
private GetFullRequestBetweenDateRangeCostCenterStoredProc() {
super (jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_fromDate", Types.TIMESTAMP));
declareParameter(new SqlParameter("in_toDate", Types.TIMESTAMP));
declareParameter(new SqlParameter("in_costCenterCode", Types.VARCHAR));
declareParameter(new SqlReturnResultSet("requests", new RequestWithProductsExtractor()));
}
private List<Request> execute (Timestamp from, Timestamp to, String costCenterCode) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_fromDate", from);
inputs.put("in_toDate", to);
inputs.put("in_costCenterCode", costCenterCode);
Map<String, Object> outputs = execute(inputs);
return (List<Request>) outputs.get("requests");
}
}
private class GetRequestsByStatusCodeAndApproverStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookupByStatusCodeAndApproverId";
private GetRequestsByStatusCodeAndApproverStoredProc() {
super (jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_statusCode", Types.CHAR));
declareParameter(new SqlParameter("in_employeeId", Types.CHAR));
declareParameter(new SqlReturnResultSet("requests", new RequestSummaryMapper()));
compile();
}
private List<Request> execute (RequestStatusCodes statusCode, String apprId) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_statusCode", statusCode.name());
inputs.put("in_employeeId", apprId);
Map<String, Object> outputs = execute(inputs);
return (List<Request>) outputs.get("requests");
}
}
}
| UTF-8 | Java | 23,126 | java | RequestRepository.java | Java | []
| null | []
| package com.coastcapitalsavings.mvc.repositories;
import com.coastcapitalsavings.util.RequestStatusCodes;
import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import com.coastcapitalsavings.mvc.models.Request;
import com.coastcapitalsavings.mvc.models.RequestStatus;
import com.coastcapitalsavings.mvc.repositories.extractor.RequestWithProductsExtractor;
import com.coastcapitalsavings.mvc.repositories.mapper.RequestSummaryMapper;
import com.coastcapitalsavings.mvc.repositories.mapper.RequestStatusMapper;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.dao.TypeMismatchDataAccessException;
import org.springframework.jdbc.object.StoredProcedure;
import org.springframework.jdbc.core.*;
import java.sql.Date;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Database access object for the requests endpoint
*/
@Repository
public class RequestRepository {
JdbcTemplate jdbcTemplate;
// Store stored procedures so that they don't have to be recompiled for every use;
GetRequestByIdStoredProc getRequestByIdStoredProc;
PostNewRequestStoredProc postNewRequestStoredProc;
PutRequestUpdateStatusStoredProc putRequestUpdateStatusStoredProc;
CheckRequestExistsStoredProc checkRequestExistsStoredProc;
GetRequestsBetweenDateRangeStoredProc getRequestBetweenDateRangeStoredProc;
PutApproverRequestStatusStoredProc putApproverRequestStatusStoredProc;
PutRequestProductStatusCodeStoredProc putRequestProductStatusCodeStoredProc;
GetUserRequestBetweenDateRangeStoredProc getUserRequestBetweenDateRangeStoredProc;
GetFullRequestBetweenDateRangeCostCenterStoredProc getFullRequestBetweenDateRangeCostCenterStoredProc;
GetRequestsByStatusCodeAndApproverStoredProc getRequestsByStatusCodeAndApproverStoredProc;
GetPendingRequestsByApproverStoredProc getPendingRequestsByApproverStoredProc;
@Autowired
/*
Tricky: Need to do this instead of autowiring the Jdbc template so that we can ensure that the
template is up before the stored procedures are initialized.
*/
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
getRequestByIdStoredProc = new GetRequestByIdStoredProc();
postNewRequestStoredProc = new PostNewRequestStoredProc();
putRequestUpdateStatusStoredProc = new PutRequestUpdateStatusStoredProc();
checkRequestExistsStoredProc = new CheckRequestExistsStoredProc();
getRequestBetweenDateRangeStoredProc = new GetRequestsBetweenDateRangeStoredProc();
putApproverRequestStatusStoredProc = new PutApproverRequestStatusStoredProc();
putRequestProductStatusCodeStoredProc = new PutRequestProductStatusCodeStoredProc();
getUserRequestBetweenDateRangeStoredProc = new GetUserRequestBetweenDateRangeStoredProc();
getFullRequestBetweenDateRangeCostCenterStoredProc = new GetFullRequestBetweenDateRangeCostCenterStoredProc();
getRequestsByStatusCodeAndApproverStoredProc = new GetRequestsByStatusCodeAndApproverStoredProc();
getPendingRequestsByApproverStoredProc = new GetPendingRequestsByApproverStoredProc();
}
/**
* Verifies if there is a request record with a particular id in the database
* @param reqId id of Request to verify
* @return true if exists, false otherwise
*/
public Boolean checkRequestExists(long reqId) {
return checkRequestExistsStoredProc.execute(reqId);
}
public Request getRequestById(long reqId) {
return getRequestByIdStoredProc.execute(reqId);
}
/**
* Handles request posts by invoking a stored procedure
* @param reqToPost request object to post without id set
* @return posted request object without products set, with request status set to pending.
*/
public Request postNewRequest(Request reqToPost) {
return postNewRequestStoredProc.execute(reqToPost);
}
public List<String> putRequestStatusByApprover(long reqId, String approverId, String statusCode) {
return putApproverRequestStatusStoredProc.execute(reqId, approverId, statusCode);
}
public Request putRequestNewStatusId(long reqId, String statusCode, String approverId, Timestamp now, java.sql.Date expectedDate) {
return putRequestUpdateStatusStoredProc.execute(reqId, statusCode, approverId, now, expectedDate);
}
public void putRequestProductStatusCode(long reqId, String productCode, String productStatus, Timestamp timestamp, String approverId) {
putRequestProductStatusCodeStoredProc.execute(reqId, productCode, productStatus, timestamp, approverId);
}
public List<Request> getRequestsByDateRange(Timestamp tsFrom, Timestamp tsTo) {
return getRequestBetweenDateRangeStoredProc.execute(tsFrom, tsTo);
}
public List<Request> getUserRequestsByDateRange(Timestamp tsFrom, Timestamp tsTo, String userId) {
return getUserRequestBetweenDateRangeStoredProc.execute(tsFrom, tsTo, userId);
}
public List<Request> getFullRequestsByDateRangeCostCenter(Timestamp tsFrom, Timestamp tsTo, String costCenterCode) {
return getFullRequestBetweenDateRangeCostCenterStoredProc.execute(tsFrom, tsTo, costCenterCode);
}
public List<Request> getPendingRequestByApprover(String apprId) {
return getPendingRequestsByApproverStoredProc.execute(apprId);
}
public List<Request> getRequestsByStatusCodeAndApprover(RequestStatusCodes statusCode, String apprId) {
return getRequestsByStatusCodeAndApproverStoredProc.execute(statusCode, apprId);
}
private class CheckRequestExistsStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookupExists";
private CheckRequestExistsStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_requestId", Types.BIGINT));
declareParameter(new SqlOutParameter("out_exists", Types.BOOLEAN));
compile();
}
private boolean execute(long reqId) {
HashMap<String, Object> inputs = new HashMap<>();
inputs.put("in_requestId",reqId);
Map<String, Object> outputs = execute(inputs);
return (boolean) outputs.get("out_exists");
}
}
private class GetRequestByIdStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookupById";
private GetRequestByIdStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlInOutParameter("inout_requestId", Types.BIGINT));
declareParameter(new SqlOutParameter("out_notes", Types.VARCHAR));
declareParameter(new SqlOutParameter("out_dateCreated", Types.TIMESTAMP));
declareParameter(new SqlOutParameter("out_submittedBy", Types.CHAR));
declareParameter(new SqlOutParameter("out_lastModified", Types.TIMESTAMP));
declareParameter(new SqlOutParameter("out_lastModifiedBy", Types.CHAR));
declareParameter(new SqlOutParameter("out_statusCode", Types.CHAR));
declareParameter(new SqlOutParameter("out_expectedDate", Types.DATE));
compile();
}
/**
* Perform the stored procedure to get a request.
* @param reqId Request object to get.
* @return Request object with the reqId.
*/
private Request execute(long reqId) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("inout_requestId", reqId);
Map<String, Object> outputs= execute(inputs);
return mapResponseToRequest(outputs);
}
/**
* Parse out a new Request object from a HashMap
* @param responseMap Keys and values from the stored procedure response
* @return new Request object with id set
*/
private Request mapResponseToRequest(Map<String, Object> responseMap) {
try {
Request req = new Request();
req.setId((long)responseMap.get("inout_requestId"));
req.setNotes((String)responseMap.get("out_notes"));
req.setDateCreated((Timestamp)responseMap.get("out_dateCreated"));
req.setSubmittedBy((String)responseMap.get("out_submittedBy"));
req.setDateModified((Timestamp)responseMap.get("out_lastModified"));
req.setLastModifiedBy((String)responseMap.get("out_lastModifiedBy"));
req.setStatusCode(RequestStatusCodes.valueOf((String) responseMap.get("out_statusCode")));
req.setExpectedDate((Date) responseMap.get("out_expectedDate"));
req.setStatusCode(RequestStatusCodes.valueOf((String) responseMap.get("out_statusCode")));
return req;
} catch (ClassCastException e) {
System.err.println("Class cast exception in getRequestById.mapResponseToRequest, check DB");
throw new TypeMismatchDataAccessException(e.getMessage());
}
}
}
private class PutApproverRequestStatusStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_updateApproverStatus";
private PutApproverRequestStatusStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlInOutParameter("inout_requestId", Types.BIGINT));
declareParameter(new SqlInOutParameter("inout_approverId", Types.CHAR));
declareParameter(new SqlInOutParameter("inout_statusCode", Types.CHAR));
declareParameter(new SqlReturnResultSet("results", new RequestStatusMapper()));
compile();
}
private List<String> execute(long reqId, String approverId, String statusCode) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("inout_requestId", reqId);
inputs.put("inout_approverId", approverId);
inputs.put("inout_statusCode", statusCode);
Map<String, Object> outputs = execute(inputs);
List<RequestStatus> rows = (List<RequestStatus>) outputs.get("results");
List<String> statuses = new ArrayList<>();
for (RequestStatus r : rows) statuses.add(r.getStatusCode().name());
return statuses;
}
}
private class PutRequestUpdateStatusStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_updateStatus";
// NOTE: The expected date param is split into in_expectedDate and out_expectedDate because
// the former can be null when a status is being updated while it is already set in the db
// (in which case it will be picked up by the latter)
private PutRequestUpdateStatusStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_expectedDate", Types.DATE));
declareParameter(new SqlInOutParameter("inout_requestId", Types.BIGINT));
declareParameter(new SqlInOutParameter("inout_statusCode", Types.CHAR));
declareParameter(new SqlInOutParameter("inout_lastModified", Types.TIMESTAMP));
declareParameter(new SqlInOutParameter("inout_lastModifiedBy", Types.CHAR));
declareParameter(new SqlOutParameter("out_notes", Types.VARCHAR));
declareParameter(new SqlOutParameter("out_dateCreated", Types.TIMESTAMP));
declareParameter(new SqlOutParameter("out_submittedBy", Types.CHAR));
declareParameter(new SqlOutParameter("out_expectedDate", Types.DATE));
compile();
}
private Request execute(long reqId, String statusCode, String approverId, Timestamp now, java.sql.Date expectedDate) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_expectedDate", expectedDate);
inputs.put("inout_requestId", reqId);
inputs.put("inout_statusCode", statusCode);
inputs.put("inout_lastModified", now);
inputs.put("inout_lastModifiedBy", approverId);
Map<String, Object> outputs = execute(inputs);
return mapResponseToRequest(outputs);
}
private Request mapResponseToRequest(Map<String, Object> responseMap) {
try {
Request req = new Request();
req.setId((long) responseMap.get("inout_requestId"));
req.setStatusCode(RequestStatusCodes.valueOf((String) responseMap.get("inout_statusCode")));
req.setDateModified((Timestamp) responseMap.get("inout_lastModified"));
req.setLastModifiedBy((String) responseMap.get("inout_lastModifiedBy"));
req.setNotes((String) responseMap.get("out_notes"));
req.setDateCreated((Timestamp) responseMap.get("out_dateCreated"));
req.setSubmittedBy((String) responseMap.get("out_submittedBy"));
req.setExpectedDate((Date) responseMap.get("out_expectedDate"));
return req;
} catch (ClassCastException e) {
System.err.println("Class cast exception in PutRequestNewStatusId.mapResponseToRequest, check DB");
throw new TypeMismatchDataAccessException(e.getMessage());
}
}
}
private class PutRequestProductStatusCodeStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_updateProductStatus";
private PutRequestProductStatusCodeStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_requestId", Types.BIGINT));
declareParameter(new SqlParameter("in_productCode", Types.VARCHAR));
declareParameter(new SqlParameter("in_statusCode", Types.CHAR));
declareParameter(new SqlParameter("in_lastModified", Types.TIMESTAMP));
declareParameter(new SqlParameter("in_lastModifiedBy", Types.VARCHAR));
compile();
}
private void execute(long reqId, String productCode, String statusCode, Timestamp ts, String approverId) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_requestId", reqId);
inputs.put("in_productCode", productCode);
inputs.put("in_statusCode", statusCode);
inputs.put("in_lastModified", ts);
inputs.put("in_lastModifiedBy", approverId);
execute(inputs);
}
}
/**
* Responsible for calling the stored procedure used to create a request in the database.
* The input request object should NOT have an id set as it will be overwritten by the
* database using autoincrement.
*/
private class PostNewRequestStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_insert";
private PostNewRequestStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlInOutParameter("inout_notes", Types.VARCHAR));
declareParameter(new SqlInOutParameter("inout_dateCreated", Types.TIMESTAMP));
declareParameter(new SqlInOutParameter("inout_submittedBy", Types.CHAR));
declareParameter(new SqlInOutParameter("inout_lastModified", Types.TIMESTAMP));
declareParameter(new SqlInOutParameter("inout_lastModifiedBy", Types.CHAR));
declareParameter(new SqlInOutParameter("inout_statusCode", Types.CHAR));
declareParameter(new SqlOutParameter("out_requestId", Types.BIGINT));
declareParameter(new SqlOutParameter("out_expectedDate", Types.DATE));
compile();
}
/**
* Perform the stored procedure to post a request.
* @param req Request object to post. The id value should be null as it will be
* set by the database using autoincrement.
* @return posted Request object with id set.
*/
private Request execute(Request req) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("inout_notes", req.getNotes());
inputs.put("inout_dateCreated", req.getDateCreated());
inputs.put("inout_submittedBy", req.getSubmittedBy());
inputs.put("inout_lastModified", req.getDateModified());
inputs.put("inout_lastModifiedBy", req.getLastModifiedBy());
inputs.put("inout_statusCode", req.getStatusCode().name());
Map<String, Object> outputs= execute(inputs);
return mapResponseToRequest(outputs);
}
/**
* Parse out a new Request object from a HashMap
* @param responseMap Keys and values from the stored procedure response
* @return new Request object with id set
*/
private Request mapResponseToRequest(Map<String, Object> responseMap) {
try {
Request req = new Request();
req.setId((long) responseMap.get("out_requestId"));
req.setNotes((String) responseMap.get("inout_notes"));
req.setDateCreated((Timestamp) responseMap.get("inout_dateCreated"));
req.setSubmittedBy((String) responseMap.get("inout_submittedBy"));
req.setDateModified((Timestamp) responseMap.get("inout_lastModified"));
req.setLastModifiedBy((String) responseMap.get("inout_lastModifiedBy"));
req.setStatusCode(RequestStatusCodes.valueOf((String) responseMap.get("inout_statusCode")));
return req;
} catch (ClassCastException e) {
System.err.println("Class cast exception in addProductToRequest.mapResponseToRequest, check DB");
throw new TypeMismatchDataAccessException(e.getMessage());
}
}
}
private class GetRequestsBetweenDateRangeStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookUpByDateRange";
private GetRequestsBetweenDateRangeStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_fromDate", Types.TIMESTAMP));
declareParameter(new SqlParameter("in_toDate", Types.TIMESTAMP));
declareParameter(new SqlReturnResultSet("requests", new RequestSummaryMapper()));
compile();
}
private List<Request> execute(Timestamp from, Timestamp to) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_fromDate", from);
inputs.put("in_toDate", to);
Map<String, Object> outputs = execute(inputs);
return (List<Request>) outputs.get("requests");
}
}
/**
* Look up requests that an approver has yet to approve or deny in their cost center
*/
private class GetPendingRequestsByApproverStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookUpByPendingAndEmployeeCostCenter";
private GetPendingRequestsByApproverStoredProc() {
super(jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_employeeId", Types.CHAR));
declareParameter(new SqlReturnResultSet("requests", new RequestSummaryMapper()));
}
private List<Request> execute(String employeeId) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_employeeId", employeeId);
Map<String, Object> outputs = execute(inputs);
return (List<Request>) outputs.get("requests");
}
}
/**
* Look up requests that an approver has either approved, or denied, in their cost center.
*/
private class GetUserRequestBetweenDateRangeStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookUpByUserAndDateRange";
private GetUserRequestBetweenDateRangeStoredProc() {
super (jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_submittedBy", Types.CHAR));
declareParameter(new SqlParameter("in_fromDate", Types.TIMESTAMP));
declareParameter(new SqlParameter("in_toDate", Types.TIMESTAMP));
declareParameter(new SqlReturnResultSet("requests", new RequestSummaryMapper()));
}
private List<Request> execute (Timestamp from, Timestamp to, String userId) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_submittedBy", userId);
inputs.put("in_fromDate", from);
inputs.put("in_toDate", to);
Map<String, Object> outputs = execute(inputs);
return (List<Request>) outputs.get("requests");
}
}
private class GetFullRequestBetweenDateRangeCostCenterStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookUpByDateRangeAndCostCenterIncludeProducts";
private GetFullRequestBetweenDateRangeCostCenterStoredProc() {
super (jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_fromDate", Types.TIMESTAMP));
declareParameter(new SqlParameter("in_toDate", Types.TIMESTAMP));
declareParameter(new SqlParameter("in_costCenterCode", Types.VARCHAR));
declareParameter(new SqlReturnResultSet("requests", new RequestWithProductsExtractor()));
}
private List<Request> execute (Timestamp from, Timestamp to, String costCenterCode) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_fromDate", from);
inputs.put("in_toDate", to);
inputs.put("in_costCenterCode", costCenterCode);
Map<String, Object> outputs = execute(inputs);
return (List<Request>) outputs.get("requests");
}
}
private class GetRequestsByStatusCodeAndApproverStoredProc extends StoredProcedure {
private static final String PROC_NAME = "req_request_lookupByStatusCodeAndApproverId";
private GetRequestsByStatusCodeAndApproverStoredProc() {
super (jdbcTemplate, PROC_NAME);
declareParameter(new SqlParameter("in_statusCode", Types.CHAR));
declareParameter(new SqlParameter("in_employeeId", Types.CHAR));
declareParameter(new SqlReturnResultSet("requests", new RequestSummaryMapper()));
compile();
}
private List<Request> execute (RequestStatusCodes statusCode, String apprId) {
Map<String, Object> inputs = new HashMap<>();
inputs.put("in_statusCode", statusCode.name());
inputs.put("in_employeeId", apprId);
Map<String, Object> outputs = execute(inputs);
return (List<Request>) outputs.get("requests");
}
}
}
| 23,126 | 0.682306 | 0.682306 | 477 | 47.482182 | 35.266079 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.870021 | false | false | 3 |
89c3f3d3a916a859a3f5838be6e679532d01245a | 850,403,536,402 | be7b72d54574b9aaf8e7a474b461ac6f64088929 | /src/LibraryManagerFinal/AdminController.java | ba4354fc25ad66d7092fde030c4d708500b8ea47 | []
| no_license | shiponsheikh/librarymanagement | https://github.com/shiponsheikh/librarymanagement | 9b32fa106e2ed08ec1eaaab66e087f1558e78bda | fab3006ff656abd57f9bd8141a2f8ef896246fa3 | refs/heads/master | 2020-05-17T09:44:38.169000 | 2019-04-26T14:19:34 | 2019-04-26T14:19:34 | 183,640,897 | 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 LibraryManagerFinal;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
/**
* FXML Controller class
*
* @author Shah Ali
*/
public class AdminController implements Initializable {
@FXML
private PasswordField cpass;
@FXML
private PasswordField npass;
@FXML
private PasswordField n1pass;
@FXML
private TextField nuser;
Connection con;
Statement stmn;
ResultSet rs;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
Main.getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
change();
}
}
});
}
@FXML
private void change() {
String password = "23c@426*^%#^";
int i = 0;
try {
con = Main.getConnection();
stmn = con.createStatement();
rs = stmn.executeQuery("select * from login");
rs.next();
{
password = rs.getString("password");
}
if(password.equals(cpass.getText())){
if(npass.getText().equals(n1pass.getText()) && (!npass.getText().equals(""))
)
{
stmn.executeUpdate("update login set password = '"+npass.getText()+"' where username = '"+rs.getString("username")+"'");
i++;
}
else if(npass.getText().equals(""))
{
}
else if(!npass.getText().equals(n1pass.getText()))
ShowAlert.showAlert("Enter same password in both new password field !!!");
if(!nuser.getText().equals(""))
{
stmn.executeUpdate("update login set username = '"+nuser.getText()+"' where password = '"+password+"'");
i++;
}
if(i>0)
ShowAlert.showInformation("Change has been performed successfully !!!");
}
else
ShowAlert.showAlert("Incorrect current password");
rs.close();
stmn.close();
con.close();
} catch (Exception ex) {
// Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| UTF-8 | Java | 3,149 | java | AdminController.java | Java | [
{
"context": "Event;\n\n/**\n * FXML Controller class\n *\n * @author Shah Ali\n */\npublic class AdminController implements Initia",
"end": 747,
"score": 0.9362228512763977,
"start": 739,
"tag": "NAME",
"value": "Shah Ali"
},
{
"context": "rivate void change() {\n String password = \"23c@426*^%#^\";\n int i = 0;\n try {\n co",
"end": 1535,
"score": 0.9994893670082092,
"start": 1528,
"tag": "PASSWORD",
"value": "23c@426"
}
]
| 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 LibraryManagerFinal;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
/**
* FXML Controller class
*
* @author <NAME>
*/
public class AdminController implements Initializable {
@FXML
private PasswordField cpass;
@FXML
private PasswordField npass;
@FXML
private PasswordField n1pass;
@FXML
private TextField nuser;
Connection con;
Statement stmn;
ResultSet rs;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
Main.getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
change();
}
}
});
}
@FXML
private void change() {
String password = "<PASSWORD>*^%#^";
int i = 0;
try {
con = Main.getConnection();
stmn = con.createStatement();
rs = stmn.executeQuery("select * from login");
rs.next();
{
password = rs.getString("password");
}
if(password.equals(cpass.getText())){
if(npass.getText().equals(n1pass.getText()) && (!npass.getText().equals(""))
)
{
stmn.executeUpdate("update login set password = '"+npass.getText()+"' where username = '"+rs.getString("username")+"'");
i++;
}
else if(npass.getText().equals(""))
{
}
else if(!npass.getText().equals(n1pass.getText()))
ShowAlert.showAlert("Enter same password in both new password field !!!");
if(!nuser.getText().equals(""))
{
stmn.executeUpdate("update login set username = '"+nuser.getText()+"' where password = '"+password+"'");
i++;
}
if(i>0)
ShowAlert.showInformation("Change has been performed successfully !!!");
}
else
ShowAlert.showAlert("Incorrect current password");
rs.close();
stmn.close();
con.close();
} catch (Exception ex) {
// Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| 3,150 | 0.551286 | 0.54811 | 102 | 29.872549 | 25.77492 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480392 | false | false | 3 |
bf34458a0add5823defdc9593f02fdb0ad9943dc | 15,934,328,688,956 | 3c87ae5f0e1afafae8065c8a9b1ff94b770d5392 | /src/main/java/blackjack/domain/deck/DeckGenerator.java | 740bdc2df8e8f73704f31db31fa2076f133c65e9 | []
| no_license | jiwoo-kimm/mirror-java-blackjack | https://github.com/jiwoo-kimm/mirror-java-blackjack | 05e00ab93525c18ac4e52a2c0f63bd15cfc842f3 | d98cb0379c7d5293e5ce7be0dc1cd305304c5e9b | refs/heads/master | 2023-07-16T18:33:58.769000 | 2021-08-21T16:40:12 | 2021-08-21T16:40:12 | 396,597,436 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package blackjack.domain.deck;
import blackjack.domain.card.Card;
import java.util.Deque;
public interface DeckGenerator {
Deque<Card> generateDeck();
}
| UTF-8 | Java | 160 | java | DeckGenerator.java | Java | []
| null | []
| package blackjack.domain.deck;
import blackjack.domain.card.Card;
import java.util.Deque;
public interface DeckGenerator {
Deque<Card> generateDeck();
}
| 160 | 0.76875 | 0.76875 | 9 | 16.777779 | 15.046431 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 3 |
b7c181ca802945716c935c0cebe722ba5ccc2568 | 15,934,328,688,816 | b5bcac0ee7be67bd54870c162de1c75e721fd8bf | /sales/sales-ejb/src/main/java/japhet/sales/mailing/service/ITemplateReaderService.java | 11b06865a8802874939fe3bb6d57de02f0ea9eea | []
| no_license | idcodeoverflow/prosperad | https://github.com/idcodeoverflow/prosperad | 08039513bf260f92736469b5dc42057f312f56b8 | 8145bfa0f0f41924ec529c75a71515d31e3b8a28 | refs/heads/master | 2021-06-17T11:07:11.636000 | 2017-05-22T07:10:50 | 2017-05-22T07:10:50 | 63,505,715 | 0 | 1 | null | false | 2017-05-22T07:10:51 | 2016-07-16T23:03:33 | 2016-12-23T06:40:30 | 2017-05-22T07:10:51 | 7,173 | 0 | 0 | 0 | Java | null | null | /**
*
*/
package japhet.sales.mailing.service;
import java.io.Serializable;
import java.util.Map;
import javax.ejb.Local;
import japhet.sales.except.TemplateReaderException;
import japhet.sales.mailing.MailingTemplates;
/**
* @author David Israel Garcia Alcazar
*
*/
@Local
public interface ITemplateReaderService extends Serializable {
public String readTemplate(MailingTemplates mailingTemplates, Map<String, Object> params)
throws TemplateReaderException;
}
| UTF-8 | Java | 477 | java | ITemplateReaderService.java | Java | [
{
"context": "et.sales.mailing.MailingTemplates;\n\n/**\n * @author David Israel Garcia Alcazar\n *\n */\n@Local\npublic interface ITemplateReaderSer",
"end": 269,
"score": 0.9952505230903625,
"start": 242,
"tag": "NAME",
"value": "David Israel Garcia Alcazar"
}
]
| null | []
| /**
*
*/
package japhet.sales.mailing.service;
import java.io.Serializable;
import java.util.Map;
import javax.ejb.Local;
import japhet.sales.except.TemplateReaderException;
import japhet.sales.mailing.MailingTemplates;
/**
* @author <NAME>
*
*/
@Local
public interface ITemplateReaderService extends Serializable {
public String readTemplate(MailingTemplates mailingTemplates, Map<String, Object> params)
throws TemplateReaderException;
}
| 456 | 0.786164 | 0.786164 | 23 | 19.73913 | 24.315351 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false | 3 |
0514b95da0f762ce159b7551db74e9b6ef681111 | 26,147,760,909,307 | 4ff504748f2805a2c0ca912340c7f8822d92f08f | /jva-001-p1/src/com/luxoft/jva001p1/oop/demo/Demo.java | 5b2449c29756d0b19c4c32045abda37f58bde1bc | []
| no_license | Denis891906/java_007 | https://github.com/Denis891906/java_007 | 990b0ecc673a3eb43fab1ab2959930c00a10e6ec | 44615d8e2d0f27fb012baa06fd509088bf164690 | refs/heads/master | 2020-07-12T02:01:14.887000 | 2019-09-19T12:34:15 | 2019-09-19T12:34:15 | 204,689,984 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.luxoft.jva001p1.oop.demo;
import java.util.ArrayList;
public class Demo
{
public static void main(String[] args)
{
ArrayList<Cat> data = new ArrayList<>();
Cat cat1 = new Cat();
cat1.name = "Murzik";
cat1.age = 20;
Cat cat2 = new Cat();
cat2.name = "Rocky";
cat2.age = 18;
Cat cat3 = new Cat();
cat3.name = "Murka";
cat3.age = 16;
data.add(cat1);
data.add(cat2);
data.add(cat3);
for (Cat cat : data)
{
displayCat(cat);
}
// ----------------
Cat c = new Cat();
c.name = "Martin";
c.age = 65;
displayCat(c);
getOlder(c);
displayCat(c);
}
static void getOlder(Cat cat)
{
cat.age = cat.age + 1;
}
static void displayCat(Cat cat)
{
System.out.println("Cat: [name: " + cat.name + ", age: " + cat.age + "]");
}
}
| UTF-8 | Java | 983 | java | Demo.java | Java | [
{
"context": " Cat cat1 = new Cat();\n cat1.name = \"Murzik\";\n cat1.age = 20;\n\n Cat cat2 = new ",
"end": 244,
"score": 0.9995495676994324,
"start": 238,
"tag": "NAME",
"value": "Murzik"
},
{
"context": " Cat cat2 = new Cat();\n cat2.name = \"Rocky\";\n cat2.age = 18;\n\n Cat cat3 = new ",
"end": 327,
"score": 0.9996871948242188,
"start": 322,
"tag": "NAME",
"value": "Rocky"
},
{
"context": " Cat cat3 = new Cat();\n cat3.name = \"Murka\";\n cat3.age = 16;\n\n data.add(cat1);",
"end": 410,
"score": 0.9995930790901184,
"start": 405,
"tag": "NAME",
"value": "Murka"
},
{
"context": "---\n\n Cat c = new Cat();\n c.name = \"Martin\";\n c.age = 65;\n\n displayCat(c);\n\n ",
"end": 669,
"score": 0.9994661808013916,
"start": 663,
"tag": "NAME",
"value": "Martin"
}
]
| null | []
| package com.luxoft.jva001p1.oop.demo;
import java.util.ArrayList;
public class Demo
{
public static void main(String[] args)
{
ArrayList<Cat> data = new ArrayList<>();
Cat cat1 = new Cat();
cat1.name = "Murzik";
cat1.age = 20;
Cat cat2 = new Cat();
cat2.name = "Rocky";
cat2.age = 18;
Cat cat3 = new Cat();
cat3.name = "Murka";
cat3.age = 16;
data.add(cat1);
data.add(cat2);
data.add(cat3);
for (Cat cat : data)
{
displayCat(cat);
}
// ----------------
Cat c = new Cat();
c.name = "Martin";
c.age = 65;
displayCat(c);
getOlder(c);
displayCat(c);
}
static void getOlder(Cat cat)
{
cat.age = cat.age + 1;
}
static void displayCat(Cat cat)
{
System.out.println("Cat: [name: " + cat.name + ", age: " + cat.age + "]");
}
}
| 983 | 0.459817 | 0.434385 | 57 | 16.245613 | 16.228933 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.438596 | false | false | 3 |
0fc90f8ebf1607eda6d1e9cb988765bdb7f30428 | 575,525,631,697 | 2044ed1c76a96a4fea16d872a8585b0eb94707aa | /F10-cmdline/src/com/javaoktato/nio/fileop/CmdLine.java | dbe941603e0557ea776fe0815bf3e38a8cc3d555 | []
| no_license | gaborbsd/java_2ed_sources | https://github.com/gaborbsd/java_2ed_sources | 17c06cacf5feb7b5ce54b37c998430fa64d87209 | 8583ef08b06eaff7a6702ebadbddd20ddd08ec6f | refs/heads/master | 2020-03-30T07:45:11.987000 | 2018-10-02T17:29:00 | 2018-10-02T17:29:00 | 150,964,326 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright © 2018. Kövesdán Gábor
*
* Az alábbi forráskód a "Szoftverfejlesztés Java SE platformon"
* c. könyv második kiadásának (ISBN 978-615-00-2933-7) mellékletét
* képezi. A forráskódot vagy annak részeit a kiadó engedélye nélkül
* tilos reprodukálni, adatrögzítő rendszerben tárolni, bármilyen
* formában vagy eszközzel elektronikus úton vagy más módon közölni.
*/
package com.javaoktato.nio.fileop;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CmdLine {
public static void main(String[] args) {
String currentDir = System.getProperty("user.dir");
Path cwd = Paths.get(currentDir);
try (InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);) {
while (true) {
String line = br.readLine();
String[] params = line.split(" ");
switch (params[0]) {
case "cp":
Files.copy(Paths.get(params[1]), Paths.get(params[2]));
break;
case "mv":
Files.move(Paths.get(params[1]), Paths.get(params[2]));
break;
case "rm":
Files.delete(Paths.get(params[1]));
break;
case "cd":
Path newDir = cwd.resolve(params[1]);
if (newDir != null)
cwd = newDir.normalize();
else
System.out.println("Nem létező könyvtár.");
break;
case "ls":
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(cwd)) {
for (Path path : directoryStream)
System.out.println(path);
}
break;
case "pwd":
System.out.println(cwd.toAbsolutePath());
break;
case "exit":
return;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,863 | java | CmdLine.java | Java | [
{
"context": "/*\n * Copyright © 2018. Kövesdán Gábor\n * \n * Az alábbi forráskód a \"Szoftverfejlesztés ",
"end": 38,
"score": 0.9998793601989746,
"start": 24,
"tag": "NAME",
"value": "Kövesdán Gábor"
}
]
| null | []
| /*
* Copyright © 2018. <NAME>
*
* Az alábbi forráskód a "Szoftverfejlesztés Java SE platformon"
* c. könyv második kiadásának (ISBN 978-615-00-2933-7) mellékletét
* képezi. A forráskódot vagy annak részeit a kiadó engedélye nélkül
* tilos reprodukálni, adatrögzítő rendszerben tárolni, bármilyen
* formában vagy eszközzel elektronikus úton vagy más módon közölni.
*/
package com.javaoktato.nio.fileop;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CmdLine {
public static void main(String[] args) {
String currentDir = System.getProperty("user.dir");
Path cwd = Paths.get(currentDir);
try (InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);) {
while (true) {
String line = br.readLine();
String[] params = line.split(" ");
switch (params[0]) {
case "cp":
Files.copy(Paths.get(params[1]), Paths.get(params[2]));
break;
case "mv":
Files.move(Paths.get(params[1]), Paths.get(params[2]));
break;
case "rm":
Files.delete(Paths.get(params[1]));
break;
case "cd":
Path newDir = cwd.resolve(params[1]);
if (newDir != null)
cwd = newDir.normalize();
else
System.out.println("Nem létező könyvtár.");
break;
case "ls":
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(cwd)) {
for (Path path : directoryStream)
System.out.println(path);
}
break;
case "pwd":
System.out.println(cwd.toAbsolutePath());
break;
case "exit":
return;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 1,852 | 0.666667 | 0.653509 | 66 | 26.636364 | 21.273569 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.151515 | false | false | 3 |
ebb406567e65c73f4c9768dcf5c65bfebaa00eec | 31,739,808,332,419 | 9dcd51def19de3b1a13562f98b3106f9d50c3c53 | /src/test/java/com/project/CaseKey/UserTest.java | bc22cb3131daf0150fa2d381fa3471404ad1be50 | []
| no_license | Pakistanp/CaseKey | https://github.com/Pakistanp/CaseKey | 69b3e7cbd4c8052a0e5af37768092c05ec927956 | af791b368d5db2a3bf2ebc3340052abdc59b4fae | refs/heads/master | 2023-03-30T03:00:31.869000 | 2021-03-20T10:08:18 | 2021-03-20T10:08:18 | 304,367,498 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.project.CaseKey;
import com.project.CaseKey.JsonModel.UserInfo;
import com.project.CaseKey.Service.UserService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.springframework.test.util.AssertionErrors.fail;
@SpringBootTest(classes = UserService.class)
public class UserTest {
private final SteamOpenID openid = new SteamOpenID();
@Autowired
private UserService userService;
private final String RESPONSE_QUERY = "openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Flogin&openid.claimed_id=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198042001813&openid.identity=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198042001813&openid.return_to=http%3A%2F%2Flocalhost%3A8080%2Fauthenticate&openid.response_nonce=2020-10-31T15%3A18%3A15ZtpYtz93ipQu0YepzO8kU0jaksEw%3D&openid.assoc_handle=1234567890&openid.signed=signed%2Cop_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle&openid.sig=pBjfd%2FQ%2B12fOjZcCX48hVH%2BO35w%3D";
@Test
void authenticate() {
openid.login("http://localhost:8080/authenticate");
if(openid.verify("http://localhost:8080/authenticate", RESPONSE_QUERY) == null);
fail("Should authenticate correctly");
}
@Test
void getUserInformation() {
UserInfo userInfo = userService.getUserInformationFromApi("76561198042001813");
Assertions.assertEquals("Z-Boku", userInfo.getPersonaName());
}
}
| UTF-8 | Java | 1,700 | java | UserTest.java | Java | []
| null | []
| package com.project.CaseKey;
import com.project.CaseKey.JsonModel.UserInfo;
import com.project.CaseKey.Service.UserService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.springframework.test.util.AssertionErrors.fail;
@SpringBootTest(classes = UserService.class)
public class UserTest {
private final SteamOpenID openid = new SteamOpenID();
@Autowired
private UserService userService;
private final String RESPONSE_QUERY = "openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Flogin&openid.claimed_id=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198042001813&openid.identity=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198042001813&openid.return_to=http%3A%2F%2Flocalhost%3A8080%2Fauthenticate&openid.response_nonce=2020-10-31T15%3A18%3A15ZtpYtz93ipQu0YepzO8kU0jaksEw%3D&openid.assoc_handle=1234567890&openid.signed=signed%2Cop_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle&openid.sig=pBjfd%2FQ%2B12fOjZcCX48hVH%2BO35w%3D";
@Test
void authenticate() {
openid.login("http://localhost:8080/authenticate");
if(openid.verify("http://localhost:8080/authenticate", RESPONSE_QUERY) == null);
fail("Should authenticate correctly");
}
@Test
void getUserInformation() {
UserInfo userInfo = userService.getUserInformationFromApi("76561198042001813");
Assertions.assertEquals("Z-Boku", userInfo.getPersonaName());
}
}
| 1,700 | 0.785882 | 0.703529 | 31 | 53.838711 | 116.447716 | 675 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.580645 | false | false | 3 |
b2c7d1543b5401b8ff9555cc5e2832de22a02bcd | 3,496,103,396,629 | 4a596e993071b256763bb62e4a4734d9c9528834 | /src/main/java/com/karakal/tycms/web/action/terminaladapterAction/ManufacturerAction.java | a9028ad6794ad32bf9a8591abce1ad96613c0f44 | []
| no_license | kkhechao/tycms-web | https://github.com/kkhechao/tycms-web | 1390f3d75b5d779f01296d406c806a66e2310491 | 7493dc10bb727c312fdd6246934ef8c1693bf16d | refs/heads/master | 2020-03-22T01:33:37.781000 | 2018-07-01T08:50:59 | 2018-07-01T08:50:59 | 139,313,529 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.karakal.tycms.web.action.terminaladapterAction;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.karakal.tycms.entity.system.Permission;
import com.karakal.tycms.entity.terminaladapter.ManufacturerEntity;
import com.karakal.tycms.service.publishService.AppversionServices;
import com.karakal.tycms.service.terminaladapterService.ManufacturerService;
import com.karakal.tycms.util.Enum.PublishStatus;
import com.karakal.tycms.util.common.SQLBuilder;
import com.karakal.tycms.util.model.DeleteMessage;
import com.karakal.tycms.util.model.MutilConditionSearch;
import com.karakal.tycms.util.model.ValidateDeleteResponse;
import com.karakal.tycms.util.view.PageView;
import com.karakal.tycms.web.action.BaseAction;
import com.karakal.tycms.web.formbean.terminaladapter.ManufacturerFormBean;
@Controller("manufacturerAction")
@Scope("prototype")
public class ManufacturerAction extends BaseAction<ManufacturerFormBean,ManufacturerEntity> {
private static final long serialVersionUID = 8163626220932395666L;
private ManufacturerFormBean manufacturerFormBean;
private String validatePage;//验证跳转页面
@Resource(name="manufacturerService")
private ManufacturerService manufacturerService;
@Resource(name="appversionServices")
protected AppversionServices appversionServices;
private DeleteMessage deleteMessage;
/**
* 执行单位添加
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="insert")
public String addManufacturer(){
Date now = new Date();
ManufacturerEntity entity = manufacturerFormBean.convertEntity();
entity.setCreateDate(now);
entity.setUpdateDate(now);
entity.setCreateBy(getSessionUser().getUserName());
String ret = manufacturerService.addManufacturer(entity);
setOperatorResult(ret);
return ADD_OK;
}
/**
* 显示添加厂商页面
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="insert")
public String showAdd(){
if(this.manufacturerFormBean == null){
this.manufacturerFormBean = new ManufacturerFormBean();
}
manufacturerFormBean.setManufacturerSort(manufacturerService.getManufacturerMaxSortValue());
/**查所有满足条件的门户**/
List<MutilConditionSearch> p_props = new ArrayList<MutilConditionSearch>();
MutilConditionSearch p_mutilConditionSearch = new MutilConditionSearch("portalStatus","1","=");
p_props.add(p_mutilConditionSearch);
manufacturerFormBean.setPortals(appversionServices.findPortalByConditions(p_props,0));
return ADD_TO;
}
/**
* 根据ID查找厂商
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="update")
public String findManufacturerById(){
ManufacturerEntity entity = manufacturerService.findManufacturerById(manufacturerFormBean.getManufacturerId());
manufacturerFormBean = copySingletonBean(manufacturerFormBean,entity);
/**查所有满足条件的门户**/
List<MutilConditionSearch> p_props = new ArrayList<MutilConditionSearch>();
MutilConditionSearch p_mutilConditionSearch = new MutilConditionSearch("portalStatus","1","=");
p_props.add(p_mutilConditionSearch);
manufacturerFormBean.setPortals(appversionServices.findPortalByConditions(p_props,0));
return UPD_TO;
}
/**
* 厂商分页显示
* @return
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="view")
public String findManufacturerByPage() throws IllegalAccessException, InvocationTargetException{
if(manufacturerFormBean == null){
manufacturerFormBean = new ManufacturerFormBean();
}
PageView<ManufacturerFormBean> fp = manufacturerFormBean.getPageView();
PageView<ManufacturerEntity> ep = new PageView<ManufacturerEntity>();
if(fp != null){
BeanUtils.copyProperties(ep, fp);
}
List<MutilConditionSearch> params = new LinkedList<MutilConditionSearch>();
MutilConditionSearch search = new MutilConditionSearch("manufacturerStatus", PublishStatus.DELETE.getCode().toString(), "!=");
params.add(search);
if(manufacturerFormBean.getManufacturerId() != null){
MutilConditionSearch manufacturerIdSearch = new MutilConditionSearch("manufacturerId", manufacturerFormBean.getManufacturerId().toString(), "=");
params.add(manufacturerIdSearch);
}
if(manufacturerFormBean.getManufacturerName() != null && !manufacturerFormBean.getManufacturerName().equals("")){
MutilConditionSearch manufacturerNameSearch = new MutilConditionSearch("manufacturerName",SQLBuilder.toQueryLike(manufacturerFormBean.getManufacturerName().trim()), "like");
params.add(manufacturerNameSearch);
}
if(manufacturerFormBean.getManufacturerCode() != null && !manufacturerFormBean.getManufacturerCode().equals("")){
MutilConditionSearch manufacturerCodeSearch = new MutilConditionSearch("manufacturerCode", SQLBuilder.toQueryString(manufacturerFormBean.getManufacturerCode().trim()), "=");
params.add(manufacturerCodeSearch);
}
if(manufacturerFormBean.getManufacturerStatus() != null){
MutilConditionSearch manufacturerStatusSearch = new MutilConditionSearch("manufacturerStatus", manufacturerFormBean.getManufacturerStatus().toString(), "=");
params.add(manufacturerStatusSearch);
}
ep = manufacturerService.findByConditions(params, ep, 0);
//ep = manufacturerService.findManufacturerByPage(ep);
if(fp == null){
fp = new PageView<ManufacturerFormBean>();
}
BeanUtils.copyProperties(fp, ep);
fp.setRecords(CopyCollectionBean(fp.getRecords(),ep.getRecords()));
manufacturerFormBean.setPageView(fp);
return GET_OK;
}
/***
* 更新厂商
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="update")
public String updateManufacturer(){
Date now = new Date();
ManufacturerEntity entity = manufacturerFormBean.convertEntity();
entity.setUpdateDate(now);
entity.setUpdateBy(getSessionUser().getUserName());
String ret = manufacturerService.updateManufacturer(entity);
setOperatorResult(ret);
if(selfurl!=null&&!"".equals(selfurl))
return SELFURL;
return UPD_OK;
}
/**
* 修改厂商状态
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="update")
public String onlineManufacturer(){
ManufacturerEntity entity = manufacturerService.findManufacturerById(manufacturerFormBean.getManufacturerId());
entity.setManufacturerStatus(PublishStatus.ONLINE.getCode());
String ret = manufacturerService.updateManufacturer(entity);
setOperatorResult(ret);
if(selfurl!=null&&!"".equals(selfurl))
return SELFURL;
return UPD_OK;
}
/**
* 修改厂商状态
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="update")
public String offlineManufacturer(){
ManufacturerEntity entity = manufacturerService.findManufacturerById(manufacturerFormBean.getManufacturerId());
entity.setManufacturerStatus(PublishStatus.OFFLINE.getCode());
String ret = manufacturerService.updateManufacturer(entity);
setOperatorResult(ret);
if(selfurl!=null&&!"".equals(selfurl))
return SELFURL;
return UPD_OK;
}
/**
* 删除厂商
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="delete")
public String deleteManufacturer(){
String provinceid = manufacturerFormBean.getIds();
String[] ids = provinceid.split(",");
if(ids == null || ids.length == 0){
return DEL_OK;
}
ArrayList<Integer> iids = new ArrayList<Integer>();
//Integer[] idsi = new Integer[ids.length];
for (int i = 0; i < ids.length; i++) {
try {
Integer idd = Integer.parseInt(ids[i]);
ManufacturerEntity entity = manufacturerService.findManufacturerById(idd);
if(entity!=null){
List<ValidateDeleteResponse> validateDelete = manufacturerService.validateDelete(idd);
if(validateDelete == null || validateDelete.size() <= 0){
iids.add(idd);
}else{
this.deleteMessage = new DeleteMessage();
this.deleteMessage.setDeleteName(entity.getManufacturerName());
this.deleteMessage.setDeleteType("厂商");
this.deleteMessage.setDeleteResponse(validateDelete);
return DEL_ERR;
}
}
//entity.setStatus(PublishStatus.OFFLINE.getCode());
//String ret = publishService.updateProvince(entity);
//setOperatorResult(ret);
} catch (Exception e) {
continue;
}
//idsi[i] = Integer.parseInt(ids[i]);
}
String ret = manufacturerService.batchDeleteManufacturer(iids.toArray(new Integer[iids.size()]));
setOperatorResult(ret);
if(selfurl!=null&&!"".equals(selfurl))
return SELFURL;
return DEL_OK;
}
public void validateAddManufacturer(){
validatePage = "/page/terminaladapter/manufacturer_add.jsp";
validatePolicy();
String code = manufacturerFormBean.getManufacturerCode();
if(code!=null&&!"".equals(code)&&this.manufacturerService.findManufacturerByCode(code)!= null){
addFieldError("manufacturerCode", "厂商代码已存在");
}
String name = manufacturerFormBean.getManufacturerName();
if(name!=null&&!"".equals(name)&&this.manufacturerService.findManufacturerByName(name)!= null){
addFieldError("manufacturerName", "厂商名称已存在");
}
/**查所有满足条件的门户**/
List<MutilConditionSearch> p_props = new ArrayList<MutilConditionSearch>();
MutilConditionSearch p_mutilConditionSearch = new MutilConditionSearch("portalStatus","1","=");
p_props.add(p_mutilConditionSearch);
manufacturerFormBean.setPortals(appversionServices.findPortalByConditions(p_props,0));
}
public void validateUpdateManufacturer(){
validatePage = "/page/terminaladapter/manufacturer_edit.jsp";
validatePolicy();
String code = manufacturerFormBean.getManufacturerCode();
ManufacturerEntity entity = this.manufacturerService.findManufacturerById(this.manufacturerFormBean.getManufacturerId());
if(code!=null
&&!"".equals(code)
&&entity.getManufacturerCode()!=null
&&!entity.getManufacturerCode().equals(code)){
if(this.manufacturerService.findManufacturerByCode(code)!= null){
addFieldError("manufacturerCode", "厂商代码已存在");
}
}
String name = manufacturerFormBean.getManufacturerName();
if(name!=null
&&!"".equals(name)
&&entity.getManufacturerName()!=null&&
!entity.getManufacturerName().equals(name)){
if(this.manufacturerService.findManufacturerByCode(code)!= null){
addFieldError("manufacturerName", "厂商名称已存在");
}
}
/**查所有满足条件的门户**/
List<MutilConditionSearch> p_props = new ArrayList<MutilConditionSearch>();
MutilConditionSearch p_mutilConditionSearch = new MutilConditionSearch("portalStatus","1","=");
p_props.add(p_mutilConditionSearch);
manufacturerFormBean.setPortals(appversionServices.findPortalByConditions(p_props,0));
}
private void validatePolicy() {
clearErrorsAndMessages();
if(manufacturerFormBean.getManufacturerName().isEmpty()||manufacturerFormBean.getManufacturerName().length()>500||manufacturerFormBean.getManufacturerName().length()<1){
addFieldError("manufacturerTitle", "厂商名称输入错误,名字长度为不能空,1-500个字符");
}
if(!manufacturerFormBean.getManufacturerCode().isEmpty()&&manufacturerFormBean.getManufacturerCode().length()>64){
addFieldError("Manufactureraddr", "厂商名称输入错误,长度不能超过64个字符");
}
if(this.manufacturerFormBean.getManufacturerSort()!=null&&!this.manufacturerFormBean.getManufacturerSort().toString().matches("[0-9]*")
&&StringUtils.isEmpty(this.manufacturerFormBean.getManufacturerSort().toString())){
addFieldError("manufacturerSort", "厂商序号输入错误,不能为空,长度1-6个数字");
}else if(this.manufacturerFormBean.getManufacturerSort()==null){
addFieldError("manufacturerSort", "厂商序号输入错误,不能为空");
}else if(manufacturerFormBean.getManufacturerSort().toString().length()>6){
addFieldError("manufacturerSort", "厂商序号输入错误,长度1-6个数字");
}
}
private List<ManufacturerFormBean> CopyCollectionBean(List<ManufacturerFormBean> destList,List<ManufacturerEntity> origList) {
destList = new ArrayList<ManufacturerFormBean>();
if(origList.size() > 0){
for(ManufacturerEntity obj : origList){
ManufacturerFormBean destObj = new ManufacturerFormBean();
destList.add(copySingletonBean(destObj, obj));
}
}
return destList;
}
public ManufacturerFormBean getManufacturerFormBean() {
return manufacturerFormBean;
}
public void setManufacturerFormBean(ManufacturerFormBean manufacturerFormBean) {
this.manufacturerFormBean = manufacturerFormBean;
}
public String getValidatePage() {
return validatePage;
}
public void setValidatePage(String validatePage) {
this.validatePage = validatePage;
}
public DeleteMessage getDeleteMessage() {
return deleteMessage;
}
public void setDeleteMessage(DeleteMessage deleteMessage) {
this.deleteMessage = deleteMessage;
}
} | UTF-8 | Java | 13,415 | java | ManufacturerAction.java | Java | []
| null | []
| package com.karakal.tycms.web.action.terminaladapterAction;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.karakal.tycms.entity.system.Permission;
import com.karakal.tycms.entity.terminaladapter.ManufacturerEntity;
import com.karakal.tycms.service.publishService.AppversionServices;
import com.karakal.tycms.service.terminaladapterService.ManufacturerService;
import com.karakal.tycms.util.Enum.PublishStatus;
import com.karakal.tycms.util.common.SQLBuilder;
import com.karakal.tycms.util.model.DeleteMessage;
import com.karakal.tycms.util.model.MutilConditionSearch;
import com.karakal.tycms.util.model.ValidateDeleteResponse;
import com.karakal.tycms.util.view.PageView;
import com.karakal.tycms.web.action.BaseAction;
import com.karakal.tycms.web.formbean.terminaladapter.ManufacturerFormBean;
@Controller("manufacturerAction")
@Scope("prototype")
public class ManufacturerAction extends BaseAction<ManufacturerFormBean,ManufacturerEntity> {
private static final long serialVersionUID = 8163626220932395666L;
private ManufacturerFormBean manufacturerFormBean;
private String validatePage;//验证跳转页面
@Resource(name="manufacturerService")
private ManufacturerService manufacturerService;
@Resource(name="appversionServices")
protected AppversionServices appversionServices;
private DeleteMessage deleteMessage;
/**
* 执行单位添加
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="insert")
public String addManufacturer(){
Date now = new Date();
ManufacturerEntity entity = manufacturerFormBean.convertEntity();
entity.setCreateDate(now);
entity.setUpdateDate(now);
entity.setCreateBy(getSessionUser().getUserName());
String ret = manufacturerService.addManufacturer(entity);
setOperatorResult(ret);
return ADD_OK;
}
/**
* 显示添加厂商页面
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="insert")
public String showAdd(){
if(this.manufacturerFormBean == null){
this.manufacturerFormBean = new ManufacturerFormBean();
}
manufacturerFormBean.setManufacturerSort(manufacturerService.getManufacturerMaxSortValue());
/**查所有满足条件的门户**/
List<MutilConditionSearch> p_props = new ArrayList<MutilConditionSearch>();
MutilConditionSearch p_mutilConditionSearch = new MutilConditionSearch("portalStatus","1","=");
p_props.add(p_mutilConditionSearch);
manufacturerFormBean.setPortals(appversionServices.findPortalByConditions(p_props,0));
return ADD_TO;
}
/**
* 根据ID查找厂商
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="update")
public String findManufacturerById(){
ManufacturerEntity entity = manufacturerService.findManufacturerById(manufacturerFormBean.getManufacturerId());
manufacturerFormBean = copySingletonBean(manufacturerFormBean,entity);
/**查所有满足条件的门户**/
List<MutilConditionSearch> p_props = new ArrayList<MutilConditionSearch>();
MutilConditionSearch p_mutilConditionSearch = new MutilConditionSearch("portalStatus","1","=");
p_props.add(p_mutilConditionSearch);
manufacturerFormBean.setPortals(appversionServices.findPortalByConditions(p_props,0));
return UPD_TO;
}
/**
* 厂商分页显示
* @return
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="view")
public String findManufacturerByPage() throws IllegalAccessException, InvocationTargetException{
if(manufacturerFormBean == null){
manufacturerFormBean = new ManufacturerFormBean();
}
PageView<ManufacturerFormBean> fp = manufacturerFormBean.getPageView();
PageView<ManufacturerEntity> ep = new PageView<ManufacturerEntity>();
if(fp != null){
BeanUtils.copyProperties(ep, fp);
}
List<MutilConditionSearch> params = new LinkedList<MutilConditionSearch>();
MutilConditionSearch search = new MutilConditionSearch("manufacturerStatus", PublishStatus.DELETE.getCode().toString(), "!=");
params.add(search);
if(manufacturerFormBean.getManufacturerId() != null){
MutilConditionSearch manufacturerIdSearch = new MutilConditionSearch("manufacturerId", manufacturerFormBean.getManufacturerId().toString(), "=");
params.add(manufacturerIdSearch);
}
if(manufacturerFormBean.getManufacturerName() != null && !manufacturerFormBean.getManufacturerName().equals("")){
MutilConditionSearch manufacturerNameSearch = new MutilConditionSearch("manufacturerName",SQLBuilder.toQueryLike(manufacturerFormBean.getManufacturerName().trim()), "like");
params.add(manufacturerNameSearch);
}
if(manufacturerFormBean.getManufacturerCode() != null && !manufacturerFormBean.getManufacturerCode().equals("")){
MutilConditionSearch manufacturerCodeSearch = new MutilConditionSearch("manufacturerCode", SQLBuilder.toQueryString(manufacturerFormBean.getManufacturerCode().trim()), "=");
params.add(manufacturerCodeSearch);
}
if(manufacturerFormBean.getManufacturerStatus() != null){
MutilConditionSearch manufacturerStatusSearch = new MutilConditionSearch("manufacturerStatus", manufacturerFormBean.getManufacturerStatus().toString(), "=");
params.add(manufacturerStatusSearch);
}
ep = manufacturerService.findByConditions(params, ep, 0);
//ep = manufacturerService.findManufacturerByPage(ep);
if(fp == null){
fp = new PageView<ManufacturerFormBean>();
}
BeanUtils.copyProperties(fp, ep);
fp.setRecords(CopyCollectionBean(fp.getRecords(),ep.getRecords()));
manufacturerFormBean.setPageView(fp);
return GET_OK;
}
/***
* 更新厂商
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="update")
public String updateManufacturer(){
Date now = new Date();
ManufacturerEntity entity = manufacturerFormBean.convertEntity();
entity.setUpdateDate(now);
entity.setUpdateBy(getSessionUser().getUserName());
String ret = manufacturerService.updateManufacturer(entity);
setOperatorResult(ret);
if(selfurl!=null&&!"".equals(selfurl))
return SELFURL;
return UPD_OK;
}
/**
* 修改厂商状态
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="update")
public String onlineManufacturer(){
ManufacturerEntity entity = manufacturerService.findManufacturerById(manufacturerFormBean.getManufacturerId());
entity.setManufacturerStatus(PublishStatus.ONLINE.getCode());
String ret = manufacturerService.updateManufacturer(entity);
setOperatorResult(ret);
if(selfurl!=null&&!"".equals(selfurl))
return SELFURL;
return UPD_OK;
}
/**
* 修改厂商状态
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="update")
public String offlineManufacturer(){
ManufacturerEntity entity = manufacturerService.findManufacturerById(manufacturerFormBean.getManufacturerId());
entity.setManufacturerStatus(PublishStatus.OFFLINE.getCode());
String ret = manufacturerService.updateManufacturer(entity);
setOperatorResult(ret);
if(selfurl!=null&&!"".equals(selfurl))
return SELFURL;
return UPD_OK;
}
/**
* 删除厂商
* @return
*/
@Permission(module="terminaladapter.manufacturer_management",privilege="delete")
public String deleteManufacturer(){
String provinceid = manufacturerFormBean.getIds();
String[] ids = provinceid.split(",");
if(ids == null || ids.length == 0){
return DEL_OK;
}
ArrayList<Integer> iids = new ArrayList<Integer>();
//Integer[] idsi = new Integer[ids.length];
for (int i = 0; i < ids.length; i++) {
try {
Integer idd = Integer.parseInt(ids[i]);
ManufacturerEntity entity = manufacturerService.findManufacturerById(idd);
if(entity!=null){
List<ValidateDeleteResponse> validateDelete = manufacturerService.validateDelete(idd);
if(validateDelete == null || validateDelete.size() <= 0){
iids.add(idd);
}else{
this.deleteMessage = new DeleteMessage();
this.deleteMessage.setDeleteName(entity.getManufacturerName());
this.deleteMessage.setDeleteType("厂商");
this.deleteMessage.setDeleteResponse(validateDelete);
return DEL_ERR;
}
}
//entity.setStatus(PublishStatus.OFFLINE.getCode());
//String ret = publishService.updateProvince(entity);
//setOperatorResult(ret);
} catch (Exception e) {
continue;
}
//idsi[i] = Integer.parseInt(ids[i]);
}
String ret = manufacturerService.batchDeleteManufacturer(iids.toArray(new Integer[iids.size()]));
setOperatorResult(ret);
if(selfurl!=null&&!"".equals(selfurl))
return SELFURL;
return DEL_OK;
}
public void validateAddManufacturer(){
validatePage = "/page/terminaladapter/manufacturer_add.jsp";
validatePolicy();
String code = manufacturerFormBean.getManufacturerCode();
if(code!=null&&!"".equals(code)&&this.manufacturerService.findManufacturerByCode(code)!= null){
addFieldError("manufacturerCode", "厂商代码已存在");
}
String name = manufacturerFormBean.getManufacturerName();
if(name!=null&&!"".equals(name)&&this.manufacturerService.findManufacturerByName(name)!= null){
addFieldError("manufacturerName", "厂商名称已存在");
}
/**查所有满足条件的门户**/
List<MutilConditionSearch> p_props = new ArrayList<MutilConditionSearch>();
MutilConditionSearch p_mutilConditionSearch = new MutilConditionSearch("portalStatus","1","=");
p_props.add(p_mutilConditionSearch);
manufacturerFormBean.setPortals(appversionServices.findPortalByConditions(p_props,0));
}
public void validateUpdateManufacturer(){
validatePage = "/page/terminaladapter/manufacturer_edit.jsp";
validatePolicy();
String code = manufacturerFormBean.getManufacturerCode();
ManufacturerEntity entity = this.manufacturerService.findManufacturerById(this.manufacturerFormBean.getManufacturerId());
if(code!=null
&&!"".equals(code)
&&entity.getManufacturerCode()!=null
&&!entity.getManufacturerCode().equals(code)){
if(this.manufacturerService.findManufacturerByCode(code)!= null){
addFieldError("manufacturerCode", "厂商代码已存在");
}
}
String name = manufacturerFormBean.getManufacturerName();
if(name!=null
&&!"".equals(name)
&&entity.getManufacturerName()!=null&&
!entity.getManufacturerName().equals(name)){
if(this.manufacturerService.findManufacturerByCode(code)!= null){
addFieldError("manufacturerName", "厂商名称已存在");
}
}
/**查所有满足条件的门户**/
List<MutilConditionSearch> p_props = new ArrayList<MutilConditionSearch>();
MutilConditionSearch p_mutilConditionSearch = new MutilConditionSearch("portalStatus","1","=");
p_props.add(p_mutilConditionSearch);
manufacturerFormBean.setPortals(appversionServices.findPortalByConditions(p_props,0));
}
private void validatePolicy() {
clearErrorsAndMessages();
if(manufacturerFormBean.getManufacturerName().isEmpty()||manufacturerFormBean.getManufacturerName().length()>500||manufacturerFormBean.getManufacturerName().length()<1){
addFieldError("manufacturerTitle", "厂商名称输入错误,名字长度为不能空,1-500个字符");
}
if(!manufacturerFormBean.getManufacturerCode().isEmpty()&&manufacturerFormBean.getManufacturerCode().length()>64){
addFieldError("Manufactureraddr", "厂商名称输入错误,长度不能超过64个字符");
}
if(this.manufacturerFormBean.getManufacturerSort()!=null&&!this.manufacturerFormBean.getManufacturerSort().toString().matches("[0-9]*")
&&StringUtils.isEmpty(this.manufacturerFormBean.getManufacturerSort().toString())){
addFieldError("manufacturerSort", "厂商序号输入错误,不能为空,长度1-6个数字");
}else if(this.manufacturerFormBean.getManufacturerSort()==null){
addFieldError("manufacturerSort", "厂商序号输入错误,不能为空");
}else if(manufacturerFormBean.getManufacturerSort().toString().length()>6){
addFieldError("manufacturerSort", "厂商序号输入错误,长度1-6个数字");
}
}
private List<ManufacturerFormBean> CopyCollectionBean(List<ManufacturerFormBean> destList,List<ManufacturerEntity> origList) {
destList = new ArrayList<ManufacturerFormBean>();
if(origList.size() > 0){
for(ManufacturerEntity obj : origList){
ManufacturerFormBean destObj = new ManufacturerFormBean();
destList.add(copySingletonBean(destObj, obj));
}
}
return destList;
}
public ManufacturerFormBean getManufacturerFormBean() {
return manufacturerFormBean;
}
public void setManufacturerFormBean(ManufacturerFormBean manufacturerFormBean) {
this.manufacturerFormBean = manufacturerFormBean;
}
public String getValidatePage() {
return validatePage;
}
public void setValidatePage(String validatePage) {
this.validatePage = validatePage;
}
public DeleteMessage getDeleteMessage() {
return deleteMessage;
}
public void setDeleteMessage(DeleteMessage deleteMessage) {
this.deleteMessage = deleteMessage;
}
} | 13,415 | 0.765669 | 0.761747 | 328 | 38.646343 | 34.830818 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.381098 | false | false | 3 |
9753f1987bfc2d76adfec28106117826a1fcf449 | 33,569,464,412,734 | 64ef5651e1fca84cb8f777a09f7f1f57937c7037 | /app/src/main/java/com/example/thomas/artifact/AddStudents.java | c99b70aa7b1f8a4f9a878ca4e025ae1bba127382 | []
| no_license | Th0masW/Artifact | https://github.com/Th0masW/Artifact | a78ed9879889c254de7941b9ee1101471e863019 | 91af34176b125c189ea8c8a062bd198de0c91ecd | refs/heads/master | 2021-04-28T01:29:06.527000 | 2018-04-11T02:02:54 | 2018-04-11T02:02:54 | 122,278,236 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.thomas.artifact;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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.database.IgnoreExtraProperties;
import java.util.HashMap;
public class AddStudents extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText addStudentName;
private EditText studentGrade;
private DatabaseReference studentDB;
private Boolean allSaved;
@IgnoreExtraProperties
public class Student {
public String studentName;
public Student() {
//default constructor
}
public Student(String studentName) {
this.studentName = studentName;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Make sure user is logged in
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
//Redirect to login page
if(currentUser == null) {
//create login intent
Intent loginIntent = new Intent(AddStudents.this, Login.class);
startActivity(loginIntent);
finish();
}
setContentView(R.layout.activity_add_students);
mAuth = FirebaseAuth.getInstance();
addStudentName = findViewById(R.id.add_student_text_box);
studentGrade = findViewById(R.id.grade_text_box);
studentDB = FirebaseDatabase.getInstance().getReference().child("Student");
allSaved = null;
setTitle("Add Student");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.home) {
sendToMain();
} else if(item.getItemId() == R.id.capture_evidence) {
Intent go = new Intent(AddStudents.this, CaptureMyEvidence.class);
startActivity(go);
finish();
}else if(item.getItemId() == R.id.review_evidence) {
Intent go = new Intent(AddStudents.this, ReviewEvidence.class);
startActivity(go);
finish();
}else if(item.getItemId() == R.id.add_students) {
Intent go = new Intent(AddStudents.this, AddStudents.class);
startActivity(go);
finish();
}else if(item.getItemId() == R.id.edit_student) {
Intent go = new Intent(AddStudents.this, PickStudent.class);
startActivity(go);
finish();
}else if(item.getItemId() == R.id.log_out) {
FirebaseAuth.getInstance().signOut();
sendToMain();
}
return true;
}
public void addStudent(View view) {
String name = addStudentName.getText().toString();
String grade = studentGrade.getText().toString();
Log.e("AddStudents", "Student name: " + name);
Log.e("AddStudents", "Student grade: " + grade);
HashMap<String, String> datamap = new HashMap<>();
datamap.put("Name", name);
datamap.put("Grade", grade);
if(TextUtils.isEmpty(name)) {addStudentName.setError("This can not be blank");}
else
{
// add to "student" node
insertIntoDatabase(name);
// communicate if saved
if (allSaved== null) {
Toast.makeText(AddStudents.this,name + " has been added", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AddStudents.this,"Error: student could not be added. " +
"Make sure to use a unique name.", Toast.LENGTH_LONG).show();
}
//finished, return to main page
sendToMain();
}
}
private void insertIntoDatabase(String name) {
studentDB.push().setValue(name).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
} else {
allSaved = false;
}
}
});
}
@Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null) {
//create login intent
Intent loginIntent = new Intent(AddStudents.this, Login.class);
startActivity(loginIntent);
finish();
}
}
private void sendToMain() {
Intent mainIntent = new Intent(AddStudents.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
} | UTF-8 | Java | 5,321 | java | AddStudents.java | Java | []
| null | []
| package com.example.thomas.artifact;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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.database.IgnoreExtraProperties;
import java.util.HashMap;
public class AddStudents extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText addStudentName;
private EditText studentGrade;
private DatabaseReference studentDB;
private Boolean allSaved;
@IgnoreExtraProperties
public class Student {
public String studentName;
public Student() {
//default constructor
}
public Student(String studentName) {
this.studentName = studentName;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Make sure user is logged in
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
//Redirect to login page
if(currentUser == null) {
//create login intent
Intent loginIntent = new Intent(AddStudents.this, Login.class);
startActivity(loginIntent);
finish();
}
setContentView(R.layout.activity_add_students);
mAuth = FirebaseAuth.getInstance();
addStudentName = findViewById(R.id.add_student_text_box);
studentGrade = findViewById(R.id.grade_text_box);
studentDB = FirebaseDatabase.getInstance().getReference().child("Student");
allSaved = null;
setTitle("Add Student");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.home) {
sendToMain();
} else if(item.getItemId() == R.id.capture_evidence) {
Intent go = new Intent(AddStudents.this, CaptureMyEvidence.class);
startActivity(go);
finish();
}else if(item.getItemId() == R.id.review_evidence) {
Intent go = new Intent(AddStudents.this, ReviewEvidence.class);
startActivity(go);
finish();
}else if(item.getItemId() == R.id.add_students) {
Intent go = new Intent(AddStudents.this, AddStudents.class);
startActivity(go);
finish();
}else if(item.getItemId() == R.id.edit_student) {
Intent go = new Intent(AddStudents.this, PickStudent.class);
startActivity(go);
finish();
}else if(item.getItemId() == R.id.log_out) {
FirebaseAuth.getInstance().signOut();
sendToMain();
}
return true;
}
public void addStudent(View view) {
String name = addStudentName.getText().toString();
String grade = studentGrade.getText().toString();
Log.e("AddStudents", "Student name: " + name);
Log.e("AddStudents", "Student grade: " + grade);
HashMap<String, String> datamap = new HashMap<>();
datamap.put("Name", name);
datamap.put("Grade", grade);
if(TextUtils.isEmpty(name)) {addStudentName.setError("This can not be blank");}
else
{
// add to "student" node
insertIntoDatabase(name);
// communicate if saved
if (allSaved== null) {
Toast.makeText(AddStudents.this,name + " has been added", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AddStudents.this,"Error: student could not be added. " +
"Make sure to use a unique name.", Toast.LENGTH_LONG).show();
}
//finished, return to main page
sendToMain();
}
}
private void insertIntoDatabase(String name) {
studentDB.push().setValue(name).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
} else {
allSaved = false;
}
}
});
}
@Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null) {
//create login intent
Intent loginIntent = new Intent(AddStudents.this, Login.class);
startActivity(loginIntent);
finish();
}
}
private void sendToMain() {
Intent mainIntent = new Intent(AddStudents.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
} | 5,321 | 0.61605 | 0.615862 | 167 | 30.868263 | 24.096252 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.580838 | false | false | 3 |
3abbdda318ba060394fbbf6864269ad572156ac5 | 28,827,820,496,302 | 3032edbc7a7077418cc4e43d15971ff993613284 | /com-xyf-service/src/main/java/com/xyf/service/AdminService.java | 0f119dc6a9d3f76abf6f52897d140ee173c66cdb | []
| no_license | RAOE/RunnerManager | https://github.com/RAOE/RunnerManager | 13bdf7a933fa6746a919cf892d66f970f9201819 | 2e5777ad89f55501e3e43a67d2054664909196a6 | refs/heads/master | 2022-12-26T04:45:15.154000 | 2021-12-13T05:20:32 | 2021-12-13T05:20:32 | 127,129,249 | 294 | 34 | null | false | 2022-12-16T09:45:08 | 2018-03-28T11:20:12 | 2022-11-17T01:22:43 | 2022-12-16T09:45:07 | 71,200 | 181 | 33 | 17 | Java | false | false | package com.xyf.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xyf.mapper.AdminMapper;
import com.xyf.mapper.UserMapper;
import com.xyf.pojo.Admin;
import com.xyf.utils.CommonUtils;
import redis.clients.jedis.Protocol.Command;
@Service
public class AdminService extends BaseService<Admin>{
@Autowired
private AdminMapper adminMapper;
/**
* 检查账号密码的方法
* @param account
* @param password
* @return
*/
public Admin checkPassword(String name,String password)
{
//先判断值是否为空
if(CommonUtils.isEmpty(name)||CommonUtils.isEmail(password))
{
return null;
}
//开始登陆
else
{
Admin admin=new Admin();
admin.setName(name);
admin.setPassword(password);
admin=selectOne(admin);
if(admin!=null)
{
return admin;
}
return null;
}
}
public List<Admin> select(Admin admin) {
return adminMapper.select(admin);
}
}
| UTF-8 | Java | 1,120 | java | AdminService.java | Java | [
{
"context": "\n \tadmin.setName(name);\n \tadmin.setPassword(password);\n admin=selectOne(admin);\n \tif(admin!=",
"end": 853,
"score": 0.9925196170806885,
"start": 845,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.xyf.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xyf.mapper.AdminMapper;
import com.xyf.mapper.UserMapper;
import com.xyf.pojo.Admin;
import com.xyf.utils.CommonUtils;
import redis.clients.jedis.Protocol.Command;
@Service
public class AdminService extends BaseService<Admin>{
@Autowired
private AdminMapper adminMapper;
/**
* 检查账号密码的方法
* @param account
* @param password
* @return
*/
public Admin checkPassword(String name,String password)
{
//先判断值是否为空
if(CommonUtils.isEmpty(name)||CommonUtils.isEmail(password))
{
return null;
}
//开始登陆
else
{
Admin admin=new Admin();
admin.setName(name);
admin.setPassword(<PASSWORD>);
admin=selectOne(admin);
if(admin!=null)
{
return admin;
}
return null;
}
}
public List<Admin> select(Admin admin) {
return adminMapper.select(admin);
}
}
| 1,122 | 0.650278 | 0.650278 | 59 | 17.271187 | 17.188713 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.915254 | false | false | 3 |
c060f04c81409094719097eeef6bdff91e8116f9 | 24,498,493,483,506 | 4e6a1c69b4c1b2481ad356e4a30f46dd9b065f70 | /com/peter/algo/level1test/MultipleTest.java | 3debbb6331942547462a9a43df562a31103b2d88 | []
| no_license | peter0618/Programmers | https://github.com/peter0618/Programmers | 59c503792255608b0ae073d00c26d576f2462067 | 91a60cc4683ed454d558536973e8e5f52727022c | refs/heads/master | 2020-08-17T20:32:03.985000 | 2020-07-02T14:08:03 | 2020-07-02T14:08:03 | 215,708,761 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.peter.algo.level1test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.peter.algo.level1.Multiple;
class MultipleTest {
@Test
void testSolution1() {
Multiple multiple = new Multiple();
assertArrayEquals(
new int[] {5, 10},
multiple.solution1(new int[] {5,9,7,10}, 5)
);
}
@Test
void testSolution2() {
Multiple multiple = new Multiple();
assertArrayEquals(
new int[] {1,2,3,36},
multiple.solution1(new int[] {2,36,1,3}, 1)
);
}
@Test
void testSolution3() {
Multiple multiple = new Multiple();
assertArrayEquals(
new int[] {-1},
multiple.solution1(new int[] {3,2,6}, 10)
);
}
}
| UTF-8 | Java | 718 | java | MultipleTest.java | Java | []
| null | []
| package com.peter.algo.level1test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.peter.algo.level1.Multiple;
class MultipleTest {
@Test
void testSolution1() {
Multiple multiple = new Multiple();
assertArrayEquals(
new int[] {5, 10},
multiple.solution1(new int[] {5,9,7,10}, 5)
);
}
@Test
void testSolution2() {
Multiple multiple = new Multiple();
assertArrayEquals(
new int[] {1,2,3,36},
multiple.solution1(new int[] {2,36,1,3}, 1)
);
}
@Test
void testSolution3() {
Multiple multiple = new Multiple();
assertArrayEquals(
new int[] {-1},
multiple.solution1(new int[] {3,2,6}, 10)
);
}
}
| 718 | 0.632312 | 0.584958 | 44 | 15.318182 | 16.074787 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.113636 | false | false | 3 |
1ea69e4c167b2f50aa9154fcfc6654650912d13f | 747,324,329,929 | dac8684cd73a8bbab99ec9cd8a21a19e1a48a2cb | /online-store/src/main/java/com/ztgg/ecommerce/dao/ProductImgDao.java | 122ded62e6656f874b31f335aea2581b258c2c42 | []
| no_license | aaronyan0328/e-commerce-project | https://github.com/aaronyan0328/e-commerce-project | 4c1947294ead9b1c58f23487dd05b4da027c74b6 | 954316b49b67a5ebb2e12075ca71d7843f478ec9 | refs/heads/main | 2023-02-22T07:26:07.111000 | 2021-01-25T22:01:41 | 2021-01-25T22:01:41 | 311,533,230 | 1 | 0 | null | true | 2020-11-10T03:21:30 | 2020-11-10T03:21:30 | 2020-10-20T02:25:33 | 2020-10-20T02:25:30 | 0 | 0 | 0 | 0 | null | false | false | package com.ztgg.ecommerce.dao;
import java.util.List;
import com.ztgg.ecommerce.entity.ProductImg;
public interface ProductImgDao {
/**
* this function returns a list of ProductImg
* @return ProductImgList
*/
List<ProductImg> queryProductImg();
}
| UTF-8 | Java | 259 | java | ProductImgDao.java | Java | []
| null | []
| package com.ztgg.ecommerce.dao;
import java.util.List;
import com.ztgg.ecommerce.entity.ProductImg;
public interface ProductImgDao {
/**
* this function returns a list of ProductImg
* @return ProductImgList
*/
List<ProductImg> queryProductImg();
}
| 259 | 0.752896 | 0.752896 | 13 | 18.923077 | 17.255819 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 3 |
37084ebe53efe64c46f99a6d43204702aa340d54 | 26,757,646,280,340 | 9a52fe3bcdd090a396e59c68c63130f32c54a7a8 | /sources/com/applovin/impl/adview/C0887r.java | bb63abac7068e7c16406d029070363d844bb8071 | []
| no_license | mzkh/LudoKing | https://github.com/mzkh/LudoKing | 19d7c76a298ee5bd1454736063bc392e103a8203 | ee0d0e75ed9fa8894ed9877576d8e5589813b1ba | refs/heads/master | 2022-04-25T06:08:41.916000 | 2020-04-14T17:00:45 | 2020-04-14T17:00:45 | 255,670,636 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.applovin.impl.adview;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Bundle;
import com.applovin.impl.p005a.C0769a;
import com.applovin.impl.p005a.C0769a.C0773c;
import com.applovin.impl.p005a.C0776d;
import com.applovin.impl.p005a.C0780g;
import com.applovin.impl.p005a.C0781h;
import com.applovin.impl.p005a.C0782i;
import com.applovin.impl.p005a.C0786k;
import com.applovin.impl.sdk.C1227o;
import com.applovin.impl.sdk.p019b.C1096c;
import com.tapjoy.TJAdUnitConstants.String;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/* renamed from: com.applovin.impl.adview.r */
public class C0887r extends C0842m {
/* renamed from: a */
private final Set<C0780g> f1609a = new HashSet();
/* renamed from: a */
private void m1345a() {
if (isFullyWatched() && !this.f1609a.isEmpty()) {
C1227o oVar = this.logger;
StringBuilder sb = new StringBuilder();
sb.append("Firing ");
sb.append(this.f1609a.size());
sb.append(" un-fired video progress trackers when video was completed.");
oVar.mo10381d("InterstitialActivity", sb.toString());
m1350a(this.f1609a);
}
}
/* renamed from: a */
private void m1346a(C0773c cVar) {
m1347a(cVar, C0776d.UNSPECIFIED);
}
/* renamed from: a */
private void m1347a(C0773c cVar, C0776d dVar) {
m1349a(cVar, "", dVar);
}
/* renamed from: a */
private void m1348a(C0773c cVar, String str) {
m1349a(cVar, str, C0776d.UNSPECIFIED);
}
/* renamed from: a */
private void m1349a(C0773c cVar, String str, C0776d dVar) {
if (isVastAd()) {
m1351a(((C0769a) this.currentAd).mo8875a(cVar, str), dVar);
}
}
/* renamed from: a */
private void m1350a(Set<C0780g> set) {
m1351a(set, C0776d.UNSPECIFIED);
}
/* renamed from: a */
private void m1351a(Set<C0780g> set, C0776d dVar) {
if (isVastAd() && set != null && !set.isEmpty()) {
long seconds = TimeUnit.MILLISECONDS.toSeconds((long) this.videoView.getCurrentPosition());
C0786k i = m1352b().mo8895i();
Uri a = i != null ? i.mo8958a() : null;
C1227o oVar = this.logger;
StringBuilder sb = new StringBuilder();
sb.append("Firing ");
sb.append(set.size());
sb.append(" tracker(s): ");
sb.append(set);
oVar.mo10378b("InterstitialActivity", sb.toString());
C0782i.m1083a(set, seconds, a, dVar, this.sdk);
}
}
/* renamed from: b */
private C0769a m1352b() {
if (this.currentAd instanceof C0769a) {
return (C0769a) this.currentAd;
}
return null;
}
public void clickThroughFromVideo(PointF pointF) {
super.clickThroughFromVideo(pointF);
m1346a(C0773c.VIDEO_CLICK);
}
public void dismiss() {
if (isVastAd()) {
C0773c cVar = C0773c.VIDEO;
String str = String.CLOSE;
m1348a(cVar, str);
m1348a(C0773c.COMPANION, str);
}
super.dismiss();
}
public void handleCountdownStep() {
if (isVastAd()) {
long seconds = ((long) this.computedLengthSeconds) - TimeUnit.MILLISECONDS.toSeconds((long) (this.videoView.getDuration() - this.videoView.getCurrentPosition()));
HashSet hashSet = new HashSet();
for (C0780g gVar : new HashSet(this.f1609a)) {
if (gVar.mo8942a(seconds, getVideoPercentViewed())) {
hashSet.add(gVar);
this.f1609a.remove(gVar);
}
}
m1350a((Set<C0780g>) hashSet);
}
}
public void handleMediaError(String str) {
m1347a(C0773c.ERROR, C0776d.MEDIA_FILE_ERROR);
super.handleMediaError(str);
}
/* access modifiers changed from: protected */
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (isVastAd()) {
this.f1609a.addAll(m1352b().mo8876a(C0773c.VIDEO, C0781h.f1292a));
m1346a(C0773c.IMPRESSION);
m1348a(C0773c.VIDEO, "creativeView");
}
}
public void playVideo() {
this.countdownManager.mo9084a("PROGRESS_TRACKING", ((Long) this.sdk.mo10202a(C1096c.f2500eF)).longValue(), (C0830a) new C0830a() {
/* renamed from: a */
public void mo9088a() {
C0887r.this.handleCountdownStep();
}
/* renamed from: b */
public boolean mo9089b() {
return C0887r.this.shouldContinueFullLengthVideoCountdown();
}
});
super.playVideo();
}
public void showPoststitial() {
if (isVastAd()) {
m1345a();
if (!C0782i.m1090c(m1352b())) {
dismiss();
return;
} else if (!this.poststitialWasDisplayed) {
m1348a(C0773c.COMPANION, "creativeView");
} else {
return;
}
}
super.showPoststitial();
}
public void skipVideo() {
m1348a(C0773c.VIDEO, "skip");
super.skipVideo();
}
public void toggleMute() {
String str;
C0773c cVar;
super.toggleMute();
if (this.videoMuted) {
cVar = C0773c.VIDEO;
str = "mute";
} else {
cVar = C0773c.VIDEO;
str = "unmute";
}
m1348a(cVar, str);
}
}
| UTF-8 | Java | 5,635 | java | C0887r.java | Java | []
| null | []
| package com.applovin.impl.adview;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Bundle;
import com.applovin.impl.p005a.C0769a;
import com.applovin.impl.p005a.C0769a.C0773c;
import com.applovin.impl.p005a.C0776d;
import com.applovin.impl.p005a.C0780g;
import com.applovin.impl.p005a.C0781h;
import com.applovin.impl.p005a.C0782i;
import com.applovin.impl.p005a.C0786k;
import com.applovin.impl.sdk.C1227o;
import com.applovin.impl.sdk.p019b.C1096c;
import com.tapjoy.TJAdUnitConstants.String;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/* renamed from: com.applovin.impl.adview.r */
public class C0887r extends C0842m {
/* renamed from: a */
private final Set<C0780g> f1609a = new HashSet();
/* renamed from: a */
private void m1345a() {
if (isFullyWatched() && !this.f1609a.isEmpty()) {
C1227o oVar = this.logger;
StringBuilder sb = new StringBuilder();
sb.append("Firing ");
sb.append(this.f1609a.size());
sb.append(" un-fired video progress trackers when video was completed.");
oVar.mo10381d("InterstitialActivity", sb.toString());
m1350a(this.f1609a);
}
}
/* renamed from: a */
private void m1346a(C0773c cVar) {
m1347a(cVar, C0776d.UNSPECIFIED);
}
/* renamed from: a */
private void m1347a(C0773c cVar, C0776d dVar) {
m1349a(cVar, "", dVar);
}
/* renamed from: a */
private void m1348a(C0773c cVar, String str) {
m1349a(cVar, str, C0776d.UNSPECIFIED);
}
/* renamed from: a */
private void m1349a(C0773c cVar, String str, C0776d dVar) {
if (isVastAd()) {
m1351a(((C0769a) this.currentAd).mo8875a(cVar, str), dVar);
}
}
/* renamed from: a */
private void m1350a(Set<C0780g> set) {
m1351a(set, C0776d.UNSPECIFIED);
}
/* renamed from: a */
private void m1351a(Set<C0780g> set, C0776d dVar) {
if (isVastAd() && set != null && !set.isEmpty()) {
long seconds = TimeUnit.MILLISECONDS.toSeconds((long) this.videoView.getCurrentPosition());
C0786k i = m1352b().mo8895i();
Uri a = i != null ? i.mo8958a() : null;
C1227o oVar = this.logger;
StringBuilder sb = new StringBuilder();
sb.append("Firing ");
sb.append(set.size());
sb.append(" tracker(s): ");
sb.append(set);
oVar.mo10378b("InterstitialActivity", sb.toString());
C0782i.m1083a(set, seconds, a, dVar, this.sdk);
}
}
/* renamed from: b */
private C0769a m1352b() {
if (this.currentAd instanceof C0769a) {
return (C0769a) this.currentAd;
}
return null;
}
public void clickThroughFromVideo(PointF pointF) {
super.clickThroughFromVideo(pointF);
m1346a(C0773c.VIDEO_CLICK);
}
public void dismiss() {
if (isVastAd()) {
C0773c cVar = C0773c.VIDEO;
String str = String.CLOSE;
m1348a(cVar, str);
m1348a(C0773c.COMPANION, str);
}
super.dismiss();
}
public void handleCountdownStep() {
if (isVastAd()) {
long seconds = ((long) this.computedLengthSeconds) - TimeUnit.MILLISECONDS.toSeconds((long) (this.videoView.getDuration() - this.videoView.getCurrentPosition()));
HashSet hashSet = new HashSet();
for (C0780g gVar : new HashSet(this.f1609a)) {
if (gVar.mo8942a(seconds, getVideoPercentViewed())) {
hashSet.add(gVar);
this.f1609a.remove(gVar);
}
}
m1350a((Set<C0780g>) hashSet);
}
}
public void handleMediaError(String str) {
m1347a(C0773c.ERROR, C0776d.MEDIA_FILE_ERROR);
super.handleMediaError(str);
}
/* access modifiers changed from: protected */
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (isVastAd()) {
this.f1609a.addAll(m1352b().mo8876a(C0773c.VIDEO, C0781h.f1292a));
m1346a(C0773c.IMPRESSION);
m1348a(C0773c.VIDEO, "creativeView");
}
}
public void playVideo() {
this.countdownManager.mo9084a("PROGRESS_TRACKING", ((Long) this.sdk.mo10202a(C1096c.f2500eF)).longValue(), (C0830a) new C0830a() {
/* renamed from: a */
public void mo9088a() {
C0887r.this.handleCountdownStep();
}
/* renamed from: b */
public boolean mo9089b() {
return C0887r.this.shouldContinueFullLengthVideoCountdown();
}
});
super.playVideo();
}
public void showPoststitial() {
if (isVastAd()) {
m1345a();
if (!C0782i.m1090c(m1352b())) {
dismiss();
return;
} else if (!this.poststitialWasDisplayed) {
m1348a(C0773c.COMPANION, "creativeView");
} else {
return;
}
}
super.showPoststitial();
}
public void skipVideo() {
m1348a(C0773c.VIDEO, "skip");
super.skipVideo();
}
public void toggleMute() {
String str;
C0773c cVar;
super.toggleMute();
if (this.videoMuted) {
cVar = C0773c.VIDEO;
str = "mute";
} else {
cVar = C0773c.VIDEO;
str = "unmute";
}
m1348a(cVar, str);
}
}
| 5,635 | 0.566815 | 0.486779 | 183 | 29.792349 | 23.907621 | 174 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.606557 | false | false | 3 |
52db9e8ec280d6010b82c499421bc736336efab6 | 7,017,976,580,117 | 22f01e92ad3fb05d0b8439c86992e470b4a29d5c | /Java/javaWorkspace/com.ebroker.clientcima/src/test/java/com/ebroker/clientcima/fer.java | ad5ed6ac20f527182eda3e78ceb9175877515ed0 | []
| no_license | Ferangel/workspaceTest | https://github.com/Ferangel/workspaceTest | 9e71c4f51f848ebbd719ebb97ddb2ddfa88dea7c | 8588d92243bec229b361a7a4417b92ccbad52264 | refs/heads/master | 2020-06-19T18:35:12.019000 | 2020-04-27T09:20:38 | 2020-04-27T09:20:38 | 196,823,768 | 0 | 0 | null | false | 2021-03-31T22:32:24 | 2019-07-14T10:37:04 | 2020-04-27T09:20:12 | 2021-03-31T22:32:24 | 8,762 | 0 | 0 | 21 | Java | false | false | package com.ebroker.clientcima;
public class fer {
}
| UTF-8 | Java | 55 | java | fer.java | Java | []
| null | []
| package com.ebroker.clientcima;
public class fer {
}
| 55 | 0.745455 | 0.745455 | 5 | 10 | 12.537943 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 3 |
a90b9cba80fe26200e16e8b763d6d09502d2b0bf | 17,695,265,289,324 | 6ecf6ab6e7b1e398f2332db2eff97d950f5ef4c9 | /src/main/java/com/naown/aop/entity/LogEntity.java | 006354afd0173e5cefe8399425accc75b33e8772 | []
| no_license | naown/blog-vue | https://github.com/naown/blog-vue | 9dbb304a457c84eddab37e56cc4e68585caf7b2c | 7402be180588963e1601a7ff1fc9b0615b8492bb | refs/heads/main | 2023-03-31T01:25:52.317000 | 2021-03-31T09:09:38 | 2021-03-31T09:09:38 | 343,453,830 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.naown.aop.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.sql.Timestamp;
/**
* 对应sys_log表
* @author : chenjian
* @since : 2021/2/21 1:30 周日
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "sys_log")
public class LogEntity {
/** logId */
@TableId(value = "log_id",type = IdType.AUTO)
private Long id;
/** 操作用户 */
private String username;
/** 描述 */
private String description;
/** 方法名 */
private String method;
/** 参数 */
private String params;
/** 日志类型 */
private String logType;
/** 操作系统 */
private String os;
/** 请求方式 例如:POST、GET、DELETE、PUT */
private String requestMethod;
/** 请求ip */
private String requestIp;
/** 地址 */
private String address;
/** 浏览器 */
private String browser;
/** 请求耗时 */
private Long time;
/** 异常详细 */
private byte[] exceptionDetail;
/** 创建日期 */
private Timestamp createTime;
/**
* 构造Log实体只需要先传入类型和执行时间,后续属性在进行赋值添加
* @param logType
* @param time
*/
public LogEntity(String logType, Long time) {
this.logType = logType;
this.time = time;
}
}
| UTF-8 | Java | 1,562 | java | LogEntity.java | Java | [
{
"context": "ava.sql.Timestamp;\n\n/**\n * 对应sys_log表\n * @author : chenjian\n * @since : 2021/2/21 1:30 周日\n **/\n@Data\n@AllArgs",
"end": 343,
"score": 0.9996680617332458,
"start": 335,
"tag": "USERNAME",
"value": "chenjian"
}
]
| null | []
| package com.naown.aop.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.sql.Timestamp;
/**
* 对应sys_log表
* @author : chenjian
* @since : 2021/2/21 1:30 周日
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "sys_log")
public class LogEntity {
/** logId */
@TableId(value = "log_id",type = IdType.AUTO)
private Long id;
/** 操作用户 */
private String username;
/** 描述 */
private String description;
/** 方法名 */
private String method;
/** 参数 */
private String params;
/** 日志类型 */
private String logType;
/** 操作系统 */
private String os;
/** 请求方式 例如:POST、GET、DELETE、PUT */
private String requestMethod;
/** 请求ip */
private String requestIp;
/** 地址 */
private String address;
/** 浏览器 */
private String browser;
/** 请求耗时 */
private Long time;
/** 异常详细 */
private byte[] exceptionDetail;
/** 创建日期 */
private Timestamp createTime;
/**
* 构造Log实体只需要先传入类型和执行时间,后续属性在进行赋值添加
* @param logType
* @param time
*/
public LogEntity(String logType, Long time) {
this.logType = logType;
this.time = time;
}
}
| 1,562 | 0.62804 | 0.620887 | 74 | 17.891891 | 14.585783 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.351351 | false | false | 3 |
69a8f5d36db16b4a4045059bfd3d2a6c939c89d0 | 11,158,325,095,170 | 92aa6cf7ce1b180a52c4fab6bdbae573763b6172 | /lorem-ipsum-jpa/src/test/java/br/com/delogic/jpasy/populator/ApiUsageTest.java | e4ae9c9c7bf7749ca6cef0d7f48fd54978b768f3 | [
"Apache-2.0"
]
| permissive | celiosilva/jpasy | https://github.com/celiosilva/jpasy | 647fa803654c4d25e39f25adb5f9149dfdce3ce7 | b445b3b51ed757ae7798f1c04ac296f7fbed9d76 | refs/heads/master | 2020-06-01T09:29:38.074000 | 2013-12-12T12:52:51 | 2013-12-12T12:52:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.delogic.jpasy.populator;
import java.lang.reflect.Method;
import org.junit.Test;
import br.com.delogic.jpasy.populator.AttributeConfiguration;
import br.com.delogic.jpasy.populator.AttributeGenerator;
import br.com.delogic.jpasy.populator.AttributeGeneratorVarargs;
import br.com.delogic.jpasy.populator.PopulatorService;
public class ApiUsageTest {
@Test
public void test() {
for (Method m : Person.class.getMethods()) {
System.out.println(m.getName());
}
}
public void usageTest() throws InstantiationException,
IllegalAccessException {
PopulatorService populator = PopulatorService.class.newInstance();
// configure the amount right on top of the service
populator.setAmountPerEntity(100);
populator.setAttributeGenerator("image",
new AttributeGenerator<String>() {
public String generate(int index,
AttributeConfiguration configuration) {
return "image.jpg";
}
});
// populate simple class with no harness
populator.prepare(Person.class).populate();
// populate a simples class changing the amount
populator.prepare(Person.class).setAmount(100).populate();
// populate a simple class, changing the way an attribute is generated
populator
.prepare(Person.class)
.setAttributeGenerator("name",
new AttributeGenerator<String>() {
public String generate(int index,
AttributeConfiguration config) {
return "A different String " + index;
}
}).populate();
populator.prepare(Person.class).setAttributeGenerator("name",
new AttributeGeneratorVarargs<String>("John", "Mary", "Paul"));
AttributeConfiguration config = populator.prepare(Person.class)
.getAttributeConfiguration("name");
config.setNullable(true);
config.getAttributeName();
}
}
| UTF-8 | Java | 1,800 | java | ApiUsageTest.java | Java | [
{
"context": "name\",\n\t\t\t\tnew AttributeGeneratorVarargs<String>(\"John\", \"Mary\", \"Paul\"));\n\n\t\tAttributeConfiguration con",
"end": 1608,
"score": 0.9997819066047668,
"start": 1604,
"tag": "NAME",
"value": "John"
},
{
"context": "\t\t\tnew AttributeGeneratorVarargs<String>(\"John\", \"Mary\", \"Paul\"));\n\n\t\tAttributeConfiguration config = po",
"end": 1616,
"score": 0.9996380805969238,
"start": 1612,
"tag": "NAME",
"value": "Mary"
},
{
"context": "ttributeGeneratorVarargs<String>(\"John\", \"Mary\", \"Paul\"));\n\n\t\tAttributeConfiguration config = populator.",
"end": 1624,
"score": 0.9997181296348572,
"start": 1620,
"tag": "NAME",
"value": "Paul"
}
]
| null | []
| package br.com.delogic.jpasy.populator;
import java.lang.reflect.Method;
import org.junit.Test;
import br.com.delogic.jpasy.populator.AttributeConfiguration;
import br.com.delogic.jpasy.populator.AttributeGenerator;
import br.com.delogic.jpasy.populator.AttributeGeneratorVarargs;
import br.com.delogic.jpasy.populator.PopulatorService;
public class ApiUsageTest {
@Test
public void test() {
for (Method m : Person.class.getMethods()) {
System.out.println(m.getName());
}
}
public void usageTest() throws InstantiationException,
IllegalAccessException {
PopulatorService populator = PopulatorService.class.newInstance();
// configure the amount right on top of the service
populator.setAmountPerEntity(100);
populator.setAttributeGenerator("image",
new AttributeGenerator<String>() {
public String generate(int index,
AttributeConfiguration configuration) {
return "image.jpg";
}
});
// populate simple class with no harness
populator.prepare(Person.class).populate();
// populate a simples class changing the amount
populator.prepare(Person.class).setAmount(100).populate();
// populate a simple class, changing the way an attribute is generated
populator
.prepare(Person.class)
.setAttributeGenerator("name",
new AttributeGenerator<String>() {
public String generate(int index,
AttributeConfiguration config) {
return "A different String " + index;
}
}).populate();
populator.prepare(Person.class).setAttributeGenerator("name",
new AttributeGeneratorVarargs<String>("John", "Mary", "Paul"));
AttributeConfiguration config = populator.prepare(Person.class)
.getAttributeConfiguration("name");
config.setNullable(true);
config.getAttributeName();
}
}
| 1,800 | 0.733889 | 0.730556 | 64 | 27.125 | 23.241598 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.53125 | false | false | 3 |
576ff23cb41b3434c829b04e174bb953571518e9 | 9,577,777,099,364 | 3b481b302b02edf57b816acac9e5ff3b7ec602e2 | /src/com/google/android/gms/ads/internal/client/t.java | 003ef249557240bc51b4d9368faf554684f7ca39 | []
| no_license | reverseengineeringer/com.twitter.android | https://github.com/reverseengineeringer/com.twitter.android | 53338ae009b2b6aa79551a8273875ec3728eda99 | f834eee04284d773ccfcd05487021200de30bd1e | refs/heads/master | 2021-04-15T04:35:06.232000 | 2016-07-21T03:51:19 | 2016-07-21T03:51:19 | 63,835,046 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.android.gms.ads.internal.client;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.internal.oi;
import java.util.ArrayList;
import java.util.List;
@oi
public final class t
{
private long a;
private Bundle b;
private int c;
private List<String> d;
private boolean e;
private int f;
private boolean g;
private String h;
private SearchAdRequestParcel i;
private Location j;
private String k;
private Bundle l;
private Bundle m;
private List<String> n;
private String o;
private String p;
private boolean q;
public t()
{
a = -1L;
b = new Bundle();
c = -1;
d = new ArrayList();
e = false;
f = -1;
g = false;
h = null;
i = null;
j = null;
k = null;
l = new Bundle();
m = new Bundle();
n = new ArrayList();
o = null;
p = null;
q = false;
}
public t(AdRequestParcel paramAdRequestParcel)
{
a = b;
b = c;
c = d;
d = e;
e = f;
f = g;
g = h;
h = i;
i = j;
j = k;
k = l;
l = m;
m = n;
n = o;
o = p;
p = q;
}
public AdRequestParcel a()
{
return new AdRequestParcel(7, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q);
}
public t a(Location paramLocation)
{
j = paramLocation;
return this;
}
}
/* Location:
* Qualified Name: com.google.android.gms.ads.internal.client.t
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 1,503 | java | t.java | Java | []
| null | []
| package com.google.android.gms.ads.internal.client;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.internal.oi;
import java.util.ArrayList;
import java.util.List;
@oi
public final class t
{
private long a;
private Bundle b;
private int c;
private List<String> d;
private boolean e;
private int f;
private boolean g;
private String h;
private SearchAdRequestParcel i;
private Location j;
private String k;
private Bundle l;
private Bundle m;
private List<String> n;
private String o;
private String p;
private boolean q;
public t()
{
a = -1L;
b = new Bundle();
c = -1;
d = new ArrayList();
e = false;
f = -1;
g = false;
h = null;
i = null;
j = null;
k = null;
l = new Bundle();
m = new Bundle();
n = new ArrayList();
o = null;
p = null;
q = false;
}
public t(AdRequestParcel paramAdRequestParcel)
{
a = b;
b = c;
c = d;
d = e;
e = f;
f = g;
g = h;
h = i;
i = j;
j = k;
k = l;
l = m;
m = n;
n = o;
o = p;
p = q;
}
public AdRequestParcel a()
{
return new AdRequestParcel(7, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q);
}
public t a(Location paramLocation)
{
j = paramLocation;
return this;
}
}
/* Location:
* Qualified Name: com.google.android.gms.ads.internal.client.t
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 1,503 | 0.56487 | 0.557552 | 87 | 16.287355 | 13.990891 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.873563 | false | false | 3 |
d0469478068c03b028556ed196c8aa6bfbda8804 | 22,548,578,345,254 | 1a4f4de64cd0296ebf7461a80b45f590946e3328 | /src/services/ShopsService.java | b820bed2416da13b53bbb40628643d49237f68be | []
| no_license | jpmono416/Winedunk_CRUD_API | https://github.com/jpmono416/Winedunk_CRUD_API | d31fe663f614c4474c676bbfd6cb30377e2c4f64 | 540bc094cca8027ee5ceea130417042cee5089a2 | refs/heads/master | 2021-01-01T18:44:13.151000 | 2018-06-06T17:18:53 | 2018-06-06T17:18:53 | 98,418,027 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package services;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import models.tblShops;
@Stateless
@LocalBean
public class ShopsService {
@PersistenceContext(unitName = "Winedunk")
EntityManager em;
@SuppressWarnings("unchecked")
public List<tblShops> getShops()
{
Query query = em.createQuery("SELECT p FROM tblShops p");
try { return (List<tblShops>) query.getResultList(); }
catch (Exception e) { e.printStackTrace(); return null; }
}
public tblShops getShopById(Integer id)
{
try { return em.find(tblShops.class, id); }
catch (Exception e) { e.printStackTrace(); return null; }
}
public tblShops getByName(String name)
{
try {
return em.createNamedQuery("tblShops.findByName", tblShops.class)
.setParameter("name", name)
.getSingleResult();
} catch (Exception e) {
if(!e.getClass().equals(NoResultException.class))
e.printStackTrace();
return null;
}
}
public Boolean addShop(tblShops shop) {
try
{
if(shop.getId() != null) { shop.setId(null); }
// aripe 2018-04-12
Integer maxColumnLength = shop.getClass().getDeclaredField("name").getAnnotation(Column.class).length();
if (shop.getName() != null && shop.getName().length() > maxColumnLength) {
shop.setName( shop.getName().substring(0, maxColumnLength - 3).concat("...") );
}
maxColumnLength = shop.getClass().getDeclaredField("Logo").getAnnotation(Column.class).length();
if (shop.getLogo() != null && shop.getLogo().length() > maxColumnLength) {
shop.setLogo( shop.getLogo().substring(0, maxColumnLength - 3).concat("...") );
}
maxColumnLength = shop.getClass().getDeclaredField("homePage").getAnnotation(Column.class).length();
if (shop.getHomePage() != null && shop.getHomePage().length() > maxColumnLength) {
shop.setHomePage( shop.getHomePage().substring(0, maxColumnLength - 3).concat("...") );
}
maxColumnLength = shop.getClass().getDeclaredField("genericProductPage").getAnnotation(Column.class).length();
if (shop.getGenericProductPage() != null && shop.getGenericProductPage().length() > maxColumnLength) {
shop.setGenericProductPage( shop.getGenericProductPage().substring(0, maxColumnLength - 3).concat("...") );
}
em.persist(shop);
return true;
} catch (Exception e) { return false; }
}
public Boolean updateShop(tblShops shop)
{
if(shop == null || shop.getId() == null) { return false; }
em.merge(shop);
return true;
}
public Boolean deleteShop(Integer id)
{
tblShops shop = getShopById(id);
if(shop != null)
{
shop.setDeleted(true);
em.merge(shop);
return true;
}
return false;
}
} | UTF-8 | Java | 3,184 | java | ShopsService.java | Java | []
| null | []
| package services;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import models.tblShops;
@Stateless
@LocalBean
public class ShopsService {
@PersistenceContext(unitName = "Winedunk")
EntityManager em;
@SuppressWarnings("unchecked")
public List<tblShops> getShops()
{
Query query = em.createQuery("SELECT p FROM tblShops p");
try { return (List<tblShops>) query.getResultList(); }
catch (Exception e) { e.printStackTrace(); return null; }
}
public tblShops getShopById(Integer id)
{
try { return em.find(tblShops.class, id); }
catch (Exception e) { e.printStackTrace(); return null; }
}
public tblShops getByName(String name)
{
try {
return em.createNamedQuery("tblShops.findByName", tblShops.class)
.setParameter("name", name)
.getSingleResult();
} catch (Exception e) {
if(!e.getClass().equals(NoResultException.class))
e.printStackTrace();
return null;
}
}
public Boolean addShop(tblShops shop) {
try
{
if(shop.getId() != null) { shop.setId(null); }
// aripe 2018-04-12
Integer maxColumnLength = shop.getClass().getDeclaredField("name").getAnnotation(Column.class).length();
if (shop.getName() != null && shop.getName().length() > maxColumnLength) {
shop.setName( shop.getName().substring(0, maxColumnLength - 3).concat("...") );
}
maxColumnLength = shop.getClass().getDeclaredField("Logo").getAnnotation(Column.class).length();
if (shop.getLogo() != null && shop.getLogo().length() > maxColumnLength) {
shop.setLogo( shop.getLogo().substring(0, maxColumnLength - 3).concat("...") );
}
maxColumnLength = shop.getClass().getDeclaredField("homePage").getAnnotation(Column.class).length();
if (shop.getHomePage() != null && shop.getHomePage().length() > maxColumnLength) {
shop.setHomePage( shop.getHomePage().substring(0, maxColumnLength - 3).concat("...") );
}
maxColumnLength = shop.getClass().getDeclaredField("genericProductPage").getAnnotation(Column.class).length();
if (shop.getGenericProductPage() != null && shop.getGenericProductPage().length() > maxColumnLength) {
shop.setGenericProductPage( shop.getGenericProductPage().substring(0, maxColumnLength - 3).concat("...") );
}
em.persist(shop);
return true;
} catch (Exception e) { return false; }
}
public Boolean updateShop(tblShops shop)
{
if(shop == null || shop.getId() == null) { return false; }
em.merge(shop);
return true;
}
public Boolean deleteShop(Integer id)
{
tblShops shop = getShopById(id);
if(shop != null)
{
shop.setDeleted(true);
em.merge(shop);
return true;
}
return false;
}
} | 3,184 | 0.625628 | 0.620603 | 98 | 31.5 | 31.620275 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.183674 | false | false | 3 |
255a166186614b729da3e6481ea4ee6a110790db | 26,577,257,677,181 | 9b78f481f92faa20ea9ed5b574cb51a5cac0c58f | /MyDiary_MVP/app/src/main/java/com/example/my/mydiary/eventbus/SecondActivity.java | ed6ca432afe4f14e96f74a5680df0bf822ed43a9 | []
| no_license | miaoyungsjm/MyDiary | https://github.com/miaoyungsjm/MyDiary | f7a00ed5c8c35263f01c1ca024d0933ae8ebee7b | e9698a83d3104cdd59988ce556fa12ee173dd595 | refs/heads/master | 2020-03-22T14:06:32.018000 | 2018-08-25T05:36:20 | 2018-08-25T05:36:20 | 137,372,401 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.my.mydiary.eventbus;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.example.my.mydiary.R;
import org.greenrobot.eventbus.EventBus;
/**
* @author ggz
* @date 18年8月13日
*/
public class SecondActivity extends Activity {
private final String TAG = SecondActivity.class.getSimpleName();
private final String TAG_EVENT_BUS = "EVENT_BUS";
private EventBus mEventBus;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG_EVENT_BUS, "onCreate() 2");
setContentView(R.layout.activity_second);
mEventBus = EventBus.getDefault();
Button sendBtn = findViewById(R.id.btn_send);
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mEventBus.post(new MessageEvent(getResources().getString(R.string.second_send_msg)));
finish();
}
});
}
@Override
protected void onRestart() {
Log.d(TAG_EVENT_BUS, "onRestart() 2");
super.onRestart();
}
@Override
protected void onPause() {
Log.d(TAG_EVENT_BUS, "onPause() 2");
super.onPause();
}
@Override
protected void onStop() {
Log.d(TAG_EVENT_BUS, "onStop() 2" +
" isFinishing() = " + isFinishing());
super.onStop();
}
@Override
protected void onDestroy() {
Log.d(TAG_EVENT_BUS, "onDestroy() 2");
super.onDestroy();
}
}
| UTF-8 | Java | 1,715 | java | SecondActivity.java | Java | [
{
"context": " org.greenrobot.eventbus.EventBus;\n\n/**\n * @author ggz\n * @date 18年8月13日\n */\n\npublic class SecondActivit",
"end": 317,
"score": 0.9996639490127563,
"start": 314,
"tag": "USERNAME",
"value": "ggz"
}
]
| null | []
| package com.example.my.mydiary.eventbus;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.example.my.mydiary.R;
import org.greenrobot.eventbus.EventBus;
/**
* @author ggz
* @date 18年8月13日
*/
public class SecondActivity extends Activity {
private final String TAG = SecondActivity.class.getSimpleName();
private final String TAG_EVENT_BUS = "EVENT_BUS";
private EventBus mEventBus;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG_EVENT_BUS, "onCreate() 2");
setContentView(R.layout.activity_second);
mEventBus = EventBus.getDefault();
Button sendBtn = findViewById(R.id.btn_send);
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mEventBus.post(new MessageEvent(getResources().getString(R.string.second_send_msg)));
finish();
}
});
}
@Override
protected void onRestart() {
Log.d(TAG_EVENT_BUS, "onRestart() 2");
super.onRestart();
}
@Override
protected void onPause() {
Log.d(TAG_EVENT_BUS, "onPause() 2");
super.onPause();
}
@Override
protected void onStop() {
Log.d(TAG_EVENT_BUS, "onStop() 2" +
" isFinishing() = " + isFinishing());
super.onStop();
}
@Override
protected void onDestroy() {
Log.d(TAG_EVENT_BUS, "onDestroy() 2");
super.onDestroy();
}
}
| 1,715 | 0.626097 | 0.620246 | 67 | 24.507463 | 21.511797 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.492537 | false | false | 3 |
7d086e57f1c187a8b9bfaa840ff54174ad7d5368 | 19,559,281,093,303 | bd20ba6a8861abed1abe72e6c04dc8bde3fe53f0 | /src/main/java/com/djdu/address/entity/Address.java | 8bee8025aad4864ad5a006451bdb5aef9212bfdf | []
| no_license | MRDJDU/MT | https://github.com/MRDJDU/MT | b8999353c258b628a6377e6e0765afd5aed1ff4f | 3003751d064382be9d2b2784c0492a04311495a4 | refs/heads/master | 2020-04-22T03:02:32.792000 | 2019-05-10T17:28:23 | 2019-05-10T17:28:23 | 170,071,856 | 8 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.djdu.address.entity;
import com.djdu.common.base.BaseEmtity2;
import com.djdu.user.entity.User;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import javax.persistence.*;
/**
* @ClassName Address
* @Description TODO 用于存储用户填写的收货地址
* @Author DJDU
* @Date 2019/2/20 15:29
* @Version 1.0
**/
@Data
@Entity
@Table(name = "address")
@JsonIgnoreProperties({ "handler","hibernateLazyInitializer" })
public class Address extends BaseEmtity2 {
@Id
@Column(name = "address_id")
private String address_id;//收货地址id
private String name;//收货人姓名
private String phone;//手机号码
private String province;//省
private String city;//市
private String addressDetails;//详细地址
private boolean defaultAddress;//设置为默认收货地址
@ManyToOne(cascade= CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;//父,用户
}
| UTF-8 | Java | 1,009 | java | Address.java | Java | [
{
"context": "ress\n * @Description TODO 用于存储用户填写的收货地址\n * @Author DJDU\n * @Date 2019/2/20 15:29\n * @Version 1.0\n **/\n\n@D",
"end": 297,
"score": 0.9962736964225769,
"start": 293,
"tag": "USERNAME",
"value": "DJDU"
}
]
| null | []
| package com.djdu.address.entity;
import com.djdu.common.base.BaseEmtity2;
import com.djdu.user.entity.User;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import javax.persistence.*;
/**
* @ClassName Address
* @Description TODO 用于存储用户填写的收货地址
* @Author DJDU
* @Date 2019/2/20 15:29
* @Version 1.0
**/
@Data
@Entity
@Table(name = "address")
@JsonIgnoreProperties({ "handler","hibernateLazyInitializer" })
public class Address extends BaseEmtity2 {
@Id
@Column(name = "address_id")
private String address_id;//收货地址id
private String name;//收货人姓名
private String phone;//手机号码
private String province;//省
private String city;//市
private String addressDetails;//详细地址
private boolean defaultAddress;//设置为默认收货地址
@ManyToOne(cascade= CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;//父,用户
}
| 1,009 | 0.717084 | 0.700762 | 44 | 19.886364 | 18.826017 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 3 |
35e508ac71839d32c37559a5ed1fe0e834401292 | 9,783,935,538,895 | 8a4d668b93783a78ab26bdf76fa36b38531ee594 | /DE2.java | 7fa70eeb7b4743c4ca7ffeed1834da90578ada9d | []
| no_license | 2031TeamA/sonar-sensing | https://github.com/2031TeamA/sonar-sensing | b533279bc901a3dd6629f2ed9505ea19332b8bee | 8d870526a80b59750d4f3bc17ca4be56cd8688ac | refs/heads/master | 2016-09-05T22:32:23.266000 | 2015-01-21T19:59:26 | 2015-01-21T19:59:26 | 26,565,134 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pack;
import java.util.ArrayList;
public class DE2 {
int x, y, x1, y1, x2, y2, deltaX, deltaY;
public DE2(){
}
public ArrayList <String> navigateEverywhere(Point start, ArrayList<Point> points){
ArrayList <String> directions = new ArrayList <String> ();
for (Point point : points){
directions.addAll( navigate(start,point) );
start = point;
}
return directions;
}
public ArrayList <String> navigate(Point start, Point finish){
//setup
ArrayList <String> directions = new ArrayList <String> ();
x1 = start.x;
y1 = start.y;
x = x1;
y = y1;
x2 = finish.x;
y2 = finish.y;
deltaY = y2 - y;
//navigate vertically
if (deltaY > 0){ //move north
//faceNorth();
directions.addAll(goNorth(deltaY));
}
else if (deltaY < 0){ //move south
//faceSouth();
directions.addAll(goSouth(deltaY));
}
else { //don't move
}
deltaX = x2 - x;
//navigate horizontally
if (deltaX > 0){ //move east
//faceEast();
directions.addAll(goEast(deltaX));
}
else if (deltaX < 0){ //move west
//faceWest();
directions.addAll(goWest(deltaX));
}
else { //don't move
}
return directions;
}
public void setX(int x){this.x = x;}
public void setY(int y){this.y = y;}
public ArrayList <String> goNorth(int delta){
ArrayList <String> directions = new ArrayList <String> ();
while (delta != 0 && y != 4){
if (y == 2 && x > 2){ //you will hit the wall if you go north
directions.addAll(avoidBarrier(2));
}
else {
//move forward 1 square
directions.add("north");
y += 1;
delta -= 1;
}
}
return directions;
}
public ArrayList <String> goEast(int delta){
ArrayList <String> directions = new ArrayList <String> ();
// checks to see if moving east is a valid operation
while ( (delta != 0) && ((y < 3 && x != 4) || (y == 3 && x != 5) || (y == 4 && x != 6)) ){
//move forward 1 square
directions.add("east");
x += 1;
delta -= 1;
}
return directions;
}
public ArrayList <String> goSouth(int delta){ //delta should be negative
ArrayList <String> directions = new ArrayList <String> ();
while (delta != 0 && y != 1){
if (y == 3 && x > 2){ //you will hit the wall if you go north
directions.addAll(avoidBarrier(2));
}
else if (y == 4 && x == 6){ //you will hit the wall if you go north
if (delta < -1) {
directions.addAll(avoidBarrier(2));
}
else if (delta == -1) {
directions.addAll(avoidBarrier(5));
}
}
else {
//move forward 1 square
directions.add("south");
y -= 1;
delta += 1;
}
}
return directions;
}
public ArrayList <String> goWest(int delta){ //delta should be negative
ArrayList <String> directions = new ArrayList <String> ();
while (delta != 0 && x != 1){
//move forward 1 square
directions.add("west");
x -= 1;
delta += 1;
}
return directions;
}
public ArrayList <String> avoidBarrier(int columnToGoTo){
ArrayList <String> directions = new ArrayList <String> ();
while (x != columnToGoTo){
//face west and move forward 1 square
directions.add("west");
x -= 1;
}
return directions;
}
public void printDirections(ArrayList <String> directions){
for (String dir : directions){
System.out.println(dir);
}
}
public static void main(String [] args){
//test individual functions
ArrayList <String> dir;
DE2 bot = new DE2();
bot.setX(6);
bot.setY(4);
dir = bot.goSouth(-1);
//testing main function
Point start = new Point(4,2);
Point finish = new Point(6,4);
dir = bot.navigate(start,finish);
ArrayList<Point> points = new ArrayList<Point>();
points.add(new Point(1,1));
points.add(finish);
points.add(start);
dir = bot.navigateEverywhere(start,points);
bot.printDirections(dir);
}
public static class Point{
int x, y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
}
| UTF-8 | Java | 3,935 | java | DE2.java | Java | []
| null | []
| package pack;
import java.util.ArrayList;
public class DE2 {
int x, y, x1, y1, x2, y2, deltaX, deltaY;
public DE2(){
}
public ArrayList <String> navigateEverywhere(Point start, ArrayList<Point> points){
ArrayList <String> directions = new ArrayList <String> ();
for (Point point : points){
directions.addAll( navigate(start,point) );
start = point;
}
return directions;
}
public ArrayList <String> navigate(Point start, Point finish){
//setup
ArrayList <String> directions = new ArrayList <String> ();
x1 = start.x;
y1 = start.y;
x = x1;
y = y1;
x2 = finish.x;
y2 = finish.y;
deltaY = y2 - y;
//navigate vertically
if (deltaY > 0){ //move north
//faceNorth();
directions.addAll(goNorth(deltaY));
}
else if (deltaY < 0){ //move south
//faceSouth();
directions.addAll(goSouth(deltaY));
}
else { //don't move
}
deltaX = x2 - x;
//navigate horizontally
if (deltaX > 0){ //move east
//faceEast();
directions.addAll(goEast(deltaX));
}
else if (deltaX < 0){ //move west
//faceWest();
directions.addAll(goWest(deltaX));
}
else { //don't move
}
return directions;
}
public void setX(int x){this.x = x;}
public void setY(int y){this.y = y;}
public ArrayList <String> goNorth(int delta){
ArrayList <String> directions = new ArrayList <String> ();
while (delta != 0 && y != 4){
if (y == 2 && x > 2){ //you will hit the wall if you go north
directions.addAll(avoidBarrier(2));
}
else {
//move forward 1 square
directions.add("north");
y += 1;
delta -= 1;
}
}
return directions;
}
public ArrayList <String> goEast(int delta){
ArrayList <String> directions = new ArrayList <String> ();
// checks to see if moving east is a valid operation
while ( (delta != 0) && ((y < 3 && x != 4) || (y == 3 && x != 5) || (y == 4 && x != 6)) ){
//move forward 1 square
directions.add("east");
x += 1;
delta -= 1;
}
return directions;
}
public ArrayList <String> goSouth(int delta){ //delta should be negative
ArrayList <String> directions = new ArrayList <String> ();
while (delta != 0 && y != 1){
if (y == 3 && x > 2){ //you will hit the wall if you go north
directions.addAll(avoidBarrier(2));
}
else if (y == 4 && x == 6){ //you will hit the wall if you go north
if (delta < -1) {
directions.addAll(avoidBarrier(2));
}
else if (delta == -1) {
directions.addAll(avoidBarrier(5));
}
}
else {
//move forward 1 square
directions.add("south");
y -= 1;
delta += 1;
}
}
return directions;
}
public ArrayList <String> goWest(int delta){ //delta should be negative
ArrayList <String> directions = new ArrayList <String> ();
while (delta != 0 && x != 1){
//move forward 1 square
directions.add("west");
x -= 1;
delta += 1;
}
return directions;
}
public ArrayList <String> avoidBarrier(int columnToGoTo){
ArrayList <String> directions = new ArrayList <String> ();
while (x != columnToGoTo){
//face west and move forward 1 square
directions.add("west");
x -= 1;
}
return directions;
}
public void printDirections(ArrayList <String> directions){
for (String dir : directions){
System.out.println(dir);
}
}
public static void main(String [] args){
//test individual functions
ArrayList <String> dir;
DE2 bot = new DE2();
bot.setX(6);
bot.setY(4);
dir = bot.goSouth(-1);
//testing main function
Point start = new Point(4,2);
Point finish = new Point(6,4);
dir = bot.navigate(start,finish);
ArrayList<Point> points = new ArrayList<Point>();
points.add(new Point(1,1));
points.add(finish);
points.add(start);
dir = bot.navigateEverywhere(start,points);
bot.printDirections(dir);
}
public static class Point{
int x, y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
}
| 3,935 | 0.607624 | 0.590343 | 181 | 20.740332 | 19.928713 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.546961 | false | false | 3 |
950c6555cc164db5f49d2cf3f86e37cbde51d3b7 | 22,548,578,348,992 | ff0d562a9f75d1eaebc066a45248adb19262f8be | /src/main/java/co/realtime/storage/annotations/StorageProperty.java | a749c0778230cceb362151ba5df2062cf48ced25 | []
| no_license | joaoantunes87/OsmRealtimeStorage-Java | https://github.com/joaoantunes87/OsmRealtimeStorage-Java | a13b173ca8e7a7b61fdd698f0b1048263dd1809a | f4242421a2b34294934e6de54ab631aec3356ceb | refs/heads/master | 2020-05-28T04:34:06.359000 | 2015-07-13T08:57:07 | 2015-07-13T08:57:07 | 17,664,745 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.realtime.storage.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The Interface StorageProperty.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface StorageProperty {
/**
* Name.
* @return the string
*/
String name() default "";
/**
* Checks if is primary key.
* @return true, if is primary key
*/
boolean isPrimaryKey() default false;
/**
* Checks if is secondary key.
* @return true, if is secondary key
*/
boolean isSecondaryKey() default false;
}
| UTF-8 | Java | 702 | java | StorageProperty.java | Java | []
| null | []
| package co.realtime.storage.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The Interface StorageProperty.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface StorageProperty {
/**
* Name.
* @return the string
*/
String name() default "";
/**
* Checks if is primary key.
* @return true, if is primary key
*/
boolean isPrimaryKey() default false;
/**
* Checks if is secondary key.
* @return true, if is secondary key
*/
boolean isSecondaryKey() default false;
}
| 702 | 0.675214 | 0.675214 | 33 | 20.272728 | 16.63744 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.30303 | false | false | 3 |
e7c1994af6d9ee0ac716e1324799f3585d7b7c84 | 11,089,605,615,854 | 4c82b5b72421da0f555f8562c96c88b6e9ea71c0 | /CollegeScoring/src/collegescoring/ChartLine.java | d93376889d0301b41b5685fb01ede2374b325b1c | []
| no_license | AnushkaDeshmukh/Oracle-Project | https://github.com/AnushkaDeshmukh/Oracle-Project | 2ef83bfb86b9f8c4e82b38c79d5f734c47e081b0 | 7c046707558c73f9e5e4e9d8196a438602e9fe60 | refs/heads/master | 2021-01-01T16:55:44.602000 | 2014-08-06T23:59:01 | 2014-08-06T23:59:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2008, 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* 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.
* - Neither the name of Oracle Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 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
* OWNER 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 collegescoring;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
/**
* A chart in which lines connect a series of data points. Useful for viewing
* data trends over time.
*
* @see javafx.scene.chart.LineChart
* @see javafx.scene.chart.Chart
* @see javafx.scene.chart.Axis
* @see javafx.scene.chart.NumberAxis
* @related charts/area/AreaChart
* @related charts/scatter/ScatterChart
*/
public class ChartLine extends Application {
private void init(Stage primaryStage) {
CollegeScoring collegeScoring = new CollegeScoring();
collegeScoring.calc();
Group root = new Group();
primaryStage.setTitle("Results from Inference Test");
primaryStage.setScene(new Scene(root));
NumberAxis xAxis = new NumberAxis("SAT weightage", 0, 1.1, 0.1);
NumberAxis yAxis = new NumberAxis("P-value", 0, 0.15, 0.01);
ObservableList<XYChart.Series<Double, Double>> lineChartData = FXCollections.observableArrayList(
new LineChart.Series<Double, Double>("Series 1", FXCollections.observableArrayList()));
lineChartData.get(0).getData().add(new XYChart.Data<Double, Double>(1.0, collegeScoring.pSATonly));
for (CollegeScoring.Weights w : CollegeScoring.Weights.values()) {
lineChartData.get(0).getData().add(new XYChart.Data<Double, Double>(w.sPercent, collegeScoring.p[w.ordinal()]));
}
lineChartData.get(0).getData().add(new XYChart.Data<Double, Double>(0.0, collegeScoring.pGPAonly));
LineChart chart = new LineChart(xAxis, yAxis, lineChartData);
root.getChildren().add(chart);
}
@Override
public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| UTF-8 | Java | 4,144 | java | ChartLine.java | Java | []
| null | []
| /*
* Copyright (c) 2008, 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* 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.
* - Neither the name of Oracle Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 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
* OWNER 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 collegescoring;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
/**
* A chart in which lines connect a series of data points. Useful for viewing
* data trends over time.
*
* @see javafx.scene.chart.LineChart
* @see javafx.scene.chart.Chart
* @see javafx.scene.chart.Axis
* @see javafx.scene.chart.NumberAxis
* @related charts/area/AreaChart
* @related charts/scatter/ScatterChart
*/
public class ChartLine extends Application {
private void init(Stage primaryStage) {
CollegeScoring collegeScoring = new CollegeScoring();
collegeScoring.calc();
Group root = new Group();
primaryStage.setTitle("Results from Inference Test");
primaryStage.setScene(new Scene(root));
NumberAxis xAxis = new NumberAxis("SAT weightage", 0, 1.1, 0.1);
NumberAxis yAxis = new NumberAxis("P-value", 0, 0.15, 0.01);
ObservableList<XYChart.Series<Double, Double>> lineChartData = FXCollections.observableArrayList(
new LineChart.Series<Double, Double>("Series 1", FXCollections.observableArrayList()));
lineChartData.get(0).getData().add(new XYChart.Data<Double, Double>(1.0, collegeScoring.pSATonly));
for (CollegeScoring.Weights w : CollegeScoring.Weights.values()) {
lineChartData.get(0).getData().add(new XYChart.Data<Double, Double>(w.sPercent, collegeScoring.p[w.ordinal()]));
}
lineChartData.get(0).getData().add(new XYChart.Data<Double, Double>(0.0, collegeScoring.pGPAonly));
LineChart chart = new LineChart(xAxis, yAxis, lineChartData);
root.getChildren().add(chart);
}
@Override
public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| 4,144 | 0.725869 | 0.719112 | 93 | 43.559139 | 30.682369 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.731183 | false | false | 3 |
577381a3928d73898114f265c5a941b10615c8aa | 24,567,212,967,314 | 23bf9733af620b523072c155586fd1d4c809c88c | /app/src/main/java/com/neprofinishedgood/qualitycheck/model/RejectedInput.java | d05e2611e177109b1e036b7f0e6184ffaa5250d2 | []
| no_license | kartikpandey/NeproFGProject | https://github.com/kartikpandey/NeproFGProject | 277f5326ee4d7363b0e63a36bc6c8c83e7654372 | 855cb95e3af39f99d1bb6c8439ae2b0b11b1264e | refs/heads/master | 2020-11-27T00:01:42.340000 | 2020-10-17T17:46:48 | 2020-10-17T17:46:48 | 229,236,995 | 0 | 0 | null | false | 2021-01-01T06:23:24 | 2019-12-20T09:50:17 | 2020-12-22T13:23:24 | 2021-01-01T06:23:23 | 1,168 | 0 | 0 | 0 | Java | false | false | package com.neprofinishedgood.qualitycheck.model;
public class RejectedInput {
String StickerNo;
String UserId;
String Shift;
String Quantity;
String Reason;
String ReasonName;
String IsKg;
String WorkOrderNo;
public RejectedInput(String stickerNo, String userId, String quantity, String reason, String reasonName, String shift, String isKg, String workOrderNo) {
StickerNo = stickerNo;
UserId = userId;
Quantity = quantity;
Reason = reason;
ReasonName = reasonName;
Shift = shift;
IsKg = isKg;
WorkOrderNo = workOrderNo;
}
public String getStickerNo() {
return StickerNo;
}
public void setStickerNo(String stickerNo) {
StickerNo = stickerNo;
}
public String getUserId() {
return UserId;
}
public void setUserId(String userId) {
UserId = userId;
}
public String getShift() {
return Shift;
}
public void setShift(String shift) {
Shift = shift;
}
public String getQuantity() {
return Quantity;
}
public void setQuantity(String quantity) {
Quantity = quantity;
}
public String getReason() {
return Reason;
}
public void setReason(String reason) {
Reason = reason;
}
public String getReasonName() {
return ReasonName;
}
public void setReasonName(String reasonName) {
ReasonName = reasonName;
}
public String getIsKg() {
return IsKg;
}
public void setIsKg(String isKg) {
IsKg = isKg;
}
public String getWorkOrderNo() {
return WorkOrderNo;
}
public void setWorkOrderNo(String workOrderNo) {
WorkOrderNo = workOrderNo;
}
}
| UTF-8 | Java | 1,794 | java | RejectedInput.java | Java | []
| null | []
| package com.neprofinishedgood.qualitycheck.model;
public class RejectedInput {
String StickerNo;
String UserId;
String Shift;
String Quantity;
String Reason;
String ReasonName;
String IsKg;
String WorkOrderNo;
public RejectedInput(String stickerNo, String userId, String quantity, String reason, String reasonName, String shift, String isKg, String workOrderNo) {
StickerNo = stickerNo;
UserId = userId;
Quantity = quantity;
Reason = reason;
ReasonName = reasonName;
Shift = shift;
IsKg = isKg;
WorkOrderNo = workOrderNo;
}
public String getStickerNo() {
return StickerNo;
}
public void setStickerNo(String stickerNo) {
StickerNo = stickerNo;
}
public String getUserId() {
return UserId;
}
public void setUserId(String userId) {
UserId = userId;
}
public String getShift() {
return Shift;
}
public void setShift(String shift) {
Shift = shift;
}
public String getQuantity() {
return Quantity;
}
public void setQuantity(String quantity) {
Quantity = quantity;
}
public String getReason() {
return Reason;
}
public void setReason(String reason) {
Reason = reason;
}
public String getReasonName() {
return ReasonName;
}
public void setReasonName(String reasonName) {
ReasonName = reasonName;
}
public String getIsKg() {
return IsKg;
}
public void setIsKg(String isKg) {
IsKg = isKg;
}
public String getWorkOrderNo() {
return WorkOrderNo;
}
public void setWorkOrderNo(String workOrderNo) {
WorkOrderNo = workOrderNo;
}
}
| 1,794 | 0.609253 | 0.609253 | 87 | 19.620689 | 21.078529 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45977 | false | false | 3 |
364c646875044e33688f1bdbe6f8a1d1877431e8 | 472,446,427,540 | a063dcf701a8f049292667c2d525b9335d54b079 | /09_10/lesson/jw05/part01/CookieWriterToClient.java | 6323c0b162e7414fbabfb5c51908753dcf7e33bc | []
| no_license | ohchangyeol/bitcamp-theory-study | https://github.com/ohchangyeol/bitcamp-theory-study | cac6bc421ed57f740a5d7d170650a7cc0522b97e | c6cbee035ee98f983a6e55128d3f2ea44f4135bb | refs/heads/main | 2023-09-05T14:34:52.779000 | 2021-10-17T09:52:22 | 2021-10-17T09:52:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jw05;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* FileName : CookieWriterToClient.java
* :: Client 에 필요정보를 저장하는 Cookie 사용
*/
//@WebServlet("/CookieWriterToClient")
public class CookieWriterToClient extends HttpServlet{
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{
req.setCharacterEncoding("EUC_KR");
res.setContentType("text/html;charset=EUC_KR");
PrintWriter out = res.getWriter();
//Cookie 생성(name=value) :: 한글 인코딩 후 저장
Cookie cookie = new Cookie("name",URLEncoder.encode("홍길동"));
cookie.setMaxAge(60*60); //cookie 유효기간(초)
//cookie.setMaxAge(-1); //cookie memory 저장 :: ?? ==> API확인
//cookie.setMaxAge(0); //cookie 0초동안 유효 :: ?? ==> API확인
res.addCookie(cookie); //Client 로 response 인스턴스를 사용 cookie 전송
out.println("<html><body>");
out.println("Cookie 저장 완료");
out.println("</body></html>");
}
}//end of class | UHC | Java | 1,345 | java | CookieWriterToClient.java | Java | []
| null | []
| package jw05;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* FileName : CookieWriterToClient.java
* :: Client 에 필요정보를 저장하는 Cookie 사용
*/
//@WebServlet("/CookieWriterToClient")
public class CookieWriterToClient extends HttpServlet{
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{
req.setCharacterEncoding("EUC_KR");
res.setContentType("text/html;charset=EUC_KR");
PrintWriter out = res.getWriter();
//Cookie 생성(name=value) :: 한글 인코딩 후 저장
Cookie cookie = new Cookie("name",URLEncoder.encode("홍길동"));
cookie.setMaxAge(60*60); //cookie 유효기간(초)
//cookie.setMaxAge(-1); //cookie memory 저장 :: ?? ==> API확인
//cookie.setMaxAge(0); //cookie 0초동안 유효 :: ?? ==> API확인
res.addCookie(cookie); //Client 로 response 인스턴스를 사용 cookie 전송
out.println("<html><body>");
out.println("Cookie 저장 완료");
out.println("</body></html>");
}
}//end of class | 1,345 | 0.723887 | 0.716599 | 40 | 29.9 | 24.039343 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.65 | false | false | 3 |
4ad056c250d92247e58ffaaef94337307ea2f43b | 24,910,810,347,590 | 93b210724d5e1b9a1b2b89c64c12d8582135f2aa | /EliteCSM-new/Applications/netvertex/testsrc/com/elitecore/netvertex/core/conf/impl/NetvertexServerInstanceFactoryTest.java | 2d35f34a93516af042a7f6e1cf470853be1e4632 | []
| no_license | sunilkumarpvns/newbrs | https://github.com/sunilkumarpvns/newbrs | e6b205a41898b25203f34a902d1334a83baafb09 | 38e8c22ea5deaee2e46938970be405a307918ce7 | refs/heads/master | 2021-06-17T08:45:52.964000 | 2019-08-21T02:58:00 | 2019-08-21T02:58:00 | 203,326,404 | 0 | 0 | null | false | 2021-05-12T00:24:10 | 2019-08-20T07:47:41 | 2019-08-21T03:00:28 | 2021-05-12T00:24:10 | 252,939 | 0 | 0 | 10 | Java | false | false | package com.elitecore.netvertex.core.conf.impl;
import com.elitecore.commons.logging.LogLevel;
import com.elitecore.corenetvertex.constants.RollingType;
import com.elitecore.corenetvertex.constants.TimeBasedRollingUnit;
import com.elitecore.corenetvertex.sm.serverinstance.ServerInstanceData;
import com.elitecore.corenetvertex.sm.serverprofile.ServerInstanceDataBuilder;
import com.elitecore.corenetvertex.sm.serverprofile.ServerProfileData;
import com.elitecore.corenetvertex.sm.serverprofile.ServerProfileDataBuilder;
import de.bechte.junit.runners.context.HierarchicalContextRunner;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.UUID;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
@RunWith(HierarchicalContextRunner.class)
public class NetvertexServerInstanceFactoryTest {
private NetvertexServerInstanceFactory netvertexServerInstanceFactory;
private ServerProfileData serverProfileData;
private ServerInstanceData serverInstanceData;
@Before
public void setUp() {
netvertexServerInstanceFactory = new NetvertexServerInstanceFactory();
serverProfileData = ServerProfileDataBuilder.create();
serverInstanceData = ServerInstanceDataBuilder.create();
}
public class LoggingParameter {
public class SizeBaseRolling {
@Before
public void setUp() {
serverProfileData.setRollingType(RollingType.SIZE_BASED.value);
}
@Test
public void setRollingTypeToSizeBaseWhenSizeBaseRollingConfigured() {
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingType(), is(RollingType.SIZE_BASED));
}
@Test
public void setConfiguredRollingUnit() {
serverProfileData.setRollingUnits(RandomUtils.nextInt(1, Integer.MAX_VALUE));
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is(serverProfileData.getRollingUnits().toString()));
}
@Test
public void setRollingUnitOneGBWhenNotConfigured() {
serverProfileData.setRollingUnits(null);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is("1048576"));
}
}
public class TimeBaseRolling {
@Before
public void setUp() {
serverProfileData.setRollingType(RollingType.TIME_BASED.value);
}
@Test
public void setRollingTypeToSizeBaseWhenTimeBaseRollingConfigured() {
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingType(), is(RollingType.TIME_BASED));
}
@Test
public void setRolledUnitAsDailyWhenDailyConfigured() {
serverProfileData.setRollingUnits(TimeBasedRollingUnit.DAILY.value);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is(TimeBasedRollingUnit.DAILY.name()));
}
@Test
public void setRolledUnitAsWeeklyWhenHourConfigured() {
serverProfileData.setRollingUnits(TimeBasedRollingUnit.HOUR.value);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is(TimeBasedRollingUnit.HOUR.name()));
}
@Test
public void setRolledUnitAsWeeklyWhenMinutesConfigured() {
serverProfileData.setRollingUnits(TimeBasedRollingUnit.MINUTE.value);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is(TimeBasedRollingUnit.MINUTE.name()));
}
@Test
public void setRolledUnitAsDailyWhenNotConfigured() {
serverProfileData.setRollingUnits(null);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is(TimeBasedRollingUnit.DAILY.name()));
}
}
@Test
public void setLogLevelToWarnWhenNotConfigured() {
serverProfileData.setLogLevel(null);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getLogLevel(), is(LogLevel.WARN.name()));
}
@Test
public void setLogLevelToWarnWhenInvalidValueConfigured() {
serverProfileData.setLogLevel(UUID.randomUUID().toString());
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getLogLevel(), is(LogLevel.WARN.name()));
}
@Test
public void setMaxRolledUnitAsConfigured() {
serverProfileData.setMaxRolledUnits(RandomUtils.nextInt(1, 1000));
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getMaxRollingUnit(), is(serverProfileData.getMaxRolledUnits()));
}
@Test
public void setMaxRolledUnitToTenWhenNotConfigured() {
serverProfileData.setMaxRolledUnits(null);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getMaxRollingUnit(), is(10));
}
@Test
public void setTimeBaseRollingWhenNotConfigured() {
serverProfileData.setRollingType(null);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingType(), is(RollingType.TIME_BASED));
}
@Test
public void setTimeBaseRollingWhenInvalidValueConfigured() {
serverProfileData.setRollingType(1000);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingType(), is(RollingType.TIME_BASED));
}
}
}
| UTF-8 | Java | 8,434 | java | NetvertexServerInstanceFactoryTest.java | Java | []
| null | []
| package com.elitecore.netvertex.core.conf.impl;
import com.elitecore.commons.logging.LogLevel;
import com.elitecore.corenetvertex.constants.RollingType;
import com.elitecore.corenetvertex.constants.TimeBasedRollingUnit;
import com.elitecore.corenetvertex.sm.serverinstance.ServerInstanceData;
import com.elitecore.corenetvertex.sm.serverprofile.ServerInstanceDataBuilder;
import com.elitecore.corenetvertex.sm.serverprofile.ServerProfileData;
import com.elitecore.corenetvertex.sm.serverprofile.ServerProfileDataBuilder;
import de.bechte.junit.runners.context.HierarchicalContextRunner;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.UUID;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
@RunWith(HierarchicalContextRunner.class)
public class NetvertexServerInstanceFactoryTest {
private NetvertexServerInstanceFactory netvertexServerInstanceFactory;
private ServerProfileData serverProfileData;
private ServerInstanceData serverInstanceData;
@Before
public void setUp() {
netvertexServerInstanceFactory = new NetvertexServerInstanceFactory();
serverProfileData = ServerProfileDataBuilder.create();
serverInstanceData = ServerInstanceDataBuilder.create();
}
public class LoggingParameter {
public class SizeBaseRolling {
@Before
public void setUp() {
serverProfileData.setRollingType(RollingType.SIZE_BASED.value);
}
@Test
public void setRollingTypeToSizeBaseWhenSizeBaseRollingConfigured() {
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingType(), is(RollingType.SIZE_BASED));
}
@Test
public void setConfiguredRollingUnit() {
serverProfileData.setRollingUnits(RandomUtils.nextInt(1, Integer.MAX_VALUE));
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is(serverProfileData.getRollingUnits().toString()));
}
@Test
public void setRollingUnitOneGBWhenNotConfigured() {
serverProfileData.setRollingUnits(null);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is("1048576"));
}
}
public class TimeBaseRolling {
@Before
public void setUp() {
serverProfileData.setRollingType(RollingType.TIME_BASED.value);
}
@Test
public void setRollingTypeToSizeBaseWhenTimeBaseRollingConfigured() {
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingType(), is(RollingType.TIME_BASED));
}
@Test
public void setRolledUnitAsDailyWhenDailyConfigured() {
serverProfileData.setRollingUnits(TimeBasedRollingUnit.DAILY.value);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is(TimeBasedRollingUnit.DAILY.name()));
}
@Test
public void setRolledUnitAsWeeklyWhenHourConfigured() {
serverProfileData.setRollingUnits(TimeBasedRollingUnit.HOUR.value);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is(TimeBasedRollingUnit.HOUR.name()));
}
@Test
public void setRolledUnitAsWeeklyWhenMinutesConfigured() {
serverProfileData.setRollingUnits(TimeBasedRollingUnit.MINUTE.value);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is(TimeBasedRollingUnit.MINUTE.name()));
}
@Test
public void setRolledUnitAsDailyWhenNotConfigured() {
serverProfileData.setRollingUnits(null);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingUnit(), is(TimeBasedRollingUnit.DAILY.name()));
}
}
@Test
public void setLogLevelToWarnWhenNotConfigured() {
serverProfileData.setLogLevel(null);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getLogLevel(), is(LogLevel.WARN.name()));
}
@Test
public void setLogLevelToWarnWhenInvalidValueConfigured() {
serverProfileData.setLogLevel(UUID.randomUUID().toString());
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getLogLevel(), is(LogLevel.WARN.name()));
}
@Test
public void setMaxRolledUnitAsConfigured() {
serverProfileData.setMaxRolledUnits(RandomUtils.nextInt(1, 1000));
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getMaxRollingUnit(), is(serverProfileData.getMaxRolledUnits()));
}
@Test
public void setMaxRolledUnitToTenWhenNotConfigured() {
serverProfileData.setMaxRolledUnits(null);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getMaxRollingUnit(), is(10));
}
@Test
public void setTimeBaseRollingWhenNotConfigured() {
serverProfileData.setRollingType(null);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingType(), is(RollingType.TIME_BASED));
}
@Test
public void setTimeBaseRollingWhenInvalidValueConfigured() {
serverProfileData.setRollingType(1000);
NetvertexServerInstanceConfigurationImpl netvertexServerInstanceConfiguration = netvertexServerInstanceFactory.create(serverInstanceData, serverProfileData, mock(ScriptDataFactory.class));
assertThat(netvertexServerInstanceConfiguration.getRollingType(), is(RollingType.TIME_BASED));
}
}
}
| 8,434 | 0.746265 | 0.743894 | 177 | 46.649719 | 57.436394 | 204 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615819 | false | false | 3 |
b449ec993a22b63d12eb573814bd793ba0ff9ee5 | 16,595,753,633,834 | 75b43260f94287bd6162f706e645db2e7f7b3804 | /app/src/main/java/com/chartier/virginie/mynews/model/Response.java | 4e83326af002b19c5b1ac44ede7e1fce669e8aa2 | []
| no_license | Taiviv/MyNews | https://github.com/Taiviv/MyNews | f5611e00a4c760d2cc2c0acc1ea16f05e3ffdd58 | 9a27e0cf99ea3cf390b1bf7f25e212f4fdb789e7 | refs/heads/master | 2020-03-27T13:59:37.033000 | 2019-03-13T22:00:52 | 2019-03-13T22:00:52 | 146,600,399 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chartier.virginie.mynews.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by Virginie Chartier alias Taiviv on 11/11/2018.
*/
public class Response {
// Serialized JSON name
@SerializedName("docs")
@Expose
private List<Doc> docs = null;
//-------------------
// GETTER & SETTER
//-------------------
public List<Doc> getDocs() {
return docs;
}
public void setDocs(List<Doc> docs) {
this.docs = docs;
}
}
| UTF-8 | Java | 575 | java | Response.java | Java | [
{
"context": "edName;\n\nimport java.util.List;\n\n/**\n * Created by Virginie Chartier alias Taiviv on 11/11/2018.\n */\npublic class Response {",
"end": 205,
"score": 0.9992852210998535,
"start": 182,
"tag": "NAME",
"value": "Virginie Chartier alias"
},
{
"context": "l.List;\n\n/**\n * Created by Virginie Chartier alias Taiviv on 11/11/2018.\n */\npublic class Response {\n //",
"end": 212,
"score": 0.8805413246154785,
"start": 206,
"tag": "NAME",
"value": "Taiviv"
}
]
| null | []
| package com.chartier.virginie.mynews.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by <NAME> Taiviv on 11/11/2018.
*/
public class Response {
// Serialized JSON name
@SerializedName("docs")
@Expose
private List<Doc> docs = null;
//-------------------
// GETTER & SETTER
//-------------------
public List<Doc> getDocs() {
return docs;
}
public void setDocs(List<Doc> docs) {
this.docs = docs;
}
}
| 558 | 0.601739 | 0.587826 | 30 | 18.166666 | 17.295631 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.233333 | false | false | 3 |
262a51acbc2e8f2aca5bf79414702ac65d86e85d | 16,587,163,767,588 | 03dfcecb32f68604bb114138a59757211d71f897 | /0007.整数反转.java | 32a5881ecfce4bd65c5a3c57e0af93cc16b8cc49 | []
| no_license | kinwgze/LeetCode | https://github.com/kinwgze/LeetCode | 5b5e90429584790a317833fcadca20a4ad995d33 | 2c79fc38358f13e72524770f7191292b2a15750c | refs/heads/master | 2022-12-26T11:04:52.455000 | 2020-10-08T02:04:12 | 2020-10-08T02:04:12 | 282,557,172 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | //思路:我们可以一次构建反转整数的一位数字。
//在这样做的时候,我们可以预先检查向原整数附加另一位数字是否会导致溢出。
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
//解释看https://leetcode-cn.com/problems/reverse-integer/solution/zheng-shu-fan-zhuan-by-leetcode/
/****************************************************************************/
//也可以将int转为string,反转后再转换为int,注意使用long接收,并注意反转的变化过程
class Solution {
public int reverse(int x) {
if (x < Integer.MIN_VALUE) return 0; //因为该数的绝对值越界了,而且其翻转的结果超过了int范围,这里直接处理
boolean flag = true; //该标记位用来记录x是正数还是负数
if (x < 0) {
flag = false;
x = Math.abs(x);
}
String s = Integer.toString(x); //正数变成字符串String
StringBuilder str = new StringBuilder(s);
s = str.reverse().toString();
long res = Long.parseLong(s);
if (flag == false) {
res = 0 - res;
}
if (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) {
return 0;
}
return (int)res;
}
} | UTF-8 | Java | 1,647 | java | 0007.整数反转.java | Java | []
| null | []
| //思路:我们可以一次构建反转整数的一位数字。
//在这样做的时候,我们可以预先检查向原整数附加另一位数字是否会导致溢出。
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
//解释看https://leetcode-cn.com/problems/reverse-integer/solution/zheng-shu-fan-zhuan-by-leetcode/
/****************************************************************************/
//也可以将int转为string,反转后再转换为int,注意使用long接收,并注意反转的变化过程
class Solution {
public int reverse(int x) {
if (x < Integer.MIN_VALUE) return 0; //因为该数的绝对值越界了,而且其翻转的结果超过了int范围,这里直接处理
boolean flag = true; //该标记位用来记录x是正数还是负数
if (x < 0) {
flag = false;
x = Math.abs(x);
}
String s = Integer.toString(x); //正数变成字符串String
StringBuilder str = new StringBuilder(s);
s = str.reverse().toString();
long res = Long.parseLong(s);
if (flag == false) {
res = 0 - res;
}
if (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) {
return 0;
}
return (int)res;
}
} | 1,647 | 0.506264 | 0.488578 | 45 | 29.177778 | 27.113989 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false | 3 |
65cdb5f67f72886488a3231cd555e9a91c9b167f | 4,681,514,385,880 | b5d2af5a35ded2c38c05533e8d0978e332a75176 | /11 - cookies/PrimerCop.java | 96b6e779dfebfcbd6af047c30cc6a07448d6f835 | []
| no_license | sergigrau/DAWM07UF2-1-Servlets-exercicis | https://github.com/sergigrau/DAWM07UF2-1-Servlets-exercicis | b960f76af88eb9e5f34e7a304dc18e7a9bcdd9e8 | 602186f015c7534b92aff8bad0314931d366e116 | refs/heads/master | 2021-01-10T04:56:16.620000 | 2017-03-23T11:40:11 | 2017-03-23T11:40:11 | 52,009,220 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.fje.daw2;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
/**
* Servlet que treballa amb cookies. Mostra un missatge de benvinguda si és el
* primer cop, en cas contrari mostra una sèrie d'opcions
* @author Sergi Grau
* @version 2.0 7/11/2013
*/
@WebServlet("/cookie")
public class PrimerCop extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest peticio,
HttpServletResponse resposta) throws ServletException, IOException {
boolean nou = true;
Cookie[] cookies = peticio.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
if ((c.getName().equals("repeteix")) &&
// aquesta verificació es pot ometre
(c.getValue().equals("si"))) {
nou = false;
break;
}
}
}
String missatge;
if (nou) {
Cookie cookieRepeteix = new Cookie("repeteix", "si");
cookieRepeteix.setMaxAge(60 * 60 * 24 * 365); // 1 any
resposta.addCookie(cookieRepeteix);
missatge = "benvingut al site de JEE";
} else {
missatge = "opcions disponibles";
}
resposta.setContentType("text/html");
PrintWriter sortida = resposta.getWriter();
String docType = "<!DOCTYPE html>\n";
sortida.println(docType + "<html>\n" + "<head><title>" + missatge
+ "</title></head>\n" + "<body>\n" + missatge + "</body></html>");
}
}
| UTF-8 | Java | 1,472 | java | PrimerCop.java | Java | [
{
"context": "cas contrari mostra una sèrie d'opcions\n * @author Sergi Grau\n * @version 2.0 7/11/2013\n */\n@WebServlet(\"/cooki",
"end": 316,
"score": 0.9998683929443359,
"start": 306,
"tag": "NAME",
"value": "Sergi Grau"
}
]
| null | []
| package edu.fje.daw2;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
/**
* Servlet que treballa amb cookies. Mostra un missatge de benvinguda si és el
* primer cop, en cas contrari mostra una sèrie d'opcions
* @author <NAME>
* @version 2.0 7/11/2013
*/
@WebServlet("/cookie")
public class PrimerCop extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest peticio,
HttpServletResponse resposta) throws ServletException, IOException {
boolean nou = true;
Cookie[] cookies = peticio.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
if ((c.getName().equals("repeteix")) &&
// aquesta verificació es pot ometre
(c.getValue().equals("si"))) {
nou = false;
break;
}
}
}
String missatge;
if (nou) {
Cookie cookieRepeteix = new Cookie("repeteix", "si");
cookieRepeteix.setMaxAge(60 * 60 * 24 * 365); // 1 any
resposta.addCookie(cookieRepeteix);
missatge = "benvingut al site de JEE";
} else {
missatge = "opcions disponibles";
}
resposta.setContentType("text/html");
PrintWriter sortida = resposta.getWriter();
String docType = "<!DOCTYPE html>\n";
sortida.println(docType + "<html>\n" + "<head><title>" + missatge
+ "</title></head>\n" + "<body>\n" + missatge + "</body></html>");
}
}
| 1,468 | 0.668482 | 0.653506 | 49 | 28.979591 | 21.602617 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.326531 | false | false | 3 |
fb448cfa9ec3a7caec2c92bb07d94c063c3379cb | 14,328,010,936,497 | a8b41ccd2a28e11c703195c3668d20be06f7ab43 | /bridgepattern/src/main/java/bupt/lth/Client_bridge.java | 20761892b93ef45e10e034ad1b89e3aeddaef416 | []
| no_license | ShelahLi/DesignPattern | https://github.com/ShelahLi/DesignPattern | f2ca776fc2dc558b5b767c5ccc9b8a4a9c785897 | d164bafb8ab19121fc6ea7aa613690c9eec57b98 | refs/heads/master | 2020-05-24T07:37:55.651000 | 2019-05-27T14:25:59 | 2019-05-27T14:25:59 | 187,164,373 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package bupt.lth;
public class Client_bridge {
public static void main(String[] args) {
Image image;
ImageImp imageImp;
image = (Image) XMLUtil_bridge.getBean("image");
imageImp = (ImageImp) XMLUtil_bridge.getBean("os");
image.setImageImp(imageImp);
image.parseFile("...");
}
}
| UTF-8 | Java | 336 | java | Client_bridge.java | Java | []
| null | []
|
package bupt.lth;
public class Client_bridge {
public static void main(String[] args) {
Image image;
ImageImp imageImp;
image = (Image) XMLUtil_bridge.getBean("image");
imageImp = (ImageImp) XMLUtil_bridge.getBean("os");
image.setImageImp(imageImp);
image.parseFile("...");
}
}
| 336 | 0.607143 | 0.607143 | 12 | 26.916666 | 18.909691 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 3 |
73ad05937bd3860f58a06bc700599830c114abcc | 1,194,000,915,860 | feac9c2b46ffc1284780bacbf888dae9d82122f1 | /spring_erp_myoffice(지승민대리님)/src/main/java/com/erp/myoffice/project/service/ProjectService.java | 391a4248d9d09e2f51e162897f434fd861d8e90d | []
| no_license | FlashBack102/MyOffice | https://github.com/FlashBack102/MyOffice | bed7680c5d59e6cf58c8c5b7a188b92f3edcb96a | 7c748c9f9b512cbae8e161710d72316dc6cf55d1 | refs/heads/master | 2022-12-28T11:48:59.263000 | 2020-10-05T03:47:56 | 2020-10-05T03:47:56 | 289,822,038 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.erp.myoffice.project.service;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
public interface ProjectService {
// 팀장 정보 가져오기
public void getMasterInfo(HttpServletRequest req, Model model);
// 팀원 리스트 가져오기
public void getTeamMemberList(HttpServletRequest req, Model model);
// 팀 프로젝트 생성
public void createProject(HttpServletRequest req, Model model);
// 팀 프로젝트 리스트 조회
public void getProjectList(HttpServletRequest req, Model model);
// 팀 프로젝트 조회
public void getProjectInfo(HttpServletRequest req, Model model);
// 팀 프로젝트 삭제
public void deleteProject(HttpServletRequest req, Model model);
// 팀 프로젝트 수정
public void updateProject(HttpServletRequest req, Model model);
}
| UTF-8 | Java | 854 | java | ProjectService.java | Java | []
| null | []
| package com.erp.myoffice.project.service;
import javax.servlet.http.HttpServletRequest;
import org.springframework.ui.Model;
public interface ProjectService {
// 팀장 정보 가져오기
public void getMasterInfo(HttpServletRequest req, Model model);
// 팀원 리스트 가져오기
public void getTeamMemberList(HttpServletRequest req, Model model);
// 팀 프로젝트 생성
public void createProject(HttpServletRequest req, Model model);
// 팀 프로젝트 리스트 조회
public void getProjectList(HttpServletRequest req, Model model);
// 팀 프로젝트 조회
public void getProjectInfo(HttpServletRequest req, Model model);
// 팀 프로젝트 삭제
public void deleteProject(HttpServletRequest req, Model model);
// 팀 프로젝트 수정
public void updateProject(HttpServletRequest req, Model model);
}
| 854 | 0.771505 | 0.771505 | 29 | 24.655172 | 25.807344 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.310345 | false | false | 3 |
dadd7bb420976b81c1b11b56d56d2f51f698c9ee | 21,715,354,686,085 | e16439e057cb101766cde996d6165f5c4b8d4813 | /HisCinemaDNS.java | 5c560acd544fc7135707694eff040e71863ba171 | []
| no_license | marcelpierres/Content-Distribution-Network | https://github.com/marcelpierres/Content-Distribution-Network | 2ed8e67e8d1e47e96a6085fbf9a459ae1f43a9d8 | 3fd5d2342e25036920274942d71f82320b51a7d5 | refs/heads/master | 2020-03-20T03:50:11.724000 | 2018-06-13T04:21:31 | 2018-06-13T04:21:31 | 137,161,109 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package CPS706;
import java.io.*;
import java.net.*;
class HisCinemaDNS
{
public static void main(String args[]) throws Exception
{
//===============DNS================
//=====================================
DatagramSocket serverSocket = new DatagramSocket(9877); // set port
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); //creates a new recieve packet of certain size
serverSocket.receive(receivePacket); // recieves any incoming packet
String sentence = new String( receivePacket.getData()); // converts packet to a sting
System.out.println("RECEIVED: " + sentence); // reads packet to prompt
InetAddress IPAddress = receivePacket.getAddress(); // gets the IP address of the packets origin
int port = receivePacket.getPort(); // get the port address of packets origin
String response ="Oh I know HERCDN DNS knows, go ask that server";
sendData = response.getBytes();// converts response to bytes
DatagramPacket newSendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); //creates a new packet to send back to local DNS
serverSocket.send(newSendPacket); // sends packet back to IP and port location
}
}
} | UTF-8 | Java | 1,591 | java | HisCinemaDNS.java | Java | []
| null | []
| package CPS706;
import java.io.*;
import java.net.*;
class HisCinemaDNS
{
public static void main(String args[]) throws Exception
{
//===============DNS================
//=====================================
DatagramSocket serverSocket = new DatagramSocket(9877); // set port
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); //creates a new recieve packet of certain size
serverSocket.receive(receivePacket); // recieves any incoming packet
String sentence = new String( receivePacket.getData()); // converts packet to a sting
System.out.println("RECEIVED: " + sentence); // reads packet to prompt
InetAddress IPAddress = receivePacket.getAddress(); // gets the IP address of the packets origin
int port = receivePacket.getPort(); // get the port address of packets origin
String response ="Oh I know HERCDN DNS knows, go ask that server";
sendData = response.getBytes();// converts response to bytes
DatagramPacket newSendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); //creates a new packet to send back to local DNS
serverSocket.send(newSendPacket); // sends packet back to IP and port location
}
}
} | 1,591 | 0.571339 | 0.561911 | 32 | 48.75 | 44.17437 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.78125 | false | false | 3 |
11fb695128105dc96e25fe7558d2f1a5d0213247 | 137,438,987,785 | f863c1e68a2215de65360089bbdd797d2bf615a3 | /src/main/java/ca/arsenii/plan4me/to/PlanTo.java | bfccd4e33a102770954e88ce2a959fa3b7d8caea | []
| no_license | Arsenii26/plan4me | https://github.com/Arsenii26/plan4me | 89ed01f1639aee4c21e84707ba68fdfee1b24a48 | 9d4ad8a4023c4760a8b7990b647aed2758798771 | refs/heads/master | 2022-11-23T05:19:56.988000 | 2020-02-17T20:57:53 | 2020-02-17T20:57:53 | 203,691,999 | 0 | 0 | null | false | 2022-11-16T12:24:52 | 2019-08-22T01:35:00 | 2020-10-27T16:41:26 | 2022-11-16T12:24:49 | 12,737 | 0 | 0 | 8 | Java | false | false | package ca.arsenii.plan4me.to;
import java.time.LocalDateTime;
import java.util.Objects;
public class PlanTo extends BaseTo{
private LocalDateTime dateTime;
private String plan;
public PlanTo(Integer id, LocalDateTime dateTime, String plan) {
super(id);
this.dateTime = dateTime;
this.plan = plan;
}
public PlanTo() {
}
public LocalDateTime getDateTime() {
return dateTime;
}
public String getPlan() {
return plan;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PlanTo that = (PlanTo) o;
return
Objects.equals(id, that.id) &&
Objects.equals(dateTime, that.dateTime) &&
Objects.equals(plan, that.plan);
}
@Override
public int hashCode() {
return Objects.hash(getId(), getDateTime(), getPlan());
}
@Override
public String toString() {
return "PlanTo{" +
"id=" + id +
", dateTime=" + dateTime +
", plan=" + plan +
'}';
}
}
| UTF-8 | Java | 1,197 | java | PlanTo.java | Java | []
| null | []
| package ca.arsenii.plan4me.to;
import java.time.LocalDateTime;
import java.util.Objects;
public class PlanTo extends BaseTo{
private LocalDateTime dateTime;
private String plan;
public PlanTo(Integer id, LocalDateTime dateTime, String plan) {
super(id);
this.dateTime = dateTime;
this.plan = plan;
}
public PlanTo() {
}
public LocalDateTime getDateTime() {
return dateTime;
}
public String getPlan() {
return plan;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PlanTo that = (PlanTo) o;
return
Objects.equals(id, that.id) &&
Objects.equals(dateTime, that.dateTime) &&
Objects.equals(plan, that.plan);
}
@Override
public int hashCode() {
return Objects.hash(getId(), getDateTime(), getPlan());
}
@Override
public String toString() {
return "PlanTo{" +
"id=" + id +
", dateTime=" + dateTime +
", plan=" + plan +
'}';
}
}
| 1,197 | 0.538847 | 0.538012 | 54 | 21.166666 | 18.810703 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
6f358fad1fe20e36f0cf9c3cc095de1cee3991c0 | 32,203,664,814,901 | 718e4efed4ee2cb687003550e5f4b1179993f1c0 | /src/main/java/com/odisseia/note/controller/UserController.java | 1aa5474e06d921374bca905db2ad118ad7bf8dd2 | []
| no_license | ArthurPimentabraga/note-api | https://github.com/ArthurPimentabraga/note-api | 6b2cc88d6d0f62f11821d35537531f1d0468df4d | 8556c577285d327902a877c35f583a1f75e1201a | refs/heads/master | 2022-04-18T22:45:22.510000 | 2020-04-21T23:42:57 | 2020-04-21T23:42:57 | 257,742,070 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.odisseia.note.controller;
import com.odisseia.note.domain.User;
import com.odisseia.note.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user/v1")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public ResponseEntity save(@RequestBody User user){
userService.save(user);
return new ResponseEntity(HttpStatus.CREATED);
}
@GetMapping
public ResponseEntity findAll(){
List<User> userList = userService.findAll();
return new ResponseEntity(userList, HttpStatus.OK);
}
@PutMapping
public ResponseEntity update(@RequestBody User user){
userService.save(user);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
}
| UTF-8 | Java | 992 | java | UserController.java | Java | []
| null | []
| package com.odisseia.note.controller;
import com.odisseia.note.domain.User;
import com.odisseia.note.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user/v1")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public ResponseEntity save(@RequestBody User user){
userService.save(user);
return new ResponseEntity(HttpStatus.CREATED);
}
@GetMapping
public ResponseEntity findAll(){
List<User> userList = userService.findAll();
return new ResponseEntity(userList, HttpStatus.OK);
}
@PutMapping
public ResponseEntity update(@RequestBody User user){
userService.save(user);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
}
| 992 | 0.741935 | 0.740927 | 35 | 27.342857 | 20.903784 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.457143 | false | false | 3 |
2898e8638832c495bb6029e3c715a34685b5a032 | 12,541,304,572,109 | 920ff90d92a46d0e1af45a6dcab19a27f759a3b0 | /src/main/java/com/dg/banco/bancodg/service/asesor/AsesorService.java | 7b28f854ef157c5aeb9313c912fa67f0f4a7896b | []
| no_license | geedia/banco-dg | https://github.com/geedia/banco-dg | 057d2c98777d178902cad8636e9b57dc802762e2 | a9167b895156ade287b09c7d4e8d97c91cd60cb4 | refs/heads/master | 2020-04-16T00:39:37.507000 | 2019-01-13T06:02:39 | 2019-01-13T06:02:39 | 165,146,647 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dg.banco.bancodg.service.asesor;
import java.util.List;
import java.util.Optional;
import com.dg.banco.bancodg.entity.asesor.Asesor;
/*
* Interfaz para el servicio de asesor
*/
public interface AsesorService {
public List<Asesor> listarAsesores();
public void guardarAsesor(Asesor asesor);
public void eliminarAsesor(Long id);
public Optional<Asesor> buscarAsesor(Long id);
}
| UTF-8 | Java | 399 | java | AsesorService.java | Java | []
| null | []
| package com.dg.banco.bancodg.service.asesor;
import java.util.List;
import java.util.Optional;
import com.dg.banco.bancodg.entity.asesor.Asesor;
/*
* Interfaz para el servicio de asesor
*/
public interface AsesorService {
public List<Asesor> listarAsesores();
public void guardarAsesor(Asesor asesor);
public void eliminarAsesor(Long id);
public Optional<Asesor> buscarAsesor(Long id);
}
| 399 | 0.774436 | 0.774436 | 17 | 22.470589 | 19.069895 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false | 3 |
12a93318d911b7f1a8437e9c69d655016c7ce8e6 | 28,252,294,912,823 | 6c446c51f554b94687a584997da517e73b4d64f7 | /MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxsdk/maps/Style.java | d7cea7508ccb6e7e5698d25e7d4325d2fcab66d7 | [
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
]
| permissive | mapbox/mapbox-gl-native-android | https://github.com/mapbox/mapbox-gl-native-android | ffb6e9004de088445f4752fbfaabe61d35b42f52 | 7f03a710afbd714368084e4b514d3880bad11c27 | refs/heads/main | 2023-08-24T03:53:17.293000 | 2023-04-20T10:37:35 | 2023-04-20T10:37:35 | 213,687,575 | 232 | 142 | NOASSERTION | false | 2023-04-20T10:37:36 | 2019-10-08T15:52:14 | 2023-04-17T07:13:12 | 2023-04-20T10:37:35 | 9,530 | 207 | 114 | 147 | Java | false | false | package com.mapbox.mapboxsdk.maps;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Pair;
import com.mapbox.mapboxsdk.constants.MapboxConstants;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.layers.TransitionOptions;
import com.mapbox.mapboxsdk.style.light.Light;
import com.mapbox.mapboxsdk.style.sources.Source;
import com.mapbox.mapboxsdk.utils.BitmapUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringDef;
/**
* The proxy object for current map style.
* <p>
* To create new instances of this object, create a new instance using a {@link Builder} and load the style with
* MapboxMap. This object is returned from {@link MapboxMap#getStyle()} once the style
* has been loaded by underlying map.
* </p>
*/
@SuppressWarnings("unchecked")
public class Style {
static final String EMPTY_JSON = "{\"version\": 8,\"sources\": {},\"layers\": []}";
private final NativeMap nativeMap;
private final HashMap<String, Source> sources = new HashMap<>();
private final HashMap<String, Layer> layers = new HashMap<>();
private final HashMap<String, Bitmap> images = new HashMap<>();
private final Builder builder;
private boolean fullyLoaded;
/**
* Private constructor to build a style object.
*
* @param builder the builder used for creating this style
* @param nativeMap the map object used to load this style
*/
private Style(@NonNull Builder builder, @NonNull NativeMap nativeMap) {
this.builder = builder;
this.nativeMap = nativeMap;
}
/**
* Returns the current style url.
*
* @return the style url
* @deprecated use {@link #getUri()} instead
*/
@NonNull
@Deprecated
public String getUrl() {
validateState("getUrl");
return nativeMap.getStyleUri();
}
/**
* Returns the current style uri.
*
* @return the style uri
*/
@NonNull
public String getUri() {
validateState("getUri");
return nativeMap.getStyleUri();
}
/**
* Returns the current style json.
*
* @return the style json
*/
@NonNull
public String getJson() {
validateState("getJson");
return nativeMap.getStyleJson();
}
//
// Source
//
/**
* Retrieve all the sources in the style
*
* @return all the sources in the current style
*/
@NonNull
public List<Source> getSources() {
validateState("getSources");
return nativeMap.getSources();
}
/**
* Adds the source to the map. The source must be newly created and not added to the map before
*
* @param source the source to add
*/
public void addSource(@NonNull Source source) {
validateState("addSource");
nativeMap.addSource(source);
sources.put(source.getId(), source);
}
/**
* Retrieve a source by id
*
* @param id the source's id
* @return the source if present in the current style
*/
@Nullable
public Source getSource(String id) {
validateState("getSource");
Source source = sources.get(id);
if (source == null) {
source = nativeMap.getSource(id);
}
return source;
}
/**
* Tries to cast the Source to T, throws ClassCastException if it's another type.
*
* @param sourceId the id used to look up a layer
* @param <T> the generic type of a Source
* @return the casted Source, null if another type
*/
@Nullable
public <T extends Source> T getSourceAs(@NonNull String sourceId) {
validateState("getSourceAs");
// noinspection unchecked
if (sources.containsKey(sourceId)) {
return (T) sources.get(sourceId);
}
return (T) nativeMap.getSource(sourceId);
}
/**
* Removes the source from the style.
*
* @param sourceId the source to remove
* @return true if the source was removed, false otherwise
*/
public boolean removeSource(@NonNull String sourceId) {
validateState("removeSource");
sources.remove(sourceId);
return nativeMap.removeSource(sourceId);
}
/**
* Removes the source, preserving the reference for re-use
*
* @param source the source to remove
* @return true if the source was removed, false otherwise
*/
public boolean removeSource(@NonNull Source source) {
validateState("removeSource");
sources.remove(source.getId());
return nativeMap.removeSource(source);
}
//
// Layer
//
/**
* Adds the layer to the map. The layer must be newly created and not added to the map before
*
* @param layer the layer to add
*/
public void addLayer(@NonNull Layer layer) {
validateState("addLayer");
nativeMap.addLayer(layer);
layers.put(layer.getId(), layer);
}
/**
* Adds the layer to the map. The layer must be newly created and not added to the map before
*
* @param layer the layer to add
* @param below the layer id to add this layer before
*/
public void addLayerBelow(@NonNull Layer layer, @NonNull String below) {
validateState("addLayerBelow");
nativeMap.addLayerBelow(layer, below);
layers.put(layer.getId(), layer);
}
/**
* Adds the layer to the map. The layer must be newly created and not added to the map before
*
* @param layer the layer to add
* @param above the layer id to add this layer above
*/
public void addLayerAbove(@NonNull Layer layer, @NonNull String above) {
validateState("addLayerAbove");
nativeMap.addLayerAbove(layer, above);
layers.put(layer.getId(), layer);
}
/**
* Adds the layer to the map at the specified index. The layer must be newly
* created and not added to the map before
*
* @param layer the layer to add
* @param index the index to insert the layer at
*/
public void addLayerAt(@NonNull Layer layer, @IntRange(from = 0) int index) {
validateState("addLayerAbove");
nativeMap.addLayerAt(layer, index);
layers.put(layer.getId(), layer);
}
/**
* Get the layer by id
*
* @param id the layer's id
* @return the layer, if present in the style
*/
@Nullable
public Layer getLayer(@NonNull String id) {
validateState("getLayer");
Layer layer = layers.get(id);
if (layer == null) {
layer = nativeMap.getLayer(id);
}
return layer;
}
/**
* Tries to cast the Layer to T, throws ClassCastException if it's another type.
*
* @param layerId the layer id used to look up a layer
* @param <T> the generic attribute of a Layer
* @return the casted Layer, null if another type
*/
@Nullable
public <T extends Layer> T getLayerAs(@NonNull String layerId) {
validateState("getLayerAs");
// noinspection unchecked
return (T) nativeMap.getLayer(layerId);
}
/**
* Retrieve all the layers in the style
*
* @return all the layers in the current style
*/
@NonNull
public List<Layer> getLayers() {
validateState("getLayers");
return nativeMap.getLayers();
}
/**
* Removes the layer. Any references to the layer become invalid and should not be used anymore
*
* @param layerId the layer to remove
* @return true if the layer was removed, false otherwise
*/
public boolean removeLayer(@NonNull String layerId) {
validateState("removeLayer");
layers.remove(layerId);
return nativeMap.removeLayer(layerId);
}
/**
* Removes the layer. The reference is re-usable after this and can be re-added
*
* @param layer the layer to remove
* @return true if the layer was removed, false otherwise
*/
public boolean removeLayer(@NonNull Layer layer) {
validateState("removeLayer");
layers.remove(layer.getId());
return nativeMap.removeLayer(layer);
}
/**
* Removes the layer. Any other references to the layer become invalid and should not be used anymore
*
* @param index the layer index
* @return true if the layer was removed, false otherwise
*/
public boolean removeLayerAt(@IntRange(from = 0) int index) {
validateState("removeLayerAt");
return nativeMap.removeLayerAt(index);
}
//
// Image
//
/**
* Adds an image to be used in the map's style
*
* @param name the name of the image
* @param image the pre-multiplied Bitmap
*/
public void addImage(@NonNull String name, @NonNull Bitmap image) {
addImage(name, image, false);
}
/**
* Adds an image to be used in the map's style
*
* @param name the name of the image
* @param image the pre-multiplied Bitmap
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImage(@NonNull String name, @NonNull Bitmap image, @NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
addImage(name, image, false, stretchX, stretchY, content);
}
/**
* Adds an drawable to be converted into a bitmap to be used in the map's style
*
* @param name the name of the image
* @param drawable the drawable instance to convert
*/
public void addImage(@NonNull String name, @NonNull Drawable drawable) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
addImage(name, bitmap, false);
}
/**
* Adds an drawable to be converted into a bitmap to be used in the map's style
*
* @param name the name of the image
* @param drawable the drawable instance to convert
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImage(@NonNull String name, @NonNull Drawable drawable,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
addImage(name, bitmap, false, stretchX, stretchY, content);
}
/**
* Adds an image to be used in the map's style
*
* @param name the name of the image
* @param bitmap the pre-multiplied Bitmap
* @param sdf the flag indicating image is an SDF or template image
*/
public void addImage(@NonNull final String name, @NonNull Bitmap bitmap, boolean sdf) {
validateState("addImage");
nativeMap.addImages(new Image[] {toImage(new Builder.ImageWrapper(name, bitmap, sdf))});
}
/**
* Adds an image to be used in the map's style
*
* @param name the name of the image
* @param bitmap the pre-multiplied Bitmap
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImage(@NonNull final String name, @NonNull Bitmap bitmap, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
validateState("addImage");
nativeMap.addImages(new Image[] {
toImage(new Builder.ImageWrapper(name, bitmap, sdf, stretchX, stretchY, content))});
}
/**
* Adds an image asynchronously, to be used in the map's style.
*
* @param name the name of the image
* @param image the pre-multiplied Bitmap
*/
public void addImageAsync(@NonNull String name, @NonNull Bitmap image) {
addImageAsync(name, image, false);
}
/**
* Adds an image asynchronously, to be used in the map's style.
*
* @param name the name of the image
* @param image the pre-multiplied Bitmap
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImageAsync(@NonNull String name, @NonNull Bitmap image,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
addImageAsync(name, image, false, stretchX, stretchY, content);
}
/**
* Adds an drawable asynchronously, to be converted into a bitmap to be used in the map's style.
*
* @param name the name of the image
* @param drawable the drawable instance to convert
*/
public void addImageAsync(@NonNull String name, @NonNull Drawable drawable) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
addImageAsync(name, bitmap, false);
}
/**
* Adds an drawable asynchronously, to be converted into a bitmap to be used in the map's style.
*
* @param name the name of the image
* @param drawable the drawable instance to convert
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImageAsync(@NonNull String name, @NonNull Drawable drawable,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
addImageAsync(name, bitmap, false, stretchX, stretchY, content);
}
/**
* Adds an image asynchronously, to be used in the map's style.
*
* @param name the name of the image
* @param bitmap the pre-multiplied Bitmap
* @param sdf the flag indicating image is an SDF or template image
*/
public void addImageAsync(@NonNull final String name, @NonNull Bitmap bitmap, boolean sdf) {
validateState("addImage");
new BitmapImageConversionTask(nativeMap).execute(new Builder.ImageWrapper(name, bitmap, sdf));
}
/**
* Adds an image asynchronously, to be used in the map's style.
*
* @param name the name of the image
* @param bitmap the pre-multiplied Bitmap
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImageAsync(@NonNull final String name, @NonNull Bitmap bitmap, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
validateState("addImage");
new BitmapImageConversionTask(nativeMap)
.execute(new Builder.ImageWrapper(name, bitmap, sdf, stretchX, stretchY, content));
}
/**
* Adds images to be used in the map's style.
*
* @param images the map of images to add
*/
public void addImages(@NonNull HashMap<String, Bitmap> images) {
addImages(images, false);
}
/**
* Adds images to be used in the map's style.
*
* @param images the map of images to add
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImages(@NonNull HashMap<String, Bitmap> images, @NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
addImages(images, false, stretchX, stretchY, content);
}
/**
* Adds images to be used in the map's style.
*
* @param images the map of images to add
* @param sdf the flag indicating image is an SDF or template image
*/
public void addImages(@NonNull HashMap<String, Bitmap> images, boolean sdf) {
validateState("addImage");
Image[] convertedImages = new Image[images.size()];
int index = 0;
for (Builder.ImageWrapper imageWrapper : Builder.ImageWrapper.convertToImageArray(images, sdf)) {
convertedImages[index] = toImage(imageWrapper);
index++;
}
nativeMap.addImages(convertedImages);
}
/**
* Adds images to be used in the map's style.
*
* @param images the map of images to add
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImages(@NonNull HashMap<String, Bitmap> images, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
validateState("addImage");
Image[] convertedImages = new Image[images.size()];
int index = 0;
for (Builder.ImageWrapper imageWrapper
: Builder.ImageWrapper.convertToImageArray(images, sdf, stretchX, stretchY, content)) {
convertedImages[index] = toImage(imageWrapper);
index++;
}
nativeMap.addImages(convertedImages);
}
/**
* Adds images asynchronously, to be used in the map's style.
*
* @param images the map of images to add
*/
public void addImagesAsync(@NonNull HashMap<String, Bitmap> images) {
addImagesAsync(images, false);
}
/**
* Adds images asynchronously, to be used in the map's style.
*
* @param images the map of images to add
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImagesAsync(@NonNull HashMap<String, Bitmap> images, @NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
addImagesAsync(images, false, stretchX, stretchY, content);
}
/**
* Adds images asynchronously, to be used in the map's style.
*
* @param images the map of images to add
* @param sdf the flag indicating image is an SDF or template image
*/
public void addImagesAsync(@NonNull HashMap<String, Bitmap> images, boolean sdf) {
validateState("addImages");
new BitmapImageConversionTask(nativeMap).execute(Builder.ImageWrapper.convertToImageArray(images, sdf));
}
/**
* Adds images asynchronously, to be used in the map's style.
*
* @param images the map of images to add
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImagesAsync(@NonNull HashMap<String, Bitmap> images, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
validateState("addImages");
new BitmapImageConversionTask(nativeMap)
.execute(Builder.ImageWrapper.convertToImageArray(images, sdf, stretchX, stretchY, content));
}
/**
* Add images synchronously, to be used in the map's style.
*
* @param images the array of images to add
*/
public void addImages(Image[] images) {
validateState("addImages");
nativeMap.addImages(images);
}
/**
* Removes an image from the map's style.
*
* @param name the name of the image to remove
*/
public void removeImage(@NonNull String name) {
validateState("removeImage");
nativeMap.removeImage(name);
}
/**
* Get an image from the map's style using an id.
*
* @param id the id of the image
* @return the image bitmap
*/
@Nullable
public Bitmap getImage(@NonNull String id) {
validateState("getImage");
return nativeMap.getImage(id);
}
//
// Transition
//
/**
* <p>
* Set the transition options for style changes.
* </p>
* If not set, any changes take effect without animation, besides symbols,
* which will fade in/out with a default duration after symbol collision detection.
* <p>
* To disable symbols fade in/out animation,
* pass transition options with {@link TransitionOptions#enablePlacementTransitions} equal to false.
* <p>
* Both {@link TransitionOptions#duration} and {@link TransitionOptions#delay}
* will also change the behavior of the symbols fade in/out animation if the placement transition is enabled.
*
* @param transitionOptions the transition options
*/
public void setTransition(@NonNull TransitionOptions transitionOptions) {
validateState("setTransition");
nativeMap.setTransitionOptions(transitionOptions);
}
/**
* <p>
* Get the transition options for style changes.
* </p>
* By default, any changes take effect without animation, besides symbols,
* which will fade in/out with a default duration after symbol collision detection.
* <p>
* To disable symbols fade in/out animation,
* pass transition options with {@link TransitionOptions#enablePlacementTransitions} equal to false
* into {@link #setTransition(TransitionOptions)}.
* <p>
* Both {@link TransitionOptions#duration} and {@link TransitionOptions#delay}
* will also change the behavior of the symbols fade in/out animation if the placement transition is enabled.
*
* @return TransitionOptions the transition options
*/
@NonNull
public TransitionOptions getTransition() {
validateState("getTransition");
return nativeMap.getTransitionOptions();
}
//
// Light
//
/**
* Get the light source used to change lighting conditions on extruded fill layers.
*
* @return the global light source
*/
@Nullable
public Light getLight() {
validateState("getLight");
return nativeMap.getLight();
}
//
// State
//
/**
* Called when the underlying map will start loading a new style or the map is destroyed.
* This method will clean up this style by setting the java sources and layers
* in a detached state and removing them from core.
*/
void clear() {
fullyLoaded = false;
for (Layer layer : layers.values()) {
if (layer != null) {
layer.setDetached();
}
}
for (Source source : sources.values()) {
if (source != null) {
source.setDetached();
}
}
for (Map.Entry<String, Bitmap> bitmapEntry : images.entrySet()) {
nativeMap.removeImage(bitmapEntry.getKey());
bitmapEntry.getValue().recycle();
}
sources.clear();
layers.clear();
images.clear();
}
/**
* Called when the underlying map has finished loading this style.
* This method will add all components added to the builder that were defined with the 'with' prefix.
*/
void onDidFinishLoadingStyle() {
if (!fullyLoaded) {
fullyLoaded = true;
for (Source source : builder.sources) {
addSource(source);
}
for (Builder.LayerWrapper layerWrapper : builder.layers) {
if (layerWrapper instanceof Builder.LayerAtWrapper) {
addLayerAt(layerWrapper.layer, ((Builder.LayerAtWrapper) layerWrapper).index);
} else if (layerWrapper instanceof Builder.LayerAboveWrapper) {
addLayerAbove(layerWrapper.layer, ((Builder.LayerAboveWrapper) layerWrapper).aboveLayer);
} else if (layerWrapper instanceof Builder.LayerBelowWrapper) {
addLayerBelow(layerWrapper.layer, ((Builder.LayerBelowWrapper) layerWrapper).belowLayer);
} else {
// just add layer to map, but below annotations
addLayerBelow(layerWrapper.layer, MapboxConstants.LAYER_ID_ANNOTATIONS);
}
}
for (Builder.ImageWrapper image : builder.images) {
addImage(image.id, image.bitmap, image.sdf);
}
if (builder.transitionOptions != null) {
setTransition(builder.transitionOptions);
}
}
}
/**
* Returns true if the style is fully loaded. Returns false if style hasn't been fully loaded or a new style is
* underway of being loaded.
*
* @return True if fully loaded, false otherwise
*/
public boolean isFullyLoaded() {
return fullyLoaded;
}
/**
* Validates the style state, throw an IllegalArgumentException on invalid state.
*
* @param methodCall the calling method name
*/
private void validateState(String methodCall) {
if (!fullyLoaded) {
throw new IllegalStateException(
String.format("Calling %s when a newer style is loading/has loaded.", methodCall)
);
}
}
//
// Builder
//
/**
* Builder for composing a style object.
*/
public static class Builder {
private final List<Source> sources = new ArrayList<>();
private final List<LayerWrapper> layers = new ArrayList<>();
private final List<ImageWrapper> images = new ArrayList<>();
private TransitionOptions transitionOptions;
private String styleUri;
private String styleJson;
/**
* <p>
* Will loads a new map style asynchronous from the specified URL.
* </p>
* {@code url} can take the following forms:
* <ul>
* <li>{@code Style#StyleUrl}: load one of the bundled styles in {@link Style}.</li>
* <li>{@code mapbox://styles/<user>/<style>}:
* loads the style from a <a href="https://www.mapbox.com/account/">Mapbox account.</a>
* {@code user} is your username. {@code style} is the ID of your custom
* style created in <a href="https://www.mapbox.com/studio">Mapbox Studio</a>.</li>
* <li>{@code http://...} or {@code https://...}:
* loads the style over the Internet from any web server.</li>
* <li>{@code asset://...}:
* loads the style from the APK {@code assets/} directory.
* This is used to load a style bundled with your app.</li>
* <li>{@code file://...}:
* loads the style from a file path. This is used to load a style from disk.
* </li>
* </li>
* <li>{@code null}: loads the default {@link Style#MAPBOX_STREETS} style.</li>
* </ul>
* <p>
* This method is asynchronous and will return before the style finishes loading.
* If you wish to wait for the map to finish loading, listen to the {@link MapView.OnDidFinishLoadingStyleListener}
* callback or provide an {@link OnStyleLoaded} callback when setting the style on MapboxMap.
* </p>
* If the style fails to load or an invalid style URL is set, the map view will become blank.
* An error message will be logged in the Android logcat and {@link MapView.OnDidFailLoadingMapListener} callback
* will be triggered.
*
* @param url The URL of the map style
* @return this
* @see Style
* @deprecated use {@link #fromUri(String)} instead
*/
@Deprecated
@NonNull
public Builder fromUrl(@NonNull String url) {
this.styleUri = url;
return this;
}
/**
* <p>
* Will loads a new map style asynchronous from the specified URI.
* </p>
* {@code uri} can take the following forms:
* <ul>
* <li>{@code Style#StyleUrl}: load one of the bundled styles in {@link Style}.</li>
* <li>{@code mapbox://styles/<user>/<style>}:
* loads the style from a <a href="https://www.mapbox.com/account/">Mapbox account.</a>
* {@code user} is your username. {@code style} is the ID of your custom
* style created in <a href="https://www.mapbox.com/studio">Mapbox Studio</a>.</li>
* <li>{@code http://...} or {@code https://...}:
* loads the style over the Internet from any web server.</li>
* <li>{@code asset://...}:
* loads the style from the APK {@code assets/} directory.
* This is used to load a style bundled with your app.</li>
* <li>{@code file://...}:
* loads the style from a file path. This is used to load a style from disk.
* </li>
* </li>
* <li>{@code null}: loads the default {@link Style#MAPBOX_STREETS} style.</li>
* </ul>
* <p>
* This method is asynchronous and will return before the style finishes loading.
* If you wish to wait for the map to finish loading, listen to the {@link MapView.OnDidFinishLoadingStyleListener}
* callback or use {@link MapboxMap#setStyle(String, OnStyleLoaded)} instead.
* </p>
* If the style fails to load or an invalid style URI is set, the map view will become blank.
* An error message will be logged in the Android logcat and {@link MapView.OnDidFailLoadingMapListener} callback
* will be triggered.
*
* @param uri The URI of the map style
* @return this
* @see Style
*/
@NonNull
public Builder fromUri(@NonNull String uri) {
this.styleUri = uri;
return this;
}
/**
* Will load a new map style from a json string.
* <p>
* If the style fails to load or an invalid style URI is set, the map view will become blank.
* An error message will be logged in the Android logcat and {@link MapView.OnDidFailLoadingMapListener} callback
* will be triggered.
* </p>
*
* @return this
*/
@NonNull
public Builder fromJson(@NonNull String styleJson) {
this.styleJson = styleJson;
return this;
}
/**
* Will add the source when map style has loaded.
*
* @param source the source to add
* @return this
*/
@NonNull
public Builder withSource(@NonNull Source source) {
sources.add(source);
return this;
}
/**
* Will add the sources when map style has loaded.
*
* @param sources the sources to add
* @return this
*/
@NonNull
public Builder withSources(@NonNull Source... sources) {
this.sources.addAll(Arrays.asList(sources));
return this;
}
/**
* Will add the layer when the style has loaded.
*
* @param layer the layer to be added
* @return this
*/
@NonNull
public Builder withLayer(@NonNull Layer layer) {
layers.add(new LayerWrapper(layer));
return this;
}
/**
* Will add the layers when the style has loaded.
*
* @param layers the layers to be added
* @return this
*/
@NonNull
public Builder withLayers(@NonNull Layer... layers) {
for (Layer layer : layers) {
this.layers.add(new LayerWrapper(layer));
}
return this;
}
/**
* Will add the layer when the style has loaded at a specified index.
*
* @param layer the layer to be added
* @return this
*/
@NonNull
public Builder withLayerAt(@NonNull Layer layer, int index) {
layers.add(new LayerAtWrapper(layer, index));
return this;
}
/**
* Will add the layer when the style has loaded above a specified layer id.
*
* @param layer the layer to be added
* @return this
*/
@NonNull
public Builder withLayerAbove(@NonNull Layer layer, @NonNull String aboveLayerId) {
layers.add(new LayerAboveWrapper(layer, aboveLayerId));
return this;
}
/**
* Will add the layer when the style has loaded below a specified layer id.
*
* @param layer the layer to be added
* @return this
*/
@NonNull
public Builder withLayerBelow(@NonNull Layer layer, @NonNull String belowLayerId) {
layers.add(new LayerBelowWrapper(layer, belowLayerId));
return this;
}
/**
* Will add the transition when the map style has loaded.
*
* @param transition the transition to be added
* @return this
*/
@NonNull
public Builder withTransition(@NonNull TransitionOptions transition) {
this.transitionOptions = transition;
return this;
}
/**
* Will add the drawable as image when the map style has loaded.
*
* @param id the id for the image
* @param drawable the drawable to be converted and added
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Drawable drawable) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
return this.withImage(id, bitmap, false);
}
/**
* Will add the drawable as image when the map style has loaded.
*
* @param id the id for the image
* @param drawable the drawable to be converted and added
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Drawable drawable, @NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
return this.withImage(id, bitmap, false, stretchX, stretchY, content);
}
/**
* Will add the drawables as images when the map style has loaded.
*
* @param values pairs, where first is the id for te image and second is the drawable
* @return this
*/
@NonNull
public Builder withDrawableImages(@NonNull Pair<String, Drawable>... values) {
return this.withDrawableImages(false, values);
}
/**
* Will add the image when the map style has loaded.
*
* @param id the id for the image
* @param image the image to be added
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Bitmap image) {
return this.withImage(id, image, false);
}
/**
* Will add the image when the map style has loaded.
*
* @param id the id for the image
* @param image the image to be added
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Bitmap image, @NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
return this.withImage(id, image, false, stretchX, stretchY, content);
}
/**
* Will add the images when the map style has loaded.
*
* @param values pairs, where first is the id for te image and second is the bitmap
* @return this
*/
@NonNull
public Builder withBitmapImages(@NonNull Pair<String, Bitmap>... values) {
for (Pair<String, Bitmap> value : values) {
this.withImage(value.first, value.second, false);
}
return this;
}
/**
* Will add the drawable as image when the map style has loaded.
*
* @param id the id for the image
* @param drawable the drawable to be converted and added
* @param sdf the flag indicating image is an SDF or template image
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Drawable drawable, boolean sdf) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
return this.withImage(id, bitmap, sdf);
}
/**
* Will add the drawable as image when the map style has loaded.
*
* @param id the id for the image
* @param drawable the drawable to be converted and added
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Drawable drawable, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
return this.withImage(id, bitmap, sdf, stretchX, stretchY, content);
}
/**
* Will add the drawables as images when the map style has loaded.
*
* @param sdf the flag indicating image is an SDF or template image
* @param values pairs, where first is the id for te image and second is the drawable
* @return this
*/
@NonNull
public Builder withDrawableImages(boolean sdf, @NonNull Pair<String, Drawable>... values) {
for (Pair<String, Drawable> value : values) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(value.second);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
this.withImage(value.first, bitmap, sdf);
}
return this;
}
/**
* Will add the image when the map style has loaded.
*
* @param id the id for the image
* @param image the image to be added
* @param sdf the flag indicating image is an SDF or template image
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Bitmap image, boolean sdf) {
images.add(new ImageWrapper(id, image, sdf));
return this;
}
/**
* Will add the image when the map style has loaded.
*
* @param id the id for the image
* @param image the image to be added
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Bitmap image, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
images.add(new ImageWrapper(id, image, sdf, stretchX, stretchY, content));
return this;
}
/**
* Will add the images when the map style has loaded.
*
* @param sdf the flag indicating image is an SDF or template image
* @param values pairs, where first is the id for te image and second is the bitmap
* @return this
*/
@NonNull
public Builder withBitmapImages(boolean sdf, @NonNull Pair<String, Bitmap>... values) {
for (Pair<String, Bitmap> value : values) {
this.withImage(value.first, value.second, sdf);
}
return this;
}
public String getUri() {
return styleUri;
}
public String getJson() {
return styleJson;
}
public List<Source> getSources() {
return sources;
}
public List<LayerWrapper> getLayers() {
return layers;
}
public List<ImageWrapper> getImages() {
return images;
}
TransitionOptions getTransitionOptions() {
return transitionOptions;
}
/**
* Build the composed style.
*/
Style build(@NonNull NativeMap nativeMap) {
return new Style(this, nativeMap);
}
public static class ImageWrapper {
Bitmap bitmap;
String id;
boolean sdf;
List<ImageStretches> stretchX;
List<ImageStretches> stretchY;
ImageContent content;
public ImageWrapper(String id, Bitmap bitmap, boolean sdf) {
this(id, bitmap, sdf, null, null, null);
}
public ImageWrapper(String id, Bitmap bitmap, boolean sdf, List<ImageStretches> stretchX,
List<ImageStretches> stretchY, ImageContent content) {
this.id = id;
this.bitmap = bitmap;
this.sdf = sdf;
this.stretchX = stretchX;
this.stretchY = stretchY;
this.content = content;
}
public Bitmap getBitmap() {
return bitmap;
}
public String getId() {
return id;
}
public boolean isSdf() {
return sdf;
}
public List<ImageStretches> getStretchX() {
return stretchX;
}
public List<ImageStretches> getStretchY() {
return stretchY;
}
public ImageContent getContent() {
return content;
}
public static ImageWrapper[] convertToImageArray(HashMap<String, Bitmap> bitmapHashMap, boolean sdf) {
ImageWrapper[] images = new ImageWrapper[bitmapHashMap.size()];
List<String> keyList = new ArrayList<>(bitmapHashMap.keySet());
for (int i = 0; i < bitmapHashMap.size(); i++) {
String id = keyList.get(i);
images[i] = new ImageWrapper(id, bitmapHashMap.get(id), sdf);
}
return images;
}
public static ImageWrapper[] convertToImageArray(HashMap<String, Bitmap> bitmapHashMap, boolean sdf,
List<ImageStretches> stretchX,
List<ImageStretches> stretchY,
ImageContent content) {
ImageWrapper[] images = new ImageWrapper[bitmapHashMap.size()];
List<String> keyList = new ArrayList<>(bitmapHashMap.keySet());
for (int i = 0; i < bitmapHashMap.size(); i++) {
String id = keyList.get(i);
images[i] = new ImageWrapper(id, bitmapHashMap.get(id), sdf, stretchX, stretchY, content);
}
return images;
}
}
public class LayerWrapper {
Layer layer;
LayerWrapper(Layer layer) {
this.layer = layer;
}
public Layer getLayer() {
return layer;
}
}
public class LayerAboveWrapper extends LayerWrapper {
String aboveLayer;
LayerAboveWrapper(Layer layer, String aboveLayer) {
super(layer);
this.aboveLayer = aboveLayer;
}
public String getAboveLayer() {
return aboveLayer;
}
}
public class LayerBelowWrapper extends LayerWrapper {
String belowLayer;
LayerBelowWrapper(Layer layer, String belowLayer) {
super(layer);
this.belowLayer = belowLayer;
}
public String getBelowLayer() {
return belowLayer;
}
}
public class LayerAtWrapper extends LayerWrapper {
int index;
LayerAtWrapper(Layer layer, int index) {
super(layer);
this.index = index;
}
public int getIndex() {
return index;
}
}
}
public static Image toImage(Builder.ImageWrapper imageWrapper) {
Bitmap bitmap = imageWrapper.bitmap;
if (bitmap.getConfig() != Bitmap.Config.ARGB_8888) {
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, false);
}
ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount());
bitmap.copyPixelsToBuffer(buffer);
float pixelRatio = (float) bitmap.getDensity() / DisplayMetrics.DENSITY_DEFAULT;
if (imageWrapper.getStretchX() != null && imageWrapper.getStretchY() != null) {
float[] arrayX = new float[imageWrapper.getStretchX().size() * 2];
for (int i = 0; i < imageWrapper.getStretchX().size(); i++) {
arrayX[i * 2] = imageWrapper.getStretchX().get(i).getFirst();
arrayX[i * 2 + 1] = imageWrapper.getStretchX().get(i).getSecond();
}
float[] arrayY = new float[imageWrapper.getStretchY().size() * 2];
for (int i = 0; i < imageWrapper.getStretchY().size(); i++) {
arrayY[i * 2] = imageWrapper.getStretchY().get(i).getFirst();
arrayY[i * 2 + 1] = imageWrapper.getStretchY().get(i).getSecond();
}
return new Image(buffer.array(), pixelRatio, imageWrapper.id,
bitmap.getWidth(), bitmap.getHeight(), imageWrapper.sdf, arrayX, arrayY,
imageWrapper.getContent() == null ? null : imageWrapper.getContent().getContentArray()
);
}
return new Image(buffer.array(), pixelRatio, imageWrapper.id,
bitmap.getWidth(), bitmap.getHeight(), imageWrapper.sdf
);
}
private static class BitmapImageConversionTask extends AsyncTask<Builder.ImageWrapper, Void, Image[]> {
private WeakReference<NativeMap> nativeMap;
BitmapImageConversionTask(NativeMap nativeMap) {
this.nativeMap = new WeakReference<>(nativeMap);
}
@NonNull
@Override
protected Image[] doInBackground(Builder.ImageWrapper... params) {
List<Image> images = new ArrayList<>();
for (Builder.ImageWrapper param : params) {
images.add(toImage(param));
}
return images.toArray(new Image[images.size()]);
}
@Override
protected void onPostExecute(@NonNull Image[] images) {
super.onPostExecute(images);
NativeMap nativeMap = this.nativeMap.get();
if (nativeMap != null && !nativeMap.isDestroyed()) {
nativeMap.addImages(images);
}
}
}
/**
* Callback to be invoked when a style has finished loading.
*/
public interface OnStyleLoaded {
/**
* Invoked when a style has finished loading.
*
* @param style the style that has finished loading
*/
void onStyleLoaded(@NonNull Style style);
}
//
// Style URL constants
//
/**
* Indicates the parameter accepts one of the values from Style. Using one of these
* constants means your map style will always use the latest version and may change as we
* improve the style
*/
@StringDef({MAPBOX_STREETS, OUTDOORS, LIGHT, DARK, SATELLITE, SATELLITE_STREETS, TRAFFIC_DAY, TRAFFIC_NIGHT})
@Retention(RetentionPolicy.SOURCE)
public @interface StyleUrl {
}
// IMPORTANT: If you change any of these you also need to edit them in strings.xml
/**
* Mapbox Streets: A complete basemap, perfect for incorporating your own data. Using this
* constant means your map style will always use the latest version and may change as we
* improve the style.
*/
public static final String MAPBOX_STREETS = "mapbox://styles/mapbox/streets-v11";
/**
* Outdoors: A general-purpose style tailored to outdoor activities. Using this constant means
* your map style will always use the latest version and may change as we improve the style.
*/
public static final String OUTDOORS = "mapbox://styles/mapbox/outdoors-v11";
/**
* Light: Subtle light backdrop for data visualizations. Using this constant means your map
* style will always use the latest version and may change as we improve the style.
*/
public static final String LIGHT = "mapbox://styles/mapbox/light-v10";
/**
* Dark: Subtle dark backdrop for data visualizations. Using this constant means your map style
* will always use the latest version and may change as we improve the style.
*/
public static final String DARK = "mapbox://styles/mapbox/dark-v10";
/**
* Satellite: A beautiful global satellite and aerial imagery layer. Using this constant means
* your map style will always use the latest version and may change as we improve the style.
*/
public static final String SATELLITE = "mapbox://styles/mapbox/satellite-v9";
/**
* Satellite Streets: Global satellite and aerial imagery with unobtrusive labels. Using this
* constant means your map style will always use the latest version and may change as we
* improve the style.
*/
public static final String SATELLITE_STREETS = "mapbox://styles/mapbox/satellite-streets-v11";
/**
* Traffic Day: Color-coded roads based on live traffic congestion data. Traffic data is currently
* available in
* <a href="https://www.mapbox.com/help/how-directions-work/#traffic-data">these select
* countries</a>. Using this constant means your map style will always use the latest version and
* may change as we improve the style.
*/
public static final String TRAFFIC_DAY = "mapbox://styles/mapbox/traffic-day-v2";
/**
* Traffic Night: Color-coded roads based on live traffic congestion data, designed to maximize
* legibility in low-light situations. Traffic data is currently available in
* <a href="https://www.mapbox.com/help/how-directions-work/#traffic-data">these select
* countries</a>. Using this constant means your map style will always use the latest version and
* may change as we improve the style.
*/
public static final String TRAFFIC_NIGHT = "mapbox://styles/mapbox/traffic-night-v2";
}
| UTF-8 | Java | 49,852 | java | Style.java | Java | []
| null | []
| package com.mapbox.mapboxsdk.maps;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Pair;
import com.mapbox.mapboxsdk.constants.MapboxConstants;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.layers.TransitionOptions;
import com.mapbox.mapboxsdk.style.light.Light;
import com.mapbox.mapboxsdk.style.sources.Source;
import com.mapbox.mapboxsdk.utils.BitmapUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringDef;
/**
* The proxy object for current map style.
* <p>
* To create new instances of this object, create a new instance using a {@link Builder} and load the style with
* MapboxMap. This object is returned from {@link MapboxMap#getStyle()} once the style
* has been loaded by underlying map.
* </p>
*/
@SuppressWarnings("unchecked")
public class Style {
static final String EMPTY_JSON = "{\"version\": 8,\"sources\": {},\"layers\": []}";
private final NativeMap nativeMap;
private final HashMap<String, Source> sources = new HashMap<>();
private final HashMap<String, Layer> layers = new HashMap<>();
private final HashMap<String, Bitmap> images = new HashMap<>();
private final Builder builder;
private boolean fullyLoaded;
/**
* Private constructor to build a style object.
*
* @param builder the builder used for creating this style
* @param nativeMap the map object used to load this style
*/
private Style(@NonNull Builder builder, @NonNull NativeMap nativeMap) {
this.builder = builder;
this.nativeMap = nativeMap;
}
/**
* Returns the current style url.
*
* @return the style url
* @deprecated use {@link #getUri()} instead
*/
@NonNull
@Deprecated
public String getUrl() {
validateState("getUrl");
return nativeMap.getStyleUri();
}
/**
* Returns the current style uri.
*
* @return the style uri
*/
@NonNull
public String getUri() {
validateState("getUri");
return nativeMap.getStyleUri();
}
/**
* Returns the current style json.
*
* @return the style json
*/
@NonNull
public String getJson() {
validateState("getJson");
return nativeMap.getStyleJson();
}
//
// Source
//
/**
* Retrieve all the sources in the style
*
* @return all the sources in the current style
*/
@NonNull
public List<Source> getSources() {
validateState("getSources");
return nativeMap.getSources();
}
/**
* Adds the source to the map. The source must be newly created and not added to the map before
*
* @param source the source to add
*/
public void addSource(@NonNull Source source) {
validateState("addSource");
nativeMap.addSource(source);
sources.put(source.getId(), source);
}
/**
* Retrieve a source by id
*
* @param id the source's id
* @return the source if present in the current style
*/
@Nullable
public Source getSource(String id) {
validateState("getSource");
Source source = sources.get(id);
if (source == null) {
source = nativeMap.getSource(id);
}
return source;
}
/**
* Tries to cast the Source to T, throws ClassCastException if it's another type.
*
* @param sourceId the id used to look up a layer
* @param <T> the generic type of a Source
* @return the casted Source, null if another type
*/
@Nullable
public <T extends Source> T getSourceAs(@NonNull String sourceId) {
validateState("getSourceAs");
// noinspection unchecked
if (sources.containsKey(sourceId)) {
return (T) sources.get(sourceId);
}
return (T) nativeMap.getSource(sourceId);
}
/**
* Removes the source from the style.
*
* @param sourceId the source to remove
* @return true if the source was removed, false otherwise
*/
public boolean removeSource(@NonNull String sourceId) {
validateState("removeSource");
sources.remove(sourceId);
return nativeMap.removeSource(sourceId);
}
/**
* Removes the source, preserving the reference for re-use
*
* @param source the source to remove
* @return true if the source was removed, false otherwise
*/
public boolean removeSource(@NonNull Source source) {
validateState("removeSource");
sources.remove(source.getId());
return nativeMap.removeSource(source);
}
//
// Layer
//
/**
* Adds the layer to the map. The layer must be newly created and not added to the map before
*
* @param layer the layer to add
*/
public void addLayer(@NonNull Layer layer) {
validateState("addLayer");
nativeMap.addLayer(layer);
layers.put(layer.getId(), layer);
}
/**
* Adds the layer to the map. The layer must be newly created and not added to the map before
*
* @param layer the layer to add
* @param below the layer id to add this layer before
*/
public void addLayerBelow(@NonNull Layer layer, @NonNull String below) {
validateState("addLayerBelow");
nativeMap.addLayerBelow(layer, below);
layers.put(layer.getId(), layer);
}
/**
* Adds the layer to the map. The layer must be newly created and not added to the map before
*
* @param layer the layer to add
* @param above the layer id to add this layer above
*/
public void addLayerAbove(@NonNull Layer layer, @NonNull String above) {
validateState("addLayerAbove");
nativeMap.addLayerAbove(layer, above);
layers.put(layer.getId(), layer);
}
/**
* Adds the layer to the map at the specified index. The layer must be newly
* created and not added to the map before
*
* @param layer the layer to add
* @param index the index to insert the layer at
*/
public void addLayerAt(@NonNull Layer layer, @IntRange(from = 0) int index) {
validateState("addLayerAbove");
nativeMap.addLayerAt(layer, index);
layers.put(layer.getId(), layer);
}
/**
* Get the layer by id
*
* @param id the layer's id
* @return the layer, if present in the style
*/
@Nullable
public Layer getLayer(@NonNull String id) {
validateState("getLayer");
Layer layer = layers.get(id);
if (layer == null) {
layer = nativeMap.getLayer(id);
}
return layer;
}
/**
* Tries to cast the Layer to T, throws ClassCastException if it's another type.
*
* @param layerId the layer id used to look up a layer
* @param <T> the generic attribute of a Layer
* @return the casted Layer, null if another type
*/
@Nullable
public <T extends Layer> T getLayerAs(@NonNull String layerId) {
validateState("getLayerAs");
// noinspection unchecked
return (T) nativeMap.getLayer(layerId);
}
/**
* Retrieve all the layers in the style
*
* @return all the layers in the current style
*/
@NonNull
public List<Layer> getLayers() {
validateState("getLayers");
return nativeMap.getLayers();
}
/**
* Removes the layer. Any references to the layer become invalid and should not be used anymore
*
* @param layerId the layer to remove
* @return true if the layer was removed, false otherwise
*/
public boolean removeLayer(@NonNull String layerId) {
validateState("removeLayer");
layers.remove(layerId);
return nativeMap.removeLayer(layerId);
}
/**
* Removes the layer. The reference is re-usable after this and can be re-added
*
* @param layer the layer to remove
* @return true if the layer was removed, false otherwise
*/
public boolean removeLayer(@NonNull Layer layer) {
validateState("removeLayer");
layers.remove(layer.getId());
return nativeMap.removeLayer(layer);
}
/**
* Removes the layer. Any other references to the layer become invalid and should not be used anymore
*
* @param index the layer index
* @return true if the layer was removed, false otherwise
*/
public boolean removeLayerAt(@IntRange(from = 0) int index) {
validateState("removeLayerAt");
return nativeMap.removeLayerAt(index);
}
//
// Image
//
/**
* Adds an image to be used in the map's style
*
* @param name the name of the image
* @param image the pre-multiplied Bitmap
*/
public void addImage(@NonNull String name, @NonNull Bitmap image) {
addImage(name, image, false);
}
/**
* Adds an image to be used in the map's style
*
* @param name the name of the image
* @param image the pre-multiplied Bitmap
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImage(@NonNull String name, @NonNull Bitmap image, @NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
addImage(name, image, false, stretchX, stretchY, content);
}
/**
* Adds an drawable to be converted into a bitmap to be used in the map's style
*
* @param name the name of the image
* @param drawable the drawable instance to convert
*/
public void addImage(@NonNull String name, @NonNull Drawable drawable) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
addImage(name, bitmap, false);
}
/**
* Adds an drawable to be converted into a bitmap to be used in the map's style
*
* @param name the name of the image
* @param drawable the drawable instance to convert
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImage(@NonNull String name, @NonNull Drawable drawable,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
addImage(name, bitmap, false, stretchX, stretchY, content);
}
/**
* Adds an image to be used in the map's style
*
* @param name the name of the image
* @param bitmap the pre-multiplied Bitmap
* @param sdf the flag indicating image is an SDF or template image
*/
public void addImage(@NonNull final String name, @NonNull Bitmap bitmap, boolean sdf) {
validateState("addImage");
nativeMap.addImages(new Image[] {toImage(new Builder.ImageWrapper(name, bitmap, sdf))});
}
/**
* Adds an image to be used in the map's style
*
* @param name the name of the image
* @param bitmap the pre-multiplied Bitmap
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImage(@NonNull final String name, @NonNull Bitmap bitmap, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
validateState("addImage");
nativeMap.addImages(new Image[] {
toImage(new Builder.ImageWrapper(name, bitmap, sdf, stretchX, stretchY, content))});
}
/**
* Adds an image asynchronously, to be used in the map's style.
*
* @param name the name of the image
* @param image the pre-multiplied Bitmap
*/
public void addImageAsync(@NonNull String name, @NonNull Bitmap image) {
addImageAsync(name, image, false);
}
/**
* Adds an image asynchronously, to be used in the map's style.
*
* @param name the name of the image
* @param image the pre-multiplied Bitmap
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImageAsync(@NonNull String name, @NonNull Bitmap image,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
addImageAsync(name, image, false, stretchX, stretchY, content);
}
/**
* Adds an drawable asynchronously, to be converted into a bitmap to be used in the map's style.
*
* @param name the name of the image
* @param drawable the drawable instance to convert
*/
public void addImageAsync(@NonNull String name, @NonNull Drawable drawable) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
addImageAsync(name, bitmap, false);
}
/**
* Adds an drawable asynchronously, to be converted into a bitmap to be used in the map's style.
*
* @param name the name of the image
* @param drawable the drawable instance to convert
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImageAsync(@NonNull String name, @NonNull Drawable drawable,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
addImageAsync(name, bitmap, false, stretchX, stretchY, content);
}
/**
* Adds an image asynchronously, to be used in the map's style.
*
* @param name the name of the image
* @param bitmap the pre-multiplied Bitmap
* @param sdf the flag indicating image is an SDF or template image
*/
public void addImageAsync(@NonNull final String name, @NonNull Bitmap bitmap, boolean sdf) {
validateState("addImage");
new BitmapImageConversionTask(nativeMap).execute(new Builder.ImageWrapper(name, bitmap, sdf));
}
/**
* Adds an image asynchronously, to be used in the map's style.
*
* @param name the name of the image
* @param bitmap the pre-multiplied Bitmap
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImageAsync(@NonNull final String name, @NonNull Bitmap bitmap, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
validateState("addImage");
new BitmapImageConversionTask(nativeMap)
.execute(new Builder.ImageWrapper(name, bitmap, sdf, stretchX, stretchY, content));
}
/**
* Adds images to be used in the map's style.
*
* @param images the map of images to add
*/
public void addImages(@NonNull HashMap<String, Bitmap> images) {
addImages(images, false);
}
/**
* Adds images to be used in the map's style.
*
* @param images the map of images to add
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImages(@NonNull HashMap<String, Bitmap> images, @NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
addImages(images, false, stretchX, stretchY, content);
}
/**
* Adds images to be used in the map's style.
*
* @param images the map of images to add
* @param sdf the flag indicating image is an SDF or template image
*/
public void addImages(@NonNull HashMap<String, Bitmap> images, boolean sdf) {
validateState("addImage");
Image[] convertedImages = new Image[images.size()];
int index = 0;
for (Builder.ImageWrapper imageWrapper : Builder.ImageWrapper.convertToImageArray(images, sdf)) {
convertedImages[index] = toImage(imageWrapper);
index++;
}
nativeMap.addImages(convertedImages);
}
/**
* Adds images to be used in the map's style.
*
* @param images the map of images to add
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImages(@NonNull HashMap<String, Bitmap> images, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
validateState("addImage");
Image[] convertedImages = new Image[images.size()];
int index = 0;
for (Builder.ImageWrapper imageWrapper
: Builder.ImageWrapper.convertToImageArray(images, sdf, stretchX, stretchY, content)) {
convertedImages[index] = toImage(imageWrapper);
index++;
}
nativeMap.addImages(convertedImages);
}
/**
* Adds images asynchronously, to be used in the map's style.
*
* @param images the map of images to add
*/
public void addImagesAsync(@NonNull HashMap<String, Bitmap> images) {
addImagesAsync(images, false);
}
/**
* Adds images asynchronously, to be used in the map's style.
*
* @param images the map of images to add
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImagesAsync(@NonNull HashMap<String, Bitmap> images, @NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
addImagesAsync(images, false, stretchX, stretchY, content);
}
/**
* Adds images asynchronously, to be used in the map's style.
*
* @param images the map of images to add
* @param sdf the flag indicating image is an SDF or template image
*/
public void addImagesAsync(@NonNull HashMap<String, Bitmap> images, boolean sdf) {
validateState("addImages");
new BitmapImageConversionTask(nativeMap).execute(Builder.ImageWrapper.convertToImageArray(images, sdf));
}
/**
* Adds images asynchronously, to be used in the map's style.
*
* @param images the map of images to add
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
*/
public void addImagesAsync(@NonNull HashMap<String, Bitmap> images, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
validateState("addImages");
new BitmapImageConversionTask(nativeMap)
.execute(Builder.ImageWrapper.convertToImageArray(images, sdf, stretchX, stretchY, content));
}
/**
* Add images synchronously, to be used in the map's style.
*
* @param images the array of images to add
*/
public void addImages(Image[] images) {
validateState("addImages");
nativeMap.addImages(images);
}
/**
* Removes an image from the map's style.
*
* @param name the name of the image to remove
*/
public void removeImage(@NonNull String name) {
validateState("removeImage");
nativeMap.removeImage(name);
}
/**
* Get an image from the map's style using an id.
*
* @param id the id of the image
* @return the image bitmap
*/
@Nullable
public Bitmap getImage(@NonNull String id) {
validateState("getImage");
return nativeMap.getImage(id);
}
//
// Transition
//
/**
* <p>
* Set the transition options for style changes.
* </p>
* If not set, any changes take effect without animation, besides symbols,
* which will fade in/out with a default duration after symbol collision detection.
* <p>
* To disable symbols fade in/out animation,
* pass transition options with {@link TransitionOptions#enablePlacementTransitions} equal to false.
* <p>
* Both {@link TransitionOptions#duration} and {@link TransitionOptions#delay}
* will also change the behavior of the symbols fade in/out animation if the placement transition is enabled.
*
* @param transitionOptions the transition options
*/
public void setTransition(@NonNull TransitionOptions transitionOptions) {
validateState("setTransition");
nativeMap.setTransitionOptions(transitionOptions);
}
/**
* <p>
* Get the transition options for style changes.
* </p>
* By default, any changes take effect without animation, besides symbols,
* which will fade in/out with a default duration after symbol collision detection.
* <p>
* To disable symbols fade in/out animation,
* pass transition options with {@link TransitionOptions#enablePlacementTransitions} equal to false
* into {@link #setTransition(TransitionOptions)}.
* <p>
* Both {@link TransitionOptions#duration} and {@link TransitionOptions#delay}
* will also change the behavior of the symbols fade in/out animation if the placement transition is enabled.
*
* @return TransitionOptions the transition options
*/
@NonNull
public TransitionOptions getTransition() {
validateState("getTransition");
return nativeMap.getTransitionOptions();
}
//
// Light
//
/**
* Get the light source used to change lighting conditions on extruded fill layers.
*
* @return the global light source
*/
@Nullable
public Light getLight() {
validateState("getLight");
return nativeMap.getLight();
}
//
// State
//
/**
* Called when the underlying map will start loading a new style or the map is destroyed.
* This method will clean up this style by setting the java sources and layers
* in a detached state and removing them from core.
*/
void clear() {
fullyLoaded = false;
for (Layer layer : layers.values()) {
if (layer != null) {
layer.setDetached();
}
}
for (Source source : sources.values()) {
if (source != null) {
source.setDetached();
}
}
for (Map.Entry<String, Bitmap> bitmapEntry : images.entrySet()) {
nativeMap.removeImage(bitmapEntry.getKey());
bitmapEntry.getValue().recycle();
}
sources.clear();
layers.clear();
images.clear();
}
/**
* Called when the underlying map has finished loading this style.
* This method will add all components added to the builder that were defined with the 'with' prefix.
*/
void onDidFinishLoadingStyle() {
if (!fullyLoaded) {
fullyLoaded = true;
for (Source source : builder.sources) {
addSource(source);
}
for (Builder.LayerWrapper layerWrapper : builder.layers) {
if (layerWrapper instanceof Builder.LayerAtWrapper) {
addLayerAt(layerWrapper.layer, ((Builder.LayerAtWrapper) layerWrapper).index);
} else if (layerWrapper instanceof Builder.LayerAboveWrapper) {
addLayerAbove(layerWrapper.layer, ((Builder.LayerAboveWrapper) layerWrapper).aboveLayer);
} else if (layerWrapper instanceof Builder.LayerBelowWrapper) {
addLayerBelow(layerWrapper.layer, ((Builder.LayerBelowWrapper) layerWrapper).belowLayer);
} else {
// just add layer to map, but below annotations
addLayerBelow(layerWrapper.layer, MapboxConstants.LAYER_ID_ANNOTATIONS);
}
}
for (Builder.ImageWrapper image : builder.images) {
addImage(image.id, image.bitmap, image.sdf);
}
if (builder.transitionOptions != null) {
setTransition(builder.transitionOptions);
}
}
}
/**
* Returns true if the style is fully loaded. Returns false if style hasn't been fully loaded or a new style is
* underway of being loaded.
*
* @return True if fully loaded, false otherwise
*/
public boolean isFullyLoaded() {
return fullyLoaded;
}
/**
* Validates the style state, throw an IllegalArgumentException on invalid state.
*
* @param methodCall the calling method name
*/
private void validateState(String methodCall) {
if (!fullyLoaded) {
throw new IllegalStateException(
String.format("Calling %s when a newer style is loading/has loaded.", methodCall)
);
}
}
//
// Builder
//
/**
* Builder for composing a style object.
*/
public static class Builder {
private final List<Source> sources = new ArrayList<>();
private final List<LayerWrapper> layers = new ArrayList<>();
private final List<ImageWrapper> images = new ArrayList<>();
private TransitionOptions transitionOptions;
private String styleUri;
private String styleJson;
/**
* <p>
* Will loads a new map style asynchronous from the specified URL.
* </p>
* {@code url} can take the following forms:
* <ul>
* <li>{@code Style#StyleUrl}: load one of the bundled styles in {@link Style}.</li>
* <li>{@code mapbox://styles/<user>/<style>}:
* loads the style from a <a href="https://www.mapbox.com/account/">Mapbox account.</a>
* {@code user} is your username. {@code style} is the ID of your custom
* style created in <a href="https://www.mapbox.com/studio">Mapbox Studio</a>.</li>
* <li>{@code http://...} or {@code https://...}:
* loads the style over the Internet from any web server.</li>
* <li>{@code asset://...}:
* loads the style from the APK {@code assets/} directory.
* This is used to load a style bundled with your app.</li>
* <li>{@code file://...}:
* loads the style from a file path. This is used to load a style from disk.
* </li>
* </li>
* <li>{@code null}: loads the default {@link Style#MAPBOX_STREETS} style.</li>
* </ul>
* <p>
* This method is asynchronous and will return before the style finishes loading.
* If you wish to wait for the map to finish loading, listen to the {@link MapView.OnDidFinishLoadingStyleListener}
* callback or provide an {@link OnStyleLoaded} callback when setting the style on MapboxMap.
* </p>
* If the style fails to load or an invalid style URL is set, the map view will become blank.
* An error message will be logged in the Android logcat and {@link MapView.OnDidFailLoadingMapListener} callback
* will be triggered.
*
* @param url The URL of the map style
* @return this
* @see Style
* @deprecated use {@link #fromUri(String)} instead
*/
@Deprecated
@NonNull
public Builder fromUrl(@NonNull String url) {
this.styleUri = url;
return this;
}
/**
* <p>
* Will loads a new map style asynchronous from the specified URI.
* </p>
* {@code uri} can take the following forms:
* <ul>
* <li>{@code Style#StyleUrl}: load one of the bundled styles in {@link Style}.</li>
* <li>{@code mapbox://styles/<user>/<style>}:
* loads the style from a <a href="https://www.mapbox.com/account/">Mapbox account.</a>
* {@code user} is your username. {@code style} is the ID of your custom
* style created in <a href="https://www.mapbox.com/studio">Mapbox Studio</a>.</li>
* <li>{@code http://...} or {@code https://...}:
* loads the style over the Internet from any web server.</li>
* <li>{@code asset://...}:
* loads the style from the APK {@code assets/} directory.
* This is used to load a style bundled with your app.</li>
* <li>{@code file://...}:
* loads the style from a file path. This is used to load a style from disk.
* </li>
* </li>
* <li>{@code null}: loads the default {@link Style#MAPBOX_STREETS} style.</li>
* </ul>
* <p>
* This method is asynchronous and will return before the style finishes loading.
* If you wish to wait for the map to finish loading, listen to the {@link MapView.OnDidFinishLoadingStyleListener}
* callback or use {@link MapboxMap#setStyle(String, OnStyleLoaded)} instead.
* </p>
* If the style fails to load or an invalid style URI is set, the map view will become blank.
* An error message will be logged in the Android logcat and {@link MapView.OnDidFailLoadingMapListener} callback
* will be triggered.
*
* @param uri The URI of the map style
* @return this
* @see Style
*/
@NonNull
public Builder fromUri(@NonNull String uri) {
this.styleUri = uri;
return this;
}
/**
* Will load a new map style from a json string.
* <p>
* If the style fails to load or an invalid style URI is set, the map view will become blank.
* An error message will be logged in the Android logcat and {@link MapView.OnDidFailLoadingMapListener} callback
* will be triggered.
* </p>
*
* @return this
*/
@NonNull
public Builder fromJson(@NonNull String styleJson) {
this.styleJson = styleJson;
return this;
}
/**
* Will add the source when map style has loaded.
*
* @param source the source to add
* @return this
*/
@NonNull
public Builder withSource(@NonNull Source source) {
sources.add(source);
return this;
}
/**
* Will add the sources when map style has loaded.
*
* @param sources the sources to add
* @return this
*/
@NonNull
public Builder withSources(@NonNull Source... sources) {
this.sources.addAll(Arrays.asList(sources));
return this;
}
/**
* Will add the layer when the style has loaded.
*
* @param layer the layer to be added
* @return this
*/
@NonNull
public Builder withLayer(@NonNull Layer layer) {
layers.add(new LayerWrapper(layer));
return this;
}
/**
* Will add the layers when the style has loaded.
*
* @param layers the layers to be added
* @return this
*/
@NonNull
public Builder withLayers(@NonNull Layer... layers) {
for (Layer layer : layers) {
this.layers.add(new LayerWrapper(layer));
}
return this;
}
/**
* Will add the layer when the style has loaded at a specified index.
*
* @param layer the layer to be added
* @return this
*/
@NonNull
public Builder withLayerAt(@NonNull Layer layer, int index) {
layers.add(new LayerAtWrapper(layer, index));
return this;
}
/**
* Will add the layer when the style has loaded above a specified layer id.
*
* @param layer the layer to be added
* @return this
*/
@NonNull
public Builder withLayerAbove(@NonNull Layer layer, @NonNull String aboveLayerId) {
layers.add(new LayerAboveWrapper(layer, aboveLayerId));
return this;
}
/**
* Will add the layer when the style has loaded below a specified layer id.
*
* @param layer the layer to be added
* @return this
*/
@NonNull
public Builder withLayerBelow(@NonNull Layer layer, @NonNull String belowLayerId) {
layers.add(new LayerBelowWrapper(layer, belowLayerId));
return this;
}
/**
* Will add the transition when the map style has loaded.
*
* @param transition the transition to be added
* @return this
*/
@NonNull
public Builder withTransition(@NonNull TransitionOptions transition) {
this.transitionOptions = transition;
return this;
}
/**
* Will add the drawable as image when the map style has loaded.
*
* @param id the id for the image
* @param drawable the drawable to be converted and added
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Drawable drawable) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
return this.withImage(id, bitmap, false);
}
/**
* Will add the drawable as image when the map style has loaded.
*
* @param id the id for the image
* @param drawable the drawable to be converted and added
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Drawable drawable, @NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
return this.withImage(id, bitmap, false, stretchX, stretchY, content);
}
/**
* Will add the drawables as images when the map style has loaded.
*
* @param values pairs, where first is the id for te image and second is the drawable
* @return this
*/
@NonNull
public Builder withDrawableImages(@NonNull Pair<String, Drawable>... values) {
return this.withDrawableImages(false, values);
}
/**
* Will add the image when the map style has loaded.
*
* @param id the id for the image
* @param image the image to be added
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Bitmap image) {
return this.withImage(id, image, false);
}
/**
* Will add the image when the map style has loaded.
*
* @param id the id for the image
* @param image the image to be added
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Bitmap image, @NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
return this.withImage(id, image, false, stretchX, stretchY, content);
}
/**
* Will add the images when the map style has loaded.
*
* @param values pairs, where first is the id for te image and second is the bitmap
* @return this
*/
@NonNull
public Builder withBitmapImages(@NonNull Pair<String, Bitmap>... values) {
for (Pair<String, Bitmap> value : values) {
this.withImage(value.first, value.second, false);
}
return this;
}
/**
* Will add the drawable as image when the map style has loaded.
*
* @param id the id for the image
* @param drawable the drawable to be converted and added
* @param sdf the flag indicating image is an SDF or template image
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Drawable drawable, boolean sdf) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
return this.withImage(id, bitmap, sdf);
}
/**
* Will add the drawable as image when the map style has loaded.
*
* @param id the id for the image
* @param drawable the drawable to be converted and added
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Drawable drawable, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY,
@Nullable ImageContent content) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(drawable);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
return this.withImage(id, bitmap, sdf, stretchX, stretchY, content);
}
/**
* Will add the drawables as images when the map style has loaded.
*
* @param sdf the flag indicating image is an SDF or template image
* @param values pairs, where first is the id for te image and second is the drawable
* @return this
*/
@NonNull
public Builder withDrawableImages(boolean sdf, @NonNull Pair<String, Drawable>... values) {
for (Pair<String, Drawable> value : values) {
Bitmap bitmap = BitmapUtils.getBitmapFromDrawable(value.second);
if (bitmap == null) {
throw new IllegalArgumentException("Provided drawable couldn't be converted to a Bitmap.");
}
this.withImage(value.first, bitmap, sdf);
}
return this;
}
/**
* Will add the image when the map style has loaded.
*
* @param id the id for the image
* @param image the image to be added
* @param sdf the flag indicating image is an SDF or template image
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Bitmap image, boolean sdf) {
images.add(new ImageWrapper(id, image, sdf));
return this;
}
/**
* Will add the image when the map style has loaded.
*
* @param id the id for the image
* @param image the image to be added
* @param sdf the flag indicating image is an SDF or template image
* @param stretchX image stretch areas for x axix
* @param stretchY image stretch areas for y axix
* @param content image content for text to fit
* @return this
*/
@NonNull
public Builder withImage(@NonNull String id, @NonNull Bitmap image, boolean sdf,
@NonNull List<ImageStretches> stretchX,
@NonNull List<ImageStretches> stretchY, @Nullable ImageContent content) {
images.add(new ImageWrapper(id, image, sdf, stretchX, stretchY, content));
return this;
}
/**
* Will add the images when the map style has loaded.
*
* @param sdf the flag indicating image is an SDF or template image
* @param values pairs, where first is the id for te image and second is the bitmap
* @return this
*/
@NonNull
public Builder withBitmapImages(boolean sdf, @NonNull Pair<String, Bitmap>... values) {
for (Pair<String, Bitmap> value : values) {
this.withImage(value.first, value.second, sdf);
}
return this;
}
public String getUri() {
return styleUri;
}
public String getJson() {
return styleJson;
}
public List<Source> getSources() {
return sources;
}
public List<LayerWrapper> getLayers() {
return layers;
}
public List<ImageWrapper> getImages() {
return images;
}
TransitionOptions getTransitionOptions() {
return transitionOptions;
}
/**
* Build the composed style.
*/
Style build(@NonNull NativeMap nativeMap) {
return new Style(this, nativeMap);
}
public static class ImageWrapper {
Bitmap bitmap;
String id;
boolean sdf;
List<ImageStretches> stretchX;
List<ImageStretches> stretchY;
ImageContent content;
public ImageWrapper(String id, Bitmap bitmap, boolean sdf) {
this(id, bitmap, sdf, null, null, null);
}
public ImageWrapper(String id, Bitmap bitmap, boolean sdf, List<ImageStretches> stretchX,
List<ImageStretches> stretchY, ImageContent content) {
this.id = id;
this.bitmap = bitmap;
this.sdf = sdf;
this.stretchX = stretchX;
this.stretchY = stretchY;
this.content = content;
}
public Bitmap getBitmap() {
return bitmap;
}
public String getId() {
return id;
}
public boolean isSdf() {
return sdf;
}
public List<ImageStretches> getStretchX() {
return stretchX;
}
public List<ImageStretches> getStretchY() {
return stretchY;
}
public ImageContent getContent() {
return content;
}
public static ImageWrapper[] convertToImageArray(HashMap<String, Bitmap> bitmapHashMap, boolean sdf) {
ImageWrapper[] images = new ImageWrapper[bitmapHashMap.size()];
List<String> keyList = new ArrayList<>(bitmapHashMap.keySet());
for (int i = 0; i < bitmapHashMap.size(); i++) {
String id = keyList.get(i);
images[i] = new ImageWrapper(id, bitmapHashMap.get(id), sdf);
}
return images;
}
public static ImageWrapper[] convertToImageArray(HashMap<String, Bitmap> bitmapHashMap, boolean sdf,
List<ImageStretches> stretchX,
List<ImageStretches> stretchY,
ImageContent content) {
ImageWrapper[] images = new ImageWrapper[bitmapHashMap.size()];
List<String> keyList = new ArrayList<>(bitmapHashMap.keySet());
for (int i = 0; i < bitmapHashMap.size(); i++) {
String id = keyList.get(i);
images[i] = new ImageWrapper(id, bitmapHashMap.get(id), sdf, stretchX, stretchY, content);
}
return images;
}
}
public class LayerWrapper {
Layer layer;
LayerWrapper(Layer layer) {
this.layer = layer;
}
public Layer getLayer() {
return layer;
}
}
public class LayerAboveWrapper extends LayerWrapper {
String aboveLayer;
LayerAboveWrapper(Layer layer, String aboveLayer) {
super(layer);
this.aboveLayer = aboveLayer;
}
public String getAboveLayer() {
return aboveLayer;
}
}
public class LayerBelowWrapper extends LayerWrapper {
String belowLayer;
LayerBelowWrapper(Layer layer, String belowLayer) {
super(layer);
this.belowLayer = belowLayer;
}
public String getBelowLayer() {
return belowLayer;
}
}
public class LayerAtWrapper extends LayerWrapper {
int index;
LayerAtWrapper(Layer layer, int index) {
super(layer);
this.index = index;
}
public int getIndex() {
return index;
}
}
}
public static Image toImage(Builder.ImageWrapper imageWrapper) {
Bitmap bitmap = imageWrapper.bitmap;
if (bitmap.getConfig() != Bitmap.Config.ARGB_8888) {
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, false);
}
ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount());
bitmap.copyPixelsToBuffer(buffer);
float pixelRatio = (float) bitmap.getDensity() / DisplayMetrics.DENSITY_DEFAULT;
if (imageWrapper.getStretchX() != null && imageWrapper.getStretchY() != null) {
float[] arrayX = new float[imageWrapper.getStretchX().size() * 2];
for (int i = 0; i < imageWrapper.getStretchX().size(); i++) {
arrayX[i * 2] = imageWrapper.getStretchX().get(i).getFirst();
arrayX[i * 2 + 1] = imageWrapper.getStretchX().get(i).getSecond();
}
float[] arrayY = new float[imageWrapper.getStretchY().size() * 2];
for (int i = 0; i < imageWrapper.getStretchY().size(); i++) {
arrayY[i * 2] = imageWrapper.getStretchY().get(i).getFirst();
arrayY[i * 2 + 1] = imageWrapper.getStretchY().get(i).getSecond();
}
return new Image(buffer.array(), pixelRatio, imageWrapper.id,
bitmap.getWidth(), bitmap.getHeight(), imageWrapper.sdf, arrayX, arrayY,
imageWrapper.getContent() == null ? null : imageWrapper.getContent().getContentArray()
);
}
return new Image(buffer.array(), pixelRatio, imageWrapper.id,
bitmap.getWidth(), bitmap.getHeight(), imageWrapper.sdf
);
}
private static class BitmapImageConversionTask extends AsyncTask<Builder.ImageWrapper, Void, Image[]> {
private WeakReference<NativeMap> nativeMap;
BitmapImageConversionTask(NativeMap nativeMap) {
this.nativeMap = new WeakReference<>(nativeMap);
}
@NonNull
@Override
protected Image[] doInBackground(Builder.ImageWrapper... params) {
List<Image> images = new ArrayList<>();
for (Builder.ImageWrapper param : params) {
images.add(toImage(param));
}
return images.toArray(new Image[images.size()]);
}
@Override
protected void onPostExecute(@NonNull Image[] images) {
super.onPostExecute(images);
NativeMap nativeMap = this.nativeMap.get();
if (nativeMap != null && !nativeMap.isDestroyed()) {
nativeMap.addImages(images);
}
}
}
/**
* Callback to be invoked when a style has finished loading.
*/
public interface OnStyleLoaded {
/**
* Invoked when a style has finished loading.
*
* @param style the style that has finished loading
*/
void onStyleLoaded(@NonNull Style style);
}
//
// Style URL constants
//
/**
* Indicates the parameter accepts one of the values from Style. Using one of these
* constants means your map style will always use the latest version and may change as we
* improve the style
*/
@StringDef({MAPBOX_STREETS, OUTDOORS, LIGHT, DARK, SATELLITE, SATELLITE_STREETS, TRAFFIC_DAY, TRAFFIC_NIGHT})
@Retention(RetentionPolicy.SOURCE)
public @interface StyleUrl {
}
// IMPORTANT: If you change any of these you also need to edit them in strings.xml
/**
* Mapbox Streets: A complete basemap, perfect for incorporating your own data. Using this
* constant means your map style will always use the latest version and may change as we
* improve the style.
*/
public static final String MAPBOX_STREETS = "mapbox://styles/mapbox/streets-v11";
/**
* Outdoors: A general-purpose style tailored to outdoor activities. Using this constant means
* your map style will always use the latest version and may change as we improve the style.
*/
public static final String OUTDOORS = "mapbox://styles/mapbox/outdoors-v11";
/**
* Light: Subtle light backdrop for data visualizations. Using this constant means your map
* style will always use the latest version and may change as we improve the style.
*/
public static final String LIGHT = "mapbox://styles/mapbox/light-v10";
/**
* Dark: Subtle dark backdrop for data visualizations. Using this constant means your map style
* will always use the latest version and may change as we improve the style.
*/
public static final String DARK = "mapbox://styles/mapbox/dark-v10";
/**
* Satellite: A beautiful global satellite and aerial imagery layer. Using this constant means
* your map style will always use the latest version and may change as we improve the style.
*/
public static final String SATELLITE = "mapbox://styles/mapbox/satellite-v9";
/**
* Satellite Streets: Global satellite and aerial imagery with unobtrusive labels. Using this
* constant means your map style will always use the latest version and may change as we
* improve the style.
*/
public static final String SATELLITE_STREETS = "mapbox://styles/mapbox/satellite-streets-v11";
/**
* Traffic Day: Color-coded roads based on live traffic congestion data. Traffic data is currently
* available in
* <a href="https://www.mapbox.com/help/how-directions-work/#traffic-data">these select
* countries</a>. Using this constant means your map style will always use the latest version and
* may change as we improve the style.
*/
public static final String TRAFFIC_DAY = "mapbox://styles/mapbox/traffic-day-v2";
/**
* Traffic Night: Color-coded roads based on live traffic congestion data, designed to maximize
* legibility in low-light situations. Traffic data is currently available in
* <a href="https://www.mapbox.com/help/how-directions-work/#traffic-data">these select
* countries</a>. Using this constant means your map style will always use the latest version and
* may change as we improve the style.
*/
public static final String TRAFFIC_NIGHT = "mapbox://styles/mapbox/traffic-night-v2";
}
| 49,852 | 0.652572 | 0.651809 | 1,499 | 32.25684 | 30.113064 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.414943 | false | false | 3 |
15cfc81cf5d8981dfc5f9974c7c145b636180b8f | 25,074,019,119,187 | 9e681bfb6b2d24c9ae5a733a12c661788e4b6876 | /pointoffer/src/org/dalvin/chapter7/LowestCommonParent_50.java | 12c0526eaa1542e1ed493c28401e1960eb16a89b | []
| no_license | qiudeyang/pointoffer | https://github.com/qiudeyang/pointoffer | cb83789c99878fb335a3075145a27d5eea9c076b | cf7072f8189a0cb2cad907483bcfb4d5666c7215 | refs/heads/master | 2021-01-12T09:07:59.098000 | 2017-04-27T09:33:18 | 2017-04-27T09:33:18 | 76,771,793 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.dalvin.chapter7;
import org.dalvin.chapter2.TreeNode;
import java.util.Stack;
/**
* Created by qiudeyang on 04/02/17.
*/
public class LowestCommonParent_50 {
// 遍历方式
public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == null || q == null) {
return null;
}
Stack<TreeNode> stackP = new Stack<TreeNode>();
Stack<TreeNode> stackQ = new Stack<TreeNode>();
getPath(root, p, stackP);
getPath(root, q, stackQ);
TreeNode result = null;
while (!stackP.isEmpty() && !stackQ.isEmpty() && stackP.peek() == stackQ.peek()) {
result = stackP.peek();
stackP.pop();
stackQ.pop();
}
return result;
}
// 这个代码在实现过程中,是当找到给定节点的时候才将路径依次压入stack中的,
// * 也就是说,两个stack的栈顶都是存放着root节点。
// * 因此,此时就应该找两条路径分离开之前的最后一个节点,
// * 此节点就是所求的最低公共祖先。
public static boolean getPath(TreeNode root, TreeNode p, Stack<TreeNode> stackP) {
if (root == null) {
return false;
}
if (root == p) {
stackP.push(root);
return true;
} else {
if (getPath(root.left, p, stackP) || getPath(root.right, p, stackP)) {
stackP.push(root);
return true;
} else {
return false;
}
}
}
// Leetcode上的解法,递归方式
public static TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor1(root.left, p, q);
TreeNode right = lowestCommonAncestor1(root.right, p, q);
if (left != null && right != null) {
return root;
}
return left == null ? right : left;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
System.out.println(lowestCommonAncestor(root, root.left.right, root.right.left).val);
System.out.println(lowestCommonAncestor1(root, root.left.right, root.right.left).val);
}
}
| UTF-8 | Java | 2,610 | java | LowestCommonParent_50.java | Java | [
{
"context": "eNode;\n\nimport java.util.Stack;\n\n/**\n * Created by qiudeyang on 04/02/17.\n */\npublic class LowestCommonParent_",
"end": 120,
"score": 0.999283492565155,
"start": 111,
"tag": "USERNAME",
"value": "qiudeyang"
}
]
| null | []
| package org.dalvin.chapter7;
import org.dalvin.chapter2.TreeNode;
import java.util.Stack;
/**
* Created by qiudeyang on 04/02/17.
*/
public class LowestCommonParent_50 {
// 遍历方式
public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == null || q == null) {
return null;
}
Stack<TreeNode> stackP = new Stack<TreeNode>();
Stack<TreeNode> stackQ = new Stack<TreeNode>();
getPath(root, p, stackP);
getPath(root, q, stackQ);
TreeNode result = null;
while (!stackP.isEmpty() && !stackQ.isEmpty() && stackP.peek() == stackQ.peek()) {
result = stackP.peek();
stackP.pop();
stackQ.pop();
}
return result;
}
// 这个代码在实现过程中,是当找到给定节点的时候才将路径依次压入stack中的,
// * 也就是说,两个stack的栈顶都是存放着root节点。
// * 因此,此时就应该找两条路径分离开之前的最后一个节点,
// * 此节点就是所求的最低公共祖先。
public static boolean getPath(TreeNode root, TreeNode p, Stack<TreeNode> stackP) {
if (root == null) {
return false;
}
if (root == p) {
stackP.push(root);
return true;
} else {
if (getPath(root.left, p, stackP) || getPath(root.right, p, stackP)) {
stackP.push(root);
return true;
} else {
return false;
}
}
}
// Leetcode上的解法,递归方式
public static TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor1(root.left, p, q);
TreeNode right = lowestCommonAncestor1(root.right, p, q);
if (left != null && right != null) {
return root;
}
return left == null ? right : left;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
System.out.println(lowestCommonAncestor(root, root.left.right, root.right.left).val);
System.out.println(lowestCommonAncestor1(root, root.left.right, root.right.left).val);
}
}
| 2,610 | 0.553333 | 0.545 | 74 | 31.432432 | 24.867802 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.864865 | false | false | 3 |
c5a0bec9e9c2e0675b52d5a7cb352013998025d2 | 4,861,903,025,182 | 143c21cd79bcd24f91a5d3344e2bc23f350a2e21 | /sdk/src/test/java/com/google/cloud/dataflow/sdk/PipelineTest.java | a61fad9ccaff9dd7eaae270e154b9c1078eaaccf | [
"Apache-2.0"
]
| permissive | haonature888/DataflowJavaSDK | https://github.com/haonature888/DataflowJavaSDK | 51515356fb9f581ae372750022a40acf6bcb18f6 | e6252c0e9191aef4c8bea98bdeb8340dd09d9695 | refs/heads/master | 2021-01-18T11:45:53.650000 | 2015-04-16T21:51:54 | 2015-04-16T21:51:54 | 34,178,376 | 2 | 0 | null | true | 2015-04-18T18:51:58 | 2015-04-18T18:51:58 | 2015-04-18T18:51:48 | 2015-04-16T21:51:56 | 3,642 | 0 | 0 | 0 | null | null | null | /*
* Copyright (C) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.dataflow.sdk;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.fail;
import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
import com.google.cloud.dataflow.sdk.runners.PipelineRunner;
import com.google.cloud.dataflow.sdk.util.UserCodeException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for Pipeline.
*/
@RunWith(JUnit4.class)
public class PipelineTest {
static class PipelineWrapper extends Pipeline {
protected PipelineWrapper(PipelineRunner<?> runner) {
super(runner, PipelineOptionsFactory.create());
}
}
// Mock class that throws a user code exception during the call to
// Pipeline.run().
static class TestPipelineRunnerThrowingUserException
extends PipelineRunner<PipelineResult> {
@Override
public PipelineResult run(Pipeline pipeline) {
Throwable t = new IllegalStateException("user code exception");
throw new UserCodeException(t);
}
}
// Mock class that throws an SDK or API client code exception during
// the call to Pipeline.run().
static class TestPipelineRunnerThrowingSDKException
extends PipelineRunner<PipelineResult> {
@Override
public PipelineResult run(Pipeline pipeline) {
throw new IllegalStateException("SDK exception");
}
}
@Test
public void testPipelineUserExceptionHandling() {
Pipeline p = new PipelineWrapper(
new TestPipelineRunnerThrowingUserException());
// Check pipeline runner correctly catches user errors.
try {
Object results = p.run();
fail("Should have thrown an exception.");
} catch (RuntimeException exn) {
// Make sure users don't have to worry about the
// UserCodeException wrapper.
Assert.assertThat(exn, not(instanceOf(UserCodeException.class)));
// Assert that the message is correct.
Assert.assertThat(
exn.getMessage(), containsString("user code exception"));
// Cause should be IllegalStateException.
Assert.assertThat(
exn.getCause(), instanceOf(IllegalStateException.class));
}
}
@Test
public void testPipelineSDKExceptionHandling() {
Pipeline p = new PipelineWrapper(new TestPipelineRunnerThrowingSDKException());
// Check pipeline runner correctly catches SDK errors.
try {
Object results = p.run();
fail("Should have thrown an exception.");
} catch (RuntimeException exn) {
// Make sure the exception isn't a UserCodeException.
Assert.assertThat(exn, not(instanceOf(UserCodeException.class)));
// Assert that the message is correct.
Assert.assertThat(exn.getMessage(), containsString("SDK exception"));
// RuntimeException should be IllegalStateException.
Assert.assertThat(exn, instanceOf(IllegalStateException.class));
}
}
}
| UTF-8 | Java | 3,626 | java | PipelineTest.java | Java | []
| null | []
| /*
* Copyright (C) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.dataflow.sdk;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.fail;
import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
import com.google.cloud.dataflow.sdk.runners.PipelineRunner;
import com.google.cloud.dataflow.sdk.util.UserCodeException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for Pipeline.
*/
@RunWith(JUnit4.class)
public class PipelineTest {
static class PipelineWrapper extends Pipeline {
protected PipelineWrapper(PipelineRunner<?> runner) {
super(runner, PipelineOptionsFactory.create());
}
}
// Mock class that throws a user code exception during the call to
// Pipeline.run().
static class TestPipelineRunnerThrowingUserException
extends PipelineRunner<PipelineResult> {
@Override
public PipelineResult run(Pipeline pipeline) {
Throwable t = new IllegalStateException("user code exception");
throw new UserCodeException(t);
}
}
// Mock class that throws an SDK or API client code exception during
// the call to Pipeline.run().
static class TestPipelineRunnerThrowingSDKException
extends PipelineRunner<PipelineResult> {
@Override
public PipelineResult run(Pipeline pipeline) {
throw new IllegalStateException("SDK exception");
}
}
@Test
public void testPipelineUserExceptionHandling() {
Pipeline p = new PipelineWrapper(
new TestPipelineRunnerThrowingUserException());
// Check pipeline runner correctly catches user errors.
try {
Object results = p.run();
fail("Should have thrown an exception.");
} catch (RuntimeException exn) {
// Make sure users don't have to worry about the
// UserCodeException wrapper.
Assert.assertThat(exn, not(instanceOf(UserCodeException.class)));
// Assert that the message is correct.
Assert.assertThat(
exn.getMessage(), containsString("user code exception"));
// Cause should be IllegalStateException.
Assert.assertThat(
exn.getCause(), instanceOf(IllegalStateException.class));
}
}
@Test
public void testPipelineSDKExceptionHandling() {
Pipeline p = new PipelineWrapper(new TestPipelineRunnerThrowingSDKException());
// Check pipeline runner correctly catches SDK errors.
try {
Object results = p.run();
fail("Should have thrown an exception.");
} catch (RuntimeException exn) {
// Make sure the exception isn't a UserCodeException.
Assert.assertThat(exn, not(instanceOf(UserCodeException.class)));
// Assert that the message is correct.
Assert.assertThat(exn.getMessage(), containsString("SDK exception"));
// RuntimeException should be IllegalStateException.
Assert.assertThat(exn, instanceOf(IllegalStateException.class));
}
}
}
| 3,626 | 0.727523 | 0.724766 | 105 | 33.533333 | 26.246475 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false | 3 |
78959664eef8140ca4ded92a15e720638d1ea67a | 11,536,282,192,754 | 0e9c6f5d27bdf3b54fc6e1f10bd371ead4a914c3 | /mysystem/src/main/java/com/graduation/controller/LoginController.java | 651fa0481cead75af0905109c32910aac95c0339 | []
| no_license | SmallAirP/graduation | https://github.com/SmallAirP/graduation | 8f119f9e84ade9bae574771fcfb88b5f4a495f92 | ceb4b6e1e289129cb31d6aa226aa10a09fb847c9 | refs/heads/master | 2022-11-13T02:34:18.861000 | 2020-06-30T07:47:22 | 2020-06-30T07:47:22 | 276,033,747 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.graduation.controller;
import com.graduation.bean.User;
import com.graduation.mapper.UserMapper;
import com.graduation.tool.CryptoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Controller
public class LoginController {
@Autowired
private UserMapper mapper;
@PostMapping(value = "/user/checklogin")
public String login(@RequestParam("username") String name,
@RequestParam("password") String password,
Map<String,Object> map,
HttpSession session){
if(!StringUtils.isEmpty(name)){
User user= mapper.getUserByName(name);
String p = CryptoUtil.encode(password);
//判断用户名、密码是否正确
if (p.equals(user.getPassword())){
//将用户信息存入session中
session.setAttribute("loginuser",user);
session.setAttribute("isT","y");
session.setAttribute("id",user.getId());
return "redirect:/index.html";
}else{
map.put("msg","用户名密码错误");
return "login";
}
}else{
map.put("msg","用户名密码错误");
return "login";
}
}
}
| UTF-8 | Java | 1,642 | java | LoginController.java | Java | [
{
"context": "ecklogin\")\n public String login(@RequestParam(\"username\") String name,\n @RequestPa",
"end": 727,
"score": 0.9936403632164001,
"start": 719,
"tag": "USERNAME",
"value": "username"
}
]
| null | []
| package com.graduation.controller;
import com.graduation.bean.User;
import com.graduation.mapper.UserMapper;
import com.graduation.tool.CryptoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Controller
public class LoginController {
@Autowired
private UserMapper mapper;
@PostMapping(value = "/user/checklogin")
public String login(@RequestParam("username") String name,
@RequestParam("password") String password,
Map<String,Object> map,
HttpSession session){
if(!StringUtils.isEmpty(name)){
User user= mapper.getUserByName(name);
String p = CryptoUtil.encode(password);
//判断用户名、密码是否正确
if (p.equals(user.getPassword())){
//将用户信息存入session中
session.setAttribute("loginuser",user);
session.setAttribute("isT","y");
session.setAttribute("id",user.getId());
return "redirect:/index.html";
}else{
map.put("msg","用户名密码错误");
return "login";
}
}else{
map.put("msg","用户名密码错误");
return "login";
}
}
}
| 1,642 | 0.625159 | 0.625159 | 49 | 31.12245 | 20.704561 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.653061 | false | false | 3 |
6a63fa99a5ea8b5d34acbb59e2a7cf98336f94b0 | 12,704,513,312,996 | a651a2bcaa8cc1400d78da92a0ae24fdb5ebf676 | /org.activiti.designer.kickstart.gui.process/src/main/java/org/activiti/designer/kickstart/process/features/CreateEmailStepFeature.java | f0b58d5b9d3da455f9ca8860ea303dc760137744 | []
| no_license | chrisrobbo/Activiti-Designer | https://github.com/chrisrobbo/Activiti-Designer | 3612af031324d2c701e031ef3a3c1af0f01d6b29 | 051b1d6d262b8cdb5c39f764237c0e91b038498f | refs/heads/master | 2020-12-30T22:56:16.300000 | 2018-10-18T00:18:09 | 2018-10-18T00:18:09 | 56,194,583 | 0 | 1 | null | true | 2016-04-14T00:17:10 | 2016-04-14T00:17:10 | 2016-04-12T01:23:16 | 2016-02-05T20:14:51 | 21,405 | 0 | 0 | 0 | null | null | null | package org.activiti.designer.kickstart.process.features;
import org.activiti.designer.kickstart.process.KickstartProcessPluginImage;
import org.activiti.designer.kickstart.process.diagram.KickstartProcessFeatureProvider;
import org.activiti.workflow.simple.alfresco.step.AlfrescoEmailStepDefinition;
import org.activiti.workflow.simple.definition.StepDefinition;
import org.eclipse.graphiti.features.context.ICreateContext;
public class CreateEmailStepFeature extends AbstractCreateStepDefinitionFeature {
public static final String FEATURE_ID_KEY = "email-step";
public CreateEmailStepFeature(KickstartProcessFeatureProvider fp) {
super(fp, "Email step", "Add an email step");
}
@Override
public boolean canCreate(ICreateContext context) {
return true;
}
@Override
protected StepDefinition createStepDefinition(ICreateContext context) {
AlfrescoEmailStepDefinition definition = new AlfrescoEmailStepDefinition();
definition.setName("Email step");
return definition;
}
@Override
public String getCreateImageId() {
return KickstartProcessPluginImage.EMAIL_STEP_ICON.getImageKey();
}
} | UTF-8 | Java | 1,141 | java | CreateEmailStepFeature.java | Java | [
{
"context": "public static final String FEATURE_ID_KEY = \"email-step\";\n\n public CreateEmailStepFeature(KickstartProce",
"end": 567,
"score": 0.7145600318908691,
"start": 563,
"tag": "KEY",
"value": "step"
}
]
| null | []
| package org.activiti.designer.kickstart.process.features;
import org.activiti.designer.kickstart.process.KickstartProcessPluginImage;
import org.activiti.designer.kickstart.process.diagram.KickstartProcessFeatureProvider;
import org.activiti.workflow.simple.alfresco.step.AlfrescoEmailStepDefinition;
import org.activiti.workflow.simple.definition.StepDefinition;
import org.eclipse.graphiti.features.context.ICreateContext;
public class CreateEmailStepFeature extends AbstractCreateStepDefinitionFeature {
public static final String FEATURE_ID_KEY = "email-step";
public CreateEmailStepFeature(KickstartProcessFeatureProvider fp) {
super(fp, "Email step", "Add an email step");
}
@Override
public boolean canCreate(ICreateContext context) {
return true;
}
@Override
protected StepDefinition createStepDefinition(ICreateContext context) {
AlfrescoEmailStepDefinition definition = new AlfrescoEmailStepDefinition();
definition.setName("Email step");
return definition;
}
@Override
public String getCreateImageId() {
return KickstartProcessPluginImage.EMAIL_STEP_ICON.getImageKey();
}
} | 1,141 | 0.80631 | 0.80631 | 33 | 33.60606 | 31.502707 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 3 |
c5b2336aa55edd872ecca8d1051ce12c638c2411 | 22,874,995,870,105 | c0456d9871e8cd204024bc0e9252d11fb0d7de60 | /picture_library/src/main/java/com/luck/picture/lib/SpacesItemDecoration.java | 20579804532b64e81dc64be741a7c64f8c9cf8bc | []
| no_license | githubwxq/DevelopTools | https://github.com/githubwxq/DevelopTools | c3c85747604131280c40be9684a3179deb49f97c | 6b08b91897816845ed7f0f17eeeb3afa170586d1 | refs/heads/master | 2022-10-12T09:50:01.189000 | 2022-09-26T06:50:13 | 2022-09-26T06:50:13 | 138,365,510 | 10 | 6 | null | false | 2019-01-08T07:01:07 | 2018-06-23T02:37:50 | 2019-01-08T03:32:03 | 2019-01-08T07:01:06 | 10,925 | 3 | 2 | 0 | Java | false | null | package com.luck.picture.lib;
import android.graphics.Rect;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
/**
* 右边有 最后一项没有 上面的间距 处理右面的间距
*/
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
private int span; //列数
// 右边间距
public SpacesItemDecoration(int space, int span) {
this.space = space;
this.span = span;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) <= span - 1) { //第一行上边距不需要
outRect.top = 0;
} else {
outRect.top = (int) (parent.getResources().getDisplayMetrics().density * space + 0.5f);
}
if ((parent.getChildAdapterPosition(view) + 1) % span == 0) { //列的倍数右边距不需要
outRect.right = 0;
} else {
outRect.right = (int) (parent.getResources().getDisplayMetrics().density * space + 0.5f);
}
}
}
//
//最后在说下我理解的等间距的原理
// 比如我想给间距设置成20
//那我们考虑到上面说的叠加 设置间距我只设置一半 就是10
// 在代码里在给recyclerview设置一个10的内边距
//这样就间距就都是20了 | UTF-8 | Java | 1,398 | java | SpacesItemDecoration.java | Java | []
| null | []
| package com.luck.picture.lib;
import android.graphics.Rect;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
/**
* 右边有 最后一项没有 上面的间距 处理右面的间距
*/
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
private int span; //列数
// 右边间距
public SpacesItemDecoration(int space, int span) {
this.space = space;
this.span = span;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) <= span - 1) { //第一行上边距不需要
outRect.top = 0;
} else {
outRect.top = (int) (parent.getResources().getDisplayMetrics().density * space + 0.5f);
}
if ((parent.getChildAdapterPosition(view) + 1) % span == 0) { //列的倍数右边距不需要
outRect.right = 0;
} else {
outRect.right = (int) (parent.getResources().getDisplayMetrics().density * space + 0.5f);
}
}
}
//
//最后在说下我理解的等间距的原理
// 比如我想给间距设置成20
//那我们考虑到上面说的叠加 设置间距我只设置一半 就是10
// 在代码里在给recyclerview设置一个10的内边距
//这样就间距就都是20了 | 1,398 | 0.640275 | 0.625645 | 45 | 24.844444 | 28.834358 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.355556 | false | false | 3 |
af369543c1d0746f58c2614cd2da4cad7d224731 | 22,874,995,869,712 | 518017a73d63ea162e12063f2ce456d7f47a7d6d | /03-tag/rel-v1.0.0beta/03-tag/tag-v0.9.1beta/01-core/src/sys/spvisor/core/service/user/center/UserCenterService.java | bdb0661c313cfb5bbcfc9027d4c2ded5c15b96dc | []
| no_license | wzc99/MaurerlabSupervision | https://github.com/wzc99/MaurerlabSupervision | 7a1a9f21feb032cfc5d2085730dfc37f96177e4c | 105cd643795fd15c2f6d5ca856c51a460169189d | refs/heads/master | 2020-03-19T11:53:45.364000 | 2018-06-07T15:09:26 | 2018-06-07T15:09:26 | 136,483,463 | 0 | 0 | null | true | 2018-06-07T13:44:16 | 2018-06-07T13:44:16 | 2018-05-24T14:25:20 | 2018-06-07T13:40:23 | 112,117 | 0 | 0 | 0 | null | false | null | package sys.spvisor.core.service.user.center;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sys.spvisor.core.dao.ana.RoleDao;
import sys.spvisor.core.dao.ana.TUserMapper;
import sys.spvisor.core.dao.ana.TUserRoleMapper;
import sys.spvisor.core.dao.ana.UserDao;
import sys.spvisor.core.entity.ana.TUser;
import sys.spvisor.core.entity.ana.TUserRole;
import sys.spvisor.core.entity.ana.TUserRoleExample;
import sys.spvisor.core.entity.ana.User;
import sys.spvisor.core.entity.ana.UserCase;
import sys.spvisor.core.service.ana.RoleService;
@Service
public class UserCenterService {
@Autowired
UserDao userDao;
@Autowired
RoleDao roleDao;
@Autowired
RoleService roleService;
@Autowired
private TUserMapper TUserMapper;
@Autowired
private TUserRoleMapper TUserRoleMapper;
// @Autowired
// UserCaseDao userCaseDao;
public User getUserByUserId(Long userId) {
return userDao.getById(userId,false);
}
// public UserCase getUserCaseByUserCaseId(Long userId) {
// return userCaseDao.getById(userId,false);
// }
@Transactional
// public void editUser(User user, String roles) {
public Long editUser(UserCase user) {
TUser Tuser = new TUser();
Tuser.setUserName(user.getName());
Tuser.setUserId(Integer.parseInt(String.valueOf(user.getId())));
Tuser.setStatus(user.getStatus());
Tuser.setMemo(user.getMemo());
Tuser.setExpirationDate(user.getExpirationDate());
Tuser.setUpdateDatetime(new Date());
TUserMapper.updateByPrimaryKeySelective(Tuser);
TUserRoleExample example = new TUserRoleExample();
sys.spvisor.core.entity.ana.TUserRoleExample.Criteria Criteria = example.createCriteria();
Criteria.andUserIdEqualTo(Tuser.getUserId());
TUserRoleMapper.deleteByExample(example);
Long newUserId = user.getId();
if(user.getRoles() != null){
String[] roleIds = user.getRoles().split(";|,");
for (String roleId : roleIds) {
// userCaseDao.insertUserRole(user.getId(), Long.parseLong(roleId));
TUserRole userrole = new TUserRole();
userrole.setUserId(Tuser.getUserId());
userrole.setRoleId(Integer.parseInt(roleId));
TUserRoleMapper.insertSelective(userrole);
}
}
return newUserId;
}
}
| UTF-8 | Java | 2,337 | java | UserCenterService.java | Java | []
| null | []
| package sys.spvisor.core.service.user.center;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sys.spvisor.core.dao.ana.RoleDao;
import sys.spvisor.core.dao.ana.TUserMapper;
import sys.spvisor.core.dao.ana.TUserRoleMapper;
import sys.spvisor.core.dao.ana.UserDao;
import sys.spvisor.core.entity.ana.TUser;
import sys.spvisor.core.entity.ana.TUserRole;
import sys.spvisor.core.entity.ana.TUserRoleExample;
import sys.spvisor.core.entity.ana.User;
import sys.spvisor.core.entity.ana.UserCase;
import sys.spvisor.core.service.ana.RoleService;
@Service
public class UserCenterService {
@Autowired
UserDao userDao;
@Autowired
RoleDao roleDao;
@Autowired
RoleService roleService;
@Autowired
private TUserMapper TUserMapper;
@Autowired
private TUserRoleMapper TUserRoleMapper;
// @Autowired
// UserCaseDao userCaseDao;
public User getUserByUserId(Long userId) {
return userDao.getById(userId,false);
}
// public UserCase getUserCaseByUserCaseId(Long userId) {
// return userCaseDao.getById(userId,false);
// }
@Transactional
// public void editUser(User user, String roles) {
public Long editUser(UserCase user) {
TUser Tuser = new TUser();
Tuser.setUserName(user.getName());
Tuser.setUserId(Integer.parseInt(String.valueOf(user.getId())));
Tuser.setStatus(user.getStatus());
Tuser.setMemo(user.getMemo());
Tuser.setExpirationDate(user.getExpirationDate());
Tuser.setUpdateDatetime(new Date());
TUserMapper.updateByPrimaryKeySelective(Tuser);
TUserRoleExample example = new TUserRoleExample();
sys.spvisor.core.entity.ana.TUserRoleExample.Criteria Criteria = example.createCriteria();
Criteria.andUserIdEqualTo(Tuser.getUserId());
TUserRoleMapper.deleteByExample(example);
Long newUserId = user.getId();
if(user.getRoles() != null){
String[] roleIds = user.getRoles().split(";|,");
for (String roleId : roleIds) {
// userCaseDao.insertUserRole(user.getId(), Long.parseLong(roleId));
TUserRole userrole = new TUserRole();
userrole.setUserId(Tuser.getUserId());
userrole.setRoleId(Integer.parseInt(roleId));
TUserRoleMapper.insertSelective(userrole);
}
}
return newUserId;
}
}
| 2,337 | 0.764656 | 0.764656 | 84 | 26.821428 | 22.053593 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.785714 | false | false | 3 |
8e9c86195a4bb6902888fdf1347c6c7bda440f88 | 17,136,919,565,719 | 7c72cb055c2905aea3e7f971808b13113ca66c88 | /calculadora/src/calcudaroraTest.java | a1712efce460116de8e65399d4c47d3bbe72a952 | []
| no_license | tejedorjesus/Segundo-trimestre | https://github.com/tejedorjesus/Segundo-trimestre | 193cfbbd7cf57b83d2b82bf69bce884bb0dff3f8 | 9ea8a8f2446a66aab86653c8d66a43e525c863d4 | refs/heads/master | 2021-05-06T08:18:32.914000 | 2018-04-23T19:48:25 | 2018-04-23T19:48:25 | 114,010,918 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import static org.junit.Assert.*;
import org.junit.Test;
public class calcudaroraTest {
@Test
public void testObject() {
fail("Not yet implemented");
}
@Test
public void testGetClass() {
fail("Not yet implemented");
}
@Test
public void testHashCode() {
fail("Not yet implemented");
}
@Test
public void testEquals() {
fail("Not yet implemented");
}
}
| UTF-8 | Java | 377 | java | calcudaroraTest.java | Java | []
| null | []
| import static org.junit.Assert.*;
import org.junit.Test;
public class calcudaroraTest {
@Test
public void testObject() {
fail("Not yet implemented");
}
@Test
public void testGetClass() {
fail("Not yet implemented");
}
@Test
public void testHashCode() {
fail("Not yet implemented");
}
@Test
public void testEquals() {
fail("Not yet implemented");
}
}
| 377 | 0.67374 | 0.67374 | 27 | 12.962963 | 13.384572 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.962963 | false | false | 3 |
20a85175ab9ed95028e1e38d41fd0bf9564a4885 | 16,956,530,952,199 | 82b44ff7014cd29c87c75ea838f5d2608996967d | /MovieCatalogueService/src/main/java/com/java/microservices/resources/MovieCatalogueResource.java | 6486fac61f754a94a9225ac880566e42e5344b43 | []
| no_license | shivam13singh94/MicroservicesUsingSpringBoot | https://github.com/shivam13singh94/MicroservicesUsingSpringBoot | 8ae5a3027c50d1521f455eaa42fa8f0a9354ff9c | 4bbfb0876d1329d583faa8edf3054aa836735f2b | refs/heads/main | 2023-04-22T21:21:31.023000 | 2021-04-29T21:21:25 | 2021-04-29T21:21:25 | 362,924,804 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.java.microservices.resources;
import java.util.Collections;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.java.microservices.model.CatalogueItem;
@RestController
@RequestMapping("/catalogue")
public class MovieCatalogueResource {
@GetMapping("/{userId}")
public List<CatalogueItem> getCatalog(@PathVariable("userId") String userId) {
return Collections.singletonList(new CatalogueItem("Aspirants", "Best Show Ever", 5));
}
}
| UTF-8 | Java | 684 | java | MovieCatalogueResource.java | Java | []
| null | []
| package com.java.microservices.resources;
import java.util.Collections;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.java.microservices.model.CatalogueItem;
@RestController
@RequestMapping("/catalogue")
public class MovieCatalogueResource {
@GetMapping("/{userId}")
public List<CatalogueItem> getCatalog(@PathVariable("userId") String userId) {
return Collections.singletonList(new CatalogueItem("Aspirants", "Best Show Ever", 5));
}
}
| 684 | 0.809942 | 0.80848 | 24 | 27.5 | 28.179483 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 3 |
e2f36e0786ef09e46e5e9c5a578ccc30410ec5fc | 27,444,841,084,512 | 64841873d47dbba4a4682441e6473e7072695af8 | /app/src/main/java/de/umr/jepc/android/adapter/core/Adapter.java | 864fb8f4f3f3d928b60ba79edf647fb353101269 | []
| no_license | 3472/TestApplikation | https://github.com/3472/TestApplikation | 3d154e4b86edfdbc9f3b916b0d79f3c15bc7ce45 | 654ce233d4e7fbab90a537c3515bb0861d44f8c5 | refs/heads/master | 2017-12-22T11:01:58.119000 | 2016-03-15T22:01:55 | 2016-03-15T22:01:55 | 53,982,019 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.umr.jepc.android.adapter.core;
import android.jepc.umr.de.servicelibrary.Event;
import android.jepc.umr.de.servicelibrary.EventStream;
import android.jepc.umr.de.servicelibrary.Query;
import java.util.ArrayList;
/**
* Created by gerald on 03.10.15.
*/
/**
* An Adapter is used to convert events coming from an event source
* to a format that the cep engine can process
*
* @author Gerald Bründl
*/
public class Adapter implements IAdapter {
/**
* The client where this adapter is registered
*/
protected ICEPClient cepClient;
/**
* List of the streams to be registered with the adapter
*/
protected ArrayList<EventStream> streams = new ArrayList<EventStream>();
/**
* List of queries to be registered with the adapter
*/
protected ArrayList<Query> queries = new ArrayList<Query>();
/**
* Creates a new Adapter which sends events to the provided client
*
* @param cepClient
*/
public Adapter(ICEPClient cepClient) {
this.cepClient = cepClient;
}
/**
* Create an event from a list of attributes and add an id
*
* @param id the id for this event
* @param attributes list of attribute values
* @return event as object array
*/
public Object[] createEvent(int id, Object... attributes) {
Object[] event = new Object[attributes.length + 1];
event[0] = id;
System.arraycopy(attributes, 0, event, 1, attributes.length);
return event;
}
/**
* push an event to the eventqueue of the coresponding client
*
* @param streamname the name of the stream which this event belongs to
* @param event the event itself
* @param timestamp a timestamp for when the event was created
*/
public void pushEvent(String streamname, Object[] event, long timestamp) {
pushEvent(new Event(streamname, event, timestamp));
}
/**
* add event to the eventqueue of the coresponding client
*
* @param event the event which is added
*/
public void pushEvent(Event event) {
cepClient.getEventQueue().offer(event);
}
/**
* @return list of the streams which are to be registered for this adapter
*/
public ArrayList<EventStream> getStreams() {
return streams;
}
/**
* @return list of the the queriese which are to be registered for this adapter
*/
public ArrayList<Query> getQueries() {
return queries;
}
}
| UTF-8 | Java | 2,531 | java | Adapter.java | Java | [
{
"context": ";\n\nimport java.util.ArrayList;\n\n\n/**\n * Created by gerald on 03.10.15.\n */\n\n/**\n * An Adapter is used to co",
"end": 251,
"score": 0.9429752826690674,
"start": 245,
"tag": "USERNAME",
"value": "gerald"
},
{
"context": "rmat that the cep engine can process\n *\n * @author Gerald Bründl\n */\npublic class Adapter implements IAdapter {\n\n ",
"end": 416,
"score": 0.999896228313446,
"start": 403,
"tag": "NAME",
"value": "Gerald Bründl"
}
]
| null | []
| package de.umr.jepc.android.adapter.core;
import android.jepc.umr.de.servicelibrary.Event;
import android.jepc.umr.de.servicelibrary.EventStream;
import android.jepc.umr.de.servicelibrary.Query;
import java.util.ArrayList;
/**
* Created by gerald on 03.10.15.
*/
/**
* An Adapter is used to convert events coming from an event source
* to a format that the cep engine can process
*
* @author <NAME>
*/
public class Adapter implements IAdapter {
/**
* The client where this adapter is registered
*/
protected ICEPClient cepClient;
/**
* List of the streams to be registered with the adapter
*/
protected ArrayList<EventStream> streams = new ArrayList<EventStream>();
/**
* List of queries to be registered with the adapter
*/
protected ArrayList<Query> queries = new ArrayList<Query>();
/**
* Creates a new Adapter which sends events to the provided client
*
* @param cepClient
*/
public Adapter(ICEPClient cepClient) {
this.cepClient = cepClient;
}
/**
* Create an event from a list of attributes and add an id
*
* @param id the id for this event
* @param attributes list of attribute values
* @return event as object array
*/
public Object[] createEvent(int id, Object... attributes) {
Object[] event = new Object[attributes.length + 1];
event[0] = id;
System.arraycopy(attributes, 0, event, 1, attributes.length);
return event;
}
/**
* push an event to the eventqueue of the coresponding client
*
* @param streamname the name of the stream which this event belongs to
* @param event the event itself
* @param timestamp a timestamp for when the event was created
*/
public void pushEvent(String streamname, Object[] event, long timestamp) {
pushEvent(new Event(streamname, event, timestamp));
}
/**
* add event to the eventqueue of the coresponding client
*
* @param event the event which is added
*/
public void pushEvent(Event event) {
cepClient.getEventQueue().offer(event);
}
/**
* @return list of the streams which are to be registered for this adapter
*/
public ArrayList<EventStream> getStreams() {
return streams;
}
/**
* @return list of the the queriese which are to be registered for this adapter
*/
public ArrayList<Query> getQueries() {
return queries;
}
}
| 2,523 | 0.644664 | 0.640711 | 93 | 26.204302 | 25.82387 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.27957 | false | false | 3 |
f7651b1971a6c9b4161933651f8d9e37cd7adcbc | 14,302,241,161,864 | dbf3e1f21a76b93a7f7154afd43af6b2c35a33ea | /core/src/io/dico/dicore/config/serializers/IConfigSerializer.java | 3be27884aca364891ac9b7c1bdcd6fed7db64829 | []
| no_license | Dico200/dicore3 | https://github.com/Dico200/dicore3 | d6df6a624f5233e359be3151025b39d2b44b499d | e927c1381fbd96fe7088446a3f1e0b673e0c7867 | refs/heads/master | 2021-10-23T01:06:03.609000 | 2019-03-14T04:03:56 | 2019-03-14T04:03:56 | 113,863,385 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.dico.dicore.config.serializers;
import io.dico.dicore.config.ConfigLogging;
import java.util.function.UnaryOperator;
public interface IConfigSerializer<T> {
SerializerResult<T> load(Object source, ConfigLogging logger);
T defaultValue();
Object serialize(T value);
Class<T> type();
default String inputTypeName() {
return type().getSimpleName();
}
default <TOut> IConfigSerializer<TOut> map(IConfigSerializerMapper<T, TOut> mapper) {
return MappedSerializer.map(BaseConfigSerializer.wrap(this), mapper);
}
default IConfigSerializer<T> mapLoadOnly(UnaryOperator<SerializerResult<T>> load) {
return map(MapperWithLambdas.loadOnlyMapper(type(), load));
}
default IConfigSerializer<T> mapLoadOnlySimple(UnaryOperator<T> load) {
return map(MapperWithLambdas.simpleLoadOnlyMapper(type(), load));
}
}
| UTF-8 | Java | 933 | java | IConfigSerializer.java | Java | []
| null | []
| package io.dico.dicore.config.serializers;
import io.dico.dicore.config.ConfigLogging;
import java.util.function.UnaryOperator;
public interface IConfigSerializer<T> {
SerializerResult<T> load(Object source, ConfigLogging logger);
T defaultValue();
Object serialize(T value);
Class<T> type();
default String inputTypeName() {
return type().getSimpleName();
}
default <TOut> IConfigSerializer<TOut> map(IConfigSerializerMapper<T, TOut> mapper) {
return MappedSerializer.map(BaseConfigSerializer.wrap(this), mapper);
}
default IConfigSerializer<T> mapLoadOnly(UnaryOperator<SerializerResult<T>> load) {
return map(MapperWithLambdas.loadOnlyMapper(type(), load));
}
default IConfigSerializer<T> mapLoadOnlySimple(UnaryOperator<T> load) {
return map(MapperWithLambdas.simpleLoadOnlyMapper(type(), load));
}
}
| 933 | 0.69239 | 0.69239 | 33 | 27.272728 | 29.197626 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484848 | false | false | 3 |
3f56d6ab54ceea74b5a56fc130d8e5f1b945a3c3 | 26,362,509,278,065 | 0f23178a62f1692e3f4a94efeedd21d3142efd7d | /net.menthor.antipattern/src/net/menthor/antipattern/wizard/undefphase/ChangeStereoTable.java | 86c46765b05a6a7abc3d28eda37104c910664233 | [
"MIT"
]
| permissive | EdeysonGomes/menthor-editor | https://github.com/EdeysonGomes/menthor-editor | b59ca520eea89de3f7c28a923a9a483cca0b4a21 | 1618b272d8976688dff46fc9e9e35eb9371cd0f4 | refs/heads/master | 2023-03-13T15:29:56.984000 | 2021-03-10T20:49:35 | 2021-03-10T20:49:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.menthor.antipattern.wizard.undefphase;
import java.util.ArrayList;
import net.menthor.antipattern.undefphase.UndefPhaseOccurrence;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import RefOntoUML.Phase;
public class ChangeStereoTable {
private UndefPhaseOccurrence up;
private Table table;
@SuppressWarnings("unused")
public ChangeStereoTable (Composite parent, int args, UndefPhaseOccurrence up)
{
table = new Table(parent, args);
this.up = up;
table.setHeaderVisible(true);
table.setLinesVisible(true);
String columnName1 = "Phase";
TableColumn tableColumn1 = new TableColumn(table, SWT.CENTER);
tableColumn1.setWidth(142);
tableColumn1.setText(columnName1);
String columnName2 = "Stereotype";
TableColumn tableColumn2 = new TableColumn(table, SWT.CENTER);
tableColumn2.setWidth(112);
tableColumn2.setText(columnName2);
int tableWidth = 0;
for (TableColumn tc : table.getColumns()) {
tableWidth+=tc.getWidth();
}
table.setSize(332, 117);
fulfillLines();
}
public void fulfillLines()
{
for(Phase p: up.getPhases())
{
TableItem tableItem = new TableItem(table,SWT.NONE);
// Phase Name
TableEditor editor = new TableEditor(table);
tableItem.setText(0, p.getName());
// Stereotype
editor = new TableEditor(table);
Combo combo = new Combo(table, SWT.READ_ONLY);
combo.setItems(new String[] {"Phase","SubKind","Role"});
combo.select(0);
combo.pack();
editor.grabHorizontal = true;
editor.horizontalAlignment = SWT.CENTER;
editor.setEditor(combo, tableItem, 1);
tableItem.setData("1", combo);
}
}
public Table getTable() {
return table;
}
public boolean isAllPhase()
{
for (TableItem ti : table.getItems()){
Combo combo = (Combo) ti.getData("1");
if(combo.getText().compareToIgnoreCase("Phase")!=0) return false;
}
return true;
}
public ArrayList<String> getStereotypes()
{
ArrayList<String> result = new ArrayList<String>();
for (TableItem ti : table.getItems()){
Combo combo = (Combo) ti.getData("1");
result.add(combo.getText());
}
return result;
}
} | UTF-8 | Java | 2,495 | java | ChangeStereoTable.java | Java | []
| null | []
| package net.menthor.antipattern.wizard.undefphase;
import java.util.ArrayList;
import net.menthor.antipattern.undefphase.UndefPhaseOccurrence;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import RefOntoUML.Phase;
public class ChangeStereoTable {
private UndefPhaseOccurrence up;
private Table table;
@SuppressWarnings("unused")
public ChangeStereoTable (Composite parent, int args, UndefPhaseOccurrence up)
{
table = new Table(parent, args);
this.up = up;
table.setHeaderVisible(true);
table.setLinesVisible(true);
String columnName1 = "Phase";
TableColumn tableColumn1 = new TableColumn(table, SWT.CENTER);
tableColumn1.setWidth(142);
tableColumn1.setText(columnName1);
String columnName2 = "Stereotype";
TableColumn tableColumn2 = new TableColumn(table, SWT.CENTER);
tableColumn2.setWidth(112);
tableColumn2.setText(columnName2);
int tableWidth = 0;
for (TableColumn tc : table.getColumns()) {
tableWidth+=tc.getWidth();
}
table.setSize(332, 117);
fulfillLines();
}
public void fulfillLines()
{
for(Phase p: up.getPhases())
{
TableItem tableItem = new TableItem(table,SWT.NONE);
// Phase Name
TableEditor editor = new TableEditor(table);
tableItem.setText(0, p.getName());
// Stereotype
editor = new TableEditor(table);
Combo combo = new Combo(table, SWT.READ_ONLY);
combo.setItems(new String[] {"Phase","SubKind","Role"});
combo.select(0);
combo.pack();
editor.grabHorizontal = true;
editor.horizontalAlignment = SWT.CENTER;
editor.setEditor(combo, tableItem, 1);
tableItem.setData("1", combo);
}
}
public Table getTable() {
return table;
}
public boolean isAllPhase()
{
for (TableItem ti : table.getItems()){
Combo combo = (Combo) ti.getData("1");
if(combo.getText().compareToIgnoreCase("Phase")!=0) return false;
}
return true;
}
public ArrayList<String> getStereotypes()
{
ArrayList<String> result = new ArrayList<String>();
for (TableItem ti : table.getItems()){
Combo combo = (Combo) ti.getData("1");
result.add(combo.getText());
}
return result;
}
} | 2,495 | 0.674549 | 0.662525 | 97 | 23.721649 | 19.8794 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.587629 | false | false | 3 |
77254fb818d975fb757d2b3d0a188228993b1ebb | 22,179,211,142,900 | 0afe1aaeadc2307f1b35d66293ed49afdadaeeb0 | /src/main/java/com/weixe/wifidog/dao/ApAdminDaoGen.java | 1881e0c6479556d1e775e79c56f14f113a2b2020 | []
| no_license | jiangchao0304/wifidog | https://github.com/jiangchao0304/wifidog | b6e9c89d697f9e11d79db2b236d6e55a7cb4ed18 | f0a018057c04f106f226b695ba9c6d049716f66c | refs/heads/master | 2017-12-22T01:51:59.788000 | 2016-11-10T13:43:26 | 2016-11-10T13:43:26 | 72,807,774 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.weixe.wifidog.dao;
import com.weixe.wifidog.model.ApAdminModel;
import org.springframework.dao.DataAccessException;
import java.util.List;
import java.util.Map;
public interface ApAdminDaoGen {
//===========================================代码生成开始 ========================================
ApAdminModel getApAdmin(Integer id) throws DataAccessException;
List<ApAdminModel> getApAdminList(Map<String, Object> searchParams) throws DataAccessException;
int insertApAdmin(ApAdminModel apAdminModel) throws DataAccessException;
int insertApAdminBatch(List<ApAdminModel> apAdminModelList) throws DataAccessException;
int updateApAdmin(ApAdminModel apAdminModel) throws DataAccessException;
int deleteApAdmin(Integer id) throws DataAccessException;
//===========================================代码生成结束============================================
}
| UTF-8 | Java | 913 | java | ApAdminDaoGen.java | Java | []
| null | []
| package com.weixe.wifidog.dao;
import com.weixe.wifidog.model.ApAdminModel;
import org.springframework.dao.DataAccessException;
import java.util.List;
import java.util.Map;
public interface ApAdminDaoGen {
//===========================================代码生成开始 ========================================
ApAdminModel getApAdmin(Integer id) throws DataAccessException;
List<ApAdminModel> getApAdminList(Map<String, Object> searchParams) throws DataAccessException;
int insertApAdmin(ApAdminModel apAdminModel) throws DataAccessException;
int insertApAdminBatch(List<ApAdminModel> apAdminModelList) throws DataAccessException;
int updateApAdmin(ApAdminModel apAdminModel) throws DataAccessException;
int deleteApAdmin(Integer id) throws DataAccessException;
//===========================================代码生成结束============================================
}
| 913 | 0.652418 | 0.652418 | 26 | 33.192307 | 36.708855 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
e483a6601911faca1cea4369199c089344fcb921 | 6,081,673,738,139 | e8b897df108a445dd92b47be7f0cfe490432ee7d | /sem2/ADF-II/JAVA2_BT/d03_generics/src/data/ProductList.java | f562039a1410d377c385ca7cb985becafd8301a8 | []
| no_license | thisisminh172/Aptech | https://github.com/thisisminh172/Aptech | 2e4f51dc4f21c839a1d8a8121b17756c96a780f9 | bd275eb99ed19909da4c156f5a973a0dff479297 | refs/heads/master | 2023-01-04T00:04:52.503000 | 2020-10-31T04:13:52 | 2020-10-31T04:13:52 | 265,212,106 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Quan ly danh sach san pham trong HashSet
*/
package data;
import java.util.*;
import java.io.*;
import java.util.stream.Stream;
public class ProductList {
HashSet<Product> prList = new HashSet<>();
public void add() {
Product p = new Product();
p.input();
long cnt = prList.stream().filter(item -> item.id.equals(p.id)).count();
if (cnt == 0) {
prList.add(p);
} else {
System.out.println("Ma so da ton tai, tu choi them moi!");
}
}
public void display() {
if (prList.isEmpty()) {
System.out.println("HT chua co du lieu");
return;
}
System.out.println("Danh sach san pham");
/*
for (Product d : prList){
System.out.println(d);
}
prList.forEach((d)-> {
System.out.println(d);
});
*/
//Cach 3: rut gon bt lamba: method referce
prList.forEach(System.out::println);
}
public void display(String s) {
if (prList.isEmpty()) {
System.out.println("HT chua co du lieu");
return;
}
//Stream<Product> prStream = prList.stream().filter(item -> item.name.toLowerCase().contains(s));
long cnt = prList.stream().filter(item -> item.name.toLowerCase().contains(s)).count();
if(cnt == 0){
System.out.println("ko co");
}else{
prList.stream().filter(item -> item.name.toLowerCase().contains(s)).forEach(System.out::println);
}
}
String fname = "sanpham.data";
public void saveFile() {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fname));
oos.writeObject(prList);
oos.close();
} catch (Exception ex) {
System.out.println("Loi: " + ex.getMessage());
}
}
public void readFile() {
try {
ObjectInputStream iis = new ObjectInputStream(new FileInputStream(fname));
prList = (HashSet<Product>) iis.readObject();
iis.close();
} catch (Exception ex) {
System.out.println("Loi: " + ex.getMessage());
}
}
}
| UTF-8 | Java | 2,237 | java | ProductList.java | Java | []
| null | []
| /*
Quan ly danh sach san pham trong HashSet
*/
package data;
import java.util.*;
import java.io.*;
import java.util.stream.Stream;
public class ProductList {
HashSet<Product> prList = new HashSet<>();
public void add() {
Product p = new Product();
p.input();
long cnt = prList.stream().filter(item -> item.id.equals(p.id)).count();
if (cnt == 0) {
prList.add(p);
} else {
System.out.println("Ma so da ton tai, tu choi them moi!");
}
}
public void display() {
if (prList.isEmpty()) {
System.out.println("HT chua co du lieu");
return;
}
System.out.println("Danh sach san pham");
/*
for (Product d : prList){
System.out.println(d);
}
prList.forEach((d)-> {
System.out.println(d);
});
*/
//Cach 3: rut gon bt lamba: method referce
prList.forEach(System.out::println);
}
public void display(String s) {
if (prList.isEmpty()) {
System.out.println("HT chua co du lieu");
return;
}
//Stream<Product> prStream = prList.stream().filter(item -> item.name.toLowerCase().contains(s));
long cnt = prList.stream().filter(item -> item.name.toLowerCase().contains(s)).count();
if(cnt == 0){
System.out.println("ko co");
}else{
prList.stream().filter(item -> item.name.toLowerCase().contains(s)).forEach(System.out::println);
}
}
String fname = "sanpham.data";
public void saveFile() {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fname));
oos.writeObject(prList);
oos.close();
} catch (Exception ex) {
System.out.println("Loi: " + ex.getMessage());
}
}
public void readFile() {
try {
ObjectInputStream iis = new ObjectInputStream(new FileInputStream(fname));
prList = (HashSet<Product>) iis.readObject();
iis.close();
} catch (Exception ex) {
System.out.println("Loi: " + ex.getMessage());
}
}
}
| 2,237 | 0.530174 | 0.528833 | 85 | 25.317648 | 25.664446 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388235 | false | false | 3 |
7cb06c53a130b4d60de17c3013564ac41785385b | 32,770,600,474,858 | e1572ca52d3c2bc46dc81958be78947ca566a780 | /Algorithms-and-DataStructures/leetcode/A344.java | 111d3887109347a2c129345a1d4999f74383f74d | []
| no_license | itsttk/Algorithms-and-DataStructures | https://github.com/itsttk/Algorithms-and-DataStructures | 687c63adc3ec6a603e9bf4605dd6b40ff160bb21 | e3397c569c664403f7d63b306fc39623e8a8003e | refs/heads/master | 2020-03-18T07:03:03.600000 | 2018-05-22T18:38:54 | 2018-05-22T18:38:54 | 134,429,341 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class A344
{
public String reverseString(String s) {
StringBuffer result= new StringBuffer();
for(int i=s.length();i>0;i--){
result = result.append(s.charAt(i-1));
}
return result.toString();
}
public static void main(String[] args){
String num1 = "19";
A344 object = new A344();
String a = object.reverseString( num1);
System.out.println(a);
}
} | UTF-8 | Java | 515 | java | A344.java | Java | []
| null | []
| public class A344
{
public String reverseString(String s) {
StringBuffer result= new StringBuffer();
for(int i=s.length();i>0;i--){
result = result.append(s.charAt(i-1));
}
return result.toString();
}
public static void main(String[] args){
String num1 = "19";
A344 object = new A344();
String a = object.reverseString( num1);
System.out.println(a);
}
} | 515 | 0.485437 | 0.456311 | 43 | 11 | 15.249857 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.488372 | false | false | 3 |
4bfee6a669b111b9794da00ffdb78275b58b49c5 | 26,362,509,283,052 | 5aa1f82e63c7e80d3f3a62088f0f65d92d200c4e | /src/main/java/com/cinematic/entities/Seat.java | 8e50b3c3b0e34ee2cf87e0551e6b0e8caaf98c7e | []
| no_license | CrackedClown/Cinematic | https://github.com/CrackedClown/Cinematic | 0638af3754f5400352420907c293bdc5ec1b4db6 | b0b2b81250c238296d62a19159c02d6d2c27710f | refs/heads/master | 2020-07-06T10:36:39.623000 | 2019-08-19T12:37:30 | 2019-08-19T12:37:30 | 202,988,571 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cinematic.entities;
import javax.persistence.CascadeType;
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.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
@Entity
@Table(name = "seat")
public class Seat {
@Id
@Column(name = "seat_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int seatID;
@JoinColumn(name = "screen_id")
@ManyToOne(cascade = CascadeType.ALL)
@JsonManagedReference
private Screen screen;
@JoinColumn(name = "reservation_id")
@OneToOne
@JsonBackReference
private Reservation reservation;
@Column(name = "seat_occupied", nullable = false)
private boolean seatOccupied;
public int getSeatID() {
return seatID;
}
public void setSeatID(int seatID) {
this.seatID = seatID;
}
public Screen getScreen() {
return screen;
}
public void setScreen(Screen screen) {
this.screen = screen;
}
public boolean isSeatOccupied() {
return seatOccupied;
}
public void setSeatOccupied(boolean seatOccupied) {
this.seatOccupied = seatOccupied;
}
public Reservation getReservation() {
return reservation;
}
public void setReservation(Reservation reservation) {
this.reservation = reservation;
}
@Override
public String toString() {
return "Seat [seatID=" + seatID + ", screen=" + screen + ", reservation=" + reservation + ", seatOccupied="
+ seatOccupied + "]";
}
}
| UTF-8 | Java | 1,730 | java | Seat.java | Java | []
| null | []
| package com.cinematic.entities;
import javax.persistence.CascadeType;
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.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
@Entity
@Table(name = "seat")
public class Seat {
@Id
@Column(name = "seat_id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int seatID;
@JoinColumn(name = "screen_id")
@ManyToOne(cascade = CascadeType.ALL)
@JsonManagedReference
private Screen screen;
@JoinColumn(name = "reservation_id")
@OneToOne
@JsonBackReference
private Reservation reservation;
@Column(name = "seat_occupied", nullable = false)
private boolean seatOccupied;
public int getSeatID() {
return seatID;
}
public void setSeatID(int seatID) {
this.seatID = seatID;
}
public Screen getScreen() {
return screen;
}
public void setScreen(Screen screen) {
this.screen = screen;
}
public boolean isSeatOccupied() {
return seatOccupied;
}
public void setSeatOccupied(boolean seatOccupied) {
this.seatOccupied = seatOccupied;
}
public Reservation getReservation() {
return reservation;
}
public void setReservation(Reservation reservation) {
this.reservation = reservation;
}
@Override
public String toString() {
return "Seat [seatID=" + seatID + ", screen=" + screen + ", reservation=" + reservation + ", seatOccupied="
+ seatOccupied + "]";
}
}
| 1,730 | 0.749133 | 0.749133 | 82 | 20.097561 | 20.153442 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.134146 | false | false | 3 |
bea5e4c91971ed0eb1ab0efd5c4df318db00445f | 25,752,623,921,024 | d489e83a65bd612b0b75d9fd1f64a865ba2558e2 | /GestionReservasHotel/src/java/reservashotel/presentation/util/FechasUtil.java | fc88727c4949834fc421063e9d96d8733a8bce7e | []
| no_license | Albertocd/GestionApps | https://github.com/Albertocd/GestionApps | 953e27d000d6dc03fd51a3cfff0fdbf7f6073b3e | 5199e3406dce4673aa1b792e72d2b7da3f1904c1 | refs/heads/master | 2021-01-20T11:11:32.673000 | 2015-03-27T11:58:20 | 2015-03-27T11:58:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package reservashotel.presentation.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @author alberto
* Clase con funcionalidades específicas para fechas.
*/
public class FechasUtil {
/**
* Obtiene la fecha actual.
* @return
*/
public static Date fechaActual() {
Calendar cal = Calendar.getInstance();
return cal.getTime();
}
/**
* Incrementa/decrementa los dias indicados en el parámetro
* a la fecha también indicada.
* @param fecha Fecha
* @param dias Días
* @return Date
*/
public static Date fechaMasMenosDias(Date fecha, int dias) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(fecha);
calendar.add(Calendar.DAY_OF_YEAR, dias);
return calendar.getTime();
}
/**
* Calcula la diferencia en dias entre las fechas.
* @param fechaInicial Fecha inicial.
* @param fechaFinal Fecha final.
* @return número de días.
*/
public static int diferenciaDias(Date fechaInicial, Date fechaFinal) {
long millsecs = 24 * 60 * 60 * 1000;
int dias = (int)((int)(fechaFinal.getTime() - fechaInicial.getTime())/ millsecs);
return dias;
}
/**
* Obtiene el año de una fecha.
* @param fecha
* @return año
*/
public static int anoFecha(Date fecha){
Calendar calendar = Calendar.getInstance();
calendar.setTime(fecha);
return calendar.get(Calendar.YEAR);
}
/**
* Obtiene el mes de una fecha.
* @param fecha
* @return mes
*/
public static int mesFecha(Date fecha){
Calendar calendar = Calendar.getInstance();
calendar.setTime(fecha);
return calendar.get(Calendar.MONTH)+1;
}
/**
* Obtiene el dia de una fecha.
* @param fecha
* @return dia
*/
public static int diaFecha(Date fecha){
Calendar calendar = Calendar.getInstance();
calendar.setTime(fecha);
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* Elimina los datos de hora, minutos... de la fecha.
* @param fecha
* @return fecha sin horas.
* @throws java.text.ParseException
*/
public static Date quitaHorasFecha(Date fecha) throws ParseException {
SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
String fechaString = formato.format(fecha);
Date fechaSinHora = formato.parse(fechaString);
return fechaSinHora;
}
}
| UTF-8 | Java | 2,637 | java | FechasUtil.java | Java | [
{
"context": "l.Calendar;\nimport java.util.Date;\n\n/**\n * @author alberto\n * Clase con funcionalidades específicas para fec",
"end": 184,
"score": 0.9966679811477661,
"start": 177,
"tag": "USERNAME",
"value": "alberto"
}
]
| null | []
|
package reservashotel.presentation.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @author alberto
* Clase con funcionalidades específicas para fechas.
*/
public class FechasUtil {
/**
* Obtiene la fecha actual.
* @return
*/
public static Date fechaActual() {
Calendar cal = Calendar.getInstance();
return cal.getTime();
}
/**
* Incrementa/decrementa los dias indicados en el parámetro
* a la fecha también indicada.
* @param fecha Fecha
* @param dias Días
* @return Date
*/
public static Date fechaMasMenosDias(Date fecha, int dias) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(fecha);
calendar.add(Calendar.DAY_OF_YEAR, dias);
return calendar.getTime();
}
/**
* Calcula la diferencia en dias entre las fechas.
* @param fechaInicial Fecha inicial.
* @param fechaFinal Fecha final.
* @return número de días.
*/
public static int diferenciaDias(Date fechaInicial, Date fechaFinal) {
long millsecs = 24 * 60 * 60 * 1000;
int dias = (int)((int)(fechaFinal.getTime() - fechaInicial.getTime())/ millsecs);
return dias;
}
/**
* Obtiene el año de una fecha.
* @param fecha
* @return año
*/
public static int anoFecha(Date fecha){
Calendar calendar = Calendar.getInstance();
calendar.setTime(fecha);
return calendar.get(Calendar.YEAR);
}
/**
* Obtiene el mes de una fecha.
* @param fecha
* @return mes
*/
public static int mesFecha(Date fecha){
Calendar calendar = Calendar.getInstance();
calendar.setTime(fecha);
return calendar.get(Calendar.MONTH)+1;
}
/**
* Obtiene el dia de una fecha.
* @param fecha
* @return dia
*/
public static int diaFecha(Date fecha){
Calendar calendar = Calendar.getInstance();
calendar.setTime(fecha);
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* Elimina los datos de hora, minutos... de la fecha.
* @param fecha
* @return fecha sin horas.
* @throws java.text.ParseException
*/
public static Date quitaHorasFecha(Date fecha) throws ParseException {
SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
String fechaString = formato.format(fecha);
Date fechaSinHora = formato.parse(fechaString);
return fechaSinHora;
}
}
| 2,637 | 0.613161 | 0.608977 | 98 | 25.816326 | 20.831858 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.316327 | false | false | 3 |
dbc04e7b91957193f6baedd18a60f5191375db5b | 31,387,621,032,990 | 372a94350745a8695d44def0146e045468707e23 | /app/src/main/java/com/example/csimcik/bakingapp/Recipe.java | a95582da2c51c93875dca2395286074198026abc | []
| no_license | christophersimcik/BakingApp_Udacity | https://github.com/christophersimcik/BakingApp_Udacity | 866757dfa4cd751f4c9cf0499c115c3f98cc3e4f | 1a23d7a9c365e9be7350a9644b78b37e648c08a5 | refs/heads/master | 2020-04-01T03:30:20.578000 | 2018-10-13T01:58:39 | 2018-10-13T01:58:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.csimcik.bakingapp;
import java.util.ArrayList;
public class Recipe {
public String name;
public ArrayList<Ingredient> ingredients;
public ArrayList<Instruction> instructions;
public String servings;
public Recipe(String nameA,String servingsA,ArrayList<Ingredient> ingredientsA,ArrayList<Instruction> instructionsA){
this.name = nameA;
this.servings = servingsA;
this.ingredients = ingredientsA;
this.instructions = instructionsA;
}
public String getName(){
return name;
}
public String getServings(){
return servings;
}
public ArrayList getIngredients(){
return ingredients;
}
public ArrayList getInstructions(){
return instructions;
}
}
| UTF-8 | Java | 788 | java | Recipe.java | Java | []
| null | []
| package com.example.csimcik.bakingapp;
import java.util.ArrayList;
public class Recipe {
public String name;
public ArrayList<Ingredient> ingredients;
public ArrayList<Instruction> instructions;
public String servings;
public Recipe(String nameA,String servingsA,ArrayList<Ingredient> ingredientsA,ArrayList<Instruction> instructionsA){
this.name = nameA;
this.servings = servingsA;
this.ingredients = ingredientsA;
this.instructions = instructionsA;
}
public String getName(){
return name;
}
public String getServings(){
return servings;
}
public ArrayList getIngredients(){
return ingredients;
}
public ArrayList getInstructions(){
return instructions;
}
}
| 788 | 0.678934 | 0.678934 | 30 | 25.233334 | 23.276144 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.566667 | false | false | 3 |
b5e05f59a3f23fd323c0f580d0822d9b834abe5c | 21,887,153,405,261 | 2f85cd1ba29d8f74083041d7cb60cd073f733353 | /app/src/main/java/com/example/trabalho/presenter/contracts/ActivityContract.java | bb57802a736c0fdede79c42e8fd09972fdce0f7c | []
| no_license | gabrielgl9/trabalho-dispositivos-moveis | https://github.com/gabrielgl9/trabalho-dispositivos-moveis | 957b5a5065c66afdcbf7c14a1142a0f21f2e5bc5 | 985d971097538988f2cd5466765df9b3935b6a3e | refs/heads/master | 2023-06-06T09:06:22.201000 | 2021-06-17T00:40:51 | 2021-06-17T00:40:51 | 359,964,747 | 0 | 5 | null | false | 2021-06-14T16:48:57 | 2021-04-20T22:17:42 | 2021-06-14T07:04:55 | 2021-06-14T16:48:56 | 10,795 | 0 | 3 | 0 | Java | false | false | package com.example.trabalho.presenter.contracts;
import android.content.Context;
import android.content.Intent;
import com.example.trabalho.models.Trip;
public class ActivityContract {
public interface ActivityView {
public Context getContext();
public void showToast(String message);
public void navigate(Intent intent);
}
public interface ActivityPresenter {
public void start();
}
public interface ActivityFormPresenter {
public void submit(ModelContract.Model model);
public void validate() throws Exception;
}
}
| UTF-8 | Java | 595 | java | ActivityContract.java | Java | []
| null | []
| package com.example.trabalho.presenter.contracts;
import android.content.Context;
import android.content.Intent;
import com.example.trabalho.models.Trip;
public class ActivityContract {
public interface ActivityView {
public Context getContext();
public void showToast(String message);
public void navigate(Intent intent);
}
public interface ActivityPresenter {
public void start();
}
public interface ActivityFormPresenter {
public void submit(ModelContract.Model model);
public void validate() throws Exception;
}
}
| 595 | 0.712605 | 0.712605 | 23 | 24.869566 | 19.545498 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 3 |
70cace3755d4c765ae6e85ca3f6a0a78b40c2540 | 19,104,014,591,652 | b3e8e30330546faa2abfb7649353c713a54fe1ed | /Chess/src/chessfiles/SmartPlayer.java | 4a9bf0fafb442487db9aae338b449b5f8d8d7f73 | [
"MIT"
]
| permissive | 18AdrianoH/Miscellaneous | https://github.com/18AdrianoH/Miscellaneous | 12af9e9683653e17dd0d0af3924b7c9a72e67080 | 633a31572ebe9996642d76a3868593070f8faf43 | refs/heads/master | 2021-01-19T07:53:06.567000 | 2017-03-18T20:39:49 | 2017-03-18T20:39:49 | 83,102,144 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chessfiles;
import java.awt.Color;
public class SmartPlayer extends Player {
public SmartPlayer(Board board, Color color, String name) {
super(board, color, name);
// TODO Auto-generated constructor stub
}
@Override
public Move nextMove() {
// TODO Auto-generated method stub
return null;
}
}
| UTF-8 | Java | 337 | java | SmartPlayer.java | Java | []
| null | []
| package chessfiles;
import java.awt.Color;
public class SmartPlayer extends Player {
public SmartPlayer(Board board, Color color, String name) {
super(board, color, name);
// TODO Auto-generated constructor stub
}
@Override
public Move nextMove() {
// TODO Auto-generated method stub
return null;
}
}
| 337 | 0.68546 | 0.68546 | 18 | 16.722221 | 17.925171 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false | 3 |
89b2d01ce6a56dbadf84d8d091670c1ade1f62c9 | 29,953,101,934,494 | 55e020dd17a90593cee269e7e926b7d8ea166490 | /src/main/java/com/ecotage/vo/AddCategory.java | 434c271f32b12c68eb6ee42dd196e5ff5e2fbd77 | []
| no_license | bharathithangaraj/Ecotage_java | https://github.com/bharathithangaraj/Ecotage_java | b8507b9c5cb36e0d5d8ccdbfd505162ba6c871dd | c788014ab7cde5350d2028be2feccd5e85760c30 | refs/heads/master | 2023-04-27T06:51:05.168000 | 2019-06-18T14:43:54 | 2019-06-18T14:43:54 | 182,494,240 | 0 | 0 | null | false | 2023-04-14T17:47:50 | 2019-04-21T05:35:39 | 2019-06-21T07:00:27 | 2023-04-14T17:47:48 | 1,220 | 0 | 0 | 1 | Java | false | false | package com.ecotage.vo;
public class AddCategory {
private String categoryName;
private String categoryType;
private String categoryDesc;
private int status;
private String navigateTo;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryType() {
return categoryType;
}
public void setCategoryType(String categoryType) {
this.categoryType = categoryType;
}
public String getCategoryDesc() {
return categoryDesc;
}
public void setCategoryDesc(String categoryDesc) {
this.categoryDesc = categoryDesc;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getNavigateTo() {
return navigateTo;
}
public void setNavigateTo(String navigateTo) {
this.navigateTo = navigateTo;
}
}
| UTF-8 | Java | 911 | java | AddCategory.java | Java | []
| null | []
| package com.ecotage.vo;
public class AddCategory {
private String categoryName;
private String categoryType;
private String categoryDesc;
private int status;
private String navigateTo;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryType() {
return categoryType;
}
public void setCategoryType(String categoryType) {
this.categoryType = categoryType;
}
public String getCategoryDesc() {
return categoryDesc;
}
public void setCategoryDesc(String categoryDesc) {
this.categoryDesc = categoryDesc;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getNavigateTo() {
return navigateTo;
}
public void setNavigateTo(String navigateTo) {
this.navigateTo = navigateTo;
}
}
| 911 | 0.74753 | 0.74753 | 51 | 16.862745 | 16.62389 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.196078 | false | false | 3 |
56b9dcadcaf74492f9332ac9869243f66f08c2eb | 22,162,031,315,239 | 38a82b234ebde0f68bc4890da7253e027510b0eb | /src/com/bugframework/auth/dao/impl/RoleImpl.java | d7891063879565989257885375f336e03fe03efa | []
| no_license | ruan374519700/weischool | https://github.com/ruan374519700/weischool | db3cb448cd6309118dece79ccb3e64caa2674c48 | dec83183e49300562cbc593adcd8abc29b03b3b0 | refs/heads/master | 2020-11-30T15:05:15.714000 | 2016-09-03T14:14:57 | 2016-09-03T14:14:57 | 67,276,469 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bugframework.auth.dao.impl;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;
import org.springframework.stereotype.Repository;
import com.bugframework.auth.dao.RoleDao;
import com.bugframework.auth.pojo.AuthRole;
import com.bugframework.common.dao.impl.BaseDaoImpl;
import com.bugframework.common.pojo.DataGrid;
import com.bugframework.common.utility.HqlGenerateUtil;
@Repository("roleDao")
public class RoleImpl extends BaseDaoImpl<AuthRole> implements RoleDao{
@Override
public List<AuthRole> getRoleList() {
Criteria criteria=getSession().createCriteria(AuthRole.class);
criteria.add(Expression.eq("isenable", 1));
criteria.add(Expression.eq("isAdmin", (short)0));
criteria.add(Expression.eq("delFlag", 0));
List<AuthRole> deptList=criteria.list();
return deptList;
}
@Override
public void datagrid(AuthRole t, DataGrid<AuthRole> datagrid,HttpServletRequest request) {
Criteria cq =this.getCriteria();
HqlGenerateUtil.installHql(cq, t);
this.setDataGridData(cq,datagrid,true);
}
}
| UTF-8 | Java | 1,138 | java | RoleImpl.java | Java | []
| null | []
| package com.bugframework.auth.dao.impl;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;
import org.springframework.stereotype.Repository;
import com.bugframework.auth.dao.RoleDao;
import com.bugframework.auth.pojo.AuthRole;
import com.bugframework.common.dao.impl.BaseDaoImpl;
import com.bugframework.common.pojo.DataGrid;
import com.bugframework.common.utility.HqlGenerateUtil;
@Repository("roleDao")
public class RoleImpl extends BaseDaoImpl<AuthRole> implements RoleDao{
@Override
public List<AuthRole> getRoleList() {
Criteria criteria=getSession().createCriteria(AuthRole.class);
criteria.add(Expression.eq("isenable", 1));
criteria.add(Expression.eq("isAdmin", (short)0));
criteria.add(Expression.eq("delFlag", 0));
List<AuthRole> deptList=criteria.list();
return deptList;
}
@Override
public void datagrid(AuthRole t, DataGrid<AuthRole> datagrid,HttpServletRequest request) {
Criteria cq =this.getCriteria();
HqlGenerateUtil.installHql(cq, t);
this.setDataGridData(cq,datagrid,true);
}
}
| 1,138 | 0.779438 | 0.776801 | 39 | 28.179487 | 24.208361 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.461538 | false | false | 3 |
dd6f9af2ed97e376746d8d99559b481370857acd | 28,492,813,046,141 | b6c5b7bc661bfde7d47b52fbefae72dc836df3c1 | /src/Main.java | bfbb7518327752afde5349aec4664c3314c32ce2 | []
| no_license | babun1994/FillingArray | https://github.com/babun1994/FillingArray | 592718bb97dcc3738ba749cfcd60047f16c15ca9 | e68d37b51ab2016ca6d5844b36f8f2a67989fef7 | refs/heads/master | 2020-04-08T08:01:07.393000 | 2018-11-27T11:32:05 | 2018-11-27T11:32:05 | 159,161,559 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Main main = new Main();
InputNumbersForArray inputNumbersForArray = new InputNumbersForArray();
inputNumbersForArray.inputNumbs();
int a = inputNumbersForArray.getFistNum();
int b = inputNumbersForArray.getSecondNum();
//main.showArray(main.fillTheArrayFromLeftToRightIncrementingNumbers(a,b));
//main.showArray(main.fillTheArrayFromTopToBottomByIncrementingTheNumber(a,b));
//main.showArray(main.fillTheArrayFromLeftToRightDecreasinNumbers(a,b));
//main.showArray(main.fillTheArrayFromTopToBottomByDecreasingNumber(a,b));
main.showArray(main.fillTheArray(a,b));
}
int[][] fillTheArrayFromLeftToRightIncrementingNumbers (int fistNum, int secondNum){
int [][] doubleArray = new int[fistNum][secondNum];
int counter = 0;
for (int i = 0; i < fistNum ; i++) {
for (int j = 0; j < secondNum ; j++) {
doubleArray[i][j] = counter++;
}
}
return doubleArray;
}
int[][] fillTheArrayFromTopToBottomByIncrementingTheNumber (int fistNum, int secondNum){
int [][] doubleArray = new int[fistNum][secondNum];
int countr = 0;
for (int i = 0; i < secondNum ; i++) {
for (int j = 0; j < fistNum ; j++) {
doubleArray[j][i] = countr ++;
}
}
return doubleArray;
}
int[][] fillTheArrayFromLeftToRightDecreasinNumbers (int fistNum, int secondNum){
int [][] doubleArray = new int[fistNum][secondNum];
int counter = fistNum * secondNum;
for (int i = 0; i < fistNum ; i++) {
for (int j = 0; j < secondNum ; j++) {
doubleArray[i][j] = (counter--) - 1;
}
}
return doubleArray;
}
int[][] fillTheArrayFromTopToBottomByDecreasingNumber (int fistNum, int secondNum){
int [][] doubleArray = new int[fistNum][secondNum];
int countr = fistNum * secondNum;
for (int i = 0; i < secondNum ; i++) {
for (int j = 0; j < fistNum ; j++) {
doubleArray[j][i] = (countr --) - 1;
}
}
return doubleArray;
}
int [][] fillTheArray (int fistNum, int secondNum){
int [][] doubleArray = new int[fistNum][secondNum];
int counter = 1;
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 1; i <= fistNum ; i++) {
if(i % 2 != 0){
for (int j = 0; j < secondNum ; j++) {
arrayList.add(counter++);
}
counter = counter + secondNum - 1;
}else {
for (int j = 0; j <secondNum ; j++) {
arrayList.add(counter--);
}
counter = counter + secondNum + 1;
}
}
counter = 0;
for (int i = 0; i < fistNum ; i++) {
for (int j = 0; j < secondNum ; j++) {
doubleArray[i][j] = arrayList.get(counter++);
}
}
return doubleArray;
}
void showArray (int arr [][]){
int arrLenght = arr[0].length;
for (int i = 0; i < arr.length ; i++) {
System.out.println("");
for (int j = 0; j < arrLenght; j++) {
System.out.print(arr[i][j] + " ");
}
}
System.out.println("");
}
}
| UTF-8 | Java | 3,553 | java | Main.java | Java | []
| null | []
| import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Main main = new Main();
InputNumbersForArray inputNumbersForArray = new InputNumbersForArray();
inputNumbersForArray.inputNumbs();
int a = inputNumbersForArray.getFistNum();
int b = inputNumbersForArray.getSecondNum();
//main.showArray(main.fillTheArrayFromLeftToRightIncrementingNumbers(a,b));
//main.showArray(main.fillTheArrayFromTopToBottomByIncrementingTheNumber(a,b));
//main.showArray(main.fillTheArrayFromLeftToRightDecreasinNumbers(a,b));
//main.showArray(main.fillTheArrayFromTopToBottomByDecreasingNumber(a,b));
main.showArray(main.fillTheArray(a,b));
}
int[][] fillTheArrayFromLeftToRightIncrementingNumbers (int fistNum, int secondNum){
int [][] doubleArray = new int[fistNum][secondNum];
int counter = 0;
for (int i = 0; i < fistNum ; i++) {
for (int j = 0; j < secondNum ; j++) {
doubleArray[i][j] = counter++;
}
}
return doubleArray;
}
int[][] fillTheArrayFromTopToBottomByIncrementingTheNumber (int fistNum, int secondNum){
int [][] doubleArray = new int[fistNum][secondNum];
int countr = 0;
for (int i = 0; i < secondNum ; i++) {
for (int j = 0; j < fistNum ; j++) {
doubleArray[j][i] = countr ++;
}
}
return doubleArray;
}
int[][] fillTheArrayFromLeftToRightDecreasinNumbers (int fistNum, int secondNum){
int [][] doubleArray = new int[fistNum][secondNum];
int counter = fistNum * secondNum;
for (int i = 0; i < fistNum ; i++) {
for (int j = 0; j < secondNum ; j++) {
doubleArray[i][j] = (counter--) - 1;
}
}
return doubleArray;
}
int[][] fillTheArrayFromTopToBottomByDecreasingNumber (int fistNum, int secondNum){
int [][] doubleArray = new int[fistNum][secondNum];
int countr = fistNum * secondNum;
for (int i = 0; i < secondNum ; i++) {
for (int j = 0; j < fistNum ; j++) {
doubleArray[j][i] = (countr --) - 1;
}
}
return doubleArray;
}
int [][] fillTheArray (int fistNum, int secondNum){
int [][] doubleArray = new int[fistNum][secondNum];
int counter = 1;
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 1; i <= fistNum ; i++) {
if(i % 2 != 0){
for (int j = 0; j < secondNum ; j++) {
arrayList.add(counter++);
}
counter = counter + secondNum - 1;
}else {
for (int j = 0; j <secondNum ; j++) {
arrayList.add(counter--);
}
counter = counter + secondNum + 1;
}
}
counter = 0;
for (int i = 0; i < fistNum ; i++) {
for (int j = 0; j < secondNum ; j++) {
doubleArray[i][j] = arrayList.get(counter++);
}
}
return doubleArray;
}
void showArray (int arr [][]){
int arrLenght = arr[0].length;
for (int i = 0; i < arr.length ; i++) {
System.out.println("");
for (int j = 0; j < arrLenght; j++) {
System.out.print(arr[i][j] + " ");
}
}
System.out.println("");
}
}
| 3,553 | 0.518717 | 0.511399 | 111 | 31.009008 | 25.556332 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.738739 | false | false | 3 |
faef9d03a898a169c68e664d3a8fb530df0720ac | 7,524,782,773,448 | d7fc4ddc2dbacd71f82bcf0a1e4ba652fd18457f | /app/src/main/java/com/example/mastermind/ui/activities/ThemesActivity.java | fb4afa215490705439c57b26fe33be2892d35213 | []
| no_license | alon1302/MasterMind | https://github.com/alon1302/MasterMind | 7f3d318b1011fee55999ada7dfecca7a2195a6d0 | 912365980a9a1e8b9b4f499d0202e08c71a39b2d | refs/heads/master | 2023-05-01T07:02:26.766000 | 2021-05-24T15:17:08 | 2021-05-24T15:17:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.mastermind.ui.activities;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.mastermind.R;
import com.example.mastermind.model.Const;
import com.example.mastermind.model.listeners.MethodCallBack;
import com.example.mastermind.model.theme.Themes;
import com.example.mastermind.model.user.CurrentUser;
import com.example.mastermind.ui.adapters.AdapterThemes;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
public class ThemesActivity extends AppCompatActivity implements MethodCallBack {
private TextView textViewCoins;
private RecyclerView recyclerView;
private AdapterThemes adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_themes);
textViewCoins = findViewById(R.id.textView_coinsThemes);
textViewCoins.setText("" + CurrentUser.getUserCoins());
recyclerView = findViewById(R.id.recyclerView_themes);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
adapter = new AdapterThemes(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
recyclerView.startLayoutAnimation();
}
@SuppressLint("SetTextI18n")
@Override
public void onCallBack(final int action, final Object value) {
final int index = action;
Drawable theme = (Drawable) value;
if (!Themes.getInstance(ThemesActivity.this.getApplicationContext()).getAllThemes().get(index).isOpened()) {
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog_get_theme);
Objects.requireNonNull(d.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
final TextView coins = d.findViewById(R.id.textView_coinsGetTheme);
coins.setText("" + CurrentUser.getUserCoins());
CircleImageView[] images = new CircleImageView[6];
images[0] = d.findViewById(R.id.red);
images[1] = d.findViewById(R.id.green);
images[2] = d.findViewById(R.id.blue);
images[3] = d.findViewById(R.id.orange);
images[4] = d.findViewById(R.id.yellow);
images[5] = d.findViewById(R.id.light);
for (int i = 0; i < images.length; i++)
images[i].setForeground(theme);
d.setCancelable(true);
d.show();
d.findViewById(R.id.buyThemeButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (CurrentUser.getUserCoins() >= Const.THEME_COST) {
CurrentUser.addCoins(-1 * Const.THEME_COST);
Themes.getInstance(ThemesActivity.this.getApplicationContext()).getAllThemes().get(index).setOpened(true);
d.dismiss();
textViewCoins.setText("" + CurrentUser.getUserCoins());
Themes.getInstance(ThemesActivity.this).openATheme(index);
adapter.notifyDataSetChanged();
recyclerView.startLayoutAnimation();
} else
Toast.makeText(ThemesActivity.this, "You Have Not Enough Coins", Toast.LENGTH_SHORT).show();
}
});
}else {
Themes.getInstance(ThemesActivity.this.getApplicationContext()).setCurrentThemeIndex(index);
}
adapter.notifyDataSetChanged();
}
} | UTF-8 | Java | 4,036 | java | ThemesActivity.java | Java | []
| null | []
| package com.example.mastermind.ui.activities;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.mastermind.R;
import com.example.mastermind.model.Const;
import com.example.mastermind.model.listeners.MethodCallBack;
import com.example.mastermind.model.theme.Themes;
import com.example.mastermind.model.user.CurrentUser;
import com.example.mastermind.ui.adapters.AdapterThemes;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
public class ThemesActivity extends AppCompatActivity implements MethodCallBack {
private TextView textViewCoins;
private RecyclerView recyclerView;
private AdapterThemes adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_themes);
textViewCoins = findViewById(R.id.textView_coinsThemes);
textViewCoins.setText("" + CurrentUser.getUserCoins());
recyclerView = findViewById(R.id.recyclerView_themes);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
adapter = new AdapterThemes(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
recyclerView.startLayoutAnimation();
}
@SuppressLint("SetTextI18n")
@Override
public void onCallBack(final int action, final Object value) {
final int index = action;
Drawable theme = (Drawable) value;
if (!Themes.getInstance(ThemesActivity.this.getApplicationContext()).getAllThemes().get(index).isOpened()) {
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog_get_theme);
Objects.requireNonNull(d.getWindow()).setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
final TextView coins = d.findViewById(R.id.textView_coinsGetTheme);
coins.setText("" + CurrentUser.getUserCoins());
CircleImageView[] images = new CircleImageView[6];
images[0] = d.findViewById(R.id.red);
images[1] = d.findViewById(R.id.green);
images[2] = d.findViewById(R.id.blue);
images[3] = d.findViewById(R.id.orange);
images[4] = d.findViewById(R.id.yellow);
images[5] = d.findViewById(R.id.light);
for (int i = 0; i < images.length; i++)
images[i].setForeground(theme);
d.setCancelable(true);
d.show();
d.findViewById(R.id.buyThemeButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (CurrentUser.getUserCoins() >= Const.THEME_COST) {
CurrentUser.addCoins(-1 * Const.THEME_COST);
Themes.getInstance(ThemesActivity.this.getApplicationContext()).getAllThemes().get(index).setOpened(true);
d.dismiss();
textViewCoins.setText("" + CurrentUser.getUserCoins());
Themes.getInstance(ThemesActivity.this).openATheme(index);
adapter.notifyDataSetChanged();
recyclerView.startLayoutAnimation();
} else
Toast.makeText(ThemesActivity.this, "You Have Not Enough Coins", Toast.LENGTH_SHORT).show();
}
});
}else {
Themes.getInstance(ThemesActivity.this.getApplicationContext()).setCurrentThemeIndex(index);
}
adapter.notifyDataSetChanged();
}
} | 4,036 | 0.669475 | 0.666749 | 95 | 41.494736 | 30.431242 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.715789 | false | false | 3 |
2601ca989e86a2a98689f560b1f2fd79eb23f911 | 19,937,238,254,766 | 0a93a191e05892a9aa293a5591c2ef7e771a7860 | /libhandyhttpd/src/main/java/me/linjw/handyhttpd/annotation/Param.java | 3ea4742ed1cae4a93cb900ea1cd9d793c3cd9ab1 | [
"WTFPL"
]
| permissive | bluesky466/HandyHTTPD | https://github.com/bluesky466/HandyHTTPD | b64f7d630af3bcea8c143224314e414dd2b9b5a0 | a10942afa79d9e2c2a16624e3b95a855fed7a8ea | refs/heads/master | 2020-03-07T10:48:57.154000 | 2018-09-15T03:59:17 | 2018-09-15T03:59:17 | 127,440,455 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.linjw.handyhttpd.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by linjiawei on 2018/7/4.
* e-mail : bluesky466@qq.com
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.CLASS)
public @interface Param {
/**
* param name.
*
* @return param name
*/
String value() default "";
}
| UTF-8 | Java | 471 | java | Param.java | Java | [
{
"context": "rt java.lang.annotation.Target;\n\n/**\n * Created by linjiawei on 2018/7/4.\n * e-mail : bluesky466@qq.com\n */\n\n@",
"end": 230,
"score": 0.998301088809967,
"start": 221,
"tag": "USERNAME",
"value": "linjiawei"
},
{
"context": "*\n * Created by linjiawei on 2018/7/4.\n * e-mail : bluesky466@qq.com\n */\n\n@Target(ElementType.PARAMETER)\n@Retention(Re",
"end": 273,
"score": 0.9999270439147949,
"start": 256,
"tag": "EMAIL",
"value": "bluesky466@qq.com"
}
]
| null | []
| package me.linjw.handyhttpd.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by linjiawei on 2018/7/4.
* e-mail : <EMAIL>
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.CLASS)
public @interface Param {
/**
* param name.
*
* @return param name
*/
String value() default "";
}
| 461 | 0.70913 | 0.690021 | 22 | 20.40909 | 15.54366 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 3 |
9f92f06c71b47b793af62b4569c57fd02543f990 | 2,070,174,245,533 | 310ac6aa4af069f68266101f56f32ea1affd0931 | /src/ha/MyQueue.java | 0c0ccc6d14bd66f6a2be0e43e5ecfa34a67ffe1e | []
| no_license | Hakulukiam/Marcel-HA | https://github.com/Hakulukiam/Marcel-HA | ec2ae6aedb17a5fa9abc1b569f34073967f48f8d | 84dab6d72a0a1e80a57fd1bdb8739e7f60aa0a3e | refs/heads/master | 2021-01-21T07:08:42.407000 | 2017-06-10T16:50:23 | 2017-06-10T16:50:23 | 91,600,992 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ha;
/**
*
* @author Marcel Clemeur 4840095 Gruppe 2C
*/
public class MyQueue extends MyList {
/**
* Fügt das Element e ans Ende der Warteschlange ein.
* @param e wird uebergeben
*/
public void add(MyListElement e) {
this.append(e);
}
/**
* Löscht das vorderste Element und gibt dies zurück. Wenn die Warteschlange leer ist, wird null zurückgegeben.
* @return ret oder null
*/
public MyListElement remove() {
if (this.length() > 0) {
MyListElement ret = new MyListElement(this.getfirstElement().getMyElement());
this.delete(this.getfirstElement());
return ret;
} else {
return null;
}
}
/**
* Gibt das vorderste Element zurück. Wenn die Warteschlange leer ist, wird null zurückgegeben.
* @return getfirstElement oder null
*/
public MyListElement element() {
if (this.length() > 0) {
return this.getfirstElement();
} else {
return null;
}
}
} | UTF-8 | Java | 1,158 | java | MyQueue.java | Java | [
{
"context": "\npackage ha;\n\n/**\n *\n * @author Marcel Clemeur 4840095 Gruppe 2C\n */\npublic class MyQueue extend",
"end": 46,
"score": 0.9998777508735657,
"start": 32,
"tag": "NAME",
"value": "Marcel Clemeur"
}
]
| null | []
|
package ha;
/**
*
* @author <NAME> 4840095 Gruppe 2C
*/
public class MyQueue extends MyList {
/**
* Fügt das Element e ans Ende der Warteschlange ein.
* @param e wird uebergeben
*/
public void add(MyListElement e) {
this.append(e);
}
/**
* Löscht das vorderste Element und gibt dies zurück. Wenn die Warteschlange leer ist, wird null zurückgegeben.
* @return ret oder null
*/
public MyListElement remove() {
if (this.length() > 0) {
MyListElement ret = new MyListElement(this.getfirstElement().getMyElement());
this.delete(this.getfirstElement());
return ret;
} else {
return null;
}
}
/**
* Gibt das vorderste Element zurück. Wenn die Warteschlange leer ist, wird null zurückgegeben.
* @return getfirstElement oder null
*/
public MyListElement element() {
if (this.length() > 0) {
return this.getfirstElement();
} else {
return null;
}
}
} | 1,150 | 0.53559 | 0.52691 | 42 | 26.428572 | 25.999214 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.238095 | false | false | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.