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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c1f2c3d362893040392f2bde576c360299c4726f | 39,161,511,838,045 | 9c8069432b46f5fb59c057416ac4f14347eece5e | /src/euler/problem4.java | 4c4eb4e10d2565959635eea7dc4bf626db34a448 | [] | no_license | fiskr/dabble | https://github.com/fiskr/dabble | 046fe066519b3ec219ea757d605c84b77f230983 | 127b8ab7f61c13bef2621ee0176bfaf52a9534f5 | refs/heads/master | 2021-01-18T15:14:51.152000 | 2013-06-08T04:50:50 | 2013-06-08T04:50:50 | 9,460,772 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Author: Brandon Foster
* Date: 12/25/2012
* Problem:
* A palindromic number reads the same both ways.
* The largest palindrome made from the product of
* two 2-digit numbers is 9009 = 91 × 99.
* Find the largest palindrome made from the product of two 3-digit numbers.
*/
package euler;
public class problem4 {
public static void main(String[] args){
//x and y represent the two digit numbers used to make the palindrome
//p is the product of these two digits, and the potential palindrome
int p = 0;
//sb is the string buffer to reverse second half of product to eval
StringBuffer sb = new StringBuffer();
StringBuffer firstHalf = new StringBuffer();
StringBuffer secondHalf = new StringBuffer();
StringBuffer reversedSecondHalf = new StringBuffer();
//int x = 999;
//int y = 999;
for(int x = 999; x > 0; x--){
for(int y = 999; y > 0; y--){
if(sb.length() > 0){
sb.delete(0, sb.length());
//System.out.println("Deleted sb");
}
if(firstHalf.length() > 0){
firstHalf.delete(0, firstHalf.length());
//System.out.println("Deleted first half");
}
if(secondHalf.length() > 0){
secondHalf.delete(0, secondHalf.length());
//System.out.println("Deleted second half");
}
if(reversedSecondHalf.length() > 0){
reversedSecondHalf.delete(0, reversedSecondHalf.length());
//System.out.println("Deleted reversedSecondHalf");
}
p = x * y;
sb.append(p);
if((sb.length()) % 2 == 0){
firstHalf.append(sb.substring(0, (sb.length()/2)));
secondHalf.append(sb.substring((sb.length()/2), sb.length()));
for(int f = secondHalf.length(); f > 0 ; f --){
reversedSecondHalf.append(secondHalf.charAt(f-1));
}
if(firstHalf.toString().equals(reversedSecondHalf.toString())){
System.out.println("\nX: " + x +
"\nY: " + y +
"\nP: " + p +
"\nSB: " + sb +
"\nlength: " + sb.length() +
"\nFirst Half: " + firstHalf +
"\nSecond Half: " + secondHalf +
"\nReversed second half: " + reversedSecondHalf);
System.out.println("\n\n\nWE'VE GOT A WINNER GIRLS AND BOYS!!!!\n\n");
}
}
}
}
}
}
| UTF-8 | Java | 3,153 | java | problem4.java | Java | [
{
"context": "/*\n * Author: Brandon Foster\n * Date: 12/25/2012\n * Problem:\n * A palindromic ",
"end": 28,
"score": 0.9998791217803955,
"start": 14,
"tag": "NAME",
"value": "Brandon Foster"
}
] | null | [] | /*
* Author: <NAME>
* Date: 12/25/2012
* Problem:
* A palindromic number reads the same both ways.
* The largest palindrome made from the product of
* two 2-digit numbers is 9009 = 91 × 99.
* Find the largest palindrome made from the product of two 3-digit numbers.
*/
package euler;
public class problem4 {
public static void main(String[] args){
//x and y represent the two digit numbers used to make the palindrome
//p is the product of these two digits, and the potential palindrome
int p = 0;
//sb is the string buffer to reverse second half of product to eval
StringBuffer sb = new StringBuffer();
StringBuffer firstHalf = new StringBuffer();
StringBuffer secondHalf = new StringBuffer();
StringBuffer reversedSecondHalf = new StringBuffer();
//int x = 999;
//int y = 999;
for(int x = 999; x > 0; x--){
for(int y = 999; y > 0; y--){
if(sb.length() > 0){
sb.delete(0, sb.length());
//System.out.println("Deleted sb");
}
if(firstHalf.length() > 0){
firstHalf.delete(0, firstHalf.length());
//System.out.println("Deleted first half");
}
if(secondHalf.length() > 0){
secondHalf.delete(0, secondHalf.length());
//System.out.println("Deleted second half");
}
if(reversedSecondHalf.length() > 0){
reversedSecondHalf.delete(0, reversedSecondHalf.length());
//System.out.println("Deleted reversedSecondHalf");
}
p = x * y;
sb.append(p);
if((sb.length()) % 2 == 0){
firstHalf.append(sb.substring(0, (sb.length()/2)));
secondHalf.append(sb.substring((sb.length()/2), sb.length()));
for(int f = secondHalf.length(); f > 0 ; f --){
reversedSecondHalf.append(secondHalf.charAt(f-1));
}
if(firstHalf.toString().equals(reversedSecondHalf.toString())){
System.out.println("\nX: " + x +
"\nY: " + y +
"\nP: " + p +
"\nSB: " + sb +
"\nlength: " + sb.length() +
"\nFirst Half: " + firstHalf +
"\nSecond Half: " + secondHalf +
"\nReversed second half: " + reversedSecondHalf);
System.out.println("\n\n\nWE'VE GOT A WINNER GIRLS AND BOYS!!!!\n\n");
}
}
}
}
}
}
| 3,145 | 0.426713 | 0.411168 | 85 | 36.082352 | 24.666821 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.494118 | false | false | 11 |
fd52f897a5ef88c6ff4fd0e06d91c7b1ae05875b | 38,697,655,362,702 | 7358a57c77c70e158716cbc10779b3e87b56b758 | /Design_Pattern/src/main/java/musementpark/online/facade/OperationAndMaintain_UI.java | ebc49b3b1b22f0eff67f301b96a4bdbc40aedc6e | [
"MIT"
] | permissive | Yxxxb/Design_Pattern | https://github.com/Yxxxb/Design_Pattern | ef838fae7c298629b48b04756a15d4dbb16119b2 | d7dae3ee836f02c9ea7e5be24eebebd555368010 | refs/heads/main | 2023-09-03T12:39:03.303000 | 2021-11-03T13:40:28 | 2021-11-03T13:40:28 | 425,465,607 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package musementpark.online.facade;
import musementpark.util.Print;
import musementpark.util.PrintInfo;
/**
* author: PandaLYZ
* description:该类为OperationAndMaintain_UI类,其向客户端提供了对游乐设施进行日常运维检修的一个接口,采用单例模式实现。同时,该类按顺序封装了进行运维检测的
* 具体操作,只需要客户端调用类的doMaintenance方法即可完成对游乐设施的运维检测,因此使用了外观模式。减少了客户端与系统内部的耦合。
*/
public class OperationAndMaintain_UI {
private static final OperationAndMaintain_UI _singleton=new OperationAndMaintain_UI();
/**
* description:私有构造函数,因为是单例模式
*/
private OperationAndMaintain_UI(){};
/**
* description: 供外界调用,获取该类的唯一实例
* @return 返回该类的唯一实例_singleton
*/
public static OperationAndMaintain_UI getInstance(){
return _singleton;
}
private static AgingTestSystem _agingTestSys = AgingTestSystem.getInstance();
private static ElectricSystem _electricSys = ElectricSystem.getInstance();
private static MechanicalSystem _mechanicalSys = MechanicalSystem.getInstance();
private static StructureSystem _structureSys = StructureSystem.getInstance();
/**
* description:该方法是提供给客户端的接口,客户端只需要调用该方法即可完成运维检测所需的一系列操作
*/
public void doMaintenance(){
Print.print(new PrintInfo(
"OperationAndMaintain_UI",
String.valueOf(System.identityHashCode(this)),
"doMaintenance",
"开始对设备进行运维检测!"
));
_electricSys.doElectricTesting();//进行电路连通性检测
_mechanicalSys.doMechanicalTesting();//进行整体机械结构测试
_structureSys.doStructureTesting();//进行机器结构稳定性测试
_agingTestSys.doAgingTest();//进行设备老龄化测试
Print.print(new PrintInfo(
"OperationAndMaintain_UI",
String.valueOf(System.identityHashCode(this)),
"doMaintenance",
"设备运维检测完成!"
));
}
}
| UTF-8 | Java | 2,312 | java | OperationAndMaintain_UI.java | Java | [
{
"context": "mport musementpark.util.PrintInfo;\n\n/**\n * author: PandaLYZ\n * description:该类为OperationAndMaintain_UI类,其向客户端提",
"end": 129,
"score": 0.9991507530212402,
"start": 121,
"tag": "USERNAME",
"value": "PandaLYZ"
}
] | null | [] | package musementpark.online.facade;
import musementpark.util.Print;
import musementpark.util.PrintInfo;
/**
* author: PandaLYZ
* description:该类为OperationAndMaintain_UI类,其向客户端提供了对游乐设施进行日常运维检修的一个接口,采用单例模式实现。同时,该类按顺序封装了进行运维检测的
* 具体操作,只需要客户端调用类的doMaintenance方法即可完成对游乐设施的运维检测,因此使用了外观模式。减少了客户端与系统内部的耦合。
*/
public class OperationAndMaintain_UI {
private static final OperationAndMaintain_UI _singleton=new OperationAndMaintain_UI();
/**
* description:私有构造函数,因为是单例模式
*/
private OperationAndMaintain_UI(){};
/**
* description: 供外界调用,获取该类的唯一实例
* @return 返回该类的唯一实例_singleton
*/
public static OperationAndMaintain_UI getInstance(){
return _singleton;
}
private static AgingTestSystem _agingTestSys = AgingTestSystem.getInstance();
private static ElectricSystem _electricSys = ElectricSystem.getInstance();
private static MechanicalSystem _mechanicalSys = MechanicalSystem.getInstance();
private static StructureSystem _structureSys = StructureSystem.getInstance();
/**
* description:该方法是提供给客户端的接口,客户端只需要调用该方法即可完成运维检测所需的一系列操作
*/
public void doMaintenance(){
Print.print(new PrintInfo(
"OperationAndMaintain_UI",
String.valueOf(System.identityHashCode(this)),
"doMaintenance",
"开始对设备进行运维检测!"
));
_electricSys.doElectricTesting();//进行电路连通性检测
_mechanicalSys.doMechanicalTesting();//进行整体机械结构测试
_structureSys.doStructureTesting();//进行机器结构稳定性测试
_agingTestSys.doAgingTest();//进行设备老龄化测试
Print.print(new PrintInfo(
"OperationAndMaintain_UI",
String.valueOf(System.identityHashCode(this)),
"doMaintenance",
"设备运维检测完成!"
));
}
}
| 2,312 | 0.68091 | 0.68091 | 54 | 32.370369 | 27.334211 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.407407 | false | false | 11 |
a628253cee7d23a7a2115d27b82e7e3b0f3a3ae4 | 15,857,019,270,695 | 1ac64a07b161bad29ac87601783c0f384cdac641 | /AppointmentFrame.java | 436636360f819b4fb1f85a02d49b008a4713a10e | [] | no_license | TheValresh/AppointmentViewer | https://github.com/TheValresh/AppointmentViewer | ac92b8769824f9a4046fe8dd99ca66b508a920c4 | 73888564ee2b547feddac0d6ab7235fe928fcf86 | refs/heads/master | 2021-01-20T02:42:11.660000 | 2017-04-26T06:22:08 | 2017-04-26T06:22:08 | 89,440,420 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by Ahnaf Mir STUDENT ID: 500570401 on 4/13/2017.
*/
public class AppointmentFrame extends JFrame {
private static final int FRAME_WIDTH = 1000;
private static final int FRAME_HEIGHT = 800;
Calendar currentDate;
SimpleDateFormat currentDateSDF;
SimpleDateFormat currentDateAndTimeAppointment;
ArrayList<Appointment> appointments;
JLabel currentDateLabel;
JTextArea appointmentText;
JScrollPane scrollPane;
JPanel controlPanel;
JPanel descriptionPanel;
JLabel descriptionLabel;
JTextField descriptionTextField;
JPanel dateControlPanel;
JButton previousDay;
JButton nextDay;
JLabel dayRequestLabel;
JTextField requestedDay;
JLabel monthRequestLabel;
JTextField requestedMonth;
JLabel yearRequestLabel;
JTextField requestedYear;
JButton showAppointmentButton;
JPanel actionPanel;
JLabel makeHour;
JTextField requestedHour;
JLabel makeMinutes;
JTextField requestedMinute;
JButton makeAppointmentButton;
JButton removeAppointmentButton;
JLabel contactLastNameLabel;
JTextField contactLastNameField;
JLabel contactFirstName;
JTextField contactFirstNameField;
JLabel contactTelephoneLabel;
JTextField contactTelephoneField;
JLabel contactAddressLabel;
JTextField contactAddressField;
JLabel contactEmailLabel;
JTextField contactEmailField;
JButton findPerson;
JButton clearPersonInfo;
JButton recallButton;
JButton currentDayButton;
Calendar dayInRealTime;
Contacts contactList;
Stack<Appointment> appointmentStack;
public AppointmentFrame() {
createAppointmentPanel();
contactList = new Contacts();
appointmentStack = new Stack<Appointment>();
try {
contactList.readContactFiles();
} catch (FileNotFoundException exception) {
descriptionTextField.setText("Cannot read file");
} catch (NumberFormatException exception) {
descriptionTextField.setText("File imported did not contain a number in the first line.");
}
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createAppointmentPanel() {
JPanel appointmentViewerWindow = createAppointmentViewerWindow();
JPanel appointmentDateControlsPanel = createAppointmentDateControlsPanel();
JPanel appointmentControlsPanel = createActionPanel();
JPanel description = createDescriptionPanel();
JPanel contactPanel = createContactPanel();
JPanel appointmentPanel = new JPanel();
appointmentPanel.setLayout(new GridLayout(4, 2));
appointmentPanel.add(appointmentViewerWindow);
appointmentPanel.add(appointmentDateControlsPanel);
appointmentPanel.add(appointmentControlsPanel);
appointmentPanel.add(description);
appointmentPanel.add(contactPanel);
add(appointmentPanel);
}
public JPanel createAppointmentViewerWindow() {
JPanel appointmentViewerWindow = new JPanel();
appointments = new ArrayList<Appointment>();
currentDate = new GregorianCalendar();
currentDate = currentDate.getInstance(); // Set currentDate to the time the program is run.
dayInRealTime = new GregorianCalendar();
dayInRealTime = dayInRealTime.getInstance();
currentDateSDF = new SimpleDateFormat("EEE, dd, MMM, yyyy");
currentDateLabel = new JLabel();
currentDateLabel.setText("" + currentDateSDF.format(currentDate.getTime()));
currentDateAndTimeAppointment = new SimpleDateFormat("HH : mm EEE, dd, MMM, yyyy");
appointmentViewerWindow.add(currentDateLabel, BorderLayout.NORTH);
appointmentText = new JTextArea(80, 50);
appointmentViewerWindow.add(appointmentText);
scrollPane = new JScrollPane(appointmentText);
appointmentViewerWindow.add(scrollPane);
return appointmentViewerWindow;
}
public JPanel createAppointmentDateControlsPanel() {
dateControlPanel = new JPanel();
previousDay = new JButton("<");
dateControlPanel.add(previousDay, BorderLayout.NORTH);
previousDay.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentDate.add(currentDate.DAY_OF_MONTH, -1);
appointmentText.setText(printAppointments(appointments, currentDate));
currentDateLabel.setText(currentDateSDF.format(currentDate.getTime()));
}
});
nextDay = new JButton(">");
dateControlPanel.add(nextDay, BorderLayout.NORTH);
nextDay.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentDate.add(currentDate.DAY_OF_MONTH, 1);
appointmentText.setText(printAppointments(appointments, currentDate));
currentDateLabel.setText(currentDateSDF.format(currentDate.getTime()));
}
});
currentDayButton = new JButton("Current Day");
dateControlPanel.add(currentDayButton);
currentDayButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentDate.setTime(dayInRealTime.getTime());
appointmentText.setText(printAppointments(appointments, dayInRealTime));
currentDateLabel.setText(currentDateSDF.format(dayInRealTime.getTime()));
}
});
dayRequestLabel = new JLabel("Day");
dateControlPanel.add(dayRequestLabel, BorderLayout.CENTER);
requestedDay = new JTextField(2);
dateControlPanel.add(requestedDay, BorderLayout.CENTER);
monthRequestLabel = new JLabel("Month");
dateControlPanel.add(monthRequestLabel, BorderLayout.CENTER);
requestedMonth = new JTextField(2);
dateControlPanel.add(requestedMonth, BorderLayout.CENTER);
yearRequestLabel = new JLabel("Year");
dateControlPanel.add(yearRequestLabel, BorderLayout.CENTER);
requestedYear = new JTextField(4);
dateControlPanel.add(requestedYear, BorderLayout.CENTER);
showAppointmentButton = new JButton("Show");
dateControlPanel.add(showAppointmentButton, BorderLayout.SOUTH);
showAppointmentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int dayReq = Integer.parseInt(requestedDay.getText());
int monthReq = Integer.parseInt(requestedMonth.getText());
int yearReq = Integer.parseInt(requestedYear.getText());
// Error checking for wrong dates
if (monthReq > 12) {
descriptionTextField.setText("Months are invalid");
throw new IllegalArgumentException("Months are invalid");
}
if ((dayReq > 29) && monthReq == 2) {
descriptionTextField.setText("Days are invalid");
throw new IllegalArgumentException("Days is invalid");
}
if (((dayReq == 29) && (monthReq == 2)) && ((yearReq % 4) != 0)) {
descriptionTextField.setText("Days are invalid");
throw new IllegalArgumentException("Days is invalid");
}
if ((dayReq > 30) && ((monthReq != 1) || (monthReq != 3) || (monthReq != 5) || (monthReq != 7) || (monthReq != 8) || (monthReq != 10) || (monthReq != 12))) {
descriptionTextField.setText("Days are invalid");
throw new IllegalArgumentException("Days is invalid");
}
currentDate.set(yearReq + 0, monthReq - 1, dayReq + 0);
appointmentText.setText(printAppointments(appointments, currentDate));
currentDateLabel.setText(currentDateSDF.format(currentDate.getTime()));
}
});
return dateControlPanel;
}
public JPanel createDescriptionPanel() {
descriptionPanel = new JPanel();
descriptionLabel = new JLabel("Description");
descriptionPanel.add(descriptionLabel);
descriptionTextField = new JTextField(40);
descriptionPanel.add(descriptionTextField);
return descriptionPanel;
}
// Action Control Panel functions
public JPanel createActionPanel() {
actionPanel = new JPanel();
makeHour = new JLabel("Hour");
actionPanel.add(makeHour);
requestedHour = new JTextField(2);
actionPanel.add(requestedHour);
makeMinutes = new JLabel("Minutes");
actionPanel.add(makeMinutes);
requestedMinute = new JTextField(2);
actionPanel.add(requestedMinute);
makeAppointmentButton = new JButton("Create");
actionPanel.add(makeAppointmentButton);
makeAppointmentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int year, month, day, hourReq, minuteReq;
hourReq = Integer.parseInt(requestedHour.getText());
minuteReq = Integer.parseInt(requestedMinute.getText());
try {
year = currentDate.get(Calendar.YEAR);
month = currentDate.get(Calendar.MONTH);
day = currentDate.get(Calendar.DAY_OF_MONTH);
// Error checking for invalid values here
if (hourReq > 24 || hourReq < 0) {
throw new IllegalArgumentException();
}
if (minuteReq > 59 || minuteReq < 0) {
throw new IllegalArgumentException();
}
Calendar requestedAppointmentTime = new GregorianCalendar(year, month, day, hourReq, minuteReq, 0);
String requestedAppointmentDescription = descriptionTextField.getText();
Person requestedPerson = new Person();
requestedPerson.setLastName(contactLastNameField.getText());
requestedPerson.setFirstName(contactFirstNameField.getText());
requestedPerson.setTelephone(contactTelephoneField.getText());
requestedPerson.setAddress(contactAddressField.getText());
requestedPerson.setEmail(contactEmailField.getText());
Appointment requestedAppointment = new Appointment(requestedAppointmentTime, requestedAppointmentDescription, requestedPerson);
if (!findAppointment(appointments, requestedAppointment)) {
appointments.add(requestedAppointment);
appointmentStack.push(requestedAppointment);
appointmentText.setText(printAppointments(appointments, currentDate));
} else
descriptionTextField.setText("CONFLICT!!");
}
catch (IllegalArgumentException exception) {
if (minuteReq > 59 || minuteReq < 0)
descriptionTextField.setText("Minutes are invalid");
if (hourReq > 24 || hourReq < 0)
descriptionTextField.setText("Hours are invalid");
}
}
});
removeAppointmentButton = new JButton("Cancel");
actionPanel.add(removeAppointmentButton);
removeAppointmentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int year = currentDate.get(Calendar.YEAR);
int month = currentDate.get(Calendar.MONTH);
int day = currentDate.get(Calendar.DAY_OF_MONTH);
int hourReq = Integer.parseInt(requestedHour.getText());
int minuteReq = Integer.parseInt(requestedMinute.getText());
Calendar requestedAppointmentTime = new GregorianCalendar(year, month, day, hourReq, minuteReq, 0);
String requestedAppointmentDescription = descriptionTextField.getText();
Person personToRemove = new Person();
personToRemove.setLastName(contactLastNameField.getText());
personToRemove.setFirstName(contactFirstNameField.getText());
personToRemove.setEmail(contactEmailField.getText());
personToRemove.setAddress(contactAddressField.getText());
personToRemove.setTelephone(contactTelephoneField.getText());
Appointment requestedAppointment = new Appointment(requestedAppointmentTime, requestedAppointmentDescription, personToRemove);
if (findAppointment(appointments, requestedAppointment)) {
for (int i = 0; i < appointments.size(); i++) {
Appointment checkingThisAppointment = appointments.get(i);
if (requestedAppointment.getDate().equals(checkingThisAppointment.getDate())) {
appointments.remove(i);
appointmentStack.pop();
}
}
}
appointmentText.setText(printAppointments(appointments, currentDate));
}
});
recallButton = new JButton("Recall");
actionPanel.add(recallButton);
recallButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Appointment appointmentToSetFieldsTo = appointmentStack.peek();
Person personDetails = appointmentToSetFieldsTo.getPerson();
Calendar dateDetails = appointmentToSetFieldsTo.getDate();
contactAddressField.setText(personDetails.getAddress());
contactEmailField.setText(personDetails.getEmail());
contactTelephoneField.setText(personDetails.getTelephone());
contactFirstNameField.setText(personDetails.getFirstName());
contactLastNameField.setText(personDetails.getLastName());
currentDate = dateDetails;
requestedHour.setText(currentDate.get(Calendar.HOUR_OF_DAY) + "");
requestedMinute.setText(currentDate.get(Calendar.MINUTE) + "");
appointmentText.setText(printAppointments(appointments, currentDate));
currentDateLabel.setText(currentDateSDF.format(currentDate.getTime()));
}
});
return actionPanel;
}
public JPanel createContactPanel() {
JPanel contactPanel = new JPanel();
contactPanel.setLayout(new GridLayout(6, 2));
contactLastNameLabel = new JLabel("Last Name");
contactPanel.add(contactLastNameLabel);
contactFirstName = new JLabel("First Name");
contactPanel.add(contactFirstName);
contactLastNameField = new JTextField(20);
contactPanel.add(contactLastNameField);
contactFirstNameField = new JTextField(20);
contactPanel.add(contactFirstNameField);
contactEmailLabel = new JLabel("Email");
contactPanel.add(contactEmailLabel);
contactTelephoneLabel = new JLabel("Telephone");
contactPanel.add(contactTelephoneLabel);
contactEmailField = new JTextField(20);
contactPanel.add(contactEmailField);
contactTelephoneField = new JTextField(20);
contactPanel.add(contactTelephoneField);
contactAddressLabel = new JLabel("Address");
contactPanel.add(contactAddressLabel);
contactAddressField = new JTextField(20);
contactPanel.add(contactAddressField);
findPerson = new JButton("Find");
contactPanel.add(findPerson);
findPerson.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String lastName, firstName, address, telephone, email;
lastName = contactLastNameField.getText();
firstName = contactFirstNameField.getText();
address = contactAddressField.getText();
telephone = contactTelephoneField.getText();
email = contactEmailField.getText();
Person personFound = new Person();
try {
if (!email.isEmpty())
personFound = contactList.FindPersonWithEmail(email);
if (!telephone.isEmpty() && email.isEmpty())
personFound = contactList.FindPersonWithNumber(telephone);
if (email.isEmpty() && telephone.isEmpty())
personFound = contactList.FindPersonWithName(lastName, firstName);
contactLastNameField.setText(personFound.getLastName());
contactFirstNameField.setText(personFound.getFirstName());
contactAddressField.setText(personFound.getAddress());
contactTelephoneField.setText(personFound.getTelephone());
contactEmailField.setText(personFound.getEmail());
} catch (NullPointerException exception) {
descriptionTextField.setText("Unable to find person, please check the fields."); // Catches wrong input or nullpointers.
}
}
});
clearPersonInfo = new JButton("Clear");
contactPanel.add(clearPersonInfo);
clearPersonInfo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
contactLastNameField.setText("");
contactFirstNameField.setText("");
contactTelephoneField.setText("");
contactEmailField.setText("");
contactAddressField.setText("");
}
});
return contactPanel;
}
public boolean findAppointment(ArrayList<Appointment> listOfAppointments, Appointment appointmentToFind) {
for (int i = 0; i < listOfAppointments.size(); i++) {
Appointment appointmentToCheck = listOfAppointments.get(i);
if ((appointmentToFind.occursOn(appointmentToCheck))) {
return true;
}
}
return false;
}
public String printAppointments(ArrayList<Appointment> listOfAppointments, Calendar inputDate) {
Collections.sort(listOfAppointments, new Comparator<Appointment>() {
@Override
public int compare(Appointment app1, Appointment app2) {
return app1.getDate().compareTo(app2.getDate());
}
});
Collections.sort(listOfAppointments);
String relevantAppointments = "";
for (int i = 0; i < listOfAppointments.size(); i++) {
Appointment appointmentBeingChecked = listOfAppointments.get(i);
Calendar checkedDate = appointmentBeingChecked.getDate();
boolean sameYear, sameMonth, sameDay;
sameYear = checkedDate.get(Calendar.YEAR) == inputDate.get(Calendar.YEAR);
sameMonth = checkedDate.get(Calendar.MONTH) == inputDate.get(Calendar.MONTH);
sameDay = checkedDate.get(Calendar.DAY_OF_MONTH) == inputDate.get(Calendar.DAY_OF_MONTH);
if (sameYear && sameMonth && sameDay) {
relevantAppointments = relevantAppointments + currentDateAndTimeAppointment.format(checkedDate.getTime()) + " "
+ appointmentBeingChecked.getDescription() + " " + appointmentBeingChecked.getPerson() + "\n";
}
}
return relevantAppointments;
}
}
| UTF-8 | Java | 20,624 | java | AppointmentFrame.java | Java | [
{
"context": "rmat;\r\nimport java.util.*;\r\n\r\n\r\n/**\r\n * Created by Ahnaf Mir STUDENT ID: 500570401 on 4/13/2017.\r\n */\r\npublic ",
"end": 246,
"score": 0.999787449836731,
"start": 237,
"tag": "NAME",
"value": "Ahnaf Mir"
},
{
"context": "Performed(ActionEvent e) {\r\n ... | null | [] | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by <NAME> STUDENT ID: 500570401 on 4/13/2017.
*/
public class AppointmentFrame extends JFrame {
private static final int FRAME_WIDTH = 1000;
private static final int FRAME_HEIGHT = 800;
Calendar currentDate;
SimpleDateFormat currentDateSDF;
SimpleDateFormat currentDateAndTimeAppointment;
ArrayList<Appointment> appointments;
JLabel currentDateLabel;
JTextArea appointmentText;
JScrollPane scrollPane;
JPanel controlPanel;
JPanel descriptionPanel;
JLabel descriptionLabel;
JTextField descriptionTextField;
JPanel dateControlPanel;
JButton previousDay;
JButton nextDay;
JLabel dayRequestLabel;
JTextField requestedDay;
JLabel monthRequestLabel;
JTextField requestedMonth;
JLabel yearRequestLabel;
JTextField requestedYear;
JButton showAppointmentButton;
JPanel actionPanel;
JLabel makeHour;
JTextField requestedHour;
JLabel makeMinutes;
JTextField requestedMinute;
JButton makeAppointmentButton;
JButton removeAppointmentButton;
JLabel contactLastNameLabel;
JTextField contactLastNameField;
JLabel contactFirstName;
JTextField contactFirstNameField;
JLabel contactTelephoneLabel;
JTextField contactTelephoneField;
JLabel contactAddressLabel;
JTextField contactAddressField;
JLabel contactEmailLabel;
JTextField contactEmailField;
JButton findPerson;
JButton clearPersonInfo;
JButton recallButton;
JButton currentDayButton;
Calendar dayInRealTime;
Contacts contactList;
Stack<Appointment> appointmentStack;
public AppointmentFrame() {
createAppointmentPanel();
contactList = new Contacts();
appointmentStack = new Stack<Appointment>();
try {
contactList.readContactFiles();
} catch (FileNotFoundException exception) {
descriptionTextField.setText("Cannot read file");
} catch (NumberFormatException exception) {
descriptionTextField.setText("File imported did not contain a number in the first line.");
}
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createAppointmentPanel() {
JPanel appointmentViewerWindow = createAppointmentViewerWindow();
JPanel appointmentDateControlsPanel = createAppointmentDateControlsPanel();
JPanel appointmentControlsPanel = createActionPanel();
JPanel description = createDescriptionPanel();
JPanel contactPanel = createContactPanel();
JPanel appointmentPanel = new JPanel();
appointmentPanel.setLayout(new GridLayout(4, 2));
appointmentPanel.add(appointmentViewerWindow);
appointmentPanel.add(appointmentDateControlsPanel);
appointmentPanel.add(appointmentControlsPanel);
appointmentPanel.add(description);
appointmentPanel.add(contactPanel);
add(appointmentPanel);
}
public JPanel createAppointmentViewerWindow() {
JPanel appointmentViewerWindow = new JPanel();
appointments = new ArrayList<Appointment>();
currentDate = new GregorianCalendar();
currentDate = currentDate.getInstance(); // Set currentDate to the time the program is run.
dayInRealTime = new GregorianCalendar();
dayInRealTime = dayInRealTime.getInstance();
currentDateSDF = new SimpleDateFormat("EEE, dd, MMM, yyyy");
currentDateLabel = new JLabel();
currentDateLabel.setText("" + currentDateSDF.format(currentDate.getTime()));
currentDateAndTimeAppointment = new SimpleDateFormat("HH : mm EEE, dd, MMM, yyyy");
appointmentViewerWindow.add(currentDateLabel, BorderLayout.NORTH);
appointmentText = new JTextArea(80, 50);
appointmentViewerWindow.add(appointmentText);
scrollPane = new JScrollPane(appointmentText);
appointmentViewerWindow.add(scrollPane);
return appointmentViewerWindow;
}
public JPanel createAppointmentDateControlsPanel() {
dateControlPanel = new JPanel();
previousDay = new JButton("<");
dateControlPanel.add(previousDay, BorderLayout.NORTH);
previousDay.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentDate.add(currentDate.DAY_OF_MONTH, -1);
appointmentText.setText(printAppointments(appointments, currentDate));
currentDateLabel.setText(currentDateSDF.format(currentDate.getTime()));
}
});
nextDay = new JButton(">");
dateControlPanel.add(nextDay, BorderLayout.NORTH);
nextDay.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentDate.add(currentDate.DAY_OF_MONTH, 1);
appointmentText.setText(printAppointments(appointments, currentDate));
currentDateLabel.setText(currentDateSDF.format(currentDate.getTime()));
}
});
currentDayButton = new JButton("Current Day");
dateControlPanel.add(currentDayButton);
currentDayButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
currentDate.setTime(dayInRealTime.getTime());
appointmentText.setText(printAppointments(appointments, dayInRealTime));
currentDateLabel.setText(currentDateSDF.format(dayInRealTime.getTime()));
}
});
dayRequestLabel = new JLabel("Day");
dateControlPanel.add(dayRequestLabel, BorderLayout.CENTER);
requestedDay = new JTextField(2);
dateControlPanel.add(requestedDay, BorderLayout.CENTER);
monthRequestLabel = new JLabel("Month");
dateControlPanel.add(monthRequestLabel, BorderLayout.CENTER);
requestedMonth = new JTextField(2);
dateControlPanel.add(requestedMonth, BorderLayout.CENTER);
yearRequestLabel = new JLabel("Year");
dateControlPanel.add(yearRequestLabel, BorderLayout.CENTER);
requestedYear = new JTextField(4);
dateControlPanel.add(requestedYear, BorderLayout.CENTER);
showAppointmentButton = new JButton("Show");
dateControlPanel.add(showAppointmentButton, BorderLayout.SOUTH);
showAppointmentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int dayReq = Integer.parseInt(requestedDay.getText());
int monthReq = Integer.parseInt(requestedMonth.getText());
int yearReq = Integer.parseInt(requestedYear.getText());
// Error checking for wrong dates
if (monthReq > 12) {
descriptionTextField.setText("Months are invalid");
throw new IllegalArgumentException("Months are invalid");
}
if ((dayReq > 29) && monthReq == 2) {
descriptionTextField.setText("Days are invalid");
throw new IllegalArgumentException("Days is invalid");
}
if (((dayReq == 29) && (monthReq == 2)) && ((yearReq % 4) != 0)) {
descriptionTextField.setText("Days are invalid");
throw new IllegalArgumentException("Days is invalid");
}
if ((dayReq > 30) && ((monthReq != 1) || (monthReq != 3) || (monthReq != 5) || (monthReq != 7) || (monthReq != 8) || (monthReq != 10) || (monthReq != 12))) {
descriptionTextField.setText("Days are invalid");
throw new IllegalArgumentException("Days is invalid");
}
currentDate.set(yearReq + 0, monthReq - 1, dayReq + 0);
appointmentText.setText(printAppointments(appointments, currentDate));
currentDateLabel.setText(currentDateSDF.format(currentDate.getTime()));
}
});
return dateControlPanel;
}
public JPanel createDescriptionPanel() {
descriptionPanel = new JPanel();
descriptionLabel = new JLabel("Description");
descriptionPanel.add(descriptionLabel);
descriptionTextField = new JTextField(40);
descriptionPanel.add(descriptionTextField);
return descriptionPanel;
}
// Action Control Panel functions
public JPanel createActionPanel() {
actionPanel = new JPanel();
makeHour = new JLabel("Hour");
actionPanel.add(makeHour);
requestedHour = new JTextField(2);
actionPanel.add(requestedHour);
makeMinutes = new JLabel("Minutes");
actionPanel.add(makeMinutes);
requestedMinute = new JTextField(2);
actionPanel.add(requestedMinute);
makeAppointmentButton = new JButton("Create");
actionPanel.add(makeAppointmentButton);
makeAppointmentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int year, month, day, hourReq, minuteReq;
hourReq = Integer.parseInt(requestedHour.getText());
minuteReq = Integer.parseInt(requestedMinute.getText());
try {
year = currentDate.get(Calendar.YEAR);
month = currentDate.get(Calendar.MONTH);
day = currentDate.get(Calendar.DAY_OF_MONTH);
// Error checking for invalid values here
if (hourReq > 24 || hourReq < 0) {
throw new IllegalArgumentException();
}
if (minuteReq > 59 || minuteReq < 0) {
throw new IllegalArgumentException();
}
Calendar requestedAppointmentTime = new GregorianCalendar(year, month, day, hourReq, minuteReq, 0);
String requestedAppointmentDescription = descriptionTextField.getText();
Person requestedPerson = new Person();
requestedPerson.setLastName(contactLastNameField.getText());
requestedPerson.setFirstName(contactFirstNameField.getText());
requestedPerson.setTelephone(contactTelephoneField.getText());
requestedPerson.setAddress(contactAddressField.getText());
requestedPerson.setEmail(contactEmailField.getText());
Appointment requestedAppointment = new Appointment(requestedAppointmentTime, requestedAppointmentDescription, requestedPerson);
if (!findAppointment(appointments, requestedAppointment)) {
appointments.add(requestedAppointment);
appointmentStack.push(requestedAppointment);
appointmentText.setText(printAppointments(appointments, currentDate));
} else
descriptionTextField.setText("CONFLICT!!");
}
catch (IllegalArgumentException exception) {
if (minuteReq > 59 || minuteReq < 0)
descriptionTextField.setText("Minutes are invalid");
if (hourReq > 24 || hourReq < 0)
descriptionTextField.setText("Hours are invalid");
}
}
});
removeAppointmentButton = new JButton("Cancel");
actionPanel.add(removeAppointmentButton);
removeAppointmentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int year = currentDate.get(Calendar.YEAR);
int month = currentDate.get(Calendar.MONTH);
int day = currentDate.get(Calendar.DAY_OF_MONTH);
int hourReq = Integer.parseInt(requestedHour.getText());
int minuteReq = Integer.parseInt(requestedMinute.getText());
Calendar requestedAppointmentTime = new GregorianCalendar(year, month, day, hourReq, minuteReq, 0);
String requestedAppointmentDescription = descriptionTextField.getText();
Person personToRemove = new Person();
personToRemove.setLastName(contactLastNameField.getText());
personToRemove.setFirstName(contactFirstNameField.getText());
personToRemove.setEmail(contactEmailField.getText());
personToRemove.setAddress(contactAddressField.getText());
personToRemove.setTelephone(contactTelephoneField.getText());
Appointment requestedAppointment = new Appointment(requestedAppointmentTime, requestedAppointmentDescription, personToRemove);
if (findAppointment(appointments, requestedAppointment)) {
for (int i = 0; i < appointments.size(); i++) {
Appointment checkingThisAppointment = appointments.get(i);
if (requestedAppointment.getDate().equals(checkingThisAppointment.getDate())) {
appointments.remove(i);
appointmentStack.pop();
}
}
}
appointmentText.setText(printAppointments(appointments, currentDate));
}
});
recallButton = new JButton("Recall");
actionPanel.add(recallButton);
recallButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Appointment appointmentToSetFieldsTo = appointmentStack.peek();
Person personDetails = appointmentToSetFieldsTo.getPerson();
Calendar dateDetails = appointmentToSetFieldsTo.getDate();
contactAddressField.setText(personDetails.getAddress());
contactEmailField.setText(personDetails.getEmail());
contactTelephoneField.setText(personDetails.getTelephone());
contactFirstNameField.setText(personDetails.getFirstName());
contactLastNameField.setText(personDetails.getLastName());
currentDate = dateDetails;
requestedHour.setText(currentDate.get(Calendar.HOUR_OF_DAY) + "");
requestedMinute.setText(currentDate.get(Calendar.MINUTE) + "");
appointmentText.setText(printAppointments(appointments, currentDate));
currentDateLabel.setText(currentDateSDF.format(currentDate.getTime()));
}
});
return actionPanel;
}
public JPanel createContactPanel() {
JPanel contactPanel = new JPanel();
contactPanel.setLayout(new GridLayout(6, 2));
contactLastNameLabel = new JLabel("Last Name");
contactPanel.add(contactLastNameLabel);
contactFirstName = new JLabel("First Name");
contactPanel.add(contactFirstName);
contactLastNameField = new JTextField(20);
contactPanel.add(contactLastNameField);
contactFirstNameField = new JTextField(20);
contactPanel.add(contactFirstNameField);
contactEmailLabel = new JLabel("Email");
contactPanel.add(contactEmailLabel);
contactTelephoneLabel = new JLabel("Telephone");
contactPanel.add(contactTelephoneLabel);
contactEmailField = new JTextField(20);
contactPanel.add(contactEmailField);
contactTelephoneField = new JTextField(20);
contactPanel.add(contactTelephoneField);
contactAddressLabel = new JLabel("Address");
contactPanel.add(contactAddressLabel);
contactAddressField = new JTextField(20);
contactPanel.add(contactAddressField);
findPerson = new JButton("Find");
contactPanel.add(findPerson);
findPerson.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String lastName, firstName, address, telephone, email;
lastName = contactLastNameField.getText();
firstName = contactFirstNameField.getText();
address = contactAddressField.getText();
telephone = contactTelephoneField.getText();
email = contactEmailField.getText();
Person personFound = new Person();
try {
if (!email.isEmpty())
personFound = contactList.FindPersonWithEmail(email);
if (!telephone.isEmpty() && email.isEmpty())
personFound = contactList.FindPersonWithNumber(telephone);
if (email.isEmpty() && telephone.isEmpty())
personFound = contactList.FindPersonWithName(lastName, firstName);
contactLastNameField.setText(personFound.getLastName());
contactFirstNameField.setText(personFound.getFirstName());
contactAddressField.setText(personFound.getAddress());
contactTelephoneField.setText(personFound.getTelephone());
contactEmailField.setText(personFound.getEmail());
} catch (NullPointerException exception) {
descriptionTextField.setText("Unable to find person, please check the fields."); // Catches wrong input or nullpointers.
}
}
});
clearPersonInfo = new JButton("Clear");
contactPanel.add(clearPersonInfo);
clearPersonInfo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
contactLastNameField.setText("");
contactFirstNameField.setText("");
contactTelephoneField.setText("");
contactEmailField.setText("");
contactAddressField.setText("");
}
});
return contactPanel;
}
public boolean findAppointment(ArrayList<Appointment> listOfAppointments, Appointment appointmentToFind) {
for (int i = 0; i < listOfAppointments.size(); i++) {
Appointment appointmentToCheck = listOfAppointments.get(i);
if ((appointmentToFind.occursOn(appointmentToCheck))) {
return true;
}
}
return false;
}
public String printAppointments(ArrayList<Appointment> listOfAppointments, Calendar inputDate) {
Collections.sort(listOfAppointments, new Comparator<Appointment>() {
@Override
public int compare(Appointment app1, Appointment app2) {
return app1.getDate().compareTo(app2.getDate());
}
});
Collections.sort(listOfAppointments);
String relevantAppointments = "";
for (int i = 0; i < listOfAppointments.size(); i++) {
Appointment appointmentBeingChecked = listOfAppointments.get(i);
Calendar checkedDate = appointmentBeingChecked.getDate();
boolean sameYear, sameMonth, sameDay;
sameYear = checkedDate.get(Calendar.YEAR) == inputDate.get(Calendar.YEAR);
sameMonth = checkedDate.get(Calendar.MONTH) == inputDate.get(Calendar.MONTH);
sameDay = checkedDate.get(Calendar.DAY_OF_MONTH) == inputDate.get(Calendar.DAY_OF_MONTH);
if (sameYear && sameMonth && sameDay) {
relevantAppointments = relevantAppointments + currentDateAndTimeAppointment.format(checkedDate.getTime()) + " "
+ appointmentBeingChecked.getDescription() + " " + appointmentBeingChecked.getPerson() + "\n";
}
}
return relevantAppointments;
}
}
| 20,621 | 0.617048 | 0.612442 | 471 | 41.787685 | 30.191841 | 173 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.789809 | false | false | 11 |
845d64b99ae96c48e8b140859dff382aa8d90e07 | 6,854,767,840,652 | 6f255b093357ec12fb5dbef292368f021b455a76 | /src/deadlybanquet/model/ItemsAndNameSingelton.java | 5dde5da3a47ad526390baf885e816d07477709a7 | [] | no_license | Mathcar/DeadlyBanquet | https://github.com/Mathcar/DeadlyBanquet | cff3aa9b440a746fe3177f7329d0143c2b41c6ae | 8c53f9fb55648eb23fc9c18bf89c4c6c93da73dc | refs/heads/master | 2021-01-18T21:57:35.209000 | 2016-05-25T23:05:08 | 2016-05-25T23:05:08 | 51,753,720 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package deadlybanquet.model;
import java.io.*;
import java.util.ArrayList;
/**
* Created by Tom on 2016-04-25.
*/
public class ItemsAndNameSingelton {
private ArrayList<String> allNPCNames;
private ArrayList<String> allNames;
private ArrayList<String> items;
private static ItemsAndNameSingelton instance = null;
protected ItemsAndNameSingelton() {
// Exists only to defeat instantiation.
}
public static ItemsAndNameSingelton getInstance() {
if(instance == null) {
instance = new ItemsAndNameSingelton();
}
return instance;
}
public ArrayList<String> readFile(){
ArrayList<String> temp=new ArrayList<String>();
BufferedReader br = null;
String line = "";
File file = new File("res/items/items");
try{
br = new BufferedReader(new FileReader(file.getAbsolutePath()));
while((line=br.readLine()) != null){
temp.add(line);
}
}catch(FileNotFoundException e){
e.printStackTrace();
System.exit(0);
}catch(IOException e){
e.printStackTrace();
System.exit(0);
}
return temp;
}
public ArrayList<String> getAllNPCNames() {
return allNPCNames;
}
public void setAllNPCNames(ArrayList<String> allNPCNames) {
this.allNPCNames = allNPCNames;
}
public ArrayList<String> getAllNames() {
return allNames;
}
public void setAllNames(ArrayList<String> allNames) {
this.allNames = allNames;
}
public ArrayList<String> getItems() {
return items;
}
public void setItems(ArrayList<String> items) {
this.items = items;
}
}
| UTF-8 | Java | 1,764 | java | ItemsAndNameSingelton.java | Java | [
{
"context": ".*;\nimport java.util.ArrayList;\n\n/**\n * Created by Tom on 2016-04-25.\n */\npublic class ItemsAndNameSinge",
"end": 98,
"score": 0.9981407523155212,
"start": 95,
"tag": "NAME",
"value": "Tom"
}
] | null | [] | package deadlybanquet.model;
import java.io.*;
import java.util.ArrayList;
/**
* Created by Tom on 2016-04-25.
*/
public class ItemsAndNameSingelton {
private ArrayList<String> allNPCNames;
private ArrayList<String> allNames;
private ArrayList<String> items;
private static ItemsAndNameSingelton instance = null;
protected ItemsAndNameSingelton() {
// Exists only to defeat instantiation.
}
public static ItemsAndNameSingelton getInstance() {
if(instance == null) {
instance = new ItemsAndNameSingelton();
}
return instance;
}
public ArrayList<String> readFile(){
ArrayList<String> temp=new ArrayList<String>();
BufferedReader br = null;
String line = "";
File file = new File("res/items/items");
try{
br = new BufferedReader(new FileReader(file.getAbsolutePath()));
while((line=br.readLine()) != null){
temp.add(line);
}
}catch(FileNotFoundException e){
e.printStackTrace();
System.exit(0);
}catch(IOException e){
e.printStackTrace();
System.exit(0);
}
return temp;
}
public ArrayList<String> getAllNPCNames() {
return allNPCNames;
}
public void setAllNPCNames(ArrayList<String> allNPCNames) {
this.allNPCNames = allNPCNames;
}
public ArrayList<String> getAllNames() {
return allNames;
}
public void setAllNames(ArrayList<String> allNames) {
this.allNames = allNames;
}
public ArrayList<String> getItems() {
return items;
}
public void setItems(ArrayList<String> items) {
this.items = items;
}
}
| 1,764 | 0.603741 | 0.598073 | 71 | 23.84507 | 19.842087 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.366197 | false | false | 11 |
176aaf579c94204c21fc929560eff5c3c80adaa5 | 21,749,714,429,273 | 56728b8d2f0dd39541f2b16c7b88beb1061788dc | /src/com/box/game/planeandroid/SocketClient.java | bbbc2615199327e30ada2b07771a3bc7ff17c406 | [] | no_license | floralejandro07/Topgun--Android-based-jet-game | https://github.com/floralejandro07/Topgun--Android-based-jet-game | d3f79f8acdfef01850959c4844e58fbc122dcf75 | a693021d5e72df0ab368a365d400cc4267eadd70 | refs/heads/master | 2020-04-02T02:04:31.299000 | 2012-01-02T15:39:57 | 2012-01-02T15:39:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Copyright 2011 codeoedoc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.box.game.planeandroid;
import java.io.*;
import java.net.*;
public class SocketClient {
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
public void getConnection() {
try {
requestSocket = new Socket("127.0.0.1", 2004);
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
} catch (Exception e) {
}
}
public void closeConnection() {
try {
in.close();
out.close();
requestSocket.close();
} catch (Exception e) {
}
}
public void sendXY(double x, double y) {
try {
out.writeDouble(x);
out.writeDouble(y);
out.flush();
} catch (Exception classNot) {
}
}
public double rcv() {
double r = 0;
try {
int t = in.available();
if (t != 0) {
r = in.readDouble();
} else {
r = 0;
}
} catch (Exception classNot) {
r = 0;
}
return r;
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
| UTF-8 | Java | 2,011 | java | SocketClient.java | Java | [
{
"context": "/*\n Copyright 2011 codeoedoc\n\n Licensed under the Apache License, Version 2.0 ",
"end": 28,
"score": 0.9997000694274902,
"start": 19,
"tag": "USERNAME",
"value": "codeoedoc"
},
{
"context": " try {\n requestSocket = new Socket(\"127.0.0.1\", 2004);\n ... | null | [] | /*
Copyright 2011 codeoedoc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.box.game.planeandroid;
import java.io.*;
import java.net.*;
public class SocketClient {
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
public void getConnection() {
try {
requestSocket = new Socket("127.0.0.1", 2004);
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
} catch (Exception e) {
}
}
public void closeConnection() {
try {
in.close();
out.close();
requestSocket.close();
} catch (Exception e) {
}
}
public void sendXY(double x, double y) {
try {
out.writeDouble(x);
out.writeDouble(y);
out.flush();
} catch (Exception classNot) {
}
}
public double rcv() {
double r = 0;
try {
int t = in.available();
if (t != 0) {
r = in.readDouble();
} else {
r = 0;
}
} catch (Exception classNot) {
r = 0;
}
return r;
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
| 2,011 | 0.565888 | 0.554948 | 83 | 23.228916 | 20.334152 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.39759 | false | false | 11 |
20e2df2ec7b176de5112f783b988d083b899fbb9 | 14,448,270,026,422 | dddb90b63b4d4daa8b490e5f3a3ce765f92be6fc | /Android/LoginActivity.java | 91447d487632abb28321ecd3ec5ed6341c41f2b3 | [] | no_license | rashedoz/ECG_Graph | https://github.com/rashedoz/ECG_Graph | 1636fb10cd99c9b9ff8bd9d880c00c2a6c72bbd7 | b724778c53c951f8ed698d286899e6c365b39185 | refs/heads/master | 2018-11-30T22:14:22.115000 | 2018-11-29T09:14:42 | 2018-11-29T09:14:42 | 145,239,155 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.rashed.ecgmonitoring;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText nPasswordField;
private EditText nEmailField;
String TAG = "LoginActivity";
private FirebaseAuth.AuthStateListener nAuthListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Log.e(TAG,"lOGIN aCTIVITY STARTED");
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
nEmailField = (EditText) findViewById(R.id.email);
nPasswordField = (EditText) findViewById(R.id.password);
nAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser()!=null){
//startActivity(new Intent(LoginActivity.this,UserDetails.class));
}
}
};
Button lBttn = (Button) findViewById(R.id.LoginBttn);
lBttn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSignIn();
}
});
Button SignUpBtn = (Button) findViewById(R.id.signUpBtn);
SignUpBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StartSignup();
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(nAuthListener);
}
private void startSignIn(){
String email = nEmailField.getText().toString();
String password = nPasswordField.getText().toString();
if(TextUtils.isEmpty(email) || TextUtils.isEmpty(password)){
Toast.makeText(LoginActivity.this, "Fields are Empty", Toast.LENGTH_LONG).show();
}
else {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
String login_email = user.getEmail().toString();
Toast.makeText(LoginActivity.this, "Welcome: "+login_email, Toast.LENGTH_LONG).show();
startActivity(new Intent(LoginActivity.this,MainActivity.class));
}else{
Log.e(TAG,"sIGN iN FAILED");
Toast.makeText(LoginActivity.this, "Sign In Failed", Toast.LENGTH_LONG).show();
}
}
});
}
}
private void StartSignup(){
String email = nEmailField.getText().toString();
String password = nPasswordField.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.e(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
String login_email = user.getEmail().toString();
Toast.makeText(LoginActivity.this, "Welcome: "+login_email, Toast.LENGTH_LONG).show();
} else {
// If sign in fails, display a message to the user.
Log.e(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
| UTF-8 | Java | 4,894 | java | LoginActivity.java | Java | [
{
"context": "ld.getText().toString();\n String password = nPasswordField.getText().toString();\n\n if(TextUtils.",
"end": 2441,
"score": 0.8623136281967163,
"start": 2432,
"tag": "PASSWORD",
"value": "nPassword"
},
{
"context": "ld.getText().toString();\n String... | null | [] | package com.example.rashed.ecgmonitoring;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private EditText nPasswordField;
private EditText nEmailField;
String TAG = "LoginActivity";
private FirebaseAuth.AuthStateListener nAuthListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Log.e(TAG,"lOGIN aCTIVITY STARTED");
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
nEmailField = (EditText) findViewById(R.id.email);
nPasswordField = (EditText) findViewById(R.id.password);
nAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser()!=null){
//startActivity(new Intent(LoginActivity.this,UserDetails.class));
}
}
};
Button lBttn = (Button) findViewById(R.id.LoginBttn);
lBttn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSignIn();
}
});
Button SignUpBtn = (Button) findViewById(R.id.signUpBtn);
SignUpBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StartSignup();
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(nAuthListener);
}
private void startSignIn(){
String email = nEmailField.getText().toString();
String password = <PASSWORD>Field.getText().toString();
if(TextUtils.isEmpty(email) || TextUtils.isEmpty(password)){
Toast.makeText(LoginActivity.this, "Fields are Empty", Toast.LENGTH_LONG).show();
}
else {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
String login_email = user.getEmail().toString();
Toast.makeText(LoginActivity.this, "Welcome: "+login_email, Toast.LENGTH_LONG).show();
startActivity(new Intent(LoginActivity.this,MainActivity.class));
}else{
Log.e(TAG,"sIGN iN FAILED");
Toast.makeText(LoginActivity.this, "Sign In Failed", Toast.LENGTH_LONG).show();
}
}
});
}
}
private void StartSignup(){
String email = nEmailField.getText().toString();
String password = <PASSWORD>();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.e(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
String login_email = user.getEmail().toString();
Toast.makeText(LoginActivity.this, "Welcome: "+login_email, Toast.LENGTH_LONG).show();
} else {
// If sign in fails, display a message to the user.
Log.e(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
| 4,872 | 0.587658 | 0.587454 | 150 | 31.626667 | 30.378622 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54 | false | false | 11 |
5da39a7f783f05115387e3926620be39314589a5 | 618,475,335,107 | 1999a5e48b85d9cbe665f957bb342091cacf106c | /src/test/ImageEntity.java | 92cc3304cdcd135b0ed6c18a77e0afbf25ba8fa0 | [] | no_license | Madao17/Balmung | https://github.com/Madao17/Balmung | a34f59a014223963b2863d4fa6ef954a9b929b83 | b71c3252c08648a76c477b75bc3389e8dab6b195 | refs/heads/master | 2021-01-10T22:08:19.768000 | 2012-04-14T01:38:24 | 2012-04-14T01:38:24 | 3,375,126 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import entityGame.Entity;
import entityGame.EntityGame;
public class ImageEntity implements Entity {
private String id;
private Image img;
private Rectangle bound;
public ImageEntity(String id, Image img, int width, int height, int x, int y) {
this.id = id;
this.img = img;
bound = new Rectangle(x, y, width, height);
//System.out.println("I am a tile");
}
@Override
public Rectangle getBoundingBox() {
// TODO Auto-generated method stub
return bound;
}
@Override
public String getId() {
// TODO Auto-generated method stub
return id;
}
@Override
public void update(EntityGame eg) {
// TODO Auto-generated method stub
}
@Override
public void render(Graphics2D g, EntityGame eg) {
// TODO Auto-generated method stub
g.drawImage(img, bound.x, bound.y, eg.getCanvas());
}
@Override
public boolean isSolid() {
// TODO Auto-generated method stub
return false;
}
}
| UTF-8 | Java | 1,065 | java | ImageEntity.java | Java | [] | null | [] | package test;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import entityGame.Entity;
import entityGame.EntityGame;
public class ImageEntity implements Entity {
private String id;
private Image img;
private Rectangle bound;
public ImageEntity(String id, Image img, int width, int height, int x, int y) {
this.id = id;
this.img = img;
bound = new Rectangle(x, y, width, height);
//System.out.println("I am a tile");
}
@Override
public Rectangle getBoundingBox() {
// TODO Auto-generated method stub
return bound;
}
@Override
public String getId() {
// TODO Auto-generated method stub
return id;
}
@Override
public void update(EntityGame eg) {
// TODO Auto-generated method stub
}
@Override
public void render(Graphics2D g, EntityGame eg) {
// TODO Auto-generated method stub
g.drawImage(img, bound.x, bound.y, eg.getCanvas());
}
@Override
public boolean isSolid() {
// TODO Auto-generated method stub
return false;
}
}
| 1,065 | 0.671362 | 0.669484 | 53 | 18.094339 | 17.72352 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.490566 | false | false | 11 |
9df99109fddba8129dadc7dfbc1b7f7291a53c7b | 9,929,964,442,007 | 30fb2305c07aabc919c224f9d43f7e6310e282b6 | /Grocery_8mm/app/src/main/java/com/example/ps12868_assignment_8mm/Fragments/OrdersFragment.java | 6fb4b6ded883bfca819aaaf7ee5ffc5a60c7e84b | [] | no_license | huyboken/Android-Networking-8mm-Grocery-App | https://github.com/huyboken/Android-Networking-8mm-Grocery-App | 7461bd3d3a61d5fff2a661402173c057bbdc466a | 3ab81fb1b44ce220e939548ecf0b0fd6dd80e91b | refs/heads/master | 2023-07-22T08:37:39.888000 | 2021-09-06T07:40:41 | 2021-09-06T07:40:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.ps12868_assignment_8mm.Fragments;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
import com.example.ps12868_assignment_8mm.Adapters.BannerAdapter;
import com.example.ps12868_assignment_8mm.Adapters.CatAdapter;
import com.example.ps12868_assignment_8mm.Adapters.GreatOffersAdapter;
import com.example.ps12868_assignment_8mm.Adapters.SimpleVerticalAdapter;
import com.example.ps12868_assignment_8mm.MainActivity;
import com.example.ps12868_assignment_8mm.Models.BannerModel;
import com.example.ps12868_assignment_8mm.Models.CategoryModel;
import com.example.ps12868_assignment_8mm.Models.GreatOffersModel;
import com.example.ps12868_assignment_8mm.Models.SimpleVerticalModel;
import com.example.ps12868_assignment_8mm.OperationRetrofitApi.ApiClient;
import com.example.ps12868_assignment_8mm.OperationRetrofitApi.ApiInterface;
import com.example.ps12868_assignment_8mm.OperationRetrofitApi.Users;
import com.example.ps12868_assignment_8mm.R;
import com.example.ps12868_assignment_8mm.Sessions.SessionManager;
import com.google.android.material.navigation.NavigationView;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class OrdersFragment extends Fragment implements View.OnClickListener {
public OrdersFragment() {
// Required empty public constructor
}
DrawerLayout drawerLayout;
ImageView navigationBar;
NavigationView navigationView;
private View view;
private RelativeLayout bookmarks, eightMMGold;
private TextView login, logout, your_orders, favorite_orders, address_book, online_ordering_help, send_feedback, report_safety_emergency, rate_playstore;
SessionManager sessionManager;
//////// category slider start ////////
private RecyclerView recyclerViewCategory;
private CatAdapter catAdapter;
private List<CategoryModel> categoryModelList;
//////// category slider end ////////
///////// banner slider start ////////
private RecyclerView recyclerViewBanner;
private BannerAdapter bannerAdapter;
private List<BannerModel> bannerModelList;
///////// banner slider end ////////
///////// simple vertical slider start ////////
private RecyclerView recyclerViewSimple;
private SimpleVerticalAdapter simpleVerticalAdapter;
private List<SimpleVerticalModel> simpleVerticalModelList;
///////// simple vertical slider end ////////
//////// great offers horizotall start ////////
private RecyclerView recyclerViewGreatOffersHorizontall;
private GreatOffersAdapter greatOffersAdapter;
private List<GreatOffersModel> greatOffersModelList;
//////// great offers horizotall end ////////
//////// great offers vertical slider start ////////
private RecyclerView greatOffersRecyclerViewVertical;
//////// great offers vertical slider end ////////
//////// new arrivals horizontall slider start ////////
private RecyclerView newArrivalHorizontallRecyclerViev;
//////// new arrivals horizontall slider end ////////
//////// new arrivals vertical slider start ////////
private RecyclerView newArrivalVerticalRecyclerViev;
//////// new arrivals vertical slider end ////////
//////// 8mm exclusive vertical slider start ////////
private RecyclerView exclusiveVerticalRecyclerViev;
//////// 8mm exclusive vertical slider end ////////
//////// 8mm exclusive horizontall slider start ////////
private RecyclerView exclusiveHorizontallRecyclerViev;
//////// 8mm exclusive horizontall slider end ////////
//////// api's calling ////////
public static ApiInterface apiInterface;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_orders, container, false);
sessionManager = new SessionManager(getContext());
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
init();
onSetNavigationDrawerEvents();
return view;
}
private void init() {
//////// category model list start ////////
recyclerViewCategory = (RecyclerView) view.findViewById(R.id.recyclerViewCategory);
LinearLayoutManager layoutManagerCategory = new LinearLayoutManager(getContext());
layoutManagerCategory.setOrientation(RecyclerView.HORIZONTAL);
recyclerViewCategory.setLayoutManager(layoutManagerCategory);
categoryModelList = new ArrayList<>();
Call<Users> categoryCall = apiInterface.getCategories();
categoryCall.enqueue(new Callback<Users>() {
@Override
public void onResponse(Call<Users> call, Response<Users> response) {
categoryModelList = response.body().getCategory();
catAdapter = new CatAdapter(categoryModelList, getContext());
recyclerViewCategory.setAdapter(catAdapter);
catAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(Call<Users> call, Throwable t) {
}
});
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Sản phẩm và Thực phẩm"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Rau quả và Trái cây"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Chăm sóc cá nhân"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Mục hộ gia đình"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Nhà và Nhà bếp"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Đồ uống"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Bữa sáng & Sản phẩm từ sữa"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Giá trị tốt nhất"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Mì và Đồ ăn liền"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Nội thất và Nhu cầu nhà ở"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Chăm sóc trẻ"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Chăm sóc thú cưng"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Thời trang"));
//////// category model list end ////////
//////// banner model list start ////////
recyclerViewBanner = (RecyclerView) view.findViewById(R.id.recyclerViewBanner);
LinearLayoutManager layoutManagerBanner = new LinearLayoutManager(getContext());
layoutManagerBanner.setOrientation(RecyclerView.HORIZONTAL);
recyclerViewBanner.setLayoutManager(layoutManagerBanner);
bannerModelList = new ArrayList<>();
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerAdapter = new BannerAdapter(bannerModelList,getContext());
recyclerViewBanner.setAdapter(bannerAdapter);
bannerAdapter.notifyDataSetChanged();
//////// banner model list end ////////
//////// simple vertical slider start ////////
recyclerViewSimple = (RecyclerView) view.findViewById(R.id.recyclerViewSimple);
LinearLayoutManager layoutManagerSimpleVerticalSlider = new LinearLayoutManager(getContext());
layoutManagerSimpleVerticalSlider.setOrientation(RecyclerView.VERTICAL);
recyclerViewSimple.setLayoutManager(layoutManagerSimpleVerticalSlider);
simpleVerticalModelList = new ArrayList<>();
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalAdapter = new SimpleVerticalAdapter(simpleVerticalModelList,getContext());
recyclerViewSimple.setAdapter(simpleVerticalAdapter);
simpleVerticalAdapter.notifyDataSetChanged();
//////// simple vertical slider end ////////
//////// great offers horizotall start ////////
recyclerViewGreatOffersHorizontall = (RecyclerView) view.findViewById(R.id.recyclerViewGreatOffersHorizontall);
LinearLayoutManager layoutManagerGreatOffers = new LinearLayoutManager(getContext());
layoutManagerGreatOffers.setOrientation(RecyclerView.HORIZONTAL);
recyclerViewGreatOffersHorizontall.setLayoutManager(layoutManagerGreatOffers);
greatOffersModelList = new ArrayList<>();
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersAdapter = new GreatOffersAdapter(greatOffersModelList,getContext());
recyclerViewGreatOffersHorizontall.setAdapter(greatOffersAdapter);
greatOffersAdapter.notifyDataSetChanged();
//////// great offers horizotall end ////////
//////// new great offers vertical slider start ////////
greatOffersRecyclerViewVertical = (RecyclerView) view.findViewById(R.id.greatOffersRecyclerViewVertical);
LinearLayoutManager layoutManagerVertivalGreatOffers = new LinearLayoutManager(getContext());
layoutManagerVertivalGreatOffers.setOrientation(RecyclerView.VERTICAL);
greatOffersRecyclerViewVertical.setLayoutManager(layoutManagerVertivalGreatOffers);
simpleVerticalModelList = new ArrayList<>();
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalAdapter = new SimpleVerticalAdapter(simpleVerticalModelList,getContext());
greatOffersRecyclerViewVertical.setAdapter(simpleVerticalAdapter);
simpleVerticalAdapter.notifyDataSetChanged();
//////// new great offers vertical slider end ////////
//////// new arrival horizontal model list start ////////
newArrivalHorizontallRecyclerViev = (RecyclerView) view.findViewById(R.id.newArrivalHorizontallRecyclerViev);
LinearLayoutManager layoutManagerHorizontallNewArrival = new LinearLayoutManager(getContext());
layoutManagerHorizontallNewArrival.setOrientation(RecyclerView.HORIZONTAL);
newArrivalHorizontallRecyclerViev.setLayoutManager(layoutManagerHorizontallNewArrival);
greatOffersModelList = new ArrayList<>();
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersAdapter = new GreatOffersAdapter(greatOffersModelList,getContext());
newArrivalHorizontallRecyclerViev.setAdapter(greatOffersAdapter);
greatOffersAdapter.notifyDataSetChanged();
//////// new arrival horizontal model list end ////////
//////// new arrival vertical model list start ////////
newArrivalVerticalRecyclerViev = (RecyclerView) view.findViewById(R.id.newArrivalVerticalRecyclerViev);
LinearLayoutManager layoutManagerVerticalNewArrival = new LinearLayoutManager(getContext());
layoutManagerVerticalNewArrival.setOrientation(RecyclerView.VERTICAL);
newArrivalVerticalRecyclerViev.setLayoutManager(layoutManagerVerticalNewArrival);
simpleVerticalModelList = new ArrayList<>();
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalAdapter = new SimpleVerticalAdapter(simpleVerticalModelList,getContext());
newArrivalVerticalRecyclerViev.setAdapter(simpleVerticalAdapter);
simpleVerticalAdapter.notifyDataSetChanged();
//////// new arrival vertical model list end ////////
//////// exclusive horizontal model list start ////////
exclusiveHorizontallRecyclerViev = (RecyclerView) view.findViewById(R.id.exclusiveHorizontallRecyclerViev);
LinearLayoutManager layoutManagerExclusiveHorizontal = new LinearLayoutManager(getContext());
layoutManagerExclusiveHorizontal.setOrientation(RecyclerView.HORIZONTAL);
exclusiveHorizontallRecyclerViev.setLayoutManager(layoutManagerExclusiveHorizontal);
greatOffersModelList = new ArrayList<>();
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersAdapter = new GreatOffersAdapter(greatOffersModelList,getContext());
exclusiveHorizontallRecyclerViev.setAdapter(greatOffersAdapter);
greatOffersAdapter.notifyDataSetChanged();
//////// exclusive horizontal model list end ////////
//////// exclusive vertical model list start ////////
exclusiveVerticalRecyclerViev = (RecyclerView) view.findViewById(R.id.exclusiveVerticalRecyclerViev);
LinearLayoutManager layoutManagerExclusiveVertical = new LinearLayoutManager(getContext());
layoutManagerExclusiveVertical.setOrientation(RecyclerView.VERTICAL);
exclusiveVerticalRecyclerViev.setLayoutManager(layoutManagerExclusiveVertical);
simpleVerticalModelList = new ArrayList<>();
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalAdapter = new SimpleVerticalAdapter(simpleVerticalModelList,getContext());
exclusiveVerticalRecyclerViev.setAdapter(simpleVerticalAdapter);
simpleVerticalAdapter.notifyDataSetChanged();
//////// exclusive vertical model list end ////////
}
private void onSetNavigationDrawerEvents() {
drawerLayout = (DrawerLayout) view.findViewById(R.id.drawerLayout);
navigationView = (NavigationView) view.findViewById(R.id.navigationView);
navigationBar = (ImageView) view.findViewById(R.id.navigationBar);
login = (TextView) view.findViewById(R.id.login);
logout = (TextView) view.findViewById(R.id.logout);
bookmarks = (RelativeLayout) view.findViewById(R.id.relativeLayout3);
eightMMGold = (RelativeLayout) view.findViewById(R.id.relativeLayout4);
your_orders = (TextView) view.findViewById(R.id.your_orders);
favorite_orders = (TextView) view.findViewById(R.id.favorite_orders);
address_book = (TextView) view.findViewById(R.id.address_book);
online_ordering_help = (TextView) view.findViewById(R.id.online_ordering_help);
send_feedback = (TextView) view.findViewById(R.id.send_feedback);
report_safety_emergency = (TextView) view.findViewById(R.id.report_safety_emergency);
rate_playstore = (TextView) view.findViewById(R.id.rate_playstore);
navigationBar.setOnClickListener(this);
login.setOnClickListener(this);
logout.setOnClickListener(this);
bookmarks.setOnClickListener(this);
eightMMGold.setOnClickListener(this);
your_orders.setOnClickListener(this);
favorite_orders.setOnClickListener(this);
address_book.setOnClickListener(this);
online_ordering_help.setOnClickListener(this);
send_feedback.setOnClickListener(this);
report_safety_emergency.setOnClickListener(this);
rate_playstore.setOnClickListener(this);
}
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.navigationBar:
drawerLayout.openDrawer(navigationView, true);
break;
case R.id.login:
Login();
break;
case R.id.logout:
Logout();
break;
case R.id.relativeLayout3:
Toast.makeText(getContext(), "bookmarks", Toast.LENGTH_SHORT).show();
break;
case R.id.relativeLayout4:
Toast.makeText(getContext(), "eightMMGold", Toast.LENGTH_SHORT).show();
break;
case R.id.your_orders:
Toast.makeText(getContext(), "your_orders", Toast.LENGTH_SHORT).show();
break;
case R.id.favorite_orders:
Toast.makeText(getContext(), "favorite_orders", Toast.LENGTH_SHORT).show();
break;
case R.id.address_book:
Toast.makeText(getContext(), "address_book", Toast.LENGTH_SHORT).show();
break;
case R.id.online_ordering_help:
Toast.makeText(getContext(), "online_ordering_help", Toast.LENGTH_SHORT).show();
break;
case R.id.send_feedback:
Toast.makeText(getContext(), "send_feedback", Toast.LENGTH_SHORT).show();
break;
case R.id.report_safety_emergency:
Toast.makeText(getContext(), "report_safety_emergency", Toast.LENGTH_SHORT).show();
break;
case R.id.rate_playstore:
Toast.makeText(getContext(), "rate_playstore", Toast.LENGTH_SHORT).show();
break;
}
}
private void Logout() {
sessionManager.editor.clear();
sessionManager.editor.commit();
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
getActivity().finish();
Animatoo.animateSwipeRight(getContext());
}
private void Login() {
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
getActivity().finish();
Animatoo.animateSwipeRight(getContext());
}
@Override
public void onStart() {
super.onStart();
if (sessionManager.isLogin()) {
login.setVisibility(View.GONE);
logout.setVisibility(View.VISIBLE);
}
}
} | UTF-8 | Java | 26,026 | java | OrdersFragment.java | Java | [] | null | [] | package com.example.ps12868_assignment_8mm.Fragments;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
import com.example.ps12868_assignment_8mm.Adapters.BannerAdapter;
import com.example.ps12868_assignment_8mm.Adapters.CatAdapter;
import com.example.ps12868_assignment_8mm.Adapters.GreatOffersAdapter;
import com.example.ps12868_assignment_8mm.Adapters.SimpleVerticalAdapter;
import com.example.ps12868_assignment_8mm.MainActivity;
import com.example.ps12868_assignment_8mm.Models.BannerModel;
import com.example.ps12868_assignment_8mm.Models.CategoryModel;
import com.example.ps12868_assignment_8mm.Models.GreatOffersModel;
import com.example.ps12868_assignment_8mm.Models.SimpleVerticalModel;
import com.example.ps12868_assignment_8mm.OperationRetrofitApi.ApiClient;
import com.example.ps12868_assignment_8mm.OperationRetrofitApi.ApiInterface;
import com.example.ps12868_assignment_8mm.OperationRetrofitApi.Users;
import com.example.ps12868_assignment_8mm.R;
import com.example.ps12868_assignment_8mm.Sessions.SessionManager;
import com.google.android.material.navigation.NavigationView;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class OrdersFragment extends Fragment implements View.OnClickListener {
public OrdersFragment() {
// Required empty public constructor
}
DrawerLayout drawerLayout;
ImageView navigationBar;
NavigationView navigationView;
private View view;
private RelativeLayout bookmarks, eightMMGold;
private TextView login, logout, your_orders, favorite_orders, address_book, online_ordering_help, send_feedback, report_safety_emergency, rate_playstore;
SessionManager sessionManager;
//////// category slider start ////////
private RecyclerView recyclerViewCategory;
private CatAdapter catAdapter;
private List<CategoryModel> categoryModelList;
//////// category slider end ////////
///////// banner slider start ////////
private RecyclerView recyclerViewBanner;
private BannerAdapter bannerAdapter;
private List<BannerModel> bannerModelList;
///////// banner slider end ////////
///////// simple vertical slider start ////////
private RecyclerView recyclerViewSimple;
private SimpleVerticalAdapter simpleVerticalAdapter;
private List<SimpleVerticalModel> simpleVerticalModelList;
///////// simple vertical slider end ////////
//////// great offers horizotall start ////////
private RecyclerView recyclerViewGreatOffersHorizontall;
private GreatOffersAdapter greatOffersAdapter;
private List<GreatOffersModel> greatOffersModelList;
//////// great offers horizotall end ////////
//////// great offers vertical slider start ////////
private RecyclerView greatOffersRecyclerViewVertical;
//////// great offers vertical slider end ////////
//////// new arrivals horizontall slider start ////////
private RecyclerView newArrivalHorizontallRecyclerViev;
//////// new arrivals horizontall slider end ////////
//////// new arrivals vertical slider start ////////
private RecyclerView newArrivalVerticalRecyclerViev;
//////// new arrivals vertical slider end ////////
//////// 8mm exclusive vertical slider start ////////
private RecyclerView exclusiveVerticalRecyclerViev;
//////// 8mm exclusive vertical slider end ////////
//////// 8mm exclusive horizontall slider start ////////
private RecyclerView exclusiveHorizontallRecyclerViev;
//////// 8mm exclusive horizontall slider end ////////
//////// api's calling ////////
public static ApiInterface apiInterface;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_orders, container, false);
sessionManager = new SessionManager(getContext());
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
init();
onSetNavigationDrawerEvents();
return view;
}
private void init() {
//////// category model list start ////////
recyclerViewCategory = (RecyclerView) view.findViewById(R.id.recyclerViewCategory);
LinearLayoutManager layoutManagerCategory = new LinearLayoutManager(getContext());
layoutManagerCategory.setOrientation(RecyclerView.HORIZONTAL);
recyclerViewCategory.setLayoutManager(layoutManagerCategory);
categoryModelList = new ArrayList<>();
Call<Users> categoryCall = apiInterface.getCategories();
categoryCall.enqueue(new Callback<Users>() {
@Override
public void onResponse(Call<Users> call, Response<Users> response) {
categoryModelList = response.body().getCategory();
catAdapter = new CatAdapter(categoryModelList, getContext());
recyclerViewCategory.setAdapter(catAdapter);
catAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(Call<Users> call, Throwable t) {
}
});
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Sản phẩm và Thực phẩm"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Rau quả và Trái cây"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Chăm sóc cá nhân"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Mục hộ gia đình"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Nhà và Nhà bếp"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Đồ uống"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Bữa sáng & Sản phẩm từ sữa"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Giá trị tốt nhất"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Mì và Đồ ăn liền"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Nội thất và Nhu cầu nhà ở"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Chăm sóc trẻ"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Chăm sóc thú cưng"));
// categoryModelList.add(new CategoryModel(R.drawable.black_placeholder, "Thời trang"));
//////// category model list end ////////
//////// banner model list start ////////
recyclerViewBanner = (RecyclerView) view.findViewById(R.id.recyclerViewBanner);
LinearLayoutManager layoutManagerBanner = new LinearLayoutManager(getContext());
layoutManagerBanner.setOrientation(RecyclerView.HORIZONTAL);
recyclerViewBanner.setLayoutManager(layoutManagerBanner);
bannerModelList = new ArrayList<>();
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerModelList.add(new BannerModel(R.drawable.black_placeholder));
bannerAdapter = new BannerAdapter(bannerModelList,getContext());
recyclerViewBanner.setAdapter(bannerAdapter);
bannerAdapter.notifyDataSetChanged();
//////// banner model list end ////////
//////// simple vertical slider start ////////
recyclerViewSimple = (RecyclerView) view.findViewById(R.id.recyclerViewSimple);
LinearLayoutManager layoutManagerSimpleVerticalSlider = new LinearLayoutManager(getContext());
layoutManagerSimpleVerticalSlider.setOrientation(RecyclerView.VERTICAL);
recyclerViewSimple.setLayoutManager(layoutManagerSimpleVerticalSlider);
simpleVerticalModelList = new ArrayList<>();
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalAdapter = new SimpleVerticalAdapter(simpleVerticalModelList,getContext());
recyclerViewSimple.setAdapter(simpleVerticalAdapter);
simpleVerticalAdapter.notifyDataSetChanged();
//////// simple vertical slider end ////////
//////// great offers horizotall start ////////
recyclerViewGreatOffersHorizontall = (RecyclerView) view.findViewById(R.id.recyclerViewGreatOffersHorizontall);
LinearLayoutManager layoutManagerGreatOffers = new LinearLayoutManager(getContext());
layoutManagerGreatOffers.setOrientation(RecyclerView.HORIZONTAL);
recyclerViewGreatOffersHorizontall.setLayoutManager(layoutManagerGreatOffers);
greatOffersModelList = new ArrayList<>();
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersAdapter = new GreatOffersAdapter(greatOffersModelList,getContext());
recyclerViewGreatOffersHorizontall.setAdapter(greatOffersAdapter);
greatOffersAdapter.notifyDataSetChanged();
//////// great offers horizotall end ////////
//////// new great offers vertical slider start ////////
greatOffersRecyclerViewVertical = (RecyclerView) view.findViewById(R.id.greatOffersRecyclerViewVertical);
LinearLayoutManager layoutManagerVertivalGreatOffers = new LinearLayoutManager(getContext());
layoutManagerVertivalGreatOffers.setOrientation(RecyclerView.VERTICAL);
greatOffersRecyclerViewVertical.setLayoutManager(layoutManagerVertivalGreatOffers);
simpleVerticalModelList = new ArrayList<>();
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalAdapter = new SimpleVerticalAdapter(simpleVerticalModelList,getContext());
greatOffersRecyclerViewVertical.setAdapter(simpleVerticalAdapter);
simpleVerticalAdapter.notifyDataSetChanged();
//////// new great offers vertical slider end ////////
//////// new arrival horizontal model list start ////////
newArrivalHorizontallRecyclerViev = (RecyclerView) view.findViewById(R.id.newArrivalHorizontallRecyclerViev);
LinearLayoutManager layoutManagerHorizontallNewArrival = new LinearLayoutManager(getContext());
layoutManagerHorizontallNewArrival.setOrientation(RecyclerView.HORIZONTAL);
newArrivalHorizontallRecyclerViev.setLayoutManager(layoutManagerHorizontallNewArrival);
greatOffersModelList = new ArrayList<>();
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersAdapter = new GreatOffersAdapter(greatOffersModelList,getContext());
newArrivalHorizontallRecyclerViev.setAdapter(greatOffersAdapter);
greatOffersAdapter.notifyDataSetChanged();
//////// new arrival horizontal model list end ////////
//////// new arrival vertical model list start ////////
newArrivalVerticalRecyclerViev = (RecyclerView) view.findViewById(R.id.newArrivalVerticalRecyclerViev);
LinearLayoutManager layoutManagerVerticalNewArrival = new LinearLayoutManager(getContext());
layoutManagerVerticalNewArrival.setOrientation(RecyclerView.VERTICAL);
newArrivalVerticalRecyclerViev.setLayoutManager(layoutManagerVerticalNewArrival);
simpleVerticalModelList = new ArrayList<>();
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalAdapter = new SimpleVerticalAdapter(simpleVerticalModelList,getContext());
newArrivalVerticalRecyclerViev.setAdapter(simpleVerticalAdapter);
simpleVerticalAdapter.notifyDataSetChanged();
//////// new arrival vertical model list end ////////
//////// exclusive horizontal model list start ////////
exclusiveHorizontallRecyclerViev = (RecyclerView) view.findViewById(R.id.exclusiveHorizontallRecyclerViev);
LinearLayoutManager layoutManagerExclusiveHorizontal = new LinearLayoutManager(getContext());
layoutManagerExclusiveHorizontal.setOrientation(RecyclerView.HORIZONTAL);
exclusiveHorizontallRecyclerViev.setLayoutManager(layoutManagerExclusiveHorizontal);
greatOffersModelList = new ArrayList<>();
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersModelList.add(new GreatOffersModel(R.drawable.black_placeholder, "Ngã ba rau","49 phút","Giảm Giá 30%","3.6"));
greatOffersAdapter = new GreatOffersAdapter(greatOffersModelList,getContext());
exclusiveHorizontallRecyclerViev.setAdapter(greatOffersAdapter);
greatOffersAdapter.notifyDataSetChanged();
//////// exclusive horizontal model list end ////////
//////// exclusive vertical model list start ////////
exclusiveVerticalRecyclerViev = (RecyclerView) view.findViewById(R.id.exclusiveVerticalRecyclerViev);
LinearLayoutManager layoutManagerExclusiveVertical = new LinearLayoutManager(getContext());
layoutManagerExclusiveVertical.setOrientation(RecyclerView.VERTICAL);
exclusiveVerticalRecyclerViev.setLayoutManager(layoutManagerExclusiveVertical);
simpleVerticalModelList = new ArrayList<>();
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalModelList.add(new SimpleVerticalModel(R.drawable.black_placeholder,"Trung Bắc","Thực phẩm tốt cho sức khỏe","10.000đ mỗi kg | 2 giờ","GIẢM GIÁ 20% - sử dụng mã ZOMATO","Nhà bếp được vệ sinh tốt.","4.6"));
simpleVerticalAdapter = new SimpleVerticalAdapter(simpleVerticalModelList,getContext());
exclusiveVerticalRecyclerViev.setAdapter(simpleVerticalAdapter);
simpleVerticalAdapter.notifyDataSetChanged();
//////// exclusive vertical model list end ////////
}
private void onSetNavigationDrawerEvents() {
drawerLayout = (DrawerLayout) view.findViewById(R.id.drawerLayout);
navigationView = (NavigationView) view.findViewById(R.id.navigationView);
navigationBar = (ImageView) view.findViewById(R.id.navigationBar);
login = (TextView) view.findViewById(R.id.login);
logout = (TextView) view.findViewById(R.id.logout);
bookmarks = (RelativeLayout) view.findViewById(R.id.relativeLayout3);
eightMMGold = (RelativeLayout) view.findViewById(R.id.relativeLayout4);
your_orders = (TextView) view.findViewById(R.id.your_orders);
favorite_orders = (TextView) view.findViewById(R.id.favorite_orders);
address_book = (TextView) view.findViewById(R.id.address_book);
online_ordering_help = (TextView) view.findViewById(R.id.online_ordering_help);
send_feedback = (TextView) view.findViewById(R.id.send_feedback);
report_safety_emergency = (TextView) view.findViewById(R.id.report_safety_emergency);
rate_playstore = (TextView) view.findViewById(R.id.rate_playstore);
navigationBar.setOnClickListener(this);
login.setOnClickListener(this);
logout.setOnClickListener(this);
bookmarks.setOnClickListener(this);
eightMMGold.setOnClickListener(this);
your_orders.setOnClickListener(this);
favorite_orders.setOnClickListener(this);
address_book.setOnClickListener(this);
online_ordering_help.setOnClickListener(this);
send_feedback.setOnClickListener(this);
report_safety_emergency.setOnClickListener(this);
rate_playstore.setOnClickListener(this);
}
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.navigationBar:
drawerLayout.openDrawer(navigationView, true);
break;
case R.id.login:
Login();
break;
case R.id.logout:
Logout();
break;
case R.id.relativeLayout3:
Toast.makeText(getContext(), "bookmarks", Toast.LENGTH_SHORT).show();
break;
case R.id.relativeLayout4:
Toast.makeText(getContext(), "eightMMGold", Toast.LENGTH_SHORT).show();
break;
case R.id.your_orders:
Toast.makeText(getContext(), "your_orders", Toast.LENGTH_SHORT).show();
break;
case R.id.favorite_orders:
Toast.makeText(getContext(), "favorite_orders", Toast.LENGTH_SHORT).show();
break;
case R.id.address_book:
Toast.makeText(getContext(), "address_book", Toast.LENGTH_SHORT).show();
break;
case R.id.online_ordering_help:
Toast.makeText(getContext(), "online_ordering_help", Toast.LENGTH_SHORT).show();
break;
case R.id.send_feedback:
Toast.makeText(getContext(), "send_feedback", Toast.LENGTH_SHORT).show();
break;
case R.id.report_safety_emergency:
Toast.makeText(getContext(), "report_safety_emergency", Toast.LENGTH_SHORT).show();
break;
case R.id.rate_playstore:
Toast.makeText(getContext(), "rate_playstore", Toast.LENGTH_SHORT).show();
break;
}
}
private void Logout() {
sessionManager.editor.clear();
sessionManager.editor.commit();
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
getActivity().finish();
Animatoo.animateSwipeRight(getContext());
}
private void Login() {
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
getActivity().finish();
Animatoo.animateSwipeRight(getContext());
}
@Override
public void onStart() {
super.onStart();
if (sessionManager.isLogin()) {
login.setVisibility(View.GONE);
logout.setVisibility(View.VISIBLE);
}
}
} | 26,026 | 0.703413 | 0.687142 | 424 | 58.285378 | 51.484573 | 226 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.266509 | false | false | 11 |
418b970c80fdfec1a4b24d1a3c9e87a43d5df607 | 30,537,217,503,577 | 3e6513e97a8822d5fb4873f1b16ce7a8a14a7739 | /src/test/java/com/tang/async/AsyncDemoTest.java | 67cd48c2c1fa4f3c89c716e2ebaafe96aafdbdf6 | [] | no_license | TangXW777/spring-boot-test | https://github.com/TangXW777/spring-boot-test | a9b6438c404cd9adee1b25d81544a684e9d2915b | d4b54b4fbcedb2c54c3ed12d57c501c12a5f6878 | refs/heads/master | 2020-04-27T07:49:32.033000 | 2019-03-06T15:04:25 | 2019-03-06T15:04:25 | 174,148,906 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tang.async;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.Future;
@SpringBootTest
@RunWith(SpringRunner.class)
public class AsyncDemoTest {
@Autowired
AsyncDemo asyncDemo;
@Test
public void test1() throws Exception{
asyncDemo.asyncSimple();
asyncDemo.asyncSimpleWithParams(1);
Future<String> future = asyncDemo.asyncWithReturnFuture(1);
System.out.println(future.get());
}
}
| UTF-8 | Java | 669 | java | AsyncDemoTest.java | Java | [] | null | [] | package com.tang.async;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.Future;
@SpringBootTest
@RunWith(SpringRunner.class)
public class AsyncDemoTest {
@Autowired
AsyncDemo asyncDemo;
@Test
public void test1() throws Exception{
asyncDemo.asyncSimple();
asyncDemo.asyncSimpleWithParams(1);
Future<String> future = asyncDemo.asyncWithReturnFuture(1);
System.out.println(future.get());
}
}
| 669 | 0.751868 | 0.745889 | 27 | 23.777779 | 21.461996 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 11 |
a011597c012f792803a683258e6f1c870568cfd0 | 22,454,089,092,165 | 634106a53e93682a6b71d67ab863349926b18717 | /Lab3/src/RationalTest.java | 70d97022e823d044ba8162b6e7eba06934ccae58 | [] | no_license | Catherine-Paul/Lab3 | https://github.com/Catherine-Paul/Lab3 | ca3d9d85c71908b678d27ff73fe5bc2510921624 | 3667061b54c0bc07fbd4f71692edfe5213554d1d | refs/heads/master | 2021-01-01T15:35:15.738000 | 2014-02-20T17:30:08 | 2014-02-20T17:30:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import static org.junit.Assert.*;
import org.junit.Test;
import junit.framework.TestCase;
public class RationalTest extends TestCase {
protected Rational HALF;
protected void setUp() {
HALF = new Rational( 1, 2 );
}
// Create new test
public RationalTest (String name) {
super(name);
}
public void testEquality() {
assertEquals(new Rational(1,3), new Rational(1,3));
assertEquals(new Rational(1,3), new Rational(2,6));
assertEquals(new Rational(3,3), new Rational(1,1));
}
// Test for nonequality
public void testNonEquality() {
assertFalse(new Rational(2,3).equals(
new Rational(1,3)));
}
public void testAccessors() {
assertEquals(new Rational(2,3).numerator(), 2);
assertEquals(new Rational(2,3).denominator(), 3);
}
public void testRoot() {
Rational s = new Rational( 1, 4 );
Rational sRoot = null;
try {
sRoot = s.root();
} catch (IllegalArgumentToSquareRootException e) {
e.printStackTrace();
}
assertTrue( sRoot.isLessThan( HALF.plus( Rational.getTolerance() ) )
&& HALF.minus( Rational.getTolerance() ).isLessThan( sRoot ) );
}
//Additional Test cases
public void testplus() {
assertEquals((new Rational(3,1).plus(new Rational(3,1))),new Rational(6,1));
assertEquals((new Rational(3,4).plus(new Rational(5,12))),new Rational(7,6));
assertEquals((new Rational(-3,4).plus(new Rational(5,12))),new Rational(-1,3));
}
public void testTimes() {
assertEquals((new Rational(5, 3)).times(new Rational(9, 2)), new Rational(15, 2));
}
public void testMinus() {
assertEquals((new Rational(2, 3)).minus(new Rational(3, 2)), new Rational(-5, 6));
}
public void testisLessThan()
{
assertTrue(new Rational(1,3).isLessThan(new Rational(2,3)));
assertTrue(new Rational(-2,3).isLessThan(new Rational(-1,3)));
}
public void testDivides() {
Rational a = new Rational(4, 3);
Rational b = new Rational(5, 6);
Rational c = new Rational(8, 5);
assertEquals(a.divides(b), c);
Rational a1 = new Rational(-4, 3);
Rational b1 = new Rational(5, 6);
Rational c1 = new Rational(-8, 5);
assertEquals(a.divides(b), c);
}
public void testDivideByZero() {
boolean testflag = false;
try {
Rational a = new Rational(4, 0);
}
catch (Exception e) {
//divide by zero should cause exception
testflag = true;
}
assertTrue( testflag);
}
public void testoString() {
Rational a = new Rational(7, 1);
String b = "7";
//assertEquals(a.toString(), b);
System.out.println("\n Conversion of rational numbers toString : " + a.toString()+"\n");
}
public void testabs() {
Rational a = new Rational(-4, -3);
Rational b = new Rational(4, 3);
assertEquals(a.abs(), b);
}
public void testgcd() {
Rational myRational = new Rational(10, 5);
try {
java.lang.reflect.Method gcd_method =
Rational.class.getDeclaredMethod("gcd", int.class, int.class);
gcd_method.setAccessible(true);
Object result = gcd_method.invoke(myRational,10 , 5 );
assertEquals(5, result);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testlcm() {
Rational myRational = new Rational(6, 8);
try {
java.lang.reflect.Method lcm_method
= Rational.class.getDeclaredMethod("lcm", int.class, int.class);
lcm_method.setAccessible(true);
Object result = lcm_method.invoke(myRational,6 , 8 );
assertEquals(24, result);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testSqRoot() {
Rational s = new Rational( 1, 4 );
Rational sRoot = null;
try {
sRoot = s.root();
} catch (IllegalArgumentToSquareRootException e) {
e.printStackTrace();
}
assertEquals(sRoot, new Rational( 1, 2 ));
}
public void testRootforhigh() {
Rational s = new Rational( 46342, 1);
Rational sRoot = null;
try {
sRoot = s.root();
} catch (IllegalArgumentToSquareRootException e) {
assertEquals(sRoot, null);
}
}
public void testRootforlow() {
Rational s = new Rational( -1, 3);
Rational sRoot = null;
try {
sRoot = s.root();
} catch (IllegalArgumentToSquareRootException e) {
assertEquals(sRoot, null);
}
}
public static void main(String args[]) {
String[] testCaseName =
{ RationalTest.class.getName() };
// junit.swingui.TestRunner.main(testCaseName);
junit.textui.TestRunner.main(testCaseName);
}
} | UTF-8 | Java | 5,361 | java | RationalTest.java | Java | [] | null | [] | import static org.junit.Assert.*;
import org.junit.Test;
import junit.framework.TestCase;
public class RationalTest extends TestCase {
protected Rational HALF;
protected void setUp() {
HALF = new Rational( 1, 2 );
}
// Create new test
public RationalTest (String name) {
super(name);
}
public void testEquality() {
assertEquals(new Rational(1,3), new Rational(1,3));
assertEquals(new Rational(1,3), new Rational(2,6));
assertEquals(new Rational(3,3), new Rational(1,1));
}
// Test for nonequality
public void testNonEquality() {
assertFalse(new Rational(2,3).equals(
new Rational(1,3)));
}
public void testAccessors() {
assertEquals(new Rational(2,3).numerator(), 2);
assertEquals(new Rational(2,3).denominator(), 3);
}
public void testRoot() {
Rational s = new Rational( 1, 4 );
Rational sRoot = null;
try {
sRoot = s.root();
} catch (IllegalArgumentToSquareRootException e) {
e.printStackTrace();
}
assertTrue( sRoot.isLessThan( HALF.plus( Rational.getTolerance() ) )
&& HALF.minus( Rational.getTolerance() ).isLessThan( sRoot ) );
}
//Additional Test cases
public void testplus() {
assertEquals((new Rational(3,1).plus(new Rational(3,1))),new Rational(6,1));
assertEquals((new Rational(3,4).plus(new Rational(5,12))),new Rational(7,6));
assertEquals((new Rational(-3,4).plus(new Rational(5,12))),new Rational(-1,3));
}
public void testTimes() {
assertEquals((new Rational(5, 3)).times(new Rational(9, 2)), new Rational(15, 2));
}
public void testMinus() {
assertEquals((new Rational(2, 3)).minus(new Rational(3, 2)), new Rational(-5, 6));
}
public void testisLessThan()
{
assertTrue(new Rational(1,3).isLessThan(new Rational(2,3)));
assertTrue(new Rational(-2,3).isLessThan(new Rational(-1,3)));
}
public void testDivides() {
Rational a = new Rational(4, 3);
Rational b = new Rational(5, 6);
Rational c = new Rational(8, 5);
assertEquals(a.divides(b), c);
Rational a1 = new Rational(-4, 3);
Rational b1 = new Rational(5, 6);
Rational c1 = new Rational(-8, 5);
assertEquals(a.divides(b), c);
}
public void testDivideByZero() {
boolean testflag = false;
try {
Rational a = new Rational(4, 0);
}
catch (Exception e) {
//divide by zero should cause exception
testflag = true;
}
assertTrue( testflag);
}
public void testoString() {
Rational a = new Rational(7, 1);
String b = "7";
//assertEquals(a.toString(), b);
System.out.println("\n Conversion of rational numbers toString : " + a.toString()+"\n");
}
public void testabs() {
Rational a = new Rational(-4, -3);
Rational b = new Rational(4, 3);
assertEquals(a.abs(), b);
}
public void testgcd() {
Rational myRational = new Rational(10, 5);
try {
java.lang.reflect.Method gcd_method =
Rational.class.getDeclaredMethod("gcd", int.class, int.class);
gcd_method.setAccessible(true);
Object result = gcd_method.invoke(myRational,10 , 5 );
assertEquals(5, result);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testlcm() {
Rational myRational = new Rational(6, 8);
try {
java.lang.reflect.Method lcm_method
= Rational.class.getDeclaredMethod("lcm", int.class, int.class);
lcm_method.setAccessible(true);
Object result = lcm_method.invoke(myRational,6 , 8 );
assertEquals(24, result);
} catch (Exception e) {
e.printStackTrace();
}
}
public void testSqRoot() {
Rational s = new Rational( 1, 4 );
Rational sRoot = null;
try {
sRoot = s.root();
} catch (IllegalArgumentToSquareRootException e) {
e.printStackTrace();
}
assertEquals(sRoot, new Rational( 1, 2 ));
}
public void testRootforhigh() {
Rational s = new Rational( 46342, 1);
Rational sRoot = null;
try {
sRoot = s.root();
} catch (IllegalArgumentToSquareRootException e) {
assertEquals(sRoot, null);
}
}
public void testRootforlow() {
Rational s = new Rational( -1, 3);
Rational sRoot = null;
try {
sRoot = s.root();
} catch (IllegalArgumentToSquareRootException e) {
assertEquals(sRoot, null);
}
}
public static void main(String args[]) {
String[] testCaseName =
{ RationalTest.class.getName() };
// junit.swingui.TestRunner.main(testCaseName);
junit.textui.TestRunner.main(testCaseName);
}
} | 5,361 | 0.535908 | 0.51427 | 180 | 27.794445 | 22.444424 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.994444 | false | false | 11 |
df409cbe31703167ee9cffb3db1ab6c787e2c4f5 | 24,584,392,833,294 | 6bfce045b845746d74ae350ee7e31be9ccb25db0 | /src/Abstract/Vehicle.java | 8804f935bddff9dbc23d4f7f7940c8b03512166d | [] | no_license | navreetKaur/InfyJavaClass | https://github.com/navreetKaur/InfyJavaClass | dbd66258313df0553d23e3da5f5663d739ddeaa4 | c95a5d213e70331a28138b28b1b17edda2167554 | refs/heads/master | 2021-01-17T18:04:30.866000 | 2016-06-22T18:29:27 | 2016-06-22T18:29:27 | 61,737,778 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Abstract;
public abstract class Vehicle {
public abstract String run();
public abstract String stop();
public abstract String accelerate();
}
| UTF-8 | Java | 155 | java | Vehicle.java | Java | [] | null | [] | package Abstract;
public abstract class Vehicle {
public abstract String run();
public abstract String stop();
public abstract String accelerate();
}
| 155 | 0.76129 | 0.76129 | 8 | 18.375 | 14.91591 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false | 11 |
274c475417316d1c0907be2f7a8070c57854805d | 14,869,176,799,196 | 70b29621776be22dd9fbb24bb35728ae98383eb5 | /src/Servidor/Delegado.java | 3c42f29ad5c08840c89159d6b5301a9324808a2e | [] | no_license | cmcastro85/Lab4Infracom | https://github.com/cmcastro85/Lab4Infracom | d37493ae6c8fc181388b09d27741f6bf34a84aeb | 350d7ec9996d9a4e9fea7b3841187f3be1507d98 | refs/heads/master | 2020-08-03T12:52:17.522000 | 2019-09-30T02:26:18 | 2019-09-30T02:26:18 | 211,758,697 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Servidor;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;
public class Delegado extends Thread{
public static final String ACK = "ACK";
public static final String ARCH = "ARCH";
public static final String HASH = "HASH";
public static final String ERR = "ERR";
public static final String HELLO = "HELLO";
public static final String READY = "READY";
public static final int BUFFER = 1;
private static final Logger LOGGER = Logger.getLogger(Delegado.class.getName());
private Counter contador;
private Socket sc;
private int ip;
private byte[] hash;
private byte[] bytes;
Delegado(Socket pSc,int pIp,Counter pContador,byte[] pBytes, byte[] pHash) {
sc = pSc;
ip = pIp;
contador = pContador;
hash = pHash;
bytes = pBytes;
}
public void run() {
LOGGER.info("Delegado " + ip + ": Empezando conexión.");
String linea;
try {
PrintWriter ac = new PrintWriter(sc.getOutputStream() , true);
BufferedReader dc = new BufferedReader(new InputStreamReader(sc.getInputStream()));
/***** Fase 1: Inicio *****/
linea = dc.readLine();
if (!linea.equals(HELLO)) {
ac.println(ERR);
sc.close();
throw new Exception(ip + ERR + linea +"-terminando.");
} else {
ac.println(ACK);
LOGGER.info(ip + linea + "-OK, continuando.");
}
/***** Fase 2: Espera OK *****/
linea = dc.readLine();
if (!linea.equals(READY)) {
ac.println(ERR);
sc.close();
throw new Exception(ip + ERR + linea +"-terminando.");
} else {
LOGGER.info(ip + linea + "- Esperando a los demás usuarios.");
contador.increment();
synchronized(contador) {
contador.wait();
}
}
/***** Fase 3: Archivo *****/
LOGGER.info(ip + ": Transmitiendo archivo");
Long inicio = System.currentTimeMillis();
send();
Long fin = System.currentTimeMillis();
float total = fin -inicio;
total = total / 1000;
LOGGER.info("Demora: "+ total+ " segundos.");
sc.close();
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error en el printwriter/buffer",e);
}
}
private void send() {
try {
PrintWriter ac = new PrintWriter(sc.getOutputStream() , true);
LOGGER.info("Creando hash");
ac.println(hash);
String hasho = DatatypeConverter.printHexBinary(hash).toUpperCase();
System.out.println(hasho);
LOGGER.info("Hash enviado");
ac.println(bytes.length);
OutputStream out = sc.getOutputStream();
byte[] buffer = new byte[BUFFER];
int pos = 0;
int i = 0;
int restante = bytes.length;
for(byte b:bytes) {
buffer[pos] = b;
pos++;
i++;
if(pos == buffer.length) {
out.write(buffer);
pos = 0;
restante -= buffer.length;
if(restante >= BUFFER) {
buffer = new byte[BUFFER];
}else {
buffer = new byte[restante];
System.out.println("Last pass: " + restante);
}
}
}
System.out.println("FINAL I = "+ i);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Error al mandar el archivo.",e);
}
}
}
| UTF-8 | Java | 3,805 | java | Delegado.java | Java | [] | null | [] | package Servidor;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;
public class Delegado extends Thread{
public static final String ACK = "ACK";
public static final String ARCH = "ARCH";
public static final String HASH = "HASH";
public static final String ERR = "ERR";
public static final String HELLO = "HELLO";
public static final String READY = "READY";
public static final int BUFFER = 1;
private static final Logger LOGGER = Logger.getLogger(Delegado.class.getName());
private Counter contador;
private Socket sc;
private int ip;
private byte[] hash;
private byte[] bytes;
Delegado(Socket pSc,int pIp,Counter pContador,byte[] pBytes, byte[] pHash) {
sc = pSc;
ip = pIp;
contador = pContador;
hash = pHash;
bytes = pBytes;
}
public void run() {
LOGGER.info("Delegado " + ip + ": Empezando conexión.");
String linea;
try {
PrintWriter ac = new PrintWriter(sc.getOutputStream() , true);
BufferedReader dc = new BufferedReader(new InputStreamReader(sc.getInputStream()));
/***** Fase 1: Inicio *****/
linea = dc.readLine();
if (!linea.equals(HELLO)) {
ac.println(ERR);
sc.close();
throw new Exception(ip + ERR + linea +"-terminando.");
} else {
ac.println(ACK);
LOGGER.info(ip + linea + "-OK, continuando.");
}
/***** Fase 2: Espera OK *****/
linea = dc.readLine();
if (!linea.equals(READY)) {
ac.println(ERR);
sc.close();
throw new Exception(ip + ERR + linea +"-terminando.");
} else {
LOGGER.info(ip + linea + "- Esperando a los demás usuarios.");
contador.increment();
synchronized(contador) {
contador.wait();
}
}
/***** Fase 3: Archivo *****/
LOGGER.info(ip + ": Transmitiendo archivo");
Long inicio = System.currentTimeMillis();
send();
Long fin = System.currentTimeMillis();
float total = fin -inicio;
total = total / 1000;
LOGGER.info("Demora: "+ total+ " segundos.");
sc.close();
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error en el printwriter/buffer",e);
}
}
private void send() {
try {
PrintWriter ac = new PrintWriter(sc.getOutputStream() , true);
LOGGER.info("Creando hash");
ac.println(hash);
String hasho = DatatypeConverter.printHexBinary(hash).toUpperCase();
System.out.println(hasho);
LOGGER.info("Hash enviado");
ac.println(bytes.length);
OutputStream out = sc.getOutputStream();
byte[] buffer = new byte[BUFFER];
int pos = 0;
int i = 0;
int restante = bytes.length;
for(byte b:bytes) {
buffer[pos] = b;
pos++;
i++;
if(pos == buffer.length) {
out.write(buffer);
pos = 0;
restante -= buffer.length;
if(restante >= BUFFER) {
buffer = new byte[BUFFER];
}else {
buffer = new byte[restante];
System.out.println("Last pass: " + restante);
}
}
}
System.out.println("FINAL I = "+ i);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Error al mandar el archivo.",e);
}
}
}
| 3,805 | 0.636077 | 0.633184 | 161 | 22.621119 | 19.191725 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.645963 | false | false | 11 |
4648a10a231a04bf773bf6dc2fd67c9cda7561db | 21,955,872,857,669 | 502ea93de54a1be3ef42edb0412a2bf4bc9ddbef | /sources/com/facebook/ads/NativeAdLayout.java | 234a82827ce27a8a950cfd33708ef9d93dc699e9 | [] | no_license | dovanduy/MegaBoicotApk | https://github.com/dovanduy/MegaBoicotApk | c0852af0773be1b272ec907113e8f088addb0f0c | 56890cb9f7afac196bd1fec2d1326f2cddda37a3 | refs/heads/master | 2020-07-02T04:28:02.199000 | 2019-08-08T20:44:49 | 2019-08-08T20:44:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook.ads;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import com.facebook.ads.internal.p115w.p117b.C2342x;
import com.facebook.ads.internal.view.p099a.C1917c;
public class NativeAdLayout extends FrameLayout {
/* renamed from: a */
private View f4735a;
/* renamed from: b */
private int f4736b = 0;
/* renamed from: c */
private int f4737c = 0;
public NativeAdLayout(Context context) {
super(context);
}
public NativeAdLayout(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public NativeAdLayout(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
}
public void clearAdReportingLayout() {
C2342x.m9085a((ViewGroup) this);
removeView(this.f4735a);
this.f4735a = null;
}
/* access modifiers changed from: protected */
public void onMeasure(int i, int i2) {
int i3;
super.onMeasure(i, i2);
if (this.f4737c > 0 && getMeasuredWidth() > this.f4737c) {
i3 = this.f4737c;
} else if (getMeasuredWidth() < this.f4736b) {
i3 = this.f4736b;
} else {
return;
}
setMeasuredDimension(i3, getMeasuredHeight());
}
public void setAdReportingLayout(C1917c cVar) {
this.f4735a = cVar;
this.f4735a.setLayoutParams(new LayoutParams(-1, -1));
C2342x.m9085a((ViewGroup) this);
addView(this.f4735a);
}
public void setMaxWidth(int i) {
this.f4737c = i;
}
public void setMinWidth(int i) {
this.f4736b = i;
}
}
| UTF-8 | Java | 1,813 | java | NativeAdLayout.java | Java | [] | null | [] | package com.facebook.ads;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import com.facebook.ads.internal.p115w.p117b.C2342x;
import com.facebook.ads.internal.view.p099a.C1917c;
public class NativeAdLayout extends FrameLayout {
/* renamed from: a */
private View f4735a;
/* renamed from: b */
private int f4736b = 0;
/* renamed from: c */
private int f4737c = 0;
public NativeAdLayout(Context context) {
super(context);
}
public NativeAdLayout(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public NativeAdLayout(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
}
public void clearAdReportingLayout() {
C2342x.m9085a((ViewGroup) this);
removeView(this.f4735a);
this.f4735a = null;
}
/* access modifiers changed from: protected */
public void onMeasure(int i, int i2) {
int i3;
super.onMeasure(i, i2);
if (this.f4737c > 0 && getMeasuredWidth() > this.f4737c) {
i3 = this.f4737c;
} else if (getMeasuredWidth() < this.f4736b) {
i3 = this.f4736b;
} else {
return;
}
setMeasuredDimension(i3, getMeasuredHeight());
}
public void setAdReportingLayout(C1917c cVar) {
this.f4735a = cVar;
this.f4735a.setLayoutParams(new LayoutParams(-1, -1));
C2342x.m9085a((ViewGroup) this);
addView(this.f4735a);
}
public void setMaxWidth(int i) {
this.f4737c = i;
}
public void setMinWidth(int i) {
this.f4736b = i;
}
}
| 1,813 | 0.636514 | 0.576944 | 69 | 25.275362 | 20.142164 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57971 | false | false | 11 |
c886bb8a4d45930f9153b8d2f413c73dc1c9eb7e | 8,899,172,304,317 | f7db37ed1435284b009392f591f71f4619bb9ff3 | /src/main/java/org/raviolini/aspects/io/configuration/drivers/FileConfigDriver.java | c298d9f4abd92617f52870311dd52c9306b2af76 | [] | no_license | otaviofff/raviolini | https://github.com/otaviofff/raviolini | 2ab22037d8e01fd37ea36dc368b3af453ab73d22 | d18c1cd2fd4117ffb0cb64b4bdb7e142967f486d | refs/heads/master | 2021-01-10T05:59:55.881000 | 2018-01-02T03:44:50 | 2018-01-02T03:44:50 | 43,460,284 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.raviolini.aspects.io.configuration.drivers;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.raviolini.aspects.io.configuration.exceptions.UnloadableConfigException;
public class FileConfigDriver extends AbstractConfigDriver {
private String fileName;
private InputStream file;
private Properties properties;
public FileConfigDriver() {
this.fileName = "application.properties";
}
public FileConfigDriver(String fileName) {
this.fileName = fileName;
}
private InputStream getFile() {
if (file == null) {
file = getClass().getClassLoader().getResourceAsStream(fileName);
}
return file;
}
private Properties getProperties() throws IOException, NullPointerException {
if (properties == null) {
properties = new Properties();
properties.load(getFile());
getFile().close();
}
return properties;
}
private Map<String, String> loadMap(String namespace, String[] keys, Properties properties) {
Map<String, String> map = new HashMap<>();
for (String key : keys) {
map.put(key, properties.getProperty(namespace + key));
}
return map;
}
@Override
protected Map<String, String> loadMap(String namespace, String[] keys) throws UnloadableConfigException {
try {
return loadMap(namespace, keys, getProperties());
} catch (NullPointerException | IOException e) {
throw new UnloadableConfigException(e);
}
}
@Override
public Boolean isActive() {
return getFile() != null;
}
} | UTF-8 | Java | 1,824 | java | FileConfigDriver.java | Java | [] | null | [] | package org.raviolini.aspects.io.configuration.drivers;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.raviolini.aspects.io.configuration.exceptions.UnloadableConfigException;
public class FileConfigDriver extends AbstractConfigDriver {
private String fileName;
private InputStream file;
private Properties properties;
public FileConfigDriver() {
this.fileName = "application.properties";
}
public FileConfigDriver(String fileName) {
this.fileName = fileName;
}
private InputStream getFile() {
if (file == null) {
file = getClass().getClassLoader().getResourceAsStream(fileName);
}
return file;
}
private Properties getProperties() throws IOException, NullPointerException {
if (properties == null) {
properties = new Properties();
properties.load(getFile());
getFile().close();
}
return properties;
}
private Map<String, String> loadMap(String namespace, String[] keys, Properties properties) {
Map<String, String> map = new HashMap<>();
for (String key : keys) {
map.put(key, properties.getProperty(namespace + key));
}
return map;
}
@Override
protected Map<String, String> loadMap(String namespace, String[] keys) throws UnloadableConfigException {
try {
return loadMap(namespace, keys, getProperties());
} catch (NullPointerException | IOException e) {
throw new UnloadableConfigException(e);
}
}
@Override
public Boolean isActive() {
return getFile() != null;
}
} | 1,824 | 0.626096 | 0.626096 | 66 | 26.651516 | 25.389984 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.530303 | false | false | 11 |
871a31120a1c9ef7e8cb0f8e856bf630984625ef | 34,668,976,035,354 | 6f4ea0e43b59312463a700761d04831a5d128259 | /src/main/java/com/rgs/effectivejava/entity/section3/InstrumentedHashSet.java | 0e525862e48538c4f5cc90e5b4c3504b7f58da1f | [] | no_license | Lunzqd/EffectiveJava | https://github.com/Lunzqd/EffectiveJava | 8dbd350a3eed02dc878f015ad3f812a8da6161b0 | 4e0d6cb45760e067fe1990e29c55d06793343c79 | refs/heads/master | 2022-10-12T20:59:47.407000 | 2019-12-04T09:16:27 | 2019-12-04T09:16:27 | 219,404,020 | 0 | 1 | null | false | 2022-09-01T23:15:20 | 2019-11-04T02:49:32 | 2019-12-04T09:16:31 | 2022-09-01T23:15:18 | 1,557 | 0 | 1 | 4 | Java | false | false | package com.rgs.effectivejava.entity.section3;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.util.Collection;
import java.util.HashSet;
/**
* 重写一个HashSet,计算从创立对象到现在为止,有多少元素被添加过
* addedCount!=set.size()
* @param <E>
*/
@Data
public class InstrumentedHashSet<E> extends HashSet<E> {
@Setter(AccessLevel.PRIVATE)
private Integer addedCount=0;
public InstrumentedHashSet(){super();}
public InstrumentedHashSet(int initCap, float loadFactor){
super(initCap,loadFactor);
}
@Override
public boolean add(E e) {
this.addedCount++;
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends E> c) {
this.addedCount+=c.size();
return super.addAll(c);
}
}
| UTF-8 | Java | 873 | java | InstrumentedHashSet.java | Java | [] | null | [] | package com.rgs.effectivejava.entity.section3;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.util.Collection;
import java.util.HashSet;
/**
* 重写一个HashSet,计算从创立对象到现在为止,有多少元素被添加过
* addedCount!=set.size()
* @param <E>
*/
@Data
public class InstrumentedHashSet<E> extends HashSet<E> {
@Setter(AccessLevel.PRIVATE)
private Integer addedCount=0;
public InstrumentedHashSet(){super();}
public InstrumentedHashSet(int initCap, float loadFactor){
super(initCap,loadFactor);
}
@Override
public boolean add(E e) {
this.addedCount++;
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends E> c) {
this.addedCount+=c.size();
return super.addAll(c);
}
}
| 873 | 0.678091 | 0.675643 | 42 | 18.452381 | 17.667837 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false | 11 |
04fc87e50c98b2aa3320c71fb2e257f795488bed | 31,129,922,991,890 | 3d6d99a83fee97d85395475a79823e90848a5e31 | /Calculator.java | 9097a91e0cf94b40e8c3cf296abd6c5362b09ee5 | [] | no_license | mclarsson/inlupp4 | https://github.com/mclarsson/inlupp4 | 9182f36c8f473af064467992e4b9420cd272a98f | f23d8fc9fcda61ccfa89e9c3aa8367f620dc4521 | refs/heads/master | 2021-08-23T09:25:43.440000 | 2017-12-04T13:41:20 | 2017-12-04T13:41:20 | 111,679,353 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.IOException;
import java.util.*;
public class Calculator {
/**
* Main function for the program. Starts the calculator and initializes a new parser.
* Throws exceptions when necessary.
*
*/
public static void main(String[] args){
Parser p = new Parser();
Sexpr expr;
HashMap<String, Sexpr> variables = new HashMap<String, Sexpr>();
System.out.println("Welcome to the parser!\n");
System.out.println("Enter \"q\" to exit at any point.");
while (true) {
System.out.print("\n? ");
try {
expr = p.expression();
if (expr.isVars()) {
for (String key : variables.keySet()) {
System.out.println(key + " = " + variables.get(key));
}
} else if (expr.isQuit()){
return;
} else {
System.out.println("input: " + expr);
System.out.println("result: " + expr.eval(variables));
variables.put("ans", expr.eval(variables));
}
} catch (SyntaxErrorException e) {
p.flush();
System.out.print("Syntax Error: ");
System.out.println(e.getMessage());
} catch (IOException e) {
p.flush();
System.err.println("IO Exception!");
}
}
}
}
| UTF-8 | Java | 1,301 | java | Calculator.java | Java | [] | null | [] |
import java.io.IOException;
import java.util.*;
public class Calculator {
/**
* Main function for the program. Starts the calculator and initializes a new parser.
* Throws exceptions when necessary.
*
*/
public static void main(String[] args){
Parser p = new Parser();
Sexpr expr;
HashMap<String, Sexpr> variables = new HashMap<String, Sexpr>();
System.out.println("Welcome to the parser!\n");
System.out.println("Enter \"q\" to exit at any point.");
while (true) {
System.out.print("\n? ");
try {
expr = p.expression();
if (expr.isVars()) {
for (String key : variables.keySet()) {
System.out.println(key + " = " + variables.get(key));
}
} else if (expr.isQuit()){
return;
} else {
System.out.println("input: " + expr);
System.out.println("result: " + expr.eval(variables));
variables.put("ans", expr.eval(variables));
}
} catch (SyntaxErrorException e) {
p.flush();
System.out.print("Syntax Error: ");
System.out.println(e.getMessage());
} catch (IOException e) {
p.flush();
System.err.println("IO Exception!");
}
}
}
}
| 1,301 | 0.539585 | 0.539585 | 48 | 26.0625 | 22.804792 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 11 |
86e3f440f70b139bec78b1057404671adc0f5255 | 35,536,559,419,659 | 01b06873d4bbae8604580c883c62e6360761634d | /src/main/java/scotch/compiler/ast/InstanceMembersNode.java | 1ea297889b6fee1653d6a7e1c7e7b3837e351a77 | [] | no_license | amukiza/scotch-lang | https://github.com/amukiza/scotch-lang | a2ef03498bf7dae78512d9e4e7aae34066e6cacd | 10ab960e4189c3c06e5d41ab23c43cee1fbe5827 | refs/heads/master | 2021-01-14T08:57:09.837000 | 2015-04-28T16:55:33 | 2015-04-28T16:55:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package scotch.compiler.ast;
import java.util.List;
import com.google.common.collect.ImmutableList;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import scotch.compiler.text.SourceLocation;
@EqualsAndHashCode(callSuper = false)
@ToString(exclude = "sourceLocation")
public class InstanceMembersNode extends AstNode {
@Getter
private final SourceLocation sourceLocation;
private final AstNode openCurly;
private final List<AstNode> instanceMembers;
private final AstNode closeCurly;
public InstanceMembersNode(SourceLocation sourceLocation, AstNode openCurly, List<AstNode> instanceMembers, AstNode closeCurly) {
this.sourceLocation = sourceLocation;
this.openCurly = openCurly;
this.instanceMembers = ImmutableList.copyOf(instanceMembers);
this.closeCurly = closeCurly;
}
@Override
public <T> T accept(AstNodeVisitor<T> visitor) {
return visitor.visitInstanceMembersNode(this);
}
}
| UTF-8 | Java | 1,015 | java | InstanceMembersNode.java | Java | [] | null | [] | package scotch.compiler.ast;
import java.util.List;
import com.google.common.collect.ImmutableList;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import scotch.compiler.text.SourceLocation;
@EqualsAndHashCode(callSuper = false)
@ToString(exclude = "sourceLocation")
public class InstanceMembersNode extends AstNode {
@Getter
private final SourceLocation sourceLocation;
private final AstNode openCurly;
private final List<AstNode> instanceMembers;
private final AstNode closeCurly;
public InstanceMembersNode(SourceLocation sourceLocation, AstNode openCurly, List<AstNode> instanceMembers, AstNode closeCurly) {
this.sourceLocation = sourceLocation;
this.openCurly = openCurly;
this.instanceMembers = ImmutableList.copyOf(instanceMembers);
this.closeCurly = closeCurly;
}
@Override
public <T> T accept(AstNodeVisitor<T> visitor) {
return visitor.visitInstanceMembersNode(this);
}
}
| 1,015 | 0.749754 | 0.749754 | 31 | 31.741936 | 27.145924 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612903 | false | false | 11 |
692c2d015a0c94af45da8c613437ae0082f0623d | 5,042,291,613,259 | 3bd2c6ad5376148f66d3d7521b648c04ea7870b1 | /src/main/java/csata/jatek/harc/TaborBarmi.java | 226ec0576783fc7bfd5f229d3767591e6cf2f6ca | [] | no_license | oaron/Projekteszkozok | https://github.com/oaron/Projekteszkozok | 31cb06e60a65dffca6085fb3e105dd610c539005 | 791674c2cd4ba6d4d59e2543b33249df79532b16 | refs/heads/master | 2020-12-31T04:56:11.548000 | 2016-05-23T16:08:05 | 2016-05-23T16:08:05 | 56,449,907 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package csata.jatek.harc;
import csata.jatek.HarcInterface;
import csata.jatek.Jatekos;
import csata.jatek.szereplo.Tabor;
/**
*
* Tabor bármilyen játékossal valo harcat reprezentalo osztaly.
* A tabor nem tud vedekezni.
*
*/
public class TaborBarmi implements HarcInterface {
@Override
public Class getJatekosTipus1() {
return Tabor.class;
}
@Override
public Class getJatekosTipus2() {
return Jatekos.class;
}
@Override
public Jatekos csataz(Jatekos tabor, Jatekos barmi) {
// a tabor nem tud vedekezni
return tabor;
}
}
| ISO-8859-2 | Java | 553 | java | TaborBarmi.java | Java | [] | null | [] | package csata.jatek.harc;
import csata.jatek.HarcInterface;
import csata.jatek.Jatekos;
import csata.jatek.szereplo.Tabor;
/**
*
* Tabor bármilyen játékossal valo harcat reprezentalo osztaly.
* A tabor nem tud vedekezni.
*
*/
public class TaborBarmi implements HarcInterface {
@Override
public Class getJatekosTipus1() {
return Tabor.class;
}
@Override
public Class getJatekosTipus2() {
return Jatekos.class;
}
@Override
public Jatekos csataz(Jatekos tabor, Jatekos barmi) {
// a tabor nem tud vedekezni
return tabor;
}
}
| 553 | 0.74 | 0.736364 | 30 | 17.333334 | 17.853727 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 11 |
41c5cd0a7a1b43a3c942e9dbd6050a5e06bd7b30 | 33,251,636,820,426 | ef4b1e99cc8f010f5eccf63445192967ac963e18 | /src/main/java/com/noaa/nema/viewer/service/impl/CommonServiceImpl.java | d7b5a18de442237f796c972076b8b3fddae481f1 | [] | no_license | kyr6886/advis | https://github.com/kyr6886/advis | 9c71d583fb2ea2746d6c689b742184932b040b47 | ed0841d3c18035b639932ded35c2a9195820fa9e | refs/heads/master | 2022-12-14T09:22:01.760000 | 2020-01-13T06:14:56 | 2020-01-13T06:14:56 | 233,521,972 | 0 | 0 | null | false | 2022-12-10T14:42:22 | 2020-01-13T05:56:21 | 2020-01-13T06:15:30 | 2022-12-10T14:42:21 | 28,428 | 0 | 0 | 17 | JavaScript | false | false | package com.noaa.nema.viewer.service.impl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.noaa.nema.viewer.area.dao.SectorDamageModel;
import com.noaa.nema.viewer.area.dao.YearAreaCodeDto;
import com.noaa.nema.viewer.area.service.IAreaCodeService;
import com.noaa.nema.viewer.base.ViewerSysKeyword;
import com.noaa.nema.viewer.service.ICommonService;
import com.noaa.nema.viewer.year.dme.dao.ICommonDataDao;
import com.noaa.nema.viewer.year.dme.dao.YearDmeDto;
import com.noaa.nema.viewer.year.dme.dao.YearDmePbmDto;
import com.noaa.nema.viewer.year.dme.dao.YearDmePubDto;
@Service("commonService")
public class CommonServiceImpl implements ICommonService {
@Autowired
private ICommonDataDao commonDataDao;
@Autowired
private IAreaCodeService areaCodeService;
@Override
public int countThissen(String paramSiguguCode) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSiguguCode.substring(0, 2));
return commonDataDao.countThissen(paramMap);
}
@Override
public List<YearDmeDto> listDmeWithGungu(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
//paramMap.put("damage_code", paramDemCode);
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.listDmeWithGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
//paramMap.put("damage_code", paramDemCode);
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.listDmeWithGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.listDmeWithGunguByArea(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.listDmeWithGunguByArea(paramMap);
}
return rs;
}
@Override
public List<SectorDamageModel> listRainDemSector(List<YearDmeDto> paramList) {
List<SectorDamageModel> rs = new ArrayList<SectorDamageModel>();
for (int i = 0; i < 4; i++) {
SectorDamageModel temp = new SectorDamageModel();
if (i == 0) {
temp.setSector(ViewerSysKeyword.RAIN_SECTION_ST_1);
temp.setEndSector(ViewerSysKeyword.RAIN_SECTION_ST_2 - 1);
}
if (i == 1) {
temp.setSector(ViewerSysKeyword.RAIN_SECTION_ST_2);
temp.setEndSector(ViewerSysKeyword.RAIN_SECTION_ST_3 - 1);
}
if (i == 2) {
temp.setSector(ViewerSysKeyword.RAIN_SECTION_ST_3);
temp.setEndSector(ViewerSysKeyword.RAIN_SECTION_ST_4 - 1);
}
if (i == 3) {
temp.setSector(ViewerSysKeyword.RAIN_SECTION_ST_4);
temp.setEndSector(99999);
}
rs.add(temp);
}
for (SectorDamageModel sectorDamageModel : rs) {
sectorDamageModel.setListDmePbm(new ArrayList<YearDmeDto>());
sectorDamageModel.setListDmePub(new ArrayList<YearDmeDto>());
sectorDamageModel.setListDmePerson(new ArrayList<YearDmeDto>());
sectorDamageModel.setCountDamage(paramList.size());
for (YearDmeDto yearDmeDto : paramList) {
if (yearDmeDto.getRn_day() >= sectorDamageModel.getSector()
&& yearDmeDto.getRn_day() <= sectorDamageModel.getEndSector()) {
if (yearDmeDto.getCom_dme() > 0) {
sectorDamageModel.getListDmePerson().add(yearDmeDto);
sectorDamageModel
.setTotalDmePerson(sectorDamageModel.getTotalDmePerson() + yearDmeDto.getCom_dme());
}
if (yearDmeDto.getPub_total() > 0) {
sectorDamageModel.getListDmePub().add(yearDmeDto);
sectorDamageModel
.setTotalDmePub(sectorDamageModel.getTotalDmePub() + yearDmeDto.getPub_total());
}
if ((yearDmeDto.getPri_total() + yearDmeDto.getCom_total()) > 0) {
sectorDamageModel.getListDmePbm().add(yearDmeDto);
sectorDamageModel.setTotalDmePbm(sectorDamageModel.getTotalDmePbm() + yearDmeDto.getPri_total()
+ yearDmeDto.getCom_total());
}
}
}
sectorDamageModel.setCountPerson(sectorDamageModel.getListDmePerson().size());
sectorDamageModel.setCountPublic(sectorDamageModel.getListDmePub().size());
sectorDamageModel.setCountPrivate(sectorDamageModel.getListDmePbm().size());
createGroupCount(sectorDamageModel);
sectorDamageModel.setListDmePerson(createGroupPersonSum(sectorDamageModel.getListDmePerson()));
sectorDamageModel.setListDmePub(createGroupPublicSum(sectorDamageModel.getListDmePub()));
sectorDamageModel.setListDmePbm(createGroupPrivateSum(sectorDamageModel.getListDmePbm()));
}
return rs;
}
private void createGroupCount(SectorDamageModel paramTarget) {
HashMap<String, String> damageArea = new HashMap<String, String>();
for (YearDmeDto yearDmeDto : paramTarget.getListDmePub()) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
for (YearDmeDto yearDmeDto : paramTarget.getListDmePbm()) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
for (YearDmeDto yearDmeDto : paramTarget.getListDmePerson()) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
paramTarget.setDamageAreaCount(damageArea.size());
}
private List<YearDmeDto> createGroupPersonSum(List<YearDmeDto> paramTarget) {
HashMap<String, String> damageArea = new HashMap<String, String>();
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
for (YearDmeDto yearDmeDto : paramTarget) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
for (Map.Entry<String, String> entry : damageArea.entrySet()) {
String _key = entry.getKey();
YearDmeDto temp = new YearDmeDto();
for (YearDmeDto yearDmeDto : paramTarget) {
if (_key.equals(yearDmeDto.getSigungu_code())) {
temp.setSido(yearDmeDto.getSido());
temp.setSigungu(yearDmeDto.getSigungu());
temp.setCount(temp.getCount() + 1);
temp.setCom_dme(temp.getCom_dme() + yearDmeDto.getCom_dme());
}
}
rs.add(temp);
}
return rs;
}
private List<YearDmeDto> createGroupPublicSum(List<YearDmeDto> paramTarget) {
HashMap<String, String> damageArea = new HashMap<String, String>();
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
for (YearDmeDto yearDmeDto : paramTarget) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
for (Map.Entry<String, String> entry : damageArea.entrySet()) {
String _key = entry.getKey();
YearDmeDto temp = new YearDmeDto();
for (YearDmeDto yearDmeDto : paramTarget) {
if (_key.equals(yearDmeDto.getSigungu_code())) {
temp.setSido(yearDmeDto.getSido());
temp.setSigungu(yearDmeDto.getSigungu());
temp.setCount(temp.getCount() + 1);
temp.setPub_total(temp.getPub_total() + yearDmeDto.getPub_total());
}
}
rs.add(temp);
}
return rs;
}
private List<YearDmeDto> createGroupPrivateSum(List<YearDmeDto> paramTarget) {
HashMap<String, String> damageArea = new HashMap<String, String>();
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
for (YearDmeDto yearDmeDto : paramTarget) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
for (Map.Entry<String, String> entry : damageArea.entrySet()) {
String _key = entry.getKey();
YearDmeDto temp = new YearDmeDto();
for (YearDmeDto yearDmeDto : paramTarget) {
if (_key.equals(yearDmeDto.getSigungu_code())) {
temp.setSido(yearDmeDto.getSido());
temp.setSigungu(yearDmeDto.getSigungu());
temp.setCount(temp.getCount() + 1);
temp.setPri_total(temp.getPri_total() + yearDmeDto.getPri_total());
temp.setCom_total(temp.getCom_total() + yearDmeDto.getCom_total());
}
}
rs.add(temp);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(List<String> paramGunguCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramGunguCode != null && paramGunguCode.size() > 0) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("gunguCodes", paramGunguCode);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.sumDamageByGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(List<String> paramGunguCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramGunguCode != null && paramGunguCode.size() > 0) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("gunguCodes", paramGunguCode);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.sumDamageByGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(List<String> paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramSidoCode != null && paramSidoCode.size() > 0) {
for (String sido : paramSidoCode) {
int _countThissen = countThissen(sido);
String lawAreaYn = thissenLawAreaYn(sido);
if(lawAreaYn==null){
lawAreaYn=thissenLawAreaYn(sido.substring(0,2));
}
if (paramDemCode.equals(ViewerSysKeyword.DME_CODE_RAIN)) {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(rs.size(), listDmeWithGunguByArea(sido, paramStDate, paramEndDate,ViewerSysKeyword.DME_CODE_RAIN));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, ViewerSysKeyword.DME_CODE_RAIN));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,ViewerSysKeyword.DME_CODE_RAIN));
}
} else {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, paramDemCode));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode));
}
}
}
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(List<String> paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramSidoCode != null && paramSidoCode.size() > 0) {
for (String sido : paramSidoCode) {
int _countThissen = countThissen(sido);
String lawAreaYn = thissenLawAreaYn(sido);
if(lawAreaYn==null){
lawAreaYn=thissenLawAreaYn(sido.substring(0,2));
}
if (paramDemCode.equals(ViewerSysKeyword.DME_CODE_RAIN)) {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramStRainValue, paramEndRainValue));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, ViewerSysKeyword.DME_CODE_RAIN,
paramStRainValue, paramEndRainValue));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramStRainValue, paramEndRainValue));
}
} else {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode,
paramStRainValue, paramEndRainValue));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, paramDemCode, paramStRainValue,
paramEndRainValue));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode,
paramStRainValue, paramEndRainValue));
}
}
}
}
return rs;
}
@Override
public List<YearDmeDto> listDmeHisWithGungu(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramStDate.length() >= 4
&& paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.length() < 5 ? paramSidoCode : paramSidoCode.substring(0, 5));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
if (paramDemCode != null) {
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.listDmeHisWithGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeHisWithGunguByArea(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramStDate.length() >= 4
&& paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("sido_code", paramSidoCode.substring(0, 2));
paramMap.put("law_code", paramSidoCode.length() < 5 ? paramSidoCode : paramSidoCode.substring(0, 5));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
if (paramDemCode != null) {
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.listDmeHisWithGunguByArea(paramMap);
}
return rs;
}
@Override
public YearDmeDto totalDamage(String paramSigungu, String paramStDate, String paramEndDate, String paramDemCode) {
YearDmeDto rs = null;
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSigungu.substring(0, 5));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.totalDamage(paramMap);
return rs;
}
@Override
public String thissenLawAreaYn(String paramGungu) {
HashMap<String, Object> paramMap = new HashMap<>();
String paramReGungu = (paramGungu.substring(0, 2).equals(ViewerSysKeyword.RAIN_JEJU_SIDO_AREA))
? ViewerSysKeyword.RAIN_JEJU_GUNGU_AREA : paramGungu;
paramMap.put("law_code", paramReGungu);
return commonDataDao.lookingLawArea(paramMap);
}
@Override
public YearDmeDto maxDamagePerson(String paramSigungu, String paramStDate, String paramEndDate,
String paramDemCode) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSigungu);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
return commonDataDao.maxDamagePersonByYear(paramMap);
}
@Override
public YearDmeDto maxDamageMoney(String paramSigungu, String paramStDate, String paramEndDate,
String paramDemCode) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSigungu);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
return commonDataDao.maxDamageMoneyByYear(paramMap);
}
@Override
public List<YearDmeDto> listDamagePersonTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
return commonDataDao.listDamagePersonTop10(paramMap);
}
@Override
public List<YearDmeDto> listDamageMoneyTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
return commonDataDao.listDamageMoneyTop10(paramMap);
}
@Override
public List<YearDmeDto> listDamageMoneyTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue, String paramDamgeName) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamgeName);
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
return commonDataDao.listDamageMoneyTop10(paramMap);
}
@Override
public List<YearDmeDto> listDamageMoneyTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
return commonDataDao.listDamageMoneyTop10(paramMap);
}
@Override
public List<YearDmeDto> listGunguDamageCause(String paramSido, String paramStDate, String paramEndDate) {
SimpleDateFormat prev_df = new SimpleDateFormat("yyyyMMdd");
Calendar cal_prev_month = Calendar.getInstance();
try {
cal_prev_month.setTime(prev_df.parse(paramStDate));
} catch (ParseException e1) {
e1.printStackTrace();
}
cal_prev_month.add(Calendar.DATE, -1);
String paramNewStDate = prev_df.format(cal_prev_month.getTime());
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido);
paramMap.put("beg_date", paramNewStDate);
paramMap.put("end_date", paramEndDate);
return commonDataDao.listGunguDmeCause(paramMap);
}
@Override
public List<YearDmeDto> listGunguDamageCauseResultSum(String paramSido, String paramStDate, String paramEndDate) {
SimpleDateFormat prev_df = new SimpleDateFormat("yyyyMMdd");
Calendar cal_prev_month = Calendar.getInstance();
try {
cal_prev_month.setTime(prev_df.parse(paramStDate));
} catch (ParseException e1) {
e1.printStackTrace();
}
cal_prev_month.add(Calendar.DATE, -1);
String paramNewStDate = prev_df.format(cal_prev_month.getTime());
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido);
paramMap.put("beg_date", paramNewStDate);
paramMap.put("end_date", paramEndDate);
return commonDataDao.listGunguDmeCauseResultSum(paramMap);
}
@Override
public YearDmeDto detailSummary(String paramStDate, String paramEndDate, String paramDmeCode) {
HashMap<String, Object> paramMap = new HashMap<>();
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDmeCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDmeCode);
}
return commonDataDao.detailSummary(paramMap);
}
@Override
public List<YearDmeDto> listDamagePersonTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
return commonDataDao.listDamagePersonTop10(paramMap);
}
@Override
public List<YearDmeDto> listDamageMoneyTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
return commonDataDao.listDamageMoneyTop10(paramMap);
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
rs = commonDataDao.listDmeWithGunguByArea(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue, String paramDamageName) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.listDmeWithGunguByArea(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(List<String> paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramSidoCode != null && paramSidoCode.size() > 0) {
for (String sido : paramSidoCode) {
int _countThissen = countThissen(sido);
String lawAreaYn = thissenLawAreaYn(sido);
if (paramDemCode.equals(ViewerSysKeyword.DME_CODE_RAIN)) {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramDamageName));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, ViewerSysKeyword.DME_CODE_RAIN,
paramDamageName));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramDamageName));
}
} else {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode,
paramDamageName));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, paramDemCode, paramDamageName));
}
} else {
rs.addAll(
listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode, paramDamageName));
}
}
}
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(List<String> paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue, String paramDamageName) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramSidoCode != null && paramSidoCode.size() > 0) {
for (String sido : paramSidoCode) {
int _countThissen = countThissen(sido);
String lawAreaYn = thissenLawAreaYn(sido);
if (paramDemCode.equals(ViewerSysKeyword.DME_CODE_RAIN)) {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramDamageName));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, ViewerSysKeyword.DME_CODE_RAIN,
paramDamageName));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramDamageName));
}
} else {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode,
paramDamageName));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, paramDemCode, paramDamageName));
}
} else {
rs.addAll(
listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode, paramDamageName));
}
}
}
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
paramMap.put("damage_code", paramDemCode);
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
rs = commonDataDao.listDmeWithGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue, String paramDamageName) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
paramMap.put("damage_code", paramDemCode);
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.listDmeWithGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(List<String> paramGunguCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramGunguCode != null && paramGunguCode.size() > 0) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("gunguCodes", paramGunguCode);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
rs = commonDataDao.sumDamageByGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(List<String> paramGunguCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue, String paramDamageName) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramGunguCode != null && paramGunguCode.size() > 0) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("gunguCodes", paramGunguCode);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.sumDamageByGungu(paramMap);
}
return rs;
}
}
| UTF-8 | Java | 39,960 | java | CommonServiceImpl.java | Java | [] | null | [] | package com.noaa.nema.viewer.service.impl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.noaa.nema.viewer.area.dao.SectorDamageModel;
import com.noaa.nema.viewer.area.dao.YearAreaCodeDto;
import com.noaa.nema.viewer.area.service.IAreaCodeService;
import com.noaa.nema.viewer.base.ViewerSysKeyword;
import com.noaa.nema.viewer.service.ICommonService;
import com.noaa.nema.viewer.year.dme.dao.ICommonDataDao;
import com.noaa.nema.viewer.year.dme.dao.YearDmeDto;
import com.noaa.nema.viewer.year.dme.dao.YearDmePbmDto;
import com.noaa.nema.viewer.year.dme.dao.YearDmePubDto;
@Service("commonService")
public class CommonServiceImpl implements ICommonService {
@Autowired
private ICommonDataDao commonDataDao;
@Autowired
private IAreaCodeService areaCodeService;
@Override
public int countThissen(String paramSiguguCode) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSiguguCode.substring(0, 2));
return commonDataDao.countThissen(paramMap);
}
@Override
public List<YearDmeDto> listDmeWithGungu(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
//paramMap.put("damage_code", paramDemCode);
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.listDmeWithGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
//paramMap.put("damage_code", paramDemCode);
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.listDmeWithGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.listDmeWithGunguByArea(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.listDmeWithGunguByArea(paramMap);
}
return rs;
}
@Override
public List<SectorDamageModel> listRainDemSector(List<YearDmeDto> paramList) {
List<SectorDamageModel> rs = new ArrayList<SectorDamageModel>();
for (int i = 0; i < 4; i++) {
SectorDamageModel temp = new SectorDamageModel();
if (i == 0) {
temp.setSector(ViewerSysKeyword.RAIN_SECTION_ST_1);
temp.setEndSector(ViewerSysKeyword.RAIN_SECTION_ST_2 - 1);
}
if (i == 1) {
temp.setSector(ViewerSysKeyword.RAIN_SECTION_ST_2);
temp.setEndSector(ViewerSysKeyword.RAIN_SECTION_ST_3 - 1);
}
if (i == 2) {
temp.setSector(ViewerSysKeyword.RAIN_SECTION_ST_3);
temp.setEndSector(ViewerSysKeyword.RAIN_SECTION_ST_4 - 1);
}
if (i == 3) {
temp.setSector(ViewerSysKeyword.RAIN_SECTION_ST_4);
temp.setEndSector(99999);
}
rs.add(temp);
}
for (SectorDamageModel sectorDamageModel : rs) {
sectorDamageModel.setListDmePbm(new ArrayList<YearDmeDto>());
sectorDamageModel.setListDmePub(new ArrayList<YearDmeDto>());
sectorDamageModel.setListDmePerson(new ArrayList<YearDmeDto>());
sectorDamageModel.setCountDamage(paramList.size());
for (YearDmeDto yearDmeDto : paramList) {
if (yearDmeDto.getRn_day() >= sectorDamageModel.getSector()
&& yearDmeDto.getRn_day() <= sectorDamageModel.getEndSector()) {
if (yearDmeDto.getCom_dme() > 0) {
sectorDamageModel.getListDmePerson().add(yearDmeDto);
sectorDamageModel
.setTotalDmePerson(sectorDamageModel.getTotalDmePerson() + yearDmeDto.getCom_dme());
}
if (yearDmeDto.getPub_total() > 0) {
sectorDamageModel.getListDmePub().add(yearDmeDto);
sectorDamageModel
.setTotalDmePub(sectorDamageModel.getTotalDmePub() + yearDmeDto.getPub_total());
}
if ((yearDmeDto.getPri_total() + yearDmeDto.getCom_total()) > 0) {
sectorDamageModel.getListDmePbm().add(yearDmeDto);
sectorDamageModel.setTotalDmePbm(sectorDamageModel.getTotalDmePbm() + yearDmeDto.getPri_total()
+ yearDmeDto.getCom_total());
}
}
}
sectorDamageModel.setCountPerson(sectorDamageModel.getListDmePerson().size());
sectorDamageModel.setCountPublic(sectorDamageModel.getListDmePub().size());
sectorDamageModel.setCountPrivate(sectorDamageModel.getListDmePbm().size());
createGroupCount(sectorDamageModel);
sectorDamageModel.setListDmePerson(createGroupPersonSum(sectorDamageModel.getListDmePerson()));
sectorDamageModel.setListDmePub(createGroupPublicSum(sectorDamageModel.getListDmePub()));
sectorDamageModel.setListDmePbm(createGroupPrivateSum(sectorDamageModel.getListDmePbm()));
}
return rs;
}
private void createGroupCount(SectorDamageModel paramTarget) {
HashMap<String, String> damageArea = new HashMap<String, String>();
for (YearDmeDto yearDmeDto : paramTarget.getListDmePub()) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
for (YearDmeDto yearDmeDto : paramTarget.getListDmePbm()) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
for (YearDmeDto yearDmeDto : paramTarget.getListDmePerson()) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
paramTarget.setDamageAreaCount(damageArea.size());
}
private List<YearDmeDto> createGroupPersonSum(List<YearDmeDto> paramTarget) {
HashMap<String, String> damageArea = new HashMap<String, String>();
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
for (YearDmeDto yearDmeDto : paramTarget) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
for (Map.Entry<String, String> entry : damageArea.entrySet()) {
String _key = entry.getKey();
YearDmeDto temp = new YearDmeDto();
for (YearDmeDto yearDmeDto : paramTarget) {
if (_key.equals(yearDmeDto.getSigungu_code())) {
temp.setSido(yearDmeDto.getSido());
temp.setSigungu(yearDmeDto.getSigungu());
temp.setCount(temp.getCount() + 1);
temp.setCom_dme(temp.getCom_dme() + yearDmeDto.getCom_dme());
}
}
rs.add(temp);
}
return rs;
}
private List<YearDmeDto> createGroupPublicSum(List<YearDmeDto> paramTarget) {
HashMap<String, String> damageArea = new HashMap<String, String>();
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
for (YearDmeDto yearDmeDto : paramTarget) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
for (Map.Entry<String, String> entry : damageArea.entrySet()) {
String _key = entry.getKey();
YearDmeDto temp = new YearDmeDto();
for (YearDmeDto yearDmeDto : paramTarget) {
if (_key.equals(yearDmeDto.getSigungu_code())) {
temp.setSido(yearDmeDto.getSido());
temp.setSigungu(yearDmeDto.getSigungu());
temp.setCount(temp.getCount() + 1);
temp.setPub_total(temp.getPub_total() + yearDmeDto.getPub_total());
}
}
rs.add(temp);
}
return rs;
}
private List<YearDmeDto> createGroupPrivateSum(List<YearDmeDto> paramTarget) {
HashMap<String, String> damageArea = new HashMap<String, String>();
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
for (YearDmeDto yearDmeDto : paramTarget) {
damageArea.put(yearDmeDto.getSigungu_code(), "");
}
for (Map.Entry<String, String> entry : damageArea.entrySet()) {
String _key = entry.getKey();
YearDmeDto temp = new YearDmeDto();
for (YearDmeDto yearDmeDto : paramTarget) {
if (_key.equals(yearDmeDto.getSigungu_code())) {
temp.setSido(yearDmeDto.getSido());
temp.setSigungu(yearDmeDto.getSigungu());
temp.setCount(temp.getCount() + 1);
temp.setPri_total(temp.getPri_total() + yearDmeDto.getPri_total());
temp.setCom_total(temp.getCom_total() + yearDmeDto.getCom_total());
}
}
rs.add(temp);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(List<String> paramGunguCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramGunguCode != null && paramGunguCode.size() > 0) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("gunguCodes", paramGunguCode);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.sumDamageByGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(List<String> paramGunguCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramGunguCode != null && paramGunguCode.size() > 0) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("gunguCodes", paramGunguCode);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.sumDamageByGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(List<String> paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramSidoCode != null && paramSidoCode.size() > 0) {
for (String sido : paramSidoCode) {
int _countThissen = countThissen(sido);
String lawAreaYn = thissenLawAreaYn(sido);
if(lawAreaYn==null){
lawAreaYn=thissenLawAreaYn(sido.substring(0,2));
}
if (paramDemCode.equals(ViewerSysKeyword.DME_CODE_RAIN)) {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(rs.size(), listDmeWithGunguByArea(sido, paramStDate, paramEndDate,ViewerSysKeyword.DME_CODE_RAIN));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, ViewerSysKeyword.DME_CODE_RAIN));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,ViewerSysKeyword.DME_CODE_RAIN));
}
} else {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, paramDemCode));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode));
}
}
}
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(List<String> paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramSidoCode != null && paramSidoCode.size() > 0) {
for (String sido : paramSidoCode) {
int _countThissen = countThissen(sido);
String lawAreaYn = thissenLawAreaYn(sido);
if(lawAreaYn==null){
lawAreaYn=thissenLawAreaYn(sido.substring(0,2));
}
if (paramDemCode.equals(ViewerSysKeyword.DME_CODE_RAIN)) {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramStRainValue, paramEndRainValue));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, ViewerSysKeyword.DME_CODE_RAIN,
paramStRainValue, paramEndRainValue));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramStRainValue, paramEndRainValue));
}
} else {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode,
paramStRainValue, paramEndRainValue));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, paramDemCode, paramStRainValue,
paramEndRainValue));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode,
paramStRainValue, paramEndRainValue));
}
}
}
}
return rs;
}
@Override
public List<YearDmeDto> listDmeHisWithGungu(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramStDate.length() >= 4
&& paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.length() < 5 ? paramSidoCode : paramSidoCode.substring(0, 5));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
if (paramDemCode != null) {
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.listDmeHisWithGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeHisWithGunguByArea(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramStDate.length() >= 4
&& paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("sido_code", paramSidoCode.substring(0, 2));
paramMap.put("law_code", paramSidoCode.length() < 5 ? paramSidoCode : paramSidoCode.substring(0, 5));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
if (paramDemCode != null) {
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.listDmeHisWithGunguByArea(paramMap);
}
return rs;
}
@Override
public YearDmeDto totalDamage(String paramSigungu, String paramStDate, String paramEndDate, String paramDemCode) {
YearDmeDto rs = null;
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSigungu.substring(0, 5));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
rs = commonDataDao.totalDamage(paramMap);
return rs;
}
@Override
public String thissenLawAreaYn(String paramGungu) {
HashMap<String, Object> paramMap = new HashMap<>();
String paramReGungu = (paramGungu.substring(0, 2).equals(ViewerSysKeyword.RAIN_JEJU_SIDO_AREA))
? ViewerSysKeyword.RAIN_JEJU_GUNGU_AREA : paramGungu;
paramMap.put("law_code", paramReGungu);
return commonDataDao.lookingLawArea(paramMap);
}
@Override
public YearDmeDto maxDamagePerson(String paramSigungu, String paramStDate, String paramEndDate,
String paramDemCode) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSigungu);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
return commonDataDao.maxDamagePersonByYear(paramMap);
}
@Override
public YearDmeDto maxDamageMoney(String paramSigungu, String paramStDate, String paramEndDate,
String paramDemCode) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSigungu);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
return commonDataDao.maxDamageMoneyByYear(paramMap);
}
@Override
public List<YearDmeDto> listDamagePersonTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
return commonDataDao.listDamagePersonTop10(paramMap);
}
@Override
public List<YearDmeDto> listDamageMoneyTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
return commonDataDao.listDamageMoneyTop10(paramMap);
}
@Override
public List<YearDmeDto> listDamageMoneyTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue, String paramDamgeName) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamgeName);
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
return commonDataDao.listDamageMoneyTop10(paramMap);
}
@Override
public List<YearDmeDto> listDamageMoneyTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
return commonDataDao.listDamageMoneyTop10(paramMap);
}
@Override
public List<YearDmeDto> listGunguDamageCause(String paramSido, String paramStDate, String paramEndDate) {
SimpleDateFormat prev_df = new SimpleDateFormat("yyyyMMdd");
Calendar cal_prev_month = Calendar.getInstance();
try {
cal_prev_month.setTime(prev_df.parse(paramStDate));
} catch (ParseException e1) {
e1.printStackTrace();
}
cal_prev_month.add(Calendar.DATE, -1);
String paramNewStDate = prev_df.format(cal_prev_month.getTime());
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido);
paramMap.put("beg_date", paramNewStDate);
paramMap.put("end_date", paramEndDate);
return commonDataDao.listGunguDmeCause(paramMap);
}
@Override
public List<YearDmeDto> listGunguDamageCauseResultSum(String paramSido, String paramStDate, String paramEndDate) {
SimpleDateFormat prev_df = new SimpleDateFormat("yyyyMMdd");
Calendar cal_prev_month = Calendar.getInstance();
try {
cal_prev_month.setTime(prev_df.parse(paramStDate));
} catch (ParseException e1) {
e1.printStackTrace();
}
cal_prev_month.add(Calendar.DATE, -1);
String paramNewStDate = prev_df.format(cal_prev_month.getTime());
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido);
paramMap.put("beg_date", paramNewStDate);
paramMap.put("end_date", paramEndDate);
return commonDataDao.listGunguDmeCauseResultSum(paramMap);
}
@Override
public YearDmeDto detailSummary(String paramStDate, String paramEndDate, String paramDmeCode) {
HashMap<String, Object> paramMap = new HashMap<>();
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDmeCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDmeCode);
}
return commonDataDao.detailSummary(paramMap);
}
@Override
public List<YearDmeDto> listDamagePersonTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
return commonDataDao.listDamagePersonTop10(paramMap);
}
@Override
public List<YearDmeDto> listDamageMoneyTop10(String paramSido, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("law_code", paramSido == null || paramSido.isEmpty() ? null : paramSido.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
return commonDataDao.listDamageMoneyTop10(paramMap);
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
rs = commonDataDao.listDmeWithGunguByArea(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue, String paramDamageName) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.listDmeWithGunguByArea(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(List<String> paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramSidoCode != null && paramSidoCode.size() > 0) {
for (String sido : paramSidoCode) {
int _countThissen = countThissen(sido);
String lawAreaYn = thissenLawAreaYn(sido);
if (paramDemCode.equals(ViewerSysKeyword.DME_CODE_RAIN)) {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramDamageName));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, ViewerSysKeyword.DME_CODE_RAIN,
paramDamageName));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramDamageName));
}
} else {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode,
paramDamageName));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, paramDemCode, paramDamageName));
}
} else {
rs.addAll(
listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode, paramDamageName));
}
}
}
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGunguByArea(List<String> paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue, String paramDamageName) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramSidoCode != null && paramSidoCode.size() > 0) {
for (String sido : paramSidoCode) {
int _countThissen = countThissen(sido);
String lawAreaYn = thissenLawAreaYn(sido);
if (paramDemCode.equals(ViewerSysKeyword.DME_CODE_RAIN)) {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramDamageName));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, ViewerSysKeyword.DME_CODE_RAIN,
paramDamageName));
}
} else {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate,
ViewerSysKeyword.DME_CODE_RAIN, paramDamageName));
}
} else {
if (_countThissen > 1) {
if (lawAreaYn == null || lawAreaYn.equals("Y")) {
rs.addAll(listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode,
paramDamageName));
} else {
rs.addAll(listDmeWithGungu(sido, paramStDate, paramEndDate, paramDemCode, paramDamageName));
}
} else {
rs.addAll(
listDmeWithGunguByArea(sido, paramStDate, paramEndDate, paramDemCode, paramDamageName));
}
}
}
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
paramMap.put("damage_code", paramDemCode);
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
rs = commonDataDao.listDmeWithGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(String paramSidoCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue, String paramDamageName) {
List<YearDmeDto> rs = null;
if (paramSidoCode != null && paramStDate != null && paramEndDate != null && paramSidoCode.length() >= 2
&& paramStDate.length() >= 4 && paramEndDate.length() >= 4) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("law_code", paramSidoCode.substring(0, 2));
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
paramMap.put("damage_code", paramDemCode);
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.listDmeWithGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(List<String> paramGunguCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramDamageName) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramGunguCode != null && paramGunguCode.size() > 0) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("gunguCodes", paramGunguCode);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("damage_info", paramDamageName);
rs = commonDataDao.sumDamageByGungu(paramMap);
}
return rs;
}
@Override
public List<YearDmeDto> listDmeWithGungu(List<String> paramGunguCode, String paramStDate, String paramEndDate,
String paramDemCode, String paramStRainValue, String paramEndRainValue, String paramDamageName) {
List<YearDmeDto> rs = new ArrayList<YearDmeDto>();
if (paramGunguCode != null && paramGunguCode.size() > 0) {
HashMap<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("gunguCodes", paramGunguCode);
if (paramStDate.length() == 8 && paramEndDate.length() == 8) {
paramMap.put("beg_date", paramStDate);
paramMap.put("end_date", paramEndDate);
} else {
paramMap.put("beg_date", paramStDate.substring(0, 4) + "0101");
paramMap.put("end_date", paramEndDate.substring(0, 4) + "1231");
}
String[] paramDemCodes = paramDemCode.split(",");
if (paramDemCodes.length > 1) {
paramMap.put("damage_codes", paramDemCodes);
} else {
paramMap.put("damage_code", paramDemCode);
}
paramMap.put("stRainValue", paramStRainValue);
paramMap.put("endRainValue", paramEndRainValue);
rs = commonDataDao.sumDamageByGungu(paramMap);
}
return rs;
}
}
| 39,960 | 0.694945 | 0.682257 | 1,055 | 36.876778 | 30.166269 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.69763 | false | false | 11 |
b616850a0615a59879bb29edcf898788501ef783 | 14,748,917,730,521 | b3b2380bd5872cd3075461f0a2e8539cb47c89aa | /elasticsearch-spring-boot-starter/src/main/java/com/digitalgd/dpd/elasticsearch/config/ElasticSearchUtil.java | 9c364629659dca875592a4173f2a7d3635b9596e | [
"Apache-2.0"
] | permissive | chenglinjava68/spring-boot-starters | https://github.com/chenglinjava68/spring-boot-starters | 025c1b381a86227922bec7889fd3628a9eef0f8e | 4ac0126ff96d18ef6885da05c9cfc64858d99aa9 | refs/heads/master | 2023-06-15T15:29:24.025000 | 2021-07-15T03:46:03 | 2021-07-15T03:46:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //package com.digitalgd.dpd.elasticsearch.config;
//
//import io.micrometer.core.instrument.util.StringUtils;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.http.HttpHost;
//import org.apache.http.auth.AuthScope;
//import org.apache.http.auth.UsernamePasswordCredentials;
//import org.apache.http.client.CredentialsProvider;
//import org.apache.http.impl.client.BasicCredentialsProvider;
//import org.elasticsearch.ElasticsearchException;
//import org.elasticsearch.action.DocWriteRequest;
//import org.elasticsearch.action.DocWriteResponse;
//import org.elasticsearch.action.bulk.BulkItemResponse;
//import org.elasticsearch.action.bulk.BulkItemResponse.Failure;
//import org.elasticsearch.action.bulk.BulkRequest;
//import org.elasticsearch.action.bulk.BulkResponse;
//import org.elasticsearch.action.delete.DeleteResponse;
//import org.elasticsearch.action.get.GetRequest;
//import org.elasticsearch.action.get.GetResponse;
//import org.elasticsearch.action.index.IndexRequest;
//import org.elasticsearch.action.index.IndexResponse;
//import org.elasticsearch.action.search.SearchRequest;
//import org.elasticsearch.action.search.SearchResponse;
//import org.elasticsearch.action.support.replication.ReplicationResponse;
//import org.elasticsearch.action.update.UpdateRequest;
//import org.elasticsearch.action.update.UpdateResponse;
//import org.elasticsearch.client.*;
//import org.elasticsearch.common.Strings;
//import org.elasticsearch.index.query.BoolQueryBuilder;
//import org.elasticsearch.index.query.QueryBuilder;
//import org.elasticsearch.index.query.QueryBuilders;
//import org.elasticsearch.index.query.RangeQueryBuilder;
//import org.elasticsearch.rest.RestStatus;
//import org.elasticsearch.search.SearchHit;
//import org.elasticsearch.search.aggregations.AggregationBuilders;
//import org.elasticsearch.search.aggregations.Aggregations;
//import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
//import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
//import org.elasticsearch.search.aggregations.bucket.histogram.ParsedDateHistogram;
//import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
//import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
//import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
//import org.elasticsearch.search.builder.SearchSourceBuilder;
//import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
//import org.elasticsearch.search.sort.SortOrder;
//import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
//import org.springframework.core.io.ClassPathResource;
//
//import java.io.IOException;
//import java.util.*;
//@Slf4j
//public class ElasticSearchUtil {
// private static RestHighLevelClient client = null;
// //单例获取客户端
// public static RestHighLevelClient getClient() {
//// if (client == null) {
//// synchronized (ElasticSearchUtil.class) {
//// List<HttpHost> hosts = new ArrayList<>();
//// try {
//// ClassPathResource r = new ClassPathResource("application.properties");
//// if (r.exists()) {
//// Properties p = new Properties();
//// p.load(r.getInputStream());
//// String ips = p.get("elasticsearch.ip").toString();
//// for (String ipport : ips.split(",")) {
//// String ip = ipport.split(":")[0];
//// String port = ipport.split(":")[1];
//// hosts.add(new HttpHost(ip, Integer.parseInt(port), "http"));
//// }
//// }else{
//// Properties p =yaml2Properties("application.yml");
//// String ips = p.get("elasticsearch.ip").toString();
//// for (String ipport : ips.split(",")) {
//// String ip = ipport.split(":")[0];
//// String port = ipport.split(":")[1];
//// hosts.add(new HttpHost(ip, Integer.parseInt(port), "http"));
//// }
//// }
//// } catch (Exception e) {
//// e.printStackTrace();
//// }
////
//// RequestConfigCallback requestConfigCallback = new RequestConfigCallback() {
//// @Override
//// public Builder customizeRequestConfig(Builder requestConfigBuilder) {
//// requestConfigBuilder.setConnectTimeout(2000);
//// requestConfigBuilder.setSocketTimeout(300000);
//// return requestConfigBuilder;
//// }
//// };
//// client = new RestHighLevelClient(RestClient.builder(hosts.toArray(new HttpHost[0]))
//// .setRequestConfigCallback(requestConfigCallback));
//// }
//// }
// RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost("xtbgzww.digitalgd.com.cn",80,"http")).setPathPrefix("/es/search");;
// CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// credentialsProvider.setCredentials(AuthScope.ANY,
// new UsernamePasswordCredentials("elastic", "ap20pOPS20"));
// restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> {
// httpClientBuilder.disableAuthCaching().setDefaultCredentialsProvider(credentialsProvider);
// return httpClientBuilder;
// });
//
// // 异步httpclient连接延时配置
//// setConnectTimeOutConfig(restClientBuilder);
// // 异步httpclient连接数配置
//// setConnectConfig(restClientBuilder);
//// setAuth(restClientBuilder);
// RestHighLevelClient client = new RestHighLevelClient(restClientBuilder);
// return client;
// }
//
// public static void main(String[] args) throws Exception {
// Map<String, Object> map = ElasticSearchUtil.getListData("operation_log",null);
// System.out.println();
// }
// // yml转properties
// public static Properties yaml2Properties(String yamlSource) {
// try {
// YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
// yaml.setResources(new ClassPathResource(yamlSource));
// return yaml.getObject();
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
//
//
// /**
// * 递归回调获取数据
// * @param data
// * @param datalist
// * @param fields
// * @param aggs
// * @param index
// */
// private static void getGroupData(Map<String, String> data,List<Map<String, String>> datalist,String fields[],List<Object> aggs,int index){
// //普通统计
// if (aggs.get(index) instanceof ParsedStringTerms ) {
// for (Bucket bucket : ((ParsedStringTerms)aggs.get(index)).getBuckets()) {
// if (data==null) {
// data = new LinkedHashMap<String, String>();
// }
// if (index+1==aggs.size()) {//如果到最后一层则输出
// data.put(fields[index], bucket.getKeyAsString());
// data.put("total", bucket.getDocCount()+"");
// Map<String, String> tempdata = new LinkedHashMap<String, String>();
// tempdata.putAll(data);
// if (bucket.getDocCount()>0) {//数据为0的不要
// datalist.add(tempdata);
// }
// }else{
// data.put(fields[index], bucket.getKeyAsString());
// aggs.set(index+1, bucket.getAggregations().get(fields[index+1]));//切换上层对应的聚合结果
// getGroupData(data,datalist,fields,aggs,index+1);
// }
// }
// }
// //日期统计
// if (aggs.get(index) instanceof ParsedDateHistogram ) {
// for (org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket bucket : ((ParsedDateHistogram)aggs.get(index)).getBuckets()) {
// if (index+1==aggs.size()) {//如果到最后一层则输出
// data.put(fields[index], bucket.getKeyAsString());
// data.put("total", bucket.getDocCount()+"");
// Map<String, String> tempdata = new LinkedHashMap<String, String>();
// tempdata.putAll(data);
// if (bucket.getDocCount()>0) {//数据为0的不要
// datalist.add(tempdata);
// }
// }else{
// if (data==null) {
// data = new LinkedHashMap<String, String>();
// }
// data.put(fields[index], bucket.getKeyAsString());
// aggs.set(index+1, bucket.getAggregations().get(fields[index+1]));//切换上层对应的聚合结果
// getGroupData(data,datalist,fields,aggs,index+1);
// }
// }
// }
//
// }
//
// /**
// * 分组统计方法
// * @param indexs 索引(支持多个索引联合查询) 相当于表名,多个相当于union
// * @param fields 统计字段 相当于 group by 字段名,注意如果存在日期字段统计,日期放最后一个
// * @param filterMap 过滤参数 相当于where 字段名=值
// */
// public static List<Map<String, String>> queryForGroupBy(String index,String fields[],Map<String,String> filterMap){
// List<Map<String, String>> list = new ArrayList<Map<String,String>>();
// try {
// // 1、创建search请求
// SearchRequest searchRequest = new SearchRequest(index);
// // 2、用SearchSourceBuilder来构造查询请求体 ,请仔细查看它的方法,构造各种查询的方法都在这。
// SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// sourceBuilder.size(0);
// //多字段分组
// List<Object> termsBuilders = new ArrayList<Object>();
// for (int i = 0; i < fields.length; i++) {
// if ("AcceptTime".equals(fields[i])) {//日期字段统计
// DateHistogramAggregationBuilder termsBuilder = AggregationBuilders.dateHistogram("AcceptTime").field("AcceptTime").dateHistogramInterval(new DateHistogramInterval("1d")).format("yyyy-MM-dd").minDocCount(1);
// termsBuilders.add(termsBuilder);
// if (i!=0) {
// ((TermsAggregationBuilder)termsBuilders.get(i-1)).subAggregation(termsBuilder);
// }
// }else if ("ViolationTime".equals(fields[i])) {//日期字段统计
// DateHistogramAggregationBuilder termsBuilder = AggregationBuilders.dateHistogram("ViolationTime").field("ViolationTime").dateHistogramInterval(new DateHistogramInterval("1d")).format("yyyy-MM-dd").minDocCount(1);
// termsBuilders.add(termsBuilder);
// if (i!=0) {
// ((TermsAggregationBuilder)termsBuilders.get(i-1)).subAggregation(termsBuilder);
// }
// }else{//普通字符串字段统计
// TermsAggregationBuilder termsBuilder = AggregationBuilders.terms(fields[i]).field(fields[i]).size(10000);//不设size每个分组默认返回十条
// termsBuilders.add(termsBuilder);
// if (i!=0) {
// ((TermsAggregationBuilder)termsBuilders.get(i-1)).subAggregation(termsBuilder);
// }
// }
// }
// //加入聚合
// sourceBuilder.aggregation((TermsAggregationBuilder)termsBuilders.get(0));
// //过滤条件
// if(filterMap!=null){
// BoolQueryBuilder globalBuilder = QueryBuilders.boolQuery();
// for (String key : filterMap.keySet()) {
// QueryBuilder matchQueryBuilder = QueryBuilders.termsQuery(key, filterMap.get(key));
// globalBuilder.must(matchQueryBuilder);
// }
// sourceBuilder.query(globalBuilder);
// }
// log.info("分组统计请求参数:"+index+" "+sourceBuilder);
// searchRequest.source(sourceBuilder);
// //3、发送请求
// RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
// builder.setHttpAsyncResponseConsumerFactory(new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(1*1024*1024*1024));//5G
// SearchResponse searchResponse = getClient().search(searchRequest,builder.build());
// //4、处理响应
// //搜索结果状态信息
// if(RestStatus.OK.equals(searchResponse.status())) {
// // 获取聚合结果
// Aggregations aggregations = searchResponse.getAggregations();
// List<Object> aggs = new ArrayList<Object>();
// for (int i = 0; i < fields.length; i++) {
// if (i==0) {
// aggs.add(aggregations.get(fields[i]));
// }else if((aggs.size()>i-1)&&(aggs.get(i-1) instanceof ParsedStringTerms)&&
// ((ParsedStringTerms)aggs.get(i-1)).getBuckets().size()>0) {//第一个字段没数据,后面都为空 //普通字符串字段统计
// aggs.add(((ParsedStringTerms) aggs.get(i-1)).getBuckets().get(0).getAggregations().get(fields[i]));
// }else if((aggs.size()>i-1)&&(aggs.get(i-1) instanceof ParsedDateHistogram)&&
// ((ParsedDateHistogram)aggs.get(i-1)).getBuckets().size()>0) {//第一个字段没数据,后面都为空 //日期字段统计
// aggs.add(((ParsedDateHistogram) aggs.get(i-1)).getBuckets().get(0).getAggregations().get(fields[i]));
// }
// }
// if (aggs.size()==fields.length) {
// getGroupData(null, list, fields, aggs, 0);
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// log.info("结果数:"+list.size());
// return list;
// }
//
// /**
// * 日期统计
// * @param indexs 索引(支持多个索引联合查询) 相当于表名,多个相当于union
// * @param timefield 日期字段
// * @param interval 间隔 1d 一天 1M 一个月 1y 一年
// * @param format 日期字段
// * @param filterMap 过滤参数 相当于where 字段名=值
// */
// public static Map<String, Object> queryForTimeInterval(String index,String timefield,String interval,String format,Map<String,String> filterMap){
// Map<String, Object> result = new LinkedHashMap<String, Object>();
// try {
// // 1、创建search请求
// SearchRequest searchRequest = new SearchRequest(index);
// // 2、用SearchSourceBuilder来构造查询请求体 ,请仔细查看它的方法,构造各种查询的方法都在这。
// SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// sourceBuilder.size(0);
// //多字段分组
// DateHistogramAggregationBuilder termsBuilder = AggregationBuilders.dateHistogram(timefield).field(timefield).dateHistogramInterval(new DateHistogramInterval(interval)).format(format);
//
// //加入聚合
// sourceBuilder.aggregation(termsBuilder);
// //过滤条件
// if(filterMap!=null){
// BoolQueryBuilder globalBuilder = QueryBuilders.boolQuery();
//
// if (filterMap.containsKey("ViolationTime")) {
// String timerange[] = filterMap.get("ViolationTime").toString().split(" - ");
// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("ViolationTime");
// if (timerange.length>0) {
// rangeQueryBuilder.gte(timerange[0]);
// }
// if (timerange.length>1) {
// rangeQueryBuilder.lt(timerange[1]);
// }
// globalBuilder.must(rangeQueryBuilder);
// filterMap.remove("ViolationTime");
// }
//
// for (String key : filterMap.keySet()) {
// QueryBuilder matchQueryBuilder = QueryBuilders.termsQuery(key, filterMap.get(key).split(","));
// globalBuilder.must(matchQueryBuilder);
// }
// sourceBuilder.query(globalBuilder);
// }
// log.info("分组统计请求参数:"+index+" "+sourceBuilder);
// searchRequest.source(sourceBuilder);
// //3、发送请求
// RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
// builder.setHttpAsyncResponseConsumerFactory(new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(1*1024*1024*1024));//5G
// SearchResponse searchResponse = getClient().search(searchRequest,builder.build());
// //4、处理响应
// //搜索结果状态信息
// if(RestStatus.OK.equals(searchResponse.status())) {
// // 获取聚合结果
// Aggregations aggregations = searchResponse.getAggregations();
// ParsedDateHistogram parsedDateHistogram = aggregations.get(timefield);
// for (org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket bucket : parsedDateHistogram.getBuckets()) {
// System.out.println(bucket.getKeyAsString()+" "+bucket.getDocCount());
// result.put(bucket.getKeyAsString(), bucket.getDocCount());
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// log.info("结果数:"+result.size());
// return result;
// }
//
// /**
// * 获取es数据
// * @param indexs 索引名
// * @param paramsMap 过滤参数
// * @return
// * @throws Exception
// */
// public static Map<String, Object> getListData(String index,Map<String,Object> paramsMap)throws Exception{
// List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
// // 1、创建search请求
// SearchRequest searchRequest = new SearchRequest(index);
// // 2、用SearchSourceBuilder来构造查询请求体 ,请仔细查看它的方法,构造各种查询的方法都在这。
// SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// sourceBuilder.trackTotalHits(true);
// //过滤条件
// if(paramsMap!=null){
// BoolQueryBuilder globalBuilder = QueryBuilders.boolQuery();
// if (paramsMap.containsKey("CreateDate")) {//上次最新时间
// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("CreateDate").gt(paramsMap.get("CreateDate"));
// globalBuilder.must(rangeQueryBuilder);
// }
// if (paramsMap.containsKey("AcceptTime")) {//上次最新时间
// String timerange[] = paramsMap.get("AcceptTime").toString().split(" - ");
// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("AcceptTime");
// if (timerange.length>0) {
// rangeQueryBuilder.gte(timerange[0]);
// }
// if (timerange.length>1) {
// rangeQueryBuilder.lte(timerange[1]);
// }
// globalBuilder.must(rangeQueryBuilder);
// }
// if (paramsMap.containsKey("notType")) {//设置返回数量,不设置默认返回十条,最大返回10000条,超过10000条需要设置,全部返回设为0
// BoolQueryBuilder notinqueryQuery = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("Type", paramsMap.get("notType")));
// globalBuilder.must(notinqueryQuery);
// }
// if (paramsMap.containsKey("page")&¶msMap.containsKey("size")) {//分页,从1开始
// sourceBuilder.from((Integer.parseInt(paramsMap.get("page").toString())-1)*Integer.parseInt(paramsMap.get("size").toString()));
// }
// if (paramsMap.containsKey("size")) {//设置返回数量,不设置默认返回十条,最大返回10000条,超过10000条需要设置,全部返回设为0
// Integer size = Integer.parseInt(paramsMap.get("size").toString());
// sourceBuilder.size(size);
// }
// if (paramsMap.containsKey("sortName")&¶msMap.containsKey("sortOrder")) {//排序
// sourceBuilder.sort(paramsMap.get("sortName").toString(), (SortOrder)paramsMap.get("sortOrder"));
// }
// if (paramsMap.containsKey("OperatorID")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("OperatorID", paramsMap.get("OperatorID"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("MSISDN")) {
// //QueryBuilder queryBuilder = QueryBuilders.termQuery("MSISDN", paramsMap.get("MSISDN"));
// QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("MSISDN", "*"+paramsMap.get("MSISDN")+"*");
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("IMEI")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("IMEI", paramsMap.get("IMEI"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("Industry")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("Industry", paramsMap.get("Industry"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("Province")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("Province", paramsMap.get("Province"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("Data")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("Data", paramsMap.get("Data"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("Voice")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("Voice", paramsMap.get("Voice"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("Message")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("Message", paramsMap.get("Message"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("ViolationType")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("ViolationType", paramsMap.get("ViolationType"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("ViolationTime")) {
// String timerange[] = paramsMap.get("ViolationTime").toString().split(" - ");
// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("ViolationTime");
// if (timerange.length>0) {
// rangeQueryBuilder.gte(timerange[0]);
// }
// if (timerange.length>1) {
// rangeQueryBuilder.lt(timerange[1]);
// }
// globalBuilder.must(rangeQueryBuilder);
// }
//
// /*合规性检查*/
// if (paramsMap.containsKey("ID")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("ID", paramsMap.get("ID"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("TypeID")&& StringUtils.isNotBlank(paramsMap.get("TypeID").toString())) {
// String arr[] =paramsMap.get("TypeID").toString().split(",");
// QueryBuilder queryBuilder = QueryBuilders.termsQuery("TypeID", arr);
// globalBuilder.must(queryBuilder);
// }
// /*合规性检查*/
// sourceBuilder.query(globalBuilder);
// }
// searchRequest.source(sourceBuilder);
//// Scroll scroll = new Scroll(TimeValue.timeValueMinutes(1L));
//// searchRequest.scroll(scroll);
//
// log.info("获取列表请求参数:"+index+" "+sourceBuilder);
// //3、发送请求
// SearchResponse searchResponse = getClient().search(searchRequest,RequestOptions.DEFAULT);
// long total = searchResponse.getHits().getTotalHits().value;
//
// //4、处理响应
// //搜索结果状态信息
// if(RestStatus.OK.equals(searchResponse.status())) {
//
//// String scrollId = searchResponse.getScrollId();
// SearchHit[] searchHit = searchResponse.getHits().getHits();
// for (SearchHit hit : searchHit) {
// list.add(hit.getSourceAsMap());
// }
// System.out.println("总数:"+total+" 当前:"+list.size()+" 本次返回:"+searchHit.length);
//// while( searchHit != null && searchHit.length > 0 ) {
//// System.out.println("总数:"+total+" 当前:"+list.size()+" 本次返回:"+searchHit.length);
//// for (SearchHit hit : searchHit) {
//// list.add(hit.getSourceAsMap());
//// }
////
//// SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
//// scrollRequest.scroll(scroll);
////
//// searchResponse = getClient().searchScroll(scrollRequest,RequestOptions.DEFAULT);
//// scrollId = searchResponse.getScrollId();
//// searchHit = searchResponse.getHits().getHits();
//// }
//
//// ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
//// clearScrollRequest.addScrollId(scrollId);
//// ClearScrollResponse clearScrollResponse = getClient().clearScroll(clearScrollRequest,RequestOptions.DEFAULT);
// }
// //System.out.println(JSON.toJSONString(list));
// Map<String, Object> result = new HashMap<String, Object>();
// result.put("list", list);
// result.put("total", total);
// return result;
// }
//
// public static void insert(String index,Map<String,Object> map) throws Exception{
// IndexRequest indexRequest = null;
// if (map.containsKey("_id")) {
// String _id = map.get("_id").toString();
// System.out.println("插入文档:"+index+" "+_id);
// map.remove("_id");
// indexRequest = new IndexRequest(index,"_doc",_id).source(map);
// }else{
// indexRequest = new IndexRequest(index).source(map);
// }
//
// IndexResponse indexResponse = getClient().index(indexRequest, RequestOptions.DEFAULT);
// //5、处理响应
// if(indexResponse != null) {
// if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
//// System.out.println("新增文档成功:"+JSON.toJSONString(map));
// } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
//// System.out.println("修改文档成功:"+JSON.toJSONString(map));
// }
// // 分片处理信息
// ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
// if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
//
// }
// // 如果有分片副本失败,可以获得失败原因信息
// if (shardInfo.getFailed() > 0) {
// for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
// String reason = failure.reason();
// System.out.println("副本失败原因:" + reason);
// }
// }
// }
// }
//
//
// public static void update(String index,String id,Map<String,Object> map) throws Exception{
// UpdateRequest request = new UpdateRequest(index, id).doc(map);
// UpdateResponse response = getClient().update(request, RequestOptions.DEFAULT);
// //5、处理响应
// if(response != null) {
// if (response.getResult() == DocWriteResponse.Result.CREATED) {
// System.out.println("新增文档成功,处理逻辑代码写到这里。");
// } else if (response.getResult() == DocWriteResponse.Result.UPDATED) {
// System.out.println("修改文档成功:"+id);
// }
// // 分片处理信息
// ReplicationResponse.ShardInfo shardInfo = response.getShardInfo();
// if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
//
// }
// // 如果有分片副本失败,可以获得失败原因信息
// if (shardInfo.getFailed() > 0) {
// for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
// String reason = failure.reason();
// System.out.println("副本失败原因:" + reason);
// }
// }
// }
// }
//
// /**
// * 根据ID获取文档
// * @param index
// * @param id
// * @return
// */
// public static Map<String, Object> getDocument(String index,String id) throws Exception{
// // 1、创建获取文档请求
// GetRequest request = new GetRequest(index,"_doc",id);
// //选择返回的字段
// String[] includes = new String[]{"*"};
// String[] excludes = Strings.EMPTY_ARRAY;
// FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);
// request.fetchSourceContext(fetchSourceContext);
//
// //3、发送请求
// GetResponse getResponse = null;
// try {
// // 同步请求
// getResponse = getClient().get(request,RequestOptions.DEFAULT);
// } catch (ElasticsearchException e) {
// if (e.status() == RestStatus.NOT_FOUND) {
// System.out.println("没有找到该id的文档" );
// }
// if (e.status() == RestStatus.CONFLICT) {
// System.out.println("获取时版本冲突了,请在此写冲突处理逻辑!" );
// }
// System.out.println("获取文档异常"+ e.getDetailedMessage());
// }
//
// //4、处理响应
// if(getResponse != null) {
// if (getResponse.isExists()) { // 文档存在
// String sourceAsString = getResponse.getSourceAsString(); //结果取成 String
// Map<String, Object> sourceAsMap = getResponse.getSourceAsMap(); // 结果取成Map
// System.out.println("获取文档:"+sourceAsString);
// return sourceAsMap;
// } else {
// System.out.println("没有找到该id的文档,index:"+index+" id:"+id );
// }
// }
// return null;
// }
//
//
// /**
// * 批量插入
// * @param index
// * @param list
// */
// public static void bulkInsert(String index,List<Map<String, Object>> list) throws Exception{
// BulkRequest request = new BulkRequest();
// for (Map<String, Object> map : list) {
// if (map.containsKey("_id")) {
// String _id = map.get("_id").toString();
// map.remove("_id");
// request.add(new IndexRequest(index,"_doc",_id).source(map));
// }else{
// request.add(new IndexRequest(index).source(map));
// }
//
// }
// BulkResponse bulkResponse = getClient().bulk(request, RequestOptions.DEFAULT);
// //4、处理响应
// if(bulkResponse != null) {
// for (BulkItemResponse bulkItemResponse : bulkResponse) {
// DocWriteResponse itemResponse = bulkItemResponse.getResponse();
// Failure failure = bulkItemResponse.getFailure();
// if (failure!=null) {
// System.out.println(failure.getMessage());
// }else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.INDEX|| bulkItemResponse.getOpType() == DocWriteRequest.OpType.CREATE) {
// IndexResponse indexResponse = (IndexResponse) itemResponse;
// //TODO 新增成功的处理
//
// } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.UPDATE) {
// UpdateResponse updateResponse = (UpdateResponse) itemResponse;
// //TODO 修改成功的处理
//
// } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.DELETE) {
// DeleteResponse deleteResponse = (DeleteResponse) itemResponse;
// //TODO 删除成功的处理
// }
// }
// }
// }
//}
| UTF-8 | Java | 29,520 | java | ElasticSearchUtil.java | Java | [
{
"context": "Scope.ANY,\n//\t\t\t\tnew UsernamePasswordCredentials(\"elastic\", \"ap20pOPS20\"));\n//\t\trestClientBuilder.setHttpCl",
"end": 4815,
"score": 0.6948504447937012,
"start": 4808,
"tag": "USERNAME",
"value": "elastic"
},
{
"context": "//\t\t\t\tnew UsernamePasswordCreden... | null | [] | //package com.digitalgd.dpd.elasticsearch.config;
//
//import io.micrometer.core.instrument.util.StringUtils;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.http.HttpHost;
//import org.apache.http.auth.AuthScope;
//import org.apache.http.auth.UsernamePasswordCredentials;
//import org.apache.http.client.CredentialsProvider;
//import org.apache.http.impl.client.BasicCredentialsProvider;
//import org.elasticsearch.ElasticsearchException;
//import org.elasticsearch.action.DocWriteRequest;
//import org.elasticsearch.action.DocWriteResponse;
//import org.elasticsearch.action.bulk.BulkItemResponse;
//import org.elasticsearch.action.bulk.BulkItemResponse.Failure;
//import org.elasticsearch.action.bulk.BulkRequest;
//import org.elasticsearch.action.bulk.BulkResponse;
//import org.elasticsearch.action.delete.DeleteResponse;
//import org.elasticsearch.action.get.GetRequest;
//import org.elasticsearch.action.get.GetResponse;
//import org.elasticsearch.action.index.IndexRequest;
//import org.elasticsearch.action.index.IndexResponse;
//import org.elasticsearch.action.search.SearchRequest;
//import org.elasticsearch.action.search.SearchResponse;
//import org.elasticsearch.action.support.replication.ReplicationResponse;
//import org.elasticsearch.action.update.UpdateRequest;
//import org.elasticsearch.action.update.UpdateResponse;
//import org.elasticsearch.client.*;
//import org.elasticsearch.common.Strings;
//import org.elasticsearch.index.query.BoolQueryBuilder;
//import org.elasticsearch.index.query.QueryBuilder;
//import org.elasticsearch.index.query.QueryBuilders;
//import org.elasticsearch.index.query.RangeQueryBuilder;
//import org.elasticsearch.rest.RestStatus;
//import org.elasticsearch.search.SearchHit;
//import org.elasticsearch.search.aggregations.AggregationBuilders;
//import org.elasticsearch.search.aggregations.Aggregations;
//import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
//import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
//import org.elasticsearch.search.aggregations.bucket.histogram.ParsedDateHistogram;
//import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
//import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
//import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
//import org.elasticsearch.search.builder.SearchSourceBuilder;
//import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
//import org.elasticsearch.search.sort.SortOrder;
//import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
//import org.springframework.core.io.ClassPathResource;
//
//import java.io.IOException;
//import java.util.*;
//@Slf4j
//public class ElasticSearchUtil {
// private static RestHighLevelClient client = null;
// //单例获取客户端
// public static RestHighLevelClient getClient() {
//// if (client == null) {
//// synchronized (ElasticSearchUtil.class) {
//// List<HttpHost> hosts = new ArrayList<>();
//// try {
//// ClassPathResource r = new ClassPathResource("application.properties");
//// if (r.exists()) {
//// Properties p = new Properties();
//// p.load(r.getInputStream());
//// String ips = p.get("elasticsearch.ip").toString();
//// for (String ipport : ips.split(",")) {
//// String ip = ipport.split(":")[0];
//// String port = ipport.split(":")[1];
//// hosts.add(new HttpHost(ip, Integer.parseInt(port), "http"));
//// }
//// }else{
//// Properties p =yaml2Properties("application.yml");
//// String ips = p.get("elasticsearch.ip").toString();
//// for (String ipport : ips.split(",")) {
//// String ip = ipport.split(":")[0];
//// String port = ipport.split(":")[1];
//// hosts.add(new HttpHost(ip, Integer.parseInt(port), "http"));
//// }
//// }
//// } catch (Exception e) {
//// e.printStackTrace();
//// }
////
//// RequestConfigCallback requestConfigCallback = new RequestConfigCallback() {
//// @Override
//// public Builder customizeRequestConfig(Builder requestConfigBuilder) {
//// requestConfigBuilder.setConnectTimeout(2000);
//// requestConfigBuilder.setSocketTimeout(300000);
//// return requestConfigBuilder;
//// }
//// };
//// client = new RestHighLevelClient(RestClient.builder(hosts.toArray(new HttpHost[0]))
//// .setRequestConfigCallback(requestConfigCallback));
//// }
//// }
// RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost("xtbgzww.digitalgd.com.cn",80,"http")).setPathPrefix("/es/search");;
// CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// credentialsProvider.setCredentials(AuthScope.ANY,
// new UsernamePasswordCredentials("elastic", "<PASSWORD>"));
// restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> {
// httpClientBuilder.disableAuthCaching().setDefaultCredentialsProvider(credentialsProvider);
// return httpClientBuilder;
// });
//
// // 异步httpclient连接延时配置
//// setConnectTimeOutConfig(restClientBuilder);
// // 异步httpclient连接数配置
//// setConnectConfig(restClientBuilder);
//// setAuth(restClientBuilder);
// RestHighLevelClient client = new RestHighLevelClient(restClientBuilder);
// return client;
// }
//
// public static void main(String[] args) throws Exception {
// Map<String, Object> map = ElasticSearchUtil.getListData("operation_log",null);
// System.out.println();
// }
// // yml转properties
// public static Properties yaml2Properties(String yamlSource) {
// try {
// YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
// yaml.setResources(new ClassPathResource(yamlSource));
// return yaml.getObject();
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
//
//
// /**
// * 递归回调获取数据
// * @param data
// * @param datalist
// * @param fields
// * @param aggs
// * @param index
// */
// private static void getGroupData(Map<String, String> data,List<Map<String, String>> datalist,String fields[],List<Object> aggs,int index){
// //普通统计
// if (aggs.get(index) instanceof ParsedStringTerms ) {
// for (Bucket bucket : ((ParsedStringTerms)aggs.get(index)).getBuckets()) {
// if (data==null) {
// data = new LinkedHashMap<String, String>();
// }
// if (index+1==aggs.size()) {//如果到最后一层则输出
// data.put(fields[index], bucket.getKeyAsString());
// data.put("total", bucket.getDocCount()+"");
// Map<String, String> tempdata = new LinkedHashMap<String, String>();
// tempdata.putAll(data);
// if (bucket.getDocCount()>0) {//数据为0的不要
// datalist.add(tempdata);
// }
// }else{
// data.put(fields[index], bucket.getKeyAsString());
// aggs.set(index+1, bucket.getAggregations().get(fields[index+1]));//切换上层对应的聚合结果
// getGroupData(data,datalist,fields,aggs,index+1);
// }
// }
// }
// //日期统计
// if (aggs.get(index) instanceof ParsedDateHistogram ) {
// for (org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket bucket : ((ParsedDateHistogram)aggs.get(index)).getBuckets()) {
// if (index+1==aggs.size()) {//如果到最后一层则输出
// data.put(fields[index], bucket.getKeyAsString());
// data.put("total", bucket.getDocCount()+"");
// Map<String, String> tempdata = new LinkedHashMap<String, String>();
// tempdata.putAll(data);
// if (bucket.getDocCount()>0) {//数据为0的不要
// datalist.add(tempdata);
// }
// }else{
// if (data==null) {
// data = new LinkedHashMap<String, String>();
// }
// data.put(fields[index], bucket.getKeyAsString());
// aggs.set(index+1, bucket.getAggregations().get(fields[index+1]));//切换上层对应的聚合结果
// getGroupData(data,datalist,fields,aggs,index+1);
// }
// }
// }
//
// }
//
// /**
// * 分组统计方法
// * @param indexs 索引(支持多个索引联合查询) 相当于表名,多个相当于union
// * @param fields 统计字段 相当于 group by 字段名,注意如果存在日期字段统计,日期放最后一个
// * @param filterMap 过滤参数 相当于where 字段名=值
// */
// public static List<Map<String, String>> queryForGroupBy(String index,String fields[],Map<String,String> filterMap){
// List<Map<String, String>> list = new ArrayList<Map<String,String>>();
// try {
// // 1、创建search请求
// SearchRequest searchRequest = new SearchRequest(index);
// // 2、用SearchSourceBuilder来构造查询请求体 ,请仔细查看它的方法,构造各种查询的方法都在这。
// SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// sourceBuilder.size(0);
// //多字段分组
// List<Object> termsBuilders = new ArrayList<Object>();
// for (int i = 0; i < fields.length; i++) {
// if ("AcceptTime".equals(fields[i])) {//日期字段统计
// DateHistogramAggregationBuilder termsBuilder = AggregationBuilders.dateHistogram("AcceptTime").field("AcceptTime").dateHistogramInterval(new DateHistogramInterval("1d")).format("yyyy-MM-dd").minDocCount(1);
// termsBuilders.add(termsBuilder);
// if (i!=0) {
// ((TermsAggregationBuilder)termsBuilders.get(i-1)).subAggregation(termsBuilder);
// }
// }else if ("ViolationTime".equals(fields[i])) {//日期字段统计
// DateHistogramAggregationBuilder termsBuilder = AggregationBuilders.dateHistogram("ViolationTime").field("ViolationTime").dateHistogramInterval(new DateHistogramInterval("1d")).format("yyyy-MM-dd").minDocCount(1);
// termsBuilders.add(termsBuilder);
// if (i!=0) {
// ((TermsAggregationBuilder)termsBuilders.get(i-1)).subAggregation(termsBuilder);
// }
// }else{//普通字符串字段统计
// TermsAggregationBuilder termsBuilder = AggregationBuilders.terms(fields[i]).field(fields[i]).size(10000);//不设size每个分组默认返回十条
// termsBuilders.add(termsBuilder);
// if (i!=0) {
// ((TermsAggregationBuilder)termsBuilders.get(i-1)).subAggregation(termsBuilder);
// }
// }
// }
// //加入聚合
// sourceBuilder.aggregation((TermsAggregationBuilder)termsBuilders.get(0));
// //过滤条件
// if(filterMap!=null){
// BoolQueryBuilder globalBuilder = QueryBuilders.boolQuery();
// for (String key : filterMap.keySet()) {
// QueryBuilder matchQueryBuilder = QueryBuilders.termsQuery(key, filterMap.get(key));
// globalBuilder.must(matchQueryBuilder);
// }
// sourceBuilder.query(globalBuilder);
// }
// log.info("分组统计请求参数:"+index+" "+sourceBuilder);
// searchRequest.source(sourceBuilder);
// //3、发送请求
// RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
// builder.setHttpAsyncResponseConsumerFactory(new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(1*1024*1024*1024));//5G
// SearchResponse searchResponse = getClient().search(searchRequest,builder.build());
// //4、处理响应
// //搜索结果状态信息
// if(RestStatus.OK.equals(searchResponse.status())) {
// // 获取聚合结果
// Aggregations aggregations = searchResponse.getAggregations();
// List<Object> aggs = new ArrayList<Object>();
// for (int i = 0; i < fields.length; i++) {
// if (i==0) {
// aggs.add(aggregations.get(fields[i]));
// }else if((aggs.size()>i-1)&&(aggs.get(i-1) instanceof ParsedStringTerms)&&
// ((ParsedStringTerms)aggs.get(i-1)).getBuckets().size()>0) {//第一个字段没数据,后面都为空 //普通字符串字段统计
// aggs.add(((ParsedStringTerms) aggs.get(i-1)).getBuckets().get(0).getAggregations().get(fields[i]));
// }else if((aggs.size()>i-1)&&(aggs.get(i-1) instanceof ParsedDateHistogram)&&
// ((ParsedDateHistogram)aggs.get(i-1)).getBuckets().size()>0) {//第一个字段没数据,后面都为空 //日期字段统计
// aggs.add(((ParsedDateHistogram) aggs.get(i-1)).getBuckets().get(0).getAggregations().get(fields[i]));
// }
// }
// if (aggs.size()==fields.length) {
// getGroupData(null, list, fields, aggs, 0);
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// log.info("结果数:"+list.size());
// return list;
// }
//
// /**
// * 日期统计
// * @param indexs 索引(支持多个索引联合查询) 相当于表名,多个相当于union
// * @param timefield 日期字段
// * @param interval 间隔 1d 一天 1M 一个月 1y 一年
// * @param format 日期字段
// * @param filterMap 过滤参数 相当于where 字段名=值
// */
// public static Map<String, Object> queryForTimeInterval(String index,String timefield,String interval,String format,Map<String,String> filterMap){
// Map<String, Object> result = new LinkedHashMap<String, Object>();
// try {
// // 1、创建search请求
// SearchRequest searchRequest = new SearchRequest(index);
// // 2、用SearchSourceBuilder来构造查询请求体 ,请仔细查看它的方法,构造各种查询的方法都在这。
// SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// sourceBuilder.size(0);
// //多字段分组
// DateHistogramAggregationBuilder termsBuilder = AggregationBuilders.dateHistogram(timefield).field(timefield).dateHistogramInterval(new DateHistogramInterval(interval)).format(format);
//
// //加入聚合
// sourceBuilder.aggregation(termsBuilder);
// //过滤条件
// if(filterMap!=null){
// BoolQueryBuilder globalBuilder = QueryBuilders.boolQuery();
//
// if (filterMap.containsKey("ViolationTime")) {
// String timerange[] = filterMap.get("ViolationTime").toString().split(" - ");
// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("ViolationTime");
// if (timerange.length>0) {
// rangeQueryBuilder.gte(timerange[0]);
// }
// if (timerange.length>1) {
// rangeQueryBuilder.lt(timerange[1]);
// }
// globalBuilder.must(rangeQueryBuilder);
// filterMap.remove("ViolationTime");
// }
//
// for (String key : filterMap.keySet()) {
// QueryBuilder matchQueryBuilder = QueryBuilders.termsQuery(key, filterMap.get(key).split(","));
// globalBuilder.must(matchQueryBuilder);
// }
// sourceBuilder.query(globalBuilder);
// }
// log.info("分组统计请求参数:"+index+" "+sourceBuilder);
// searchRequest.source(sourceBuilder);
// //3、发送请求
// RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
// builder.setHttpAsyncResponseConsumerFactory(new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(1*1024*1024*1024));//5G
// SearchResponse searchResponse = getClient().search(searchRequest,builder.build());
// //4、处理响应
// //搜索结果状态信息
// if(RestStatus.OK.equals(searchResponse.status())) {
// // 获取聚合结果
// Aggregations aggregations = searchResponse.getAggregations();
// ParsedDateHistogram parsedDateHistogram = aggregations.get(timefield);
// for (org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket bucket : parsedDateHistogram.getBuckets()) {
// System.out.println(bucket.getKeyAsString()+" "+bucket.getDocCount());
// result.put(bucket.getKeyAsString(), bucket.getDocCount());
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// log.info("结果数:"+result.size());
// return result;
// }
//
// /**
// * 获取es数据
// * @param indexs 索引名
// * @param paramsMap 过滤参数
// * @return
// * @throws Exception
// */
// public static Map<String, Object> getListData(String index,Map<String,Object> paramsMap)throws Exception{
// List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
// // 1、创建search请求
// SearchRequest searchRequest = new SearchRequest(index);
// // 2、用SearchSourceBuilder来构造查询请求体 ,请仔细查看它的方法,构造各种查询的方法都在这。
// SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// sourceBuilder.trackTotalHits(true);
// //过滤条件
// if(paramsMap!=null){
// BoolQueryBuilder globalBuilder = QueryBuilders.boolQuery();
// if (paramsMap.containsKey("CreateDate")) {//上次最新时间
// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("CreateDate").gt(paramsMap.get("CreateDate"));
// globalBuilder.must(rangeQueryBuilder);
// }
// if (paramsMap.containsKey("AcceptTime")) {//上次最新时间
// String timerange[] = paramsMap.get("AcceptTime").toString().split(" - ");
// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("AcceptTime");
// if (timerange.length>0) {
// rangeQueryBuilder.gte(timerange[0]);
// }
// if (timerange.length>1) {
// rangeQueryBuilder.lte(timerange[1]);
// }
// globalBuilder.must(rangeQueryBuilder);
// }
// if (paramsMap.containsKey("notType")) {//设置返回数量,不设置默认返回十条,最大返回10000条,超过10000条需要设置,全部返回设为0
// BoolQueryBuilder notinqueryQuery = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("Type", paramsMap.get("notType")));
// globalBuilder.must(notinqueryQuery);
// }
// if (paramsMap.containsKey("page")&¶msMap.containsKey("size")) {//分页,从1开始
// sourceBuilder.from((Integer.parseInt(paramsMap.get("page").toString())-1)*Integer.parseInt(paramsMap.get("size").toString()));
// }
// if (paramsMap.containsKey("size")) {//设置返回数量,不设置默认返回十条,最大返回10000条,超过10000条需要设置,全部返回设为0
// Integer size = Integer.parseInt(paramsMap.get("size").toString());
// sourceBuilder.size(size);
// }
// if (paramsMap.containsKey("sortName")&¶msMap.containsKey("sortOrder")) {//排序
// sourceBuilder.sort(paramsMap.get("sortName").toString(), (SortOrder)paramsMap.get("sortOrder"));
// }
// if (paramsMap.containsKey("OperatorID")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("OperatorID", paramsMap.get("OperatorID"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("MSISDN")) {
// //QueryBuilder queryBuilder = QueryBuilders.termQuery("MSISDN", paramsMap.get("MSISDN"));
// QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("MSISDN", "*"+paramsMap.get("MSISDN")+"*");
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("IMEI")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("IMEI", paramsMap.get("IMEI"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("Industry")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("Industry", paramsMap.get("Industry"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("Province")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("Province", paramsMap.get("Province"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("Data")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("Data", paramsMap.get("Data"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("Voice")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("Voice", paramsMap.get("Voice"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("Message")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("Message", paramsMap.get("Message"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("ViolationType")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("ViolationType", paramsMap.get("ViolationType"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("ViolationTime")) {
// String timerange[] = paramsMap.get("ViolationTime").toString().split(" - ");
// RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("ViolationTime");
// if (timerange.length>0) {
// rangeQueryBuilder.gte(timerange[0]);
// }
// if (timerange.length>1) {
// rangeQueryBuilder.lt(timerange[1]);
// }
// globalBuilder.must(rangeQueryBuilder);
// }
//
// /*合规性检查*/
// if (paramsMap.containsKey("ID")) {
// QueryBuilder queryBuilder = QueryBuilders.termQuery("ID", paramsMap.get("ID"));
// globalBuilder.must(queryBuilder);
// }
// if (paramsMap.containsKey("TypeID")&& StringUtils.isNotBlank(paramsMap.get("TypeID").toString())) {
// String arr[] =paramsMap.get("TypeID").toString().split(",");
// QueryBuilder queryBuilder = QueryBuilders.termsQuery("TypeID", arr);
// globalBuilder.must(queryBuilder);
// }
// /*合规性检查*/
// sourceBuilder.query(globalBuilder);
// }
// searchRequest.source(sourceBuilder);
//// Scroll scroll = new Scroll(TimeValue.timeValueMinutes(1L));
//// searchRequest.scroll(scroll);
//
// log.info("获取列表请求参数:"+index+" "+sourceBuilder);
// //3、发送请求
// SearchResponse searchResponse = getClient().search(searchRequest,RequestOptions.DEFAULT);
// long total = searchResponse.getHits().getTotalHits().value;
//
// //4、处理响应
// //搜索结果状态信息
// if(RestStatus.OK.equals(searchResponse.status())) {
//
//// String scrollId = searchResponse.getScrollId();
// SearchHit[] searchHit = searchResponse.getHits().getHits();
// for (SearchHit hit : searchHit) {
// list.add(hit.getSourceAsMap());
// }
// System.out.println("总数:"+total+" 当前:"+list.size()+" 本次返回:"+searchHit.length);
//// while( searchHit != null && searchHit.length > 0 ) {
//// System.out.println("总数:"+total+" 当前:"+list.size()+" 本次返回:"+searchHit.length);
//// for (SearchHit hit : searchHit) {
//// list.add(hit.getSourceAsMap());
//// }
////
//// SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
//// scrollRequest.scroll(scroll);
////
//// searchResponse = getClient().searchScroll(scrollRequest,RequestOptions.DEFAULT);
//// scrollId = searchResponse.getScrollId();
//// searchHit = searchResponse.getHits().getHits();
//// }
//
//// ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
//// clearScrollRequest.addScrollId(scrollId);
//// ClearScrollResponse clearScrollResponse = getClient().clearScroll(clearScrollRequest,RequestOptions.DEFAULT);
// }
// //System.out.println(JSON.toJSONString(list));
// Map<String, Object> result = new HashMap<String, Object>();
// result.put("list", list);
// result.put("total", total);
// return result;
// }
//
// public static void insert(String index,Map<String,Object> map) throws Exception{
// IndexRequest indexRequest = null;
// if (map.containsKey("_id")) {
// String _id = map.get("_id").toString();
// System.out.println("插入文档:"+index+" "+_id);
// map.remove("_id");
// indexRequest = new IndexRequest(index,"_doc",_id).source(map);
// }else{
// indexRequest = new IndexRequest(index).source(map);
// }
//
// IndexResponse indexResponse = getClient().index(indexRequest, RequestOptions.DEFAULT);
// //5、处理响应
// if(indexResponse != null) {
// if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
//// System.out.println("新增文档成功:"+JSON.toJSONString(map));
// } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
//// System.out.println("修改文档成功:"+JSON.toJSONString(map));
// }
// // 分片处理信息
// ReplicationResponse.ShardInfo shardInfo = indexResponse.getShardInfo();
// if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
//
// }
// // 如果有分片副本失败,可以获得失败原因信息
// if (shardInfo.getFailed() > 0) {
// for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
// String reason = failure.reason();
// System.out.println("副本失败原因:" + reason);
// }
// }
// }
// }
//
//
// public static void update(String index,String id,Map<String,Object> map) throws Exception{
// UpdateRequest request = new UpdateRequest(index, id).doc(map);
// UpdateResponse response = getClient().update(request, RequestOptions.DEFAULT);
// //5、处理响应
// if(response != null) {
// if (response.getResult() == DocWriteResponse.Result.CREATED) {
// System.out.println("新增文档成功,处理逻辑代码写到这里。");
// } else if (response.getResult() == DocWriteResponse.Result.UPDATED) {
// System.out.println("修改文档成功:"+id);
// }
// // 分片处理信息
// ReplicationResponse.ShardInfo shardInfo = response.getShardInfo();
// if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
//
// }
// // 如果有分片副本失败,可以获得失败原因信息
// if (shardInfo.getFailed() > 0) {
// for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
// String reason = failure.reason();
// System.out.println("副本失败原因:" + reason);
// }
// }
// }
// }
//
// /**
// * 根据ID获取文档
// * @param index
// * @param id
// * @return
// */
// public static Map<String, Object> getDocument(String index,String id) throws Exception{
// // 1、创建获取文档请求
// GetRequest request = new GetRequest(index,"_doc",id);
// //选择返回的字段
// String[] includes = new String[]{"*"};
// String[] excludes = Strings.EMPTY_ARRAY;
// FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);
// request.fetchSourceContext(fetchSourceContext);
//
// //3、发送请求
// GetResponse getResponse = null;
// try {
// // 同步请求
// getResponse = getClient().get(request,RequestOptions.DEFAULT);
// } catch (ElasticsearchException e) {
// if (e.status() == RestStatus.NOT_FOUND) {
// System.out.println("没有找到该id的文档" );
// }
// if (e.status() == RestStatus.CONFLICT) {
// System.out.println("获取时版本冲突了,请在此写冲突处理逻辑!" );
// }
// System.out.println("获取文档异常"+ e.getDetailedMessage());
// }
//
// //4、处理响应
// if(getResponse != null) {
// if (getResponse.isExists()) { // 文档存在
// String sourceAsString = getResponse.getSourceAsString(); //结果取成 String
// Map<String, Object> sourceAsMap = getResponse.getSourceAsMap(); // 结果取成Map
// System.out.println("获取文档:"+sourceAsString);
// return sourceAsMap;
// } else {
// System.out.println("没有找到该id的文档,index:"+index+" id:"+id );
// }
// }
// return null;
// }
//
//
// /**
// * 批量插入
// * @param index
// * @param list
// */
// public static void bulkInsert(String index,List<Map<String, Object>> list) throws Exception{
// BulkRequest request = new BulkRequest();
// for (Map<String, Object> map : list) {
// if (map.containsKey("_id")) {
// String _id = map.get("_id").toString();
// map.remove("_id");
// request.add(new IndexRequest(index,"_doc",_id).source(map));
// }else{
// request.add(new IndexRequest(index).source(map));
// }
//
// }
// BulkResponse bulkResponse = getClient().bulk(request, RequestOptions.DEFAULT);
// //4、处理响应
// if(bulkResponse != null) {
// for (BulkItemResponse bulkItemResponse : bulkResponse) {
// DocWriteResponse itemResponse = bulkItemResponse.getResponse();
// Failure failure = bulkItemResponse.getFailure();
// if (failure!=null) {
// System.out.println(failure.getMessage());
// }else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.INDEX|| bulkItemResponse.getOpType() == DocWriteRequest.OpType.CREATE) {
// IndexResponse indexResponse = (IndexResponse) itemResponse;
// //TODO 新增成功的处理
//
// } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.UPDATE) {
// UpdateResponse updateResponse = (UpdateResponse) itemResponse;
// //TODO 修改成功的处理
//
// } else if (bulkItemResponse.getOpType() == DocWriteRequest.OpType.DELETE) {
// DeleteResponse deleteResponse = (DeleteResponse) itemResponse;
// //TODO 删除成功的处理
// }
// }
// }
// }
//}
| 29,520 | 0.655588 | 0.649772 | 632 | 42.800632 | 33.599911 | 219 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.061709 | false | false | 11 |
65ef2c8af3727b9fe78c2ef44372a3514244a578 | 14,190,571,965,776 | a50812b83436a61c92df667c01880e9deda9504b | /src/main/java/com/projet/isidis/web/menusoap/MenusRequest.java | 627d75df0a6b785d5f3b835a11050bf031e97ee7 | [] | no_license | YANLINQU/projet_isidis | https://github.com/YANLINQU/projet_isidis | 231e6799b924833c688a16ec3d400ff608dfa223 | e41fcfd41f526497d0877670e6179ca949550d19 | refs/heads/master | 2021-05-13T22:51:06.629000 | 2018-03-29T21:12:19 | 2018-03-29T21:12:19 | 116,497,178 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.projet.isidis.web.menusoap;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>anonymous complex type\u7684 Java \u7c7b\u3002
*
* <p>\u4ee5\u4e0b\u6a21\u5f0f\u7247\u6bb5\u6307\u5b9a\u5305\u542b\u5728\u6b64\u7c7b\u4e2d\u7684\u9884\u671f\u5185\u5bb9\u3002
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="id_table" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"idTable"
})
@XmlRootElement(name = "MenusRequest", namespace = "http://iaws/resto/menus/projet")
public class MenusRequest {
@XmlElement(name = "id_table", namespace = "http://iaws/resto/menus/projet", required = true)
protected String idTable;
/**
* \u83b7\u53d6idTable\u5c5e\u6027\u7684\u503c\u3002
*
* @return
* possible object is
* {@link String }
*
*/
public String getIdTable() {
return idTable;
}
/**
* \u8bbe\u7f6eidTable\u5c5e\u6027\u7684\u503c\u3002
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIdTable(String value) {
this.idTable = value;
}
}
| UTF-8 | Java | 1,639 | java | MenusRequest.java | Java | [] | null | [] |
package com.projet.isidis.web.menusoap;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>anonymous complex type\u7684 Java \u7c7b\u3002
*
* <p>\u4ee5\u4e0b\u6a21\u5f0f\u7247\u6bb5\u6307\u5b9a\u5305\u542b\u5728\u6b64\u7c7b\u4e2d\u7684\u9884\u671f\u5185\u5bb9\u3002
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="id_table" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"idTable"
})
@XmlRootElement(name = "MenusRequest", namespace = "http://iaws/resto/menus/projet")
public class MenusRequest {
@XmlElement(name = "id_table", namespace = "http://iaws/resto/menus/projet", required = true)
protected String idTable;
/**
* \u83b7\u53d6idTable\u5c5e\u6027\u7684\u503c\u3002
*
* @return
* possible object is
* {@link String }
*
*/
public String getIdTable() {
return idTable;
}
/**
* \u8bbe\u7f6eidTable\u5c5e\u6027\u7684\u503c\u3002
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIdTable(String value) {
this.idTable = value;
}
}
| 1,639 | 0.635143 | 0.560098 | 63 | 25 | 26.171595 | 126 | false | false | 0 | 0 | 120 | 0.109823 | 0 | 0 | 0.349206 | false | false | 11 |
54f7406d593cbb13e1d808a71d56e45113840ca8 | 627,065,255,902 | 42838074a1b1e29f48a257b9b0afeadd3d830be0 | /core/src/com/mayhem/overlay/IActionAcknowledgmentListner.java | c9139f1620c6ebd1d0f1a231f867e063126fc9aa | [] | no_license | dreadnought303/MajorMayhem | https://github.com/dreadnought303/MajorMayhem | a86c8eef3afca4342fd3fbe9f9e69bdd48fa965c | 8c2b0c90ef0ecb62fd6c26e6c0fa868d4c9a9dad | refs/heads/master | 2020-05-30T15:04:09.955000 | 2014-08-31T20:38:12 | 2014-08-31T20:38:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mayhem.overlay;
public interface IActionAcknowledgmentListner {
public void acknowledgmentReceived(long messageid, Object result);
}
| UTF-8 | Java | 147 | java | IActionAcknowledgmentListner.java | Java | [] | null | [] | package com.mayhem.overlay;
public interface IActionAcknowledgmentListner {
public void acknowledgmentReceived(long messageid, Object result);
}
| 147 | 0.836735 | 0.836735 | 5 | 28.4 | 26.058395 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 11 |
619dea48d5cb4c7890295858e055c25e7ae49222 | 33,303,176,467,871 | 5f3e14720140eae3bcd517b2b56813e54f5ba7f3 | /src/main/java/com/ailtonluiz/erpapi/api/disassembler/GroupInputDisassembler.java | 3cb46fe7cec9b6382991b4aac0571d2747d683ff | [] | no_license | ailtonluiz/erp-api | https://github.com/ailtonluiz/erp-api | b5a9b4266898b58df69c39f18cb93d38fea579ce | 913bf1399a2562941709f0c3114b1bf070fb1fde | refs/heads/master | 2023-08-21T10:57:23.634000 | 2021-10-15T19:34:18 | 2021-10-15T19:34:18 | 416,838,474 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ailtonluiz.erpapi.api.disassembler;
import com.ailtonluiz.erpapi.api.model.input.GroupInput;
import com.ailtonluiz.erpapi.domain.model.Group;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class GroupInputDisassembler {
@Autowired
private ModelMapper modelMapper;
public Group toDomainObject(GroupInput groupInput) {
return modelMapper.map(groupInput, Group.class);
}
public void copyToDomainObject(GroupInput groupInput, Group group) {
modelMapper.map(groupInput, group);
}
} | UTF-8 | Java | 653 | java | GroupInputDisassembler.java | Java | [] | null | [] | package com.ailtonluiz.erpapi.api.disassembler;
import com.ailtonluiz.erpapi.api.model.input.GroupInput;
import com.ailtonluiz.erpapi.domain.model.Group;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class GroupInputDisassembler {
@Autowired
private ModelMapper modelMapper;
public Group toDomainObject(GroupInput groupInput) {
return modelMapper.map(groupInput, Group.class);
}
public void copyToDomainObject(GroupInput groupInput, Group group) {
modelMapper.map(groupInput, group);
}
} | 653 | 0.782542 | 0.782542 | 23 | 27.434782 | 24.696112 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false | 11 |
99f77b76dc937bbca7c1c76002725bc7b0ae4100 | 33,303,176,468,956 | 3b0d03e1d84aa22d0c3f99547742a282ffe535c1 | /app/src/main/java/jp/faraopro/play/frg/mode/LoginSelectFragment.java | 04631e0be9cfc3a59f93d086d4631c4d2c246ecc | [] | no_license | faith-masui/FaRaoPRO_kotlin | https://github.com/faith-masui/FaRaoPRO_kotlin | 03c5660286b1891448783efe66472ea4618986eb | c898be80e5f6b61c45cf17d6380c064c5908c3c0 | refs/heads/master | 2020-04-01T22:10:54.727000 | 2018-10-18T23:17:10 | 2018-10-18T23:17:10 | 153,695,844 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jp.faraopro.play.frg.mode;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import jp.faraopro.play.R;
import jp.faraopro.play.act.newone.BaseActivity;
import jp.faraopro.play.act.newone.BootActivity;
import jp.faraopro.play.act.newone.LoginActivity;
import jp.faraopro.play.app.FROForm;
import jp.faraopro.play.common.Flavor;
import jp.faraopro.play.common.LocationHelper;
import jp.faraopro.play.common.TextChecker;
import jp.faraopro.play.mclient.MCDefParam;
import jp.faraopro.play.mclient.MCUserInfoPreference;
/**
*
* @author Aim タイトルバー
*/
public class LoginSelectFragment extends Fragment implements TextWatcher {
/** dialog tags **/
private static final int DIALOG_INVALID_PASS = 100;
/** view **/
private Button btnLogin;
private EditText edtEmail;
private EditText edtPassword;
/** member **/
String email;
String password;
public static LoginSelectFragment newInstance() {
LoginSelectFragment instance = new LoginSelectFragment();
return instance;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_frg_login_select, container, false);
initViews(view);
return view;
}
// Viewの初期化(参照取得、イベント設定など)
@SuppressLint("SetJavaScriptEnabled")
private void initViews(View view) {
Bundle args = getArguments();
if (args != null) {
}
btnLogin = (Button) view.findViewById(R.id.login_btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!LocationHelper.isEnableProvider(getActivity())) {
((BaseActivity) getActivity()).showNegativeDialog(R.string.msg_logout_failed_location,
LoginActivity.DIALOG_TAG_GOTO_SETTING_FOR_LOCATION, -1, true);
return;
}
email = edtEmail.getText().toString();
password = edtPassword.getText().toString();
String errorMsg = null;
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
errorMsg = getString(R.string.msg_input_all_fields);
} else if (TextChecker.CheckType(password, 7) != 0 || !TextChecker.CheckAppearance(password)
|| !TextChecker.CheckLength(password, 6, 16)) {
errorMsg = getString(R.string.msg_invalid_password);
}
if (errorMsg == null) {
((BaseActivity) getActivity()).showProgress();
FROForm.getInstance().login(email, password, MCDefParam.MCP_PARAM_STR_NO);
} else {
((BaseActivity) getActivity()).showPositiveDialog(errorMsg, DIALOG_INVALID_PASS, true);
}
}
});
edtEmail = (EditText) view.findViewById(R.id.login_edt_email);
edtPassword = (EditText) view.findViewById(R.id.login_edt_password);
if (Flavor.DEVELOPER_MODE) {
edtEmail.setText("f1000.302@biz.faraoradio.jp");
edtPassword.setText("qwe123");
}
String email;
String password;
try {
email = FROForm.getInstance().getPreferenceString(MCUserInfoPreference.STRING_DATA_MAIL);
password = FROForm.getInstance().getPreferenceString(MCUserInfoPreference.STRING_DATA_PASS);
} catch (Exception e) {
((BaseActivity) getActivity()).startActivity(BootActivity.class, true);
return;
}
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
edtEmail.setText(email);
edtPassword.setText(password);
}
}
public String getEmail() {
return email;
}
public String getPass() {
return password;
}
private boolean checkEmpty() {
boolean isEmpty = true;
String mail = edtEmail.getText().toString();
String pass = edtPassword.getText().toString();
if (!TextUtils.isEmpty(mail) && !TextUtils.isEmpty(pass))
isEmpty = false;
return isEmpty;
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
btnLogin.setEnabled(!checkEmpty());
}
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
}
| UTF-8 | Java | 4,677 | java | LoginSelectFragment.java | Java | [
{
"context": "ient.MCUserInfoPreference;\r\n\r\n/**\r\n * \r\n * @author Aim タイトルバー\r\n */\r\npublic class LoginSelectFragment extends Frag",
"end": 889,
"score": 0.9552031755447388,
"start": 879,
"tag": "NAME",
"value": "Aim タイトルバー"
},
{
"context": ".DEVELOPER_MODE) {\r\n ... | null | [] | package jp.faraopro.play.frg.mode;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import jp.faraopro.play.R;
import jp.faraopro.play.act.newone.BaseActivity;
import jp.faraopro.play.act.newone.BootActivity;
import jp.faraopro.play.act.newone.LoginActivity;
import jp.faraopro.play.app.FROForm;
import jp.faraopro.play.common.Flavor;
import jp.faraopro.play.common.LocationHelper;
import jp.faraopro.play.common.TextChecker;
import jp.faraopro.play.mclient.MCDefParam;
import jp.faraopro.play.mclient.MCUserInfoPreference;
/**
*
* @author <NAME>
*/
public class LoginSelectFragment extends Fragment implements TextWatcher {
/** dialog tags **/
private static final int DIALOG_INVALID_PASS = 100;
/** view **/
private Button btnLogin;
private EditText edtEmail;
private EditText edtPassword;
/** member **/
String email;
String password;
public static LoginSelectFragment newInstance() {
LoginSelectFragment instance = new LoginSelectFragment();
return instance;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_frg_login_select, container, false);
initViews(view);
return view;
}
// Viewの初期化(参照取得、イベント設定など)
@SuppressLint("SetJavaScriptEnabled")
private void initViews(View view) {
Bundle args = getArguments();
if (args != null) {
}
btnLogin = (Button) view.findViewById(R.id.login_btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!LocationHelper.isEnableProvider(getActivity())) {
((BaseActivity) getActivity()).showNegativeDialog(R.string.msg_logout_failed_location,
LoginActivity.DIALOG_TAG_GOTO_SETTING_FOR_LOCATION, -1, true);
return;
}
email = edtEmail.getText().toString();
password = edtPassword.getText().toString();
String errorMsg = null;
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
errorMsg = getString(R.string.msg_input_all_fields);
} else if (TextChecker.CheckType(password, 7) != 0 || !TextChecker.CheckAppearance(password)
|| !TextChecker.CheckLength(password, 6, 16)) {
errorMsg = getString(R.string.msg_invalid_password);
}
if (errorMsg == null) {
((BaseActivity) getActivity()).showProgress();
FROForm.getInstance().login(email, password, MCDefParam.MCP_PARAM_STR_NO);
} else {
((BaseActivity) getActivity()).showPositiveDialog(errorMsg, DIALOG_INVALID_PASS, true);
}
}
});
edtEmail = (EditText) view.findViewById(R.id.login_edt_email);
edtPassword = (EditText) view.findViewById(R.id.login_edt_password);
if (Flavor.DEVELOPER_MODE) {
edtEmail.setText("<EMAIL>");
edtPassword.setText("<PASSWORD>");
}
String email;
String password;
try {
email = FROForm.getInstance().getPreferenceString(MCUserInfoPreference.STRING_DATA_MAIL);
password = FROForm.getInstance().getPreferenceString(MCUserInfoPreference.STRING_DATA_PASS);
} catch (Exception e) {
((BaseActivity) getActivity()).startActivity(BootActivity.class, true);
return;
}
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
edtEmail.setText(email);
edtPassword.setText(password);
}
}
public String getEmail() {
return email;
}
public String getPass() {
return password;
}
private boolean checkEmpty() {
boolean isEmpty = true;
String mail = edtEmail.getText().toString();
String pass = edtPassword.getText().toString();
if (!TextUtils.isEmpty(mail) && !TextUtils.isEmpty(pass))
isEmpty = false;
return isEmpty;
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
btnLogin.setEnabled(!checkEmpty());
}
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
}
| 4,645 | 0.689052 | 0.683654 | 150 | 28.873333 | 26.724344 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.833333 | false | false | 11 |
7dd30d6df2456a684942c5251d03cd30e83f1d37 | 21,242,908,267,790 | f7b6ef06c7fee4985e8bba5edce208b3af0c13ab | /server/jeecg/sdk-jeecg/src/jeecg/ext/sdk/entity/SdkOutChannelDetail.java | b4073a00517a35d6f7563281e089af0f3c20cd5a | [] | no_license | iNarcissuss/bird_pay_sdk | https://github.com/iNarcissuss/bird_pay_sdk | 4d2bc9f4e9b11e4524c36fd3925f836e81ecf6d2 | 22bbcd36b72b2a125a92023039e6958647cca977 | refs/heads/master | 2021-01-15T09:56:33.799000 | 2016-06-26T13:54:09 | 2016-06-26T13:54:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jeecg.ext.sdk.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* SdkOutChannelDetail entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "sdk_out_channel_detail", catalog = "game_sdk")
public class SdkOutChannelDetail implements java.io.Serializable {
// Fields
private Integer id;
private SdkOutChannel sdkOutChannel;
private Timestamp inputTime;
private Integer regNumber;
private Timestamp createTime;
// Constructors
/** default constructor */
public SdkOutChannelDetail() {
}
/** full constructor */
public SdkOutChannelDetail(SdkOutChannel sdkOutChannel,
Timestamp inputTime, Integer regNumber, Timestamp createTime) {
this.sdkOutChannel = sdkOutChannel;
this.inputTime = inputTime;
this.regNumber = regNumber;
this.createTime = createTime;
}
// Property accessors
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "channel_id", nullable = false)
public SdkOutChannel getSdkOutChannel() {
return this.sdkOutChannel;
}
public void setSdkOutChannel(SdkOutChannel sdkOutChannel) {
this.sdkOutChannel = sdkOutChannel;
}
@Column(name = "input_time", nullable = false, length = 19)
public Timestamp getInputTime() {
return this.inputTime;
}
public void setInputTime(Timestamp inputTime) {
this.inputTime = inputTime;
}
@Column(name = "reg_number", nullable = false)
public Integer getRegNumber() {
return this.regNumber;
}
public void setRegNumber(Integer regNumber) {
this.regNumber = regNumber;
}
@Column(name = "create_time", nullable = false, length = 19)
public Timestamp getCreateTime() {
return this.createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
} | UTF-8 | Java | 2,236 | java | SdkOutChannelDetail.java | Java | [] | null | [] | package jeecg.ext.sdk.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* SdkOutChannelDetail entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "sdk_out_channel_detail", catalog = "game_sdk")
public class SdkOutChannelDetail implements java.io.Serializable {
// Fields
private Integer id;
private SdkOutChannel sdkOutChannel;
private Timestamp inputTime;
private Integer regNumber;
private Timestamp createTime;
// Constructors
/** default constructor */
public SdkOutChannelDetail() {
}
/** full constructor */
public SdkOutChannelDetail(SdkOutChannel sdkOutChannel,
Timestamp inputTime, Integer regNumber, Timestamp createTime) {
this.sdkOutChannel = sdkOutChannel;
this.inputTime = inputTime;
this.regNumber = regNumber;
this.createTime = createTime;
}
// Property accessors
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "channel_id", nullable = false)
public SdkOutChannel getSdkOutChannel() {
return this.sdkOutChannel;
}
public void setSdkOutChannel(SdkOutChannel sdkOutChannel) {
this.sdkOutChannel = sdkOutChannel;
}
@Column(name = "input_time", nullable = false, length = 19)
public Timestamp getInputTime() {
return this.inputTime;
}
public void setInputTime(Timestamp inputTime) {
this.inputTime = inputTime;
}
@Column(name = "reg_number", nullable = false)
public Integer getRegNumber() {
return this.regNumber;
}
public void setRegNumber(Integer regNumber) {
this.regNumber = regNumber;
}
@Column(name = "create_time", nullable = false, length = 19)
public Timestamp getCreateTime() {
return this.createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
} | 2,236 | 0.753131 | 0.751342 | 93 | 23.053764 | 20.172571 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.236559 | false | false | 11 |
10f982e7dc153817aaacd2574411e62327932960 | 12,670,153,555,695 | aa5245a21140bd1858c58a2310f59667a986f53e | /src/main/java/ru/parsentev/task_004/IsoscelesTriangle.java | a9ff3ddaafccc43aeb3ebaa4fb519797a213202f | [
"MIT"
] | permissive | CargiMan/course_test | https://github.com/CargiMan/course_test | 12a7b408bc4f683e5f903e04bfe814e3dc301e3a | 2211624434fefc0aaede4e642e75d841207f8853 | refs/heads/master | 2020-05-20T19:32:06.655000 | 2017-02-08T17:46:08 | 2017-02-08T17:46:08 | 66,152,027 | 0 | 0 | null | true | 2016-08-20T14:51:52 | 2016-08-20T14:51:51 | 2016-08-20T14:51:52 | 2016-07-30T12:16:04 | 41 | 0 | 0 | 0 | Java | null | null | package ru.parsentev.task_004;
import org.slf4j.Logger;
import ru.parsentev.task_002.Point;
import ru.parsentev.task_003.Triangle;
import static org.slf4j.LoggerFactory.getLogger;
/**
* TODO: comment
*
* @author parsentev
* @since 28.07.2016
*/
public class IsoscelesTriangle extends Triangle {
private static final Logger log = getLogger(IsoscelesTriangle.class);
public IsoscelesTriangle(Point first, Point second, Point third) {
super(first, second, third);
}
@Override
public boolean exists() {
double sideA = first.distanceTo(second);
double sideB = second.distanceTo(third);
double sideC = third.distanceTo(first);
if (super.exists()) {
if (sideA == sideB || sideB == sideC || sideC == sideA) {
return true;
} else {
throw new IllegalStateException();
}
}
return super.exists();
}
}
| UTF-8 | Java | 947 | java | IsoscelesTriangle.java | Java | [
{
"context": "ory.getLogger;\n\n/**\n * TODO: comment\n *\n * @author parsentev\n * @since 28.07.2016\n */\npublic class IsoscelesTr",
"end": 227,
"score": 0.996942937374115,
"start": 218,
"tag": "USERNAME",
"value": "parsentev"
}
] | null | [] | package ru.parsentev.task_004;
import org.slf4j.Logger;
import ru.parsentev.task_002.Point;
import ru.parsentev.task_003.Triangle;
import static org.slf4j.LoggerFactory.getLogger;
/**
* TODO: comment
*
* @author parsentev
* @since 28.07.2016
*/
public class IsoscelesTriangle extends Triangle {
private static final Logger log = getLogger(IsoscelesTriangle.class);
public IsoscelesTriangle(Point first, Point second, Point third) {
super(first, second, third);
}
@Override
public boolean exists() {
double sideA = first.distanceTo(second);
double sideB = second.distanceTo(third);
double sideC = third.distanceTo(first);
if (super.exists()) {
if (sideA == sideB || sideB == sideC || sideC == sideA) {
return true;
} else {
throw new IllegalStateException();
}
}
return super.exists();
}
}
| 947 | 0.62302 | 0.602957 | 36 | 25.305555 | 21.546873 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 11 |
209e04cc53cca1ee84e06a0ce051cc04e4dc69ec | 10,153,302,745,014 | aad9b37436cc8655f95f227d887941d6dc4b8a7d | /beanpod-as/src/main/java/org/beanpod/auth/service/impl/UserService.java | 4d020b8923119254ac19f24831dc4e5ad4f2bb2d | [] | no_license | ChenBravery/beanpod | https://github.com/ChenBravery/beanpod | ab2b8b46cde941e6a5041d86922b9a4d49dabb88 | 37b68ccbd239c1e5d135daed6b2db1f2f1d3b426 | refs/heads/master | 2021-04-26T08:55:40.679000 | 2017-10-16T16:05:57 | 2017-10-16T16:05:57 | 106,944,138 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.beanpod.auth.service.impl;
import java.util.List;
import org.beanpod.auth.entity.User;
import org.beanpod.auth.dao.mapper.IUserDao;
import org.beanpod.auth.msg.user.UserListReq;
import org.beanpod.auth.msg.user.UserListResp;
import org.beanpod.auth.msg.user.UserResp;
import org.beanpod.auth.service.IUserService;
import org.beanpod.common.msg.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.java.Log;
@Service
@Log
public class UserService implements IUserService {
@Autowired
private IUserDao userDao;
public UserListResp getUserList ( UserListReq req ) {
UserListResp resp = new UserListResp();
User user = req.getParam();
if(user == null){
user = new User();
}
PageParam pageParam = req.getPageParam();
List<User> userList = null;
if(pageParam == null) {
//pageParam = new PageParam(1, 10);
pageParam = new PageParam();
}else{
if(pageParam.getPageNum() <= 0){
pageParam.setPageNum(1);
}
if(pageParam.getPageSize() <= 0){
pageParam.setPageSize(10);
}
}
PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
userList = userDao.selectList(user);
PageInfo<User> pageInfo = new PageInfo<User>(userList);
resp.setPageInfo(pageInfo);
resp.setData(userList);
log.info("getUserList, resp:" + resp.toString());
return resp;
}
public UserResp getUser ( String id ){
UserResp resp = new UserResp();
User user = userDao.selectById(id);
resp.setData(user);
return resp;
}
}
| UTF-8 | Java | 1,759 | java | UserService.java | Java | [] | null | [] | package org.beanpod.auth.service.impl;
import java.util.List;
import org.beanpod.auth.entity.User;
import org.beanpod.auth.dao.mapper.IUserDao;
import org.beanpod.auth.msg.user.UserListReq;
import org.beanpod.auth.msg.user.UserListResp;
import org.beanpod.auth.msg.user.UserResp;
import org.beanpod.auth.service.IUserService;
import org.beanpod.common.msg.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.java.Log;
@Service
@Log
public class UserService implements IUserService {
@Autowired
private IUserDao userDao;
public UserListResp getUserList ( UserListReq req ) {
UserListResp resp = new UserListResp();
User user = req.getParam();
if(user == null){
user = new User();
}
PageParam pageParam = req.getPageParam();
List<User> userList = null;
if(pageParam == null) {
//pageParam = new PageParam(1, 10);
pageParam = new PageParam();
}else{
if(pageParam.getPageNum() <= 0){
pageParam.setPageNum(1);
}
if(pageParam.getPageSize() <= 0){
pageParam.setPageSize(10);
}
}
PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
userList = userDao.selectList(user);
PageInfo<User> pageInfo = new PageInfo<User>(userList);
resp.setPageInfo(pageInfo);
resp.setData(userList);
log.info("getUserList, resp:" + resp.toString());
return resp;
}
public UserResp getUser ( String id ){
UserResp resp = new UserResp();
User user = userDao.selectById(id);
resp.setData(user);
return resp;
}
}
| 1,759 | 0.690165 | 0.685617 | 69 | 23.492754 | 19.350784 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.811594 | false | false | 11 |
105a6d39fce8e8e1b1fbfa2ed977e9fe364d2853 | 12,034,498,412,833 | 29f4101abc7603f5b020bae2d9fa8b88eef2906b | /backend/src/main/java/com/example/demo/repositories/TagNoteConnectionRepository.java | ecb904190037c26a0b11c4c44e411c6b7d9144b2 | [] | no_license | BartoszWilkk/Notatnix | https://github.com/BartoszWilkk/Notatnix | 42d094e20b66ca31457264bf76799706dffebda9 | 9049cd55f6df11b9537e326f09a4b2f590fba268 | refs/heads/master | 2023-02-02T12:53:23.294000 | 2020-06-14T23:49:43 | 2020-06-14T23:49:43 | 247,717,933 | 0 | 0 | null | false | 2023-01-07T16:14:32 | 2020-03-16T14:04:16 | 2020-06-14T23:51:42 | 2023-01-07T16:14:32 | 4,081 | 0 | 0 | 25 | Java | false | false | package com.example.demo.repositories;
import com.example.demo.composite.keys.TagNoteConnectionId;
import com.example.demo.entities.TagNoteConnectionEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import javax.transaction.Transactional;
import java.util.List;
public interface TagNoteConnectionRepository extends JpaRepository<TagNoteConnectionEntity, TagNoteConnectionId> {
List<TagNoteConnectionEntity> findAllByTagNoteConnectionId_NoteId(Long noteId);
List<TagNoteConnectionEntity> findAllByTagNoteConnectionId_TagId(Long tagId);
@Transactional
void deleteAllByTagNoteConnectionId_NoteId(Long noteId);
}
| UTF-8 | Java | 648 | java | TagNoteConnectionRepository.java | Java | [] | null | [] | package com.example.demo.repositories;
import com.example.demo.composite.keys.TagNoteConnectionId;
import com.example.demo.entities.TagNoteConnectionEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import javax.transaction.Transactional;
import java.util.List;
public interface TagNoteConnectionRepository extends JpaRepository<TagNoteConnectionEntity, TagNoteConnectionId> {
List<TagNoteConnectionEntity> findAllByTagNoteConnectionId_NoteId(Long noteId);
List<TagNoteConnectionEntity> findAllByTagNoteConnectionId_TagId(Long tagId);
@Transactional
void deleteAllByTagNoteConnectionId_NoteId(Long noteId);
}
| 648 | 0.848765 | 0.848765 | 15 | 42.200001 | 34.213448 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 11 |
c507370bf2d86b234f9defb694ef505047109414 | 12,034,498,416,192 | b831dccf86c0799cc385e7e733969d0db6e93716 | /src/main/java/com/salesforce/iblockedu/IBlockedU/controllers/IBlockedUAdminController.java | 9debb60c13ce7be5bdc89c35471aad92c8962a18 | [] | no_license | kobyperets/i-blocked-u | https://github.com/kobyperets/i-blocked-u | 2be12f76779bae3df5774af0a7dfe49642897920 | ce91a16aeaf5a0dc2a958c3db167eb5be90430e9 | refs/heads/master | 2021-09-03T09:51:40.659000 | 2018-01-08T05:59:09 | 2018-01-08T05:59:09 | 111,665,449 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.salesforce.iblockedu.IBlockedU.controllers;
import com.salesforce.iblockedu.IBlockedU.dal.CarsDal;
import com.salesforce.iblockedu.IBlockedU.logic.BlocksLogic;
import com.salesforce.iblockedu.IBlockedU.logic.UsersLogic;
import com.salesforce.iblockedu.IBlockedU.model.Block;
import com.salesforce.iblockedu.IBlockedU.model.Car;
import com.salesforce.iblockedu.IBlockedU.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by doron.levi on 29/11/2017.
*/
@RestController
@RequestMapping("/iblockedu/ui")
public class IBlockedUAdminController {
@Autowired
UsersLogic usersLogic;
@Autowired
CarsDal carsDal;
@Autowired
BlocksLogic blocksLogic;
@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<User> users() {
return usersLogic.getAllUsers(true);
}
@RequestMapping(value = "/emails", method = RequestMethod.GET)
public List<String> emails() {
return usersLogic.getAllUsers(true).stream().map(User::getEmail).collect(Collectors.toList());
}
@RequestMapping(value = "/cars", method = RequestMethod.GET)
public List<Car> cars() {
return carsDal.getAllCars();
}
@RequestMapping(value = "/blocks", method = RequestMethod.GET)
public List<Block> blocks() {
return blocksLogic.getAllBlocks(true);
}
@RequestMapping(value = "/users/add", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void addUser(@RequestBody User user) {
usersLogic.addUser(user);
}
@RequestMapping(value = "/cars/add", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void addCar(@RequestBody Car car) {
carsDal.createCar(car);
}
}
| UTF-8 | Java | 1,868 | java | IBlockedUAdminController.java | Java | [
{
"context": "rt java.util.stream.Collectors;\n\n/**\n * Created by doron.levi on 29/11/2017.\n */\n\n@RestController\n@RequestMappi",
"end": 641,
"score": 0.9791904091835022,
"start": 631,
"tag": "USERNAME",
"value": "doron.levi"
}
] | null | [] | package com.salesforce.iblockedu.IBlockedU.controllers;
import com.salesforce.iblockedu.IBlockedU.dal.CarsDal;
import com.salesforce.iblockedu.IBlockedU.logic.BlocksLogic;
import com.salesforce.iblockedu.IBlockedU.logic.UsersLogic;
import com.salesforce.iblockedu.IBlockedU.model.Block;
import com.salesforce.iblockedu.IBlockedU.model.Car;
import com.salesforce.iblockedu.IBlockedU.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by doron.levi on 29/11/2017.
*/
@RestController
@RequestMapping("/iblockedu/ui")
public class IBlockedUAdminController {
@Autowired
UsersLogic usersLogic;
@Autowired
CarsDal carsDal;
@Autowired
BlocksLogic blocksLogic;
@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<User> users() {
return usersLogic.getAllUsers(true);
}
@RequestMapping(value = "/emails", method = RequestMethod.GET)
public List<String> emails() {
return usersLogic.getAllUsers(true).stream().map(User::getEmail).collect(Collectors.toList());
}
@RequestMapping(value = "/cars", method = RequestMethod.GET)
public List<Car> cars() {
return carsDal.getAllCars();
}
@RequestMapping(value = "/blocks", method = RequestMethod.GET)
public List<Block> blocks() {
return blocksLogic.getAllBlocks(true);
}
@RequestMapping(value = "/users/add", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void addUser(@RequestBody User user) {
usersLogic.addUser(user);
}
@RequestMapping(value = "/cars/add", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void addCar(@RequestBody Car car) {
carsDal.createCar(car);
}
}
| 1,868 | 0.745182 | 0.740899 | 74 | 24.243244 | 24.9382 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.364865 | false | false | 11 |
6ba1edd2ca530fd517a2b5176e9438c1528fac51 | 21,938,692,955,039 | 4d6b0ba23239f9a49c1219c29ca15dee62553195 | /src/test/java/MyService.java | a8c5bc7d82e5003038c9c4af9bf1f58756567783 | [] | no_license | Ohrimenko1988/quice_tutorial | https://github.com/Ohrimenko1988/quice_tutorial | 72951383dcb3d4132a834d0f04fb414124855eed | eeecb75811c82ff38d9396b5d79081c30f5e9f21 | refs/heads/master | 2020-03-21T00:41:00.110000 | 2019-08-14T13:20:45 | 2019-08-14T13:20:45 | 137,904,882 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import com.google.inject.Inject;
import com.google.inject.Singleton;
import test_interface.TestInterface;
@Singleton
public class MyService {
private TestInterface testInterface;
@Inject
MyService(TestInterface testInterface){
this.testInterface = testInterface;
}
public void doSomething(){
testInterface.doSomething();
}
}
| UTF-8 | Java | 350 | java | MyService.java | Java | [] | null | [] | import com.google.inject.Inject;
import com.google.inject.Singleton;
import test_interface.TestInterface;
@Singleton
public class MyService {
private TestInterface testInterface;
@Inject
MyService(TestInterface testInterface){
this.testInterface = testInterface;
}
public void doSomething(){
testInterface.doSomething();
}
}
| 350 | 0.762857 | 0.762857 | 19 | 17.421053 | 16.236139 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false | 11 |
1578bc98fccff5fbdfd621448d8ebe09d5aec40e | 29,403,346,169,326 | a147c2a566a1c9fc12330da0f5b4313af8894f67 | /app/src/test/java/com/example/shanesardinha/codeproject/Activity/DetailSongActivityTest.java | bc164a2d6d517943961246acfe97db23ec7b0e25 | [] | no_license | creed6312/CodeProject | https://github.com/creed6312/CodeProject | 3bb8831b14f0fca131b62e73a3e2f5fad2a9e3a0 | 92b17fe3f9ff393b2de802c379717bea70e74599 | refs/heads/master | 2021-01-20T17:26:45.992000 | 2016-08-16T09:56:00 | 2016-08-16T09:56:00 | 65,184,490 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.shanesardinha.codeproject.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.shanesardinha.codeproject.BuildConfig;
import com.example.shanesardinha.codeproject.DetailSongActivity;
import com.example.shanesardinha.codeproject.Interfaces.IArtistPresenter;
import com.example.shanesardinha.codeproject.Interfaces.IDetailSongPresenter;
import com.example.shanesardinha.codeproject.Presenters.ArtistPresenter;
import com.example.shanesardinha.codeproject.Presenters.DetailSongPresenter;
import com.example.shanesardinha.codeproject.R;
import com.example.shanesardinha.codeproject.TestHelpers.CustomRobolectricRunner;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.robolectric.Robolectric;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by shanesardinha on 2016/08/11.
*/
@RunWith(CustomRobolectricRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class DetailSongActivityTest {
private DetailSongActivity mDetailSongActivity;
private static TextView tvDetailName;
private static TextView tvDetailArtist;
private static TextView tvDetailDuration;
private static TextView tvDetailListeners;
private static TextView tvDetailPlayCount;
private static TextView tvDetailSongUrl;
private static TextView tvDetailWikiPublished;
private static TextView tvDetailWikiSummary;
private static TextView tvOnTour;
private static ImageView ivDetailImage;
private static LinearLayout llTopTag;
@Before
public void setUp() throws Exception {
// Use the debug configuration
ReflectionHelpers.setStaticField(BuildConfig.class, "DEBUG", true);
Intent intent = new Intent();
// Build the Activity
Bundle savedInstanceState = new Bundle();
mDetailSongActivity = Robolectric.buildActivity(DetailSongActivity.class)
.withIntent(intent)
.create(savedInstanceState)
.start()
.resume()
.pause()
.destroy()
.visible()
.get();
}
@Test
public void test_ActivityStarted() {
assertNotNull("mDetailSongActivity is null", mDetailSongActivity);
assertThat(mDetailSongActivity.getClass().getSimpleName()).isEqualTo(DetailSongActivity.class.getSimpleName());
}
@Test
public void test_DetailSongPresenterTag() {
IDetailSongPresenter detailSongPresenter = new DetailSongPresenter(mDetailSongActivity);
assertEquals("DetailSongPresenter", detailSongPresenter.getRequestPresenter());
}
@Test
public void test_ArtistPresenterTag() {
DetailSongPresenter detailSongPresenter = new DetailSongPresenter(mDetailSongActivity);
IArtistPresenter artistPresenter = new ArtistPresenter(detailSongPresenter);
assertEquals("ArtistPresenter", artistPresenter.getRequestPresenter());
}
@Test
public void test_a_InitialiseControls() {
tvDetailName = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_name);
tvDetailArtist = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_artist);
tvDetailDuration = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_duration);
ivDetailImage = (ImageView) mDetailSongActivity.findViewById(R.id.iv_detail_image);
tvDetailListeners = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_listeners);
tvDetailPlayCount = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_play_count);
tvDetailSongUrl = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_url);
tvDetailWikiPublished = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_wiki_published);
tvDetailWikiSummary = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_wiki_summary);
tvOnTour = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_on_tour);
llTopTag = (LinearLayout) mDetailSongActivity.findViewById(R.id.song_detail_tag_layout);
}
@Test
public void test_b_CheckControls() {
assertNotNull("tvDetailName is null", tvDetailName);
assertNotNull("tvDetailArtist is null", tvDetailArtist);
assertNotNull("tvDetailDuration is null", tvDetailDuration);
assertNotNull("ivDetailImage is null", ivDetailImage);
assertNotNull("tvDetailListeners is null", tvDetailListeners);
assertNotNull("tvDetailPlayCount is null", tvDetailPlayCount);
assertNotNull("tvDetailSongUrl is null", tvDetailSongUrl);
assertNotNull("tvDetailWikiPublished is null", tvDetailWikiPublished);
assertNotNull("tvDetailWikiSummary is null", tvDetailWikiSummary);
assertNotNull("tvOnTour is null", tvOnTour);
assertNotNull("llTopTag is null", llTopTag);
}
} | UTF-8 | Java | 5,331 | java | DetailSongActivityTest.java | Java | [
{
"context": "core.api.Assertions.assertThat;\n\n/**\n * Created by shanesardinha on 2016/08/11.\n */\n@RunWith(CustomRobolectricRunn",
"end": 1245,
"score": 0.996860682964325,
"start": 1232,
"tag": "USERNAME",
"value": "shanesardinha"
}
] | null | [] | package com.example.shanesardinha.codeproject.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.shanesardinha.codeproject.BuildConfig;
import com.example.shanesardinha.codeproject.DetailSongActivity;
import com.example.shanesardinha.codeproject.Interfaces.IArtistPresenter;
import com.example.shanesardinha.codeproject.Interfaces.IDetailSongPresenter;
import com.example.shanesardinha.codeproject.Presenters.ArtistPresenter;
import com.example.shanesardinha.codeproject.Presenters.DetailSongPresenter;
import com.example.shanesardinha.codeproject.R;
import com.example.shanesardinha.codeproject.TestHelpers.CustomRobolectricRunner;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.robolectric.Robolectric;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by shanesardinha on 2016/08/11.
*/
@RunWith(CustomRobolectricRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class DetailSongActivityTest {
private DetailSongActivity mDetailSongActivity;
private static TextView tvDetailName;
private static TextView tvDetailArtist;
private static TextView tvDetailDuration;
private static TextView tvDetailListeners;
private static TextView tvDetailPlayCount;
private static TextView tvDetailSongUrl;
private static TextView tvDetailWikiPublished;
private static TextView tvDetailWikiSummary;
private static TextView tvOnTour;
private static ImageView ivDetailImage;
private static LinearLayout llTopTag;
@Before
public void setUp() throws Exception {
// Use the debug configuration
ReflectionHelpers.setStaticField(BuildConfig.class, "DEBUG", true);
Intent intent = new Intent();
// Build the Activity
Bundle savedInstanceState = new Bundle();
mDetailSongActivity = Robolectric.buildActivity(DetailSongActivity.class)
.withIntent(intent)
.create(savedInstanceState)
.start()
.resume()
.pause()
.destroy()
.visible()
.get();
}
@Test
public void test_ActivityStarted() {
assertNotNull("mDetailSongActivity is null", mDetailSongActivity);
assertThat(mDetailSongActivity.getClass().getSimpleName()).isEqualTo(DetailSongActivity.class.getSimpleName());
}
@Test
public void test_DetailSongPresenterTag() {
IDetailSongPresenter detailSongPresenter = new DetailSongPresenter(mDetailSongActivity);
assertEquals("DetailSongPresenter", detailSongPresenter.getRequestPresenter());
}
@Test
public void test_ArtistPresenterTag() {
DetailSongPresenter detailSongPresenter = new DetailSongPresenter(mDetailSongActivity);
IArtistPresenter artistPresenter = new ArtistPresenter(detailSongPresenter);
assertEquals("ArtistPresenter", artistPresenter.getRequestPresenter());
}
@Test
public void test_a_InitialiseControls() {
tvDetailName = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_name);
tvDetailArtist = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_artist);
tvDetailDuration = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_duration);
ivDetailImage = (ImageView) mDetailSongActivity.findViewById(R.id.iv_detail_image);
tvDetailListeners = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_listeners);
tvDetailPlayCount = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_play_count);
tvDetailSongUrl = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_url);
tvDetailWikiPublished = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_wiki_published);
tvDetailWikiSummary = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_wiki_summary);
tvOnTour = (TextView) mDetailSongActivity.findViewById(R.id.tv_detail_on_tour);
llTopTag = (LinearLayout) mDetailSongActivity.findViewById(R.id.song_detail_tag_layout);
}
@Test
public void test_b_CheckControls() {
assertNotNull("tvDetailName is null", tvDetailName);
assertNotNull("tvDetailArtist is null", tvDetailArtist);
assertNotNull("tvDetailDuration is null", tvDetailDuration);
assertNotNull("ivDetailImage is null", ivDetailImage);
assertNotNull("tvDetailListeners is null", tvDetailListeners);
assertNotNull("tvDetailPlayCount is null", tvDetailPlayCount);
assertNotNull("tvDetailSongUrl is null", tvDetailSongUrl);
assertNotNull("tvDetailWikiPublished is null", tvDetailWikiPublished);
assertNotNull("tvDetailWikiSummary is null", tvDetailWikiSummary);
assertNotNull("tvOnTour is null", tvOnTour);
assertNotNull("llTopTag is null", llTopTag);
}
} | 5,331 | 0.751454 | 0.749578 | 120 | 43.433334 | 30.758396 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.725 | false | false | 11 |
a1d9ea91fa7d1c02125d9c5e38f68984863f9657 | 35,502,199,681,370 | da49fc602222cb7bb616be241a53e79e2c700423 | /src/com/tactfactory/itstart/vehicule/FirstClass.java | a9d902f363b87d43b0aed1f4d032b331a8294270 | [] | no_license | jponcy/itstart_2019_java_fundamentals | https://github.com/jponcy/itstart_2019_java_fundamentals | a9a6956e9b7615f7fe6fccb77dbf321f99b5dce1 | c6611ffbfa8c7a874e179502649914fcc4277c9a | refs/heads/master | 2020-04-21T02:28:27.190000 | 2019-02-08T15:33:09 | 2019-02-08T15:33:09 | 169,255,508 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tactfactory.itstart.vehicule;
/**
* My first class.
*/
public class FirstClass {
/**
* The entry point of my useless program.
* <ul>
* <li>point 1</li>
* </ul>
*
* @param args The CLI parameters.
*/
/*
* Commentaire qui ne deviendra pas de la documentation (generation
* documentation HTML).
*/
public static void main(String[] args) {
@SuppressWarnings("unused")
Skate skate1 = new Skate(42f, 210f, "Santa cruz", (byte) 4);
Skate skate2 = new Skate();
skate2.setLargeur(50f);
skate2.setMarque("Oxelo");
skate2.setNbRoues((byte) 4);
skate2.setPrix(61.52f);
String marques[] = { "Santa cruz", "Oxelo", "Lidle", "Bic", "Volvo", "Mont blanc" };
System.out.print("Les marques disponibles sont : ");
for (byte i = 0; i < marques.length; ++i) {
if (i != 0) {
System.out.print(", ");
}
System.out.print(marques[i]);
}
System.out.println(".");
Skate skates[] = new Skate[200];
for (short i = 0; i < 200; ++i) {
float largeur = (float) (Math.random() * 40 + 20);
float prix = ((int) ((Math.random() * 1_000 + 200) * 100)) / 100.0f;
String marque = marques[(int) (Math.random() * marques.length)];
byte nbRoues = (byte) (Math.random() * 3 + 3);
skates[i] = new Skate(largeur, prix, marque, nbRoues);
}
for (short i = 0; i < skates.length; ++i) {
System.out
.println(skates[i].getMarque() + " à " + skates[i].getPrix() + " € (avec " + skates[i].getNbRoues()
+ " roues)");
}
}
@SuppressWarnings("all")
private static void exempleFinal() {
int i = 3;
i = 4;
System.out.println(i);
final int j = 2;
// j = 4; // Ne fonctionne pas.
Voiture tuture = new Voiture();
tuture.fabriquant = "volvo";
Voiture old = tuture;
old = tuture;
tuture = new Voiture(); // possible car non final.
System.out.println(tuture.fabriquant);
System.out.println(old.fabriquant);
final Voiture titi = new Voiture();
titi.fabriquant = "volvo";
titi.fabriquant = "BM";
// titi = new Voiture(); // Impossible car final (seul la reference ne peut pas etre change).
// titi = tuture;
final Voiture tuture2 = tuture;
MyMath.somme(3, 5);
MyMath math = new MyMath();
math.mult(3, 5);
}
@SuppressWarnings("all")
private static void baseVoiture() {
Voiture tuture = new Voiture();
tuture.ch = 3;
tuture.nbPortes = 5;
tuture.fabriquant = "Super voiture maker";
tuture.prix = 321_432.21f;
tuture.couleur = "Rouge metalisé avec rayure jaune bleuté spéciale coupe du monde";
Voiture twingo2 = new Voiture();
twingo2.couleur = "Noir électrique";
twingo2.fabriquant = "tesla";
twingo2.prix = 12_843f;
Voiture voitures[] = { twingo2, tuture };
for (int i = 0; i < voitures.length; ++i) {
Voiture current = voitures[i];
System.out.println("");
System.out.println("Voiture " + current.couleur + " fabriqué par " + current.fabriquant);
System.out.println("Prix avant remise " + current.prix + " €");
current.remiseOccasion(543112);
System.out.println("Prix après remise " + current.prix + " €");
}
tuture.fabriquant = "Peux-jo?";
System.out.println(tuture.fabriquant);
System.out.println(twingo2.fabriquant);
// // Pas bien.
// tuture.compteur ++;
//
// System.out.println(tuture.compteur);
// System.out.println(twingo2.compteur);
// Bien.
Voiture.compteur++;
System.out.println(Voiture.compteur);
// System.out.println(tuture.compteur);
// System.out.println(twingo2.compteur);
}
@SuppressWarnings("all")
private static void examples() {
Integer i = 3;
int j = 2;
if (true) {
System.out.println("Vrai");
} else {
System.out.println("Faux");
}
int res = i + j;
}
}
| UTF-8 | Java | 4,390 | java | FirstClass.java | Java | [] | null | [] | package com.tactfactory.itstart.vehicule;
/**
* My first class.
*/
public class FirstClass {
/**
* The entry point of my useless program.
* <ul>
* <li>point 1</li>
* </ul>
*
* @param args The CLI parameters.
*/
/*
* Commentaire qui ne deviendra pas de la documentation (generation
* documentation HTML).
*/
public static void main(String[] args) {
@SuppressWarnings("unused")
Skate skate1 = new Skate(42f, 210f, "Santa cruz", (byte) 4);
Skate skate2 = new Skate();
skate2.setLargeur(50f);
skate2.setMarque("Oxelo");
skate2.setNbRoues((byte) 4);
skate2.setPrix(61.52f);
String marques[] = { "Santa cruz", "Oxelo", "Lidle", "Bic", "Volvo", "Mont blanc" };
System.out.print("Les marques disponibles sont : ");
for (byte i = 0; i < marques.length; ++i) {
if (i != 0) {
System.out.print(", ");
}
System.out.print(marques[i]);
}
System.out.println(".");
Skate skates[] = new Skate[200];
for (short i = 0; i < 200; ++i) {
float largeur = (float) (Math.random() * 40 + 20);
float prix = ((int) ((Math.random() * 1_000 + 200) * 100)) / 100.0f;
String marque = marques[(int) (Math.random() * marques.length)];
byte nbRoues = (byte) (Math.random() * 3 + 3);
skates[i] = new Skate(largeur, prix, marque, nbRoues);
}
for (short i = 0; i < skates.length; ++i) {
System.out
.println(skates[i].getMarque() + " à " + skates[i].getPrix() + " € (avec " + skates[i].getNbRoues()
+ " roues)");
}
}
@SuppressWarnings("all")
private static void exempleFinal() {
int i = 3;
i = 4;
System.out.println(i);
final int j = 2;
// j = 4; // Ne fonctionne pas.
Voiture tuture = new Voiture();
tuture.fabriquant = "volvo";
Voiture old = tuture;
old = tuture;
tuture = new Voiture(); // possible car non final.
System.out.println(tuture.fabriquant);
System.out.println(old.fabriquant);
final Voiture titi = new Voiture();
titi.fabriquant = "volvo";
titi.fabriquant = "BM";
// titi = new Voiture(); // Impossible car final (seul la reference ne peut pas etre change).
// titi = tuture;
final Voiture tuture2 = tuture;
MyMath.somme(3, 5);
MyMath math = new MyMath();
math.mult(3, 5);
}
@SuppressWarnings("all")
private static void baseVoiture() {
Voiture tuture = new Voiture();
tuture.ch = 3;
tuture.nbPortes = 5;
tuture.fabriquant = "Super voiture maker";
tuture.prix = 321_432.21f;
tuture.couleur = "Rouge metalisé avec rayure jaune bleuté spéciale coupe du monde";
Voiture twingo2 = new Voiture();
twingo2.couleur = "Noir électrique";
twingo2.fabriquant = "tesla";
twingo2.prix = 12_843f;
Voiture voitures[] = { twingo2, tuture };
for (int i = 0; i < voitures.length; ++i) {
Voiture current = voitures[i];
System.out.println("");
System.out.println("Voiture " + current.couleur + " fabriqué par " + current.fabriquant);
System.out.println("Prix avant remise " + current.prix + " €");
current.remiseOccasion(543112);
System.out.println("Prix après remise " + current.prix + " €");
}
tuture.fabriquant = "Peux-jo?";
System.out.println(tuture.fabriquant);
System.out.println(twingo2.fabriquant);
// // Pas bien.
// tuture.compteur ++;
//
// System.out.println(tuture.compteur);
// System.out.println(twingo2.compteur);
// Bien.
Voiture.compteur++;
System.out.println(Voiture.compteur);
// System.out.println(tuture.compteur);
// System.out.println(twingo2.compteur);
}
@SuppressWarnings("all")
private static void examples() {
Integer i = 3;
int j = 2;
if (true) {
System.out.println("Vrai");
} else {
System.out.println("Faux");
}
int res = i + j;
}
}
| 4,390 | 0.52913 | 0.508339 | 162 | 26.018518 | 24.54612 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.58642 | false | false | 11 |
acbbb2d5bb3fa2c5b68959c8878a132459096456 | 15,857,019,299,125 | 45ba836d48d900fb1d779579ce184d8c44ca2cc2 | /AdvancedConcepts/src/Generics/Varargs.java | acae99cdce85c7ede57119e2df8616540065e532 | [] | no_license | brand222/AdvancedJava | https://github.com/brand222/AdvancedJava | 34c7ca7eb9c715c52347c9cff1dbec0a22831da6 | 55d170963b71d831f95e4b9ea17f57a4cb01e955 | refs/heads/master | 2022-01-12T17:19:38.976000 | 2019-06-10T21:18:58 | 2019-06-10T21:18:58 | 188,452,432 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Generics;
public class Varargs {
public static void main(String[] args) {
String item1 = "Apples";
String item2 = "Oranges";
String item3 = "Pears";
String[] shopping = { "Bread", "Milk", "Eggs", "Bananas" };
printShoppingList(item1, item2, item3);
printShoppingList(shopping);
}
// public static void printShoppingList(String string1, String string2) {
// System.out.println("SHOPPING LIST");
// System.out.println("1. " + string1);
// System.out.println("2. " + string2);
// }
//
// public static void printShoppingList(String string1, String string2,
// String string3) {
// System.out.println("SHOPPING LIST");
// System.out.println("1. " + string1);
// System.out.println("2. " + string2);
// System.out.println("3. " + string3);
// }
//
// public static void printShoppingList(String[] stringArray) {
// System.out.println("SHOPPING LIST");
// int num = 1;
// for (String i : stringArray) {
// System.out.println(num + ". " + i);
// num++;
// }
// }
// in the previous 3 methods, they all are ultimately accomplishing the same
// thing:
// printing out a shopping list, the only difference between them is the
// arguments that are being passed.
// One method is overridden and the other takes an array as a parameter
// you will notice that the method below has '...' in the method parameter
// section
// these dots basically mean that this method can take a variable amount of
// arguments (of type string)
//with these 3 dots, this means i can pass in, 1 item, 2 items, no items, or an array of items
//thus, this replaces all the three previous methods and saves alot of lines of code.
public static void printShoppingList(String... stringArray) {
System.out.println("SHOPPING LIST");
int num = 1;
for (String i : stringArray) {
System.out.println(num + "." + i);
num++;
}
}
}
| UTF-8 | Java | 1,866 | java | Varargs.java | Java | [] | null | [] | package Generics;
public class Varargs {
public static void main(String[] args) {
String item1 = "Apples";
String item2 = "Oranges";
String item3 = "Pears";
String[] shopping = { "Bread", "Milk", "Eggs", "Bananas" };
printShoppingList(item1, item2, item3);
printShoppingList(shopping);
}
// public static void printShoppingList(String string1, String string2) {
// System.out.println("SHOPPING LIST");
// System.out.println("1. " + string1);
// System.out.println("2. " + string2);
// }
//
// public static void printShoppingList(String string1, String string2,
// String string3) {
// System.out.println("SHOPPING LIST");
// System.out.println("1. " + string1);
// System.out.println("2. " + string2);
// System.out.println("3. " + string3);
// }
//
// public static void printShoppingList(String[] stringArray) {
// System.out.println("SHOPPING LIST");
// int num = 1;
// for (String i : stringArray) {
// System.out.println(num + ". " + i);
// num++;
// }
// }
// in the previous 3 methods, they all are ultimately accomplishing the same
// thing:
// printing out a shopping list, the only difference between them is the
// arguments that are being passed.
// One method is overridden and the other takes an array as a parameter
// you will notice that the method below has '...' in the method parameter
// section
// these dots basically mean that this method can take a variable amount of
// arguments (of type string)
//with these 3 dots, this means i can pass in, 1 item, 2 items, no items, or an array of items
//thus, this replaces all the three previous methods and saves alot of lines of code.
public static void printShoppingList(String... stringArray) {
System.out.println("SHOPPING LIST");
int num = 1;
for (String i : stringArray) {
System.out.println(num + "." + i);
num++;
}
}
}
| 1,866 | 0.670954 | 0.656484 | 59 | 30.627119 | 26.440786 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.711864 | false | false | 9 |
482316f9f720c9222397d0890ff586c89538b2de | 5,549,097,810,380 | 48cbc3a7bd3278f361c1693339f46205501f06c9 | /src/LeetCodeProblems/AlienDictionaryValidator.java | 08f56bf583e476ef16d1e04772f5796cd8917c26 | [] | no_license | sdamaraju/Prep2021 | https://github.com/sdamaraju/Prep2021 | 2dc0631c8d8431034c3c401f378757bd9b0f47c4 | 22b7bb5239ebc2427353d93cafa9378a20a0d51a | refs/heads/main | 2023-07-10T03:10:12.162000 | 2021-08-14T20:25:14 | 2021-08-14T20:25:14 | 396,107,351 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package LeetCodeProblems;
import java.util.HashMap;
public class AlienDictionaryValidator {
public static void main(String[] args) {
/*["word","world","row"]
"worldabcefghijkmnpqstuvxyz"*/
AlienDictionaryValidator obj = new AlienDictionaryValidator();
//obj.initLanguage("worldabcefghijkmnpqstuvxyz");
System.out.println(obj.isAlienSorted(new String[]{"hello", "hello"},"abcdefghijklmnopqstuvxyz"));
}
private HashMap initLanguage(String order) {
HashMap charOrder = new HashMap<Character, Integer>();
for (int i = 0; i < order.length(); i++) {
charOrder.put(order.charAt(i), i + 1);
}
return charOrder;
}
private boolean isAlienSorted(String[] strings, String order) {
HashMap<Character, Integer> charOrder = initLanguage(order);
boolean isValid = true;
for (int i = 0; i < strings.length - 1; i++) {
isValid = validate(strings[i], strings[i + 1], charOrder);
if (!isValid) return false;
}
return true;
}
private boolean validate(String string1, String string2, HashMap<Character,Integer> charOrder) {
int str1Length = string1.length();
int str2Length = string2.length();
if (str1Length == 0 && str2Length >= 0) return true;
if (str1Length >= 0 && str2Length == 0) return false;
int j = 0;
int i = 0;
int currChar1, currChar2;
while (i < str1Length && j < str2Length) {
//if(charOrder.get(string1.charAt(i)) == null || charOrder.get(string2.charAt(j)) == null) return false;
currChar1 = charOrder.get(string1.charAt(i++));
currChar2 = charOrder.get(string2.charAt(j++));
// if ((Integer)currChar1 == null || (Integer)currChar2 == null) return false;
if (currChar1 > currChar2) return false;
if (currChar1 < currChar2) return true;
}
if (str1Length > str2Length) return false;
return true;
}
// Need to discuss on this..
/*private static boolean validator(String[] strings) {
boolean[] accuratelyPlaced = new boolean[strings.length];
for (int i = 0; i < strings.length; i++) accuratelyPlaced[i] = false;
for (int i = 0; i < Integer.MAX_VALUE; i++) { //index
int[] checkCharactersAtIndex = new int[strings.length];
for (int j = 0; j < strings.length; j++) { // each string
if (strings[j].length() >= i + 1) {
checkCharactersAtIndex[i] = charOrder.get(strings[j].charAt(i));
} else if (strings[j].length() == 0) checkCharactersAtIndex[i] = Integer.MIN_VALUE;
else checkCharactersAtIndex[i] = -1;
}
validate(checkCharactersAtIndex);
}
}
private static boolean validate(int[] values) {
boolean isValid = true;
for (int i = 0; i < values.length - 1; i++) {
if (values[i] <= values[i + 1]) {
}
}
return isValid;
}*/
}
| UTF-8 | Java | 3,087 | java | AlienDictionaryValidator.java | Java | [] | null | [] | package LeetCodeProblems;
import java.util.HashMap;
public class AlienDictionaryValidator {
public static void main(String[] args) {
/*["word","world","row"]
"worldabcefghijkmnpqstuvxyz"*/
AlienDictionaryValidator obj = new AlienDictionaryValidator();
//obj.initLanguage("worldabcefghijkmnpqstuvxyz");
System.out.println(obj.isAlienSorted(new String[]{"hello", "hello"},"abcdefghijklmnopqstuvxyz"));
}
private HashMap initLanguage(String order) {
HashMap charOrder = new HashMap<Character, Integer>();
for (int i = 0; i < order.length(); i++) {
charOrder.put(order.charAt(i), i + 1);
}
return charOrder;
}
private boolean isAlienSorted(String[] strings, String order) {
HashMap<Character, Integer> charOrder = initLanguage(order);
boolean isValid = true;
for (int i = 0; i < strings.length - 1; i++) {
isValid = validate(strings[i], strings[i + 1], charOrder);
if (!isValid) return false;
}
return true;
}
private boolean validate(String string1, String string2, HashMap<Character,Integer> charOrder) {
int str1Length = string1.length();
int str2Length = string2.length();
if (str1Length == 0 && str2Length >= 0) return true;
if (str1Length >= 0 && str2Length == 0) return false;
int j = 0;
int i = 0;
int currChar1, currChar2;
while (i < str1Length && j < str2Length) {
//if(charOrder.get(string1.charAt(i)) == null || charOrder.get(string2.charAt(j)) == null) return false;
currChar1 = charOrder.get(string1.charAt(i++));
currChar2 = charOrder.get(string2.charAt(j++));
// if ((Integer)currChar1 == null || (Integer)currChar2 == null) return false;
if (currChar1 > currChar2) return false;
if (currChar1 < currChar2) return true;
}
if (str1Length > str2Length) return false;
return true;
}
// Need to discuss on this..
/*private static boolean validator(String[] strings) {
boolean[] accuratelyPlaced = new boolean[strings.length];
for (int i = 0; i < strings.length; i++) accuratelyPlaced[i] = false;
for (int i = 0; i < Integer.MAX_VALUE; i++) { //index
int[] checkCharactersAtIndex = new int[strings.length];
for (int j = 0; j < strings.length; j++) { // each string
if (strings[j].length() >= i + 1) {
checkCharactersAtIndex[i] = charOrder.get(strings[j].charAt(i));
} else if (strings[j].length() == 0) checkCharactersAtIndex[i] = Integer.MIN_VALUE;
else checkCharactersAtIndex[i] = -1;
}
validate(checkCharactersAtIndex);
}
}
private static boolean validate(int[] values) {
boolean isValid = true;
for (int i = 0; i < values.length - 1; i++) {
if (values[i] <= values[i + 1]) {
}
}
return isValid;
}*/
}
| 3,087 | 0.577259 | 0.56171 | 81 | 37.111111 | 29.302593 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.82716 | false | false | 9 |
82c9c436cb65849549f65b9eaea52c9120d782c6 | 4,569,845,250,263 | 850a31f13d28ebafbee27a73dba44519e5ca49cf | /src/main/java/com/highbar/cards/poker/Low8Classifier.java | 7831e840704f38f6362ad90451e11f8ec60ffa14 | [] | no_license | gordwilling/OmahaHiLo | https://github.com/gordwilling/OmahaHiLo | 6b6f8e7157f3828d24cc87e90ebf1a2f3884e093 | f02af63a9779b869781b1edbb0900fadbdd41c7a | refs/heads/master | 2020-06-21T05:53:36.966000 | 2016-12-11T20:40:23 | 2016-12-11T20:40:23 | 74,802,190 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.highbar.cards.poker;
import com.highbar.cards.Card;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static java.util.Collections.emptyList;
public class Low8Classifier extends AbstractHandClassifier {
public Low8Classifier() {
super(CardComparators.aceLow());
}
@NotNull
@Contract(pure = true)
public Optional<RankedHand> low8Hand(@NotNull List<Card> hand) {
if (hand.size() != 5) throw new IllegalArgumentException();
List<Card> cards = new ArrayList<>();
cards.addAll(hand);
// the spec didn't mention it, but according to the Internet, Low 8
// rules ignore flushes and straights. That means all hands are
// ranked as High Card... Without this knowledge, this program was
// generating results that differed from the spec.
return noneHigherThan8(cards) && distinctRanks(cards)
? Optional.of(new HighCard(cards, comparator()))
: Optional.empty();
}
@Contract(pure = true)
private boolean distinctRanks(@NotNull List<Card> cards) {
Map<Integer, List<List<Card>>> groupByN = groupByN(cards);
List<List<Card>> singles = groupByN.getOrDefault(1, emptyList());
return singles.size() == 5;
}
@Contract(pure = true)
private boolean noneHigherThan8(@NotNull List<Card> cards) {
return cards.stream().filter(x -> x.rank().ordinal() > 7).count() == 0;
}
} | UTF-8 | Java | 1,598 | java | Low8Classifier.java | Java | [] | null | [] | package com.highbar.cards.poker;
import com.highbar.cards.Card;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static java.util.Collections.emptyList;
public class Low8Classifier extends AbstractHandClassifier {
public Low8Classifier() {
super(CardComparators.aceLow());
}
@NotNull
@Contract(pure = true)
public Optional<RankedHand> low8Hand(@NotNull List<Card> hand) {
if (hand.size() != 5) throw new IllegalArgumentException();
List<Card> cards = new ArrayList<>();
cards.addAll(hand);
// the spec didn't mention it, but according to the Internet, Low 8
// rules ignore flushes and straights. That means all hands are
// ranked as High Card... Without this knowledge, this program was
// generating results that differed from the spec.
return noneHigherThan8(cards) && distinctRanks(cards)
? Optional.of(new HighCard(cards, comparator()))
: Optional.empty();
}
@Contract(pure = true)
private boolean distinctRanks(@NotNull List<Card> cards) {
Map<Integer, List<List<Card>>> groupByN = groupByN(cards);
List<List<Card>> singles = groupByN.getOrDefault(1, emptyList());
return singles.size() == 5;
}
@Contract(pure = true)
private boolean noneHigherThan8(@NotNull List<Card> cards) {
return cards.stream().filter(x -> x.rank().ordinal() > 7).count() == 0;
}
} | 1,598 | 0.667084 | 0.6602 | 48 | 32.3125 | 26.425333 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
22f79d8fda9e653627e0424b7d910261740bf4a7 | 32,624,571,637,601 | dfaa3d34adaf6268391c8fab0d45549b23d12fc3 | /javaee-jms-remote/src/main/java/ir/moke/jaavee/MessageReader.java | 6075f41ef9c69844539bcf8531fcd52712a46d6e | [] | no_license | mah454/JavaEE-Tutorials | https://github.com/mah454/JavaEE-Tutorials | 7fae86203b788867f83f80797818468d9c959707 | 9d00725b50c85b762683921f8c9996db99760030 | refs/heads/master | 2023-07-09T16:55:53.405000 | 2023-06-29T19:34:28 | 2023-06-29T19:34:28 | 149,864,123 | 12 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ir.moke.jaavee;
import jakarta.ejb.MessageDriven;
import jakarta.jms.Message;
import jakarta.jms.MessageListener;
import jakarta.jms.TextMessage;
@MessageDriven(name = "sample")
public class MessageReader implements MessageListener {
@Override
public void onMessage(Message message) {
try {
TextMessage textMessage = (TextMessage) message;
var text = textMessage.getText();
System.out.println("Receive: " + text);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 561 | java | MessageReader.java | Java | [] | null | [] | package ir.moke.jaavee;
import jakarta.ejb.MessageDriven;
import jakarta.jms.Message;
import jakarta.jms.MessageListener;
import jakarta.jms.TextMessage;
@MessageDriven(name = "sample")
public class MessageReader implements MessageListener {
@Override
public void onMessage(Message message) {
try {
TextMessage textMessage = (TextMessage) message;
var text = textMessage.getText();
System.out.println("Receive: " + text);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 561 | 0.655971 | 0.655971 | 22 | 24.5 | 18.956289 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false | 9 |
578cbc9dfa6e810ff33aef7c0daa1ce513227f76 | 34,797,825,034,801 | 738eba0ce21049aca65c33be401ef9418cacdc35 | /Java/2017-03-08Queue/src/queue/Queue.java | 563d504c0e7eb18acf850390443f376463dd1e1b | [] | no_license | MarcoDiFrancesco/LittleProjects | https://github.com/MarcoDiFrancesco/LittleProjects | 7fe0c69dfe8cd8c6981450fe0c8f99c4299e6f2a | 526641c9f0f88585134bfbc2df5a2fdaf4436656 | refs/heads/master | 2022-10-05T15:18:56.683000 | 2022-10-05T05:08:49 | 2022-10-05T05:08:49 | 151,850,270 | 5 | 12 | null | false | 2022-10-05T05:08:50 | 2018-10-06T14:54:07 | 2021-10-30T15:57:07 | 2022-10-05T05:08:49 | 87,325 | 0 | 11 | 0 | Jupyter Notebook | false | false | package queue;
public class Queue {
private Node head;
private Node tail;
private int counter = 0;
public void enqueue(Object value) {
Node node = new Node(value, null);
tail.setNext(node);
tail = node;
counter++;
}
/*
* public void dequeue() {
*
* head = head.getNext(); counter--; }
*/
public int size() {
return counter;
}
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
}
| UTF-8 | Java | 460 | java | Queue.java | Java | [] | null | [] | package queue;
public class Queue {
private Node head;
private Node tail;
private int counter = 0;
public void enqueue(Object value) {
Node node = new Node(value, null);
tail.setNext(node);
tail = node;
counter++;
}
/*
* public void dequeue() {
*
* head = head.getNext(); counter--; }
*/
public int size() {
return counter;
}
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
}
| 460 | 0.623913 | 0.621739 | 31 | 13.83871 | 12.179032 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.419355 | false | false | 9 |
6329b3bd8e15e5a1e1db0d51825a280513735c06 | 25,829,933,370,485 | 4aed712e4d9761d3252aa13c7d69a1b8df45f43b | /src/cz/burios/uniql/persistence/mappings/xdb/DirectToXMLTypeMapping.java | c5fe98f74a7fef77c57bf280cef2d2265317d967 | [] | no_license | buriosca/cz.burios.uniql-jpa | https://github.com/buriosca/cz.burios.uniql-jpa | 86c682f2d19c824e21102ac71c150e7de1a25e18 | e9a651f836018456b99048f02191f2ebe824e511 | refs/heads/master | 2022-06-25T01:22:43.605000 | 2020-07-19T05:13:25 | 2020-07-19T05:13:25 | 247,073,006 | 0 | 0 | null | false | 2022-06-21T03:53:36 | 2020-03-13T13:05:10 | 2020-07-19T05:14:28 | 2022-06-21T03:53:35 | 5,823 | 0 | 0 | 3 | Java | false | false | /*******************************************************************************
* Copyright (c) 1998, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
* 11/10/2011-2.4 Guy Pelletier
* - 357474: Address primaryKey option from tenant discriminator column
******************************************************************************/
package cz.burios.uniql.persistence.mappings.xdb;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import cz.burios.uniql.persistence.exceptions.ConversionException;
import cz.burios.uniql.persistence.exceptions.DescriptorException;
import cz.burios.uniql.persistence.internal.helper.ClassConstants;
import cz.burios.uniql.persistence.internal.platform.database.XMLTypePlaceholder;
import cz.burios.uniql.persistence.internal.sessions.AbstractSession;
import cz.burios.uniql.persistence.mappings.DirectToFieldMapping;
import cz.burios.uniql.persistence.platform.xml.XMLComparer;
import cz.burios.uniql.persistence.platform.xml.XMLParser;
import cz.burios.uniql.persistence.platform.xml.XMLPlatformFactory;
import cz.burios.uniql.persistence.platform.xml.XMLTransformer;
import cz.burios.uniql.persistence.sessions.Session;
/**
* <b>Purpose</b>: Mapping used to map from a DOM (org.w3c.Document) or XML String into
* an Oracle XMLType field, in Oracle 9i XDB.
*
* @since Toplink 10.1.3
*/
public class DirectToXMLTypeMapping extends DirectToFieldMapping {
/**
* Indicates if we should initialize the whole DOM on a read.
* This is only used if the user is mapping from an Oracle Document implementation.
*/
protected boolean shouldReadWholeDocument = false;
/**
* Used to convert the DOM to a String.
*/
private XMLTransformer xmlTransformer;
/**
* Used to determine if the XML document has been modified.
*/
private XMLComparer xmlComparer;
/**
* Used to convert the String to a DOM
*/
private XMLParser xmlParser;
/**
* INTERNAL:
* Default to mutable if mapped as a DOM.
*/
public void preInitialize(AbstractSession session) throws DescriptorException {
if (this.attributeClassification == null) {
this.attributeClassification = getAttributeAccessor().getAttributeClass();
}
if ((this.isMutable == null) && (this.attributeClassification != ClassConstants.STRING)) {
setIsMutable(true);
}
super.preInitialize(session);
}
/**
* INTERNAL:
* The mapping is initialized with the given session. This mapping is fully initialized
* after this.
*/
@Override
public void initialize(AbstractSession session) throws DescriptorException {
super.initialize(session);
setFieldClassification(XMLTypePlaceholder.class);
}
public DirectToXMLTypeMapping() {
super();
this.xmlTransformer = XMLPlatformFactory.getInstance().getXMLPlatform().newXMLTransformer();
this.xmlTransformer.setFormattedOutput(false);
this.xmlParser = XMLPlatformFactory.getInstance().getXMLPlatform().newXMLParser();
this.xmlComparer = new XMLComparer();
}
/**
* PUBLIC:
* @param readWholeDocument - determines if the Oracle XDB DOM should be fully initialized
* on a read.
*/
public void setShouldReadWholeDocument(boolean readWholeDocument) {
this.shouldReadWholeDocument = readWholeDocument;
}
/**
* PUBLIC:
* @return boolean - returns true if currently initializing DOMs on reads.
*/
public boolean shouldReadWholeDocument() {
return shouldReadWholeDocument;
}
/**
* INTERNAL:
* Get the attribute value for the given field value. If we're mapping to a
* Document, we need to check if we should return the Oracle DOM or build a
* new one.
*/
@Override
public Object getObjectValue(Object fieldValue, Session session) throws ConversionException {
Object attributeValue = fieldValue;
try {
if (attributeValue != null) {
if (this.attributeClassification != ClassConstants.STRING) {
String xml = (String)attributeValue;
java.io.StringReader reader = new java.io.StringReader(xml);
return this.xmlParser.parse(reader);
}
}
} catch (Exception ex) {
throw ConversionException.couldNotBeConverted(fieldValue, this.attributeClassification, ex);
}
if ((attributeValue == null) && (this.nullValue != null)) {// Translate default null value
return this.nullValue;
}
// Allow for user defined conversion to the object value.
if (this.converter != null) {
attributeValue = this.converter.convertDataValueToObjectValue(attributeValue, session);
}
return attributeValue;
}
@Override
public boolean isDirectToXMLTypeMapping() {
return true;
}
/**
* INTERNAL:
* Clone the DOM Document if required.
*/
@Override
protected Object buildCloneValue(Object attributeValue, AbstractSession session) {
Object newAttributeValue = attributeValue;
if (isMutable() && attributeValue != null) {
if ((getAttributeClassification() == ClassConstants.DOCUMENT) || (getAttributeClassification() == ClassConstants.NODE)) {
Document doc = (Document)attributeValue;
newAttributeValue = doc.cloneNode(true);
}
}
return newAttributeValue;
}
/**
* INTERNAL:
* Compare the attribute values.
* Compare Nodes if mapped as a DOM.
*/
@Override
protected boolean compareObjectValues(Object firstValue, Object secondValue, AbstractSession session) {
// PERF: Check identity before conversion.
if (firstValue == secondValue) {
return true;
}
if ((firstValue == null) && (secondValue == null)) {
return true;
}
if ((firstValue == null) || (secondValue == null)) {
return false;
}
if (getAttributeClassification() == ClassConstants.STRING) {
return firstValue.equals(secondValue);
} else {
Object one = getFieldValue(firstValue, session);
Object two = getFieldValue(secondValue, session);
if (one instanceof Node && two instanceof Node) {
return this.xmlComparer.isNodeEqual((Node)one, (Node)two);
}
return one.equals(two);
}
}
}
| UTF-8 | Java | 7,327 | java | DirectToXMLTypeMapping.java | Java | [
{
"context": "ntation from Oracle TopLink\r\n * 11/10/2011-2.4 Guy Pelletier \r\n * - 357474: Address primaryKey option fr",
"end": 693,
"score": 0.9998222589492798,
"start": 680,
"tag": "NAME",
"value": "Guy Pelletier"
}
] | null | [] | /*******************************************************************************
* Copyright (c) 1998, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
* 11/10/2011-2.4 <NAME>
* - 357474: Address primaryKey option from tenant discriminator column
******************************************************************************/
package cz.burios.uniql.persistence.mappings.xdb;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import cz.burios.uniql.persistence.exceptions.ConversionException;
import cz.burios.uniql.persistence.exceptions.DescriptorException;
import cz.burios.uniql.persistence.internal.helper.ClassConstants;
import cz.burios.uniql.persistence.internal.platform.database.XMLTypePlaceholder;
import cz.burios.uniql.persistence.internal.sessions.AbstractSession;
import cz.burios.uniql.persistence.mappings.DirectToFieldMapping;
import cz.burios.uniql.persistence.platform.xml.XMLComparer;
import cz.burios.uniql.persistence.platform.xml.XMLParser;
import cz.burios.uniql.persistence.platform.xml.XMLPlatformFactory;
import cz.burios.uniql.persistence.platform.xml.XMLTransformer;
import cz.burios.uniql.persistence.sessions.Session;
/**
* <b>Purpose</b>: Mapping used to map from a DOM (org.w3c.Document) or XML String into
* an Oracle XMLType field, in Oracle 9i XDB.
*
* @since Toplink 10.1.3
*/
public class DirectToXMLTypeMapping extends DirectToFieldMapping {
/**
* Indicates if we should initialize the whole DOM on a read.
* This is only used if the user is mapping from an Oracle Document implementation.
*/
protected boolean shouldReadWholeDocument = false;
/**
* Used to convert the DOM to a String.
*/
private XMLTransformer xmlTransformer;
/**
* Used to determine if the XML document has been modified.
*/
private XMLComparer xmlComparer;
/**
* Used to convert the String to a DOM
*/
private XMLParser xmlParser;
/**
* INTERNAL:
* Default to mutable if mapped as a DOM.
*/
public void preInitialize(AbstractSession session) throws DescriptorException {
if (this.attributeClassification == null) {
this.attributeClassification = getAttributeAccessor().getAttributeClass();
}
if ((this.isMutable == null) && (this.attributeClassification != ClassConstants.STRING)) {
setIsMutable(true);
}
super.preInitialize(session);
}
/**
* INTERNAL:
* The mapping is initialized with the given session. This mapping is fully initialized
* after this.
*/
@Override
public void initialize(AbstractSession session) throws DescriptorException {
super.initialize(session);
setFieldClassification(XMLTypePlaceholder.class);
}
public DirectToXMLTypeMapping() {
super();
this.xmlTransformer = XMLPlatformFactory.getInstance().getXMLPlatform().newXMLTransformer();
this.xmlTransformer.setFormattedOutput(false);
this.xmlParser = XMLPlatformFactory.getInstance().getXMLPlatform().newXMLParser();
this.xmlComparer = new XMLComparer();
}
/**
* PUBLIC:
* @param readWholeDocument - determines if the Oracle XDB DOM should be fully initialized
* on a read.
*/
public void setShouldReadWholeDocument(boolean readWholeDocument) {
this.shouldReadWholeDocument = readWholeDocument;
}
/**
* PUBLIC:
* @return boolean - returns true if currently initializing DOMs on reads.
*/
public boolean shouldReadWholeDocument() {
return shouldReadWholeDocument;
}
/**
* INTERNAL:
* Get the attribute value for the given field value. If we're mapping to a
* Document, we need to check if we should return the Oracle DOM or build a
* new one.
*/
@Override
public Object getObjectValue(Object fieldValue, Session session) throws ConversionException {
Object attributeValue = fieldValue;
try {
if (attributeValue != null) {
if (this.attributeClassification != ClassConstants.STRING) {
String xml = (String)attributeValue;
java.io.StringReader reader = new java.io.StringReader(xml);
return this.xmlParser.parse(reader);
}
}
} catch (Exception ex) {
throw ConversionException.couldNotBeConverted(fieldValue, this.attributeClassification, ex);
}
if ((attributeValue == null) && (this.nullValue != null)) {// Translate default null value
return this.nullValue;
}
// Allow for user defined conversion to the object value.
if (this.converter != null) {
attributeValue = this.converter.convertDataValueToObjectValue(attributeValue, session);
}
return attributeValue;
}
@Override
public boolean isDirectToXMLTypeMapping() {
return true;
}
/**
* INTERNAL:
* Clone the DOM Document if required.
*/
@Override
protected Object buildCloneValue(Object attributeValue, AbstractSession session) {
Object newAttributeValue = attributeValue;
if (isMutable() && attributeValue != null) {
if ((getAttributeClassification() == ClassConstants.DOCUMENT) || (getAttributeClassification() == ClassConstants.NODE)) {
Document doc = (Document)attributeValue;
newAttributeValue = doc.cloneNode(true);
}
}
return newAttributeValue;
}
/**
* INTERNAL:
* Compare the attribute values.
* Compare Nodes if mapped as a DOM.
*/
@Override
protected boolean compareObjectValues(Object firstValue, Object secondValue, AbstractSession session) {
// PERF: Check identity before conversion.
if (firstValue == secondValue) {
return true;
}
if ((firstValue == null) && (secondValue == null)) {
return true;
}
if ((firstValue == null) || (secondValue == null)) {
return false;
}
if (getAttributeClassification() == ClassConstants.STRING) {
return firstValue.equals(secondValue);
} else {
Object one = getFieldValue(firstValue, session);
Object two = getFieldValue(secondValue, session);
if (one instanceof Node && two instanceof Node) {
return this.xmlComparer.isNodeEqual((Node)one, (Node)two);
}
return one.equals(two);
}
}
}
| 7,320 | 0.629043 | 0.623584 | 191 | 36.371727 | 31.043005 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.356021 | false | false | 9 |
12e0158bfc9bdc5a955b777971e19ed97c82245d | 36,189,394,444,351 | 05511d26ab6f713e1a2be6d6f9716647d1c2fd72 | /mylibrary/src/main/java/com/zxh/mylibrary/base/OnSingleClickListener.java | be21166c682b2c4120a63da09b6433dde8fc6ddb | [] | no_license | xyzle/MyCustom | https://github.com/xyzle/MyCustom | 77ba8ee80450456f69f6885146eb6f065b6d4e31 | e9c2c28afd629ec0dcba936d9b6f2c41cde9e73b | refs/heads/master | 2020-03-17T16:35:09.422000 | 2018-02-05T09:51:22 | 2018-02-05T09:51:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zxh.mylibrary.base;
import android.view.View;
import com.xwjr.utilcode.utils.LogUtils;
/**
* Created by Administrator on 2017/4/1.
*/
public abstract class OnSingleClickListener implements View.OnClickListener {
private long delayTime = 500;
private static long lastTime;
public abstract void singleClick(View v);
@Override
public void onClick(View v) {
if (!((System.currentTimeMillis() - lastTime) < delayTime)) {
try {
singleClick(v);
lastTime = System.currentTimeMillis();
}catch (Exception e){
LogUtils.i("OnSingleClickListener-->单击发生异常");
}
}else{
}
}
}
| UTF-8 | Java | 726 | java | OnSingleClickListener.java | Java | [
{
"context": "m.xwjr.utilcode.utils.LogUtils;\n\n/**\n * Created by Administrator on 2017/4/1.\n */\n\npublic abstract class OnSingleC",
"end": 133,
"score": 0.5145835876464844,
"start": 120,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | package com.zxh.mylibrary.base;
import android.view.View;
import com.xwjr.utilcode.utils.LogUtils;
/**
* Created by Administrator on 2017/4/1.
*/
public abstract class OnSingleClickListener implements View.OnClickListener {
private long delayTime = 500;
private static long lastTime;
public abstract void singleClick(View v);
@Override
public void onClick(View v) {
if (!((System.currentTimeMillis() - lastTime) < delayTime)) {
try {
singleClick(v);
lastTime = System.currentTimeMillis();
}catch (Exception e){
LogUtils.i("OnSingleClickListener-->单击发生异常");
}
}else{
}
}
}
| 726 | 0.609244 | 0.596639 | 31 | 22.032259 | 22.255821 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.290323 | false | false | 9 |
aab37a456393d0696aeab17c39e03692a7af7201 | 5,514,738,076,186 | 3e461303deb6661379a21d66210e890c198cfd67 | /app/src/main/java/com/myapplicationdev/android/tw_listview/SecondActivity.java | 2166c9d358b3b94c8923b0098454c34f02a3615a | [] | no_license | 16023054/TW-ListView | https://github.com/16023054/TW-ListView | 298166c937c8c092b4ea5d49522258ca87b65e38 | 749495cb2f7931ca8c520a5d5f17b424c39e393e | refs/heads/master | 2020-03-12T13:22:35.937000 | 2018-04-23T05:21:59 | 2018-04-23T05:21:59 | 130,640,490 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.myapplicationdev.android.tw_listview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class SecondActivity extends AppCompatActivity {
ListView lv;
TextView tvYear;
ArrayAdapter aa;
ArrayList<Module> module;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
lv = findViewById(R.id.lvModules);
tvYear = findViewById(R.id.tvYear);
Intent i = getIntent();
String year = i.getStringExtra("year");
tvYear.setText(year);
module = new ArrayList<Module>();
aa = new ModuleAdapter(this, R.layout.row, module);
if (year.equals("Year 1")){
module.add(new Module("A113", false));
module.add(new Module("B102", false));
module.add(new Module("C105", true));
module.add(new Module("C111", false));
module.add(new Module("G101", false));
module.add(new Module("C207", true));
module.add(new Module("C208", true));
module.add(new Module("C227", false));
module.add(new Module("C294", false));
module.add(new Module("G107", false));
lv.setAdapter(aa);
}else if (year.equals("Year 2")){
module.add(new Module("C202", false));
module.add(new Module("C203", true));
module.add(new Module("C235", true));
module.add(new Module("C318", false));
module.add(new Module("C346", true));
module.add(new Module("C236", true));
module.add(new Module("C273", true));
module.add(new Module("C308", true));
module.add(new Module("C348", true));
lv.setAdapter(aa);
}else if (year.equals("Year 3")){
module.add(new Module("C347", true));
module.add(new Module("C302", true));
module.add(new Module("C349", true));
lv.setAdapter(aa);
}
}
}
| UTF-8 | Java | 2,250 | java | SecondActivity.java | Java | [] | null | [] | package com.myapplicationdev.android.tw_listview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class SecondActivity extends AppCompatActivity {
ListView lv;
TextView tvYear;
ArrayAdapter aa;
ArrayList<Module> module;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
lv = findViewById(R.id.lvModules);
tvYear = findViewById(R.id.tvYear);
Intent i = getIntent();
String year = i.getStringExtra("year");
tvYear.setText(year);
module = new ArrayList<Module>();
aa = new ModuleAdapter(this, R.layout.row, module);
if (year.equals("Year 1")){
module.add(new Module("A113", false));
module.add(new Module("B102", false));
module.add(new Module("C105", true));
module.add(new Module("C111", false));
module.add(new Module("G101", false));
module.add(new Module("C207", true));
module.add(new Module("C208", true));
module.add(new Module("C227", false));
module.add(new Module("C294", false));
module.add(new Module("G107", false));
lv.setAdapter(aa);
}else if (year.equals("Year 2")){
module.add(new Module("C202", false));
module.add(new Module("C203", true));
module.add(new Module("C235", true));
module.add(new Module("C318", false));
module.add(new Module("C346", true));
module.add(new Module("C236", true));
module.add(new Module("C273", true));
module.add(new Module("C308", true));
module.add(new Module("C348", true));
lv.setAdapter(aa);
}else if (year.equals("Year 3")){
module.add(new Module("C347", true));
module.add(new Module("C302", true));
module.add(new Module("C349", true));
lv.setAdapter(aa);
}
}
}
| 2,250 | 0.589333 | 0.558222 | 70 | 31.142857 | 20.268404 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 9 |
422b10713e71f4c08b8021842b36f162649a7915 | 17,102,559,823,772 | ea9deb97fbd3a5e0c87ac60449dbd659facb64db | /baseio-test/src/main/java/com/generallycloud/test/nio/others/JedisTest.java | 44824d38a4b4a7b57ed50af2be852ae1a06b804a | [] | no_license | DONGXUE1/baseio | https://github.com/DONGXUE1/baseio | a16f44a1da7d66fcd7991ce601ec0886269251bb | 0aaed42b625cc41e6f1b5c42f372b8c6006f045b | refs/heads/master | 2021-01-13T09:26:58.125000 | 2017-10-24T14:15:55 | 2017-10-24T14:15:55 | 72,083,553 | 0 | 0 | null | true | 2016-10-27T07:41:18 | 2016-10-27T07:41:17 | 2016-10-27T07:09:55 | 2016-10-27T07:24:22 | 23,416 | 0 | 0 | 0 | null | null | null | package com.generallycloud.test.nio.others;
import java.util.Set;
import com.generallycloud.nio.common.CloseUtil;
import redis.clients.jedis.Jedis;
public class JedisTest {
public static void main(String[] args) {
// 连接本地的 Redis 服务
Jedis jedis = new Jedis("localhost");
System.out.println("Connection to server sucessfully");
// 设置 redis 字符串数据
jedis.set("k1", "v1");
jedis.set("k2", "v2");
// 获取存储的数据并输出
String value = jedis.get("k1");
Set<String> keys = jedis.keys("*");
for(String k : keys){
System.out.println("KEY:"+k);
}
System.out.println("Stored string in redis:: " + value);
CloseUtil.close(jedis);
}
}
| UTF-8 | Java | 709 | java | JedisTest.java | Java | [] | null | [] | package com.generallycloud.test.nio.others;
import java.util.Set;
import com.generallycloud.nio.common.CloseUtil;
import redis.clients.jedis.Jedis;
public class JedisTest {
public static void main(String[] args) {
// 连接本地的 Redis 服务
Jedis jedis = new Jedis("localhost");
System.out.println("Connection to server sucessfully");
// 设置 redis 字符串数据
jedis.set("k1", "v1");
jedis.set("k2", "v2");
// 获取存储的数据并输出
String value = jedis.get("k1");
Set<String> keys = jedis.keys("*");
for(String k : keys){
System.out.println("KEY:"+k);
}
System.out.println("Stored string in redis:: " + value);
CloseUtil.close(jedis);
}
}
| 709 | 0.664145 | 0.656581 | 33 | 19.030304 | 18.084791 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.636364 | false | false | 9 |
a7250c5c2d74f0099f317b38d13af2754ab73c90 | 4,569,845,255,693 | b9cb6e6089085313cc64217e75841e19fe2200a5 | /app/src/main/java/com/example/zhulong/model/DatumModel.java | d9724bfdcaf98553442253b8d29df741f78d07f4 | [] | no_license | xb19960925/zlproject | https://github.com/xb19960925/zlproject | a1fc0c24f2a554b547b4392b150405931a33d199 | bf359b147e61ab2ed19f55b0d03f860e93a49def | refs/heads/master | 2022-11-05T09:15:30.506000 | 2020-06-16T11:33:21 | 2020-06-16T11:33:21 | 268,838,136 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.zhulong.model;
import android.content.Context;
import android.text.TextUtils;
import com.example.frame.ApiConfig;
import com.example.frame.ConnectionModel;
import com.example.frame.ConnectionPersenter;
import com.example.frame.FrameApplication;
import com.example.frame.Host;
import com.example.frame.NetManger;
import com.example.zhulong.ParamHashMap;
import com.example.zhulong.R;
import com.example.zhulong.base.Application1907;
import com.example.zhulong.constants.Method;
public class DatumModel implements ConnectionModel {
@Override
public void getNetData(ConnectionPersenter pPresenter, int whichApi, Object[] params) {
switch (whichApi) {
case ApiConfig.DATA_GROUP:
ParamHashMap add = new ParamHashMap().add("type", 1).add("fid", FrameApplication.getFrameApplication().getSelectedInfo().getFid()).add("page", params[1]);
NetManger.getInstance().netWork(NetManger.mService.getGroupList(Host.BBS_OPENAPI+ Method.GETGROUPLIST,add),pPresenter,whichApi,params[0]);
break;
case ApiConfig.CLICK_CANCEL_FOCUS:
ParamHashMap add1 = new ParamHashMap().add("group_id", params[0]).add("type", 1).add("screctKey", FrameApplication.getFrameApplicationContext().getString(R.string.secrectKey_posting));
NetManger.getInstance().netWork(NetManger.mService.removeFocus(Host.BBS_API+Method.REMOVEGROUP,add1),pPresenter,whichApi,params[1]);
break;
case ApiConfig.CLICK_TO_FOCUS:
ParamHashMap add2 = new ParamHashMap().add("gid", params[0]).add("group_name", params[1]).add("screctKey", FrameApplication.getFrameApplicationContext().getString(R.string.secrectKey_posting));
NetManger.getInstance().netWork(NetManger.mService.focus(Host.BBS_API+Method.JOINGROUP,add2),pPresenter,whichApi,params[2]);
break;
}
}
}
| UTF-8 | Java | 1,931 | java | DatumModel.java | Java | [] | null | [] | package com.example.zhulong.model;
import android.content.Context;
import android.text.TextUtils;
import com.example.frame.ApiConfig;
import com.example.frame.ConnectionModel;
import com.example.frame.ConnectionPersenter;
import com.example.frame.FrameApplication;
import com.example.frame.Host;
import com.example.frame.NetManger;
import com.example.zhulong.ParamHashMap;
import com.example.zhulong.R;
import com.example.zhulong.base.Application1907;
import com.example.zhulong.constants.Method;
public class DatumModel implements ConnectionModel {
@Override
public void getNetData(ConnectionPersenter pPresenter, int whichApi, Object[] params) {
switch (whichApi) {
case ApiConfig.DATA_GROUP:
ParamHashMap add = new ParamHashMap().add("type", 1).add("fid", FrameApplication.getFrameApplication().getSelectedInfo().getFid()).add("page", params[1]);
NetManger.getInstance().netWork(NetManger.mService.getGroupList(Host.BBS_OPENAPI+ Method.GETGROUPLIST,add),pPresenter,whichApi,params[0]);
break;
case ApiConfig.CLICK_CANCEL_FOCUS:
ParamHashMap add1 = new ParamHashMap().add("group_id", params[0]).add("type", 1).add("screctKey", FrameApplication.getFrameApplicationContext().getString(R.string.secrectKey_posting));
NetManger.getInstance().netWork(NetManger.mService.removeFocus(Host.BBS_API+Method.REMOVEGROUP,add1),pPresenter,whichApi,params[1]);
break;
case ApiConfig.CLICK_TO_FOCUS:
ParamHashMap add2 = new ParamHashMap().add("gid", params[0]).add("group_name", params[1]).add("screctKey", FrameApplication.getFrameApplicationContext().getString(R.string.secrectKey_posting));
NetManger.getInstance().netWork(NetManger.mService.focus(Host.BBS_API+Method.JOINGROUP,add2),pPresenter,whichApi,params[2]);
break;
}
}
}
| 1,931 | 0.718281 | 0.709477 | 36 | 52.638889 | 56.601509 | 209 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false | 9 |
d57ad9d366f1a1eb78521cc768f48512cff7a9c7 | 29,978,871,765,724 | dba87418d2286ce141d81deb947305a0eaf9824f | /sources/com/google/android/apps/analytics/Event.java | 85d267a070602249cfe89e8c93040eec995cc742 | [] | no_license | Sluckson/copyOavct | https://github.com/Sluckson/copyOavct | 1f73f47ce94bb08df44f2ba9f698f2e8589b5cf6 | d20597e14411e8607d1d6e93b632d0cd2e8af8cb | refs/heads/main | 2023-03-09T12:14:38.824000 | 2021-02-26T01:38:16 | 2021-02-26T01:38:16 | 341,292,450 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.android.apps.analytics;
import org.codehaus.jackson.util.MinimalPrettyPrinter;
class Event {
static final String INSTALL_EVENT_CATEGORY = "__##GOOGLEINSTALL##__";
static final String ITEM_CATEGORY = "__##GOOGLEITEM##__";
static final String PAGEVIEW_EVENT_CATEGORY = "__##GOOGLEPAGEVIEW##__";
static final String TRANSACTION_CATEGORY = "__##GOOGLETRANSACTION##__";
final String accountId;
final String action;
private int adHitId;
private boolean anonymizeIp;
final String category;
CustomVariableBuffer customVariableBuffer;
final long eventId;
private Item item;
final String label;
private int randomVal;
final int screenHeight;
final int screenWidth;
private int timestampCurrent;
private int timestampFirst;
private int timestampPrevious;
private Transaction transaction;
private boolean useServerTime;
private int userId;
final int value;
private int visits;
Event(long j, String str, int i, int i2, int i3, int i4, int i5, String str2, String str3, String str4, int i6, int i7, int i8) {
this.eventId = j;
this.accountId = str;
this.randomVal = i;
this.timestampFirst = i2;
this.timestampPrevious = i3;
this.timestampCurrent = i4;
this.visits = i5;
this.category = str2;
this.action = str3;
this.label = str4;
this.value = i6;
this.screenHeight = i8;
this.screenWidth = i7;
this.userId = -1;
this.useServerTime = false;
}
/* JADX WARNING: Illegal instructions before constructor call */
/* Code decompiled incorrectly, please refer to instructions dump. */
Event(com.google.android.apps.analytics.Event r18, java.lang.String r19) {
/*
r17 = this;
r15 = r17
r14 = r18
long r1 = r14.eventId
int r4 = r14.randomVal
int r5 = r14.timestampFirst
int r6 = r14.timestampPrevious
int r7 = r14.timestampCurrent
int r8 = r14.visits
java.lang.String r9 = r14.category
java.lang.String r10 = r14.action
java.lang.String r11 = r14.label
int r12 = r14.value
int r13 = r14.screenWidth
int r3 = r14.screenHeight
r0 = r17
r16 = r3
r3 = r19
r15 = r14
r14 = r16
r0.<init>(r1, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14)
int r0 = r15.adHitId
r1 = r17
r2 = r15
r1.adHitId = r0
int r0 = r2.userId
r1.userId = r0
boolean r0 = r2.anonymizeIp
r1.anonymizeIp = r0
boolean r0 = r2.useServerTime
r1.useServerTime = r0
com.google.android.apps.analytics.CustomVariableBuffer r0 = r2.customVariableBuffer
r1.customVariableBuffer = r0
com.google.android.apps.analytics.Transaction r0 = r2.transaction
r1.transaction = r0
com.google.android.apps.analytics.Item r0 = r2.item
r1.item = r0
return
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.android.apps.analytics.Event.<init>(com.google.android.apps.analytics.Event, java.lang.String):void");
}
Event(String str, String str2, String str3, String str4, int i, int i2, int i3) {
this(-1, str, -1, -1, -1, -1, -1, str2, str3, str4, i, i2, i3);
}
/* access modifiers changed from: package-private */
public int getAdHitId() {
return this.adHitId;
}
/* access modifiers changed from: package-private */
public boolean getAnonymizeIp() {
return this.anonymizeIp;
}
public CustomVariableBuffer getCustomVariableBuffer() {
return this.customVariableBuffer;
}
public Item getItem() {
return this.item;
}
/* access modifiers changed from: package-private */
public int getRandomVal() {
return this.randomVal;
}
/* access modifiers changed from: package-private */
public int getTimestampCurrent() {
return this.timestampCurrent;
}
/* access modifiers changed from: package-private */
public int getTimestampFirst() {
return this.timestampFirst;
}
/* access modifiers changed from: package-private */
public int getTimestampPrevious() {
return this.timestampPrevious;
}
public Transaction getTransaction() {
return this.transaction;
}
/* access modifiers changed from: package-private */
public boolean getUseServerTime() {
return this.useServerTime;
}
/* access modifiers changed from: package-private */
public int getUserId() {
return this.userId;
}
/* access modifiers changed from: package-private */
public int getVisits() {
return this.visits;
}
public boolean isSessionInitialized() {
return this.timestampFirst != -1;
}
/* access modifiers changed from: package-private */
public void setAdHitId(int i) {
this.adHitId = i;
}
/* access modifiers changed from: package-private */
public void setAnonymizeIp(boolean z) {
this.anonymizeIp = z;
}
public void setCustomVariableBuffer(CustomVariableBuffer customVariableBuffer2) {
this.customVariableBuffer = customVariableBuffer2;
}
public void setItem(Item item2) {
if (this.category.equals(ITEM_CATEGORY)) {
this.item = item2;
return;
}
throw new IllegalStateException("Attempted to add an item to an event of type " + this.category);
}
/* access modifiers changed from: package-private */
public void setRandomVal(int i) {
this.randomVal = i;
}
/* access modifiers changed from: package-private */
public void setTimestampCurrent(int i) {
this.timestampCurrent = i;
}
/* access modifiers changed from: package-private */
public void setTimestampFirst(int i) {
this.timestampFirst = i;
}
/* access modifiers changed from: package-private */
public void setTimestampPrevious(int i) {
this.timestampPrevious = i;
}
public void setTransaction(Transaction transaction2) {
if (this.category.equals(TRANSACTION_CATEGORY)) {
this.transaction = transaction2;
return;
}
throw new IllegalStateException("Attempted to add a transction to an event of type " + this.category);
}
/* access modifiers changed from: package-private */
public void setUseServerTime(boolean z) {
this.useServerTime = z;
}
/* access modifiers changed from: package-private */
public void setUserId(int i) {
this.userId = i;
}
/* access modifiers changed from: package-private */
public void setVisits(int i) {
this.visits = i;
}
public String toString() {
return "id:" + this.eventId + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "random:" + this.randomVal + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "timestampCurrent:" + this.timestampCurrent + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "timestampPrevious:" + this.timestampPrevious + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "timestampFirst:" + this.timestampFirst + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "visits:" + this.visits + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "value:" + this.value + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "category:" + this.category + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "action:" + this.action + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "label:" + this.label + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "width:" + this.screenWidth + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "height:" + this.screenHeight;
}
}
| UTF-8 | Java | 8,044 | java | Event.java | Java | [] | null | [] | package com.google.android.apps.analytics;
import org.codehaus.jackson.util.MinimalPrettyPrinter;
class Event {
static final String INSTALL_EVENT_CATEGORY = "__##GOOGLEINSTALL##__";
static final String ITEM_CATEGORY = "__##GOOGLEITEM##__";
static final String PAGEVIEW_EVENT_CATEGORY = "__##GOOGLEPAGEVIEW##__";
static final String TRANSACTION_CATEGORY = "__##GOOGLETRANSACTION##__";
final String accountId;
final String action;
private int adHitId;
private boolean anonymizeIp;
final String category;
CustomVariableBuffer customVariableBuffer;
final long eventId;
private Item item;
final String label;
private int randomVal;
final int screenHeight;
final int screenWidth;
private int timestampCurrent;
private int timestampFirst;
private int timestampPrevious;
private Transaction transaction;
private boolean useServerTime;
private int userId;
final int value;
private int visits;
Event(long j, String str, int i, int i2, int i3, int i4, int i5, String str2, String str3, String str4, int i6, int i7, int i8) {
this.eventId = j;
this.accountId = str;
this.randomVal = i;
this.timestampFirst = i2;
this.timestampPrevious = i3;
this.timestampCurrent = i4;
this.visits = i5;
this.category = str2;
this.action = str3;
this.label = str4;
this.value = i6;
this.screenHeight = i8;
this.screenWidth = i7;
this.userId = -1;
this.useServerTime = false;
}
/* JADX WARNING: Illegal instructions before constructor call */
/* Code decompiled incorrectly, please refer to instructions dump. */
Event(com.google.android.apps.analytics.Event r18, java.lang.String r19) {
/*
r17 = this;
r15 = r17
r14 = r18
long r1 = r14.eventId
int r4 = r14.randomVal
int r5 = r14.timestampFirst
int r6 = r14.timestampPrevious
int r7 = r14.timestampCurrent
int r8 = r14.visits
java.lang.String r9 = r14.category
java.lang.String r10 = r14.action
java.lang.String r11 = r14.label
int r12 = r14.value
int r13 = r14.screenWidth
int r3 = r14.screenHeight
r0 = r17
r16 = r3
r3 = r19
r15 = r14
r14 = r16
r0.<init>(r1, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14)
int r0 = r15.adHitId
r1 = r17
r2 = r15
r1.adHitId = r0
int r0 = r2.userId
r1.userId = r0
boolean r0 = r2.anonymizeIp
r1.anonymizeIp = r0
boolean r0 = r2.useServerTime
r1.useServerTime = r0
com.google.android.apps.analytics.CustomVariableBuffer r0 = r2.customVariableBuffer
r1.customVariableBuffer = r0
com.google.android.apps.analytics.Transaction r0 = r2.transaction
r1.transaction = r0
com.google.android.apps.analytics.Item r0 = r2.item
r1.item = r0
return
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.android.apps.analytics.Event.<init>(com.google.android.apps.analytics.Event, java.lang.String):void");
}
Event(String str, String str2, String str3, String str4, int i, int i2, int i3) {
this(-1, str, -1, -1, -1, -1, -1, str2, str3, str4, i, i2, i3);
}
/* access modifiers changed from: package-private */
public int getAdHitId() {
return this.adHitId;
}
/* access modifiers changed from: package-private */
public boolean getAnonymizeIp() {
return this.anonymizeIp;
}
public CustomVariableBuffer getCustomVariableBuffer() {
return this.customVariableBuffer;
}
public Item getItem() {
return this.item;
}
/* access modifiers changed from: package-private */
public int getRandomVal() {
return this.randomVal;
}
/* access modifiers changed from: package-private */
public int getTimestampCurrent() {
return this.timestampCurrent;
}
/* access modifiers changed from: package-private */
public int getTimestampFirst() {
return this.timestampFirst;
}
/* access modifiers changed from: package-private */
public int getTimestampPrevious() {
return this.timestampPrevious;
}
public Transaction getTransaction() {
return this.transaction;
}
/* access modifiers changed from: package-private */
public boolean getUseServerTime() {
return this.useServerTime;
}
/* access modifiers changed from: package-private */
public int getUserId() {
return this.userId;
}
/* access modifiers changed from: package-private */
public int getVisits() {
return this.visits;
}
public boolean isSessionInitialized() {
return this.timestampFirst != -1;
}
/* access modifiers changed from: package-private */
public void setAdHitId(int i) {
this.adHitId = i;
}
/* access modifiers changed from: package-private */
public void setAnonymizeIp(boolean z) {
this.anonymizeIp = z;
}
public void setCustomVariableBuffer(CustomVariableBuffer customVariableBuffer2) {
this.customVariableBuffer = customVariableBuffer2;
}
public void setItem(Item item2) {
if (this.category.equals(ITEM_CATEGORY)) {
this.item = item2;
return;
}
throw new IllegalStateException("Attempted to add an item to an event of type " + this.category);
}
/* access modifiers changed from: package-private */
public void setRandomVal(int i) {
this.randomVal = i;
}
/* access modifiers changed from: package-private */
public void setTimestampCurrent(int i) {
this.timestampCurrent = i;
}
/* access modifiers changed from: package-private */
public void setTimestampFirst(int i) {
this.timestampFirst = i;
}
/* access modifiers changed from: package-private */
public void setTimestampPrevious(int i) {
this.timestampPrevious = i;
}
public void setTransaction(Transaction transaction2) {
if (this.category.equals(TRANSACTION_CATEGORY)) {
this.transaction = transaction2;
return;
}
throw new IllegalStateException("Attempted to add a transction to an event of type " + this.category);
}
/* access modifiers changed from: package-private */
public void setUseServerTime(boolean z) {
this.useServerTime = z;
}
/* access modifiers changed from: package-private */
public void setUserId(int i) {
this.userId = i;
}
/* access modifiers changed from: package-private */
public void setVisits(int i) {
this.visits = i;
}
public String toString() {
return "id:" + this.eventId + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "random:" + this.randomVal + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "timestampCurrent:" + this.timestampCurrent + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "timestampPrevious:" + this.timestampPrevious + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "timestampFirst:" + this.timestampFirst + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "visits:" + this.visits + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "value:" + this.value + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "category:" + this.category + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "action:" + this.action + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "label:" + this.label + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "width:" + this.screenWidth + MinimalPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR + "height:" + this.screenHeight;
}
}
| 8,044 | 0.637618 | 0.616609 | 228 | 34.280701 | 66.832535 | 965 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52193 | false | false | 9 |
5c4b5b0c98a792616bac45794f83239abe21091b | 22,359,599,744,650 | a455967f30884e0569a9fc8b753d2e3cfd59495c | /java/nova-formats/src/main/java/es/elixir/bsc/ngs/nova/sam/header/ReadGroupLine.java | d1b2ae40dbf661e3a2e553db45f3f08b3d322b22 | [] | no_license | redmitry/gecoz | https://github.com/redmitry/gecoz | ee6648a5eed2e18b84793e98024a49d447ae9a52 | 5c2d6c8438226a829a18124f75c40eb0577078bd | refs/heads/master | 2021-06-05T05:32:08.962000 | 2020-12-01T12:27:05 | 2020-12-01T12:28:06 | 98,430,996 | 0 | 0 | null | false | 2020-10-12T20:13:51 | 2017-07-26T14:18:07 | 2019-08-08T11:02:21 | 2020-10-12T20:13:50 | 1,381 | 1 | 0 | 5 | Java | false | false | /**
* *****************************************************************************
* Copyright (C) 2019 Spanish National Bioinformatics Institute (INB) and
* Barcelona Supercomputing Center
*
* Modifications to the initial code base are copyright of their respective
* authors, or their employers as appropriate.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*****************************************************************************
*/
package es.elixir.bsc.ngs.nova.sam.header;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
/**
* @author Dmitry Repchevsky
*/
public class ReadGroupLine extends AbstractHeaderLine {
public final static String TAG = "@RG";
public final static String[] TAGS = {"ID", "BC", "CN", "DS", "DT", "FO",
"KS", "LB", "PG", "PI", "PL", "PM", "PU", "SM"};
public final String readGroupId;
public final String barcodes;
public final String sequencingCenter;
public final String description;
public final String date;
public final String flowOrder;
public final String keySequence;
public final String library;
public final String programs;
public final Double median;
public final ReadGroupLinePlatform platform;
public final String platformModel;
public final String platformUnit;
public final String sample;
public ReadGroupLine(
final String readGroupId,
final String barcodes,
final String sequencingCenter,
final String description,
final String date,
final String flowOrder,
final String keySequence,
final String library,
final String programs,
final Double median,
final ReadGroupLinePlatform platform,
final String platformModel,
final String platformUnit,
final String sample) {
this.readGroupId = readGroupId;
this.barcodes = barcodes;
this.sequencingCenter = sequencingCenter;
this.description = description;
this.date = date;
this.flowOrder = flowOrder;
this.keySequence = keySequence;
this.library = library;
this.programs = programs;
this.median = median;
this.platform = platform;
this.platformModel = platformModel;
this.platformUnit = platformUnit;
this.sample = sample;
}
public ReadGroupLine(final String line) {
final String[] tags = parseHeaderLine(line, Arrays.copyOf(TAGS, TAGS.length));
readGroupId = tags[0];
barcodes = tags[1];
sequencingCenter = tags[2];
description = tags[3];
date = tags[4];
flowOrder = tags[5];
keySequence = tags[6];
library = tags[7];
programs = tags[8];
median = tags[9] == null ? null : Double.valueOf(tags[9]);
platform = tags[10] == null ? null : ReadGroupLinePlatform.valueOf(tags[10]);
platformModel = tags[11];
platformUnit = tags[12];
sample = tags[13];
}
@Override
public void write(final PrintStream out) throws IOException {
out.append(TAG);
if (readGroupId != null) {
out.append("\tID:").append(readGroupId);
}
if(platform != null) {
out.append("\tPL:").print(platform);
}
if(platformUnit != null){
out.append("\tPU:").append(platformUnit);
}
if(library != null) {
out.append("\tLB:").append(library);
}
if(description != null) {
out.append("\tDS:").append(description);
}
if(barcodes != null) {
out.append("\tBC:").append(barcodes);
}
if(date != null) {
out.append("\tDT:").append(date);
}
if(flowOrder != null) {
out.append("\tFO:").append(flowOrder);
}
if(keySequence != null) {
out.append("\tKS:").append(keySequence);
}
if(programs != null) {
out.append("\tPG:").append(programs);
}
if(median != null) {
out.append("\tPI:").print(median);
}
if(platformModel != null) {
out.append("\tPM:").append(platformModel);
}
if(sample != null) {
out.append("\tSM:").append(sample);
}
if(sequencingCenter != null) {
out.append("\tCN:").append(sequencingCenter);
}
}
}
| UTF-8 | Java | 5,245 | java | ReadGroupLine.java | Java | [
{
"context": "ntStream;\nimport java.util.Arrays;\n\n/**\n * @author Dmitry Repchevsky\n */\n\npublic class ReadGroupLine extends AbstractHe",
"end": 1308,
"score": 0.986087441444397,
"start": 1291,
"tag": "NAME",
"value": "Dmitry Repchevsky"
}
] | null | [] | /**
* *****************************************************************************
* Copyright (C) 2019 Spanish National Bioinformatics Institute (INB) and
* Barcelona Supercomputing Center
*
* Modifications to the initial code base are copyright of their respective
* authors, or their employers as appropriate.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*****************************************************************************
*/
package es.elixir.bsc.ngs.nova.sam.header;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
/**
* @author <NAME>
*/
public class ReadGroupLine extends AbstractHeaderLine {
public final static String TAG = "@RG";
public final static String[] TAGS = {"ID", "BC", "CN", "DS", "DT", "FO",
"KS", "LB", "PG", "PI", "PL", "PM", "PU", "SM"};
public final String readGroupId;
public final String barcodes;
public final String sequencingCenter;
public final String description;
public final String date;
public final String flowOrder;
public final String keySequence;
public final String library;
public final String programs;
public final Double median;
public final ReadGroupLinePlatform platform;
public final String platformModel;
public final String platformUnit;
public final String sample;
public ReadGroupLine(
final String readGroupId,
final String barcodes,
final String sequencingCenter,
final String description,
final String date,
final String flowOrder,
final String keySequence,
final String library,
final String programs,
final Double median,
final ReadGroupLinePlatform platform,
final String platformModel,
final String platformUnit,
final String sample) {
this.readGroupId = readGroupId;
this.barcodes = barcodes;
this.sequencingCenter = sequencingCenter;
this.description = description;
this.date = date;
this.flowOrder = flowOrder;
this.keySequence = keySequence;
this.library = library;
this.programs = programs;
this.median = median;
this.platform = platform;
this.platformModel = platformModel;
this.platformUnit = platformUnit;
this.sample = sample;
}
public ReadGroupLine(final String line) {
final String[] tags = parseHeaderLine(line, Arrays.copyOf(TAGS, TAGS.length));
readGroupId = tags[0];
barcodes = tags[1];
sequencingCenter = tags[2];
description = tags[3];
date = tags[4];
flowOrder = tags[5];
keySequence = tags[6];
library = tags[7];
programs = tags[8];
median = tags[9] == null ? null : Double.valueOf(tags[9]);
platform = tags[10] == null ? null : ReadGroupLinePlatform.valueOf(tags[10]);
platformModel = tags[11];
platformUnit = tags[12];
sample = tags[13];
}
@Override
public void write(final PrintStream out) throws IOException {
out.append(TAG);
if (readGroupId != null) {
out.append("\tID:").append(readGroupId);
}
if(platform != null) {
out.append("\tPL:").print(platform);
}
if(platformUnit != null){
out.append("\tPU:").append(platformUnit);
}
if(library != null) {
out.append("\tLB:").append(library);
}
if(description != null) {
out.append("\tDS:").append(description);
}
if(barcodes != null) {
out.append("\tBC:").append(barcodes);
}
if(date != null) {
out.append("\tDT:").append(date);
}
if(flowOrder != null) {
out.append("\tFO:").append(flowOrder);
}
if(keySequence != null) {
out.append("\tKS:").append(keySequence);
}
if(programs != null) {
out.append("\tPG:").append(programs);
}
if(median != null) {
out.append("\tPI:").print(median);
}
if(platformModel != null) {
out.append("\tPM:").append(platformModel);
}
if(sample != null) {
out.append("\tSM:").append(sample);
}
if(sequencingCenter != null) {
out.append("\tCN:").append(sequencingCenter);
}
}
}
| 5,234 | 0.581316 | 0.574071 | 157 | 32.407642 | 20.882124 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.66879 | false | false | 9 |
741c090bc0e70d6fbc231dc51f88d76ae810f0e6 | 33,741,263,089,052 | d97248694d1a18cf0701a47258a2ec87bb245fdc | /src/main/java/com/nasa/mission/exceptions/MissionException.java | 3814513715857ad7db6c016b015f201909386ac1 | [] | no_license | JeffersonAlmeida/Mission | https://github.com/JeffersonAlmeida/Mission | 4c7b879bf057869f102f451a3a81e65806d7c494 | dba58b9c248464255a335575b0ae93ce97941318 | refs/heads/master | 2020-06-08T16:11:04.207000 | 2015-07-02T21:23:05 | 2015-07-02T21:27:36 | 37,743,903 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nasa.mission.exceptions;
import com.nasa.mission.erros.IError;
public class MissionException extends Exception{
private static final long serialVersionUID = 1L;
private IError error;
private String details;
public MissionException(IError error) {
this.error = error;
details = "";
}
public MissionException(IError error, String details) {
this(error);
this.details = details + "\n";
}
public void handle (){
System.out.println("\t " + error.getMessage());
if (details != null){
System.out.println("\t " + details);
}
}
public void setDetails(String details) {
this.details += details + "\n";
}
public IError getError() {
return error;
}
@Override
public String getMessage() {
return error.getMessage();
}
}
| UTF-8 | Java | 780 | java | MissionException.java | Java | [] | null | [] | package com.nasa.mission.exceptions;
import com.nasa.mission.erros.IError;
public class MissionException extends Exception{
private static final long serialVersionUID = 1L;
private IError error;
private String details;
public MissionException(IError error) {
this.error = error;
details = "";
}
public MissionException(IError error, String details) {
this(error);
this.details = details + "\n";
}
public void handle (){
System.out.println("\t " + error.getMessage());
if (details != null){
System.out.println("\t " + details);
}
}
public void setDetails(String details) {
this.details += details + "\n";
}
public IError getError() {
return error;
}
@Override
public String getMessage() {
return error.getMessage();
}
}
| 780 | 0.679487 | 0.678205 | 40 | 18.5 | 17.724277 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.475 | false | false | 9 |
63382b38aacaf3e0bf87e03fb237070399b2e259 | 18,657,337,959,880 | 44abad7f8813e88ff24255568f6d7c289d8ff380 | /src/main/java/dbf0/base/BaseClient.java | b14750b24a77e298c202e0d1a162988c325f2cf3 | [
"Apache-2.0"
] | permissive | floydlin/dbf0java | https://github.com/floydlin/dbf0java | 55a5abeffbc0b217b02f8c706f541955423bcd6b | 605b7cb93fda9dd831134cd832a24cf3aca7302e | refs/heads/master | 2023-03-31T02:54:44.721000 | 2020-12-11T14:45:11 | 2020-12-11T14:45:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dbf0.base;
import dbf0.common.Dbf0Util;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class BaseClient extends Thread {
private static final Logger LOGGER = Dbf0Util.getLogger(BaseClient.class);
private final Collection<? extends BaseConnector> connectors;
protected BaseClient(Collection<? extends BaseConnector> connectors) {
super("client");
this.connectors = connectors;
}
abstract protected void waitUntilComplete() throws InterruptedException;
@Override
public void run() {
LOGGER.info("Starting client with " + connectors.size() + " connectors");
connectors.forEach(BaseConnector::start);
try {
waitUntilComplete();
connectors.forEach(Thread::interrupt);
connectors.forEach(BaseConnector::closeSocket);
for (var thread : connectors) {
thread.join();
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, e, () -> "Error closing socket in " + this);
}
}
}
| UTF-8 | Java | 1,028 | java | BaseClient.java | Java | [] | null | [] | package dbf0.base;
import dbf0.common.Dbf0Util;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class BaseClient extends Thread {
private static final Logger LOGGER = Dbf0Util.getLogger(BaseClient.class);
private final Collection<? extends BaseConnector> connectors;
protected BaseClient(Collection<? extends BaseConnector> connectors) {
super("client");
this.connectors = connectors;
}
abstract protected void waitUntilComplete() throws InterruptedException;
@Override
public void run() {
LOGGER.info("Starting client with " + connectors.size() + " connectors");
connectors.forEach(BaseConnector::start);
try {
waitUntilComplete();
connectors.forEach(Thread::interrupt);
connectors.forEach(BaseConnector::closeSocket);
for (var thread : connectors) {
thread.join();
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, e, () -> "Error closing socket in " + this);
}
}
}
| 1,028 | 0.70428 | 0.700389 | 37 | 26.783783 | 25.52067 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.513514 | false | false | 9 |
b49e68ef498553b0be414f916ca7ca6b2af67af3 | 27,410,481,295,400 | 0def9c6f0d5890083e0c6e956fe43cd0c6876efa | /src/main/java/de/lostuxos/labs/AsyncTest/AsyncController.java | 49b8485d896216731d844922d6947a11e65b3511 | [] | no_license | jegolo/AsyncTest | https://github.com/jegolo/AsyncTest | 5204e810b9798f363c4492932da791830b4e7eb5 | 1f75cd716ecd12dbb75ae2055c86558a0ce0ca14 | refs/heads/main | 2023-06-07T12:05:54.886000 | 2021-06-22T20:36:30 | 2021-06-22T20:36:30 | 379,394,348 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.lostuxos.labs.AsyncTest;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
@Controller
public class AsyncController {
private Map<String, Future<String>> asyncMap = new ConcurrentHashMap<>();
@Autowired
private Calculator calculator;
@GetMapping(path="start")
public @ResponseBody String startRequest(@RequestParam String value) {
var uid = UUID.randomUUID().toString();
asyncMap.put(uid, calculator.calculate(value));
return uid;
}
@SneakyThrows
@GetMapping(path="result")
public ResponseEntity<String> result(@RequestParam String id) {
var resultValue = "Waiting";
if (asyncMap.containsKey(id)) {
var result = asyncMap.get(id);
if (result.isDone()) {
resultValue=result.get();
asyncMap.remove(id);
}
} else {
return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(resultValue, HttpStatus.OK);
}
}
| UTF-8 | Java | 1,535 | java | AsyncController.java | Java | [] | null | [] | package de.lostuxos.labs.AsyncTest;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
@Controller
public class AsyncController {
private Map<String, Future<String>> asyncMap = new ConcurrentHashMap<>();
@Autowired
private Calculator calculator;
@GetMapping(path="start")
public @ResponseBody String startRequest(@RequestParam String value) {
var uid = UUID.randomUUID().toString();
asyncMap.put(uid, calculator.calculate(value));
return uid;
}
@SneakyThrows
@GetMapping(path="result")
public ResponseEntity<String> result(@RequestParam String id) {
var resultValue = "Waiting";
if (asyncMap.containsKey(id)) {
var result = asyncMap.get(id);
if (result.isDone()) {
resultValue=result.get();
asyncMap.remove(id);
}
} else {
return new ResponseEntity<>("Not found", HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(resultValue, HttpStatus.OK);
}
}
| 1,535 | 0.700977 | 0.700977 | 48 | 30.958334 | 23.319304 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 9 |
2668ffe85f49bd32e5e5ba840c1b3f93fea30159 | 27,410,481,292,772 | 92952c8882aa9f41f63a499f954e940029ef22a9 | /room/app/src/main/java/com/zenzoori/room/MainActivity.java | a1fa3a963f2bfeacc8794a31a108b4966cd38464 | [] | no_license | supreedaoon/MyPoint | https://github.com/supreedaoon/MyPoint | e4d9597c4d4c892782f1bbdfdc75046724384093 | 1aaf6dc488c613c82526bef92c55daf9a49558e3 | refs/heads/master | 2020-07-13T04:23:59.753000 | 2019-09-10T13:57:08 | 2019-09-10T13:57:08 | 204,988,545 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zenzoori.room;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.sql.Array;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TargetViewModel targetViewModel;
private TextView sumPointTextView;
SharedPreferences record;
SharedPreferences.Editor recordEditor;
ArrayList<Target> allTarget = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Show total collected point
sumPointTextView = findViewById(R.id.sumPointTextView);
record = this.getSharedPreferences("RECORD", Context.MODE_PRIVATE);
recordEditor = record.edit();
sumPointTextView.setText("Total Collected Point = " + record.getInt("totalPoint",0));
//List all targeted activities
RecyclerView recyclerView = findViewById(R.id.recycle_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final TargetAdapter tAdapter = new TargetAdapter();
recyclerView.setAdapter(tAdapter);
targetViewModel = ViewModelProviders.of(this).get(TargetViewModel.class);
//targetViewModel.deleteAllTarget();
targetViewModel.getAllTarget().observe(this, new Observer<List<Target>>() {
@Override
public void onChanged(List<Target> targets) {
tAdapter.setAllTarget(targets);
//automatically generate activity
for(Target t: targets){
allTarget.add(t);
}
}
});
//Add new targeted activity
FloatingActionButton fab = findViewById(R.id.addFAB);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddEditTargetActivity.class);
startActivityForResult(intent, 1);
}
});
//Delete a targeted activity by swiping
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
targetViewModel.delete(tAdapter.getTargetAt(viewHolder.getAdapterPosition()));
Toast.makeText(MainActivity.this, "Target deleted", Toast.LENGTH_SHORT).show();
}
}).attachToRecyclerView(recyclerView);
//Edit a targeted activity by clicking on it.
//Click on 'Done' would mark the activity as finished. Assigned point would be accumulated in total point.
tAdapter.setOnItemClickListener(new TargetAdapter.OnItemClickListener() {
@Override
public void onItemClick(Target t) {
Intent intent = new Intent(MainActivity.this, AddEditTargetActivity.class);
intent.putExtra(AddEditTargetActivity.EXTRA_ID, t.getId());
intent.putExtra(AddEditTargetActivity.EXTRA_TARGET, t.getTarget());
intent.putExtra(AddEditTargetActivity.EXTRA_POINT, String.valueOf(t.getPoint()));
intent.putExtra(AddEditTargetActivity.EXTRA_TIME,t.getTime());
intent.putExtra(AddEditTargetActivity.EXTRA_ORIID,t.getOriID());
intent.putExtra(AddEditTargetActivity.EXTRA_REPEAT,t.isRepeat());
//RequestCode 2 == Edit
startActivityForResult(intent, 2);
}
@Override
public void onButtonClick(Target t) {
int sumPoint = record.getInt("totalPoint",0);
int currentPoint = t.getPoint();
sumPoint += currentPoint;
recordEditor.putInt("totalPoint", sumPoint);
recordEditor.commit();
sumPointTextView.setText("Total Collected Point = "+ sumPoint);
targetViewModel.delete(t);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int currentTime = Calendar.DAY_OF_MONTH;
//LocalDateTime currentTime = LocalDateTime.now();
//Create and edit targeted activities
if (requestCode == 1 && resultCode == RESULT_OK) {
//Create new activity
String target = data.getStringExtra(AddEditTargetActivity.EXTRA_TARGET);
String point = data.getStringExtra(AddEditTargetActivity.EXTRA_POINT);
Boolean repeat = data.getBooleanExtra(AddEditTargetActivity.EXTRA_REPEAT, false);
//For test purpose
Target newTarget = new Target(target, Integer.parseInt(point),19,-1,repeat);
targetViewModel.insert(newTarget);
//Toast.makeText(this, "Target saved", Toast.LENGTH_SHORT).show();
} else if(requestCode == 2 && resultCode == RESULT_OK){
int id = data.getIntExtra(AddEditTargetActivity.EXTRA_ID, -1);
//Something went wrong
if (id == -1) {
Toast.makeText(this, "Target can't be updated", Toast.LENGTH_SHORT).show();
return;
}
//Edit an existed target activity
String target = data.getStringExtra(AddEditTargetActivity.EXTRA_TARGET);
String point = data.getStringExtra(AddEditTargetActivity.EXTRA_POINT);
int time = data.getIntExtra(AddEditTargetActivity.EXTRA_TIME, -1);
Boolean repeat = data.getBooleanExtra(AddEditTargetActivity.EXTRA_REPEAT, false);
Target upTarget = new Target(target, Integer.parseInt(point), time, -1,repeat);
upTarget.setId(id);
targetViewModel.update(upTarget);
Toast.makeText(this, "Target updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Target not saved", Toast.LENGTH_SHORT).show();
}
}
//Reset total collected point (for test purpose)
public void resetSumPoint(int point){
recordEditor.putInt("totalPoint", point);
recordEditor.commit();
}
//Calculate number of automatically generated activities.
// (When user wish that the activity would be daily generated.)
public int checktime(int old, int current){
int currentMonth = Calendar.MONTH;
int diff = current - old;
int repeat;
if(diff >= 0){
repeat = diff;
}else{
if(currentMonth == 2){
repeat = diff + 29;
}else if(currentMonth == 4 || currentMonth == 6 ||currentMonth == 9 ||currentMonth == 11 ){
repeat = diff + 30;
}else {
repeat = diff + 31;
}
}
if (repeat > 3){
repeat = 3;
}
return repeat;
}
public void createTarget (View view){
int currentTime = Calendar.DAY_OF_MONTH;
ArrayList<Integer> processID = new ArrayList<>();
ArrayList<Target> repeatTarget = new ArrayList<>();
for(Target target :allTarget){
//check repeatable activity
if(target.isRepeat()) {
//this ID is not process yet
if (!processID.contains(target.getOriID())) {
Target newTarget = new Target(target.getTarget(),
target.getPoint(),
target.getTime(),
target.getOriID(),
target.isRepeat());
//mark that this ID already processed
//save new target
processID.add(target.getOriID());
repeatTarget.add(newTarget);
}
//delete all processed activity
targetViewModel.delete(target);
}
}
//automatically generate repeatable targeted activity
for(Target t: repeatTarget){
for(int i = 1; i <= checktime(t.getTime(),currentTime); i++){
targetViewModel.insert(t);
}
}
}
}
| UTF-8 | Java | 9,210 | java | MainActivity.java | Java | [] | null | [] | package com.zenzoori.room;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.sql.Array;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TargetViewModel targetViewModel;
private TextView sumPointTextView;
SharedPreferences record;
SharedPreferences.Editor recordEditor;
ArrayList<Target> allTarget = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Show total collected point
sumPointTextView = findViewById(R.id.sumPointTextView);
record = this.getSharedPreferences("RECORD", Context.MODE_PRIVATE);
recordEditor = record.edit();
sumPointTextView.setText("Total Collected Point = " + record.getInt("totalPoint",0));
//List all targeted activities
RecyclerView recyclerView = findViewById(R.id.recycle_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final TargetAdapter tAdapter = new TargetAdapter();
recyclerView.setAdapter(tAdapter);
targetViewModel = ViewModelProviders.of(this).get(TargetViewModel.class);
//targetViewModel.deleteAllTarget();
targetViewModel.getAllTarget().observe(this, new Observer<List<Target>>() {
@Override
public void onChanged(List<Target> targets) {
tAdapter.setAllTarget(targets);
//automatically generate activity
for(Target t: targets){
allTarget.add(t);
}
}
});
//Add new targeted activity
FloatingActionButton fab = findViewById(R.id.addFAB);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddEditTargetActivity.class);
startActivityForResult(intent, 1);
}
});
//Delete a targeted activity by swiping
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
targetViewModel.delete(tAdapter.getTargetAt(viewHolder.getAdapterPosition()));
Toast.makeText(MainActivity.this, "Target deleted", Toast.LENGTH_SHORT).show();
}
}).attachToRecyclerView(recyclerView);
//Edit a targeted activity by clicking on it.
//Click on 'Done' would mark the activity as finished. Assigned point would be accumulated in total point.
tAdapter.setOnItemClickListener(new TargetAdapter.OnItemClickListener() {
@Override
public void onItemClick(Target t) {
Intent intent = new Intent(MainActivity.this, AddEditTargetActivity.class);
intent.putExtra(AddEditTargetActivity.EXTRA_ID, t.getId());
intent.putExtra(AddEditTargetActivity.EXTRA_TARGET, t.getTarget());
intent.putExtra(AddEditTargetActivity.EXTRA_POINT, String.valueOf(t.getPoint()));
intent.putExtra(AddEditTargetActivity.EXTRA_TIME,t.getTime());
intent.putExtra(AddEditTargetActivity.EXTRA_ORIID,t.getOriID());
intent.putExtra(AddEditTargetActivity.EXTRA_REPEAT,t.isRepeat());
//RequestCode 2 == Edit
startActivityForResult(intent, 2);
}
@Override
public void onButtonClick(Target t) {
int sumPoint = record.getInt("totalPoint",0);
int currentPoint = t.getPoint();
sumPoint += currentPoint;
recordEditor.putInt("totalPoint", sumPoint);
recordEditor.commit();
sumPointTextView.setText("Total Collected Point = "+ sumPoint);
targetViewModel.delete(t);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int currentTime = Calendar.DAY_OF_MONTH;
//LocalDateTime currentTime = LocalDateTime.now();
//Create and edit targeted activities
if (requestCode == 1 && resultCode == RESULT_OK) {
//Create new activity
String target = data.getStringExtra(AddEditTargetActivity.EXTRA_TARGET);
String point = data.getStringExtra(AddEditTargetActivity.EXTRA_POINT);
Boolean repeat = data.getBooleanExtra(AddEditTargetActivity.EXTRA_REPEAT, false);
//For test purpose
Target newTarget = new Target(target, Integer.parseInt(point),19,-1,repeat);
targetViewModel.insert(newTarget);
//Toast.makeText(this, "Target saved", Toast.LENGTH_SHORT).show();
} else if(requestCode == 2 && resultCode == RESULT_OK){
int id = data.getIntExtra(AddEditTargetActivity.EXTRA_ID, -1);
//Something went wrong
if (id == -1) {
Toast.makeText(this, "Target can't be updated", Toast.LENGTH_SHORT).show();
return;
}
//Edit an existed target activity
String target = data.getStringExtra(AddEditTargetActivity.EXTRA_TARGET);
String point = data.getStringExtra(AddEditTargetActivity.EXTRA_POINT);
int time = data.getIntExtra(AddEditTargetActivity.EXTRA_TIME, -1);
Boolean repeat = data.getBooleanExtra(AddEditTargetActivity.EXTRA_REPEAT, false);
Target upTarget = new Target(target, Integer.parseInt(point), time, -1,repeat);
upTarget.setId(id);
targetViewModel.update(upTarget);
Toast.makeText(this, "Target updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Target not saved", Toast.LENGTH_SHORT).show();
}
}
//Reset total collected point (for test purpose)
public void resetSumPoint(int point){
recordEditor.putInt("totalPoint", point);
recordEditor.commit();
}
//Calculate number of automatically generated activities.
// (When user wish that the activity would be daily generated.)
public int checktime(int old, int current){
int currentMonth = Calendar.MONTH;
int diff = current - old;
int repeat;
if(diff >= 0){
repeat = diff;
}else{
if(currentMonth == 2){
repeat = diff + 29;
}else if(currentMonth == 4 || currentMonth == 6 ||currentMonth == 9 ||currentMonth == 11 ){
repeat = diff + 30;
}else {
repeat = diff + 31;
}
}
if (repeat > 3){
repeat = 3;
}
return repeat;
}
public void createTarget (View view){
int currentTime = Calendar.DAY_OF_MONTH;
ArrayList<Integer> processID = new ArrayList<>();
ArrayList<Target> repeatTarget = new ArrayList<>();
for(Target target :allTarget){
//check repeatable activity
if(target.isRepeat()) {
//this ID is not process yet
if (!processID.contains(target.getOriID())) {
Target newTarget = new Target(target.getTarget(),
target.getPoint(),
target.getTime(),
target.getOriID(),
target.isRepeat());
//mark that this ID already processed
//save new target
processID.add(target.getOriID());
repeatTarget.add(newTarget);
}
//delete all processed activity
targetViewModel.delete(target);
}
}
//automatically generate repeatable targeted activity
for(Target t: repeatTarget){
for(int i = 1; i <= checktime(t.getTime(),currentTime); i++){
targetViewModel.insert(t);
}
}
}
}
| 9,210 | 0.617915 | 0.614549 | 244 | 36.745903 | 29.04718 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.688525 | false | false | 9 |
52a9fbdf83bb292982f1f8424c2169a42e1d360a | 9,826,885,203,172 | a3739afed4530a16ce2b9c239b3da779a0daa690 | /CarbookLogin/app/src/main/java/it/rizzoli/carbooklogin/Registrazione.java | 73ca798097a14d2f33f3bf47dfcf8d42271aa422 | [] | no_license | LucaNastasi/LibroAuto | https://github.com/LucaNastasi/LibroAuto | 8464f96a737522e856c100e3b7b4225602ea0fc5 | f0121e6975628714bf2b2b61b93babdba1a68bd4 | refs/heads/master | 2023-04-18T15:06:40.425000 | 2021-03-08T17:35:07 | 2021-03-08T17:35:07 | 321,686,845 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.rizzoli.carbooklogin;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import database.Persona;
import database.PersonaDbAdapter;
public class Registrazione extends AppCompatActivity {
PersonaDbAdapter pdb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrazione);
pdb = new PersonaDbAdapter(this);
pdb.open();
EditText nameEt = findViewById(R.id.nameEditText);
EditText surnameEt = findViewById(R.id.surnameEditText);
EditText emailEt = findViewById(R.id.emailEditText);
EditText usernameEt = findViewById(R.id.usernameEditText);
EditText passwordEt = findViewById(R.id.passwordEditText);
EditText etaEt = findViewById(R.id.ageEditText);
EditText cittaEt = findViewById(R.id.cityEditText);
Button buttonSign = findViewById(R.id.signupButton);
buttonSign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nome = nameEt.getText().toString();
String cognome = surnameEt.getText().toString();
String email = emailEt.getText().toString();
String username = usernameEt.getText().toString();
String password = passwordEt.getText().toString();
int eta = 25;//Integer.getInteger(etaEditText.getText().toString());
String citta = cittaEt.getText().toString();
Persona persona = new Persona();
persona.setEmail(email);
persona.setNome(nome);
persona.setCognome(cognome);
persona.setUsername(username);
persona.setPassword(password);
persona.setEta(eta);
persona.setCitta(citta);
pdb.insertPersona(persona);
}
});
}
@Override
protected void onStop() {
super.onStop();
if (pdb != null)
pdb.close();
}
} | UTF-8 | Java | 2,222 | java | Registrazione.java | Java | [
{
"context": "ome(cognome);\n persona.setUsername(username);\n persona.setPassword(password);\n",
"end": 1890,
"score": 0.9731035828590393,
"start": 1882,
"tag": "USERNAME",
"value": "username"
},
{
"context": "me(username);\n persona.setP... | null | [] | package it.rizzoli.carbooklogin;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import database.Persona;
import database.PersonaDbAdapter;
public class Registrazione extends AppCompatActivity {
PersonaDbAdapter pdb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrazione);
pdb = new PersonaDbAdapter(this);
pdb.open();
EditText nameEt = findViewById(R.id.nameEditText);
EditText surnameEt = findViewById(R.id.surnameEditText);
EditText emailEt = findViewById(R.id.emailEditText);
EditText usernameEt = findViewById(R.id.usernameEditText);
EditText passwordEt = findViewById(R.id.passwordEditText);
EditText etaEt = findViewById(R.id.ageEditText);
EditText cittaEt = findViewById(R.id.cityEditText);
Button buttonSign = findViewById(R.id.signupButton);
buttonSign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nome = nameEt.getText().toString();
String cognome = surnameEt.getText().toString();
String email = emailEt.getText().toString();
String username = usernameEt.getText().toString();
String password = passwordEt.getText().toString();
int eta = 25;//Integer.getInteger(etaEditText.getText().toString());
String citta = cittaEt.getText().toString();
Persona persona = new Persona();
persona.setEmail(email);
persona.setNome(nome);
persona.setCognome(cognome);
persona.setUsername(username);
persona.setPassword(<PASSWORD>);
persona.setEta(eta);
persona.setCitta(citta);
pdb.insertPersona(persona);
}
});
}
@Override
protected void onStop() {
super.onStop();
if (pdb != null)
pdb.close();
}
} | 2,224 | 0.625563 | 0.624662 | 65 | 33.200001 | 23.683945 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.630769 | false | false | 9 |
fb54e3e725865603d20dbf3db311f1c282a547bc | 15,066,745,277,979 | 87d72629cb59b2651a259b8dc1716708126b92b4 | /src/main/java/com/zhaoxiang/rocketmq/quickStart/Consumer.java | 254487fcd7221c824996cd54d478b3e033629843 | [] | no_license | RiversLau/jms-study | https://github.com/RiversLau/jms-study | bacdd8abf7965f05a766ad5428f3f7d446f750b4 | 697aea78b1e07bdd8c7133afe6310cdf5542d32d | refs/heads/master | 2021-01-20T01:50:41.281000 | 2017-09-14T09:39:05 | 2017-09-14T09:39:05 | 101,302,517 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zhaoxiang.rocketmq.quickStart;
import com.zhaoxiang.rocketmq.RocketMQConstants;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import java.util.List;
/**
* Author: RiversLau
* Date: 2017/9/4 17:27
*/
public class Consumer {
public static void main(String[] args) throws MQClientException {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("master-slave");
consumer.setNamesrvAddr(RocketMQConstants.NAMESRVADDR);
// consumer.setMessageModel(MessageModel.CLUSTERING);
consumer.setInstanceName("Producer");
consumer.subscribe("msTopic", "TagA||TagB");
consumer.registerMessageListener(new MessageListenerConcurrently() {
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
String brokerName = consumeConcurrentlyContext.getMessageQueue().getBrokerName();
for (MessageExt messageExt : list) {
System.out.println(messageExt.getBornHostString() + ":" + messageExt.getStoreHost().toString());
System.out.println(brokerName + ":" + messageExt.getTopic() + ":" + messageExt.getTags() + ":" + new String(messageExt.getBody()));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
consumer.start();
}
}
| UTF-8 | Java | 1,783 | java | Consumer.java | Java | [
{
"context": "essageExt;\n\nimport java.util.List;\n\n/**\n * Author: RiversLau\n * Date: 2017/9/4 17:27\n */\npublic class Consum",
"end": 563,
"score": 0.7270284295082092,
"start": 556,
"tag": "USERNAME",
"value": "RiversL"
},
{
"context": "t;\n\nimport java.util.List;\n\n/**\n * A... | null | [] | package com.zhaoxiang.rocketmq.quickStart;
import com.zhaoxiang.rocketmq.RocketMQConstants;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import java.util.List;
/**
* Author: RiversLau
* Date: 2017/9/4 17:27
*/
public class Consumer {
public static void main(String[] args) throws MQClientException {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("master-slave");
consumer.setNamesrvAddr(RocketMQConstants.NAMESRVADDR);
// consumer.setMessageModel(MessageModel.CLUSTERING);
consumer.setInstanceName("Producer");
consumer.subscribe("msTopic", "TagA||TagB");
consumer.registerMessageListener(new MessageListenerConcurrently() {
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
String brokerName = consumeConcurrentlyContext.getMessageQueue().getBrokerName();
for (MessageExt messageExt : list) {
System.out.println(messageExt.getBornHostString() + ":" + messageExt.getStoreHost().toString());
System.out.println(brokerName + ":" + messageExt.getTopic() + ":" + messageExt.getTags() + ":" + new String(messageExt.getBody()));
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
consumer.start();
}
}
| 1,783 | 0.720135 | 0.714526 | 42 | 41.452381 | 39.740948 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 9 |
507b33a4e4a7af815502ce84c53af9872c51abcb | 29,712,583,755,196 | 8c181b0ce3c8fe2ab4389c06ab74f199c7f217e0 | /design/src/main/java/com/example/design/struct/composite/CompositePatternDemo.java | fe79cd92c61a3559eeb72a9b81024967f7ce6fd7 | [] | no_license | apple-tm/design-world | https://github.com/apple-tm/design-world | f1976d268a23ffa54f27ead1d085633bc08cae75 | 1d8261a8a605870868b091c311391c0406a221ee | refs/heads/main | 2023-05-31T23:05:42.851000 | 2021-06-16T02:47:49 | 2021-06-16T02:47:49 | 337,002,995 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.design.struct.composite;
public class CompositePatternDemo {
public static void main(String[] args) {
Employee CEO = new Employee("John","CEO", 30000);
Employee headSales = new Employee("Robert","Head Sales", 20000);
Employee headMarketing = new Employee("Michel","Head Marketing", 20000);
Employee clerk1 = new Employee("Laura","Marketing", 10000);
Employee clerk2 = new Employee("Bob","Marketing", 10000);
Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
Employee salesExecutive2 = new Employee("Rob","Sales", 10000);
CEO.add(headSales);
CEO.add(headMarketing);
headSales.add(salesExecutive1);
headSales.add(salesExecutive2);
headMarketing.add(clerk1);
headMarketing.add(clerk2);
print(CEO);
}
private static void print(Employee employee) {
if (employee !=null) {
System.out.println(employee);
if (employee.getSubordinates().size() > 0) {
employee.getSubordinates().forEach(e -> print(e));
}
}
}
}
| UTF-8 | Java | 1,146 | java | CompositePatternDemo.java | Java | [
{
"context": "ng[] args) {\n Employee CEO = new Employee(\"John\",\"CEO\", 30000);\n\n Employee headSales = new",
"end": 169,
"score": 0.9998786449432373,
"start": 165,
"tag": "NAME",
"value": "John"
},
{
"context": "000);\n\n Employee headSales = new Employee(\"... | null | [] | package com.example.design.struct.composite;
public class CompositePatternDemo {
public static void main(String[] args) {
Employee CEO = new Employee("John","CEO", 30000);
Employee headSales = new Employee("Robert","Head Sales", 20000);
Employee headMarketing = new Employee("Michel","Head Marketing", 20000);
Employee clerk1 = new Employee("Laura","Marketing", 10000);
Employee clerk2 = new Employee("Bob","Marketing", 10000);
Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
Employee salesExecutive2 = new Employee("Rob","Sales", 10000);
CEO.add(headSales);
CEO.add(headMarketing);
headSales.add(salesExecutive1);
headSales.add(salesExecutive2);
headMarketing.add(clerk1);
headMarketing.add(clerk2);
print(CEO);
}
private static void print(Employee employee) {
if (employee !=null) {
System.out.println(employee);
if (employee.getSubordinates().size() > 0) {
employee.getSubordinates().forEach(e -> print(e));
}
}
}
}
| 1,146 | 0.614311 | 0.575916 | 39 | 28.384615 | 26.735758 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.794872 | false | false | 9 |
9ecab2cac5a10fd44570a1971c51c568c542f4e2 | 32,143,535,275,407 | d7df3b9232b21124d835317e26f3783ddd37f45e | /src/main/java/com/works/vetrestapi/repositories/AnimalRepository.java | be6a771b3b55ce1a9cf6aad7723609d4f5c3a10c | [
"MIT"
] | permissive | Sahsanem/Java-RestApi-Mysql-Vet-Clinic-Service | https://github.com/Sahsanem/Java-RestApi-Mysql-Vet-Clinic-Service | fab6a97550f7f3fb63603f31fe24e434de5fdb5e | e05e5e26838da8a88591deed1690cb1226c1291e | refs/heads/main | 2023-08-07T19:28:37.166000 | 2021-10-07T18:03:17 | 2021-10-07T18:03:17 | 414,695,492 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.works.vetrestapi.repositories;
import com.works.vetrestapi.entities.Animal;
import com.works.vetrestapi.entities.AnimalCustomer;
import com.works.vetrestapi.entities.Animals;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface AnimalRepository extends JpaRepository<Animal,Integer> {
@Query(value = "select a.P_NAME,a.AID from ANIMAL as a INNER JOIN CUSTOMER as c ON c.C_NO=a.CUS_NO WHERE a.CUS_NO=?1",nativeQuery = true)
List<AnimalCustomer> animalCustomer(int cus_no);
@Query(value = "select COUNT( AID) as totalAnmal from ANIMAL",nativeQuery = true)
List<Animals> totalAnimal();
}
| UTF-8 | Java | 725 | java | AnimalRepository.java | Java | [] | null | [] | package com.works.vetrestapi.repositories;
import com.works.vetrestapi.entities.Animal;
import com.works.vetrestapi.entities.AnimalCustomer;
import com.works.vetrestapi.entities.Animals;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface AnimalRepository extends JpaRepository<Animal,Integer> {
@Query(value = "select a.P_NAME,a.AID from ANIMAL as a INNER JOIN CUSTOMER as c ON c.C_NO=a.CUS_NO WHERE a.CUS_NO=?1",nativeQuery = true)
List<AnimalCustomer> animalCustomer(int cus_no);
@Query(value = "select COUNT( AID) as totalAnmal from ANIMAL",nativeQuery = true)
List<Animals> totalAnimal();
}
| 725 | 0.776552 | 0.775172 | 22 | 31.954546 | 36.396149 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.590909 | false | false | 9 |
f36fc5c8b755a0539e076659b061d43a2987aea5 | 1,786,706,419,554 | 9d82eacd1494671267c19bb7386e2e0aa7ea927b | /msa/src/msa12/A.java | b726992d08091ed40f3877722f30d87fa4fa0691 | [] | no_license | yl9517/ETC_java_jsp | https://github.com/yl9517/ETC_java_jsp | 2edbf3f953db03df375c5cfa6462b3989936e8ef | 77b19d9b52af986a35549a8f1f9cbb14d8b541ce | refs/heads/main | 2023-07-04T01:39:33.203000 | 2021-08-12T12:26:57 | 2021-08-12T12:26:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package msa12;
public class A {
/*
* 11일차 문제 -> String -> Object ->objectEqu -> Ref
*
* [object] - 최상위 클래스
*
* 객체이름 출력시 toString 자동호출
* p1.equals(p2); // 객체가 가르키는 메모리 비교 false ▶ 툴로 equals와 hashCode 모두 재정의
*
*/
}
| UHC | Java | 329 | java | A.java | Java | [] | null | [] | package msa12;
public class A {
/*
* 11일차 문제 -> String -> Object ->objectEqu -> Ref
*
* [object] - 최상위 클래스
*
* 객체이름 출력시 toString 자동호출
* p1.equals(p2); // 객체가 가르키는 메모리 비교 false ▶ 툴로 equals와 hashCode 모두 재정의
*
*/
}
| 329 | 0.546939 | 0.522449 | 13 | 17.846153 | 22.187475 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.153846 | false | false | 9 |
0fbfb239e2251d70d76bfb75c1cd791ae155373e | 21,835,613,799,682 | 8f731d5916988ef45bc4c5ea05cbb3eb760ffa42 | /Java Course/spellchecker/test/SimilarWordsGeneratorTest.java | 1a038d7088e0a5a56be8489cef182745e633e379 | [] | no_license | RosinaGeorgieva/Bachelor-Studies | https://github.com/RosinaGeorgieva/Bachelor-Studies | a3363bf28c368baf4b2ddb720975d0040ca420ce | 57239d64db862604e6843924ebd3930c7fadde67 | refs/heads/master | 2023-02-28T11:35:32.872000 | 2021-02-03T16:38:44 | 2021-02-03T16:38:44 | 307,678,455 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import dictionaries.Dictionary;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import similarwords.SimilarWordsGenerator;
import similarwords.SimilarityCoefficient;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class SimilarWordsGeneratorTest { //oshte testove est
private static final String WORD = "hello";
private static final String FIRST_SIMILAR = "hallo";
private static SimilarityCoefficient firstCoefficient;
private static final String SECOND_SIMILAR = "help";
private static SimilarityCoefficient secondCoefficient;
private static TreeMap<SimilarityCoefficient, ArrayList<String>> expectedSuggestionsBySimilarity;
@Mock
private Dictionary dictionary;
@Before
public void setUp(){
firstCoefficient = new SimilarityCoefficient(0.5);
secondCoefficient = new SimilarityCoefficient(0.58); //da se iznesat
expectedSuggestionsBySimilarity = new TreeMap<>();
expectedSuggestionsBySimilarity.put(firstCoefficient, new ArrayList<>(List.of(FIRST_SIMILAR)));
expectedSuggestionsBySimilarity.put(secondCoefficient, new ArrayList<>(List.of(SECOND_SIMILAR)));
}
@Test
public void testGenerate(){
when(dictionary.getWords()).thenReturn(Set.of(FIRST_SIMILAR, SECOND_SIMILAR));
assertEquals(expectedSuggestionsBySimilarity, SimilarWordsGenerator.generate(WORD, dictionary));
}
}
| UTF-8 | Java | 1,750 | java | SimilarWordsGeneratorTest.java | Java | [] | null | [] | import dictionaries.Dictionary;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import similarwords.SimilarWordsGenerator;
import similarwords.SimilarityCoefficient;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class SimilarWordsGeneratorTest { //oshte testove est
private static final String WORD = "hello";
private static final String FIRST_SIMILAR = "hallo";
private static SimilarityCoefficient firstCoefficient;
private static final String SECOND_SIMILAR = "help";
private static SimilarityCoefficient secondCoefficient;
private static TreeMap<SimilarityCoefficient, ArrayList<String>> expectedSuggestionsBySimilarity;
@Mock
private Dictionary dictionary;
@Before
public void setUp(){
firstCoefficient = new SimilarityCoefficient(0.5);
secondCoefficient = new SimilarityCoefficient(0.58); //da se iznesat
expectedSuggestionsBySimilarity = new TreeMap<>();
expectedSuggestionsBySimilarity.put(firstCoefficient, new ArrayList<>(List.of(FIRST_SIMILAR)));
expectedSuggestionsBySimilarity.put(secondCoefficient, new ArrayList<>(List.of(SECOND_SIMILAR)));
}
@Test
public void testGenerate(){
when(dictionary.getWords()).thenReturn(Set.of(FIRST_SIMILAR, SECOND_SIMILAR));
assertEquals(expectedSuggestionsBySimilarity, SimilarWordsGenerator.generate(WORD, dictionary));
}
}
| 1,750 | 0.752571 | 0.749714 | 45 | 36.888889 | 29.913372 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 9 |
5512a7200c478fabc92ca454a6580566ed070749 | 27,075,473,855,217 | 4db042db5069f84f77087fa23a462c94ebe45bbf | /src/com/syntax/class24/Task1.java | 35560dd1d7444bc629631227b1eb83f04e8e3ebc | [] | no_license | guccukyavuz81/yavuz | https://github.com/guccukyavuz81/yavuz | 208af4f162a6b1a632f89993cb8979f974314f1a | 428c2780f729550eade7ceebf0c28ae31040b854 | refs/heads/master | 2022-11-23T15:19:30.665000 | 2020-07-30T04:27:16 | 2020-07-30T04:27:16 | 246,451,263 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.syntax.class24;
interface Device{
abstract void download();
abstract void upload();
}
abstract class Computer implements Device{
String brand;
int ram;
public Computer(String brand, int ram) {
this.brand = brand;
this.ram = ram;
}
void run(){
System.out.println(brand+ram+" runs");
}
void process(){
System.out.println(brand+ram+" processes");
}
}
class Apple extends Computer{
public Apple(String brand, int ram) {
super(brand, ram);
}
@Override
public void download() {
System.out.println(brand+ram+" pis download eder");
}
@Override
public void upload() {
System.out.println(brand+ram+" pis upload eder acimaz");
}
}
class Lenovo extends Computer{
public Lenovo(String brand, int ram) {
super(brand, ram);
}
@Override
public void download() {
System.out.println(brand+ram+" iyi ceker");
}
@Override
public void upload() {
System.out.println(brand+ram+" manyak yukler");
}
}
class HP extends Computer{
public HP(String brand, int ram) {
super(brand, ram);
System.out.println();
}
@Override
public void download() {
System.out.println(ram+brand+" ayipsin indirir");
}
@Override
public void upload() {
System.out.println(ram+brand+" oo manyak iter");
}
}
class Dell extends Computer{
public Dell(String brand, int ram) {
super(brand, ram);
}
@Override
public void download() {
System.out.println(ram+brand+" yarar gecer indirir");
}
@Override
public void upload() {
System.out.println(ram+brand+" acayip yukler");
}
}
public class Task1 {
public static void main(String[] args) {
//Create a Class Computer that will have 4 subclasses as Apple, Lenovo, HP, Dell.
//Define common behavior within and some fields in parent class and override some of the methods in child classes
//Define some methods specific to child classes
//Create objects of child classes and store them into array. Loop through each object and execute available methods.
Computer [] comp= {new Apple("mac",16),new Lenovo("thinkpad",8),new HP("heycpi",4),new Dell("kraldell",32)};
for(Computer c:comp) {
c.run();
c.process();
c.download();
c.upload();
System.out.println("--------------------------------------");
}
}
}
| UTF-8 | Java | 2,238 | java | Task1.java | Java | [] | null | [] | package com.syntax.class24;
interface Device{
abstract void download();
abstract void upload();
}
abstract class Computer implements Device{
String brand;
int ram;
public Computer(String brand, int ram) {
this.brand = brand;
this.ram = ram;
}
void run(){
System.out.println(brand+ram+" runs");
}
void process(){
System.out.println(brand+ram+" processes");
}
}
class Apple extends Computer{
public Apple(String brand, int ram) {
super(brand, ram);
}
@Override
public void download() {
System.out.println(brand+ram+" pis download eder");
}
@Override
public void upload() {
System.out.println(brand+ram+" pis upload eder acimaz");
}
}
class Lenovo extends Computer{
public Lenovo(String brand, int ram) {
super(brand, ram);
}
@Override
public void download() {
System.out.println(brand+ram+" iyi ceker");
}
@Override
public void upload() {
System.out.println(brand+ram+" manyak yukler");
}
}
class HP extends Computer{
public HP(String brand, int ram) {
super(brand, ram);
System.out.println();
}
@Override
public void download() {
System.out.println(ram+brand+" ayipsin indirir");
}
@Override
public void upload() {
System.out.println(ram+brand+" oo manyak iter");
}
}
class Dell extends Computer{
public Dell(String brand, int ram) {
super(brand, ram);
}
@Override
public void download() {
System.out.println(ram+brand+" yarar gecer indirir");
}
@Override
public void upload() {
System.out.println(ram+brand+" acayip yukler");
}
}
public class Task1 {
public static void main(String[] args) {
//Create a Class Computer that will have 4 subclasses as Apple, Lenovo, HP, Dell.
//Define common behavior within and some fields in parent class and override some of the methods in child classes
//Define some methods specific to child classes
//Create objects of child classes and store them into array. Loop through each object and execute available methods.
Computer [] comp= {new Apple("mac",16),new Lenovo("thinkpad",8),new HP("heycpi",4),new Dell("kraldell",32)};
for(Computer c:comp) {
c.run();
c.process();
c.download();
c.upload();
System.out.println("--------------------------------------");
}
}
}
| 2,238 | 0.672922 | 0.668454 | 97 | 22.072165 | 24.478161 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.556701 | false | false | 9 |
3f1bcf10b4c1915638af7d03d125d60cae3e579b | 1,245,540,522,855 | fc9d989e035f75c000677320bde8409860df1361 | /src/test/java/gd/engineering/httplogmonitor/model/metrics/InMemoryMetricsStoreTest.java | fa0767b34cacdada922b7a2afa1b9903ce65c25d | [] | no_license | airrr/http-log-monitor | https://github.com/airrr/http-log-monitor | 446725eced0047bce9414cff83219f32a14a9717 | 73ed589551c8ba38b242e849f9d8f1f8ea462872 | refs/heads/master | 2020-04-05T00:57:22.177000 | 2018-11-06T16:58:02 | 2018-11-06T16:58:02 | 156,417,405 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gd.engineering.httplogmonitor.model.metrics;
import org.junit.Assert;
import org.junit.Test;
public class InMemoryMetricsStoreTest {
@Test
public void testCurrentCounterValue() {
InMemoryMetricsStore store = buildStore();
Assert.assertEquals(30, store.getTotalSumCounterValue("test"));
Assert.assertEquals(40, store.getTotalSumCounterValue("test2"));
Assert.assertEquals(30, store.getTotalSumCounterValue("test3"));
Assert.assertEquals(0, store.getTotalSumCounterValue("test4"));
}
@Test
public void testAverageCounterValue() {
InMemoryMetricsStore store = buildStore();
int value = store.getAverageCounterValue("test", 5L, 3L);
Assert.assertEquals(10, value);
value = store.getAverageCounterValue("test", 5L, 4L);
Assert.assertEquals(15, value);
value = store.getAverageCounterValue("test", 5L, 1L);
Assert.assertEquals(0, value);
value = store.getAverageCounterValue("test2", 3L, 1L);
Assert.assertEquals(0, value);
value = store.getAverageCounterValue("test2", 3L, 2L);
Assert.assertEquals(20, value);
value = store.getAverageCounterValue("test3", 3L, 1L);
Assert.assertEquals(30, value);
value = store.getAverageCounterValue("test3", 3L, 2L);
Assert.assertEquals(15, value);
}
@Test
public void testSumCounterValue() {
InMemoryMetricsStore store = buildStore();
int value = store.getSumCounterValue("test", 5L, 1L);
Assert.assertEquals(0, value);
value = store.getSumCounterValue("test", 5L, 3L);
Assert.assertEquals(10, value);
value = store.getSumCounterValue("test", 5L, 4L);
Assert.assertEquals(30, value);
value = store.getSumCounterValue("test2", 5L, 3L);
Assert.assertEquals(0, value);
value = store.getSumCounterValue("test2", 5L, 4L);
Assert.assertEquals(40, value);
value = store.getSumCounterValue("test2", 1L, 2L);
Assert.assertEquals(0, value);
}
@Test
public void testAverageRateValue() {
InMemoryMetricsStore store = buildStore();
int value = store.getAverageRateValue("test", 5L, 1L);
Assert.assertEquals(0, value);
value = store.getAverageRateValue("test", 5L, 3L);
Assert.assertEquals(1, value);
value = store.getAverageRateValue("test", 5L, 4L);
Assert.assertEquals(1, value);
value = store.getAverageRateValue("test2", 5L, 3L);
Assert.assertEquals(0, value);
value = store.getAverageRateValue("test", 1L, 2L);
Assert.assertEquals(0, value);
}
@Test
public void testEmptyStore() {
InMemoryMetricsStore store = new InMemoryMetricsStore();
Assert.assertEquals(0, store.getAverageCounterValue("test", 1L, 1L));
Assert.assertEquals(0, store.getSumCounterValue("test", 1L, 1L));
Assert.assertEquals(0, store.getAverageRateValue("test", 1L, 1L));
Assert.assertEquals(0, store.getTotalSumCounterValue("test"));
}
private InMemoryMetricsStore buildStore() {
IntervalMetrics s1 = new IntervalMetrics();
s1.incrBy("test", 20);
s1.incrBy("test2", 40);
s1.putRate("test", 2);
s1.putRate("test2", 4);
s1.setStartTime(1L);
IntervalMetrics s2 = new IntervalMetrics();
s2.incrBy("test", 10);
s2.incrBy("test3", 30);
s2.putRate("test", 1);
s2.putRate("test3", 3);
s2.setStartTime(2L);
InMemoryMetricsStore store = new InMemoryMetricsStore();
store.add(s1);
store.add(s2);
return store;
}
}
| UTF-8 | Java | 3,407 | java | InMemoryMetricsStoreTest.java | Java | [] | null | [] | package gd.engineering.httplogmonitor.model.metrics;
import org.junit.Assert;
import org.junit.Test;
public class InMemoryMetricsStoreTest {
@Test
public void testCurrentCounterValue() {
InMemoryMetricsStore store = buildStore();
Assert.assertEquals(30, store.getTotalSumCounterValue("test"));
Assert.assertEquals(40, store.getTotalSumCounterValue("test2"));
Assert.assertEquals(30, store.getTotalSumCounterValue("test3"));
Assert.assertEquals(0, store.getTotalSumCounterValue("test4"));
}
@Test
public void testAverageCounterValue() {
InMemoryMetricsStore store = buildStore();
int value = store.getAverageCounterValue("test", 5L, 3L);
Assert.assertEquals(10, value);
value = store.getAverageCounterValue("test", 5L, 4L);
Assert.assertEquals(15, value);
value = store.getAverageCounterValue("test", 5L, 1L);
Assert.assertEquals(0, value);
value = store.getAverageCounterValue("test2", 3L, 1L);
Assert.assertEquals(0, value);
value = store.getAverageCounterValue("test2", 3L, 2L);
Assert.assertEquals(20, value);
value = store.getAverageCounterValue("test3", 3L, 1L);
Assert.assertEquals(30, value);
value = store.getAverageCounterValue("test3", 3L, 2L);
Assert.assertEquals(15, value);
}
@Test
public void testSumCounterValue() {
InMemoryMetricsStore store = buildStore();
int value = store.getSumCounterValue("test", 5L, 1L);
Assert.assertEquals(0, value);
value = store.getSumCounterValue("test", 5L, 3L);
Assert.assertEquals(10, value);
value = store.getSumCounterValue("test", 5L, 4L);
Assert.assertEquals(30, value);
value = store.getSumCounterValue("test2", 5L, 3L);
Assert.assertEquals(0, value);
value = store.getSumCounterValue("test2", 5L, 4L);
Assert.assertEquals(40, value);
value = store.getSumCounterValue("test2", 1L, 2L);
Assert.assertEquals(0, value);
}
@Test
public void testAverageRateValue() {
InMemoryMetricsStore store = buildStore();
int value = store.getAverageRateValue("test", 5L, 1L);
Assert.assertEquals(0, value);
value = store.getAverageRateValue("test", 5L, 3L);
Assert.assertEquals(1, value);
value = store.getAverageRateValue("test", 5L, 4L);
Assert.assertEquals(1, value);
value = store.getAverageRateValue("test2", 5L, 3L);
Assert.assertEquals(0, value);
value = store.getAverageRateValue("test", 1L, 2L);
Assert.assertEquals(0, value);
}
@Test
public void testEmptyStore() {
InMemoryMetricsStore store = new InMemoryMetricsStore();
Assert.assertEquals(0, store.getAverageCounterValue("test", 1L, 1L));
Assert.assertEquals(0, store.getSumCounterValue("test", 1L, 1L));
Assert.assertEquals(0, store.getAverageRateValue("test", 1L, 1L));
Assert.assertEquals(0, store.getTotalSumCounterValue("test"));
}
private InMemoryMetricsStore buildStore() {
IntervalMetrics s1 = new IntervalMetrics();
s1.incrBy("test", 20);
s1.incrBy("test2", 40);
s1.putRate("test", 2);
s1.putRate("test2", 4);
s1.setStartTime(1L);
IntervalMetrics s2 = new IntervalMetrics();
s2.incrBy("test", 10);
s2.incrBy("test3", 30);
s2.putRate("test", 1);
s2.putRate("test3", 3);
s2.setStartTime(2L);
InMemoryMetricsStore store = new InMemoryMetricsStore();
store.add(s1);
store.add(s2);
return store;
}
}
| 3,407 | 0.693866 | 0.658057 | 96 | 34.489582 | 21.351227 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 9 |
ee1c6e375fe0d77b21cb935a0cf8969f82c48a4e | 85,899,405,488 | dee407e7d56c3591e93400685b75900bc91d97fb | /mobileoa2.0/app/src/main/java/com/idxk/mobileoa/android/ui/activity/LauncherActivity.java | b4ae8d19769f56c1a5ae36d873b2292c0b54edb8 | [] | no_license | chengyue5923/android-OaCode | https://github.com/chengyue5923/android-OaCode | 20777c4ec319f990e05fd6443f3b5bebde7a57ef | c93b2673be33e203413eba05966d9348dd28f0ca | refs/heads/master | 2021-01-14T08:13:49.651000 | 2017-02-15T05:20:26 | 2017-02-15T05:20:26 | 82,023,114 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.idxk.mobileoa.android.ui.activity;
import android.app.Notification;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.ImageView;
import com.baidu.android.pushservice.CustomPushNotificationBuilder;
import com.baidu.android.pushservice.PushManager;
import com.idxk.mobileoa.R;
import com.idxk.mobileoa.utils.cache.preferce.PreferceManager;
import com.idxk.mobileoa.utils.common.android.IntentTool;
import com.umeng.update.UmengUpdateAgent;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lenovo on 2015/3/24.
*/
public class LauncherActivity extends BaseActivity {
ImageView allLayout;
@Override
protected void initView() {
setContentView(R.layout.activity_launcher);
allLayout = (ImageView) id2v(R.id.allLayout);
}
@Override
protected void initData() {
String token = PreferceManager.getInsance().getValueBYkey(LauncherActivity.this, "oauth_token");
startFrist();
if (token != null && !"".equals(token)) {
IntentTool.homePage(LauncherActivity.this);
}
else {
Intent intent = new Intent(LauncherActivity.this, LoginActivity.class);
startActivity(intent);
}
LauncherActivity.this.finish();
}
private void startFrist() {
Resources resource = this.getResources();
String pkgName = this.getPackageName();
CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
resource.getIdentifier(
"notification_custom_builder", "layout", pkgName),
resource.getIdentifier("notification_icon", "id", pkgName),
resource.getIdentifier("notification_title", "id", pkgName),
resource.getIdentifier("notification_text", "id", pkgName));
cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
cBuilder.setNotificationDefaults(Notification.DEFAULT_VIBRATE);
cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
cBuilder.setLayoutDrawable(resource.getIdentifier(
"simple_notification_icon", "drawable", pkgName));
cBuilder.setNotificationSound(Uri.withAppendedPath(
MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "6").toString());
// 推送高级设置,通知栏样式设置为下面的ID
PushManager.setNotificationBuilder(this, 1, cBuilder);
List<String> list = new ArrayList<String>();
list.add("zmt");
PushManager.setTags(this, list);
PushManager.bindGroup(this, "");
UmengUpdateAgent.update(this);
UmengUpdateAgent.setUpdateOnlyWifi(false);
}
}
| UTF-8 | Java | 2,795 | java | LauncherActivity.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by lenovo on 2015/3/24.\n */\npublic class LauncherActivity e",
"end": 630,
"score": 0.9996085166931152,
"start": 624,
"tag": "USERNAME",
"value": "lenovo"
}
] | null | [] | package com.idxk.mobileoa.android.ui.activity;
import android.app.Notification;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.ImageView;
import com.baidu.android.pushservice.CustomPushNotificationBuilder;
import com.baidu.android.pushservice.PushManager;
import com.idxk.mobileoa.R;
import com.idxk.mobileoa.utils.cache.preferce.PreferceManager;
import com.idxk.mobileoa.utils.common.android.IntentTool;
import com.umeng.update.UmengUpdateAgent;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lenovo on 2015/3/24.
*/
public class LauncherActivity extends BaseActivity {
ImageView allLayout;
@Override
protected void initView() {
setContentView(R.layout.activity_launcher);
allLayout = (ImageView) id2v(R.id.allLayout);
}
@Override
protected void initData() {
String token = PreferceManager.getInsance().getValueBYkey(LauncherActivity.this, "oauth_token");
startFrist();
if (token != null && !"".equals(token)) {
IntentTool.homePage(LauncherActivity.this);
}
else {
Intent intent = new Intent(LauncherActivity.this, LoginActivity.class);
startActivity(intent);
}
LauncherActivity.this.finish();
}
private void startFrist() {
Resources resource = this.getResources();
String pkgName = this.getPackageName();
CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
resource.getIdentifier(
"notification_custom_builder", "layout", pkgName),
resource.getIdentifier("notification_icon", "id", pkgName),
resource.getIdentifier("notification_title", "id", pkgName),
resource.getIdentifier("notification_text", "id", pkgName));
cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
cBuilder.setNotificationDefaults(Notification.DEFAULT_VIBRATE);
cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
cBuilder.setLayoutDrawable(resource.getIdentifier(
"simple_notification_icon", "drawable", pkgName));
cBuilder.setNotificationSound(Uri.withAppendedPath(
MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "6").toString());
// 推送高级设置,通知栏样式设置为下面的ID
PushManager.setNotificationBuilder(this, 1, cBuilder);
List<String> list = new ArrayList<String>();
list.add("zmt");
PushManager.setTags(this, list);
PushManager.bindGroup(this, "");
UmengUpdateAgent.update(this);
UmengUpdateAgent.setUpdateOnlyWifi(false);
}
}
| 2,795 | 0.686481 | 0.682856 | 77 | 34.831169 | 26.601631 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.766234 | false | false | 9 |
b258045d89f6e7684548e77d680e08f3b4b8b7ef | 85,899,404,409 | ba84bcf9e3fc3a1ee46def4786f1bdfc1627ca84 | /java_01/src/day06_abstract/Test01.java | 116156a3bc8a1cfe0722132a87ffe2aede7ca35e | [] | no_license | skysamer/java_multi | https://github.com/skysamer/java_multi | 39f468bff80fa8197dcf245f20f2f2348582f03b | 602f0fc0e377de5dae1cd659465ceec4ca7d2a07 | refs/heads/master | 2023-02-10T14:39:51.976000 | 2021-01-13T10:17:06 | 2021-01-13T10:17:06 | 323,294,999 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day06_abstract;
public class Test01 {
public static void main(String[] args) {
Animal[] animals= {
new Dog(),
new Dog("진돗개", "캐리"),
new Fish("쿠피"),
new Fish()
};
for(Animal data:animals) {
data.print();
data.breath();
}
}
}
| UTF-8 | Java | 298 | java | Test01.java | Java | [] | null | [] | package day06_abstract;
public class Test01 {
public static void main(String[] args) {
Animal[] animals= {
new Dog(),
new Dog("진돗개", "캐리"),
new Fish("쿠피"),
new Fish()
};
for(Animal data:animals) {
data.print();
data.breath();
}
}
}
| 298 | 0.535211 | 0.521127 | 22 | 11.909091 | 11.301284 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.318182 | false | false | 9 |
93373ce837f47c01fa55c079d6b145a674ef59fc | 26,465,588,544,671 | 8254ab325f6571027e0ee18594067f54a44010ce | /src/com/chengjf/wtfdoc/bean/resources/FilePath.java | 5326311fb6e349f57672d2cb0d3041fd69f5c589 | [] | no_license | chengjf/WTFDoc | https://github.com/chengjf/WTFDoc | d05ce85b9e036a672dbad01243aba2d3c03c4cbb | 8c108b90e0550cd57e6458f5be50886f09b03579 | refs/heads/master | 2016-09-05T09:54:03.329000 | 2014-10-23T14:51:19 | 2014-10-23T14:51:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2014 chengjf.
* All rights reserved.
* project name: WTFDoc
* version: WTFDocV1.0
*---------------------------------------------------
* @FileName: FilePaths.java
* @Package:com.chengjf.wtfdoc.bean.resources
* @Description: TODO
* @author: chengjf
* @date:2014-10-15 上午11:21:19
* @version V1.0
*/
package com.chengjf.wtfdoc.bean.resources;
/**
* 文件路径
*
* @ClassName: FilePath
* @author: chengjf
* @date: 2014-10-18
*/
public class FilePath {
/**
* 文件的key
*
* @Fields: key
* @author: chengjf
* @date: 2014-10-18
*/
private int key;
/**
* 文件的路径
*
* @Fields: path
* @author: chengjf
* @date: 2014-10-18
*/
private String path;
/**
* @Title: getKey
* @author: chengjf
* @date: 2014-10-18
* @return
*/
public int getKey() {
return key;
}
/**
* @Title: setKey
* @author: chengjf
* @date: 2014-10-18
* @param key
*/
public void setKey(int key) {
this.key = key;
}
/**
* @Title: getPath
* @author: chengjf
* @date: 2014-10-18
* @return
*/
public String getPath() {
return path;
}
/**
* @Title: setPath
* @author: chengjf
* @date: 2014-10-18
* @param path
*/
public void setPath(String path) {
this.path = path;
}
}
| UTF-8 | Java | 1,295 | java | FilePath.java | Java | [
{
"context": "/* \n * Copyright 2014 chengjf.\n * All rights reserved.\n * project name: WTFDoc\n",
"end": 32,
"score": 0.9996107220649719,
"start": 25,
"tag": "USERNAME",
"value": "chengjf"
},
{
"context": "ean.resources \n * @Description: TODO \n * @author: chengjf \n * @date:... | null | [] | /*
* Copyright 2014 chengjf.
* All rights reserved.
* project name: WTFDoc
* version: WTFDocV1.0
*---------------------------------------------------
* @FileName: FilePaths.java
* @Package:com.chengjf.wtfdoc.bean.resources
* @Description: TODO
* @author: chengjf
* @date:2014-10-15 上午11:21:19
* @version V1.0
*/
package com.chengjf.wtfdoc.bean.resources;
/**
* 文件路径
*
* @ClassName: FilePath
* @author: chengjf
* @date: 2014-10-18
*/
public class FilePath {
/**
* 文件的key
*
* @Fields: key
* @author: chengjf
* @date: 2014-10-18
*/
private int key;
/**
* 文件的路径
*
* @Fields: path
* @author: chengjf
* @date: 2014-10-18
*/
private String path;
/**
* @Title: getKey
* @author: chengjf
* @date: 2014-10-18
* @return
*/
public int getKey() {
return key;
}
/**
* @Title: setKey
* @author: chengjf
* @date: 2014-10-18
* @param key
*/
public void setKey(int key) {
this.key = key;
}
/**
* @Title: getPath
* @author: chengjf
* @date: 2014-10-18
* @return
*/
public String getPath() {
return path;
}
/**
* @Title: setPath
* @author: chengjf
* @date: 2014-10-18
* @param path
*/
public void setPath(String path) {
this.path = path;
}
}
| 1,295 | 0.54854 | 0.486977 | 83 | 14.26506 | 11.501791 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.759036 | false | false | 9 |
660f972534a074424b2ee32cfd12fbc7e9b847f1 | 26,465,588,543,830 | cda3e0a897a65dce9da16f051a7effa31d19f996 | /REL/src/bradesco/dpoc/relatorio/model/RelatorioGeneric.java | c2528b030b887c5a7a30ee4e7f1dde7607534c8e | [] | no_license | mpalos/simRAR | https://github.com/mpalos/simRAR | da437fa941afcc844be3f53d57fd9bb870388dea | 49e56a6c8d04794bad28b73f997f5e88e3eaa4dd | refs/heads/master | 2016-08-09T18:08:08.337000 | 2016-02-18T15:24:05 | 2016-02-18T15:24:05 | 47,927,104 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bradesco.dpoc.relatorio.model;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import bradesco.dpoc.model.integration.RelatorioDAO;
import bradesco.dpoc.relatorio.model.relatorios.Relatorio;
import de.congrace.exp4j.Calculable;
import de.congrace.exp4j.ExpressionBuilder;
public class RelatorioGeneric extends Relatorio {
private int id;
private String nome;
private int maxNivel;
private List<RelatorioGeneric> grupoFilho;
private List<RelatorioColuna> colunas;
private List<String> validVariables;
public RelatorioGeneric() {
this.colunas = new ArrayList<RelatorioColuna>();
this.grupoFilho = new ArrayList<RelatorioGeneric>();
this.validVariables = Arrays.asList("AT_1", "AT_2", "AT_3", "AT_4",
"AT_5", "AT_6", "AT_7", "AT_8", "AT_9", "AT_10", "AT_11",
"AT_12", "OR_1", "OR_2", "OR_3", "OR_4", "OR_5", "OR_6",
"OR_7", "OR_8", "OR_9", "OR_10", "OR_11", "OR_12", "RE_1",
"RE_2", "RE_3", "RE_4", "RE_5", "RE_6", "RE_7", "RE_8", "RE_9",
"RE_10", "RE_11", "RE_12");
}
public RelatorioTO geraRelatorio(Filtro filtro) {
List<RelatorioColuna> listColunas = getAllColunas();
RelatorioTO ret = new RelatorioTO();
ret.setLinhas(this.montaRelatorio(listColunas, filtro));
ret = this.configuraPDF(ret, filtro);
ret = this.montaCabCanto(ret);
ret = this.montaCab(listColunas, ret, filtro);
return ret;
}
protected RelatorioTO configuraPDF(RelatorioTO ret, Filtro filtro) {
return ret;
}
public RelatorioTO montaCabCanto(RelatorioTO ret) {
ret.setCabecCanto("<table cellpadding=\"0\" cellspacing=\"0\" border=0 height=50px width=215px>"
+ "<tr><td rowspan="
+ this.maxNivel
+ " class= \"bS bE bD bI negritoCabBold2\" align=center>Descrição</td></tr></table>");
return ret;
}
private int getColSpan(RelatorioGeneric rel) {
int retorno = 0;
if (rel.getGrupoFilho().size() > 0) {
for (RelatorioGeneric relFilho : rel.getGrupoFilho()) {
retorno += relFilho.getColSpan(relFilho);
}
} else {
retorno = rel.getColunas().size();
}
return retorno;
}
private List<RelatorioColuna> orderByOrdem(List<RelatorioColuna> listColuna) {
Comparator<RelatorioColuna> c = new Comparator<RelatorioColuna>() {
public int compare(RelatorioColuna o1, RelatorioColuna o2) {
if (o1.getOrdem() > o2.getOrdem())
return 1;
else
return -1;
}
};
Collections.sort(listColuna, c);
return listColuna;
}
private String montaCab(List<RelatorioGeneric> listGrupo, int nivelMax,
int[] larguras) {
String retorno = "";
String rowSpan = String.valueOf(nivelMax);
String className = "";
boolean addRowSpan = false;
if (listGrupo.size() == 0)
return "";
retorno += "<tr>";
boolean[] removeIndex = new boolean[listGrupo.size()];
for (int i = 0; i < listGrupo.size(); i++) {
RelatorioGeneric rel = listGrupo.get(i);
if (rel.getColunas().size() == 1)
addRowSpan = true;
/*
* if (i == 0) className = "bS bD negritoCabBold2"; else if (i + 1
* >= listGrupo.size()) className = "bS bD negritoCabBold2"; else
*/
className = "bS bD negritoCabBold2";
if(addRowSpan)
className += " bI";
retorno += "<td colspan=\""
+ getColSpan(rel)
+ "\" "
+ (addRowSpan ? "rowspan=\"" + rowSpan + "\"" : "")
+ (addRowSpan ? "style=\"width: "
+ rel.getColunas().get(0).getTamanho() + "px;\""
: "") + " class=\"" + className
+ "\" align=\"center\">";
retorno += rel.getNome();
retorno += "</td>";
if (addRowSpan)
removeIndex[i] = true;
addRowSpan = false;
}
for (int j = (listGrupo.size() - 1); j >= 0; j--) {
if (removeIndex[j])
listGrupo.remove(j);
}
retorno += "</tr>";
List<RelatorioColuna> colunasFilho = orderByOrdem(getAllColunas(listGrupo));
if (colunasFilho.size() > 0) {
retorno += "<tr>";
for (int i = 0; i < colunasFilho.size(); i++) {
RelatorioColuna col = colunasFilho.get(i);
/*
* if (i == 0) className = "bI negritoCabBold2"; else if (i + 1
* >= colunasFilho.size()) className =
* "bI bE bD negritoCabBold2"; else
*/
className = "bI bS bD negritoCabBold2";
retorno += "<td class=\""
+ className
+ "\" align=\"center\" style=\"width:"
+ larguras[i]
+ "px;\">"
+ (col.getTipoColuna() == TipoColuna.ResultadoMedio ? "Resultado"
: (col.getTipoColuna() == TipoColuna.SaldoMedio ? "Saldo Médio"
: "Spread (%)")) + "</td>";
}
retorno += "</tr>";
}
retorno += montaCab(getGruposFilhos(listGrupo), nivelMax--, larguras);
return retorno;
}
public RelatorioTO montaCab(List<RelatorioColuna> listColunas,
RelatorioTO ret, Filtro filtro) {
int larguras[] = new int[listColunas.size()];
for (int i = 0; i < listColunas.size(); i++) {
larguras[i] = listColunas.get(i).getTamanho();
}
ret.setLarguraColTela(larguras);
int soma = 0;
for (int a : larguras) {
soma += a;
}
ret.setLarguraRelTela(soma);
StringBuffer geraCab = new StringBuffer(
"<table width="
+ soma
+ "px height= \"50px\" border=0 cellpadding=\"0\" cellspacing=\"0\">");
geraCab.append(montaCab(this.grupoFilho, this.maxNivel, larguras));
geraCab.append("</table>");
ret.setCabecTela(geraCab.toString());
return ret;
}
private boolean verificaTabela(List<RelatorioColuna> listColunas,
TabelaReferencia tabela) {
for (RelatorioColuna col : listColunas) {
if (col.getTabelaReferencia() == tabela)
return true;
}
return false;
}
protected ArrayList<ArrayList<String>> montaRelatorio(
List<RelatorioColuna> listColuna, Filtro filtro) {
ArrayList<ArrayList<String>> mascara = this.buscaMascara(filtro);
ArrayList<RegistroTO> dadosRef = null;
if (verificaTabela(listColuna, TabelaReferencia.Referencia)) {
dadosRef = this.buscaDados(filtro);
}
ArrayList<RegistroTO> dadosIni = null;
if (verificaTabela(listColuna, TabelaReferencia.Inicial)) {
dadosIni = this.buscaDados(filtro);
}
ArrayList<RegistroTO> dadosRefTotal = null;
if (verificaTabela(listColuna, TabelaReferencia.ReferenciaTotais)) {
dadosRefTotal = this.buscaDados(filtro);
}
ArrayList<RegistroTO> dadosIniTotal = null;
if (verificaTabela(listColuna, TabelaReferencia.InicialTotais)) {
dadosIniTotal = this
.buscaDados(
filtro);
}
try {
return montaRelatorio(listColuna, mascara, dadosRef, dadosRefTotal,
dadosIni, dadosIniTotal);
} catch (Exception e) {
return null;
}
}
protected ArrayList<ArrayList<String>> montaRelatorio(
List<RelatorioColuna> listColuna,
ArrayList<ArrayList<String>> mascara,
ArrayList<RegistroTO> dadosRef,
ArrayList<RegistroTO> dadosRefTotal,
ArrayList<RegistroTO> dadosIni, ArrayList<RegistroTO> dadosIniTotal) {
for (ArrayList<String> line : mascara) {
for (RelatorioColuna col : listColuna) {
ExpressionBuilder exp = new ExpressionBuilder(col.getFormula());
exp = defineVariaveis(
col,
exp,
line,
(col.getTabelaReferencia() == TabelaReferencia.Inicial ? dadosIni
: (col.getTabelaReferencia() == TabelaReferencia.InicialTotais ? dadosIniTotal
: (col.getTabelaReferencia() == TabelaReferencia.Referencia ? dadosRef
: dadosRefTotal))));
Calculable calc = null;
double result = 0;
try {
calc = exp.build();
result = calc.calculate();
} catch (Exception e) {
result = 0;
}
line.set(4 + col.getOrdem(),
formata(result, col.getNmDecimais()));
}
}
return mascara;
}
private ExpressionBuilder defineVariaveis(RelatorioColuna coluna,
ExpressionBuilder exp, ArrayList<String> line,
ArrayList<RegistroTO> dados) {
final List<Character> reserved = Arrays.asList(' ', '+', '-', '/', '*',
'^', '&', '%', '(', ')', '{', '}');
final char[] chars = coluna.getFormula().toCharArray();
boolean findingVar = false;
String varName = "";
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((Character.isLetter(c) || c == '_' || c == '[' || c == ']')
|| findingVar) {
findingVar = !reserved.contains(c);
if (findingVar) {
varName += c;
if (!(i + 1 >= chars.length))
continue;
}
}
if (validVariables.contains(varName)) {
// AT_1 ou RE_1 ou OR_1
exp.withVariable(
varName,
getValue(
varName,
dados,
(coluna.getTipoColuna() == TipoColuna.SaldoMedio ? "S"
: "R"), line.get(1)));
varName = "";
findingVar = false;
} else if (varName.startsWith("_")) {
// index para soma
int id = Integer.parseInt(varName.replace("_i", ""));
exp.withVariable(
varName,
Double.parseDouble(line.get(4 + getOrdemById(id))
.replace(".", "").replace('(', '-')
.replace(")", "").replace(" - ", "0")));
varName = "";
findingVar = false;
}
}
return exp;
}
private int getOrdemById(int id) {
for (RelatorioColuna col : getAllColunas()) {
if (col.getId() == id) {
return col.getOrdem();
}
}
return 0;
}
private double getValue(String fieldName, ArrayList<RegistroTO> dados,
String tipo, String id) {
for (RegistroTO reg : dados) {
if (reg.getId_linha().equals(id) && reg.getMedida().equals(tipo)) {
try {
for (Method mt : reg.getClass().getMethods()) {
if (mt.getName().startsWith("get")
&& mt.getName().toLowerCase()
.endsWith(fieldName.toLowerCase())) {
return (Double) mt.invoke(reg, (Object[]) null);
}
}
} catch (Exception ex) {
ex.printStackTrace();
return 0d;
}
}
}
return 0d;
}
protected ArrayList<ArrayList<String>> buscaMascara(Filtro filtro) {
RelatorioDAO relDAO;
int numeroColunas = getNumeroColunas();
try {
relDAO = new RelatorioDAO();
return relDAO.buscaMascara(filtro, numeroColunas, filtro.getRubrica());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private int getNumeroColunas() {
return getAllColunas().size();
}
/**
* @return Retorna int contendo o/a id
*/
public int getId() {
return id;
}
/**
* @param id
* Define o campo id
*/
public void setId(int id) {
this.id = id;
}
/**
* @return Retorna String contendo o/a nome
*/
public String getNome() {
return nome;
}
/**
* @param nome
* Define o campo nome
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return Retorna List<RelatorioGeneric> contendo o/a grupoFilho
*/
public List<RelatorioGeneric> getGrupoFilho() {
return grupoFilho;
}
/**
* @param grupoFilho
* Define o campo grupoFilho
*/
public void setGrupoFilho(List<RelatorioGeneric> grupoFilho) {
this.grupoFilho = grupoFilho;
}
/**
* @return Retorna List<ColunasGrupo> contendo o/a colunas
*/
public List<RelatorioColuna> getColunas() {
return colunas;
}
/**
* @param colunas
* Define o campo colunas
*/
public void setColunas(List<RelatorioColuna> colunas) {
this.colunas = colunas;
}
/**
* @return Retorna int contendo o/a maxNivel
*/
public int getMaxNivel() {
return maxNivel;
}
/**
* @param maxNivel
* Define o campo maxNivel
*/
public void setMaxNivel(int maxNivel) {
this.maxNivel = maxNivel;
}
public List<RelatorioColuna> getAllColunas() {
List<RelatorioColuna> retorno = new ArrayList<RelatorioColuna>();
for (RelatorioColuna col : this.colunas)
retorno.add(col);
for (RelatorioGeneric rel : this.grupoFilho)
retorno.addAll(rel.getAllColunas());
return retorno;
}
public List<RelatorioColuna> getAllColunas(List<RelatorioGeneric> listGrupo) {
List<RelatorioColuna> retorno = new ArrayList<RelatorioColuna>();
for (RelatorioGeneric rel : listGrupo) {
retorno.addAll(rel.getColunas());
}
return retorno;
}
public List<RelatorioGeneric> getGruposFilhos(
List<RelatorioGeneric> listGrupoPai) {
List<RelatorioGeneric> retorno = new ArrayList<RelatorioGeneric>();
for (RelatorioGeneric rel : listGrupoPai) {
retorno.addAll(rel.getGrupoFilho());
}
return retorno;
}
}
| ISO-8859-2 | Java | 12,753 | java | RelatorioGeneric.java | Java | [] | null | [] | package bradesco.dpoc.relatorio.model;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import bradesco.dpoc.model.integration.RelatorioDAO;
import bradesco.dpoc.relatorio.model.relatorios.Relatorio;
import de.congrace.exp4j.Calculable;
import de.congrace.exp4j.ExpressionBuilder;
public class RelatorioGeneric extends Relatorio {
private int id;
private String nome;
private int maxNivel;
private List<RelatorioGeneric> grupoFilho;
private List<RelatorioColuna> colunas;
private List<String> validVariables;
public RelatorioGeneric() {
this.colunas = new ArrayList<RelatorioColuna>();
this.grupoFilho = new ArrayList<RelatorioGeneric>();
this.validVariables = Arrays.asList("AT_1", "AT_2", "AT_3", "AT_4",
"AT_5", "AT_6", "AT_7", "AT_8", "AT_9", "AT_10", "AT_11",
"AT_12", "OR_1", "OR_2", "OR_3", "OR_4", "OR_5", "OR_6",
"OR_7", "OR_8", "OR_9", "OR_10", "OR_11", "OR_12", "RE_1",
"RE_2", "RE_3", "RE_4", "RE_5", "RE_6", "RE_7", "RE_8", "RE_9",
"RE_10", "RE_11", "RE_12");
}
public RelatorioTO geraRelatorio(Filtro filtro) {
List<RelatorioColuna> listColunas = getAllColunas();
RelatorioTO ret = new RelatorioTO();
ret.setLinhas(this.montaRelatorio(listColunas, filtro));
ret = this.configuraPDF(ret, filtro);
ret = this.montaCabCanto(ret);
ret = this.montaCab(listColunas, ret, filtro);
return ret;
}
protected RelatorioTO configuraPDF(RelatorioTO ret, Filtro filtro) {
return ret;
}
public RelatorioTO montaCabCanto(RelatorioTO ret) {
ret.setCabecCanto("<table cellpadding=\"0\" cellspacing=\"0\" border=0 height=50px width=215px>"
+ "<tr><td rowspan="
+ this.maxNivel
+ " class= \"bS bE bD bI negritoCabBold2\" align=center>Descrição</td></tr></table>");
return ret;
}
private int getColSpan(RelatorioGeneric rel) {
int retorno = 0;
if (rel.getGrupoFilho().size() > 0) {
for (RelatorioGeneric relFilho : rel.getGrupoFilho()) {
retorno += relFilho.getColSpan(relFilho);
}
} else {
retorno = rel.getColunas().size();
}
return retorno;
}
private List<RelatorioColuna> orderByOrdem(List<RelatorioColuna> listColuna) {
Comparator<RelatorioColuna> c = new Comparator<RelatorioColuna>() {
public int compare(RelatorioColuna o1, RelatorioColuna o2) {
if (o1.getOrdem() > o2.getOrdem())
return 1;
else
return -1;
}
};
Collections.sort(listColuna, c);
return listColuna;
}
private String montaCab(List<RelatorioGeneric> listGrupo, int nivelMax,
int[] larguras) {
String retorno = "";
String rowSpan = String.valueOf(nivelMax);
String className = "";
boolean addRowSpan = false;
if (listGrupo.size() == 0)
return "";
retorno += "<tr>";
boolean[] removeIndex = new boolean[listGrupo.size()];
for (int i = 0; i < listGrupo.size(); i++) {
RelatorioGeneric rel = listGrupo.get(i);
if (rel.getColunas().size() == 1)
addRowSpan = true;
/*
* if (i == 0) className = "bS bD negritoCabBold2"; else if (i + 1
* >= listGrupo.size()) className = "bS bD negritoCabBold2"; else
*/
className = "bS bD negritoCabBold2";
if(addRowSpan)
className += " bI";
retorno += "<td colspan=\""
+ getColSpan(rel)
+ "\" "
+ (addRowSpan ? "rowspan=\"" + rowSpan + "\"" : "")
+ (addRowSpan ? "style=\"width: "
+ rel.getColunas().get(0).getTamanho() + "px;\""
: "") + " class=\"" + className
+ "\" align=\"center\">";
retorno += rel.getNome();
retorno += "</td>";
if (addRowSpan)
removeIndex[i] = true;
addRowSpan = false;
}
for (int j = (listGrupo.size() - 1); j >= 0; j--) {
if (removeIndex[j])
listGrupo.remove(j);
}
retorno += "</tr>";
List<RelatorioColuna> colunasFilho = orderByOrdem(getAllColunas(listGrupo));
if (colunasFilho.size() > 0) {
retorno += "<tr>";
for (int i = 0; i < colunasFilho.size(); i++) {
RelatorioColuna col = colunasFilho.get(i);
/*
* if (i == 0) className = "bI negritoCabBold2"; else if (i + 1
* >= colunasFilho.size()) className =
* "bI bE bD negritoCabBold2"; else
*/
className = "bI bS bD negritoCabBold2";
retorno += "<td class=\""
+ className
+ "\" align=\"center\" style=\"width:"
+ larguras[i]
+ "px;\">"
+ (col.getTipoColuna() == TipoColuna.ResultadoMedio ? "Resultado"
: (col.getTipoColuna() == TipoColuna.SaldoMedio ? "Saldo Médio"
: "Spread (%)")) + "</td>";
}
retorno += "</tr>";
}
retorno += montaCab(getGruposFilhos(listGrupo), nivelMax--, larguras);
return retorno;
}
public RelatorioTO montaCab(List<RelatorioColuna> listColunas,
RelatorioTO ret, Filtro filtro) {
int larguras[] = new int[listColunas.size()];
for (int i = 0; i < listColunas.size(); i++) {
larguras[i] = listColunas.get(i).getTamanho();
}
ret.setLarguraColTela(larguras);
int soma = 0;
for (int a : larguras) {
soma += a;
}
ret.setLarguraRelTela(soma);
StringBuffer geraCab = new StringBuffer(
"<table width="
+ soma
+ "px height= \"50px\" border=0 cellpadding=\"0\" cellspacing=\"0\">");
geraCab.append(montaCab(this.grupoFilho, this.maxNivel, larguras));
geraCab.append("</table>");
ret.setCabecTela(geraCab.toString());
return ret;
}
private boolean verificaTabela(List<RelatorioColuna> listColunas,
TabelaReferencia tabela) {
for (RelatorioColuna col : listColunas) {
if (col.getTabelaReferencia() == tabela)
return true;
}
return false;
}
protected ArrayList<ArrayList<String>> montaRelatorio(
List<RelatorioColuna> listColuna, Filtro filtro) {
ArrayList<ArrayList<String>> mascara = this.buscaMascara(filtro);
ArrayList<RegistroTO> dadosRef = null;
if (verificaTabela(listColuna, TabelaReferencia.Referencia)) {
dadosRef = this.buscaDados(filtro);
}
ArrayList<RegistroTO> dadosIni = null;
if (verificaTabela(listColuna, TabelaReferencia.Inicial)) {
dadosIni = this.buscaDados(filtro);
}
ArrayList<RegistroTO> dadosRefTotal = null;
if (verificaTabela(listColuna, TabelaReferencia.ReferenciaTotais)) {
dadosRefTotal = this.buscaDados(filtro);
}
ArrayList<RegistroTO> dadosIniTotal = null;
if (verificaTabela(listColuna, TabelaReferencia.InicialTotais)) {
dadosIniTotal = this
.buscaDados(
filtro);
}
try {
return montaRelatorio(listColuna, mascara, dadosRef, dadosRefTotal,
dadosIni, dadosIniTotal);
} catch (Exception e) {
return null;
}
}
protected ArrayList<ArrayList<String>> montaRelatorio(
List<RelatorioColuna> listColuna,
ArrayList<ArrayList<String>> mascara,
ArrayList<RegistroTO> dadosRef,
ArrayList<RegistroTO> dadosRefTotal,
ArrayList<RegistroTO> dadosIni, ArrayList<RegistroTO> dadosIniTotal) {
for (ArrayList<String> line : mascara) {
for (RelatorioColuna col : listColuna) {
ExpressionBuilder exp = new ExpressionBuilder(col.getFormula());
exp = defineVariaveis(
col,
exp,
line,
(col.getTabelaReferencia() == TabelaReferencia.Inicial ? dadosIni
: (col.getTabelaReferencia() == TabelaReferencia.InicialTotais ? dadosIniTotal
: (col.getTabelaReferencia() == TabelaReferencia.Referencia ? dadosRef
: dadosRefTotal))));
Calculable calc = null;
double result = 0;
try {
calc = exp.build();
result = calc.calculate();
} catch (Exception e) {
result = 0;
}
line.set(4 + col.getOrdem(),
formata(result, col.getNmDecimais()));
}
}
return mascara;
}
private ExpressionBuilder defineVariaveis(RelatorioColuna coluna,
ExpressionBuilder exp, ArrayList<String> line,
ArrayList<RegistroTO> dados) {
final List<Character> reserved = Arrays.asList(' ', '+', '-', '/', '*',
'^', '&', '%', '(', ')', '{', '}');
final char[] chars = coluna.getFormula().toCharArray();
boolean findingVar = false;
String varName = "";
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((Character.isLetter(c) || c == '_' || c == '[' || c == ']')
|| findingVar) {
findingVar = !reserved.contains(c);
if (findingVar) {
varName += c;
if (!(i + 1 >= chars.length))
continue;
}
}
if (validVariables.contains(varName)) {
// AT_1 ou RE_1 ou OR_1
exp.withVariable(
varName,
getValue(
varName,
dados,
(coluna.getTipoColuna() == TipoColuna.SaldoMedio ? "S"
: "R"), line.get(1)));
varName = "";
findingVar = false;
} else if (varName.startsWith("_")) {
// index para soma
int id = Integer.parseInt(varName.replace("_i", ""));
exp.withVariable(
varName,
Double.parseDouble(line.get(4 + getOrdemById(id))
.replace(".", "").replace('(', '-')
.replace(")", "").replace(" - ", "0")));
varName = "";
findingVar = false;
}
}
return exp;
}
private int getOrdemById(int id) {
for (RelatorioColuna col : getAllColunas()) {
if (col.getId() == id) {
return col.getOrdem();
}
}
return 0;
}
private double getValue(String fieldName, ArrayList<RegistroTO> dados,
String tipo, String id) {
for (RegistroTO reg : dados) {
if (reg.getId_linha().equals(id) && reg.getMedida().equals(tipo)) {
try {
for (Method mt : reg.getClass().getMethods()) {
if (mt.getName().startsWith("get")
&& mt.getName().toLowerCase()
.endsWith(fieldName.toLowerCase())) {
return (Double) mt.invoke(reg, (Object[]) null);
}
}
} catch (Exception ex) {
ex.printStackTrace();
return 0d;
}
}
}
return 0d;
}
protected ArrayList<ArrayList<String>> buscaMascara(Filtro filtro) {
RelatorioDAO relDAO;
int numeroColunas = getNumeroColunas();
try {
relDAO = new RelatorioDAO();
return relDAO.buscaMascara(filtro, numeroColunas, filtro.getRubrica());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private int getNumeroColunas() {
return getAllColunas().size();
}
/**
* @return Retorna int contendo o/a id
*/
public int getId() {
return id;
}
/**
* @param id
* Define o campo id
*/
public void setId(int id) {
this.id = id;
}
/**
* @return Retorna String contendo o/a nome
*/
public String getNome() {
return nome;
}
/**
* @param nome
* Define o campo nome
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return Retorna List<RelatorioGeneric> contendo o/a grupoFilho
*/
public List<RelatorioGeneric> getGrupoFilho() {
return grupoFilho;
}
/**
* @param grupoFilho
* Define o campo grupoFilho
*/
public void setGrupoFilho(List<RelatorioGeneric> grupoFilho) {
this.grupoFilho = grupoFilho;
}
/**
* @return Retorna List<ColunasGrupo> contendo o/a colunas
*/
public List<RelatorioColuna> getColunas() {
return colunas;
}
/**
* @param colunas
* Define o campo colunas
*/
public void setColunas(List<RelatorioColuna> colunas) {
this.colunas = colunas;
}
/**
* @return Retorna int contendo o/a maxNivel
*/
public int getMaxNivel() {
return maxNivel;
}
/**
* @param maxNivel
* Define o campo maxNivel
*/
public void setMaxNivel(int maxNivel) {
this.maxNivel = maxNivel;
}
public List<RelatorioColuna> getAllColunas() {
List<RelatorioColuna> retorno = new ArrayList<RelatorioColuna>();
for (RelatorioColuna col : this.colunas)
retorno.add(col);
for (RelatorioGeneric rel : this.grupoFilho)
retorno.addAll(rel.getAllColunas());
return retorno;
}
public List<RelatorioColuna> getAllColunas(List<RelatorioGeneric> listGrupo) {
List<RelatorioColuna> retorno = new ArrayList<RelatorioColuna>();
for (RelatorioGeneric rel : listGrupo) {
retorno.addAll(rel.getColunas());
}
return retorno;
}
public List<RelatorioGeneric> getGruposFilhos(
List<RelatorioGeneric> listGrupoPai) {
List<RelatorioGeneric> retorno = new ArrayList<RelatorioGeneric>();
for (RelatorioGeneric rel : listGrupoPai) {
retorno.addAll(rel.getGrupoFilho());
}
return retorno;
}
}
| 12,753 | 0.614649 | 0.606571 | 490 | 24.02449 | 22.834351 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.769388 | false | false | 9 |
76178aef8ef15f3c2db587cda65fc7f498f2ce7f | 2,121,713,914,970 | 7d4e843050d72cb3573d79a3e340b0919c7ec468 | /app/src/main/java/com/example/ninjamoney/BalanceCalculation/Balance.java | b540e95c14aa6e2ab56f56a8429196fe8bc89630 | [] | no_license | Nabilatasnia/NinjaMoneyFinal | https://github.com/Nabilatasnia/NinjaMoneyFinal | a6b9c07fa1467c21b8f4e7290b53cf4569f9da69 | 904f498dc364a6c29db45f1e66ae434bb65b2d40 | refs/heads/master | 2023-08-29T03:51:03.548000 | 2021-10-06T20:07:04 | 2021-10-06T20:07:04 | 397,078,011 | 1 | 1 | null | false | 2021-09-09T18:15:12 | 2021-08-17T03:21:33 | 2021-09-06T15:34:12 | 2021-09-09T18:15:11 | 227 | 1 | 0 | 0 | Java | false | false | package com.example.ninjamoney.BalanceCalculation;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ninjamoney.Budget;
import com.example.ninjamoney.Donate;
import com.example.ninjamoney.Expense;
import com.example.ninjamoney.Income;
import com.example.ninjamoney.LoginSignUp.Login;
import com.example.ninjamoney.LoginSignUp.Profile;
import com.example.ninjamoney.MainActivity;
import com.example.ninjamoney.R;
import com.example.ninjamoney.Report;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class Balance extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
TextView balance_tv;
TextView cash_balance_tv;
TextView bank_balance_tv;
TextView mobile_balance_tv;
TextView username_tv;
TextView email_tv;
private FirebaseAuth firebaseAuth;
private FirebaseDatabase database;
private DatabaseReference dRef;
private DatabaseReference dRefBalance;
private FirebaseUser firebaseUser;
String uid;
int incomeCash, incomeBank, incomeMobile, incomeTotal;
int expenseCash, expenseBank, expenseMobile, expenseTotal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance);
setup();
drawer();
firebase();
update();
}
private void firebase() {
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
uid = firebaseUser.getUid();
dRef = database.getReference().child("Users").child(uid);
Query query = dRef.orderByChild("email");
query.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChildName) {
if (snapshot.exists()) {
String name = snapshot.child("username").getValue().toString();
String email = snapshot.child("email").getValue().toString();
username_tv.setText(name);
email_tv.setText(email);
}
}
@Override
public void onChildChanged(DataSnapshot snapshot, String previousChildName) {
}
@Override
public void onChildRemoved(DataSnapshot snapshot) {
}
@Override
public void onChildMoved(DataSnapshot snapshot, String previousChildName) {
}
@Override
public void onCancelled(DatabaseError error) {
}
});
}
private void update() {
dRefBalance = database.getReference().child("BalanceData").child(uid);
dRefBalance.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
incomeCash= Integer.parseInt(snapshot.child("incomeCash").getValue().toString().trim());
incomeBank = Integer.parseInt(snapshot.child("incomeBank").getValue().toString().trim());
incomeMobile = Integer.parseInt(snapshot.child("incomeMobile").getValue().toString().trim());
incomeTotal = Integer.parseInt(snapshot.child("incomeTotal").getValue().toString().trim());
expenseCash = Integer.parseInt(snapshot.child("expenseCash").getValue().toString().trim());
expenseBank = Integer.parseInt(snapshot.child("expenseBank").getValue().toString().trim());
expenseMobile = Integer.parseInt(snapshot.child("expenseMobile").getValue().toString().trim());
expenseTotal = Integer.parseInt(snapshot.child("expenseTotal").getValue().toString().trim());
int total = incomeTotal - expenseTotal;
int cash = incomeCash - expenseCash;
int bank = incomeBank - expenseBank;
int mobile = incomeMobile - expenseMobile;
balance_tv.setText(total+" ৳");
cash_balance_tv.setText(cash+" ৳");
bank_balance_tv.setText(bank+" ৳");
mobile_balance_tv.setText(mobile+" ৳");
}
@Override
public void onCancelled(DatabaseError error) {
}
});
}
private void setup() {
balance_tv = findViewById(R.id.balance_tv);
cash_balance_tv = findViewById(R.id.cash_balance_tv);
bank_balance_tv = findViewById(R.id.bank_balance_tv);
mobile_balance_tv = findViewById(R.id.mobile_balance_tv);
username_tv = findViewById(R.id.username_tv);
email_tv = findViewById(R.id.email_tv);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
}
private void drawer() {
setSupportActionBar(toolbar);
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_balance);
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
Intent intentHome = new Intent(this, MainActivity.class);
startActivity(intentHome);
}
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
Intent intentHome = new Intent(this, MainActivity.class);
startActivity(intentHome);
break;
case R.id.nav_income:
Intent intentInc = new Intent(this, Income.class);
startActivity(intentInc);
break;
case R.id.nav_expense:
Intent intentBud = new Intent(this, Expense.class);
startActivity(intentBud);
break;
case R.id.nav_budget:
Intent intentStat = new Intent(this, Budget.class);
startActivity(intentStat);
break;
case R.id.nav_report:
Intent intentRep = new Intent(this, Report.class);
startActivity(intentRep);
break;
case R.id.nav_donate:
Intent intentDon = new Intent(this, Donate.class);
startActivity(intentDon);
break;
case R.id.nav_profile:
Intent intentProf = new Intent(this, Profile.class);
startActivity(intentProf);
break;
case R.id.nav_logout:
FirebaseAuth.getInstance().signOut();
Intent intentOut = new Intent(this, Login.class);
startActivity(intentOut);
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
} | UTF-8 | Java | 8,239 | java | Balance.java | Java | [
{
"context": "ance_tv);\n username_tv = findViewById(R.id.username_tv);\n email_tv = findViewById(R.id.email_t",
"end": 5629,
"score": 0.5806096196174622,
"start": 5621,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | package com.example.ninjamoney.BalanceCalculation;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ninjamoney.Budget;
import com.example.ninjamoney.Donate;
import com.example.ninjamoney.Expense;
import com.example.ninjamoney.Income;
import com.example.ninjamoney.LoginSignUp.Login;
import com.example.ninjamoney.LoginSignUp.Profile;
import com.example.ninjamoney.MainActivity;
import com.example.ninjamoney.R;
import com.example.ninjamoney.Report;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class Balance extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
TextView balance_tv;
TextView cash_balance_tv;
TextView bank_balance_tv;
TextView mobile_balance_tv;
TextView username_tv;
TextView email_tv;
private FirebaseAuth firebaseAuth;
private FirebaseDatabase database;
private DatabaseReference dRef;
private DatabaseReference dRefBalance;
private FirebaseUser firebaseUser;
String uid;
int incomeCash, incomeBank, incomeMobile, incomeTotal;
int expenseCash, expenseBank, expenseMobile, expenseTotal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance);
setup();
drawer();
firebase();
update();
}
private void firebase() {
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
uid = firebaseUser.getUid();
dRef = database.getReference().child("Users").child(uid);
Query query = dRef.orderByChild("email");
query.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChildName) {
if (snapshot.exists()) {
String name = snapshot.child("username").getValue().toString();
String email = snapshot.child("email").getValue().toString();
username_tv.setText(name);
email_tv.setText(email);
}
}
@Override
public void onChildChanged(DataSnapshot snapshot, String previousChildName) {
}
@Override
public void onChildRemoved(DataSnapshot snapshot) {
}
@Override
public void onChildMoved(DataSnapshot snapshot, String previousChildName) {
}
@Override
public void onCancelled(DatabaseError error) {
}
});
}
private void update() {
dRefBalance = database.getReference().child("BalanceData").child(uid);
dRefBalance.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
incomeCash= Integer.parseInt(snapshot.child("incomeCash").getValue().toString().trim());
incomeBank = Integer.parseInt(snapshot.child("incomeBank").getValue().toString().trim());
incomeMobile = Integer.parseInt(snapshot.child("incomeMobile").getValue().toString().trim());
incomeTotal = Integer.parseInt(snapshot.child("incomeTotal").getValue().toString().trim());
expenseCash = Integer.parseInt(snapshot.child("expenseCash").getValue().toString().trim());
expenseBank = Integer.parseInt(snapshot.child("expenseBank").getValue().toString().trim());
expenseMobile = Integer.parseInt(snapshot.child("expenseMobile").getValue().toString().trim());
expenseTotal = Integer.parseInt(snapshot.child("expenseTotal").getValue().toString().trim());
int total = incomeTotal - expenseTotal;
int cash = incomeCash - expenseCash;
int bank = incomeBank - expenseBank;
int mobile = incomeMobile - expenseMobile;
balance_tv.setText(total+" ৳");
cash_balance_tv.setText(cash+" ৳");
bank_balance_tv.setText(bank+" ৳");
mobile_balance_tv.setText(mobile+" ৳");
}
@Override
public void onCancelled(DatabaseError error) {
}
});
}
private void setup() {
balance_tv = findViewById(R.id.balance_tv);
cash_balance_tv = findViewById(R.id.cash_balance_tv);
bank_balance_tv = findViewById(R.id.bank_balance_tv);
mobile_balance_tv = findViewById(R.id.mobile_balance_tv);
username_tv = findViewById(R.id.username_tv);
email_tv = findViewById(R.id.email_tv);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
}
private void drawer() {
setSupportActionBar(toolbar);
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_balance);
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
Intent intentHome = new Intent(this, MainActivity.class);
startActivity(intentHome);
}
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
Intent intentHome = new Intent(this, MainActivity.class);
startActivity(intentHome);
break;
case R.id.nav_income:
Intent intentInc = new Intent(this, Income.class);
startActivity(intentInc);
break;
case R.id.nav_expense:
Intent intentBud = new Intent(this, Expense.class);
startActivity(intentBud);
break;
case R.id.nav_budget:
Intent intentStat = new Intent(this, Budget.class);
startActivity(intentStat);
break;
case R.id.nav_report:
Intent intentRep = new Intent(this, Report.class);
startActivity(intentRep);
break;
case R.id.nav_donate:
Intent intentDon = new Intent(this, Donate.class);
startActivity(intentDon);
break;
case R.id.nav_profile:
Intent intentProf = new Intent(this, Profile.class);
startActivity(intentProf);
break;
case R.id.nav_logout:
FirebaseAuth.getInstance().signOut();
Intent intentOut = new Intent(this, Login.class);
startActivity(intentOut);
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
} | 8,239 | 0.642449 | 0.642449 | 217 | 36.935482 | 27.913551 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.695853 | false | false | 9 |
cb02139413a615c8575948931b4b10ba10342d81 | 14,516,989,508,948 | a4c32d6edffaee19569b717009fe8041749d86d2 | /src/com/mysmallcornerstudios/xwing/data/Bombs.java | 438253ad03e5bda6a382a137e387ccccdceb75a2 | [] | no_license | DevJonny/Dorn | https://github.com/DevJonny/Dorn | fa47445b34cff6bb3f68cef4d3a1cd2e1fa2ea23 | 88dc1582768d236ae88dfb6167e36d01b588ea36 | refs/heads/master | 2016-08-05T18:51:08.391000 | 2013-12-12T19:36:58 | 2013-12-12T19:36:58 | 12,574,705 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mysmallcornerstudios.xwing.data;
import com.mysmallcornerstudios.xwing.util.Constants;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public enum Bombs {
PROXIMITY_MINES(1, "Proximity Mines", 3, "Action: Discard this card to drop 1 proximity mine token. When a ship executes a maneuver, if its base or maneuver template overlaps this token, this token detonates.", false, new int[]{9}),
SEISMIC_CHARGES(2, "Seismic Charges", 2, "When you reveal your maneuver dial, you may discard this card to drop 1 seismic charge token. This token detonates at the end of the Activation phase.", false, new int[]{9, 11}),
PROTON_BOMBS(3, "Proton Bombs", 5, "When you reveal your maneuver dial, you may discard this card to drop 1 proton bomb token. The bomb detonates at the end of the Activation phase.", false, new int[]{11});
public static final String VALUE = "[BOMB]";
public final int ID;
public final String NAME;
public final int COST;
public final String DESCRIPTION;
public final boolean UNIQUE;
public final int[] SETS;
public static Map<Integer, Bombs> ID_TO_BOMB;
public static String[] BOMBS;
Bombs(int ID, String NAME, int COST, String DESCRIPTION, boolean UNIQUE, int[] SETS) {
this.ID = ID;
this.NAME = NAME;
this.COST = COST;
this.DESCRIPTION = DESCRIPTION;
this.UNIQUE = UNIQUE;
this.SETS = SETS;
}
static {
final Map<Integer, Bombs> idToBomb = new HashMap<Integer, Bombs>();
for (Bombs bomb : Bombs.values())
idToBomb.put(bomb.ID, bomb);
ID_TO_BOMB = Collections.unmodifiableMap(idToBomb);
final String[] bombs = new String[Bombs.values().length];
for (int i = 0; i < bombs.length; i++) {
bombs[i] = String.format(Constants.UPGRADE_TEXT, Bombs.values()[i].NAME, Bombs.values()[i].COST);
}
BOMBS = bombs;
}
} | UTF-8 | Java | 2,015 | java | Bombs.java | Java | [] | null | [] | package com.mysmallcornerstudios.xwing.data;
import com.mysmallcornerstudios.xwing.util.Constants;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public enum Bombs {
PROXIMITY_MINES(1, "Proximity Mines", 3, "Action: Discard this card to drop 1 proximity mine token. When a ship executes a maneuver, if its base or maneuver template overlaps this token, this token detonates.", false, new int[]{9}),
SEISMIC_CHARGES(2, "Seismic Charges", 2, "When you reveal your maneuver dial, you may discard this card to drop 1 seismic charge token. This token detonates at the end of the Activation phase.", false, new int[]{9, 11}),
PROTON_BOMBS(3, "Proton Bombs", 5, "When you reveal your maneuver dial, you may discard this card to drop 1 proton bomb token. The bomb detonates at the end of the Activation phase.", false, new int[]{11});
public static final String VALUE = "[BOMB]";
public final int ID;
public final String NAME;
public final int COST;
public final String DESCRIPTION;
public final boolean UNIQUE;
public final int[] SETS;
public static Map<Integer, Bombs> ID_TO_BOMB;
public static String[] BOMBS;
Bombs(int ID, String NAME, int COST, String DESCRIPTION, boolean UNIQUE, int[] SETS) {
this.ID = ID;
this.NAME = NAME;
this.COST = COST;
this.DESCRIPTION = DESCRIPTION;
this.UNIQUE = UNIQUE;
this.SETS = SETS;
}
static {
final Map<Integer, Bombs> idToBomb = new HashMap<Integer, Bombs>();
for (Bombs bomb : Bombs.values())
idToBomb.put(bomb.ID, bomb);
ID_TO_BOMB = Collections.unmodifiableMap(idToBomb);
final String[] bombs = new String[Bombs.values().length];
for (int i = 0; i < bombs.length; i++) {
bombs[i] = String.format(Constants.UPGRADE_TEXT, Bombs.values()[i].NAME, Bombs.values()[i].COST);
}
BOMBS = bombs;
}
} | 2,015 | 0.649132 | 0.641191 | 53 | 36.056602 | 52.0172 | 236 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.169811 | false | false | 9 |
ab151c3ed673f96622a871a6410c6077b6db13ea | 15,290,083,617,280 | dd4b432d4233efd96aac7c85943643d3603f8a6d | /TouchListenerConflict-master/app/src/main/java/me/daei/touchlistenerconflict/MainActivity.java | caa22e917b5b64e11cfc952fd13ed85b381a4340 | [] | no_license | MR-GuoQing/CustomView | https://github.com/MR-GuoQing/CustomView | eb587c2db773f41f2ea55c2bd2cd8f6beb346115 | 2fe3de9ec7162f654862c433ffd7ee07b8950c01 | refs/heads/master | 2020-03-13T15:41:22.925000 | 2018-05-01T11:56:06 | 2018-05-01T11:56:06 | 131,182,061 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.daei.touchlistenerconflict;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
@Bind(R.id.id_viewpager)
ViewPager idViewpager;
@OnClick({R.id.id_indicator_one,R.id.id_indicator_two,R.id.id_indicator_three,R.id.id_indicator_four})
void viewClick(View view) {
switch (view.getId()) {
case R.id.id_indicator_one:
clickTab(0);
break;
case R.id.id_indicator_two:
clickTab(1);
break;
case R.id.id_indicator_three:
clickTab(2);
break;
case R.id.id_indicator_four:
clickTab(3);
break;
}
}
private ViewPagerAdapter mPagerAdapter;
private final int PAGE_SIZE = 4;
private Fragment[] rootFragments = new Fragment[PAGE_SIZE];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
init();
}
private void init() {
if (idViewpager != null) {
setupViewPager(idViewpager);
}
clickTab(0);
}
private void clickTab(int tabType) {
idViewpager.setCurrentItem(tabType, true);
changeTab(tabType);
}
public void setViewpagerNoSCroll(boolean scroll) {
if(!scroll){
idViewpager.requestDisallowInterceptTouchEvent(true);
}
}
private void setupViewPager(ViewPager viewPager) {
mPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
for (int i = 0; i < PAGE_SIZE; i++) {
switch (i) {
case 0:
rootFragments[i] = new MainFragment();
break;
case 1:
rootFragments[i] = new AboutFragment();
break;
case 2:
rootFragments[i] = new AboutFragment();
break;
case 3:
rootFragments[i] = new AboutFragment();
break;
}
Log.e("rootFragments", i + "= " + rootFragments[i]);
rootFragments[i].setRetainInstance(true);
mPagerAdapter.addFragment(rootFragments[i], getFragmentTag(i));
}
viewPager.setAdapter(mPagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
changeTab(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
viewPager.setOffscreenPageLimit(PAGE_SIZE);
}
private void changeTab(int tabType) {
}
private String getFragmentTag(int pos) {
String tag = "pos_default";
switch (pos) {
case 0:
tag = "功能1";
break;
case 1:
tag = "功能2";
break;
case 2:
tag = "功能3";
break;
case 3:
tag = "功能4";
break;
}
return tag;
}
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
}
}
| UTF-8 | Java | 4,436 | java | MainActivity.java | Java | [] | null | [] | package me.daei.touchlistenerconflict;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
@Bind(R.id.id_viewpager)
ViewPager idViewpager;
@OnClick({R.id.id_indicator_one,R.id.id_indicator_two,R.id.id_indicator_three,R.id.id_indicator_four})
void viewClick(View view) {
switch (view.getId()) {
case R.id.id_indicator_one:
clickTab(0);
break;
case R.id.id_indicator_two:
clickTab(1);
break;
case R.id.id_indicator_three:
clickTab(2);
break;
case R.id.id_indicator_four:
clickTab(3);
break;
}
}
private ViewPagerAdapter mPagerAdapter;
private final int PAGE_SIZE = 4;
private Fragment[] rootFragments = new Fragment[PAGE_SIZE];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
init();
}
private void init() {
if (idViewpager != null) {
setupViewPager(idViewpager);
}
clickTab(0);
}
private void clickTab(int tabType) {
idViewpager.setCurrentItem(tabType, true);
changeTab(tabType);
}
public void setViewpagerNoSCroll(boolean scroll) {
if(!scroll){
idViewpager.requestDisallowInterceptTouchEvent(true);
}
}
private void setupViewPager(ViewPager viewPager) {
mPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
for (int i = 0; i < PAGE_SIZE; i++) {
switch (i) {
case 0:
rootFragments[i] = new MainFragment();
break;
case 1:
rootFragments[i] = new AboutFragment();
break;
case 2:
rootFragments[i] = new AboutFragment();
break;
case 3:
rootFragments[i] = new AboutFragment();
break;
}
Log.e("rootFragments", i + "= " + rootFragments[i]);
rootFragments[i].setRetainInstance(true);
mPagerAdapter.addFragment(rootFragments[i], getFragmentTag(i));
}
viewPager.setAdapter(mPagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
changeTab(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
viewPager.setOffscreenPageLimit(PAGE_SIZE);
}
private void changeTab(int tabType) {
}
private String getFragmentTag(int pos) {
String tag = "pos_default";
switch (pos) {
case 0:
tag = "功能1";
break;
case 1:
tag = "功能2";
break;
case 2:
tag = "功能3";
break;
case 3:
tag = "功能4";
break;
}
return tag;
}
static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
}
}
| 4,436 | 0.557692 | 0.552262 | 156 | 27.333334 | 21.567228 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.49359 | false | false | 9 |
ca891dd55e4760f854332223ec1ada52111aab7c | 30,623,116,827,584 | cad41fada256cbdff05a23f3c0df57faea7025d1 | /koin-projects/koin-java/src/test/java/org/koin/standalone/UnitJavaTest.java | 4004af146e5730fc64d2968bfaedbd5cf5249fa0 | [
"Apache-2.0"
] | permissive | EslamHussein/koin | https://github.com/EslamHussein/koin | daecbb1cc2e3f6593bb413a455327e0c56f674af | bdfcec953b256e98326c997c90a4ead482fdbecd | refs/heads/master | 2020-04-14T06:38:25.923000 | 2019-01-01T08:57:11 | 2019-01-01T08:57:11 | 163,691,953 | 0 | 0 | Apache-2.0 | true | 2019-01-01T08:33:26 | 2018-12-31T19:08:13 | 2018-12-31T19:08:16 | 2019-01-01T08:33:26 | 3,272 | 0 | 0 | 0 | Kotlin | false | null | package org.koin.standalone;
import kotlin.Lazy;
import org.junit.Before;
import org.junit.Test;
import org.koin.core.scope.Scope;
import org.koin.test.AutoCloseKoinTest;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.koin.java.standalone.KoinJavaComponent.*;
import static org.koin.java.standalone.KoinJavaStarter.startKoin;
import static org.koin.standalone.UnitJavaStuffKt.koinModule;
public class UnitJavaTest extends AutoCloseKoinTest {
@Before
public void before() {
startKoin(singletonList(koinModule));
}
@Test
public void successful_get() {
ComponentA a = get(ComponentA.class);
assertNotNull(a);
ComponentB b = get(ComponentB.class);
assertNotNull(b);
ComponentC c = get(ComponentC.class);
assertNotNull(c);
assertEquals(a, b.getComponentA());
assertEquals(a, c.getA());
}
@Test
public void successful_lazy() {
Lazy<ComponentA> lazy_a = inject(ComponentA.class);
Lazy<ComponentB> lazy_b = inject(ComponentB.class);
Lazy<ComponentC> lazy_c = inject(ComponentC.class);
assertEquals(lazy_a.getValue(), lazy_b.getValue().getComponentA());
assertEquals(lazy_a.getValue(), lazy_c.getValue().getA());
Scope session = getKoin().createScope("session");
assertNotNull(get(ComponentD.class));
session.close();
}
}
| UTF-8 | Java | 1,513 | java | UnitJavaTest.java | Java | [] | null | [] | package org.koin.standalone;
import kotlin.Lazy;
import org.junit.Before;
import org.junit.Test;
import org.koin.core.scope.Scope;
import org.koin.test.AutoCloseKoinTest;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.koin.java.standalone.KoinJavaComponent.*;
import static org.koin.java.standalone.KoinJavaStarter.startKoin;
import static org.koin.standalone.UnitJavaStuffKt.koinModule;
public class UnitJavaTest extends AutoCloseKoinTest {
@Before
public void before() {
startKoin(singletonList(koinModule));
}
@Test
public void successful_get() {
ComponentA a = get(ComponentA.class);
assertNotNull(a);
ComponentB b = get(ComponentB.class);
assertNotNull(b);
ComponentC c = get(ComponentC.class);
assertNotNull(c);
assertEquals(a, b.getComponentA());
assertEquals(a, c.getA());
}
@Test
public void successful_lazy() {
Lazy<ComponentA> lazy_a = inject(ComponentA.class);
Lazy<ComponentB> lazy_b = inject(ComponentB.class);
Lazy<ComponentC> lazy_c = inject(ComponentC.class);
assertEquals(lazy_a.getValue(), lazy_b.getValue().getComponentA());
assertEquals(lazy_a.getValue(), lazy_c.getValue().getA());
Scope session = getKoin().createScope("session");
assertNotNull(get(ComponentD.class));
session.close();
}
}
| 1,513 | 0.69002 | 0.69002 | 55 | 26.50909 | 23.171984 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 9 |
00a457f0f1d27ba1162ac0cc218d70e3dbd425b6 | 28,406,913,696,355 | fa9dec2d731e65a0f07dc9af5449c6356cadcb06 | /app/src/main/java/cn/closeli/rtc/utils/ext/WorkThreadFactory.java | b6d6e3cff66045bf14ecafc8a91a3217f651ccf8 | [
"Apache-2.0"
] | permissive | huizhongyu/SudiVCAndroidClient | https://github.com/huizhongyu/SudiVCAndroidClient | 8526ea236322e5a96804aab531f7431d0eb71023 | ccf3a8b6788ec6577c42740ba491785c526e373e | refs/heads/master | 2021-01-05T01:40:27.675000 | 2020-02-17T06:10:39 | 2020-02-17T06:10:39 | 240,832,731 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.closeli.rtc.utils.ext;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public class WorkThreadFactory implements ThreadFactory {
private AtomicInteger atomicInteger = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r)
{
int c = atomicInteger.incrementAndGet();
System.out.println("create no " + c + " Threads");
return new WorkThread(r, atomicInteger);//通过计数器,可以更好的管理线程
}
}
| UTF-8 | Java | 525 | java | WorkThreadFactory.java | Java | [] | null | [] | package cn.closeli.rtc.utils.ext;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public class WorkThreadFactory implements ThreadFactory {
private AtomicInteger atomicInteger = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r)
{
int c = atomicInteger.incrementAndGet();
System.out.println("create no " + c + " Threads");
return new WorkThread(r, atomicInteger);//通过计数器,可以更好的管理线程
}
}
| 525 | 0.721212 | 0.719192 | 17 | 28.117647 | 25.047913 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 9 |
5f1ca5b710aad5f6078817494f92322301001b73 | 11,836,929,925,803 | c4e9fc249bdaedd501ab56ab3a0eb2e5b14ed212 | /src/de/jspll/data/objects/game/ui/HomeCameraAssist.java | 09751fb7fc8cd037ea79bb8361eb6ad3d5810e5a | [] | no_license | SamuelMichaAssmann/Sekretariat-Spiel | https://github.com/SamuelMichaAssmann/Sekretariat-Spiel | 61c02b4a3a000d79e4771d1f3599c0f30a19c0b9 | 3647f362e7935c324fbc3ed67678bf976cf06851 | refs/heads/master | 2023-02-23T14:37:49.924000 | 2020-12-07T17:32:31 | 2020-12-07T17:32:31 | 300,528,117 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.jspll.data.objects.game.ui;
import de.jspll.data.ChannelID;
import de.jspll.data.objects.GameObject;
import de.jspll.graphics.Camera;
import java.awt.*;
/**
* © Sekretariat-Spiel
* By Jonas Sperling, Laura Schmidt, Lukas Becker, Philipp Polland, Samuel Assmann
*
* @author Lukas Becker
*
* @version 1.0
*/
public class HomeCameraAssist extends GameObject {
int mapWidth;
int mapHeight;
float zoom;
public HomeCameraAssist(int mw, int mh, float z){
super("hca", "homeCameraAssist", 0, 0, new Dimension(0,0));
mapHeight = mh;
mapWidth = mw;
zoom = z;
channels = new ChannelID[]{ChannelID.UI};
}
@Override
public void paint(Graphics g, float elapsedTime, Camera camera, ChannelID currStage) {
camera.instantlyCenterToPos(mapWidth/3, mapHeight/3);
camera.instantlyZoom(zoom);
}
}
| UTF-8 | Java | 891 | java | HomeCameraAssist.java | Java | [
{
"context": "pll.graphics.Camera;\n\nimport java.awt.*;\n\n/**\n * © Sekretariat-Spiel\n * By Jonas Sperling, Laura Schmidt, Lukas Becker",
"end": 193,
"score": 0.9971951842308044,
"start": 176,
"tag": "NAME",
"value": "Sekretariat-Spiel"
},
{
"context": "port java.awt.*;\n\n/**\n *... | null | [] | package de.jspll.data.objects.game.ui;
import de.jspll.data.ChannelID;
import de.jspll.data.objects.GameObject;
import de.jspll.graphics.Camera;
import java.awt.*;
/**
* © Sekretariat-Spiel
* By <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
*
* @author <NAME>
*
* @version 1.0
*/
public class HomeCameraAssist extends GameObject {
int mapWidth;
int mapHeight;
float zoom;
public HomeCameraAssist(int mw, int mh, float z){
super("hca", "homeCameraAssist", 0, 0, new Dimension(0,0));
mapHeight = mh;
mapWidth = mw;
zoom = z;
channels = new ChannelID[]{ChannelID.UI};
}
@Override
public void paint(Graphics g, float elapsedTime, Camera camera, ChannelID currStage) {
camera.instantlyCenterToPos(mapWidth/3, mapHeight/3);
camera.instantlyZoom(zoom);
}
}
| 847 | 0.668539 | 0.659551 | 38 | 22.421053 | 23.97546 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.789474 | false | false | 9 |
ea027c152a8368b3bffe7c6514e45faadd038c39 | 24,575,802,885,257 | f8b04daa0dabe6fc3a82dd64e392807f9e72503c | /src/main/java/com/eric/forkjoin/BinarySearcher.java | 2bd87c6201c367dd3e82da937f890af07e31dc1c | [] | no_license | gangyou/garbage | https://github.com/gangyou/garbage | 269a9dacc6fc564ad37d337374882f8602db9c63 | de60e1a2a538bdcbe943a6f35429db5542ba4469 | refs/heads/master | 2020-04-27T01:01:33.020000 | 2013-11-01T08:37:57 | 2013-11-01T08:37:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.eric.forkjoin;
import java.util.Arrays;
public class BinarySearcher {
private final int[] numbers;
private final int start;
private final int end;
public final int size;
public BinarySearcher(int[] numbers, int start, int end){
this.numbers = numbers;
this.start = start;
this.end = end;
this.size = end - start;
}
public int search(int numberToSearch){
return Arrays.binarySearch(numbers, start, end, numberToSearch);
}
public BinarySearcher sub(int subStart, int subEnd){
return new BinarySearcher(numbers, start+subStart, start+subEnd);
}
}
| UTF-8 | Java | 584 | java | BinarySearcher.java | Java | [] | null | [] | package com.eric.forkjoin;
import java.util.Arrays;
public class BinarySearcher {
private final int[] numbers;
private final int start;
private final int end;
public final int size;
public BinarySearcher(int[] numbers, int start, int end){
this.numbers = numbers;
this.start = start;
this.end = end;
this.size = end - start;
}
public int search(int numberToSearch){
return Arrays.binarySearch(numbers, start, end, numberToSearch);
}
public BinarySearcher sub(int subStart, int subEnd){
return new BinarySearcher(numbers, start+subStart, start+subEnd);
}
}
| 584 | 0.734589 | 0.734589 | 26 | 21.461538 | 20.777634 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.615385 | false | false | 9 |
939f2fc703d9943caba23fea2365d8f0b606b464 | 24,575,802,883,696 | d60e287543a95a20350c2caeabafbec517cabe75 | /NLPCCd/Hadoop/5290_2.java | 244850bee37a03753d30259b8f3203e0b667bec8 | [
"MIT"
] | permissive | sgholamian/log-aware-clone-detection | https://github.com/sgholamian/log-aware-clone-detection | 242067df2db6fd056f8d917cfbc143615c558b2c | 9993cb081c420413c231d1807bfff342c39aa69a | refs/heads/main | 2023-07-20T09:32:19.757000 | 2021-08-27T15:02:50 | 2021-08-27T15:02:50 | 337,837,827 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //,temp,sample_5753.java,2,12,temp,sample_1150.java,2,13
//,3
public class xxx {
public void testLazyPersistBlocksAreSaved() throws IOException, InterruptedException, TimeoutException {
getClusterBuilder().build();
final int NUM_BLOCKS = 10;
final String METHOD_NAME = GenericTestUtils.getMethodName();
Path path = new Path("/" + METHOD_NAME + ".dat");
makeTestFile(path, BLOCK_SIZE * NUM_BLOCKS, true);
LocatedBlocks locatedBlocks = ensureFileReplicasOnStorageType(path, RAM_DISK);
waitForMetric("RamDiskBlocksLazyPersisted", NUM_BLOCKS);
log.info("verifying copy was saved to lazypersist");
}
}; | UTF-8 | Java | 600 | java | 5290_2.java | Java | [] | null | [] | //,temp,sample_5753.java,2,12,temp,sample_1150.java,2,13
//,3
public class xxx {
public void testLazyPersistBlocksAreSaved() throws IOException, InterruptedException, TimeoutException {
getClusterBuilder().build();
final int NUM_BLOCKS = 10;
final String METHOD_NAME = GenericTestUtils.getMethodName();
Path path = new Path("/" + METHOD_NAME + ".dat");
makeTestFile(path, BLOCK_SIZE * NUM_BLOCKS, true);
LocatedBlocks locatedBlocks = ensureFileReplicasOnStorageType(path, RAM_DISK);
waitForMetric("RamDiskBlocksLazyPersisted", NUM_BLOCKS);
log.info("verifying copy was saved to lazypersist");
}
}; | 600 | 0.771667 | 0.743333 | 17 | 34.35294 | 30.793318 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.411765 | false | false | 9 |
5e02ff70fe8585fb6d87beeb8ffcb29133e7657c | 20,581,483,311,700 | 8d24d81084f03947e2a6102290607d4695df218d | /app/src/main/java/gwind/windalarm/request/requestMeteoDataTask.java | 36b2ed8456c4ab688462fed51b792d675460ec43 | [] | no_license | giaggi/NewWindAlarm | https://github.com/giaggi/NewWindAlarm | 3bc2f4591586f4b79a2a40f70b72b35723a9cbd3 | 34f07389bc7329c41d02e016917af86236ef31c2 | refs/heads/master | 2020-05-21T20:33:06.301000 | 2017-09-09T22:15:37 | 2017-09-09T22:15:37 | 61,830,325 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gwind.windalarm.request;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import gwind.windalarm.AlarmPreferences;
import gwind.windalarm.AsyncRequestMeteoDataResponse;
import gwind.windalarm.SplashActivity;
import gwind.windalarm.Spot;
import gwind.windalarm.data.Forecast;
import gwind.windalarm.data.Location;
import gwind.windalarm.data.MeteoStationData;
/**
* Created by giacomo on 01/07/2015.
*/
public class requestMeteoDataTask extends
AsyncTask<Object, Long, requestMeteoDataTask.Result> {
public static final int REQUEST_LASTMETEODATA = 1;
public static final int REQUEST_SPOTLIST = 3;
public static final int REQUEST_SPOTLIST_FULLINFO = 4;
public static final int REQUEST_LOGMETEODATA = 5;
public static final int REQUEST_ADDFAVORITE = 6;
public static final int REQUEST_REMOVEFAVORITE = 7;
public static final int REQUEST_FAVORITESLASTMETEODATA = 8;
public static final int REQUEST_FORECAST = 9;
public static final int REQUEST_FORECASTLOCATIONS = 10;
public static final int REQUEST_FAVORITESSORDER = 11;
public static final int REQUEST_FAVORITES = 11;
public static final String FORECAST_WINDFINDER = "Windfinder";
public static final String FORECAST_WINDGURU = "Windguru";
public static final String FORECAST_OPENWEATHERMAP = "OpenWeathermap";
public static String Spot_All = "all";
public AsyncRequestMeteoDataResponse delegate = null;//Call back interface
private ProgressDialog dialog;
private Activity activity;
private boolean error = false;
private String errorMessage = "";
int requestType;
int requestId;
int contentSize;
protected class Result {
public List<MeteoStationData> meteoList;
public List<Spot> spotList;
public List<Location> locations;
public List<Long> favorites;
public long spotId;
public Forecast forecast;
}
public requestMeteoDataTask(Activity activity, AsyncRequestMeteoDataResponse asyncResponse, int type) {
this.activity = activity;
dialog = new ProgressDialog(activity);
delegate = asyncResponse;//Assigning call back interfacethrough constructor
requestType = type;
}
protected requestMeteoDataTask.Result doInBackground(Object... params) {
requestMeteoDataTask.Result result = new requestMeteoDataTask.Result();
URL url;
if (requestType == REQUEST_ADDFAVORITE || requestType == REQUEST_REMOVEFAVORITE) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
//String regId = AlarmPreferences.getRegId(activity.getApplicationContext());
long spotId = (long) params[0];
String userid = (String) params[1];
String serverUrl = AlarmPreferences.getServerUrl(activity);
httppost = new HttpPost(serverUrl + "/meteo");
nameValuePairs.add(new BasicNameValuePair("spotid", "" + spotId));
nameValuePairs.add(new BasicNameValuePair("userid", userid));
if (requestType == REQUEST_REMOVEFAVORITE)
nameValuePairs.add(new BasicNameValuePair("remove", "true"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
return null;
} catch (IOException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
return null;
}
result.spotId = spotId;
return result;
} else if (requestType == REQUEST_FAVORITESSORDER) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
//String regId = AlarmPreferences.getRegId(activity.getApplicationContext());
String userid = (String) params[1];
String spotList = (String) params[2];
String serverUrl = AlarmPreferences.getServerUrl(activity);
httppost = new HttpPost(serverUrl + "/meteo");
nameValuePairs.add(new BasicNameValuePair("spotlist", "" + spotList));
nameValuePairs.add(new BasicNameValuePair("userid", userid));
nameValuePairs.add(new BasicNameValuePair("reorder", "true"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
return null;
} catch (IOException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
return null;
}
//result.spotId = spotId;
return result;
} else {
try {
String path = "/meteo?";
if (requestType == REQUEST_LASTMETEODATA) {
String spotList = (String) params[0]; //lista di spot separata da virgola
String userid = (String) params[1];
path += "lastdata=true";
path += "&history=false";
path += "&requestspotlist=false";
path += "&fullinfo=false";
path += "&spot=" + spotList;
path += "&userid=" + userid;
} else if (requestType == REQUEST_LOGMETEODATA) {
long spotId = (long) params[0]; // spotID
String userid = (String) params[1];
Date start = (Date) params[2];
Date end = (Date) params[3];
long lastWindId = (long) params[4];
path += "lastdata=false";
path += "&log=true";
path += "&requestspotlist=false";
path += "&fullinfo=false";
path += "&spot=" + spotId;
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss");
path += "&start=" + df.format(start);
path += "&end=" + df.format(end);
path += "&lastwindid=" + lastWindId;
path += "&userid=" + userid;
result.spotId = spotId;
} else if (requestType == REQUEST_SPOTLIST) {
String userid = (String) params[0];
path += "lastdata=false";
path += "&history=false";
path += "&requestspotlist=true";
path += "&fullinfo=false";
path += "&spot=" + Spot_All;
path += "&userid=" + userid;
} else if (requestType == REQUEST_FORECASTLOCATIONS) {
String userid = (String) params[0];
String source = (String) params[1];
String filter = (String) params[2];
path += "forecastlocations=" + source;
path += "&filter=" + filter;
path += "&userid=" + userid;
} else if (requestType == REQUEST_FAVORITESLASTMETEODATA) {
String userid = (String) params[0];
Long windid = (Long) params[1];
path += "favoriteslastdata=true";
path += "&userid=" + userid;
path += "&lastwindid=" + windid;
} else if (requestType == REQUEST_FAVORITES) {
String userid = (String) params[0];
path += "favorites=true";
path += "&userid=" + userid;
} else if (requestType == REQUEST_SPOTLIST_FULLINFO) {
String userid = (String) params[0];
path += "lastdata=false";
path += "&history=false";
path += "&requestspotlist=true";
path += "&fullinfo=true";
path += "&spot=" + Spot_All;
path += "&userid=" + userid;
} else if (requestType == REQUEST_FORECAST) { // OpenWeathermap
String userid = (String) params[0]; // user
String spotId = (String) params[1]; // spotID
String source = (String) params[2]; // source
requestId = (int) params[3]; // request id
long forecastId = (long) params[4]; // request id
path = "/forecast?";
path += "userid=" + userid;
path += "&spot=" + spotId;
path += "&source=" + source;
path += "&lastforecastid=" + forecastId;
}
String serverUrl = AlarmPreferences.getServerUrl(activity);
url = new URL(serverUrl + path);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (SplashActivity.getAcct() != null)
conn.setRequestProperty("user", SplashActivity.getAcct().getServerAuthCode());
conn.setConnectTimeout(5000); //set timeout to 5 seconds
conn.setAllowUserInteraction(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
try {
BufferedInputStream in = new BufferedInputStream(
conn.getInputStream());
// Convert the stream to a String
// There are various approaches, I'll leave it up to you
contentSize = 1000;//Integer.valueOf(conn.getHeaderField("Length"));//conn.getContentLength();
String json = convertStreamToString(in);
if (requestType == REQUEST_SPOTLIST || requestType == REQUEST_SPOTLIST_FULLINFO) {
List<Spot> list = new ArrayList<Spot>();
JSONObject jObject = new JSONObject(json);
JSONArray jArray = jObject.getJSONArray("spotlist");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject2 = jArray.getJSONObject(i);
Spot spt = new Spot(jObject2);
list.add(spt);
}
String favorites = jObject.getString("favorites");
result.spotList = list;
result.favorites = new ArrayList<Long>();
String[] split = favorites.split(",");
if (split != null) {
for (int i = 0; i < split.length; i++) {
if (!split[i].equals("")) {
long id = Integer.valueOf(split[i]);
if (id != 0)
result.favorites.add(id);
}
}
}
// TODO add favorites list
} else if (requestType == REQUEST_FAVORITESLASTMETEODATA || requestType == REQUEST_LASTMETEODATA) {
List<MeteoStationData> list = new ArrayList<MeteoStationData>();
JSONObject jObject = new JSONObject(json);
JSONArray jArray = jObject.getJSONArray("meteodata");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject2 = jArray.getJSONObject(i);
MeteoStationData md = new MeteoStationData(jObject2);
list.add(md);
}
result.meteoList = list;
} else if (requestType == REQUEST_FAVORITES) {
List<Long> list = new ArrayList<>();
JSONObject jObject = new JSONObject(json);
JSONArray jArray = jObject.getJSONArray("favorites");
for (int i = 0; i < jArray.length(); i++) {
Long id = jArray.getLong(i);
list.add(id);
}
result.favorites = list;
} else if (requestType == REQUEST_FORECAST) {
Forecast forecast = new Forecast(json);
result.forecast = forecast;
} else if (requestType == REQUEST_FORECASTLOCATIONS) {
//Forecast forecast = new Forecast(json);
//result.forecast = forecast;
;
JSONObject jobj = new JSONObject(json);
JSONArray jarray = null;
if (jobj.has("locations")) {
result.locations = new ArrayList<>();
jarray = jobj.getJSONArray("locations");
for (int i = 0; i < jarray.length(); i++) {
JSONObject obj = (JSONObject) jarray.get(i);
Location location = new Location(obj);
result.locations.add(location);
}
}
} else if (requestType == REQUEST_LOGMETEODATA) {
List<MeteoStationData> list = new ArrayList<MeteoStationData>();
JSONObject jObject = new JSONObject(json);
String date = jObject.getString("date");
String speed = jObject.getString("speed");
String avspeed = jObject.getString("avspeed");
String temperature = jObject.getString("temperature");
String direction = jObject.getString("direction");
String trend = jObject.getString("trend");
String id = jObject.getString("id");
String[] dates = date.split(";");
String[] speeds = speed.split(";");
String[] avspeeds = avspeed.split(";");
String[] temperatures = temperature.split(";");
String[] directions = direction.split(";");
String[] trends = trend.split(";");
String[] ids = id.split(";");
for (int i = 0; i < dates.length; i++) {
MeteoStationData md = new MeteoStationData();
if (dates[i] != null) {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss");
try {
md.date = df.parse(dates[i]);
} catch (ParseException e) {
e.printStackTrace();
continue;
}
} else {
continue;
}
if (speeds[i] != null && !speeds[i].equals(""))
md.speed = Double.valueOf(speeds[i]);
else
continue;
if (avspeeds[i] != null && !avspeeds[i].equals(""))
md.averagespeed = Double.valueOf(avspeeds[i]);
else
continue;
if (directions[i] != null && !directions[i].equals(""))
md.directionangle = Double.valueOf(directions[i]);
else
continue;
if (trends[i] != null && !trends[i].equals(""))
md.trend = Double.valueOf(trends[i]);
else
continue;
if (temperatures[i] != null && !temperatures[i].equals(""))
md.temperature = Double.valueOf(temperatures[i]);
else
continue;
if (ids[i] != null && !ids[i].equals(""))
md.id = Long.valueOf(ids[i]);
else
continue;
list.add(md);
}
result.meteoList = list;
}
if (conn != null)
conn.disconnect();
} catch (JSONException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
}
} catch (MalformedURLException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
} catch (java.net.SocketTimeoutException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
} catch (IOException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
}
return result;
}
}
protected void onPreExecute() {
//progressBar.setProgress(10);
String message = "attendere prego...";
if (requestType == REQUEST_SPOTLIST)
message = "Richiesta lista spot...";
else if (requestType == REQUEST_SPOTLIST_FULLINFO)
message = "Richiesta lista completa spot...";
//else if (requestType == REQUEST_HISTORYMETEODATA)
//message = "Richiesta dati storici...";
else if (requestType == REQUEST_LASTMETEODATA)
message = "Richiesta dati meteo...";
else if (requestType == REQUEST_FORECAST) {
message = "caricamento ...";
//this.dialog.setMessage(message);
//this.dialog.show();
} else if (requestType == REQUEST_FORECASTLOCATIONS) {
message = "caricamento...";
this.dialog.setMessage(message);
this.dialog.show();
}
//this.dialog.setMessage(message);
//this.dialog.show();
}
@Override
protected void onProgressUpdate(Long... values) {
//progressBar.setProgress(values[0].intValue());
}
protected void onPostExecute(Result result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (requestType == REQUEST_SPOTLIST || requestType == REQUEST_SPOTLIST_FULLINFO) {
delegate.processFinishSpotList(result.spotList, result.favorites, error, errorMessage);
} else if (requestType == REQUEST_LOGMETEODATA) {
List<MeteoStationData> data = new ArrayList<>();
if (result.meteoList != null) {
for (Object obj : result.meteoList) {
data.add(new MeteoStationData((MeteoStationData) obj));
}
}
delegate.processFinishHistory(result.spotId, data, error, errorMessage);
} else if (requestType == REQUEST_LASTMETEODATA || requestType == REQUEST_FAVORITESLASTMETEODATA) {
delegate.processFinish(result.meteoList, error, errorMessage);
} else if (requestType == REQUEST_ADDFAVORITE) {
delegate.processFinishAddFavorite(result.spotId, error, errorMessage);
} else if (requestType == REQUEST_REMOVEFAVORITE) {
delegate.processFinishRemoveFavorite(result.spotId, error, errorMessage);
} else if (requestType == REQUEST_FORECAST) {
delegate.processFinishForecast(requestId, result.forecast, error, errorMessage);
} else if (requestType == REQUEST_FORECASTLOCATIONS) {
delegate.processFinishForecastLocation(result.locations, error, errorMessage);
}
//progressBar.setVisibility(View.GONE);
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
long l = 100 * sb.length() / contentSize;
publishProgress(l);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
| UTF-8 | Java | 22,458 | java | requestMeteoDataTask.java | Java | [
{
"context": "indalarm.data.MeteoStationData;\n\n/**\n * Created by giacomo on 01/07/2015.\n */\npublic class requestMeteoDataT",
"end": 1305,
"score": 0.9995534420013428,
"start": 1298,
"tag": "USERNAME",
"value": "giacomo"
}
] | null | [] | package gwind.windalarm.request;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import gwind.windalarm.AlarmPreferences;
import gwind.windalarm.AsyncRequestMeteoDataResponse;
import gwind.windalarm.SplashActivity;
import gwind.windalarm.Spot;
import gwind.windalarm.data.Forecast;
import gwind.windalarm.data.Location;
import gwind.windalarm.data.MeteoStationData;
/**
* Created by giacomo on 01/07/2015.
*/
public class requestMeteoDataTask extends
AsyncTask<Object, Long, requestMeteoDataTask.Result> {
public static final int REQUEST_LASTMETEODATA = 1;
public static final int REQUEST_SPOTLIST = 3;
public static final int REQUEST_SPOTLIST_FULLINFO = 4;
public static final int REQUEST_LOGMETEODATA = 5;
public static final int REQUEST_ADDFAVORITE = 6;
public static final int REQUEST_REMOVEFAVORITE = 7;
public static final int REQUEST_FAVORITESLASTMETEODATA = 8;
public static final int REQUEST_FORECAST = 9;
public static final int REQUEST_FORECASTLOCATIONS = 10;
public static final int REQUEST_FAVORITESSORDER = 11;
public static final int REQUEST_FAVORITES = 11;
public static final String FORECAST_WINDFINDER = "Windfinder";
public static final String FORECAST_WINDGURU = "Windguru";
public static final String FORECAST_OPENWEATHERMAP = "OpenWeathermap";
public static String Spot_All = "all";
public AsyncRequestMeteoDataResponse delegate = null;//Call back interface
private ProgressDialog dialog;
private Activity activity;
private boolean error = false;
private String errorMessage = "";
int requestType;
int requestId;
int contentSize;
protected class Result {
public List<MeteoStationData> meteoList;
public List<Spot> spotList;
public List<Location> locations;
public List<Long> favorites;
public long spotId;
public Forecast forecast;
}
public requestMeteoDataTask(Activity activity, AsyncRequestMeteoDataResponse asyncResponse, int type) {
this.activity = activity;
dialog = new ProgressDialog(activity);
delegate = asyncResponse;//Assigning call back interfacethrough constructor
requestType = type;
}
protected requestMeteoDataTask.Result doInBackground(Object... params) {
requestMeteoDataTask.Result result = new requestMeteoDataTask.Result();
URL url;
if (requestType == REQUEST_ADDFAVORITE || requestType == REQUEST_REMOVEFAVORITE) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
//String regId = AlarmPreferences.getRegId(activity.getApplicationContext());
long spotId = (long) params[0];
String userid = (String) params[1];
String serverUrl = AlarmPreferences.getServerUrl(activity);
httppost = new HttpPost(serverUrl + "/meteo");
nameValuePairs.add(new BasicNameValuePair("spotid", "" + spotId));
nameValuePairs.add(new BasicNameValuePair("userid", userid));
if (requestType == REQUEST_REMOVEFAVORITE)
nameValuePairs.add(new BasicNameValuePair("remove", "true"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
return null;
} catch (IOException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
return null;
}
result.spotId = spotId;
return result;
} else if (requestType == REQUEST_FAVORITESSORDER) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
//String regId = AlarmPreferences.getRegId(activity.getApplicationContext());
String userid = (String) params[1];
String spotList = (String) params[2];
String serverUrl = AlarmPreferences.getServerUrl(activity);
httppost = new HttpPost(serverUrl + "/meteo");
nameValuePairs.add(new BasicNameValuePair("spotlist", "" + spotList));
nameValuePairs.add(new BasicNameValuePair("userid", userid));
nameValuePairs.add(new BasicNameValuePair("reorder", "true"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
return null;
} catch (IOException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
return null;
}
//result.spotId = spotId;
return result;
} else {
try {
String path = "/meteo?";
if (requestType == REQUEST_LASTMETEODATA) {
String spotList = (String) params[0]; //lista di spot separata da virgola
String userid = (String) params[1];
path += "lastdata=true";
path += "&history=false";
path += "&requestspotlist=false";
path += "&fullinfo=false";
path += "&spot=" + spotList;
path += "&userid=" + userid;
} else if (requestType == REQUEST_LOGMETEODATA) {
long spotId = (long) params[0]; // spotID
String userid = (String) params[1];
Date start = (Date) params[2];
Date end = (Date) params[3];
long lastWindId = (long) params[4];
path += "lastdata=false";
path += "&log=true";
path += "&requestspotlist=false";
path += "&fullinfo=false";
path += "&spot=" + spotId;
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss");
path += "&start=" + df.format(start);
path += "&end=" + df.format(end);
path += "&lastwindid=" + lastWindId;
path += "&userid=" + userid;
result.spotId = spotId;
} else if (requestType == REQUEST_SPOTLIST) {
String userid = (String) params[0];
path += "lastdata=false";
path += "&history=false";
path += "&requestspotlist=true";
path += "&fullinfo=false";
path += "&spot=" + Spot_All;
path += "&userid=" + userid;
} else if (requestType == REQUEST_FORECASTLOCATIONS) {
String userid = (String) params[0];
String source = (String) params[1];
String filter = (String) params[2];
path += "forecastlocations=" + source;
path += "&filter=" + filter;
path += "&userid=" + userid;
} else if (requestType == REQUEST_FAVORITESLASTMETEODATA) {
String userid = (String) params[0];
Long windid = (Long) params[1];
path += "favoriteslastdata=true";
path += "&userid=" + userid;
path += "&lastwindid=" + windid;
} else if (requestType == REQUEST_FAVORITES) {
String userid = (String) params[0];
path += "favorites=true";
path += "&userid=" + userid;
} else if (requestType == REQUEST_SPOTLIST_FULLINFO) {
String userid = (String) params[0];
path += "lastdata=false";
path += "&history=false";
path += "&requestspotlist=true";
path += "&fullinfo=true";
path += "&spot=" + Spot_All;
path += "&userid=" + userid;
} else if (requestType == REQUEST_FORECAST) { // OpenWeathermap
String userid = (String) params[0]; // user
String spotId = (String) params[1]; // spotID
String source = (String) params[2]; // source
requestId = (int) params[3]; // request id
long forecastId = (long) params[4]; // request id
path = "/forecast?";
path += "userid=" + userid;
path += "&spot=" + spotId;
path += "&source=" + source;
path += "&lastforecastid=" + forecastId;
}
String serverUrl = AlarmPreferences.getServerUrl(activity);
url = new URL(serverUrl + path);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (SplashActivity.getAcct() != null)
conn.setRequestProperty("user", SplashActivity.getAcct().getServerAuthCode());
conn.setConnectTimeout(5000); //set timeout to 5 seconds
conn.setAllowUserInteraction(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
try {
BufferedInputStream in = new BufferedInputStream(
conn.getInputStream());
// Convert the stream to a String
// There are various approaches, I'll leave it up to you
contentSize = 1000;//Integer.valueOf(conn.getHeaderField("Length"));//conn.getContentLength();
String json = convertStreamToString(in);
if (requestType == REQUEST_SPOTLIST || requestType == REQUEST_SPOTLIST_FULLINFO) {
List<Spot> list = new ArrayList<Spot>();
JSONObject jObject = new JSONObject(json);
JSONArray jArray = jObject.getJSONArray("spotlist");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject2 = jArray.getJSONObject(i);
Spot spt = new Spot(jObject2);
list.add(spt);
}
String favorites = jObject.getString("favorites");
result.spotList = list;
result.favorites = new ArrayList<Long>();
String[] split = favorites.split(",");
if (split != null) {
for (int i = 0; i < split.length; i++) {
if (!split[i].equals("")) {
long id = Integer.valueOf(split[i]);
if (id != 0)
result.favorites.add(id);
}
}
}
// TODO add favorites list
} else if (requestType == REQUEST_FAVORITESLASTMETEODATA || requestType == REQUEST_LASTMETEODATA) {
List<MeteoStationData> list = new ArrayList<MeteoStationData>();
JSONObject jObject = new JSONObject(json);
JSONArray jArray = jObject.getJSONArray("meteodata");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject2 = jArray.getJSONObject(i);
MeteoStationData md = new MeteoStationData(jObject2);
list.add(md);
}
result.meteoList = list;
} else if (requestType == REQUEST_FAVORITES) {
List<Long> list = new ArrayList<>();
JSONObject jObject = new JSONObject(json);
JSONArray jArray = jObject.getJSONArray("favorites");
for (int i = 0; i < jArray.length(); i++) {
Long id = jArray.getLong(i);
list.add(id);
}
result.favorites = list;
} else if (requestType == REQUEST_FORECAST) {
Forecast forecast = new Forecast(json);
result.forecast = forecast;
} else if (requestType == REQUEST_FORECASTLOCATIONS) {
//Forecast forecast = new Forecast(json);
//result.forecast = forecast;
;
JSONObject jobj = new JSONObject(json);
JSONArray jarray = null;
if (jobj.has("locations")) {
result.locations = new ArrayList<>();
jarray = jobj.getJSONArray("locations");
for (int i = 0; i < jarray.length(); i++) {
JSONObject obj = (JSONObject) jarray.get(i);
Location location = new Location(obj);
result.locations.add(location);
}
}
} else if (requestType == REQUEST_LOGMETEODATA) {
List<MeteoStationData> list = new ArrayList<MeteoStationData>();
JSONObject jObject = new JSONObject(json);
String date = jObject.getString("date");
String speed = jObject.getString("speed");
String avspeed = jObject.getString("avspeed");
String temperature = jObject.getString("temperature");
String direction = jObject.getString("direction");
String trend = jObject.getString("trend");
String id = jObject.getString("id");
String[] dates = date.split(";");
String[] speeds = speed.split(";");
String[] avspeeds = avspeed.split(";");
String[] temperatures = temperature.split(";");
String[] directions = direction.split(";");
String[] trends = trend.split(";");
String[] ids = id.split(";");
for (int i = 0; i < dates.length; i++) {
MeteoStationData md = new MeteoStationData();
if (dates[i] != null) {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss");
try {
md.date = df.parse(dates[i]);
} catch (ParseException e) {
e.printStackTrace();
continue;
}
} else {
continue;
}
if (speeds[i] != null && !speeds[i].equals(""))
md.speed = Double.valueOf(speeds[i]);
else
continue;
if (avspeeds[i] != null && !avspeeds[i].equals(""))
md.averagespeed = Double.valueOf(avspeeds[i]);
else
continue;
if (directions[i] != null && !directions[i].equals(""))
md.directionangle = Double.valueOf(directions[i]);
else
continue;
if (trends[i] != null && !trends[i].equals(""))
md.trend = Double.valueOf(trends[i]);
else
continue;
if (temperatures[i] != null && !temperatures[i].equals(""))
md.temperature = Double.valueOf(temperatures[i]);
else
continue;
if (ids[i] != null && !ids[i].equals(""))
md.id = Long.valueOf(ids[i]);
else
continue;
list.add(md);
}
result.meteoList = list;
}
if (conn != null)
conn.disconnect();
} catch (JSONException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
}
} catch (MalformedURLException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
} catch (java.net.SocketTimeoutException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
} catch (IOException e) {
error = true;
e.printStackTrace();
errorMessage = e.toString();
}
return result;
}
}
protected void onPreExecute() {
//progressBar.setProgress(10);
String message = "attendere prego...";
if (requestType == REQUEST_SPOTLIST)
message = "Richiesta lista spot...";
else if (requestType == REQUEST_SPOTLIST_FULLINFO)
message = "Richiesta lista completa spot...";
//else if (requestType == REQUEST_HISTORYMETEODATA)
//message = "Richiesta dati storici...";
else if (requestType == REQUEST_LASTMETEODATA)
message = "Richiesta dati meteo...";
else if (requestType == REQUEST_FORECAST) {
message = "caricamento ...";
//this.dialog.setMessage(message);
//this.dialog.show();
} else if (requestType == REQUEST_FORECASTLOCATIONS) {
message = "caricamento...";
this.dialog.setMessage(message);
this.dialog.show();
}
//this.dialog.setMessage(message);
//this.dialog.show();
}
@Override
protected void onProgressUpdate(Long... values) {
//progressBar.setProgress(values[0].intValue());
}
protected void onPostExecute(Result result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (requestType == REQUEST_SPOTLIST || requestType == REQUEST_SPOTLIST_FULLINFO) {
delegate.processFinishSpotList(result.spotList, result.favorites, error, errorMessage);
} else if (requestType == REQUEST_LOGMETEODATA) {
List<MeteoStationData> data = new ArrayList<>();
if (result.meteoList != null) {
for (Object obj : result.meteoList) {
data.add(new MeteoStationData((MeteoStationData) obj));
}
}
delegate.processFinishHistory(result.spotId, data, error, errorMessage);
} else if (requestType == REQUEST_LASTMETEODATA || requestType == REQUEST_FAVORITESLASTMETEODATA) {
delegate.processFinish(result.meteoList, error, errorMessage);
} else if (requestType == REQUEST_ADDFAVORITE) {
delegate.processFinishAddFavorite(result.spotId, error, errorMessage);
} else if (requestType == REQUEST_REMOVEFAVORITE) {
delegate.processFinishRemoveFavorite(result.spotId, error, errorMessage);
} else if (requestType == REQUEST_FORECAST) {
delegate.processFinishForecast(requestId, result.forecast, error, errorMessage);
} else if (requestType == REQUEST_FORECASTLOCATIONS) {
delegate.processFinishForecastLocation(result.locations, error, errorMessage);
}
//progressBar.setVisibility(View.GONE);
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
long l = 100 * sb.length() / contentSize;
publishProgress(l);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
| 22,458 | 0.508861 | 0.505566 | 507 | 43.295856 | 25.366413 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.741617 | false | false | 9 |
46adfaa75239118001e7c892964272f88fd2dd00 | 24,610,162,644,840 | 28ecc1111334e801ec8fddef349924b9a561912d | /src/main/java/com/franzoso/mercearia/repository/CategoriaRepository.java | 8ccfbb409fe19eb5144b0d5084991cd66e67a399 | [] | no_license | wevertonfranzoso/mercearia | https://github.com/wevertonfranzoso/mercearia | 2b497bb0c56826bb74bffc10e62b5a29f7547d51 | 9d35971befbcc16f86efcdd4f845c431bd31b88d | refs/heads/main | 2023-08-30T14:39:58.116000 | 2021-11-15T14:53:41 | 2021-11-15T14:53:41 | 428,306,089 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.franzoso.mercearia.repository;
import com.franzoso.mercearia.domain.Categoria;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CategoriaRepository extends JpaRepository<Categoria,Integer> {
}
| UTF-8 | Java | 237 | java | CategoriaRepository.java | Java | [] | null | [] | package com.franzoso.mercearia.repository;
import com.franzoso.mercearia.domain.Categoria;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CategoriaRepository extends JpaRepository<Categoria,Integer> {
}
| 237 | 0.852321 | 0.852321 | 7 | 32.857143 | 30.187172 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 9 |
f1d24bc470e558ecd38687d606294eb1c7d302d1 | 26,886,495,276,343 | 706e750ca970f907ea4b22d3f9d2b85bd92bceed | /src/sample/Main.java | e5ef235f20023dbaf5a1f37b054672f3d509d1c3 | [] | no_license | warriorWorld/MangaReaderFX | https://github.com/warriorWorld/MangaReaderFX | 41d497398867273178f2cf7db95c581de738181f | 14889f468ec36973711b6956dfe2a63ccb2b6b22 | refs/heads/master | 2020-04-21T01:34:09.705000 | 2020-03-11T07:08:17 | 2020-03-11T07:08:17 | 169,228,035 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sample;
import java.io.IOException;
import base.BaseController;
import bean.DownloadBean;
import configure.BaseParameterUtil;
import configure.Configure;
import download.DownloadMangaManager;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import read.ReadController;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
initAllInstance();
// Parent root = FXMLLoader.load(getClass().getResource("read\\read.fxml"));
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
Parent root = fxmlLoader.load();
//如果使用 Parent root = FXMLLoader.load(...) 静态读取方法,无法获取到Controller的实例对象
BaseController controller = fxmlLoader.getController(); //获取Controller的实例对象
Scene scene = new Scene(root, 800, 500);
primaryStage.setTitle(Configure.NAME);
primaryStage.setMaximized(true);
primaryStage.setScene(scene);
primaryStage.show();
controller.setStage(primaryStage);
controller.setScene(scene);
}
private void initAllInstance() {
DownloadMangaManager.getInstance().getCurrentChapter();
DownloadBean.getInstance().setDownloadInfo(DownloadBean.getInstance().getDownloadInfo());
BaseParameterUtil.getInstance();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| UTF-8 | Java | 1,637 | java | Main.java | Java | [] | null | [] | package sample;
import java.io.IOException;
import base.BaseController;
import bean.DownloadBean;
import configure.BaseParameterUtil;
import configure.Configure;
import download.DownloadMangaManager;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import read.ReadController;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws IOException {
initAllInstance();
// Parent root = FXMLLoader.load(getClass().getResource("read\\read.fxml"));
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
Parent root = fxmlLoader.load();
//如果使用 Parent root = FXMLLoader.load(...) 静态读取方法,无法获取到Controller的实例对象
BaseController controller = fxmlLoader.getController(); //获取Controller的实例对象
Scene scene = new Scene(root, 800, 500);
primaryStage.setTitle(Configure.NAME);
primaryStage.setMaximized(true);
primaryStage.setScene(scene);
primaryStage.show();
controller.setStage(primaryStage);
controller.setScene(scene);
}
private void initAllInstance() {
DownloadMangaManager.getInstance().getCurrentChapter();
DownloadBean.getInstance().setDownloadInfo(DownloadBean.getInstance().getDownloadInfo());
BaseParameterUtil.getInstance();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| 1,637 | 0.709677 | 0.705882 | 49 | 31.265306 | 24.955286 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.632653 | false | false | 9 |
6c56d2ef7db6226f9b1f51326528866f741d76c7 | 10,307,921,516,845 | 89f2055defe9430c8ecfcf551d64980b0a0d2eac | /src/com/hitchhikers/spacetrader/controllers/SpacePortController.java | 7af374d376aa5bdfdf18d5ec6c0659f6da5c4975 | [] | no_license | jv776/cs2340-SpaceTrader | https://github.com/jv776/cs2340-SpaceTrader | 4b98b144808ca68eef95a66a305a40e4a77b448d | f908bd233918a3b145b630b70b3601b252c13b91 | refs/heads/master | 2020-05-17T20:33:37.689000 | 2015-09-14T05:53:46 | 2015-09-14T05:53:46 | 42,428,025 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hitchhikers.spacetrader.controllers;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.scene.control.ProgressBar;
import com.hitchhikers.spacetrader.models.Player;
/**
* @author Roi Atalla
*/
public class SpacePortController implements Initializable {
@FXML
private Button btn_Market;
@FXML
private Button button_Refuel, button_Repair;
@FXML
private Button btn_ShipYard;
@FXML
private Button btn_Map;
@FXML
private Button btn_News;
@FXML
private Button btn_StockMarket;
@FXML
private ProgressBar health_bar, fuel_bar;
@FXML
private Label spacePortLabel;
@FXML private Label solar_system;
@FXML private Label planet;
@FXML private Label tech_level;
@FXML private Label resource;
private Player player;
public void onMarketClicked() {
GameController.getControl().setScreen(Screens.MARKET);
}
public void onShipYardClicked() {
GameController.getControl().setScreen(Screens.SHIP_YARD);
}
public void onMapClicked() {
GameController.getControl().setScreen(Screens.SOLAR_SYSTEM_MAP);
}
public void onNewsClicked() {
System.out.println("NEWS CLICKED WOOOOO!");
}
public void onStockMarketClicked() {
System.out.println("STOCK MARKET CLICKED WOOOO!");
}
@FXML
void handleRefuelButton() {
player.spend((int) (Math.ceil(player.getShip().getFuelCapacity()
- player.getShip().getFuelAmount()) * player.getShip().getFuelCost()));
player.getShip().refuel();
fuel_bar.setProgress(1.0);
button_Refuel.setDisable(true);
}
@FXML
void handleRepairButton() {
player.spend((int)((player.getShip().getMaxHullStrength()
- player.getShip().getHullStrength()) * player.getShip().getRepairCost()));
player.getShip().repair();
health_bar.setProgress(1.0);
button_Repair.setDisable(true);
}
@FXML
private void shipCustomization() {
GameController.getControl().setScreen(Screens.SHIP_CUSTOMIZATION);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
player = GameController.getGameData().getPlayer();
spacePortLabel.setText("Space Port: " + GameController.getGameData().getPlanet().getName());
btn_Map.setText("Return to " + GameController.getGameData().getSolarSystem().getName());
if (GameController.getGameData().getSolarSystem().getTechLevel().ordinal() < 4) {
btn_ShipYard.setDisable(true);
}
if (GameController.getGameData().getShip().getFuelCapacity()
== GameController.getGameData().getShip().getFuelAmount()) {
button_Refuel.setDisable(true);
}
if (GameController.getGameData().getShip().getHullStrength()
== GameController.getGameData().getShip().getMaxHullStrength()) {
button_Repair.setDisable(true);
}
solar_system.setText(GameController.getGameData().getSolarSystem().getName());
planet.setText(GameController.getGameData().getPlanet().getName());
tech_level.setText(GameController.getGameData().getSolarSystem()
.getTechLevel().toString());
resource.setText(GameController.getGameData().getPlanet()
.getResource().toString());
fuel_bar.setProgress(GameController.getGameData().getShip().getFuelAmount()
/ (double)GameController.getGameData().getShip().getFuelCapacity());
health_bar.setProgress(GameController.getGameData().getShip().getHullStrength()
/ (double)GameController.getGameData().getShip().getMaxHullStrength());
}
}
| UTF-8 | Java | 3,999 | java | SpacePortController.java | Java | [
{
"context": "hhikers.spacetrader.models.Player;\n\n/**\n * @author Roi Atalla\n */\npublic class SpacePortController implements I",
"end": 352,
"score": 0.9998109936714172,
"start": 342,
"tag": "NAME",
"value": "Roi Atalla"
}
] | null | [] | package com.hitchhikers.spacetrader.controllers;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.scene.control.ProgressBar;
import com.hitchhikers.spacetrader.models.Player;
/**
* @author <NAME>
*/
public class SpacePortController implements Initializable {
@FXML
private Button btn_Market;
@FXML
private Button button_Refuel, button_Repair;
@FXML
private Button btn_ShipYard;
@FXML
private Button btn_Map;
@FXML
private Button btn_News;
@FXML
private Button btn_StockMarket;
@FXML
private ProgressBar health_bar, fuel_bar;
@FXML
private Label spacePortLabel;
@FXML private Label solar_system;
@FXML private Label planet;
@FXML private Label tech_level;
@FXML private Label resource;
private Player player;
public void onMarketClicked() {
GameController.getControl().setScreen(Screens.MARKET);
}
public void onShipYardClicked() {
GameController.getControl().setScreen(Screens.SHIP_YARD);
}
public void onMapClicked() {
GameController.getControl().setScreen(Screens.SOLAR_SYSTEM_MAP);
}
public void onNewsClicked() {
System.out.println("NEWS CLICKED WOOOOO!");
}
public void onStockMarketClicked() {
System.out.println("STOCK MARKET CLICKED WOOOO!");
}
@FXML
void handleRefuelButton() {
player.spend((int) (Math.ceil(player.getShip().getFuelCapacity()
- player.getShip().getFuelAmount()) * player.getShip().getFuelCost()));
player.getShip().refuel();
fuel_bar.setProgress(1.0);
button_Refuel.setDisable(true);
}
@FXML
void handleRepairButton() {
player.spend((int)((player.getShip().getMaxHullStrength()
- player.getShip().getHullStrength()) * player.getShip().getRepairCost()));
player.getShip().repair();
health_bar.setProgress(1.0);
button_Repair.setDisable(true);
}
@FXML
private void shipCustomization() {
GameController.getControl().setScreen(Screens.SHIP_CUSTOMIZATION);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
player = GameController.getGameData().getPlayer();
spacePortLabel.setText("Space Port: " + GameController.getGameData().getPlanet().getName());
btn_Map.setText("Return to " + GameController.getGameData().getSolarSystem().getName());
if (GameController.getGameData().getSolarSystem().getTechLevel().ordinal() < 4) {
btn_ShipYard.setDisable(true);
}
if (GameController.getGameData().getShip().getFuelCapacity()
== GameController.getGameData().getShip().getFuelAmount()) {
button_Refuel.setDisable(true);
}
if (GameController.getGameData().getShip().getHullStrength()
== GameController.getGameData().getShip().getMaxHullStrength()) {
button_Repair.setDisable(true);
}
solar_system.setText(GameController.getGameData().getSolarSystem().getName());
planet.setText(GameController.getGameData().getPlanet().getName());
tech_level.setText(GameController.getGameData().getSolarSystem()
.getTechLevel().toString());
resource.setText(GameController.getGameData().getPlanet()
.getResource().toString());
fuel_bar.setProgress(GameController.getGameData().getShip().getFuelAmount()
/ (double)GameController.getGameData().getShip().getFuelCapacity());
health_bar.setProgress(GameController.getGameData().getShip().getHullStrength()
/ (double)GameController.getGameData().getShip().getMaxHullStrength());
}
}
| 3,995 | 0.647412 | 0.646162 | 124 | 31.25 | 27.779554 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.41129 | false | false | 9 |
c9714c12a5c8d74bf449320d0926e029d402f7ac | 2,800,318,714,434 | 47af5a0144fabcdda14d34e122407fd82dd9e0bd | /lsp/src/main/java/at/jku/isse/ecco/lsp/services/Settings.java | 4caae2e0a4b87b8e8895fb45f53ac77df24dd6ba | [] | no_license | llinsbauer/ecco | https://github.com/llinsbauer/ecco | 64ed52e1236bfe5c3f5dfae8713844f09898a5b3 | 3d6aaa2db9673dfec75ef2c716b4c5f3f2ddf030 | refs/heads/main | 2023-06-22T12:44:33.627000 | 2023-06-16T12:28:45 | 2023-06-16T12:28:45 | 256,838,285 | 4 | 3 | null | true | 2023-06-09T19:05:44 | 2020-04-18T19:40:41 | 2022-05-01T13:46:57 | 2023-06-09T19:05:43 | 44,862 | 2 | 4 | 0 | Java | false | false | package at.jku.isse.ecco.lsp.services;
public class Settings {
private boolean ignoreColumnsForColoring;
public Settings() {
this.ignoreColumnsForColoring = false;
}
public boolean getIgnoreColumnsForColoring() {
return this.ignoreColumnsForColoring;
}
public void setIgnoreColumnsForColoring(boolean value) {
this.ignoreColumnsForColoring = value;
}
@Override
public String toString() {
return "{ignoreColumnsForColoring=" + this.ignoreColumnsForColoring + "}";
}
}
| UTF-8 | Java | 544 | java | Settings.java | Java | [] | null | [] | package at.jku.isse.ecco.lsp.services;
public class Settings {
private boolean ignoreColumnsForColoring;
public Settings() {
this.ignoreColumnsForColoring = false;
}
public boolean getIgnoreColumnsForColoring() {
return this.ignoreColumnsForColoring;
}
public void setIgnoreColumnsForColoring(boolean value) {
this.ignoreColumnsForColoring = value;
}
@Override
public String toString() {
return "{ignoreColumnsForColoring=" + this.ignoreColumnsForColoring + "}";
}
}
| 544 | 0.693015 | 0.693015 | 22 | 23.727272 | 23.733715 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 9 |
bfa955a0dbf999616fa7b7f3c5c93cea7b3583f9 | 7,894,149,915,489 | ba4dba48c1e8b231024de8de0b33bbae37754553 | /Warehouse/src/main/java/io/github/srhojo/fenix/ms/warehouse/domain/mappers/QuantityMapper.java | 07079333adddff2a0ef921a20294fb84afc6327a | [
"Apache-2.0"
] | permissive | srhojo/Fenix-Microservices | https://github.com/srhojo/Fenix-Microservices | befd27f66dc6a157c6c5a993fa591af6dd1a2cb1 | e21450927b11fde5e073df585ce91df6edd4ec0e | refs/heads/master | 2022-07-07T23:08:07.731000 | 2019-07-28T19:32:45 | 2019-07-28T19:32:45 | 198,792,169 | 0 | 0 | Apache-2.0 | false | 2022-06-21T01:32:39 | 2019-07-25T08:39:02 | 2019-07-28T19:32:51 | 2022-06-21T01:32:35 | 59 | 0 | 0 | 1 | Java | false | false | package io.github.srhojo.fenix.ms.warehouse.domain.mappers;
import org.springframework.stereotype.Component;
import io.github.srhojo.fenix.ms.warehouse.domain.entities.QuantityEmbeddableEntity;
import io.github.srhojo.utils.cdm.Quantity;
import io.github.srhojo.utils.commons.mappers.InnerMapper;
@Component
public class QuantityMapper implements InnerMapper<QuantityEmbeddableEntity, Quantity> {
@Override
public QuantityEmbeddableEntity mapToInner(final Quantity outer) {
final QuantityEmbeddableEntity inner = new QuantityEmbeddableEntity();
inner.setUnities(outer.getUnities());
inner.setValue(outer.getValue());
return inner;
}
}
| UTF-8 | Java | 683 | java | QuantityMapper.java | Java | [
{
"context": "package io.github.srhojo.fenix.ms.warehouse.domain.mappers;\n\nimport org.sp",
"end": 24,
"score": 0.8031085729598999,
"start": 20,
"tag": "USERNAME",
"value": "hojo"
},
{
"context": "framework.stereotype.Component;\n\nimport io.github.srhojo.fenix.ms.warehouse.domain.e... | null | [] | package io.github.srhojo.fenix.ms.warehouse.domain.mappers;
import org.springframework.stereotype.Component;
import io.github.srhojo.fenix.ms.warehouse.domain.entities.QuantityEmbeddableEntity;
import io.github.srhojo.utils.cdm.Quantity;
import io.github.srhojo.utils.commons.mappers.InnerMapper;
@Component
public class QuantityMapper implements InnerMapper<QuantityEmbeddableEntity, Quantity> {
@Override
public QuantityEmbeddableEntity mapToInner(final Quantity outer) {
final QuantityEmbeddableEntity inner = new QuantityEmbeddableEntity();
inner.setUnities(outer.getUnities());
inner.setValue(outer.getValue());
return inner;
}
}
| 683 | 0.781845 | 0.781845 | 19 | 34.947369 | 30.795546 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 9 |
be5640d172a50c14990a2f2a9c7a768100b5f3b7 | 31,353,261,282,723 | 9d196208675db7b9f8cc76dd49758ac062f5f09d | /harvester/src/main/java/com/indexdata/masterkey/localindices/oaipmh/server/handler/implement/mockup/CommonOaiPmhHandler.java | acda487a7ca2c5717b48d189db6ef671e0c2baad | [
"Apache-2.0"
] | permissive | indexdata/localindices | https://github.com/indexdata/localindices | 3c644d2238861c618b303932d6c5474969da771b | cbd27e5af34f59cfd410a76b375e474bdab47da8 | refs/heads/master | 2023-08-17T23:38:33.479000 | 2023-08-11T13:23:28 | 2023-08-11T13:23:28 | 205,176,086 | 0 | 0 | Apache-2.0 | false | 2023-08-11T12:57:29 | 2019-08-29T13:57:26 | 2021-11-09T16:33:47 | 2023-08-11T12:57:28 | 104,857 | 0 | 1 | 1 | Java | false | false | package com.indexdata.masterkey.localindices.oaipmh.server.handler.implement.mockup;
import com.indexdata.masterkey.localindices.oaipmh.server.handler.OaiPmhHandler;
import com.indexdata.masterkey.localindices.oaipmh.server.handler.OaiPmhRequest;
public abstract class CommonOaiPmhHandler implements OaiPmhHandler {
public CommonOaiPmhHandler() {
}
public void verifyParameters(OaiPmhRequest request, String[][] parameters) {
/*
if (request.getParameter("resumptionToken") != null && request.getParameter("verb") != null) {
return ;
}
*/
RuntimeException missingParameter = null;
for (String[] oneOption: parameters) {
missingParameter = null;
for (String parameter : oneOption)
if (request.getParameter(parameter) == null)
missingParameter = new RuntimeException("Required parameter '" + parameter + "' missing");
// Had all parameters in this one.
if (missingParameter == null)
return ;
}
// Order of parameter is important. Last one will determine the error message.
if (missingParameter != null)
throw missingParameter;
}
protected String getElement(OaiPmhRequest request) {
String verb = request.getParameter("verb");
String element = "<" + verb + ">";
return element;
}
protected String getElementEnd(OaiPmhRequest request) {
String verb = request.getParameter("verb");
String element = "</" + verb + ">";
return element;
}
}
| UTF-8 | Java | 1,492 | java | CommonOaiPmhHandler.java | Java | [] | null | [] | package com.indexdata.masterkey.localindices.oaipmh.server.handler.implement.mockup;
import com.indexdata.masterkey.localindices.oaipmh.server.handler.OaiPmhHandler;
import com.indexdata.masterkey.localindices.oaipmh.server.handler.OaiPmhRequest;
public abstract class CommonOaiPmhHandler implements OaiPmhHandler {
public CommonOaiPmhHandler() {
}
public void verifyParameters(OaiPmhRequest request, String[][] parameters) {
/*
if (request.getParameter("resumptionToken") != null && request.getParameter("verb") != null) {
return ;
}
*/
RuntimeException missingParameter = null;
for (String[] oneOption: parameters) {
missingParameter = null;
for (String parameter : oneOption)
if (request.getParameter(parameter) == null)
missingParameter = new RuntimeException("Required parameter '" + parameter + "' missing");
// Had all parameters in this one.
if (missingParameter == null)
return ;
}
// Order of parameter is important. Last one will determine the error message.
if (missingParameter != null)
throw missingParameter;
}
protected String getElement(OaiPmhRequest request) {
String verb = request.getParameter("verb");
String element = "<" + verb + ">";
return element;
}
protected String getElementEnd(OaiPmhRequest request) {
String verb = request.getParameter("verb");
String element = "</" + verb + ">";
return element;
}
}
| 1,492 | 0.688338 | 0.688338 | 45 | 32.155556 | 30.102755 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.355556 | false | false | 9 |
4806d483e4a47e44ece3552f90136c9142b64cf4 | 6,794,638,273,853 | df6e23757543682e3c4d79be1a98fcc5e9dde524 | /src/CloudTest.java | d4a33e2ff85327f7da4e1e87df88c75fc4547b14 | [] | no_license | shimjinyoung/cloudTest1 | https://github.com/shimjinyoung/cloudTest1 | d0d057a79ce614b73f29ea2500268b9af7aabeb6 | 04c9ae91eca5714aa3e7af94500de45a62a69ac4 | refs/heads/master | 2023-06-23T12:10:35.152000 | 2021-07-27T14:40:07 | 2021-07-27T14:40:07 | 389,921,979 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class CloudTest {
public static void main(String args) {
System.out.println("dddd");
System.out.println("dddd");
}
}
| UTF-8 | Java | 131 | java | CloudTest.java | Java | [] | null | [] |
public class CloudTest {
public static void main(String args) {
System.out.println("dddd");
System.out.println("dddd");
}
}
| 131 | 0.687023 | 0.687023 | 6 | 20.666666 | 14.26729 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false | 9 |
c02b13eab4d645baab10ce678a7f211218eaef4d | 21,723,944,614,784 | b4bef45a48d6cf725435a043e964612f45c86c8e | /app/src/main/java/com/example/rnotes/async/DeleteAsyncTask.java | aca018001c4a47d1e53f3321c05923dddd3503aa | [] | no_license | russabit/songsAsNotes | https://github.com/russabit/songsAsNotes | 7d89a198334c88b9e532762f8cbf8faf59747c41 | 6a869862e36e85434f21b760c162e12a242dea89 | refs/heads/master | 2021-01-02T01:24:33.412000 | 2020-02-10T05:02:09 | 2020-02-10T05:02:09 | 239,431,454 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.rnotes.async;
import android.os.AsyncTask;
import com.example.rnotes.models.Note;
import com.example.rnotes.persistence.NoteDao;
public class DeleteAsyncTask extends AsyncTask<Note, Void, Void> {
private NoteDao rNoteDao;
public DeleteAsyncTask(NoteDao noteDao) {
rNoteDao = noteDao;
}
@Override
protected Void doInBackground(Note... notes) {
rNoteDao.delete(notes);
return null;
}
}
| UTF-8 | Java | 459 | java | DeleteAsyncTask.java | Java | [] | null | [] | package com.example.rnotes.async;
import android.os.AsyncTask;
import com.example.rnotes.models.Note;
import com.example.rnotes.persistence.NoteDao;
public class DeleteAsyncTask extends AsyncTask<Note, Void, Void> {
private NoteDao rNoteDao;
public DeleteAsyncTask(NoteDao noteDao) {
rNoteDao = noteDao;
}
@Override
protected Void doInBackground(Note... notes) {
rNoteDao.delete(notes);
return null;
}
}
| 459 | 0.703704 | 0.703704 | 22 | 19.863636 | 19.982483 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 9 |
1e850d5d34e9ba6d48fc13a16b60e929d0ea9392 | 21,569,325,785,323 | 7e426a2814f74c45a1ef324739d80d2e45d2fc7e | /src/main/java/Entity/BookStatus.java | c3a2ed0ae562a1a8dc578c7a218e2cd9d951f461 | [] | no_license | traidat/Library | https://github.com/traidat/Library | 16d18abb18596acbf7db80b03f0a8f6810308daf | be305ee4a8c91b19337cd4ecdfafef883362b9c7 | refs/heads/master | 2022-12-06T04:20:59.650000 | 2020-08-27T08:10:25 | 2020-08-27T08:10:25 | 287,889,896 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Entity;
public class BookStatus {
public enum Status {
Available,
NotAvailable,
Lended,
Returned,
}
}
| UTF-8 | Java | 151 | java | BookStatus.java | Java | [] | null | [] | package Entity;
public class BookStatus {
public enum Status {
Available,
NotAvailable,
Lended,
Returned,
}
}
| 151 | 0.562914 | 0.562914 | 10 | 14.1 | 8.619164 | 25 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
2db2a68ac65077bec8518c56d544438b6e25f6f2 | 8,332,236,612,104 | 7d4b51d0bfc750d1c71d80b2b8619ad53bc433e6 | /src/main/java/com/zsw/practise/gp/factory/db_pool/ConnectionPoolTest.java | 96e9bcf68cc226bec376c58cc89a8760d5a5a00e | [] | no_license | zhengshaowei/design-pattern | https://github.com/zhengshaowei/design-pattern | 7f3bfbab55eaeb9cdbd50885e5ba72f3236318b8 | 825144a8bd35baae48b011ceb5f47280456b1440 | refs/heads/master | 2020-04-27T13:07:28.945000 | 2019-03-09T10:56:38 | 2019-03-09T10:56:38 | 174,356,789 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zsw.practise.gp.factory.db_pool;
import org.junit.Test;
import java.sql.Connection;
/**
* @author zheng.shaowei
* @create 2019-03-09 14:27
**/
public class ConnectionPoolTest {
//TODO 继续完成测试
@Test
public void getPoolTest(){
DBConnectionPool connectionPool = DBConnectionPool.getInstance();
System.out.println(connectionPool);
}
@Test
public void getConnectionTest(){
DBConnectionPool connectionPool = DBConnectionPool.getInstance();
Connection connection = connectionPool.getConnection();
System.out.println(connection);
}
}
| UTF-8 | Java | 625 | java | ConnectionPoolTest.java | Java | [
{
"context": "Test;\n\nimport java.sql.Connection;\n\n/**\n * @author zheng.shaowei\n * @create 2019-03-09 14:27\n **/\npublic class Con",
"end": 127,
"score": 0.9993345737457275,
"start": 114,
"tag": "NAME",
"value": "zheng.shaowei"
}
] | null | [] | package com.zsw.practise.gp.factory.db_pool;
import org.junit.Test;
import java.sql.Connection;
/**
* @author zheng.shaowei
* @create 2019-03-09 14:27
**/
public class ConnectionPoolTest {
//TODO 继续完成测试
@Test
public void getPoolTest(){
DBConnectionPool connectionPool = DBConnectionPool.getInstance();
System.out.println(connectionPool);
}
@Test
public void getConnectionTest(){
DBConnectionPool connectionPool = DBConnectionPool.getInstance();
Connection connection = connectionPool.getConnection();
System.out.println(connection);
}
}
| 625 | 0.693312 | 0.673736 | 26 | 22.576923 | 22.369576 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 9 |
49687709fe83b0b778c7a8e8f611b347efbbc849 | 14,156,212,210,482 | 06d0015ab48be6935721e89507f56965612fc90b | /src/jsm/rtx2/phys/Texture.java | 1fb68eddcb4105cb570d0074f07d8e350e6ced88 | [] | no_license | NotJackIsMercury/RayTracingAttempt | https://github.com/NotJackIsMercury/RayTracingAttempt | d62879bce55d66e247f5500743d155017466a209 | c460c6057f0287a90f4227d8de85b1367e42b781 | refs/heads/main | 2023-01-22T15:38:54.845000 | 2020-11-30T06:59:22 | 2020-11-30T06:59:22 | 317,096,831 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jsm.rtx2.phys;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Texture {
public static final int SIZE = 64;
public static final Texture WALL2 = new Texture("res/wall2.png", SIZE);
public int[] pixels;
private String loc;
public final int size;
public Texture(String location, int s) {
loc = location;
size = s;
pixels = new int[size * size];
load();
}
private void load() {
try {
BufferedImage image = ImageIO.read(new File(loc));
int w = image.getWidth();
int h = image.getHeight();
//image = (BufferedImage) image.getScaledInstance(SIZE, SIZE, Image.SCALE_SMOOTH);
image.getRGB(0, 0, w, h, pixels, 0, w);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 863 | java | Texture.java | Java | [] | null | [] | package jsm.rtx2.phys;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Texture {
public static final int SIZE = 64;
public static final Texture WALL2 = new Texture("res/wall2.png", SIZE);
public int[] pixels;
private String loc;
public final int size;
public Texture(String location, int s) {
loc = location;
size = s;
pixels = new int[size * size];
load();
}
private void load() {
try {
BufferedImage image = ImageIO.read(new File(loc));
int w = image.getWidth();
int h = image.getHeight();
//image = (BufferedImage) image.getScaledInstance(SIZE, SIZE, Image.SCALE_SMOOTH);
image.getRGB(0, 0, w, h, pixels, 0, w);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 863 | 0.650058 | 0.640788 | 40 | 19.575001 | 19.747009 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.8 | false | false | 9 |
1c87b16ea8fa89e9c030fba51f4d702c0b9ed992 | 25,752,623,969,833 | 7dd9c1626ea7df528c31b5c5792efa1b4f4c061b | /src/com/company/Pokemon/EvolutionData.java | e2410a1a4b5c071573af2a027af8edef89f20af3 | [] | no_license | BDeshiDev/PokeProject | https://github.com/BDeshiDev/PokeProject | fcfdf25259cad53a8fc0c0161c4990255915daa8 | 2673df74280093193ca06de44fa584af3ed1c6f5 | refs/heads/master | 2023-03-15T20:33:51.311000 | 2019-02-13T04:01:24 | 2019-02-13T04:01:24 | 162,118,342 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company.Pokemon;
import com.company.Pokemon.Stats.Level;
public class EvolutionData {
public final String monToEvolveTo;
public final int lvRequirement;
public EvolutionData(){
this(null,999);//the level is pointless here
}
public EvolutionData(String monToEvolveTo, int lvRequirement) {
this.monToEvolveTo = monToEvolveTo;
this.lvRequirement = lvRequirement;
}
// to make it more clear that a pokemon can;t evolve further if this is used
public static final EvolutionData finalEvo = new EvolutionData(null,999);
boolean canEvolve(Level levelToCheck){
return monToEvolveTo != null && levelToCheck.getCurLevel() >= lvRequirement ;
}
}
| UTF-8 | Java | 722 | java | EvolutionData.java | Java | [] | null | [] | package com.company.Pokemon;
import com.company.Pokemon.Stats.Level;
public class EvolutionData {
public final String monToEvolveTo;
public final int lvRequirement;
public EvolutionData(){
this(null,999);//the level is pointless here
}
public EvolutionData(String monToEvolveTo, int lvRequirement) {
this.monToEvolveTo = monToEvolveTo;
this.lvRequirement = lvRequirement;
}
// to make it more clear that a pokemon can;t evolve further if this is used
public static final EvolutionData finalEvo = new EvolutionData(null,999);
boolean canEvolve(Level levelToCheck){
return monToEvolveTo != null && levelToCheck.getCurLevel() >= lvRequirement ;
}
}
| 722 | 0.714681 | 0.706371 | 22 | 31.818182 | 27.385525 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.590909 | false | false | 9 |
101d2be60065739aa980e3272769efb74e2f6f03 | 28,939,489,665,252 | 4096da7a5c9d84261b799f3510d26811b50e5b29 | /src/java/com/controller/ComplaintAction.java | b4b74353c9f43d35692232ab65406bcc66c136ad | [] | no_license | ninhnv/Project-Specification-Elevation-System | https://github.com/ninhnv/Project-Specification-Elevation-System | 3550c32273b4e3be3bf188d92cd6be50547e7b6a | aa88f3194a14dd71dbb221bee4428bb50d9d74cf | refs/heads/master | 2021-01-17T05:39:09.575000 | 2015-01-13T07:40:59 | 2015-01-13T07:40:59 | 29,178,443 | 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.controller;
import com.beans.TblComplaint;
import com.beans.TblOrder;
import com.beans.TblPerson;
import com.model.ComplaintModel;
import com.model.OrderModel;
import com.model.PersonModel;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author ADMIN
*/
@WebServlet(name = "ComplaintAction", urlPatterns = {"/ComplaintAction"})
public class ComplaintAction extends HttpServlet {
ComplaintModel compModel = null;
HttpSession session = null;
/**
* 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();
compModel = ComplaintModel.getInstance();
try {
if (request.getParameter("read") != null) {
processReadComplaint(request, response);
} else if (request.getParameter("del") != null) {
processDeleteComplaint(request, response);
} else if (request.getParameter("btnSearch") != null) {
processSearchComplaint(request, response);
} else if (request.getParameter("btnSendComplaint") != null) {
processSendComplaint(request, response);
}
} 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>
private void processReadComplaint(HttpServletRequest request, HttpServletResponse response) {
String id = request.getParameter("key");
int objID = Integer.parseInt(id);
TblComplaint comp = compModel.getComplaintByID(objID);
comp.setCreadComp(1);
session = request.getSession();
try {
if (compModel.updateObject(comp)) {
session.setAttribute("message", "CheckComplaintSuccess");
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage");
} else {
session.setAttribute("message", "CheckComplaintFail");
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage");
}
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
}
private void processDeleteComplaint(HttpServletRequest request, HttpServletResponse response) {
String id = request.getParameter("key");
int objID = Integer.parseInt(id);
TblComplaint comp = compModel.getComplaintByID(objID);
try {
if (comp.getCreadComp() == 1) {
if (compModel.deleteObject(objID)) {
session.setAttribute("message", "DeleteComplaintSuccess");
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage");
} else {
session.setAttribute("message", "DeleteComplaintFail");
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage");
}
} else {
session.setAttribute("message", "DeleteComplaintFail");
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage");
}
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
}
private void processSearchComplaint(HttpServletRequest request, HttpServletResponse response) throws IOException {
String txtTitle = request.getParameter("txtTitle");
String txtContent = request.getParameter("txtContent");
String txtDate = request.getParameter("txtDate");
String txtProjectName = request.getParameter("txtProjectName");
String txtCustomer = request.getParameter("txtCustomer");
String txtCheck = request.getParameter("txtCheck");
String selectStatus = request.getParameter("selectStatus");
String sqlQuery = "";
if (txtTitle != null) {
sqlQuery += " and cTitle like '%" + txtTitle + "%'";
}
if (txtContent != null) {
sqlQuery += " and cContent like '%" + txtContent + "%'";
}
if (txtDate != null) {
sqlQuery += " and cDate like '%" + txtDate + "%'";
}
if (txtProjectName != null) {
TblOrder ord = OrderModel.getInstance().getOrderByName(txtProjectName);
if (ord != null) {
sqlQuery += " and oID = " + ord.getOid();
}
}
if (txtCustomer != null) {
TblPerson per = PersonModel.getInstance().getPersonByName(txtCustomer);
if (per != null) {
sqlQuery += " and pID = " + per.getPid();
}
}
if (Integer.parseInt(txtCheck) != 2) {
sqlQuery += " and cReadComp = " + txtCheck;
}
if (Integer.parseInt(selectStatus) != 2) {
sqlQuery += " and cStatus = " + selectStatus;
}
session = request.getSession();
session.setAttribute("searchComplaint", sqlQuery);
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage&aID=" + session.getAttribute("adminID") + "&search=true");
}
private void processSendComplaint(HttpServletRequest request, HttpServletResponse response) throws IOException {
String pID = request.getParameter("pID");
String oID = request.getParameter("oID");
String txtTitle = request.getParameter("txtTitle");
String txtContent = request.getParameter("txtContent");
TblComplaint complaint = new TblComplaint();
complaint.setCtitle(txtTitle);
complaint.setCcontent(txtContent);
TblPerson per = PersonModel.getInstance().getPersonByID(Integer.parseInt(pID));
complaint.setTblPerson(per);
TblOrder ord = OrderModel.getInstance().getOrderByID(Integer.parseInt(oID));
complaint.setTblOrder(ord);
Date date = new Date();
complaint.setCdate(date);
complaint.setCreadComp(0);
complaint.setCstatus(Byte.parseByte("0"));
session = request.getSession();
if(compModel.insertObject(complaint)){
session.setAttribute("messComplaint", "SendComplaintSuccess");
response.sendRedirect("?nav=customer");
}else{
session.setAttribute("messComplaint", "SendComplaintFail");
response.sendRedirect("?nav=customer");
}
}
}
| UTF-8 | Java | 8,395 | java | ComplaintAction.java | Java | [
{
"context": "javax.servlet.http.HttpSession;\n\n/**\n *\n * @author ADMIN\n */\n@WebServlet(name = \"ComplaintAction\", urlPatt",
"end": 660,
"score": 0.9911934733390808,
"start": 655,
"tag": "USERNAME",
"value": "ADMIN"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.controller;
import com.beans.TblComplaint;
import com.beans.TblOrder;
import com.beans.TblPerson;
import com.model.ComplaintModel;
import com.model.OrderModel;
import com.model.PersonModel;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author ADMIN
*/
@WebServlet(name = "ComplaintAction", urlPatterns = {"/ComplaintAction"})
public class ComplaintAction extends HttpServlet {
ComplaintModel compModel = null;
HttpSession session = null;
/**
* 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();
compModel = ComplaintModel.getInstance();
try {
if (request.getParameter("read") != null) {
processReadComplaint(request, response);
} else if (request.getParameter("del") != null) {
processDeleteComplaint(request, response);
} else if (request.getParameter("btnSearch") != null) {
processSearchComplaint(request, response);
} else if (request.getParameter("btnSendComplaint") != null) {
processSendComplaint(request, response);
}
} 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>
private void processReadComplaint(HttpServletRequest request, HttpServletResponse response) {
String id = request.getParameter("key");
int objID = Integer.parseInt(id);
TblComplaint comp = compModel.getComplaintByID(objID);
comp.setCreadComp(1);
session = request.getSession();
try {
if (compModel.updateObject(comp)) {
session.setAttribute("message", "CheckComplaintSuccess");
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage");
} else {
session.setAttribute("message", "CheckComplaintFail");
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage");
}
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
}
private void processDeleteComplaint(HttpServletRequest request, HttpServletResponse response) {
String id = request.getParameter("key");
int objID = Integer.parseInt(id);
TblComplaint comp = compModel.getComplaintByID(objID);
try {
if (comp.getCreadComp() == 1) {
if (compModel.deleteObject(objID)) {
session.setAttribute("message", "DeleteComplaintSuccess");
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage");
} else {
session.setAttribute("message", "DeleteComplaintFail");
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage");
}
} else {
session.setAttribute("message", "DeleteComplaintFail");
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage");
}
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
}
private void processSearchComplaint(HttpServletRequest request, HttpServletResponse response) throws IOException {
String txtTitle = request.getParameter("txtTitle");
String txtContent = request.getParameter("txtContent");
String txtDate = request.getParameter("txtDate");
String txtProjectName = request.getParameter("txtProjectName");
String txtCustomer = request.getParameter("txtCustomer");
String txtCheck = request.getParameter("txtCheck");
String selectStatus = request.getParameter("selectStatus");
String sqlQuery = "";
if (txtTitle != null) {
sqlQuery += " and cTitle like '%" + txtTitle + "%'";
}
if (txtContent != null) {
sqlQuery += " and cContent like '%" + txtContent + "%'";
}
if (txtDate != null) {
sqlQuery += " and cDate like '%" + txtDate + "%'";
}
if (txtProjectName != null) {
TblOrder ord = OrderModel.getInstance().getOrderByName(txtProjectName);
if (ord != null) {
sqlQuery += " and oID = " + ord.getOid();
}
}
if (txtCustomer != null) {
TblPerson per = PersonModel.getInstance().getPersonByName(txtCustomer);
if (per != null) {
sqlQuery += " and pID = " + per.getPid();
}
}
if (Integer.parseInt(txtCheck) != 2) {
sqlQuery += " and cReadComp = " + txtCheck;
}
if (Integer.parseInt(selectStatus) != 2) {
sqlQuery += " and cStatus = " + selectStatus;
}
session = request.getSession();
session.setAttribute("searchComplaint", sqlQuery);
response.sendRedirect("admin/indexAdmin.jsp?nav=complaintManage&aID=" + session.getAttribute("adminID") + "&search=true");
}
private void processSendComplaint(HttpServletRequest request, HttpServletResponse response) throws IOException {
String pID = request.getParameter("pID");
String oID = request.getParameter("oID");
String txtTitle = request.getParameter("txtTitle");
String txtContent = request.getParameter("txtContent");
TblComplaint complaint = new TblComplaint();
complaint.setCtitle(txtTitle);
complaint.setCcontent(txtContent);
TblPerson per = PersonModel.getInstance().getPersonByID(Integer.parseInt(pID));
complaint.setTblPerson(per);
TblOrder ord = OrderModel.getInstance().getOrderByID(Integer.parseInt(oID));
complaint.setTblOrder(ord);
Date date = new Date();
complaint.setCdate(date);
complaint.setCreadComp(0);
complaint.setCstatus(Byte.parseByte("0"));
session = request.getSession();
if(compModel.insertObject(complaint)){
session.setAttribute("messComplaint", "SendComplaintSuccess");
response.sendRedirect("?nav=customer");
}else{
session.setAttribute("messComplaint", "SendComplaintFail");
response.sendRedirect("?nav=customer");
}
}
}
| 8,395 | 0.625849 | 0.625015 | 218 | 37.509174 | 27.615519 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.536697 | false | false | 9 |
9c2dab4c2ef1b136f90a23564316fec68ca883da | 13,520,557,108,683 | 3a007f799ab01a95528729ef83bcf3c10f64c9b0 | /src/main/java/com/markoni/interv/commons/error/ValidationException.java | cb6b85bcc8933871143f50b0516d875c75876985 | [] | no_license | marko-nikolic/interv | https://github.com/marko-nikolic/interv | e44f7dd119626183837c8627d04fbc88b417628f | c8df90af55fde5ffc29c8d23e9ca53419571950c | refs/heads/master | 2022-12-07T13:49:10.397000 | 2020-08-10T23:29:27 | 2020-08-10T23:29:27 | 286,098,021 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.markoni.interv.commons.error;
import com.markoni.interv.commons.message.Message;
import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
/**
* Exception used for custom validation
*/
@Getter
public class ValidationException extends RuntimeException {
private List<Message> messages;
public ValidationException(String message) {
super(message);
}
public ValidationException(String message, List<Message> messages) {
super(message);
this.messages = messages;
}
public ValidationException(List<Message> messages) {
this(null, messages);
}
public ValidationException(Message message) {
messages = new ArrayList<>();
messages.add(message);
}
}
| UTF-8 | Java | 763 | java | ValidationException.java | Java | [] | null | [] | package com.markoni.interv.commons.error;
import com.markoni.interv.commons.message.Message;
import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
/**
* Exception used for custom validation
*/
@Getter
public class ValidationException extends RuntimeException {
private List<Message> messages;
public ValidationException(String message) {
super(message);
}
public ValidationException(String message, List<Message> messages) {
super(message);
this.messages = messages;
}
public ValidationException(List<Message> messages) {
this(null, messages);
}
public ValidationException(Message message) {
messages = new ArrayList<>();
messages.add(message);
}
}
| 763 | 0.694626 | 0.694626 | 35 | 20.799999 | 20.955463 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 9 |
657f5de4deacb686975fb50bead7a33e34d7fa8b | 3,143,916,100,164 | 5c6e57a8893e92b44466ca8f90498213b0b72f21 | /JavaProjects/VirtualClassRoomApplication/src/clientapp/MentorSession.java | b53854e22c8ca7a7dc006f981410ba52aee7f22a | [] | no_license | jatinkumar762/Projects | https://github.com/jatinkumar762/Projects | 8265daad45ff84b780a66f192cc23010a3122ea2 | 893e106f572e1ee26cf40bf0b2effd8486ba993d | refs/heads/master | 2017-12-30T07:58:31.753000 | 2016-10-28T14:41:23 | 2016-10-28T14:41:23 | 72,211,986 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package clientapp;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.spi.AudioFileWriter;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
public class MentorSession extends JPanel implements ActionListener
{
JLabel labTopic,labTitle,labCE,labDis,labAnswer;
JTextArea txtCE,txtAnswer;
JTextField fTopic,fTitle;
JButton butsend,btnStart,btnStop,btnSaveEnd,btnEnd;
JScrollPane scrollCE,scrollDis,scrollReply;
TargetDataLine line;
JTable tblDis;
Object HEAD[]={"Name","Comment"};
Object DATA[][];
int index;
public MentorSession()
{
this.setLayout(null);
this.DATA=new Object[500][2];
for(int i=0;i<500;i++)
for(int j=0;j<2;j++)
DATA[i][j]="";
this.index=0;
this.labTopic=new JLabel("Topic :");
this.labTitle=new JLabel("Title :");
this.labCE=new JLabel("Code Editor :");
this.labDis=new JLabel("Discussion :");
this.labAnswer=new JLabel("Answer :");
this.fTopic=new JTextField();
this.fTitle=new JTextField();
this.txtCE=new JTextArea();
this.txtAnswer=new JTextArea();
this.tblDis=new JTable(DATA,HEAD);
this.tblDis.setShowGrid(false);
this.tblDis.setBackground(Color.CYAN);
this.tblDis.setSelectionBackground(Color.RED);
this.tblDis.setSelectionForeground(Color.BLACK);
this.butsend=new JButton("Reply");
this.btnStart=new JButton("Start");
this.btnStop=new JButton("Stop");
this.btnSaveEnd=new JButton("Save+End");
this.btnEnd=new JButton("End");
this.scrollCE=new JScrollPane(txtCE,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.scrollDis=new JScrollPane(tblDis,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.scrollReply=new JScrollPane(txtAnswer,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.labTopic.setBounds(20,10,100,25);
this.fTopic.setBounds(100,10,300,25);
this.labTitle.setBounds(20,40,100,25);
this.fTitle.setBounds(100,40,300,25);
this.labCE.setBounds(20,80,150,20);
this.scrollCE.setBounds(20,110,400,400);
this.labDis.setBounds(420,10,150,25);
this.scrollDis.setBounds(420,30,265,300);
this.labAnswer.setBounds(420,330,150,20);
this.scrollReply.setBounds(420,350,265,155);
this.butsend.setBounds(480,520,100,30);
this.btnStart.setBounds(170,80,100,25);
this.btnStop.setBounds(300,80,100,25);
this.btnSaveEnd.setBounds(80,520,100,30);
this.btnEnd.setBounds(200,520,100,30);
this.labTopic.setFont(new Font("Garamond",Font.BOLD,20));
this.labTitle.setFont(new Font("Garamond",Font.BOLD,20));
this.labCE.setFont(new Font("Garamond",Font.BOLD,20));
this.labDis.setFont(new Font("Garamond",Font.BOLD,20));
this.labAnswer.setFont(new Font("Garamond",Font.BOLD,20));
//Add txt Label
this.add(labTopic);
this.add(labTitle);
this.add(labCE);
this.add(labDis);
this.add(labAnswer);
//Add txt Field
this.add(fTopic);
this.add(fTitle);
//Add Button
this.add(butsend);
this.add(btnStart);
this.add(btnStop);
this.add(btnSaveEnd);
this.add(btnEnd);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
//Add ScrollPane
this.add(scrollCE);
this.add(scrollDis);
this.add(scrollReply);
this.fTopic.setEditable(false);
this.fTitle.addKeyListener(new KeyAdapter(){
public void keyReleased(KeyEvent ke)
{
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("MentorText");
out.writeObject("TitleText");
out.writeObject(MentorSession.this.fTitle.getText());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
});
this.txtCE.addKeyListener(new KeyAdapter(){
public void keyReleased(KeyEvent ke)
{
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("MentorText");
out.writeObject("CodeEditorText");
out.writeObject(MentorSession.this.txtCE.getText());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
});
this.butsend.addActionListener(this);
this.btnStart.addActionListener(this);
this.btnStop.addActionListener(this);
this.btnSaveEnd.addActionListener(this);
this.btnEnd.addActionListener(this);
}
class SoundRecorder extends Thread
{
public void run()
{
try
{
DataLine.Info info;
AudioFormat format=new AudioFormat(16000,8,2,true,true);
info=new DataLine.Info(TargetDataLine.class,format);
//Check if System supports the data line
if(!AudioSystem.isLineSupported(info))
{
JOptionPane.showMessageDialog(MentorSession.this, "Audio Line Not Supported!!!","Audio Recording",JOptionPane.ERROR_MESSAGE);
return;
}
line=(TargetDataLine)AudioSystem.getLine(info);
line.open(format);
line.start();
AudioInputStream ais=new AudioInputStream(line);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File("test.wav"));
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==this.butsend) {
String answer=txtAnswer.getText();
txtAnswer.setText("");
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("DiscussionText");
out.writeObject(answer);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
if(ae.getSource()==this.btnStart){
try
{
btnStart.setEnabled(false);
btnStop.setEnabled(true);
new SoundRecorder().start();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this, "Problem in Audio Line!!!","Audio Recording",JOptionPane.ERROR_MESSAGE);
}
}
if(ae.getSource()==this.btnStop)
{
try
{
this.line.stop();
this.line.close();
btnStart.setEnabled(true);
btnStop.setEnabled(false);
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("DiscussionAudio");
File file=new File("test.wav");
FileInputStream fin=new FileInputStream(file);
byte barr[]=new byte[(int)file.length()];
fin.read(barr);
fin.close();
out.writeObject(barr);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
if(ae.getSource()==this.btnEnd)
{
if(JOptionPane.showConfirmDialog(ClientRes.mwin.mSession,"Are you sure ?","EndSession",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
{
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("EndSession");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
}
if(ae.getSource()==this.btnSaveEnd)
{
if(JOptionPane.showConfirmDialog(ClientRes.mwin.mSession,"Are you sure ?","EndSession",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
{
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("SaveEndSession");
out.writeObject(fTopic.getText());
out.writeObject(fTitle.getText());
out.writeObject(txtCE.getText());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
| UTF-8 | Java | 10,246 | java | MentorSession.java | Java | [] | null | [] | package clientapp;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.spi.AudioFileWriter;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
public class MentorSession extends JPanel implements ActionListener
{
JLabel labTopic,labTitle,labCE,labDis,labAnswer;
JTextArea txtCE,txtAnswer;
JTextField fTopic,fTitle;
JButton butsend,btnStart,btnStop,btnSaveEnd,btnEnd;
JScrollPane scrollCE,scrollDis,scrollReply;
TargetDataLine line;
JTable tblDis;
Object HEAD[]={"Name","Comment"};
Object DATA[][];
int index;
public MentorSession()
{
this.setLayout(null);
this.DATA=new Object[500][2];
for(int i=0;i<500;i++)
for(int j=0;j<2;j++)
DATA[i][j]="";
this.index=0;
this.labTopic=new JLabel("Topic :");
this.labTitle=new JLabel("Title :");
this.labCE=new JLabel("Code Editor :");
this.labDis=new JLabel("Discussion :");
this.labAnswer=new JLabel("Answer :");
this.fTopic=new JTextField();
this.fTitle=new JTextField();
this.txtCE=new JTextArea();
this.txtAnswer=new JTextArea();
this.tblDis=new JTable(DATA,HEAD);
this.tblDis.setShowGrid(false);
this.tblDis.setBackground(Color.CYAN);
this.tblDis.setSelectionBackground(Color.RED);
this.tblDis.setSelectionForeground(Color.BLACK);
this.butsend=new JButton("Reply");
this.btnStart=new JButton("Start");
this.btnStop=new JButton("Stop");
this.btnSaveEnd=new JButton("Save+End");
this.btnEnd=new JButton("End");
this.scrollCE=new JScrollPane(txtCE,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.scrollDis=new JScrollPane(tblDis,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.scrollReply=new JScrollPane(txtAnswer,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.labTopic.setBounds(20,10,100,25);
this.fTopic.setBounds(100,10,300,25);
this.labTitle.setBounds(20,40,100,25);
this.fTitle.setBounds(100,40,300,25);
this.labCE.setBounds(20,80,150,20);
this.scrollCE.setBounds(20,110,400,400);
this.labDis.setBounds(420,10,150,25);
this.scrollDis.setBounds(420,30,265,300);
this.labAnswer.setBounds(420,330,150,20);
this.scrollReply.setBounds(420,350,265,155);
this.butsend.setBounds(480,520,100,30);
this.btnStart.setBounds(170,80,100,25);
this.btnStop.setBounds(300,80,100,25);
this.btnSaveEnd.setBounds(80,520,100,30);
this.btnEnd.setBounds(200,520,100,30);
this.labTopic.setFont(new Font("Garamond",Font.BOLD,20));
this.labTitle.setFont(new Font("Garamond",Font.BOLD,20));
this.labCE.setFont(new Font("Garamond",Font.BOLD,20));
this.labDis.setFont(new Font("Garamond",Font.BOLD,20));
this.labAnswer.setFont(new Font("Garamond",Font.BOLD,20));
//Add txt Label
this.add(labTopic);
this.add(labTitle);
this.add(labCE);
this.add(labDis);
this.add(labAnswer);
//Add txt Field
this.add(fTopic);
this.add(fTitle);
//Add Button
this.add(butsend);
this.add(btnStart);
this.add(btnStop);
this.add(btnSaveEnd);
this.add(btnEnd);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
//Add ScrollPane
this.add(scrollCE);
this.add(scrollDis);
this.add(scrollReply);
this.fTopic.setEditable(false);
this.fTitle.addKeyListener(new KeyAdapter(){
public void keyReleased(KeyEvent ke)
{
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("MentorText");
out.writeObject("TitleText");
out.writeObject(MentorSession.this.fTitle.getText());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
});
this.txtCE.addKeyListener(new KeyAdapter(){
public void keyReleased(KeyEvent ke)
{
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("MentorText");
out.writeObject("CodeEditorText");
out.writeObject(MentorSession.this.txtCE.getText());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
});
this.butsend.addActionListener(this);
this.btnStart.addActionListener(this);
this.btnStop.addActionListener(this);
this.btnSaveEnd.addActionListener(this);
this.btnEnd.addActionListener(this);
}
class SoundRecorder extends Thread
{
public void run()
{
try
{
DataLine.Info info;
AudioFormat format=new AudioFormat(16000,8,2,true,true);
info=new DataLine.Info(TargetDataLine.class,format);
//Check if System supports the data line
if(!AudioSystem.isLineSupported(info))
{
JOptionPane.showMessageDialog(MentorSession.this, "Audio Line Not Supported!!!","Audio Recording",JOptionPane.ERROR_MESSAGE);
return;
}
line=(TargetDataLine)AudioSystem.getLine(info);
line.open(format);
line.start();
AudioInputStream ais=new AudioInputStream(line);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File("test.wav"));
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==this.butsend) {
String answer=txtAnswer.getText();
txtAnswer.setText("");
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("DiscussionText");
out.writeObject(answer);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
if(ae.getSource()==this.btnStart){
try
{
btnStart.setEnabled(false);
btnStop.setEnabled(true);
new SoundRecorder().start();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(this, "Problem in Audio Line!!!","Audio Recording",JOptionPane.ERROR_MESSAGE);
}
}
if(ae.getSource()==this.btnStop)
{
try
{
this.line.stop();
this.line.close();
btnStart.setEnabled(true);
btnStop.setEnabled(false);
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("DiscussionAudio");
File file=new File("test.wav");
FileInputStream fin=new FileInputStream(file);
byte barr[]=new byte[(int)file.length()];
fin.read(barr);
fin.close();
out.writeObject(barr);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
if(ae.getSource()==this.btnEnd)
{
if(JOptionPane.showConfirmDialog(ClientRes.mwin.mSession,"Are you sure ?","EndSession",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
{
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("EndSession");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
}
if(ae.getSource()==this.btnSaveEnd)
{
if(JOptionPane.showConfirmDialog(ClientRes.mwin.mSession,"Are you sure ?","EndSession",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
{
try
{
ObjectOutputStream out=new ObjectOutputStream(ClientRes.client.getOutputStream());
out.writeObject("SaveEndSession");
out.writeObject(fTopic.getText());
out.writeObject(fTitle.getText());
out.writeObject(txtCE.getText());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(ClientRes.mwin.mSession,ex.toString(),"MentorSession",JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
| 10,246 | 0.608433 | 0.59067 | 305 | 31.593443 | 29.190701 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.508197 | false | false | 9 |
e66d69af81788e23caac7089b0510033ec992a70 | 3,143,916,102,530 | c36d08386a88e139e6325ea7f5de64ba00a45c9f | /hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/records/impl/pb/ReservationRequestsPBImpl.java | 1ada946b40b89483b1ede184373ac81862965874 | [
"Apache-2.0",
"LicenseRef-scancode-unknown",
"CC0-1.0",
"CC-BY-3.0",
"EPL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Classpath-exception-2.0",
"CC-PDDC",
"GCC-exception-3.1",
"CDDL-1.0",
"MIT",
"GPL-2.0-only",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-on... | permissive | dmgerman/hadoop | https://github.com/dmgerman/hadoop | 6197e3f3009196fb4ca528ab420d99a0cd5b9396 | 70c015914a8756c5440cd969d70dac04b8b6142b | refs/heads/master | 2020-12-01T06:30:51.605000 | 2019-12-19T19:37:17 | 2019-12-19T19:37:17 | 230,528,747 | 0 | 0 | Apache-2.0 | false | 2020-01-31T18:29:52 | 2019-12-27T22:48:25 | 2019-12-28T01:56:19 | 2020-01-31T18:29:51 | 128,849 | 0 | 0 | 1 | Java | false | false | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.api.records.impl.pb
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|impl
operator|.
name|pb
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Iterator
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ReservationRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ReservationRequestInterpreter
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ReservationRequests
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|proto
operator|.
name|YarnProtos
operator|.
name|ReservationRequestInterpreterProto
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|proto
operator|.
name|YarnProtos
operator|.
name|ReservationRequestProto
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|proto
operator|.
name|YarnProtos
operator|.
name|ReservationRequestsProto
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|proto
operator|.
name|YarnProtos
operator|.
name|ReservationRequestsProtoOrBuilder
import|;
end_import
begin_class
DECL|class|ReservationRequestsPBImpl
specifier|public
class|class
name|ReservationRequestsPBImpl
extends|extends
name|ReservationRequests
block|{
DECL|field|proto
name|ReservationRequestsProto
name|proto
init|=
name|ReservationRequestsProto
operator|.
name|getDefaultInstance
argument_list|()
decl_stmt|;
DECL|field|builder
name|ReservationRequestsProto
operator|.
name|Builder
name|builder
init|=
literal|null
decl_stmt|;
DECL|field|viaProto
name|boolean
name|viaProto
init|=
literal|false
decl_stmt|;
DECL|field|reservationRequests
specifier|public
name|List
argument_list|<
name|ReservationRequest
argument_list|>
name|reservationRequests
decl_stmt|;
DECL|method|ReservationRequestsPBImpl ()
specifier|public
name|ReservationRequestsPBImpl
parameter_list|()
block|{
name|builder
operator|=
name|ReservationRequestsProto
operator|.
name|newBuilder
argument_list|()
expr_stmt|;
block|}
DECL|method|ReservationRequestsPBImpl (ReservationRequestsProto proto)
specifier|public
name|ReservationRequestsPBImpl
parameter_list|(
name|ReservationRequestsProto
name|proto
parameter_list|)
block|{
name|this
operator|.
name|proto
operator|=
name|proto
expr_stmt|;
name|viaProto
operator|=
literal|true
expr_stmt|;
block|}
DECL|method|getProto ()
specifier|public
name|ReservationRequestsProto
name|getProto
parameter_list|()
block|{
name|mergeLocalToProto
argument_list|()
expr_stmt|;
name|proto
operator|=
name|viaProto
condition|?
name|proto
else|:
name|builder
operator|.
name|build
argument_list|()
expr_stmt|;
name|viaProto
operator|=
literal|true
expr_stmt|;
return|return
name|proto
return|;
block|}
DECL|method|mergeLocalToBuilder ()
specifier|private
name|void
name|mergeLocalToBuilder
parameter_list|()
block|{
if|if
condition|(
name|this
operator|.
name|reservationRequests
operator|!=
literal|null
condition|)
block|{
name|addReservationResourcesToProto
argument_list|()
expr_stmt|;
block|}
block|}
DECL|method|mergeLocalToProto ()
specifier|private
name|void
name|mergeLocalToProto
parameter_list|()
block|{
if|if
condition|(
name|viaProto
condition|)
name|maybeInitBuilder
argument_list|()
expr_stmt|;
name|mergeLocalToBuilder
argument_list|()
expr_stmt|;
name|proto
operator|=
name|builder
operator|.
name|build
argument_list|()
expr_stmt|;
name|viaProto
operator|=
literal|true
expr_stmt|;
block|}
DECL|method|maybeInitBuilder ()
specifier|private
name|void
name|maybeInitBuilder
parameter_list|()
block|{
if|if
condition|(
name|viaProto
operator|||
name|builder
operator|==
literal|null
condition|)
block|{
name|builder
operator|=
name|ReservationRequestsProto
operator|.
name|newBuilder
argument_list|(
name|proto
argument_list|)
expr_stmt|;
block|}
name|viaProto
operator|=
literal|false
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|getReservationResources ()
specifier|public
name|List
argument_list|<
name|ReservationRequest
argument_list|>
name|getReservationResources
parameter_list|()
block|{
name|initReservationRequestsList
argument_list|()
expr_stmt|;
return|return
name|reservationRequests
return|;
block|}
annotation|@
name|Override
DECL|method|setReservationResources (List<ReservationRequest> resources)
specifier|public
name|void
name|setReservationResources
parameter_list|(
name|List
argument_list|<
name|ReservationRequest
argument_list|>
name|resources
parameter_list|)
block|{
if|if
condition|(
name|resources
operator|==
literal|null
condition|)
block|{
name|builder
operator|.
name|clearReservationResources
argument_list|()
expr_stmt|;
return|return;
block|}
name|this
operator|.
name|reservationRequests
operator|=
name|resources
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|getInterpreter ()
specifier|public
name|ReservationRequestInterpreter
name|getInterpreter
parameter_list|()
block|{
name|ReservationRequestsProtoOrBuilder
name|p
init|=
name|viaProto
condition|?
name|proto
else|:
name|builder
decl_stmt|;
if|if
condition|(
operator|!
name|p
operator|.
name|hasInterpreter
argument_list|()
condition|)
block|{
return|return
literal|null
return|;
block|}
return|return
operator|(
name|convertFromProtoFormat
argument_list|(
name|p
operator|.
name|getInterpreter
argument_list|()
argument_list|)
operator|)
return|;
block|}
annotation|@
name|Override
DECL|method|setInterpreter (ReservationRequestInterpreter interpreter)
specifier|public
name|void
name|setInterpreter
parameter_list|(
name|ReservationRequestInterpreter
name|interpreter
parameter_list|)
block|{
name|maybeInitBuilder
argument_list|()
expr_stmt|;
if|if
condition|(
name|interpreter
operator|==
literal|null
condition|)
block|{
name|builder
operator|.
name|clearInterpreter
argument_list|()
expr_stmt|;
return|return;
block|}
name|builder
operator|.
name|setInterpreter
argument_list|(
name|convertToProtoFormat
argument_list|(
name|interpreter
argument_list|)
argument_list|)
expr_stmt|;
block|}
DECL|method|initReservationRequestsList ()
specifier|private
name|void
name|initReservationRequestsList
parameter_list|()
block|{
if|if
condition|(
name|this
operator|.
name|reservationRequests
operator|!=
literal|null
condition|)
block|{
return|return;
block|}
name|ReservationRequestsProtoOrBuilder
name|p
init|=
name|viaProto
condition|?
name|proto
else|:
name|builder
decl_stmt|;
name|List
argument_list|<
name|ReservationRequestProto
argument_list|>
name|resourceProtos
init|=
name|p
operator|.
name|getReservationResourcesList
argument_list|()
decl_stmt|;
name|reservationRequests
operator|=
operator|new
name|ArrayList
argument_list|<
name|ReservationRequest
argument_list|>
argument_list|()
expr_stmt|;
for|for
control|(
name|ReservationRequestProto
name|r
range|:
name|resourceProtos
control|)
block|{
name|reservationRequests
operator|.
name|add
argument_list|(
name|convertFromProtoFormat
argument_list|(
name|r
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
DECL|method|addReservationResourcesToProto ()
specifier|private
name|void
name|addReservationResourcesToProto
parameter_list|()
block|{
name|maybeInitBuilder
argument_list|()
expr_stmt|;
name|builder
operator|.
name|clearReservationResources
argument_list|()
expr_stmt|;
if|if
condition|(
name|reservationRequests
operator|==
literal|null
condition|)
return|return;
name|Iterable
argument_list|<
name|ReservationRequestProto
argument_list|>
name|iterable
init|=
operator|new
name|Iterable
argument_list|<
name|ReservationRequestProto
argument_list|>
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|Iterator
argument_list|<
name|ReservationRequestProto
argument_list|>
name|iterator
parameter_list|()
block|{
return|return
operator|new
name|Iterator
argument_list|<
name|ReservationRequestProto
argument_list|>
argument_list|()
block|{
name|Iterator
argument_list|<
name|ReservationRequest
argument_list|>
name|iter
init|=
name|reservationRequests
operator|.
name|iterator
argument_list|()
decl_stmt|;
annotation|@
name|Override
specifier|public
name|boolean
name|hasNext
parameter_list|()
block|{
return|return
name|iter
operator|.
name|hasNext
argument_list|()
return|;
block|}
annotation|@
name|Override
specifier|public
name|ReservationRequestProto
name|next
parameter_list|()
block|{
return|return
name|convertToProtoFormat
argument_list|(
name|iter
operator|.
name|next
argument_list|()
argument_list|)
return|;
block|}
annotation|@
name|Override
specifier|public
name|void
name|remove
parameter_list|()
block|{
throw|throw
operator|new
name|UnsupportedOperationException
argument_list|()
throw|;
block|}
block|}
return|;
block|}
block|}
decl_stmt|;
name|builder
operator|.
name|addAllReservationResources
argument_list|(
name|iterable
argument_list|)
expr_stmt|;
block|}
DECL|method|convertToProtoFormat (ReservationRequest r)
specifier|private
name|ReservationRequestProto
name|convertToProtoFormat
parameter_list|(
name|ReservationRequest
name|r
parameter_list|)
block|{
return|return
operator|(
operator|(
name|ReservationRequestPBImpl
operator|)
name|r
operator|)
operator|.
name|getProto
argument_list|()
return|;
block|}
DECL|method|convertFromProtoFormat ( ReservationRequestProto r)
specifier|private
name|ReservationRequestPBImpl
name|convertFromProtoFormat
parameter_list|(
name|ReservationRequestProto
name|r
parameter_list|)
block|{
return|return
operator|new
name|ReservationRequestPBImpl
argument_list|(
name|r
argument_list|)
return|;
block|}
DECL|method|convertToProtoFormat ( ReservationRequestInterpreter r)
specifier|private
name|ReservationRequestInterpreterProto
name|convertToProtoFormat
parameter_list|(
name|ReservationRequestInterpreter
name|r
parameter_list|)
block|{
return|return
name|ProtoUtils
operator|.
name|convertToProtoFormat
argument_list|(
name|r
argument_list|)
return|;
block|}
DECL|method|convertFromProtoFormat ( ReservationRequestInterpreterProto r)
specifier|private
name|ReservationRequestInterpreter
name|convertFromProtoFormat
parameter_list|(
name|ReservationRequestInterpreterProto
name|r
parameter_list|)
block|{
return|return
name|ProtoUtils
operator|.
name|convertFromProtoFormat
argument_list|(
name|r
argument_list|)
return|;
block|}
annotation|@
name|Override
DECL|method|toString ()
specifier|public
name|String
name|toString
parameter_list|()
block|{
return|return
literal|"{Reservation Resources: "
operator|+
name|getReservationResources
argument_list|()
operator|+
literal|", Reservation Type: "
operator|+
name|getInterpreter
argument_list|()
operator|+
literal|"}"
return|;
block|}
annotation|@
name|Override
DECL|method|hashCode ()
specifier|public
name|int
name|hashCode
parameter_list|()
block|{
return|return
name|getProto
argument_list|()
operator|.
name|hashCode
argument_list|()
return|;
block|}
annotation|@
name|Override
DECL|method|equals (Object other)
specifier|public
name|boolean
name|equals
parameter_list|(
name|Object
name|other
parameter_list|)
block|{
if|if
condition|(
name|other
operator|==
literal|null
condition|)
return|return
literal|false
return|;
if|if
condition|(
name|other
operator|.
name|getClass
argument_list|()
operator|.
name|isAssignableFrom
argument_list|(
name|this
operator|.
name|getClass
argument_list|()
argument_list|)
condition|)
block|{
return|return
name|this
operator|.
name|getProto
argument_list|()
operator|.
name|equals
argument_list|(
name|this
operator|.
name|getClass
argument_list|()
operator|.
name|cast
argument_list|(
name|other
argument_list|)
operator|.
name|getProto
argument_list|()
argument_list|)
return|;
block|}
return|return
literal|false
return|;
block|}
block|}
end_class
end_unit
| UTF-8 | Java | 13,444 | java | ReservationRequestsPBImpl.java | Java | [] | null | [] | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.api.records.impl.pb
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|impl
operator|.
name|pb
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Iterator
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ReservationRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ReservationRequestInterpreter
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ReservationRequests
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|proto
operator|.
name|YarnProtos
operator|.
name|ReservationRequestInterpreterProto
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|proto
operator|.
name|YarnProtos
operator|.
name|ReservationRequestProto
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|proto
operator|.
name|YarnProtos
operator|.
name|ReservationRequestsProto
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|proto
operator|.
name|YarnProtos
operator|.
name|ReservationRequestsProtoOrBuilder
import|;
end_import
begin_class
DECL|class|ReservationRequestsPBImpl
specifier|public
class|class
name|ReservationRequestsPBImpl
extends|extends
name|ReservationRequests
block|{
DECL|field|proto
name|ReservationRequestsProto
name|proto
init|=
name|ReservationRequestsProto
operator|.
name|getDefaultInstance
argument_list|()
decl_stmt|;
DECL|field|builder
name|ReservationRequestsProto
operator|.
name|Builder
name|builder
init|=
literal|null
decl_stmt|;
DECL|field|viaProto
name|boolean
name|viaProto
init|=
literal|false
decl_stmt|;
DECL|field|reservationRequests
specifier|public
name|List
argument_list|<
name|ReservationRequest
argument_list|>
name|reservationRequests
decl_stmt|;
DECL|method|ReservationRequestsPBImpl ()
specifier|public
name|ReservationRequestsPBImpl
parameter_list|()
block|{
name|builder
operator|=
name|ReservationRequestsProto
operator|.
name|newBuilder
argument_list|()
expr_stmt|;
block|}
DECL|method|ReservationRequestsPBImpl (ReservationRequestsProto proto)
specifier|public
name|ReservationRequestsPBImpl
parameter_list|(
name|ReservationRequestsProto
name|proto
parameter_list|)
block|{
name|this
operator|.
name|proto
operator|=
name|proto
expr_stmt|;
name|viaProto
operator|=
literal|true
expr_stmt|;
block|}
DECL|method|getProto ()
specifier|public
name|ReservationRequestsProto
name|getProto
parameter_list|()
block|{
name|mergeLocalToProto
argument_list|()
expr_stmt|;
name|proto
operator|=
name|viaProto
condition|?
name|proto
else|:
name|builder
operator|.
name|build
argument_list|()
expr_stmt|;
name|viaProto
operator|=
literal|true
expr_stmt|;
return|return
name|proto
return|;
block|}
DECL|method|mergeLocalToBuilder ()
specifier|private
name|void
name|mergeLocalToBuilder
parameter_list|()
block|{
if|if
condition|(
name|this
operator|.
name|reservationRequests
operator|!=
literal|null
condition|)
block|{
name|addReservationResourcesToProto
argument_list|()
expr_stmt|;
block|}
block|}
DECL|method|mergeLocalToProto ()
specifier|private
name|void
name|mergeLocalToProto
parameter_list|()
block|{
if|if
condition|(
name|viaProto
condition|)
name|maybeInitBuilder
argument_list|()
expr_stmt|;
name|mergeLocalToBuilder
argument_list|()
expr_stmt|;
name|proto
operator|=
name|builder
operator|.
name|build
argument_list|()
expr_stmt|;
name|viaProto
operator|=
literal|true
expr_stmt|;
block|}
DECL|method|maybeInitBuilder ()
specifier|private
name|void
name|maybeInitBuilder
parameter_list|()
block|{
if|if
condition|(
name|viaProto
operator|||
name|builder
operator|==
literal|null
condition|)
block|{
name|builder
operator|=
name|ReservationRequestsProto
operator|.
name|newBuilder
argument_list|(
name|proto
argument_list|)
expr_stmt|;
block|}
name|viaProto
operator|=
literal|false
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|getReservationResources ()
specifier|public
name|List
argument_list|<
name|ReservationRequest
argument_list|>
name|getReservationResources
parameter_list|()
block|{
name|initReservationRequestsList
argument_list|()
expr_stmt|;
return|return
name|reservationRequests
return|;
block|}
annotation|@
name|Override
DECL|method|setReservationResources (List<ReservationRequest> resources)
specifier|public
name|void
name|setReservationResources
parameter_list|(
name|List
argument_list|<
name|ReservationRequest
argument_list|>
name|resources
parameter_list|)
block|{
if|if
condition|(
name|resources
operator|==
literal|null
condition|)
block|{
name|builder
operator|.
name|clearReservationResources
argument_list|()
expr_stmt|;
return|return;
block|}
name|this
operator|.
name|reservationRequests
operator|=
name|resources
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|getInterpreter ()
specifier|public
name|ReservationRequestInterpreter
name|getInterpreter
parameter_list|()
block|{
name|ReservationRequestsProtoOrBuilder
name|p
init|=
name|viaProto
condition|?
name|proto
else|:
name|builder
decl_stmt|;
if|if
condition|(
operator|!
name|p
operator|.
name|hasInterpreter
argument_list|()
condition|)
block|{
return|return
literal|null
return|;
block|}
return|return
operator|(
name|convertFromProtoFormat
argument_list|(
name|p
operator|.
name|getInterpreter
argument_list|()
argument_list|)
operator|)
return|;
block|}
annotation|@
name|Override
DECL|method|setInterpreter (ReservationRequestInterpreter interpreter)
specifier|public
name|void
name|setInterpreter
parameter_list|(
name|ReservationRequestInterpreter
name|interpreter
parameter_list|)
block|{
name|maybeInitBuilder
argument_list|()
expr_stmt|;
if|if
condition|(
name|interpreter
operator|==
literal|null
condition|)
block|{
name|builder
operator|.
name|clearInterpreter
argument_list|()
expr_stmt|;
return|return;
block|}
name|builder
operator|.
name|setInterpreter
argument_list|(
name|convertToProtoFormat
argument_list|(
name|interpreter
argument_list|)
argument_list|)
expr_stmt|;
block|}
DECL|method|initReservationRequestsList ()
specifier|private
name|void
name|initReservationRequestsList
parameter_list|()
block|{
if|if
condition|(
name|this
operator|.
name|reservationRequests
operator|!=
literal|null
condition|)
block|{
return|return;
block|}
name|ReservationRequestsProtoOrBuilder
name|p
init|=
name|viaProto
condition|?
name|proto
else|:
name|builder
decl_stmt|;
name|List
argument_list|<
name|ReservationRequestProto
argument_list|>
name|resourceProtos
init|=
name|p
operator|.
name|getReservationResourcesList
argument_list|()
decl_stmt|;
name|reservationRequests
operator|=
operator|new
name|ArrayList
argument_list|<
name|ReservationRequest
argument_list|>
argument_list|()
expr_stmt|;
for|for
control|(
name|ReservationRequestProto
name|r
range|:
name|resourceProtos
control|)
block|{
name|reservationRequests
operator|.
name|add
argument_list|(
name|convertFromProtoFormat
argument_list|(
name|r
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
DECL|method|addReservationResourcesToProto ()
specifier|private
name|void
name|addReservationResourcesToProto
parameter_list|()
block|{
name|maybeInitBuilder
argument_list|()
expr_stmt|;
name|builder
operator|.
name|clearReservationResources
argument_list|()
expr_stmt|;
if|if
condition|(
name|reservationRequests
operator|==
literal|null
condition|)
return|return;
name|Iterable
argument_list|<
name|ReservationRequestProto
argument_list|>
name|iterable
init|=
operator|new
name|Iterable
argument_list|<
name|ReservationRequestProto
argument_list|>
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|Iterator
argument_list|<
name|ReservationRequestProto
argument_list|>
name|iterator
parameter_list|()
block|{
return|return
operator|new
name|Iterator
argument_list|<
name|ReservationRequestProto
argument_list|>
argument_list|()
block|{
name|Iterator
argument_list|<
name|ReservationRequest
argument_list|>
name|iter
init|=
name|reservationRequests
operator|.
name|iterator
argument_list|()
decl_stmt|;
annotation|@
name|Override
specifier|public
name|boolean
name|hasNext
parameter_list|()
block|{
return|return
name|iter
operator|.
name|hasNext
argument_list|()
return|;
block|}
annotation|@
name|Override
specifier|public
name|ReservationRequestProto
name|next
parameter_list|()
block|{
return|return
name|convertToProtoFormat
argument_list|(
name|iter
operator|.
name|next
argument_list|()
argument_list|)
return|;
block|}
annotation|@
name|Override
specifier|public
name|void
name|remove
parameter_list|()
block|{
throw|throw
operator|new
name|UnsupportedOperationException
argument_list|()
throw|;
block|}
block|}
return|;
block|}
block|}
decl_stmt|;
name|builder
operator|.
name|addAllReservationResources
argument_list|(
name|iterable
argument_list|)
expr_stmt|;
block|}
DECL|method|convertToProtoFormat (ReservationRequest r)
specifier|private
name|ReservationRequestProto
name|convertToProtoFormat
parameter_list|(
name|ReservationRequest
name|r
parameter_list|)
block|{
return|return
operator|(
operator|(
name|ReservationRequestPBImpl
operator|)
name|r
operator|)
operator|.
name|getProto
argument_list|()
return|;
block|}
DECL|method|convertFromProtoFormat ( ReservationRequestProto r)
specifier|private
name|ReservationRequestPBImpl
name|convertFromProtoFormat
parameter_list|(
name|ReservationRequestProto
name|r
parameter_list|)
block|{
return|return
operator|new
name|ReservationRequestPBImpl
argument_list|(
name|r
argument_list|)
return|;
block|}
DECL|method|convertToProtoFormat ( ReservationRequestInterpreter r)
specifier|private
name|ReservationRequestInterpreterProto
name|convertToProtoFormat
parameter_list|(
name|ReservationRequestInterpreter
name|r
parameter_list|)
block|{
return|return
name|ProtoUtils
operator|.
name|convertToProtoFormat
argument_list|(
name|r
argument_list|)
return|;
block|}
DECL|method|convertFromProtoFormat ( ReservationRequestInterpreterProto r)
specifier|private
name|ReservationRequestInterpreter
name|convertFromProtoFormat
parameter_list|(
name|ReservationRequestInterpreterProto
name|r
parameter_list|)
block|{
return|return
name|ProtoUtils
operator|.
name|convertFromProtoFormat
argument_list|(
name|r
argument_list|)
return|;
block|}
annotation|@
name|Override
DECL|method|toString ()
specifier|public
name|String
name|toString
parameter_list|()
block|{
return|return
literal|"{Reservation Resources: "
operator|+
name|getReservationResources
argument_list|()
operator|+
literal|", Reservation Type: "
operator|+
name|getInterpreter
argument_list|()
operator|+
literal|"}"
return|;
block|}
annotation|@
name|Override
DECL|method|hashCode ()
specifier|public
name|int
name|hashCode
parameter_list|()
block|{
return|return
name|getProto
argument_list|()
operator|.
name|hashCode
argument_list|()
return|;
block|}
annotation|@
name|Override
DECL|method|equals (Object other)
specifier|public
name|boolean
name|equals
parameter_list|(
name|Object
name|other
parameter_list|)
block|{
if|if
condition|(
name|other
operator|==
literal|null
condition|)
return|return
literal|false
return|;
if|if
condition|(
name|other
operator|.
name|getClass
argument_list|()
operator|.
name|isAssignableFrom
argument_list|(
name|this
operator|.
name|getClass
argument_list|()
argument_list|)
condition|)
block|{
return|return
name|this
operator|.
name|getProto
argument_list|()
operator|.
name|equals
argument_list|(
name|this
operator|.
name|getClass
argument_list|()
operator|.
name|cast
argument_list|(
name|other
argument_list|)
operator|.
name|getProto
argument_list|()
argument_list|)
return|;
block|}
return|return
literal|false
return|;
block|}
block|}
end_class
end_unit
| 13,444 | 0.803035 | 0.802291 | 858 | 14.667832 | 28.632393 | 814 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.06993 | false | false | 9 |
daa5f75ff7e1075ccf81915fd2c95b48cabcf712 | 558,345,749,939 | dc5533056d11bc046e6bbdddb9a8da1f7496140c | /hw05/src/cs3500/music/model/MusicModel.java | ac2185303ae498a44d9c669ef8f82dd425a9a017 | [] | no_license | kirumiraj/MusicEditorProject | https://github.com/kirumiraj/MusicEditorProject | ca0b4cf1500aa506dc45d159041c2a1ac32bd4ee | f01b8c0814173314ec3841f018137e22fc6f6377 | refs/heads/master | 2021-05-02T11:33:36.552000 | 2016-11-02T21:03:42 | 2016-11-02T21:03:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cs3500.music.model;
import java.util.List;
import java.util.ArrayList;
import cs3500.music.util.CompositionBuilder;
/**
* Represents a MusicModel, which is a list of Pitch objects.
*/
public class MusicModel implements IMusicModel {
private List<Pitch> pitches;
private int tempo;
/**
* Constructor for MusicModel, if list of pitches contains duplicates,
* it will only add the first one.
*
* @param pitches list of pitches to add to the MusicModel
* @throws IllegalArgumentException if a pitch has invalid pitch, octave, or notes
*/
public MusicModel(List<Pitch> pitches, int tempo) {
this.pitches = new ArrayList<Pitch>();
for (Pitch p: pitches) {
if (p.getPitch() < 1 || p.getPitch() > 12) {
throw new IllegalArgumentException("Pitch integer must be between 1 and 12.");
}
if (p.getOctave() < 0) {
throw new IllegalArgumentException("Octaves cannot be below 0.");
}
for (int i = 0; i < p.getNotes().size(); i++) {
if (p.getNotes().get(i) < 0 || p.getNotes().get(i) > 2) {
throw new IllegalArgumentException("Pitch notes can only be 0, 1, or 2.");
}
}
if (!(this.pitches.contains(p))) {
this.pitches.add(p);
}
}
this.tempo = tempo;
}
@Override
public int getTempo() {
return this.tempo;
}
@Override
public void setTempo(int t) {
this.tempo = t;
}
@Override
public Pitch getPitch(int pitch, int octave) {
Pitch p = new Pitch(pitch, octave);
for (Pitch a : this.pitches) {
if (a.equals(p)) {
return a;
}
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
/**
* Takes a Pitch object, returns a corresponding Pitch object from this MusicModel.
*
* @param p a Pitch object for the desired Pitch in the MusicModel
* @return a Pitch object matching the given Pitch
* @throws IllegalArgumentException if the MusicModel does not contain the given Pitch
*/
public Pitch getPitch(Pitch p) {
for (Pitch a : this.pitches) {
if (a.equals(p)) {
return a;
}
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
@Override
public List<Pitch> getPitches() {
return this.pitches;
}
@Override
public void addNote(int pitch, int octave, int beat, int duration) {
Pitch p = new Pitch(pitch, octave);
if (this.pitches.contains(p)) {
this.getPitch(pitch, octave).addNote(beat, duration);
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
@Override
public void addNote(Pitch p, int beat, int duration) {
if (this.pitches.contains(p)) {
this.getPitch(p).addNote(beat, duration);
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
@Override
public void addNotes(int pitch, int octave, List<Integer> notes) {
Pitch p = new Pitch(pitch, octave);
if (this.pitches.contains(p)) {
this.getPitch(pitch, octave).addNotes(notes);
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
@Override
public void addNotes(Pitch p, List<Integer> notes) {
if (this.pitches.contains(p)) {
this.getPitch(p).addNotes(notes);
} else {
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
}
@Override
public void addPitch(Pitch p) {
if (this.pitches.contains(p)) {
throw new IllegalArgumentException("MusicModel already contains this Pitch.");
} else {
this.pitches.add(p);
}
}
@Override
public void removePitch(Pitch p) {
for (int i = 0; i < this.pitches.size(); i++) {
Pitch a = this.pitches.get(i);
if (a.equals(p)) {
this.pitches.remove(i);
return;
}
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
@Override
public void combineMusicModelSimultaneous(IMusicModel s) {
for (Pitch p : s.getPitches()) {
if (this.pitches.contains(p)) {
this.removePitch(p);
this.pitches.add(p);
} else {
this.pitches.add(p);
}
}
}
@Override
public void combineMusicModelConsecutive(IMusicModel s) {
int max = this.maxBeats();
for (int i = 0; i < this.pitches.size(); i++) {
List<Integer> empty = new ArrayList<Integer>();
Pitch p = this.pitches.get(i);
int loop = max - p.getNotes().size();
for (int a = 0; a < loop; a++) {
empty.add(0);
}
this.addNotes(p, empty);
}
for (Pitch p : s.getPitches()) {
List<Integer> empty = new ArrayList<Integer>();
if (this.pitches.contains(p)) {
this.addNotes(p, p.getNotes());
} else {
for (int a = 0; a < max; a++) {
empty.add(0);
}
empty.addAll(p.getNotes());
p.setNotes(empty);
this.pitches.add(p);
}
}
}
/**
* Iterates through all the pitches and finds the longest one.
*
* @return the largest number of beats in any Pitch
**/
private int maxBeats() {
int max = 0;
for (Pitch p : this.pitches) {
if (p.getNotes().size() > max) {
max = p.getNotes().size();
}
}
return max;
}
/**
* Builder for MusicModels
*/
public static final class Builder implements CompositionBuilder<IMusicModel> {
private List<Pitch> notes;
private int tempo;
/**
* Constructs a new Song Builder object
*/
public Builder() {
this.notes = new ArrayList<Pitch>();
this.tempo = 120;
}
/**
* Constructs an actual composition, given the notes that have been added
*
* @return The new composition
*/
@Override
public IMusicModel build() {
return new MusicModel(this.notes, this.tempo);
}
/**
* Sets the tempo of the piece
*
* @param tempo The speed, in microseconds per beat
* @return This builder
*/
@Override
public CompositionBuilder<IMusicModel> setTempo(int tempo) {
this.tempo = tempo;
return this;
}
/**
* Adds a new note to the piece
*
* @param start The start time of the note, in beats
* @param end The end time of the note, in beats
* @param instrument The instrument number (to be interpreted by MIDI)
* @param pitch The pitch (in the range [0, 127], where 60 represents C4, the middle-C on a
* piano)
* @param volume The volume (in the range [0, 127])
*/
@Override
public CompositionBuilder<IMusicModel> addNote(int start, int end, int instrument, int pitch, int volume) {
int realPitch = (pitch % 12) + 1;
int realOctave = (int) Math.floor(pitch / 12) - 1;
Pitch checkPitch = new Pitch(realPitch, realOctave);
int duration = end - start - 1;
if (this.notes.contains(checkPitch)) {
for (Pitch p : this.notes) {
if (p.equals(checkPitch)) {
p.addNote(start, duration);
}
}
} else {
checkPitch.addNote(start, duration);
this.notes.add(checkPitch);
}
return this;
}
}
} | UTF-8 | Java | 7,257 | java | MusicModel.java | Java | [] | null | [] | package cs3500.music.model;
import java.util.List;
import java.util.ArrayList;
import cs3500.music.util.CompositionBuilder;
/**
* Represents a MusicModel, which is a list of Pitch objects.
*/
public class MusicModel implements IMusicModel {
private List<Pitch> pitches;
private int tempo;
/**
* Constructor for MusicModel, if list of pitches contains duplicates,
* it will only add the first one.
*
* @param pitches list of pitches to add to the MusicModel
* @throws IllegalArgumentException if a pitch has invalid pitch, octave, or notes
*/
public MusicModel(List<Pitch> pitches, int tempo) {
this.pitches = new ArrayList<Pitch>();
for (Pitch p: pitches) {
if (p.getPitch() < 1 || p.getPitch() > 12) {
throw new IllegalArgumentException("Pitch integer must be between 1 and 12.");
}
if (p.getOctave() < 0) {
throw new IllegalArgumentException("Octaves cannot be below 0.");
}
for (int i = 0; i < p.getNotes().size(); i++) {
if (p.getNotes().get(i) < 0 || p.getNotes().get(i) > 2) {
throw new IllegalArgumentException("Pitch notes can only be 0, 1, or 2.");
}
}
if (!(this.pitches.contains(p))) {
this.pitches.add(p);
}
}
this.tempo = tempo;
}
@Override
public int getTempo() {
return this.tempo;
}
@Override
public void setTempo(int t) {
this.tempo = t;
}
@Override
public Pitch getPitch(int pitch, int octave) {
Pitch p = new Pitch(pitch, octave);
for (Pitch a : this.pitches) {
if (a.equals(p)) {
return a;
}
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
/**
* Takes a Pitch object, returns a corresponding Pitch object from this MusicModel.
*
* @param p a Pitch object for the desired Pitch in the MusicModel
* @return a Pitch object matching the given Pitch
* @throws IllegalArgumentException if the MusicModel does not contain the given Pitch
*/
public Pitch getPitch(Pitch p) {
for (Pitch a : this.pitches) {
if (a.equals(p)) {
return a;
}
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
@Override
public List<Pitch> getPitches() {
return this.pitches;
}
@Override
public void addNote(int pitch, int octave, int beat, int duration) {
Pitch p = new Pitch(pitch, octave);
if (this.pitches.contains(p)) {
this.getPitch(pitch, octave).addNote(beat, duration);
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
@Override
public void addNote(Pitch p, int beat, int duration) {
if (this.pitches.contains(p)) {
this.getPitch(p).addNote(beat, duration);
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
@Override
public void addNotes(int pitch, int octave, List<Integer> notes) {
Pitch p = new Pitch(pitch, octave);
if (this.pitches.contains(p)) {
this.getPitch(pitch, octave).addNotes(notes);
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
@Override
public void addNotes(Pitch p, List<Integer> notes) {
if (this.pitches.contains(p)) {
this.getPitch(p).addNotes(notes);
} else {
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
}
@Override
public void addPitch(Pitch p) {
if (this.pitches.contains(p)) {
throw new IllegalArgumentException("MusicModel already contains this Pitch.");
} else {
this.pitches.add(p);
}
}
@Override
public void removePitch(Pitch p) {
for (int i = 0; i < this.pitches.size(); i++) {
Pitch a = this.pitches.get(i);
if (a.equals(p)) {
this.pitches.remove(i);
return;
}
}
throw new IllegalArgumentException("MusicModel does not contain this pitch.");
}
@Override
public void combineMusicModelSimultaneous(IMusicModel s) {
for (Pitch p : s.getPitches()) {
if (this.pitches.contains(p)) {
this.removePitch(p);
this.pitches.add(p);
} else {
this.pitches.add(p);
}
}
}
@Override
public void combineMusicModelConsecutive(IMusicModel s) {
int max = this.maxBeats();
for (int i = 0; i < this.pitches.size(); i++) {
List<Integer> empty = new ArrayList<Integer>();
Pitch p = this.pitches.get(i);
int loop = max - p.getNotes().size();
for (int a = 0; a < loop; a++) {
empty.add(0);
}
this.addNotes(p, empty);
}
for (Pitch p : s.getPitches()) {
List<Integer> empty = new ArrayList<Integer>();
if (this.pitches.contains(p)) {
this.addNotes(p, p.getNotes());
} else {
for (int a = 0; a < max; a++) {
empty.add(0);
}
empty.addAll(p.getNotes());
p.setNotes(empty);
this.pitches.add(p);
}
}
}
/**
* Iterates through all the pitches and finds the longest one.
*
* @return the largest number of beats in any Pitch
**/
private int maxBeats() {
int max = 0;
for (Pitch p : this.pitches) {
if (p.getNotes().size() > max) {
max = p.getNotes().size();
}
}
return max;
}
/**
* Builder for MusicModels
*/
public static final class Builder implements CompositionBuilder<IMusicModel> {
private List<Pitch> notes;
private int tempo;
/**
* Constructs a new Song Builder object
*/
public Builder() {
this.notes = new ArrayList<Pitch>();
this.tempo = 120;
}
/**
* Constructs an actual composition, given the notes that have been added
*
* @return The new composition
*/
@Override
public IMusicModel build() {
return new MusicModel(this.notes, this.tempo);
}
/**
* Sets the tempo of the piece
*
* @param tempo The speed, in microseconds per beat
* @return This builder
*/
@Override
public CompositionBuilder<IMusicModel> setTempo(int tempo) {
this.tempo = tempo;
return this;
}
/**
* Adds a new note to the piece
*
* @param start The start time of the note, in beats
* @param end The end time of the note, in beats
* @param instrument The instrument number (to be interpreted by MIDI)
* @param pitch The pitch (in the range [0, 127], where 60 represents C4, the middle-C on a
* piano)
* @param volume The volume (in the range [0, 127])
*/
@Override
public CompositionBuilder<IMusicModel> addNote(int start, int end, int instrument, int pitch, int volume) {
int realPitch = (pitch % 12) + 1;
int realOctave = (int) Math.floor(pitch / 12) - 1;
Pitch checkPitch = new Pitch(realPitch, realOctave);
int duration = end - start - 1;
if (this.notes.contains(checkPitch)) {
for (Pitch p : this.notes) {
if (p.equals(checkPitch)) {
p.addNote(start, duration);
}
}
} else {
checkPitch.addNote(start, duration);
this.notes.add(checkPitch);
}
return this;
}
}
} | 7,257 | 0.606449 | 0.599559 | 262 | 26.70229 | 24.707663 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480916 | false | false | 9 |
6b4c198f51b088ed57884e42cff5c63ad7dc261e | 549,755,883,755 | 24ccb351a2e65b946bbd2f65b39485fd7d1a546d | /ekp/src/com/landray/kmss/common/model/IBaseCreateInfoModel.java | bbe648ef7a377939206952b5257228dad528a34d | [] | no_license | cliveyao/EKPV12 | https://github.com/cliveyao/EKPV12 | 1c56389b81a6047a38e2779c18dc63cbfbfc5736 | 51285e960899cd838431b045196ee7546830843d | refs/heads/master | 2021-06-20T18:19:19.646000 | 2017-07-07T02:23:36 | 2017-07-07T02:23:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.landray.kmss.common.model;
import java.util.Date;
import com.landray.kmss.sys.organization.model.SysOrgPerson;
public interface IBaseCreateInfoModel {
public abstract Date getDocCreateTime();
public abstract void setDocCreateTime(Date createTime);
public abstract SysOrgPerson getDocCreator();
public abstract void setDocCreator(SysOrgPerson creator);
} | UTF-8 | Java | 377 | java | IBaseCreateInfoModel.java | Java | [] | null | [] | package com.landray.kmss.common.model;
import java.util.Date;
import com.landray.kmss.sys.organization.model.SysOrgPerson;
public interface IBaseCreateInfoModel {
public abstract Date getDocCreateTime();
public abstract void setDocCreateTime(Date createTime);
public abstract SysOrgPerson getDocCreator();
public abstract void setDocCreator(SysOrgPerson creator);
} | 377 | 0.816976 | 0.816976 | 17 | 21.235294 | 23.863655 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 9 |
b35e28685b93fd6a1e096b1461813defbdc313af | 11,982,958,782,323 | 8c6e1e98e49ffe041cd585ab73d185276645e344 | /Pulcer/src/com/me/pulcer/entity/UpdateStatus.java | 230dc84a9a8dc046dba59866fbb4b0e9d20f2354 | [] | no_license | JKTChua/Pulcer | https://github.com/JKTChua/Pulcer | 0a35b43c553d52b5aa6c84d75da5da572454eed3 | e213134fff28f278a857aa88fbd32c45418003e9 | refs/heads/master | 2021-01-19T22:33:43.699000 | 2013-04-02T23:25:58 | 2019-02-26T22:40:06 | 8,043,123 | 0 | 0 | null | false | 2013-03-19T23:01:28 | 2013-02-06T02:35:51 | 2013-03-19T23:01:28 | 2013-03-19T22:53:55 | 30,812 | null | 0 | 0 | Java | null | null | package com.me.pulcer.entity;
import com.google.gson.annotations.SerializedName;
import com.the9tcat.hadi.annotation.Column;
import com.the9tcat.hadi.annotation.Table;
@Table(name="update_status_log")
public class UpdateStatus {
@SerializedName("reminder_id")
@Column(name="reminder_id",primary=true)
public int reminderId;
@SerializedName("user_id")
@Column(name="user_id")
public int userId;
@SerializedName("date")
@Column(name="date_stamp")
public long dateStamp;
@SerializedName("status")
@Column(name="status")
public String status;
@SerializedName("lat")
@Column(name="lat")
public double lat;
@SerializedName("lng")
@Column(name="lng")
public double lng;
}
| UTF-8 | Java | 731 | java | UpdateStatus.java | Java | [] | null | [] | package com.me.pulcer.entity;
import com.google.gson.annotations.SerializedName;
import com.the9tcat.hadi.annotation.Column;
import com.the9tcat.hadi.annotation.Table;
@Table(name="update_status_log")
public class UpdateStatus {
@SerializedName("reminder_id")
@Column(name="reminder_id",primary=true)
public int reminderId;
@SerializedName("user_id")
@Column(name="user_id")
public int userId;
@SerializedName("date")
@Column(name="date_stamp")
public long dateStamp;
@SerializedName("status")
@Column(name="status")
public String status;
@SerializedName("lat")
@Column(name="lat")
public double lat;
@SerializedName("lng")
@Column(name="lng")
public double lng;
}
| 731 | 0.701778 | 0.699042 | 34 | 19.5 | 14.063407 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 9 |
36fbecaeb6db71f216ae3561bfc05ecdbaa1918f | 32,615,981,680,926 | ed1465b4e592d78f3f4b0ee5b9603d844c6c4858 | /homeworks/src/alexandermelnychuk/homework1/LabWork142.java | 64f1fd6469717ce108caf552ddfc29cd0ce711e3 | [] | no_license | PBaranovskyi/learningJava | https://github.com/PBaranovskyi/learningJava | 9dbee024c58009b40191ed6589ee7bbd6b16ae61 | 7d34e6a7195d9b845ea104d6d05333f5c8be7513 | refs/heads/master | 2021-01-19T00:28:49.526000 | 2017-09-18T15:38:20 | 2017-09-18T15:38:20 | 87,173,899 | 0 | 0 | null | false | 2017-06-23T14:10:18 | 2017-04-04T10:26:45 | 2017-04-04T10:46:45 | 2017-06-23T03:51:10 | 419 | 0 | 0 | 24 | Java | null | null | package alexandermelnychuk.homework1;
//Task: Write a console program that prints result of each of arithmetic operations (+, -, /, *, %) for two variables of primitive data types.
public class LabWork142 {
public static void main(String[] args) {
int firstIntValue = 1986;
int secondIntValue = 5;
System.out.println("firstIntValue + secondIntValue = " + (firstIntValue + secondIntValue));
System.out.println("firstIntValue - secondIntValue = " + (firstIntValue - secondIntValue));
System.out.println("firstIntValue / secondIntValue = " + ((float) firstIntValue / (float) secondIntValue));
System.out.println("firstIntValue * secondIntValue = " + (firstIntValue * secondIntValue));
System.out.println("firstIntValue % secondIntValue = " + (firstIntValue % secondIntValue));
}
}
| UTF-8 | Java | 846 | java | LabWork142.java | Java | [
{
"context": "package alexandermelnychuk.homework1;\n\n//Task: Write a cons",
"end": 9,
"score": 0.8124487996101379,
"start": 8,
"tag": "USERNAME",
"value": "a"
},
{
"context": "package alexandermelnychuk.homework1;\n\n//Task: Write a console program ",
"end": 21,
"score": 0.... | null | [] | package alexandermelnychuk.homework1;
//Task: Write a console program that prints result of each of arithmetic operations (+, -, /, *, %) for two variables of primitive data types.
public class LabWork142 {
public static void main(String[] args) {
int firstIntValue = 1986;
int secondIntValue = 5;
System.out.println("firstIntValue + secondIntValue = " + (firstIntValue + secondIntValue));
System.out.println("firstIntValue - secondIntValue = " + (firstIntValue - secondIntValue));
System.out.println("firstIntValue / secondIntValue = " + ((float) firstIntValue / (float) secondIntValue));
System.out.println("firstIntValue * secondIntValue = " + (firstIntValue * secondIntValue));
System.out.println("firstIntValue % secondIntValue = " + (firstIntValue % secondIntValue));
}
}
| 846 | 0.692671 | 0.682033 | 17 | 48.764706 | 47.386433 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705882 | false | false | 9 |
62c23a08ed29b35ecbbadb245acd8570515f27ce | 5,317,169,533,693 | 5cafab5f056849fc8ed94b30bbeb0672bc42dd81 | /src/main/java/com/winit/core/configuration/syncer/VCSFileSyncer.java | dbd783b366d5e0e57607cfc6a9262e28b32807f6 | [] | no_license | Winit-beijing-dev-A/beetle-api | https://github.com/Winit-beijing-dev-A/beetle-api | 1a02511a0a1e830f97a74e4807fd992347a0de51 | fa392aaf347bf1c93d309b7d00dfb00c0d504054 | refs/heads/master | 2021-01-10T23:55:03.874000 | 2016-12-19T06:42:14 | 2016-12-19T06:42:14 | 70,786,571 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.winit.core.configuration.syncer;
import com.winit.core.ci.vcs.VCS;
import com.winit.core.ci.vcs.exception.VCSException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by wangjian on 16/8/4.
*/
public class VCSFileSyncer implements ConfigFileSyncer {
private static final Logger logger = LoggerFactory.getLogger(VCSFileSyncer.class);
private VCS vcs;
public VCSFileSyncer(VCS vcs){
this.vcs = vcs;
}
@Override
public void doSynce() {
try {
this.vcs.doUpdate();
} catch (VCSException e) {
e.printStackTrace();
logger.error("更新configuration异常,e:"+e.getMessage());
}
}
}
| UTF-8 | Java | 715 | java | VCSFileSyncer.java | Java | [
{
"context": "import org.slf4j.LoggerFactory;\n\n/**\n * Created by wangjian on 16/8/4.\n */\npublic class VCSFileSyncer impleme",
"end": 217,
"score": 0.9991996884346008,
"start": 209,
"tag": "USERNAME",
"value": "wangjian"
}
] | null | [] | package com.winit.core.configuration.syncer;
import com.winit.core.ci.vcs.VCS;
import com.winit.core.ci.vcs.exception.VCSException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by wangjian on 16/8/4.
*/
public class VCSFileSyncer implements ConfigFileSyncer {
private static final Logger logger = LoggerFactory.getLogger(VCSFileSyncer.class);
private VCS vcs;
public VCSFileSyncer(VCS vcs){
this.vcs = vcs;
}
@Override
public void doSynce() {
try {
this.vcs.doUpdate();
} catch (VCSException e) {
e.printStackTrace();
logger.error("更新configuration异常,e:"+e.getMessage());
}
}
}
| 715 | 0.65488 | 0.646393 | 30 | 22.566668 | 21.764931 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 9 |
0dfdefa33575220b3780e2146c45fbed062b76cd | 17,171,279,307,126 | dc76b72577d9a45c1d6827e85302bc1659f3fa48 | /GooglePlay74/src/com/itheima/googleplay74/ui/holder/SubjectHolder.java | e776a642aa23d626a25008347b83b78eff41c225 | [] | no_license | obmitguo/simple-demo | https://github.com/obmitguo/simple-demo | 4008920074a09deb05a32559486bae965124c1ae | 97567d64084dbbda3e63ac9db7ef538d354637a0 | refs/heads/master | 2021-01-01T17:06:33.473000 | 2017-07-22T02:13:37 | 2017-07-22T02:13:37 | 97,997,018 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itheima.googleplay74.ui.holder;
import com.itheima.googleplay74.R;
import com.itheima.googleplay74.Http.HttpHelper;
import com.itheima.googleplay74.doman.SubjectInfo;
import com.itheima.googleplay74.utils.BitmapHelper;
import com.itheima.googleplay74.utils.UIUtils;
import com.lidroid.xutils.BitmapUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class SubjectHolder extends BaseHolder<SubjectInfo> {
private BitmapUtils bitmap;
private TextView title;
private ImageView picture;
@Override
public View initView() {
View subject = UIUtils.inflate(R.layout.list_item_subject);
title = (TextView) subject.findViewById(R.id.tv_title);
picture = (ImageView) subject.findViewById(R.id.iv_pic);
//得到bitmap对像
bitmap = BitmapHelper.getBitmapUtils();
return subject;
}
@Override
public void refreshView(SubjectInfo data) {
title.setText(data.des);
bitmap.display(picture, HttpHelper.URL+"image?name="+data.url);
}
}
| UTF-8 | Java | 1,051 | java | SubjectHolder.java | Java | [] | null | [] | package com.itheima.googleplay74.ui.holder;
import com.itheima.googleplay74.R;
import com.itheima.googleplay74.Http.HttpHelper;
import com.itheima.googleplay74.doman.SubjectInfo;
import com.itheima.googleplay74.utils.BitmapHelper;
import com.itheima.googleplay74.utils.UIUtils;
import com.lidroid.xutils.BitmapUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class SubjectHolder extends BaseHolder<SubjectInfo> {
private BitmapUtils bitmap;
private TextView title;
private ImageView picture;
@Override
public View initView() {
View subject = UIUtils.inflate(R.layout.list_item_subject);
title = (TextView) subject.findViewById(R.id.tv_title);
picture = (ImageView) subject.findViewById(R.id.iv_pic);
//得到bitmap对像
bitmap = BitmapHelper.getBitmapUtils();
return subject;
}
@Override
public void refreshView(SubjectInfo data) {
title.setText(data.des);
bitmap.display(picture, HttpHelper.URL+"image?name="+data.url);
}
}
| 1,051 | 0.75743 | 0.745925 | 36 | 26.972221 | 21.300087 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.277778 | false | false | 9 |
e7f8905255bfde951135162c4cc38bf2390e8631 | 17,171,279,311,124 | 7701d3b9456988cb164482f79fd2fde7307769ba | /Demo/Session11/CS105-Session11-Ex-BankApp/src/main/java/edu/sbcc/cs105/bankmodel/TransactionType.java | de4a36f5bbb4cfc2ef3bb4f97df72844a3d1539f | [] | no_license | daparducci/cs105-code | https://github.com/daparducci/cs105-code | 2fa84ed817ac93b6717baabae9e40303551c02e0 | 4a8bbfa66f5d890c9ba3b070d14c7cca0b6524b4 | refs/heads/master | 2022-12-29T03:58:03.376000 | 2020-10-01T23:55:17 | 2020-10-01T23:55:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.sbcc.cs105.bankmodel;
public enum TransactionType {
ACH_DEBIT,
CASH,
CHECK,
DEPOSIT,
DIVIDEND_CREDIT,
FEE,
TRANSFER
}
| UTF-8 | Java | 139 | java | TransactionType.java | Java | [] | null | [] | package edu.sbcc.cs105.bankmodel;
public enum TransactionType {
ACH_DEBIT,
CASH,
CHECK,
DEPOSIT,
DIVIDEND_CREDIT,
FEE,
TRANSFER
}
| 139 | 0.733813 | 0.71223 | 11 | 11.636364 | 10.191554 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.363636 | false | false | 9 |
7f953e318876991d38470a958652d96249aba32e | 24,318,104,895,260 | 160812e568216171fbb77d85785ff5dee82da3cf | /src/Condicion.java | 4f80359623ed3fcf840eb533a2fa06a03c00fb4c | [] | no_license | vickydr04/prog2 | https://github.com/vickydr04/prog2 | 77cfa8ef407b489b96e0a60299142e181c5e1a68 | bd2ef40c3f3d265de66469a29441c380cbb81ac8 | refs/heads/master | 2020-09-18T17:11:31.919000 | 2016-10-26T21:44:01 | 2016-10-26T21:44:01 | 67,439,152 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public abstract class Condicion {
public Condicion() {
}
public abstract boolean cumple(Pista p);
}
| UTF-8 | Java | 111 | java | Condicion.java | Java | [] | null | [] |
public abstract class Condicion {
public Condicion() {
}
public abstract boolean cumple(Pista p);
}
| 111 | 0.684685 | 0.684685 | 9 | 11.222222 | 15.229925 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 9 |
f43297b0ffa7e67c4b3e21e8e8bcab337287a04d | 10,557,029,632,201 | 1bd425caa90c8f6d2756330a9f5fda840d043545 | /java dee/src/com/itechart/phonny/model/entity/PhoneRecord.java | ed741a90d26e9b4bb613bb12b457d2b792a9c375 | [] | no_license | kfs/itc | https://github.com/kfs/itc | 87d33b27da4c5b082b7693672aa58fc17e789795 | 541e5d9ec8838c91a3d6cce8ac1e6616ff2fd4e4 | refs/heads/master | 2021-01-10T20:04:48.869000 | 2014-02-26T19:22:28 | 2014-02-26T19:22:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itechart.phonny.model.entity;
import java.util.Date;
import java.util.List;
public class PhoneRecord {
private String firstName;
private String patronymic;
private String surname;
private String webSite;
private String email;
private Date birthDate;
private Gender gender;
private MaritalStatus maritalStatus;
private Workplace workplace;
private Address address;
private List<Attachment> attachments;
private List<ContactPhone> contactPhones;
public PhoneRecord() {
super();
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getWebSite() {
return webSite;
}
public void setWebSite(String webSite) {
this.webSite = webSite;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public MaritalStatus getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(MaritalStatus maritalStatus) {
this.maritalStatus = maritalStatus;
}
public Workplace getWorkplace() {
return workplace;
}
public void setWorkplace(Workplace workplace) {
this.workplace = workplace;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public List<ContactPhone> getContactPhones() {
return contactPhones;
}
public void setContactPhones(List<ContactPhone> contactPhones) {
this.contactPhones = contactPhones;
}
public String getFullName() {
StringBuilder builder = new StringBuilder();
builder.append(firstName).append(' ')
.append(patronymic).append(' ')
.append(surname);
return builder.toString();
}
}
| UTF-8 | Java | 2,530 | java | PhoneRecord.java | Java | [] | null | [] | package com.itechart.phonny.model.entity;
import java.util.Date;
import java.util.List;
public class PhoneRecord {
private String firstName;
private String patronymic;
private String surname;
private String webSite;
private String email;
private Date birthDate;
private Gender gender;
private MaritalStatus maritalStatus;
private Workplace workplace;
private Address address;
private List<Attachment> attachments;
private List<ContactPhone> contactPhones;
public PhoneRecord() {
super();
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getWebSite() {
return webSite;
}
public void setWebSite(String webSite) {
this.webSite = webSite;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public MaritalStatus getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(MaritalStatus maritalStatus) {
this.maritalStatus = maritalStatus;
}
public Workplace getWorkplace() {
return workplace;
}
public void setWorkplace(Workplace workplace) {
this.workplace = workplace;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public List<ContactPhone> getContactPhones() {
return contactPhones;
}
public void setContactPhones(List<ContactPhone> contactPhones) {
this.contactPhones = contactPhones;
}
public String getFullName() {
StringBuilder builder = new StringBuilder();
builder.append(firstName).append(' ')
.append(patronymic).append(' ')
.append(surname);
return builder.toString();
}
}
| 2,530 | 0.697628 | 0.697628 | 141 | 16.943262 | 17.006371 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.042553 | false | false | 9 |
9d7f01d87e759361f5f0c6ccfc7e4125cf0d1a8c | 1,589,137,960,455 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/28/28_5725690f9fd13925e751143b482334b03d583cf3/AApplyExpAssistantTC/28_5725690f9fd13925e751143b482334b03d583cf3_AApplyExpAssistantTC_s.java | ca3630b9ae6723263681955583b52a3e49544178 | [] | no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | package org.overture.typechecker.assistant.expression;
import java.util.List;
import org.overture.ast.definitions.PDefinition;
import org.overture.ast.expressions.AApplyExp;
import org.overture.ast.expressions.AFuncInstatiationExp;
import org.overture.ast.expressions.AVariableExp;
import org.overture.ast.expressions.PExp;
import org.overture.ast.lex.LexNameList;
import org.overture.ast.lex.LexNameToken;
import org.overture.ast.types.AFunctionType;
import org.overture.ast.types.AOperationType;
import org.overture.ast.types.PType;
import org.overture.ast.types.SMapType;
import org.overture.ast.types.SSeqType;
import org.overture.ast.util.Utils;
import org.overture.typechecker.TypeCheckInfo;
import org.overture.typechecker.TypeCheckerErrors;
import org.overture.typechecker.TypeComparator;
import org.overture.typechecker.assistant.type.PTypeAssistantTC;
public class AApplyExpAssistantTC {
public static PType functionApply(AApplyExp node, boolean isSimple, AFunctionType ft) {
List<PType> ptypes = ft.getParameters();
if (node.getArgs().size() > ptypes.size())
{
TypeCheckerErrors.concern(isSimple, 3059, "Too many arguments",node.getLocation(),node);
TypeCheckerErrors.detail2(isSimple, "Args", node.getArgs(), "Params", ptypes);
return ft.getResult();
}
else if (node.getArgs().size() < ptypes.size())
{
TypeCheckerErrors.concern(isSimple, 3060, "Too few arguments",node.getLocation(),node);
TypeCheckerErrors.detail2(isSimple, "Args", node.getArgs(), "Params", ptypes);
return ft.getResult();
}
int i=0;
for (PType at: node.getArgtypes())
{
PType pt = ptypes.get(i++);
if (!TypeComparator.compatible(pt, at))
{
TypeCheckerErrors.concern(isSimple, 3061, "Inappropriate type for argument " + i + ". (Expected: "+pt+" Actual: "+at+")",node.getLocation(),node);
// TypeCheckerErrors.detail2(isSimple, "Expect", pt, "Actual", at);
}
}
return ft.getResult();
}
public static PType operationApply(AApplyExp node, boolean isSimple,
AOperationType ot) {
List<PType> ptypes = ot.getParameters();
if (node.getArgs().size() > ptypes.size())
{
TypeCheckerErrors.concern(isSimple, 3062, "Too many arguments",node.getLocation(),node);
TypeCheckerErrors.detail2(isSimple, "Args", node.getArgs(), "Params", ptypes);
return ot.getResult();
}
else if (node.getArgs().size() < ptypes.size())
{
TypeCheckerErrors.concern(isSimple, 3063, "Too few arguments",node.getLocation(),node);
TypeCheckerErrors.detail2(isSimple, "Args", node.getArgs(), "Params", ptypes);
return ot.getResult();
}
int i=0;
for (PType at: node.getArgtypes())
{
PType pt = ptypes.get(i++);
if (!TypeComparator.compatible(pt, at))
{
TypeCheckerErrors.concern(isSimple, 3064, "Inappropriate type for argument " + i +". (Expected: "+pt+" Actual: "+at+")",node.getLocation(),node);
//TypeCheckerErrors.detail2(isSimple, "Expect", pt, "Actual", at);
}
}
return ot.getResult();
}
public static PType sequenceApply(AApplyExp node, boolean isSimple,
SSeqType seq) {
if (node.getArgs().size() != 1)
{
TypeCheckerErrors.concern(isSimple, 3055, "Sequence selector must have one argument",node.getLocation(),node);
}
else if (!PTypeAssistantTC.isNumeric(node.getArgtypes().get(0)))
{
TypeCheckerErrors.concern(isSimple, 3056, "Sequence application argument must be numeric",node.getLocation(),node);
}
else if (seq.getEmpty())
{
TypeCheckerErrors.concern(isSimple, 3268, "Empty sequence cannot be applied",node.getLocation(),node);
}
return seq.getSeqof();
}
public static PType mapApply(AApplyExp node, boolean isSimple, SMapType map) {
if (node.getArgs().size() != 1)
{
TypeCheckerErrors.concern(isSimple, 3057, "Map application must have one argument",node.getLocation(),node);
}
else if (map.getEmpty())
{
TypeCheckerErrors.concern(isSimple, 3267, "Empty map cannot be applied",node.getLocation(),node);
}
PType argtype = node.getArgtypes().get(0);
if (!TypeComparator.compatible(map.getFrom(), argtype))
{
TypeCheckerErrors.concern(isSimple, 3058, "Map application argument is incompatible type",node.getLocation(),node);
TypeCheckerErrors.detail2(isSimple, "Map domain", map.getFrom(), "Argument", argtype);
}
return map.getTo();
}
public static LexNameList getOldNames(AApplyExp expression) {
LexNameList list = PExpAssistantTC.getOldNames(expression.getArgs());
list.addAll( PExpAssistantTC.getOldNames(expression.getRoot()));
return list;
}
public static PDefinition getRecursiveDefinition(AApplyExp node, TypeCheckInfo question)
{
LexNameToken fname = null;
PExp root = node.getRoot();
if (root instanceof AApplyExp)
{
AApplyExp aexp = (AApplyExp) root;
return getRecursiveDefinition(aexp, question);
}
else if (root instanceof AVariableExp)
{
AVariableExp var = (AVariableExp) root;
fname = var.getName();
}
else if (root instanceof AFuncInstatiationExp)
{
AFuncInstatiationExp fie = (AFuncInstatiationExp) root;
if (fie.getExpdef() != null)
{
fname = fie.getExpdef().getName();
}
else if (fie.getImpdef() != null)
{
fname = fie.getImpdef().getName();
}
}
if (fname != null)
{
return question.env.findName(fname, question.scope);
}
else
{
return null;
}
}
public static String getMeasureApply(AApplyExp node, LexNameToken measure)
{
return getMeasureApply(node, measure, true);
}
/**
* Create a measure application string from this apply, turning the root function
* name into the measure name passed, and collapsing curried argument sets into one.
*/
public static String getMeasureApply(AApplyExp node, LexNameToken measure, boolean close)
{
String start = null;
PExp root = node.getRoot();
if (root instanceof AApplyExp)
{
AApplyExp aexp = (AApplyExp)root;
start = getMeasureApply(aexp, measure, false);
}
else if (root instanceof AVariableExp)
{
start = measure.getName() + "(";
}
else if (root instanceof AFuncInstatiationExp)
{
AFuncInstatiationExp fie = (AFuncInstatiationExp)root;
start = measure.getName() + "[" + Utils.listToString(fie.getActualTypes()) + "](";
}
else
{
start = root.toString() + "(";
}
return start + Utils.listToString(node.getArgs()) + (close ? ")" : ", ");
}
}
| UTF-8 | Java | 6,566 | java | 28_5725690f9fd13925e751143b482334b03d583cf3_AApplyExpAssistantTC_s.java | Java | [] | null | [] | package org.overture.typechecker.assistant.expression;
import java.util.List;
import org.overture.ast.definitions.PDefinition;
import org.overture.ast.expressions.AApplyExp;
import org.overture.ast.expressions.AFuncInstatiationExp;
import org.overture.ast.expressions.AVariableExp;
import org.overture.ast.expressions.PExp;
import org.overture.ast.lex.LexNameList;
import org.overture.ast.lex.LexNameToken;
import org.overture.ast.types.AFunctionType;
import org.overture.ast.types.AOperationType;
import org.overture.ast.types.PType;
import org.overture.ast.types.SMapType;
import org.overture.ast.types.SSeqType;
import org.overture.ast.util.Utils;
import org.overture.typechecker.TypeCheckInfo;
import org.overture.typechecker.TypeCheckerErrors;
import org.overture.typechecker.TypeComparator;
import org.overture.typechecker.assistant.type.PTypeAssistantTC;
public class AApplyExpAssistantTC {
public static PType functionApply(AApplyExp node, boolean isSimple, AFunctionType ft) {
List<PType> ptypes = ft.getParameters();
if (node.getArgs().size() > ptypes.size())
{
TypeCheckerErrors.concern(isSimple, 3059, "Too many arguments",node.getLocation(),node);
TypeCheckerErrors.detail2(isSimple, "Args", node.getArgs(), "Params", ptypes);
return ft.getResult();
}
else if (node.getArgs().size() < ptypes.size())
{
TypeCheckerErrors.concern(isSimple, 3060, "Too few arguments",node.getLocation(),node);
TypeCheckerErrors.detail2(isSimple, "Args", node.getArgs(), "Params", ptypes);
return ft.getResult();
}
int i=0;
for (PType at: node.getArgtypes())
{
PType pt = ptypes.get(i++);
if (!TypeComparator.compatible(pt, at))
{
TypeCheckerErrors.concern(isSimple, 3061, "Inappropriate type for argument " + i + ". (Expected: "+pt+" Actual: "+at+")",node.getLocation(),node);
// TypeCheckerErrors.detail2(isSimple, "Expect", pt, "Actual", at);
}
}
return ft.getResult();
}
public static PType operationApply(AApplyExp node, boolean isSimple,
AOperationType ot) {
List<PType> ptypes = ot.getParameters();
if (node.getArgs().size() > ptypes.size())
{
TypeCheckerErrors.concern(isSimple, 3062, "Too many arguments",node.getLocation(),node);
TypeCheckerErrors.detail2(isSimple, "Args", node.getArgs(), "Params", ptypes);
return ot.getResult();
}
else if (node.getArgs().size() < ptypes.size())
{
TypeCheckerErrors.concern(isSimple, 3063, "Too few arguments",node.getLocation(),node);
TypeCheckerErrors.detail2(isSimple, "Args", node.getArgs(), "Params", ptypes);
return ot.getResult();
}
int i=0;
for (PType at: node.getArgtypes())
{
PType pt = ptypes.get(i++);
if (!TypeComparator.compatible(pt, at))
{
TypeCheckerErrors.concern(isSimple, 3064, "Inappropriate type for argument " + i +". (Expected: "+pt+" Actual: "+at+")",node.getLocation(),node);
//TypeCheckerErrors.detail2(isSimple, "Expect", pt, "Actual", at);
}
}
return ot.getResult();
}
public static PType sequenceApply(AApplyExp node, boolean isSimple,
SSeqType seq) {
if (node.getArgs().size() != 1)
{
TypeCheckerErrors.concern(isSimple, 3055, "Sequence selector must have one argument",node.getLocation(),node);
}
else if (!PTypeAssistantTC.isNumeric(node.getArgtypes().get(0)))
{
TypeCheckerErrors.concern(isSimple, 3056, "Sequence application argument must be numeric",node.getLocation(),node);
}
else if (seq.getEmpty())
{
TypeCheckerErrors.concern(isSimple, 3268, "Empty sequence cannot be applied",node.getLocation(),node);
}
return seq.getSeqof();
}
public static PType mapApply(AApplyExp node, boolean isSimple, SMapType map) {
if (node.getArgs().size() != 1)
{
TypeCheckerErrors.concern(isSimple, 3057, "Map application must have one argument",node.getLocation(),node);
}
else if (map.getEmpty())
{
TypeCheckerErrors.concern(isSimple, 3267, "Empty map cannot be applied",node.getLocation(),node);
}
PType argtype = node.getArgtypes().get(0);
if (!TypeComparator.compatible(map.getFrom(), argtype))
{
TypeCheckerErrors.concern(isSimple, 3058, "Map application argument is incompatible type",node.getLocation(),node);
TypeCheckerErrors.detail2(isSimple, "Map domain", map.getFrom(), "Argument", argtype);
}
return map.getTo();
}
public static LexNameList getOldNames(AApplyExp expression) {
LexNameList list = PExpAssistantTC.getOldNames(expression.getArgs());
list.addAll( PExpAssistantTC.getOldNames(expression.getRoot()));
return list;
}
public static PDefinition getRecursiveDefinition(AApplyExp node, TypeCheckInfo question)
{
LexNameToken fname = null;
PExp root = node.getRoot();
if (root instanceof AApplyExp)
{
AApplyExp aexp = (AApplyExp) root;
return getRecursiveDefinition(aexp, question);
}
else if (root instanceof AVariableExp)
{
AVariableExp var = (AVariableExp) root;
fname = var.getName();
}
else if (root instanceof AFuncInstatiationExp)
{
AFuncInstatiationExp fie = (AFuncInstatiationExp) root;
if (fie.getExpdef() != null)
{
fname = fie.getExpdef().getName();
}
else if (fie.getImpdef() != null)
{
fname = fie.getImpdef().getName();
}
}
if (fname != null)
{
return question.env.findName(fname, question.scope);
}
else
{
return null;
}
}
public static String getMeasureApply(AApplyExp node, LexNameToken measure)
{
return getMeasureApply(node, measure, true);
}
/**
* Create a measure application string from this apply, turning the root function
* name into the measure name passed, and collapsing curried argument sets into one.
*/
public static String getMeasureApply(AApplyExp node, LexNameToken measure, boolean close)
{
String start = null;
PExp root = node.getRoot();
if (root instanceof AApplyExp)
{
AApplyExp aexp = (AApplyExp)root;
start = getMeasureApply(aexp, measure, false);
}
else if (root instanceof AVariableExp)
{
start = measure.getName() + "(";
}
else if (root instanceof AFuncInstatiationExp)
{
AFuncInstatiationExp fie = (AFuncInstatiationExp)root;
start = measure.getName() + "[" + Utils.listToString(fie.getActualTypes()) + "](";
}
else
{
start = root.toString() + "(";
}
return start + Utils.listToString(node.getArgs()) + (close ? ")" : ", ");
}
}
| 6,566 | 0.686567 | 0.677277 | 211 | 30.113745 | 32.545067 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.582938 | false | false | 9 |
a67f5ab217794f72d2be4c9530720ce313bebcba | 19,207,093,812,708 | 42ed1623d97adc9b03cb797d86ec72cf0cd3d352 | /HotContext/src/luz/winapi/constants/DIBwUsage.java | 607f7c83db4c2b8710cfedd05cf84421bee04b37 | [] | no_license | NormR/Android-Simple-Web-Server | https://github.com/NormR/Android-Simple-Web-Server | d5b1823c219770cb4d5601b8ca369ac17c4f3240 | 389295f7045bcb7589ac816e47ab8962d3957f75 | refs/heads/master | 2021-01-18T18:34:05.133000 | 2017-04-01T11:54:55 | 2017-04-01T11:54:55 | 86,862,532 | 13 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null | package luz.winapi.constants;
public enum DIBwUsage{
DIB_RGB_COLORS (0);
//DIB_PAL_COLORS ();
private int value;
DIBwUsage(int value) { this.value=value; }
public int getValue() { return value; }
} | UTF-8 | Java | 214 | java | DIBwUsage.java | Java | [] | null | [] | package luz.winapi.constants;
public enum DIBwUsage{
DIB_RGB_COLORS (0);
//DIB_PAL_COLORS ();
private int value;
DIBwUsage(int value) { this.value=value; }
public int getValue() { return value; }
} | 214 | 0.668224 | 0.663551 | 10 | 20.5 | 15.857175 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.4 | false | false | 9 |
9678f8b8309dc06545a7c1c994a66ebc7f033fae | 20,169,166,487,136 | c0c88662988743e16b57c7ecdfb7534a5cf4e905 | /src/main/java/pl/wlodarczyk/springregistersecurity/controller/MainController.java | 681c0db3c4c120dda00543fcca941ed8c2c28405 | [] | no_license | empios/SpringSecurityRegisterWithEmail | https://github.com/empios/SpringSecurityRegisterWithEmail | f05070199a7cf0ccdb447e8ae58fbb12b6506cc3 | 1bc8db04510b859e1f947a097a8c7b225a74e69e | refs/heads/master | 2021-03-05T11:29:10.039000 | 2020-03-19T13:07:03 | 2020-03-19T13:07:03 | 246,119,083 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.wlodarczyk.springregistersecurity.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import pl.wlodarczyk.springregistersecurity.models.User;
import pl.wlodarczyk.springregistersecurity.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class MainController {
private UserService userService;
@Autowired
public MainController(UserService userService) {
this.userService = userService;
}
@GetMapping("/forUser")
public String forUser() {
return "userpage";
}
@GetMapping("/forAdmin")
public String forAdmin() {
return "adminpage";
}
@RequestMapping("/login")
public String login(ModelAndView model,String error) {
model.addObject("error",error);
return "login";
}
@RequestMapping("/signup")
public ModelAndView signup() {
return new ModelAndView("register", "user", new User());
}
@RequestMapping("/register")
public ModelAndView register(User user, HttpServletRequest request) {
if(!userService.isExist(user))userService.addNewUser(user, request);
else return new ModelAndView("login", "error", "User already exist");
return new ModelAndView("login", "error", "");
}
@RequestMapping("/verify")
public String verify(@RequestParam String token){
userService.verify(token);
return "redirect:/login";
}
@RequestMapping("/verifyAdmin")
public String verifyAdmin(@RequestParam String token){
userService.verify(token);
return "redirect:/login";
}
@PostMapping("/forUser")
public void afterLogin(HttpServletResponse response) throws IOException {
response.sendRedirect("/forUser");
}
@GetMapping("/")
public String index(){
return "redirect:/login";
}
@GetMapping("login/error")
public ModelAndView loginError(){
return new ModelAndView("login","error","bad credentials");
}
}
| UTF-8 | Java | 2,439 | java | MainController.java | Java | [] | null | [] | package pl.wlodarczyk.springregistersecurity.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import pl.wlodarczyk.springregistersecurity.models.User;
import pl.wlodarczyk.springregistersecurity.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class MainController {
private UserService userService;
@Autowired
public MainController(UserService userService) {
this.userService = userService;
}
@GetMapping("/forUser")
public String forUser() {
return "userpage";
}
@GetMapping("/forAdmin")
public String forAdmin() {
return "adminpage";
}
@RequestMapping("/login")
public String login(ModelAndView model,String error) {
model.addObject("error",error);
return "login";
}
@RequestMapping("/signup")
public ModelAndView signup() {
return new ModelAndView("register", "user", new User());
}
@RequestMapping("/register")
public ModelAndView register(User user, HttpServletRequest request) {
if(!userService.isExist(user))userService.addNewUser(user, request);
else return new ModelAndView("login", "error", "User already exist");
return new ModelAndView("login", "error", "");
}
@RequestMapping("/verify")
public String verify(@RequestParam String token){
userService.verify(token);
return "redirect:/login";
}
@RequestMapping("/verifyAdmin")
public String verifyAdmin(@RequestParam String token){
userService.verify(token);
return "redirect:/login";
}
@PostMapping("/forUser")
public void afterLogin(HttpServletResponse response) throws IOException {
response.sendRedirect("/forUser");
}
@GetMapping("/")
public String index(){
return "redirect:/login";
}
@GetMapping("login/error")
public ModelAndView loginError(){
return new ModelAndView("login","error","bad credentials");
}
}
| 2,439 | 0.708077 | 0.708077 | 80 | 29.487499 | 23.478178 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525 | false | false | 9 |
2acff6d86d9882469568e48bdd07bad723616322 | 20,598,663,199,793 | ed10c1f0039dc0e0522185c182eb5c6299beeaa4 | /src/main/java/com/github/jonathanxd/adapter/visitor/ExtraFieldVisitor.java | 52002213bf6e2be72631e8e46a7935da63c172d6 | [
"MIT"
] | permissive | JonathanxD/Adapter | https://github.com/JonathanxD/Adapter | 754bd779de56720fbe5102e40073d54a26d11fa1 | cc17e4ccdfc5baf9bff396d3f35d35a1b498a0e2 | refs/heads/master | 2016-09-17T03:20:16.625000 | 2016-09-07T17:07:53 | 2016-09-07T17:07:53 | 56,453,045 | 0 | 0 | null | false | 2016-08-11T00:20:07 | 2016-04-17T18:58:11 | 2016-07-10T20:43:08 | 2016-08-11T00:20:06 | 850 | 0 | 0 | 0 | Java | null | null | /*
* Adapter - Class adapter! <https://github.com/JonathanxD/Adapter>
*
* The MIT License (MIT)
*
* Copyright (c) 2016 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/ & https://github.com/TheRealBuggy/) <jonathan.scripter@programmer.net>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.adapter.visitor;
import com.github.jonathanxd.adapter.generator.CodeAPIGenerator;
import com.github.jonathanxd.adapter.processing.ProcessingEnv;
import com.github.jonathanxd.adapter.processing.element.ProcessingElement;
import com.github.jonathanxd.adapter.processing.element.ProcessingTypes;
import com.github.jonathanxd.adapter.processing.priority.Priorities;
import com.github.jonathanxd.adapter.processing.priority.Priority;
import com.github.jonathanxd.adapter.processing.specs.SpecVisitor;
import com.github.jonathanxd.adapter.spec.ConstructorSpec;
import com.github.jonathanxd.adapter.spec.ExtraFieldSpec;
import com.github.jonathanxd.adapter.spec.ValueProviderSpec;
import com.github.jonathanxd.adapter.utils.call.CallInfoGenUtil;
import com.github.jonathanxd.adapter.utils.classu.CodeAPIUtil;
import com.github.jonathanxd.adapter.utils.spec.ValueProviderSpecUtil;
import com.github.jonathanxd.codeapi.CodeAPI;
import com.github.jonathanxd.codeapi.CodePart;
import com.github.jonathanxd.codeapi.CodeSource;
import com.github.jonathanxd.codeapi.common.CodeArgument;
import com.github.jonathanxd.codeapi.common.CodeParameter;
import com.github.jonathanxd.codeapi.helper.Helper;
import com.github.jonathanxd.codeapi.impl.CodeClass;
import com.github.jonathanxd.codeapi.impl.CodeConstructor;
import com.github.jonathanxd.codeapi.impl.CodeField;
import com.github.jonathanxd.codeapi.interfaces.MethodInvocation;
import com.github.jonathanxd.codeapi.interfaces.VariableDeclaration;
import com.github.jonathanxd.codeapi.types.CodeType;
import com.github.jonathanxd.iutils.optional.Require;
import java.util.Arrays;
import java.util.List;
/**
* Created by jonathan on 07/08/16.
*/
/**
* Visitor of {@link ExtraFieldSpec}. (Create extra fields and declare in constructor).
*/
public class ExtraFieldVisitor implements SpecVisitor<ExtraFieldSpec, CodeClass, Void> {
@Override
public Void visit(ExtraFieldSpec settings, CodeClass bodied, ProcessingElement element, ProcessingEnv processingEnv) throws Throwable {
if (element.getType() == ProcessingTypes.EXTRA_FIELD) {
// Get body of class
CodeSource classBody = Require.require(bodied.getBody());
// Create a extra field
CodeField field = CodeAPI.field(settings.getModifiers(), settings.getType(), settings.getName());
// Add field to body
classBody.add(field);
}
return null;
}
@Override
public void endVisit(ExtraFieldSpec settings, CodeClass bodied, ProcessingElement element, ProcessingEnv processingEnv, Void result) throws Throwable {
}
public static class Constructor implements SpecVisitor<ConstructorSpec, CodeConstructor, Void> {
@Override
public Void visit(ConstructorSpec settings, CodeConstructor bodied, ProcessingElement element, ProcessingEnv processingEnv) throws Throwable {
if (element.getType() != ProcessingTypes.CODE_CONSTRUCTOR_AFTER_DECLARATION)
return null;
CodeSource constructorBody = Require.require(bodied.getBody());
constructorBody.add(CallInfoGenUtil.createCallInfoField(processingEnv, bodied));
CodeClass declaration = processingEnv.getData()
.getOptional(CodeAPIGenerator.CODE_CLASS)
.orElseThrow(() -> new IllegalStateException("Cannot find CodeClass!"));
List<CodeParameter> constructorParameters = bodied.getParameters();
CodeArgument[] extraArguments;
if (constructorParameters.size() > 1) {
extraArguments = CodeAPIUtil.argumentsFromParameters(constructorParameters.subList(1, constructorParameters.size()).stream().toArray(CodeParameter[]::new));
} else {
extraArguments = new CodeArgument[0];
}
CodeArgument[] arguments = extraArguments;
CodeType[] types = Arrays.stream(extraArguments).map(CodeArgument::getType).toArray(CodeType[]::new);
processingEnv.getProcessedSpecifications().stream()
.filter(processed -> processed instanceof ExtraFieldSpec)
.map(processed -> (ExtraFieldSpec) processed)
.forEach(extraField -> {
ValueProviderSpec value = extraField.getValue();
CodePart invocation = ValueProviderSpecUtil.toInvocation(value,
Helper.getJavaType(extraField.getType()),
types,
arguments);
VariableDeclaration set = Helper.setThisVariable(extraField.getName(), extraField.getType(), invocation);
constructorBody.add(set);
});
return null;
}
@Override
public void endVisit(ConstructorSpec settings, CodeConstructor bodied, ProcessingElement element, ProcessingEnv processingEnv, Void result) throws Throwable {
}
@Override
public Priority getPriority() {
return Priorities.HIGH;
}
}
}
| UTF-8 | Java | 6,635 | java | ExtraFieldVisitor.java | Java | [
{
"context": " Adapter - Class adapter! <https://github.com/JonathanxD/Adapter>\n *\n * The MIT License (MIT)\n *\n ",
"end": 66,
"score": 0.9981076121330261,
"start": 56,
"tag": "USERNAME",
"value": "JonathanxD"
},
{
"context": " (MIT)\n *\n * Copyright (c) 2016 The... | null | [] | /*
* Adapter - Class adapter! <https://github.com/JonathanxD/Adapter>
*
* The MIT License (MIT)
*
* Copyright (c) 2016 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/ & https://github.com/TheRealBuggy/) <<EMAIL>>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.jonathanxd.adapter.visitor;
import com.github.jonathanxd.adapter.generator.CodeAPIGenerator;
import com.github.jonathanxd.adapter.processing.ProcessingEnv;
import com.github.jonathanxd.adapter.processing.element.ProcessingElement;
import com.github.jonathanxd.adapter.processing.element.ProcessingTypes;
import com.github.jonathanxd.adapter.processing.priority.Priorities;
import com.github.jonathanxd.adapter.processing.priority.Priority;
import com.github.jonathanxd.adapter.processing.specs.SpecVisitor;
import com.github.jonathanxd.adapter.spec.ConstructorSpec;
import com.github.jonathanxd.adapter.spec.ExtraFieldSpec;
import com.github.jonathanxd.adapter.spec.ValueProviderSpec;
import com.github.jonathanxd.adapter.utils.call.CallInfoGenUtil;
import com.github.jonathanxd.adapter.utils.classu.CodeAPIUtil;
import com.github.jonathanxd.adapter.utils.spec.ValueProviderSpecUtil;
import com.github.jonathanxd.codeapi.CodeAPI;
import com.github.jonathanxd.codeapi.CodePart;
import com.github.jonathanxd.codeapi.CodeSource;
import com.github.jonathanxd.codeapi.common.CodeArgument;
import com.github.jonathanxd.codeapi.common.CodeParameter;
import com.github.jonathanxd.codeapi.helper.Helper;
import com.github.jonathanxd.codeapi.impl.CodeClass;
import com.github.jonathanxd.codeapi.impl.CodeConstructor;
import com.github.jonathanxd.codeapi.impl.CodeField;
import com.github.jonathanxd.codeapi.interfaces.MethodInvocation;
import com.github.jonathanxd.codeapi.interfaces.VariableDeclaration;
import com.github.jonathanxd.codeapi.types.CodeType;
import com.github.jonathanxd.iutils.optional.Require;
import java.util.Arrays;
import java.util.List;
/**
* Created by jonathan on 07/08/16.
*/
/**
* Visitor of {@link ExtraFieldSpec}. (Create extra fields and declare in constructor).
*/
public class ExtraFieldVisitor implements SpecVisitor<ExtraFieldSpec, CodeClass, Void> {
@Override
public Void visit(ExtraFieldSpec settings, CodeClass bodied, ProcessingElement element, ProcessingEnv processingEnv) throws Throwable {
if (element.getType() == ProcessingTypes.EXTRA_FIELD) {
// Get body of class
CodeSource classBody = Require.require(bodied.getBody());
// Create a extra field
CodeField field = CodeAPI.field(settings.getModifiers(), settings.getType(), settings.getName());
// Add field to body
classBody.add(field);
}
return null;
}
@Override
public void endVisit(ExtraFieldSpec settings, CodeClass bodied, ProcessingElement element, ProcessingEnv processingEnv, Void result) throws Throwable {
}
public static class Constructor implements SpecVisitor<ConstructorSpec, CodeConstructor, Void> {
@Override
public Void visit(ConstructorSpec settings, CodeConstructor bodied, ProcessingElement element, ProcessingEnv processingEnv) throws Throwable {
if (element.getType() != ProcessingTypes.CODE_CONSTRUCTOR_AFTER_DECLARATION)
return null;
CodeSource constructorBody = Require.require(bodied.getBody());
constructorBody.add(CallInfoGenUtil.createCallInfoField(processingEnv, bodied));
CodeClass declaration = processingEnv.getData()
.getOptional(CodeAPIGenerator.CODE_CLASS)
.orElseThrow(() -> new IllegalStateException("Cannot find CodeClass!"));
List<CodeParameter> constructorParameters = bodied.getParameters();
CodeArgument[] extraArguments;
if (constructorParameters.size() > 1) {
extraArguments = CodeAPIUtil.argumentsFromParameters(constructorParameters.subList(1, constructorParameters.size()).stream().toArray(CodeParameter[]::new));
} else {
extraArguments = new CodeArgument[0];
}
CodeArgument[] arguments = extraArguments;
CodeType[] types = Arrays.stream(extraArguments).map(CodeArgument::getType).toArray(CodeType[]::new);
processingEnv.getProcessedSpecifications().stream()
.filter(processed -> processed instanceof ExtraFieldSpec)
.map(processed -> (ExtraFieldSpec) processed)
.forEach(extraField -> {
ValueProviderSpec value = extraField.getValue();
CodePart invocation = ValueProviderSpecUtil.toInvocation(value,
Helper.getJavaType(extraField.getType()),
types,
arguments);
VariableDeclaration set = Helper.setThisVariable(extraField.getName(), extraField.getType(), invocation);
constructorBody.add(set);
});
return null;
}
@Override
public void endVisit(ConstructorSpec settings, CodeConstructor bodied, ProcessingElement element, ProcessingEnv processingEnv, Void result) throws Throwable {
}
@Override
public Priority getPriority() {
return Priorities.HIGH;
}
}
}
| 6,610 | 0.703693 | 0.701733 | 154 | 42.084415 | 40.152946 | 172 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false | 9 |
83738748ed78648539413bf15a6b5dbea0d54859 | 33,139,967,710,199 | c0c3900669edadfa20184aa4639c5ce162b9bb1a | /part4.java | 2e059373b94ca715b928e98034a2665d3c8ebcb4 | [] | no_license | michikofeehan/FindingGenes | https://github.com/michikofeehan/FindingGenes | f9c32ed13de263b8f1eb7322fa8f9a591481b4eb | 43cdd99e47d573ef2b57e55b56c439db3e2b6d22 | refs/heads/master | 2020-12-06T10:10:58.437000 | 2020-02-01T18:51:39 | 2020-02-01T18:51:39 | 232,434,237 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import edu.duke.*;
/**
* Use URL resource to read file word by word
* The URLResource class opens a connection to a URL and allows access to the
* contents of the web page a line at a time, using the method lines. or a word
* at a time, using the method words. These strings can then be iterated over using
* a for loop.
*
* Michiko
* Feb. 1, 2020
*/
public class Part4 {
public void findLink(){
URLResource ur = new URLResource("http://www.dukelearntoprogram.com/course2/data/manylinks.html");
for (String s: ur.words()){
if (s.indexOf("youtube.com")!= -1){ // means Youtube link was found
int you = s.indexOf("youtube.com");
int startQ= s.lastIndexOf("\"",you) + 1; // find location of first quatation and the character after that
int endQ= s.lastIndexOf("\""); // find location of last location
String link = s.substring(startQ,endQ); // substring is the link in between the two quation marks excluding the quation marks themselves
System.out.println(link);
System.out.println();
}
}
}
} | UTF-8 | Java | 1,124 | java | part4.java | Java | [
{
"context": "then be iterated over using \n * a for loop.\n * \n * Michiko\n * Feb. 1, 2020\n */ \n\n \npublic class Part4 {\n ",
"end": 342,
"score": 0.9992496371269226,
"start": 335,
"tag": "NAME",
"value": "Michiko"
}
] | null | [] | import edu.duke.*;
/**
* Use URL resource to read file word by word
* The URLResource class opens a connection to a URL and allows access to the
* contents of the web page a line at a time, using the method lines. or a word
* at a time, using the method words. These strings can then be iterated over using
* a for loop.
*
* Michiko
* Feb. 1, 2020
*/
public class Part4 {
public void findLink(){
URLResource ur = new URLResource("http://www.dukelearntoprogram.com/course2/data/manylinks.html");
for (String s: ur.words()){
if (s.indexOf("youtube.com")!= -1){ // means Youtube link was found
int you = s.indexOf("youtube.com");
int startQ= s.lastIndexOf("\"",you) + 1; // find location of first quatation and the character after that
int endQ= s.lastIndexOf("\""); // find location of last location
String link = s.substring(startQ,endQ); // substring is the link in between the two quation marks excluding the quation marks themselves
System.out.println(link);
System.out.println();
}
}
}
} | 1,124 | 0.63968 | 0.631673 | 31 | 35.290321 | 39.119495 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.419355 | false | false | 9 |
bd4b67f31128fd45f60ff20641cf970842143cdb | 19,078,244,788,657 | 3d46585c05e8aaf2cb7f9af42d2f626852fb31b9 | /Iterator/src/PancakeHouseIterator.java | 3d2dc329835865b86ee8e17e9a3323d18f50992c | [] | no_license | tangaowei/head-frist-dp | https://github.com/tangaowei/head-frist-dp | e1808ae87e160b684773e4cc01d7d0406faf620a | 0818acf29b84d2d56defa88d30c7f128088fa8c7 | refs/heads/master | 2021-01-25T08:49:22.812000 | 2013-04-21T15:20:14 | 2013-04-21T15:20:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
import java.util.Iterator;
public class PancakeHouseIterator implements Iterator<MenuItem> {
ArrayList<MenuItem> items;
int pos = 0;
public PancakeHouseIterator(ArrayList<MenuItem> items) {
this.items = items;
}
public MenuItem next() {
MenuItem menuItem = items.get(pos);
pos++;
return menuItem;
}
public boolean hasNext() {
if(pos >= items.size()) {
return false;
} else {
return true;
}
}
public void remove() {}
} | UTF-8 | Java | 510 | java | PancakeHouseIterator.java | Java | [] | null | [] | import java.util.ArrayList;
import java.util.Iterator;
public class PancakeHouseIterator implements Iterator<MenuItem> {
ArrayList<MenuItem> items;
int pos = 0;
public PancakeHouseIterator(ArrayList<MenuItem> items) {
this.items = items;
}
public MenuItem next() {
MenuItem menuItem = items.get(pos);
pos++;
return menuItem;
}
public boolean hasNext() {
if(pos >= items.size()) {
return false;
} else {
return true;
}
}
public void remove() {}
} | 510 | 0.647059 | 0.645098 | 26 | 18.653847 | 16.719271 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.730769 | false | false | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.