blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
3d8248d12ff25b7bdc62a3f22a3413b61ad9c700 | Java | xiayubudasan/student | /src/cn/edu/jsu/jyt/frm/FrmStuClass.java | GB18030 | 6,904 | 2.265625 | 2 | [] | no_license | package cn.edu.jsu.jyt.frm;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import cn.edu.jsu.jyt.dao.ClassDao;
import cn.edu.jsu.jyt.io.ClassIO;
import cn.edu.jsu.jyt.vo.CClass;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Vector;
import java.awt.event.ActionEvent;
import javax.swing.JTable;
public class FrmStuClass extends JFrame {
private JPanel contentPane;
private JTextField t1;
private JTextField t2;
private JTextField t3;
private JTable table;
private DefaultTableModel model;
private File file;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrmStuClass frame = new FrmStuClass();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FrmStuClass() {
ImageIcon icon=new ImageIcon("source"+File.separator+"img"+File.separator+"7.jpg");
Image img=icon.getImage().getScaledInstance(1000, 1000, Image.SCALE_FAST);
JLabel jlabel=new JLabel(new ImageIcon(img));
jlabel.setBounds(0, 0, 500, 600);
this.getLayeredPane().add(jlabel,new Integer(Integer.MIN_VALUE));
JPanel jp=(JPanel) this.getContentPane();
JRootPane jpl=(JRootPane) this.getRootPane();
jp.setOpaque(false);
jpl.setOpaque(false);
this.setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(380, 210, 548, 411);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setLocationRelativeTo(getOwner());
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(15, 73, 386, 267);
contentPane.add(scrollPane);
file=new File("e:"+File.separator+"γ̱.txt");
if(!file.exists())
{
try {
file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Vector<String> titles=new Vector<>();
Collections.addAll(titles, "γ̺","γ","ѧ");
Vector<Vector> v=ClassDao.getSelectClass("select cno,cname,ccredit from class where cno in(select cno from score where sno="+FrmStuLogin.getVector().elementAt(0).toString()+")");
model=new DefaultTableModel(v,titles)
{
public Class getColumnClass(int column)
{
Class returnValue;
if((column>=0)&&(column<getColumnCount()) )
{
returnValue=getValueAt(0, column).getClass();
}
else
{
returnValue=Object.class;
}
return returnValue;
}
};
table = new JTable(model);
//int j=v.size();
CClass [] c=new CClass[v.size()];
int i=0;
for(Vector vv:v)
{
c[i]=new CClass();
c[i].setCno(vv.elementAt(0).toString());
c[i].setCname(vv.elementAt(1).toString());
c[i].setCcredit(Double.parseDouble(vv.elementAt(2).toString()));
i++;
}
ClassIO.writeClass(file, c);
scrollPane.setViewportView(table);
t1 = new JTextField();
t1.setBounds(416, 99, 96, 27);
contentPane.add(t1);
t1.setColumns(10);
t2 = new JTextField();
t2.setColumns(10);
t2.setBounds(416, 206, 96, 27);
contentPane.add(t2);
t3 = new JTextField();
t3.setColumns(10);
t3.setBounds(416, 313, 96, 27);
contentPane.add(t3);
JLabel lblNewLabel_1 = new JLabel("γ");
lblNewLabel_1.setBounds(416, 170, 81, 21);
contentPane.add(lblNewLabel_1);
JLabel lblNewLabel_1_1 = new JLabel("ѧ");
lblNewLabel_1_1.setBounds(416, 279, 81, 21);
contentPane.add(lblNewLabel_1_1);
JButton btnNewButton = new JButton("");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ClassIO.updateClass(file, t1.getText().trim(), t2.getText().trim(), t3.getText().trim());
Vector<Vector> v=ClassIO.readClass(file);
for(Vector vv:v)
{
System.out.println(vv);
}
model=new DefaultTableModel(v,titles);
table.setModel(model);
}
});
btnNewButton.setBounds(15, 29, 86, 29);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ClassIO.addClass(file, t1.getText().trim(), t2.getText().trim(),t3.getText().trim());
Vector<Vector> v= ClassIO.readClass(file);
model=new DefaultTableModel(v,titles);
table.setModel(model);
}
});
btnNewButton_1.setBounds(116, 29, 86, 29);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Vector<Vector> v=ClassIO.searchClass(file, t1.getText());
for(Vector vv:v)
{System.out.println(vv);}
model=new DefaultTableModel(v,titles);
table.setModel(model);
}
});
btnNewButton_2.setBounds(217, 29, 86, 29);
contentPane.add(btnNewButton_2);
JButton btnNewButton_3 = new JButton("");
btnNewButton_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Vector<Vector> v=ClassIO.sortClass(file);
for(Vector vv:v)
{System.out.println(vv);}
model=new DefaultTableModel(v,titles);
table.setModel(model);
}
});
btnNewButton_3.setBounds(318, 29, 86, 29);
contentPane.add(btnNewButton_3);
JButton btnNewButton_4 = new JButton("ɾ");
btnNewButton_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Vector<Vector> v=ClassIO.deleteClass(file, t1.getText());
CClass [] c=new CClass[v.size()];
int i=0;
for(Vector vv:v)
{
c[i]=new CClass();
c[i].setCno(vv.elementAt(0).toString());
c[i].setCname(vv.elementAt(1).toString());
c[i].setCcredit(Double.parseDouble(vv.elementAt(2).toString()));
i++;
}
ClassIO.writeClass(file, c);
model=new DefaultTableModel(v,titles);
table.setModel(model);
}
});
btnNewButton_4.setBounds(421, 29, 86, 29);
contentPane.add(btnNewButton_4);
JLabel lblNewLabel = new JLabel("γ̺");
lblNewLabel.setBounds(416, 74, 81, 21);
contentPane.add(lblNewLabel);
}
}
| true |
c869f8f30861f83bd5e51f2803bfd8ef4b4f4c1c | Java | daiqingsong2021/ord_project | /acm-common/src/main/java/com/wisdom/base/common/util/calc/PmTaskRsrc.java | UTF-8 | 7,398 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package com.wisdom.base.common.util.calc;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
public class PmTaskRsrc implements Serializable {
/**
* 序列
*/
private static final long serialVersionUID = 1L;
/**
* 人工资源
*/
public final static String TASK_TYPE_LABOR = "Labor";
/**
* 设备资源
*/
public final static String TASK_TYPE_EQUIP = "Equip";
/**
* 材料资源
*/
public final static String TASK_TYPE_MAT = "Mat";
/**
* 主键 .
*/
private String id;
/**
* 代码 .
*/
private String rsrcCode;
/**
* 名称 .
*/
private String rsrcName;
/**
* 类型
*/
private String rsrcType;
/**
* 任务主键 .
*/
private String taskId;
/**
* 日历 .
*/
private String calendarId;
/**
* 驱控作业日期
*/
private boolean driveTaskDate;
/**
* 计划开始 .
*/
private Date planStartDate;
/**
* 计划完成 .
*/
private Date planEndDate;
/**
* 尚需最早开始 .
*/
private Date remEarlyStart;
/**
* 尚需最早完成 .
*/
private Date remEarlyEnd;
/**
* 尚需最晚开始 .
*/
private Date remLateStart;
/**
* 尚需最晚完成 .
*/
private Date remLateEnd;
/**
* 实际开始 .
*/
private Date actStartDate;
/**
* 实际完成 .
*/
private Date actEndDate;
/**
* 计划工期 .
*/
private BigDecimal planDrtn = new BigDecimal(0);
/**
* 实际工期 .
*/
private BigDecimal actDrtn = new BigDecimal(0);
/**
* 尚需工期 .
*/
private BigDecimal remainDrtn = new BigDecimal(0);
/**
* 预计工时
*/
private BigDecimal work = new BigDecimal(0);
/**
* 实际工时
*/
private BigDecimal actualWork = new BigDecimal(0);
/**
* 尚需工时
*/
private BigDecimal remainingWork = new BigDecimal(0);
/**
* 进度 .
*/
private BigDecimal completePct = new BigDecimal(0);
/**
* @return the id
*/
public String getId() {
return this.id;
}
/**
* @param id the id to set
*/
public void setId(final String id) {
this.id = id;
}
/**
* @return the rsrcCode
*/
public String getRsrcCode() {
return this.rsrcCode;
}
/**
* @param rsrcCode the rsrcCode to set
*/
public void setRsrcCode(final String rsrcCode) {
this.rsrcCode = rsrcCode;
}
/**
* @return the rsrcName
*/
public String getRsrcName() {
return this.rsrcName;
}
/**
* @param rsrcName the rsrcName to set
*/
public void setRsrcName(final String rsrcName) {
this.rsrcName = rsrcName;
}
/**
* @return the rsrcType
*/
public String getRsrcType() {
return this.rsrcType;
}
/**
* @param rsrcType the rsrcType to set
*/
public void setRsrcType(final String rsrcType) {
this.rsrcType = rsrcType;
}
/**
* @return the taskId
*/
public String getTaskId() {
return this.taskId;
}
/**
* @param taskId the taskId to set
*/
public void setTaskId(final String taskId) {
this.taskId = taskId;
}
/**
* @return the calendarId
*/
public String getCalendarId() {
return this.calendarId;
}
/**
* @param calendarId the calendarId to set
*/
public void setCalendarId(final String calendarId) {
this.calendarId = calendarId;
}
/**
* @return the driveControlTaskDate
*/
public boolean getDriveTaskDate() {
return this.driveTaskDate;
}
/**
* @param driveTaskDate the driveTaskDate to set
*/
public void setDriveTaskDate(final boolean driveTaskDate) {
this.driveTaskDate = driveTaskDate;
}
/**
* @return the planStartDate
*/
public Date getPlanStartDate() {
return this.planStartDate;
}
/**
* @param planStartDate the planStartDate to set
*/
public void setPlanStartDate(final Date planStartDate) {
this.planStartDate = planStartDate;
}
/**
* @return the planEndDate
*/
public Date getPlanEndDate() {
return this.planEndDate;
}
/**
* @param planEndDate the planEndDate to set
*/
public void setPlanEndDate(final Date planEndDate) {
this.planEndDate = planEndDate;
}
/**
* @return the remEarlyStart
*/
public Date getRemEarlyStart() {
return this.remEarlyStart;
}
/**
* @param remEarlyStart the remEarlyStart to set
*/
public void setRemEarlyStart(final Date remEarlyStart) {
this.remEarlyStart = remEarlyStart;
}
/**
* @return the remEarlyEnd
*/
public Date getRemEarlyEnd() {
return this.remEarlyEnd;
}
/**
* @param remEarlyEnd the remEarlyEnd to set
*/
public void setRemEarlyEnd(final Date remEarlyEnd) {
this.remEarlyEnd = remEarlyEnd;
}
/**
* @return the remLateStart
*/
public Date getRemLateStart() {
return this.remLateStart;
}
/**
* @param remLateStart the remLateStart to set
*/
public void setRemLateStart(final Date remLateStart) {
this.remLateStart = remLateStart;
}
/**
* @return the remLateEnd
*/
public Date getRemLateEnd() {
return this.remLateEnd;
}
/**
* @param remLateEnd the remLateEnd to set
*/
public void setRemLateEnd(final Date remLateEnd) {
this.remLateEnd = remLateEnd;
}
/**
* @return the actStartDate
*/
public Date getActStartDate() {
return this.actStartDate;
}
/**
* @param actStartDate the actStartDate to set
*/
public void setActStartDate(final Date actStartDate) {
this.actStartDate = actStartDate;
}
/**
* @return the actEndDate
*/
public Date getActEndDate() {
return this.actEndDate;
}
/**
* @param actEndDate the actEndDate to set
*/
public void setActEndDate(final Date actEndDate) {
this.actEndDate = actEndDate;
}
/**
* @return the planDrtn
*/
public BigDecimal getPlanDrtn() {
return this.planDrtn;
}
/**
* @param planDrtn the planDrtn to set
*/
public void setPlanDrtn(final BigDecimal planDrtn) {
this.planDrtn = planDrtn;
}
/**
* @return the actDrtn
*/
public BigDecimal getActDrtn() {
return this.actDrtn;
}
/**
* @param actDrtn the actDrtn to set
*/
public void setActDrtn(final BigDecimal actDrtn) {
this.actDrtn = actDrtn;
}
/**
* @return the remainDrtn
*/
public BigDecimal getRemainDrtn() {
return this.remainDrtn;
}
/**
* @param remainDrtn the remainDrtn to set
*/
public void setRemainDrtn(final BigDecimal remainDrtn) {
this.remainDrtn = remainDrtn;
}
/**
* @return the work
*/
public BigDecimal getWork() {
return this.work;
}
/**
* @param work the work to set
*/
public void setWork(final BigDecimal work) {
this.work = work;
}
/**
* @return the actualWork
*/
public BigDecimal getActualWork() {
return this.actualWork;
}
/**
* @param actualWork the actualWork to set
*/
public void setActualWork(final BigDecimal actualWork) {
this.actualWork = actualWork;
}
/**
* @return the remainingWork
*/
public BigDecimal getRemainingWork() {
return this.remainingWork;
}
/**
* @param remainingWork the remainingWork to set
*/
public void setRemainingWork(final BigDecimal remainingWork) {
this.remainingWork = remainingWork;
}
/**
* @param remEarlyStart the remEarlyStart to set
*/
public synchronized void setRemEarlyDate(final Date remEarlyStart, final Date remEarlyEnd) {
this.remEarlyStart = remEarlyStart;
this.remEarlyEnd = remEarlyEnd;
}
/**
* @param remLateStart the remLateStart to set
*/
public synchronized void setRemLateDate(final Date remLateStart, final Date remLateEnd) {
this.remLateStart = remLateStart;
this.remLateEnd = remLateEnd;
}
}
| true |
5c0ba6a40fe74364e1a19bb8b1452cdcb33d391b | Java | silex189/Java | /javatests/src/test/java/com/platzi/javatests/fizzBuzz/FizzBuzzShould.java | UTF-8 | 1,501 | 2.859375 | 3 | [] | no_license | package com.platzi.javatests.fizzBuzz;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class FizzBuzzShould {
@Test
public void return_Fizz_for_3_divided_by_3() {
FizzBuzz fizzBuzz = new FizzBuzz();
assertThat(fizzBuzz.fizzBuzz(3), is("Fizz"));
}
@Test
public void return_Fizz_for_6_divided_by_3() {
FizzBuzz fizzBuzz = new FizzBuzz();
assertThat(fizzBuzz.fizzBuzz(6), is("Fizz"));
}
@Test
public void return_Buzz_for_5_divided_by_5() {
FizzBuzz fizzBuzz = new FizzBuzz();
assertThat(fizzBuzz.fizzBuzz(5), is("Buzz"));
}
@Test
public void return_Buzz_for_10_divided_by_5() {
FizzBuzz fizzBuzz = new FizzBuzz();
assertThat(fizzBuzz.fizzBuzz(10), is("Buzz"));
}
@Test
public void return_Buzz_for_15_divided_by_3_and_5() {
FizzBuzz fizzBuzz = new FizzBuzz();
assertThat(fizzBuzz.fizzBuzz(15), is("FizzBuzz"));
}
@Test
public void return_Buzz_for_30_divided_by_3_and_5() {
FizzBuzz fizzBuzz = new FizzBuzz();
assertThat(fizzBuzz.fizzBuzz(30), is("FizzBuzz"));
}
@Test
public void return_2_for_2() {
FizzBuzz fizzBuzz = new FizzBuzz();
assertThat(fizzBuzz.fizzBuzz(2), is("2"));
}
@Test
public void return_16_for_16() {
FizzBuzz fizzBuzz = new FizzBuzz();
assertThat(fizzBuzz.fizzBuzz(16), is("16"));
}
} | true |
f0f4128119165ae9d432e655e4dc1abccfc065ac | Java | uzkha/springbank | /src/main/java/br/com/springbank/model/Gerente.java | UTF-8 | 506 | 2.296875 | 2 | [] | no_license | package br.com.springbank.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import org.hibernate.annotations.Table;
@Entity
//@DiscriminatorValue(value = "G")
public class Gerente extends Pessoa{
@Column
private Date dataContratacao;
public Date getDataContratacao() {
return dataContratacao;
}
public void setDataContratacao(Date dataContratacao) {
this.dataContratacao = dataContratacao;
}
}
| true |
4b3cc30437800305b216bbbed18fb6d43abbb45a | Java | XiHaLongGe/teamwork-mall | /src/main/java/com/nf/controller/UserController.java | UTF-8 | 562 | 2.109375 | 2 | [] | no_license | package com.nf.controller;
/**
* @Author: LJP
* @Classname UserController
* @Date: 2020-02-19 13:46
* @Description:
*/
public class UserController {
/**
* 这是张某为insert方法写的注释:这是一个insert方法
*/
public void insert(){
System.out.println("UserController............insert...........");
}
/**
* 这是周某为insert方法写的注释:这是一个update方法
*/
public void update(){
System.out.println("UserController............update...........");
}
// 234
}
| true |
0d9a0b8fd16b07565e724767b26247651f226032 | Java | Livemy/example | /java/AWT/partFour/awtComponentClass/i18n/LabelsBundle_en.java | UTF-8 | 212 | 1.84375 | 2 | [] | no_license | import java.util.*;
public class LabelsBundle_en extends ListResourceBundle {
static final Object[][] contents = {
{"Identifier", "English GUI"}
};
public Object[][] getContents() {
return contents;
}
}
| true |
858ad8ba4c565226a992205d2653dd0e94411f5d | Java | yamiacat/MartianHabManager | /app/src/test/java/com/codeclan/example/martianhabmanager/DefaultNamerTest.java | UTF-8 | 591 | 2.65625 | 3 | [] | no_license | package com.codeclan.example.martianhabmanager;
import org.junit.Test;
import static org.junit.Assert.*;
public class DefaultNamerTest {
@Test
public void canGetDefaultName() {
FakeDice dice = new FakeDice(1);
DefaultNamer namer = new DefaultNamer(dice);
assertEquals("Specimen 000-Hexagon", namer.getDefaultName());
}
@Test
public void canGetDefaultNameNotHardcoded() {
FakeDice dice = new FakeDice(10);
DefaultNamer namer = new DefaultNamer(dice);
assertEquals("Exhibit 999-Dragon", namer.getDefaultName());
}
} | true |
f0e4a4fac454cbe76a950450d4a5f0ba4714d0e9 | Java | marokac/javaUIApp | /javaUIApp/src/culculater.java | UTF-8 | 518 | 2.890625 | 3 | [] | no_license |
public class culculater {
//constructor
culculater(){}
//Perfom culculations
public Double calculateBondRate(Double faceV, Double CRate, Double period, Double IRate) {
Double monthlyInRate = IRate / 100 / 12;
Double termsInMonths = period * 12;
Double payments = (faceV * monthlyInRate) / 1 - Math.pow(1 + monthlyInRate, -termsInMonths);
// round to two decimals
payments = (double) Math.round(payments * 100) / 100;
return payments;
}
}
| true |
97a0edfaa76c43dc5ca90886ed91891d37a6ba27 | Java | craighep/JavaScheduler | /code/cs211/src/uk/ac/aber/rcs/cs211/schedulersim/scheduler/FirstComeFirstServed.java | UTF-8 | 2,003 | 3.53125 | 4 | [] | no_license | package uk.ac.aber.rcs.cs211.schedulersim.scheduler;
import java.util.*;
import uk.ac.aber.rcs.cs211.schedulersim.*;
/**
* A first come, first served scheduling algorithm.
* It will keep re-presenting the same job each time getNextjob is called, until
* that job is removed from the queue, either because it has finished, or it gets
* blocked for I/O.
* @author rcs
* @see uk.ac.aber.rcs.cs211.schedulersim.Simulator
*
*/
public class FirstComeFirstServed implements Scheduler {
protected ArrayList<Job> queue;
private int numberOfJobs;
public FirstComeFirstServed () {
this.queue = new ArrayList<Job>();
this.numberOfJobs=0;
}
public void addNewJob(Job job) throws SchedulerException {
if (this.queue.contains(job)) throw new SchedulerException("Job already on Queue");
this.queue.add(this.numberOfJobs, job);
this.numberOfJobs++;
}
/**
* Returns the next job at the head of the ready queue.
* This method should only ever do this - the queue should be kept in the correct order when things are
* added and removed.
*
* Think about making an abstract class rather then an interface, and make this method final.
*/
public Job getNextJob() throws SchedulerException {
Job lastJobReturned;
if (this.numberOfJobs<1) throw new SchedulerException("Empty Queue");
lastJobReturned = (Job)this.queue.get(0);
return lastJobReturned;
}
public void returnJob(Job job) throws SchedulerException {
if (!this.queue.contains(job)) throw new SchedulerException("Job not on Queue");
// nothing to do in this implementation.
}
public void removeJob(Job job) throws SchedulerException {
if (!this.queue.contains(job)) throw new SchedulerException("Job not on Queue");
this.queue.remove(job);
this.numberOfJobs--;
}
public void reset() {
this.queue.clear();
this.numberOfJobs=0;
}
public Job[] getJobList() {
Job[] jobs = new Job[queue.size()];
for (int i=0; i<queue.size(); i++) {
jobs[i]=this.queue.get(i);
}
return jobs;
}
}
| true |
22faaaf2bb74b899fcae2e22c2d5564a522453f7 | Java | magdyuci/testNG_tests | /src/test/java/dataProvider/MyDataProvider.java | UTF-8 | 290 | 2.109375 | 2 | [] | no_license | package dataProvider;
import org.testng.annotations.DataProvider;
public class MyDataProvider {
@DataProvider(name = "NumbersInput")
public Object[][] getDataFromDataProvider() {
return new Object[][]{
{22, 23},
{12, 13}
};
}
}
| true |
23f15250e62b77cedbed3325821ef915be1f7659 | Java | wjcjava/QueenClient | /app/src/main/java/com/ainisi/queenmirror/queenmirrorcduan/bean/SortBean.java | UTF-8 | 1,057 | 2.078125 | 2 | [] | no_license | package com.ainisi.queenmirror.queenmirrorcduan.bean;
/**
* Created by Administrator on 2018/3/14.
*/
public class SortBean {
int logo;
String name;
int stars;
int groupshop;
String time;
String distance;
public int getLogo() {
return logo;
}
public void setLogo(int logo) {
this.logo = logo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStars() {
return stars;
}
public void setStars(int stars) {
this.stars = stars;
}
public int getGroupshop() {
return groupshop;
}
public void setGroupshop(int groupshop) {
this.groupshop = groupshop;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
}
| true |
04098461471d32fc10e81a15367dc328b003ce8c | Java | liangsheng888/Estore | /app/src/main/java/com/estore/activity/myappliction/MyApplication.java | UTF-8 | 4,463 | 2.203125 | 2 | [
"Apache-2.0"
] | permissive | package com.estore.activity.myappliction;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import org.xutils.BuildConfig;
import org.xutils.x;
import c.b.BP;
import io.rong.imkit.RongIM;
/**
* Created by Administrator on 2016/9/13.
*/
public class MyApplication extends Application{
private static Context content;
private Integer messageNum;
@Override
public void onCreate() {
super.onCreate();
//初始化xutils
x.Ext.init(this);
x.Ext.setDebug(BuildConfig.DEBUG);
/**
* OnCreate 会被多个进程重入,这段保护代码,确保只有您需要使用 RongIM 的进程和 Push 进程执行了 init。
* io.rong.push 为融云 push 进程名称,不可修改。
*/
if (getApplicationInfo().packageName
.equals(getCurProcessName(getApplicationContext()))
|| "io.rong.push"
.equals(getCurProcessName(getApplicationContext()))) {
/**
* IMKit SDK调用第一步 初始化
*/
RongIM.init(this);
}
// //新消息处理
// RongIM.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
// @Override
// public boolean onReceived(final Message message, int i) {
// //false 走融云默认方法 true走自己设置的方法
//
// if (message != null) {//app是否运行在后台 不在发消息推送广播
//
// //未读消息数量
// RongIMClient.getInstance().getTotalUnreadCount(new RongIMClient.ResultCallback<Integer>() {
// @Override
// public void onSuccess(Integer integer) {
// messageNum = integer;
// Log.i("cc", "---IMMessageNum:" + integer);
//
// //app后台运行 发送广播
// Intent intent = new Intent();
// intent.putExtra("SendId", message.getSenderUserId());//消息发送者
// intent.putExtra("MsgType", message.getConversationType() + "");
// intent.putExtra("MsgNum", messageNum + "");
// intent.setAction("com.yu.chatdemo.receiver.ChatBoardcaseReceiver");
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// MyApplication.this.getApplicationContext().sendBroadcast(intent);
//
// }
//
// @Override
// public void onError(RongIMClient.ErrorCode errorCode) {
// Log.d("cc", "---IMMessageNumError:" + errorCode);
// }
// });
//
// }
//
// return true;
// }
// });
}
// SharedPreferences sp1=getSharedPreferences("user",MODE_APPEND);
// String token=sp1.getString("token","");
// Log.i("cc", "onCreate: "+token);
// RongIM.connect(token, new RongIMClient.ConnectCallback() {
// @Override
// public void onTokenIncorrect() {
//
// }
//
// @Override
// public void onSuccess(String s) {
// Log.i("cc", "——onSuccess—-" + s);
//
//// startActivity(new Intent(ProductInfoActivity.this,MyFriendsActivity.class));
//
// }
//
// @Override
// public void onError(RongIMClient.ErrorCode errorCode) {
// Log.i("cc","--onError--"+errorCode);
//
// }
// });
//
//
// }
public static Context getObjectContext() {
return content;
}
/**
* 获得当前进程的名字
*
* @param context
* @return 进程号
*/
public static String getCurProcessName(Context context) {
int pid = android.os.Process.myPid();
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
}
| true |
36eac892fe20fef51bbf788f8755fc9daab6976b | Java | wmmxsd/springDemo | /src/main/java/com/wmm/simple/proxy/dynamic/App.java | UTF-8 | 1,373 | 2.28125 | 2 | [
"MIT"
] | permissive | package com.wmm.simple.proxy.dynamic;
import com.wmm.simple.proxy.dynamic.invocation.AuditMethodInvocation;
import com.wmm.simple.proxy.dynamic.proxy.DynamicProxyFactory;
import com.wmm.simple.proxy.service.AuditService;
import com.wmm.simple.proxy.service.DeviceService;
import com.wmm.simple.proxy.service.UserService;
import com.wmm.simple.proxy.service.impl.AuditServiceImpl;
import com.wmm.simple.proxy.service.impl.DeviceServiceImpl;
import com.wmm.simple.proxy.service.impl.UserServiceImpl;
/**
* @author wangmingming160328
* @Description
* @date @2020/1/14 15:00
*/
public class App {
public static void main(String[] args) {
AuditService auditService = new AuditServiceImpl();
UserService userService = new UserServiceImpl();
AuditMethodInvocation auditMethodInvocation = new AuditMethodInvocation(userService, auditService);
UserService userServiceProxy = (UserService) DynamicProxyFactory.getProxy(userService, auditMethodInvocation);
userServiceProxy.dress();
DeviceService deviceService = new DeviceServiceImpl();
AuditMethodInvocation auditMethodInvocation1 = new AuditMethodInvocation(deviceService, auditService);
DeviceService deviceServiceProxy = (DeviceService) DynamicProxyFactory.getProxy(deviceService, auditMethodInvocation1);
deviceServiceProxy.shutdown();
}
}
| true |
2703d0f4d4297f6209e79f61ba12bbf0ae484cde | Java | negishubham/ESensor | /app/src/main/java/com/example/shubham/environmentsensor/graph.java | UTF-8 | 4,702 | 2.1875 | 2 | [] | no_license | package com.example.shubham.environmentsensor;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
public class graph extends AppCompatActivity implements SensorEventListener {
private GraphView mGraphProx,mGraphAcc,mGraphHum,mGraphTemp;
private SensorManager mSensorManager;
private Sensor mAccelerometer,mProx,mHumidity,mTemp;
private double graphLastAccelXValue = 5d;
private LineGraphSeries P,A,T,H;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graph);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
mProx=mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
mTemp=mSensorManager.getDefaultSensor(Sensor.TYPE_TEMPERATURE);
mHumidity=mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this,mHumidity,SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this,mTemp,SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this,mProx,SensorManager.SENSOR_DELAY_NORMAL);
mGraphProx = initGraph(R.id.graphView1, "Proximity");
mGraphTemp = initGraph(R.id.graphView2, "Temperature");
mGraphHum = initGraph(R.id.graphView3, "Humidity");
mGraphAcc = initGraph(R.id.graphView4, "Accelerometer");
P = initSeries(Color.BLUE, "PROXIMITY");
A = initSeries(Color.BLUE, "ACCELOROMETER");
T = initSeries(Color.BLUE, "TEMPERATURE");
H = initSeries(Color.BLUE, "HUMIDITY");
mGraphHum.addSeries(H);
mGraphProx.addSeries(P);
mGraphTemp.addSeries(T);
mGraphAcc.addSeries(A);
Button cpoButton1=(Button)findViewById(R.id.Back);
cpoButton1.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
Intent i = new Intent(graph.this, MainActivity.class);
startActivity(i);
}
}
);
}
public LineGraphSeries<DataPoint> initSeries(int color, String title) {
LineGraphSeries<DataPoint> series;
series = new LineGraphSeries<>();
series.setDrawDataPoints(false);
series.setDrawBackground(false);
series.setColor(color);
series.setTitle(title);
return series;
}
public GraphView initGraph(int id, String title) {
GraphView graph = (GraphView) findViewById(id);
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setMinX(0);
graph.getViewport().setMaxX(5);
graph.getGridLabelRenderer().setLabelVerticalWidth(100);
graph.setTitle(title);
graph.getGridLabelRenderer().setHorizontalLabelsVisible(false);
graph.getLegendRenderer().setVisible(true);
graph.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP);
return graph;
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType()==Sensor.TYPE_PROXIMITY){
graphLastAccelXValue += 0.15d;
P.appendData(new DataPoint(graphLastAccelXValue, event.values[0]), true, 33);
}
if(event.sensor.getType()==Sensor.TYPE_RELATIVE_HUMIDITY){
graphLastAccelXValue += 0.15d;
H.appendData(new DataPoint(graphLastAccelXValue, event.values[0]), true, 33);
}
if(event.sensor.getType()==Sensor.TYPE_TEMPERATURE){
graphLastAccelXValue += 0.15d;
T.appendData(new DataPoint(graphLastAccelXValue, event.values[0]), true, 33);
}
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
graphLastAccelXValue += 0.15d;
A.appendData(new DataPoint(graphLastAccelXValue, event.values[0]), true, 33);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
| true |
614df8626a88052239d2615bb213eabfb9ca501c | Java | fancq/CQEAM | /src/com/sino/ams/apd/dao/AmsAssetsCheckOrderDAO.java | GB18030 | 2,243 | 2.015625 | 2 | [] | no_license | package com.sino.ams.apd.dao;
import java.sql.Connection;
import com.sino.ams.apd.dto.AmsAssetsCheckOrderDTO;
import com.sino.ams.apd.dto.EtsItemCheckDTO;
import com.sino.ams.apd.model.AmsAssetsCheckOrderModel;
import com.sino.ams.appbase.dao.AMSBaseDAO;
import com.sino.ams.system.user.dto.SfUserDTO;
import com.sino.base.db.query.SimpleQuery;
import com.sino.base.db.sql.model.SQLModel;
import com.sino.base.dto.DTO;
import com.sino.base.dto.DTOSet;
import com.sino.base.exception.QueryException;
import com.sino.framework.dto.BaseUserDTO;
public class AmsAssetsCheckOrderDAO extends AMSBaseDAO {
public AmsAssetsCheckOrderDAO(SfUserDTO userAccount, AmsAssetsCheckOrderDTO dtoParameter,
Connection conn) {
super(userAccount, dtoParameter, conn);
}
@Override
protected void initSQLProducer(BaseUserDTO arg0, DTO arg1) {
AmsAssetsCheckOrderDTO dtoPara = (AmsAssetsCheckOrderDTO) dtoParameter;
sqlProducer = new AmsAssetsCheckOrderModel((SfUserDTO) userAccount,dtoPara);
}
//ûϢȡ
public AmsAssetsCheckOrderDTO getTraskUserModel(SfUserDTO user,Connection conn) throws QueryException {
DTOSet dtoSet=new DTOSet();
AmsAssetsCheckOrderDTO lineDTO=new AmsAssetsCheckOrderDTO();
AmsAssetsCheckOrderModel modelProducer = (AmsAssetsCheckOrderModel) sqlProducer;
SQLModel sqlModel = modelProducer.getCheckOrderModel(user);
SimpleQuery simp = new SimpleQuery(sqlModel, conn);
simp.setDTOClassName(AmsAssetsCheckOrderDTO.class.getName());
simp.executeQuery();
dtoSet=simp.getDTOSet();
if(dtoSet.getSize()>0){
lineDTO=(AmsAssetsCheckOrderDTO) dtoSet.getDTO(0);
}
return lineDTO;
}
/**
* ȡϢ
*/
public DTOSet getLineData() throws QueryException {
AmsAssetsCheckOrderDTO dto = (AmsAssetsCheckOrderDTO) dtoParameter;
AmsAssetsCheckOrderModel model = (AmsAssetsCheckOrderModel) sqlProducer;
SQLModel sqlModel = model.getLineModel();
SimpleQuery simp = new SimpleQuery(sqlModel, conn);
simp.setDTOClassName(EtsItemCheckDTO.class.getName());
simp.executeQuery();
return simp.getDTOSet();
}
}
| true |
0f7911b6cf6a283364ae481adf0a7ddd8f77b802 | Java | francisc-neculau/TheDumbAI | /ArtificialIntelligence/src/chatbot/Main.java | UTF-8 | 2,485 | 2.484375 | 2 | [] | no_license | package chatbot;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.SystemColor;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import chatbot.data.UserDb;
public class Main extends JFrame
{
private static final long serialVersionUID = -3675946471320764957L;
private static Bot bot;
public Main()
{
getContentPane().setBackground(Color.WHITE);
setMinimumSize(new Dimension(400, 450));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2 - this.getSize().height / 2);
this.setResizable(false);
getContentPane().setLayout(null);
/* * * * * * * * * * * */
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBorder(null);
scrollPane.setAutoscrolls(true);
scrollPane.setBounds(10, 83, 374, 280);
getContentPane().add(scrollPane);
JTextArea conversationComponent = new JTextArea();
conversationComponent.setBorder(null);
scrollPane.setViewportView(conversationComponent);
conversationComponent.setEditable(false);
JTextField replyComponent = new JTextField();
replyComponent.setBorder(new EmptyBorder(0, 10, 0, 0));
replyComponent.setBackground(SystemColor.control);
replyComponent.setBounds(10, 374, 374, 36);
replyComponent.addActionListener(new AbstractAction()
{
private static final long serialVersionUID = -448083876195112090L;
@Override
public void actionPerformed(ActionEvent e)
{
String conversation = conversationComponent.getText();
String userReply = replyComponent.getText();
replyComponent.setText("");
conversation += System.lineSeparator();
conversation += "Me : ";
conversation += userReply;
conversationComponent.setText(conversation);
conversation += System.lineSeparator();
conversation += bot.getName() + " : ";
conversation += bot.generateReply(" " + userReply + " ");
conversationComponent.setText(conversation);
}
});
getContentPane().add(replyComponent);
}
public static void main(String[] args)
{
bot = new Bot("Guta", "C:\\ComputerScience\\Projects\\ArtificialIntelligence\\resources\\chatbot\\knowledge.xml");
Main mw = new Main();
mw.setVisible(true);
}
}
| true |
0d26a32bc03d4e17f04c3b4c209789d1d70b5819 | Java | joseph5-ship/Corona | /GitTest/src/com/Function/change.java | UTF-8 | 1,465 | 3.4375 | 3 | [] | no_license | package com.Function;
/**Represents the logic needed to alter the coordinates
* of the player tokens in the GUI.
*/
public class change {
/**
* looks at if the locations is between certain ranges that correspond to the top,right,bottom,
* and left of the board and finds the respective x coordinate relative to this.
* @param location the integer is the location you are at
* @return the respective x coordinate associated with that location on the map
*/
public static int changeX(int location) {
int b = location + 1;
int c = 0;
int d = 0;
if(b <= 6){
c = b;
d = 0;
}
if(b <= 11 && b > 6) {
c = 7;
d = b - 5;
}
if(b <= 16 && b > 11) {
c = 17 - b;
d = 7;
}
if(b <= 20 && b > 16) {
c = 0;
d = 22 - b;
}
c = c;
d = d;
return c;
}
/**
* looks at if the locations is between certain ranges that correspond to the top,right,bottom,
* and left of the board and finds the respective y coordinate relative to this.
* @param location the integer is the location you are at
* @return the respective y coordinate associated with that location on the map
*/
public static int changeY(int location) {
int b = location + 1;
int c = 0;
int d = 0;
if(b <= 6) {
c = b;
d = 0;
}
if(b <= 11 && b > 6) {
c = 7;
d = b - 5;
}
if(b <= 16 && b > 11) {
c = 17 - b;
d = 7;
}
if(b <= 20 && b >16) {
c = 0;
d = 22 - b;
}
c = c;
d = d;
return d;
}
}
| true |
e0c075da8cd470314a35cd59f113ea649b67499d | Java | xyh123321/spring-boot-employee-2020-7-16-8-28-32-561 | /src/main/java/com/thoughtworks/springbootemployee/controller/EmployeeController.java | UTF-8 | 1,768 | 2.40625 | 2 | [] | no_license | package com.thoughtworks.springbootemployee.controller;
import com.thoughtworks.springbootemployee.entity.Employee;
import com.thoughtworks.springbootemployee.service.impl.EmployeeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class EmployeeController {
@Autowired
EmployeeServiceImpl employeeServiceImpl;
@GetMapping("/employees/{id}")
public Employee getSpecificEmployee(@RequestParam("id") int id) {
return employeeServiceImpl.getSpecificEmployee(id);
}
@PostMapping("/employees")
public void addEmployees(@RequestBody Employee employee) {
employeeServiceImpl.addEmployees(employee);
}
@DeleteMapping("/employees/{id}")
public void deleteEmployees(@PathVariable("id") int id) {
employeeServiceImpl.deleteEmployees(id);
}
@PutMapping("/employees/{id}")
public void updateEmployees(@PathVariable("id") int id, @RequestBody Employee employee) {
employeeServiceImpl.updateEmployees(id, employee);
}
@RequestMapping("/employees")
public List<Employee> pagingQueryEmployees(@RequestParam(value = "page", required = false, defaultValue = "0") int page
, @RequestParam(value = "pagesize", required = false, defaultValue = "0") int pageSize
, @RequestParam(value = "gender", required = false, defaultValue = "") String gender) {
if (!("".equals(gender))) {
return employeeServiceImpl.getMaleEmployees(gender);
}
if (page != 0 && pageSize != 0) {
employeeServiceImpl.pagingQueryEmployees(page, pageSize);
}
return employeeServiceImpl.getEmployees();
}
}
| true |
a6b3de5047eda8d3fe7c2bf7352417f005d7445f | Java | AyoubBoublil/file-manager-spring-boot | /src/main/java/com/bezkoder/spring/files/upload/db/repository/FolderRepository.java | UTF-8 | 371 | 1.734375 | 2 | [] | no_license | package com.bezkoder.spring.files.upload.db.repository;
import com.bezkoder.spring.files.upload.db.model.File;
import com.bezkoder.spring.files.upload.db.model.Folder;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface FolderRepository extends JpaRepository<Folder, String> {
}
| true |
4f1b180d0b93a4635367c69f7343dea0dfa5bb6d | Java | JasmineSantinelli/ApplicazioneDissesti | /app/src/main/java/com/example/jasmine/progettoinfo3/Upload.java | UTF-8 | 2,609 | 2.375 | 2 | [] | no_license | package com.example.jasmine.progettoinfo3;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
public class Upload extends AsyncTask<String, Void, String> {
public AsyncResponse delegate=null;
String risultato = "nessuno";
@Override
protected String doInBackground(String... params) {
String result;
//assegnazione parametri
String path=params[0];
String longitudine=params[1];
String latitudine=params[2];
Log.d("Log", "latitudine" + latitudine + "longitudine" + longitudine);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://progettoscandurra.andreacavagna.it/caricacellulare");
try {
File file = new File(path);
MultipartEntityBuilder entityBuilder=MultipartEntityBuilder.create();
//entityBuilder.addBinaryBody("file", bytes);
entityBuilder.addBinaryBody("file",file);
entityBuilder.addTextBody("lon",longitudine);
entityBuilder.addTextBody("lat",latitudine);
//entityBuilder.addPart("lon", new StringBody("1234", contentType));
//entityBuilder.addTextBody("lat","3456",ContentType.TEXT_PLAIN);
HttpEntity entity=entityBuilder.build();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
result=EntityUtils.toString(r_entity);
Log.v("results",result);
risultato = result;
return result;
} catch (ClientProtocolException e) {
result = e.toString();
Log.v("exception",result);
return "errore";
} catch (IOException e) {
result = e.toString();
Log.v("exception",result);
return "errore";
}
}
@Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
}
| true |
d09abe5b9dce6082f193fa1db2d5088bd94c59c3 | Java | BGCX261/zipf-svn-to-git | /zipf/src/zipf/event/TransportThread.java | UTF-8 | 688 | 2.25 | 2 | [] | no_license | package zipf.event;
import java.util.Timer;
import java.util.TimerTask;
import zipf.GUI.vis.TransportBar;
public class TransportThread extends TimerTask {
Seq queue;
public long currentTick;
TransportBar transportBar;
public Object transportSync = new Object();
Midi Midi;
public int counter;
public TransportThread(Seq seq) {
this.queue = seq;
Midi = queue.Midi;
transportBar = queue.tools.getTransportBar();
}
@Override
public void run() {
if(!queue.Midi.isPlaying()){
this.cancel();
}
int tick = queue.Midi.getIntTickPosition();
transportBar.setPosition(tick);
}
}
| true |
d0d3780d6cfdf0f92c6cfb65610b124d4cbd2159 | Java | nhathadt11/small-booking-backend | /src/main/java/com/nhatha/smallroombookingbackend/persistance/specification/RoomSpecifications.java | UTF-8 | 654 | 2.328125 | 2 | [] | no_license | package com.nhatha.smallroombookingbackend.persistance.specification;
import com.nhatha.smallroombookingbackend.persistance.model.Room;
import com.nhatha.smallroombookingbackend.persistance.model.Room_;
import org.springframework.data.jpa.domain.Specification;
public final class RoomSpecifications {
public static Specification<Room> hasNameLike(String name) {
return (root, query, cb) -> cb.like(root.get(Room_.name), "%" + name + "%");
}
public static Specification<Room> isAvailable(int id) {
return (root, query, cb) -> cb.and(
cb.equal(root.get(Room_.id), id),
cb.equal(root.get(Room_.available), true)
);
}
}
| true |
72ef2db554deaf9c45272ecf6af34cf4e6509d2f | Java | jesse-l/NCSC-CSC-216-Java | /Project3/test/edu/ncsu/csc216/carrental/util/StackTest.java | UTF-8 | 1,923 | 3.515625 | 4 | [] | no_license | package edu.ncsu.csc216.carrental.util;
import static org.junit.Assert.*;
import java.util.EmptyStackException;
import org.junit.Before;
import org.junit.Test;
import edu.ncsu.csc216.carrental.model.Car;
/**
* This class is used to test the Stack class and the methods inside it.
*
* @author Jesse Liddle - jaliddl2
*/
public class StackTest {
Stack<Car> carStack;
Car car1;
Car car2;
/**
* This method sets up the objects to be used during testing.
*
* @throws Exception
* General exception.
*/
@Before
public void setUp() throws Exception {
carStack = new Stack<Car>();
car1 = new Car("C1234", "Chevy", "Sonic", "Silver");
car2 = new Car("F1234", "Ford", "Explorer", "Red");
}
/**
* This method test the isEmpty method in the stack class.
*/
@Test
public void testIsEmpty() {
assertTrue(carStack.isEmpty());
carStack.push(car1);
assertTrue(!carStack.isEmpty());
carStack.push(car2);
assertFalse(carStack.isEmpty());
}
/**
* This method test the peek method in the stack class.
*/
@Test
public void testPeek() {
try {
assertNull(carStack.peek());
} catch (EmptyStackException e) {
// Nothing
}
carStack.push(car1);
assertTrue(car1.equals(carStack.peek()));
carStack.push(car2);
assertTrue(car2.equals(carStack.peek()));
}
/**
* This method test the pop method in the stack class.
*/
@Test
public void testPop() {
carStack.push(car2);
carStack.push(car1);
assertTrue(car1.equals(carStack.pop()));
assertTrue(car2.equals(carStack.pop()));
}
/**
* This method test the push method in the stack class.
*/
@Test
public void testPush() {
assertTrue(carStack.isEmpty());
carStack.push(car1);
assertTrue(!carStack.isEmpty());
carStack.push(car2);
assertFalse(carStack.isEmpty());
}
}
| true |
50d2765d2a2838d2c70877144e1cb9d020245fc2 | Java | Aman1123/Online-Lecture-Scheduling | /app/src/main/java/com/example/onlinelecturescheduling/model/BatchDateModel.java | UTF-8 | 887 | 2.1875 | 2 | [] | no_license | package com.example.onlinelecturescheduling.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class BatchDateModel implements Serializable {
public BatchDateModel(String batchName, String batchDate) {
this.batchName = batchName;
this.batchDate = batchDate;
}
public BatchDateModel() {
}
@SerializedName("batchName")
@Expose
private String batchName;
@SerializedName("batchDate")
@Expose
private String batchDate;
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
public String getBatchDate() {
return batchDate;
}
public void setBatchDate(String batchDate) {
this.batchDate = batchDate;
}
}
| true |
5834406bf001ede50193bbfc751e015f509ab2c2 | Java | z669016/adventofcode-2019 | /src/main/java/com/putoet/day23/NetworkInterfaceController.java | UTF-8 | 826 | 2.859375 | 3 | [] | no_license | package com.putoet.day23;
import com.putoet.intcode.*;
import java.util.List;
public class NetworkInterfaceController implements Runnable {
private final int address;
private final IntCodeDevice device;
public NetworkInterfaceController(int address, List<Long> intCode, InputDevice input, OutputDevice output) {
this.address = address;
final Memory memory = new ExpandableMemory(intCode);
device = IntCodeComputer
.builder()
.memory(memory)
.input(input)
.output(output)
.build();
}
public int address() {
return address;
}
@Override
public void run() {
device.run();
}
@Override
public String toString() {
return "NIC(" + address + ")";
}
}
| true |
5eda836d25a8b87a2e0b9ca6f8ac33beb74a6737 | Java | tongyu75/hwyRestful | /src/main/java/com/czz/hwy/task/AutoGenAttendanceForPlans.java | UTF-8 | 997 | 2.15625 | 2 | [] | no_license | package com.czz.hwy.task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.czz.hwy.service.usermanagement.app.AttendanceForPlansAppService;
/**
* 每天凌晨零点一分自动生成考勤记录
* @author 张咏雪
* @date 2016-10-28
*
*/
@Component("autoGenAttendanceForPlans")
public class AutoGenAttendanceForPlans {
@Autowired
private AttendanceForPlansAppService attendanceForPlansAppService;
//任务调度时间
// private final static String cron = "0 1 0 * * ?" ; //每天凌晨零点一分自动生成考勤记录,只部署在180服务器上
private final static String cron = "0 1 0 * * ?" ; //每天凌晨零点一分自动生成考勤记录,只部署在218服务器,9090端口上
//@Scheduled(cron=cron)
public void autoGenAttendanceForPlans(){
attendanceForPlansAppService.autoGenAttendanceForPlans();
}
}
| true |
fbecddf2f197f565059e722950a0e03645e2d82c | Java | yuanyind/photoAdmin | /photoAdmin/src/bs/photoAdmin/model/MsgInfo.java | UTF-8 | 1,783 | 1.96875 | 2 | [] | no_license | package bs.photoAdmin.model;
// Generated 2015-3-18 15:24:14 by Hibernate Tools 3.4.0.CR1
import java.util.Date;
/**
* MsgInfo generated by hbm2java
*/
public class MsgInfo implements java.io.Serializable {
private Integer msgId;
private UserInfo userInfoByMsgToUserId;
private UserInfo userInfoByMsgFromUserId;
private String msgVerify;
private Date msgCreatetime;
private Boolean msgFlag;
public MsgInfo() {
}
public MsgInfo(UserInfo userInfoByMsgToUserId,
UserInfo userInfoByMsgFromUserId, String msgVerify,
Date msgCreatetime, Boolean msgFlag) {
this.userInfoByMsgToUserId = userInfoByMsgToUserId;
this.userInfoByMsgFromUserId = userInfoByMsgFromUserId;
this.msgVerify = msgVerify;
this.msgCreatetime = msgCreatetime;
this.msgFlag = msgFlag;
}
public Integer getMsgId() {
return this.msgId;
}
public void setMsgId(Integer msgId) {
this.msgId = msgId;
}
public UserInfo getUserInfoByMsgToUserId() {
return this.userInfoByMsgToUserId;
}
public void setUserInfoByMsgToUserId(UserInfo userInfoByMsgToUserId) {
this.userInfoByMsgToUserId = userInfoByMsgToUserId;
}
public UserInfo getUserInfoByMsgFromUserId() {
return this.userInfoByMsgFromUserId;
}
public void setUserInfoByMsgFromUserId(UserInfo userInfoByMsgFromUserId) {
this.userInfoByMsgFromUserId = userInfoByMsgFromUserId;
}
public String getMsgVerify() {
return this.msgVerify;
}
public void setMsgVerify(String msgVerify) {
this.msgVerify = msgVerify;
}
public Date getMsgCreatetime() {
return this.msgCreatetime;
}
public void setMsgCreatetime(Date msgCreatetime) {
this.msgCreatetime = msgCreatetime;
}
public Boolean getMsgFlag() {
return this.msgFlag;
}
public void setMsgFlag(Boolean msgFlag) {
this.msgFlag = msgFlag;
}
}
| true |
7e4e2319d3bac807a2744aacb9919cf7ebd60d1c | Java | JetBrains/MPS | /samples/money/solutions/jetbrains.mps.baseLanguage.money.sandbox/source_gen/jetbrains/mps/baseLanguage/money/sandbox/model/Sample.java | UTF-8 | 351 | 2.453125 | 2 | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package jetbrains.mps.baseLanguage.money.sandbox.model;
/*Generated by MPS */
import jetbrains.mps.baseLanguage.money.runtime.Currency;
public class Sample {
public static void main(String[] args) {
Currency m1 = new Currency("10", "EUR");
Currency m2 = new Currency("20", "EUR");
System.out.println("Result: " + (m2.sub(m1)));
}
}
| true |
ca93c96dd6f1d74417f0efd5592e3f845c0cc10e | Java | karthiksg92/DemoRepo | /src/main/java/com/crm/qa/util/TestUtil.java | UTF-8 | 2,190 | 2.296875 | 2 | [] | no_license | package com.crm.qa.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import com.crm.qa.base.TestBase;
public class TestUtil extends TestBase{
public static long PAGE_LOAD_TIMEOUT = 20;
public static long IMPLICIT_WAIT = 10;
static Workbook workbook;
static Sheet sheet;
public final static String EXCEL_PATH = System.getProperty("user.dir")
+ "\\src\\main\\java\\com\\crm\\qa\\testdata\\FreeCRMTestData.xlsx";
public static String screenshotPath;
public static String screenshotName;
public static void switchToFrame(String frameName) {
driver.switchTo().frame(frameName);
}
public static void switchTodefaultContent() {
driver.switchTo().defaultContent();
}
public static Object[][] getTestData(String sheetname) {
FileInputStream fis = null;
try {
fis = new FileInputStream(EXCEL_PATH);
} catch (IOException e) {
e.printStackTrace();
}
try {
workbook = WorkbookFactory.create(fis);
} catch (Exception e) {
e.printStackTrace();
}
sheet = workbook.getSheet(sheetname);
int lastRowNum = sheet.getLastRowNum();
int lastColNum = sheet.getRow(0).getLastCellNum();
Object[][] data = new Object[lastRowNum][lastColNum];
for (int rowNum = 0; rowNum < lastRowNum; rowNum++) {
for (int colNum = 0; colNum < lastColNum; colNum++) {
data[rowNum][colNum] = sheet.getRow(rowNum + 1).getCell(colNum).toString();
}
}
return data;
}
public static void captureScreenshot() throws IOException {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Date date = new Date();
screenshotName = date.toString().replace(":", "_").replace(" ", "_") + ".jpg";
FileUtils.copyFile(scrFile,
new File(System.getProperty("user.dir") + "\\target\\surefire-reports\\html\\" + screenshotName));
FileUtils.copyFile(scrFile,
new File(".\\reports\\" + screenshotName));
}
}
| true |
dc4f0ef6dfdc756bbfe0156285dce0c244e50fec | Java | sdetOST/JavaOST19 | /src/Array/P13_CopyingArrays.java | UTF-8 | 498 | 3.5 | 4 | [] | no_license | package Array;
public class P13_CopyingArrays {
public static void main(String[] args) {
String[] sourceNames = {
"Jim", "Bob", "Dillion", "Jackson", "Cidney", "Kate", "Jessica" };
String destinationNames[] = new String[3];
System.arraycopy(sourceNames, 2, destinationNames, 0, 3);
// for (int i = 0; i < 4; i++) {
// System.out.println(destinationNames[i]);
// }
for (String dN : destinationNames) {
System.out.println(dN);
}
}
} | true |
554ade87c5a83bcf7b9968dbc451717a248165f3 | Java | Asunyrn/eframe | /src/main/java/com/framework/base/po/Tparameter.java | UTF-8 | 1,330 | 2.03125 | 2 | [] | no_license | package com.framework.base.po;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
/**
* Tparameter entity. @author MyEclipse Persistence Tools
*/
@Entity
public class Tparameter implements java.io.Serializable {
private String tparameterid;
private String area;
private String type;
private String value;
private String remarks;
private String serialnumber;
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid2")
public String getTparameterid() {
return tparameterid;
}
public void setTparameterid(String tparameterid) {
this.tparameterid = tparameterid;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getSerialnumber() {
return serialnumber;
}
public void setSerialnumber(String serialnumber) {
this.serialnumber = serialnumber;
}
}
| true |
6bb465057ec8f2833c87ace30dad991102e566b2 | Java | michaelye/MVPDemo | /app/src/main/java/com/michael/mvpdemo/presenter/MainPresenter.java | UTF-8 | 1,980 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | package com.michael.mvpdemo.presenter;
import com.michael.mvpdemo.model.AirConditioner;
import com.michael.mvpdemo.view.MainView;
/**
* Presenter持有View和Model
*
* 持有View的引用,这样View(Activity)就不能与Model直接通信,彻底实现了Model和View解耦
*
* Activity因为实现了MainView接口,通过构造器传递进来,所以Presenter能够通过MainView中的回调方法直接对Activity进行操作
*
* 所以Presenter既能对Model操作,也能对View(Activity)操作,但Model和View之间不会进行直接的通信,Presenter起到桥梁的作用
*
* 坏处:
* 1.相对于MVC代码量明显增加,当页面复杂时,代码的直观度会比较差
*
* 2.与Activity的耦合度较高,当Activity的生命周期发生变化时,需要通知Presenter
*
* */
public class MainPresenter implements IPresenter
{
//View(Activity)
private MainView mainView;
//Model
private AirConditioner airConditionerModel;
public MainPresenter(MainView mainView)
{
this.mainView = mainView;
this.airConditionerModel = new AirConditioner();
}
@Override
public void onCreate()
{
this.airConditionerModel = new AirConditioner();
updateUI();
}
@Override
public void onPause()
{
}
@Override
public void onResume()
{
}
@Override
public void onDestroy()
{
}
/**
* 温度发生变化时候调用
* */
public void onTemperatureChanged(int temperature)
{
airConditionerModel.changeTemperature(temperature);
updateUI();
}
/**
* 风力发生变化时候调用
* */
public void onWindLevelChanged()
{
airConditionerModel.changeWindLevel();
updateUI();
}
/**
* 更新UI时调用
* */
public void updateUI()
{
mainView.setTextViewText(airConditionerModel.getCurrentCondition());
}
}
| true |
850005e7e75a9517fd3362bd94d0cbcd8fb7ad6b | Java | Xarybdis167/HRMS-System | /src/main/java/Java/dev/HRMS/core/adapters/cloudinary/CloudinaryServiceAdapter.java | UTF-8 | 518 | 1.929688 | 2 | [] | no_license | package Java.dev.HRMS.core.adapters.cloudinary;
import org.springframework.web.multipart.MultipartFile;
import Java.dev.HRMS.core.utilities.results.DataResult;
public class CloudinaryServiceAdapter implements CloudinaryStorageService{
@Override
public DataResult<?> upload(MultipartFile multipartFile) {
// TODO Auto-generated method stub
return null;
}
@Override
public DataResult<?> delete(String publicIdOfImages) {
// TODO Auto-generated method stub
return null;
}
}
| true |
5b92a748c9513d9c7f539b7fc55e8c8d2bafec4f | Java | lyly0906/imapi | /mianshi-service/src/main/java/cn/xyz/commons/autoconfigure/CommAutoConfiguration.java | UTF-8 | 2,113 | 1.851563 | 2 | [] | no_license | package cn.xyz.commons.autoconfigure;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import cn.xyz.commons.autoconfigure.KApplicationProperties.AppConfig;
import cn.xyz.commons.autoconfigure.KApplicationProperties.MongoConfig;
import cn.xyz.commons.autoconfigure.KApplicationProperties.RedisConfig;
import cn.xyz.commons.autoconfigure.KApplicationProperties.SmsConfig;
import cn.xyz.commons.autoconfigure.KApplicationProperties.XMPPConfig;
import cn.xyz.commons.support.spring.converter.MappingFastjsonHttpMessageConverter;
@Configuration
public class CommAutoConfiguration {
@Autowired
private KApplicationProperties config;
@Bean
public HttpMessageConverters customConverters() {
return new HttpMessageConverters(
new MappingFastjsonHttpMessageConverter());
}
@Bean(name="appConfig")
public AppConfig appConfig(){
AppConfig appConfig=config.getAppConfig();
System.out.println("appConfig>>UploadDomain----"+appConfig.getUploadDomain());
return appConfig;
}
@Bean(name="smsConfig")
public SmsConfig smsConfig(){
SmsConfig smsConfig=config.getSmsConfig();
return smsConfig;
}
@Bean(name="xmppConfig")
public XMPPConfig xmppConfig(){
XMPPConfig xmppConfig=config.getXmppConfig();
System.out.println("xmppConfig>>Host----"+xmppConfig.getHost());
return xmppConfig;
}
@Bean(name="mongoConfig")
public MongoConfig mongoConfig(){
MongoConfig mongoConfig=config.getMongoConfig();
return mongoConfig;
}
@Bean(name="redisConfig")
public RedisConfig redisConfig(){
RedisConfig redisConfig=config.getRedisConfig();
return redisConfig;
}
/*@Bean(name="schedulerFactory")
public SchedulerFactory schedulerFactory(){
return (SchedulerFactory) context.getBean("schedulerFactory");
}
@Bean(name="scheduler")
public Scheduler scheduler() throws SchedulerException{
return schedulerFactory().getScheduler();
} */
}
| true |
840ab55016eabc4fb978052f09e5c3812830e2ec | Java | leimu222/exchange | /src/main/java/cn/com/hh/service/biz/impl/CoinCollectLogBizServiceImpl.java | UTF-8 | 2,042 | 2.03125 | 2 | [] | no_license | package com.common.api.service.impl;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.common.api.dao.CoinCollectLogMapper;
import com.common.api.model.CoinCollectLog;
import com.common.api.service.ICoinCollectLogService;
/**
* @author Gavin Lee
* @version 1.0
* @date 2020-12-08 18:16:01
* Description: [coinBiz服务实现]
*/
@Service
public class CoinCollectLogBizServiceImpl extends CommonService implements ICoinCollectLogBizService {
@Autowired
private ICoinCollectLogService coinCollectLogService;
/**
* 查询coin
*
* @param id coinID
* @return coin
*/
@Override
public CoinCollectLog selectCoinCollectLogById(Integer id) {
return coinCollectLogService.selectCoinCollectLogById(id);
}
/**
* 查询coin列表
*
* @param coinCollectLog coin
* @return coin
*/
@Override
public List<CoinCollectLog> selectCoinCollectLogList(CoinCollectLog coinCollectLog) {
return coinCollectLogService.selectCoinCollectLogList(coinCollectLog);
}
/**
* 新增coin
*
* @param coinCollectLog coin
* @return 结果
*/
@Override
public int insertCoinCollectLog(CoinCollectLog coinCollectLog) {
return coinCollectLogService.insertCoinCollectLog(coinCollectLog);
}
/**
* 修改coin
*
* @param coinCollectLog coin
* @return 结果
*/
@Override
public int updateCoinCollectLog(CoinCollectLog coinCollectLog) {
return coinCollectLogService.updateCoinCollectLog(coinCollectLog);
}
/**
* 批量删除coin
*
* @param ids 需要删除的coinID
* @return 结果
*/
@Override
public int deleteCoinCollectLogByIds(Integer[] ids) {
return coinCollectLogService.deleteCoinCollectLogByIds(ids);
}
/**
* 删除coin信息
*
* @param id coinID
* @return 结果
*/
@Override
public int deleteCoinCollectLogById(Integer id) {
return coinCollectLogService.deleteCoinCollectLogById(id);
}
}
| true |
0e67f1a409a979c708585198d9e64a290df68029 | Java | JISUJUNG/inydus-master | /app/src/main/java/com/inydus/inydus/register/register_profile/parent/view/RegChildProfileActivity_Adres.java | UTF-8 | 3,505 | 1.921875 | 2 | [] | no_license | package com.inydus.inydus.register.register_profile.parent.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.EditText;
import com.inydus.inydus.R;
import com.inydus.inydus.register.postoffice_api.view.PostDialogFragment;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class RegChildProfileActivity_Adres extends AppCompatActivity implements PostDialogFragment.PostDialogListener{
@Bind(R.id.editAddress_regCP_adres)
EditText editAddress;
@Bind(R.id.editAddress_detail_regCP_adres)
EditText editAddress_detail;
Bundle childProfile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_reg_child_profile_activity__adres);
ButterKnife.bind(this);
Intent intent = getIntent();
childProfile = intent.getBundleExtra("childProfile");
}
@OnClick(R.id.btn_next_regCP_adres)
public void setBtnNext(){
String address = editAddress.getText().toString();
String address_detail = editAddress_detail.getText().toString();
if(TextUtils.isEmpty(address))
editAddress.setError(getString(R.string.error_field_required));
else{
if(TextUtils.isEmpty(address_detail))
editAddress_detail.setError(getString(R.string.error_field_required));
else{
childProfile.putString("adres", address);
childProfile.putString("adres_d", address_detail);
Intent intent = new Intent(getApplicationContext(), RegChildProfileActivity_Info.class);
intent.putExtra("childProfile", childProfile);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
overridePendingTransition(R.anim.right_in, R.anim.left_out);
}
}
}
@OnClick(R.id.btn_previous_regCP_adres)
public void setBtnPrevious(){
previousIntentEvent();
}
@OnClick(R.id.btnAddress_regCP_adres)
public void setBtnAddress() {
PostDialogFragment postDialogFragment = new PostDialogFragment();
postDialogFragment.show(getFragmentManager(), "post");
}
@Override
public void onFinishPostDialog(String address) {
editAddress.setText(address);
}
@Override
public void onBackPressed() {
previousIntentEvent();
}
private void previousIntentEvent(){
Intent intent = new Intent(getApplicationContext(), RegChildProfileActivity_Birth.class);
intent.putExtra("childProfile", childProfile);
intent.putExtra("from", "adres");
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if(intent.getStringExtra("from").equals("birth")){
overridePendingTransition(R.anim.right_in, R.anim.left_out);
}
else{
overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
}
childProfile = intent.getBundleExtra("childProfile");
}
}
| true |
ac9b242c81ed5d182281dd16581b5586df007399 | Java | ChenXigithub/springmysqljson | /src/main/java/com/wt/test/dao/FindJsonDao.java | UTF-8 | 634 | 2.234375 | 2 | [] | no_license | package com.wt.test.dao;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class FindJsonDao {
public String getJsonById(String id)
{
String json=null;
Connection con;
ResultSet res;
Statement sta;
if(id==null)
return null;
try {
con=MysqlCollection.getDBCollection();
sta=con.createStatement();
res=sta.executeQuery("select json from jsontest where id="+id);
if(res.next())
{
json=res.getString(1);
}
} catch (ClassNotFoundException | IOException | SQLException e) {
}
return json;
}
}
| true |
2c0d7a3b5e62c9e2c4b1c1fac27ab362b2abdeb3 | Java | emersonLmoniz/chatroom_update | /src/ServerWorker.java | UTF-8 | 4,971 | 2.84375 | 3 | [] | no_license | import com.sun.deploy.util.StringUtils;
import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
public class ServerWorker extends Thread {
private final Socket clientSocket;
private final Server server;
private String userName;
private boolean userIsloggedin;
private String key;
private ArrayList<String> allowedUserList;
private OutputStream OutputStream;
private InputStream InputStream;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
/*
Default constructor for server worker.
Will login the user
Server is being passed as a parameter so the object can reference the same server when finding out who's logged in
*/
/**
* @param server
* @param clientSocket
*/
public ServerWorker(Server server, Socket clientSocket) {
this.server = server;
this.clientSocket = clientSocket;
this.userIsloggedin = true;
}
public void updateInformation (String[] tokens) throws IOException {
String name = tokens[1];
String key = tokens[2];
ArrayList<String> allowedUsers = new ArrayList<>();
for (int i = 3, j = 0; i < tokens.length - 3; i++, j++)
allowedUsers.add(j, tokens[i]);
this.userName = name;
this.key = key;
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
out.writeUTF("Finished updating the values");
}
@Override
public void run() {
try {
// Call the client to read messages
handleClientThread();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @return
*/
public Boolean getUserLogin() {
return userIsloggedin;
}
/**
* @throws IOException
*/
private void handleClientThread() throws IOException {
// set up streams
InputStream InputStream = clientSocket.getInputStream();
this.OutputStream = clientSocket.getOutputStream();
DataInputStream rr = new DataInputStream(clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(InputStream));
String message;
// String msgIn = "";
// String msgOut = "";
//// douts.writeInt(getNumUser());
//// User wants to leave chatroom
while ((message = rr.readUTF()) != null) {
System.out.println(message);
String[] tokens = StringUtils.splitString(message, "#");
if (tokens != null && tokens.length > 0) {
String cmd = tokens[0];
if (cmd.equalsIgnoreCase("exit")) {
handleLogOff();
break;
} else if (cmd.equalsIgnoreCase("update")) {
updateInformation(tokens);
}
// else if(this.newUser.equalsIgnoreCase("new")) {
// handleUserJoinChatRoom();
// this.newUser = "old";
// }
else {
sendMessageToGroup(message);
}
}
}
clientSocket.close();
}
private void handleLogOff() throws IOException {
server.removeWorker(this);
this.userIsloggedin = false;
List<ServerWorker> userList = server.getUserList();
for (ServerWorker worker : userList) {
String offlineMessage = userName + " has " +
(userIsloggedin ? "logged in to" : "logged out of") + " the chatroom";
if (!((worker.userName).equals(this.userName)) && (worker.userIsloggedin == true))
worker.sendMessage(offlineMessage,worker);
}
clientSocket.close();
}
// /**
// * @param
// */
// private void handleUserJoinChatRoom() throws IOException {
// if (userIsloggedin) {
// List<ServerWorker> userList = server.getUserList();
// for (ServerWorker worker : userList) {
// String onlineMessage = userName + " has " +
// (userIsloggedin ? "logged in to" : "logged out of") + " the chatroom";
// if (!((worker.userName).equals(this.userName)) && (worker.userIsloggedin == true))
// worker.sendMessage(onlineMessage);
// }
// }
// }
private void sendMessageToGroup(String message) throws IOException {
List<ServerWorker> userList = server.getUserList();
for (ServerWorker worker : userList) {
if (!((worker.userName).equals(this.userName)) && (worker.userIsloggedin == true))
worker.sendMessage(message,worker);
}
}
private void sendMessage(String message,ServerWorker w) throws IOException {
OutputStream.write((w.userName + ": " + message + "\n").getBytes());
}
} | true |
cd3ae97cac19ec76d15a8ff490f6f70b78f28fe8 | Java | Am-Coder/SpringForDatabases | /springjdbc/src/springjdbc/StudentJDBCTemplate.java | UTF-8 | 1,776 | 2.921875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package springjdbc;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
/**
*
* @author HP
*/
public class StudentJDBCTemplate implements StudentDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
@Override
public void setDataSource(DataSource ds) {
this.dataSource = ds;
this.jdbcTemplateObject = new JdbcTemplate(ds);
}
@Override
public void create(String name, Integer age,Integer id) {
String sql = "INSERT INTO Student(name,age,id) values(?,?,?)";
jdbcTemplateObject.update(sql,name,age,id);
System.out.println("Record Created Successfully");
}
@Override
public Student getStudent(Integer id) {
String sql="Select * from Student where id=?";
Student student = jdbcTemplateObject.queryForObject(sql,new Object[]{id},new StudentMapper());
return student;
}
@Override
public List<Student> listStudents() {
String sql = "select * from Student";
List<Student> students = jdbcTemplateObject.query(sql,new StudentMapper());
return students;
}
@Override
public void delete(Integer id) {
String sql = "delete * from Student where id=?";
jdbcTemplateObject.update(sql,id);
}
@Override
public void update(Integer id, Integer age) {
String SQL = "update Student set age = ? where id = ?";
jdbcTemplateObject.update(SQL, age, id);
System.out.println("Updated Record with ID = " + id );
}
}
| true |
602eaa529106a736c87a1180ce780cea27243a91 | Java | ivinces/ProyectoFinalDS | /Implementacion/test/Model/NombreTest.java | UTF-8 | 1,392 | 2.5 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Model;
import javafx.collections.ObservableList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author isabe
*/
public class NombreTest {
public NombreTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getOptions method, of class Nombre.
*/
@Test
public void testGetOptionsNotNull() {
System.out.println("getOptions");
Nombre instance = new Nombre();
ObservableList<String> result = instance.getOptions();
assertNotNull(result);
}
/**
* Test of setOptions method, of class Nombre.
*/
@Test
public void testSetOptions() {
System.out.println("setOptions");
ObservableList<String> options = null;
Nombre instance = new Nombre();
instance.setOptions(options);
}
}
| true |
e8feaffee7ae79a6c9327e4072df9cc49e70f1b9 | Java | PrzemekSztandera/spring-in-action | /src/main/java/com/psh3mo/springinaction/chapter_4/concert/ClassicPerformance.java | UTF-8 | 285 | 2.390625 | 2 | [] | no_license | package com.psh3mo.springinaction.chapter_4.concert;
import org.springframework.stereotype.Component;
@Component
public class ClassicPerformance implements Performance {
@Override
public void perform() {
System.out.println("Performing classic performance");
}
}
| true |
29ae8580aeadf6a5c84c66a3b7aa8b964264fceb | Java | imtdeepak/aws-rest-elasticsearch | /src/main/java/com/personalcapital/data/service/impl/InvestmentPlanElasticSearchDataService.java | UTF-8 | 2,733 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | package com.personalcapital.data.service.impl;
import java.io.IOException;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import com.personalcapital.data.service.InvestmentPlanDataService;
public class InvestmentPlanElasticSearchDataService implements InvestmentPlanDataService {
@Override
public SearchHits getPlanResponse(String index, String planName, String sponsorName, String sponsorState) {
RestHighLevelClient client = getRestClient();
BoolQueryBuilder qb = QueryBuilders.boolQuery();
SearchHits hits = null;
try {
if (planName != null) {
qb.must(QueryBuilders.matchQuery("PLAN_NAME", planName));
}
if (sponsorName != null) {
qb.must(QueryBuilders.matchQuery("SPONSOR_DFE_NAME", sponsorName));
}
if (sponsorState != null) {
qb.must(QueryBuilders.matchQuery("SPONS_DFE_MAIL_US_STATE", sponsorState));
}
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(qb);
searchRequest.source(searchSourceBuilder);
System.out.println(qb.toString());
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
hits = searchResponse.getHits();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return hits;
}
private RestHighLevelClient getRestClient() {
String esURL = System.getenv("ES_URL");
Integer port = Integer.valueOf(System.getenv("ES_PORT"));
String scheme = System.getenv("ES_PROTOCOL");
RestClientBuilder builder = RestClient.builder(new HttpHost(esURL, port, scheme));
// RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
builder.setFailureListener(new RestClient.FailureListener() {
@Override
public void onFailure(Node node) {
System.out.println(node.getName() + " is down ");
}
});
RestHighLevelClient restHighLevelClient= new RestHighLevelClient(builder);
return restHighLevelClient;
}
}
| true |
b99ba7abfe6f040a4d084d0659927ca733bdb357 | Java | jgroups-extras/manet | /src/main/java/org/jgroups/protocols/SMCASTHeader.java | UTF-8 | 2,097 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | package org.jgroups.protocols;
import org.jgroups.Header;
import org.jgroups.util.Streamable;
import java.io.*;
import java.util.function.Supplier;
public class SMCASTHeader extends Header implements Streamable{
// CONSTRUCTORS --
public SMCASTHeader() {
}
public short getMagicId() {
return Constants.SMCAST_ID;
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
/*type = in.readInt();
if (type==DATA){
dest = new OLSRNode();
dest.readExternal(in);
}*/
}
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
/*type = in.readByte();
if (type==DATA){
dest = new OLSRNode();
dest.readFrom(in);
byte[] addr = new byte[4];
for(int i=0;i<4;i++){
addr[i]=in.readByte();
}
mcastAddress = InetAddress.getByAddress(addr).getHostAddress();
}*/
}
public String toString() {
return "[SMCAST: <variables> ]";
}
public void writeExternal(ObjectOutput out) throws IOException {
/*out.writeInt(type);
if (type==DATA){
dest.writeExternal(out);
}*/
}
public void writeTo(DataOutputStream out) throws IOException {
/*out.writeByte(type);
if (type==DATA){
dest.writeTo(out);
byte[] addr = InetAddress.getByName(mcastAddress).getAddress();
for(int i=0;i<addr.length;i++){
out.writeByte(addr[i]);
}
}*/
}
public Supplier<? extends Header> create() {
return SMCASTHeader::new;
}
public int serializedSize() {
return 0; // currently no fields?
}
public void writeTo(DataOutput out) throws Exception {
}
public void readFrom(DataInput in) throws Exception {
}
/**
* @return the type
*/
/*public int getType() {
return type;
}*/
/**
* @param type the type to set
*/
/*public void setType(int type) {
this.type = type;
}*/
/**
* @return the dest
*/
/*public OLSRNode getDest() {
return dest;
}*/
/**
* @param dest the dest to set
*/
/*public void setDest(OLSRNode dest) {
this.dest = dest;
}*/
}
| true |
91c750b9b5e22f5e2da3ebf37632219d8f12fa7e | Java | senaaydiin/Java | /AmiralBattiFinal/src/Silah.java | UTF-8 | 5,920 | 2.734375 | 3 | [] | no_license |
public class Silah {
public static int[] silahlar;
public static boolean silahKontrolu(int silahTuru) {
if(silahTuru<0 || silahTuru>2) {
System.out.println("Gecersiz silah. Lutfen gecerli bir silah turu seciniz.\n");
return false;
}else if(silahlar[silahTuru]==0) {
System.out.println("Secili silahin cephanesi kalmamistir.\n");
return false;
}
return true;
}
public static int[] silahYazdir(Oyuncu oyuncu) {
int silahTuru, xEkseni, yEkseni, yataymi;
yataymi=0;
do {
if(silahlar[0]!=0)System.out.println("0. Rocket " + silahlar[0]);
if(silahlar[1]!=0)System.out.println("1. Hand Bomb " + silahlar[1]);
if(silahlar[2]!=0)System.out.println("2. Gun Shot " + silahlar[2]);
System.out.println("Select weapon: ");
silahTuru = mainclass.scan.nextInt();
}while(!silahKontrolu(silahTuru));
if(silahTuru==1)
{ do {
System.out.println("0. Dikey");
System.out.println("1. Yatay");
System.out.println("Atis yapilacak duzlemi seciniz:");
yataymi = mainclass.scan.nextInt();
}while(!duzlemKontrolu(yataymi));
}
do{
System.out.println("X coordinate to shoot: ");
xEkseni = mainclass.scan.nextInt();
System.out.println("Y coordinate to shoot: ");
yEkseni = mainclass.scan.nextInt();
}while(!koordinatKontrolu(xEkseni,yEkseni,oyuncu.grid.length));
int[] bilgiler = new int[] {silahTuru,xEkseni,yEkseni,yataymi };
return bilgiler;
}
public static void atesEt(int[] atisBilgileri,Oyuncu o) {
if(atisBilgileri[0]==0) {//Rocket
int atisSayaci=0;
for(int i=atisBilgileri[2]-1; i<atisBilgileri[2]+2;i++)
{
if(i<0||i>o.grid.length-1) { continue; }
else {
if(o.grid[i][atisBilgileri[1]].equals("X"))
{
continue;
}
else if(o.grid[i][atisBilgileri[1]].equals("1") || o.grid[i][atisBilgileri[1]].equals("2") ||o.grid[i][atisBilgileri[1]].equals("3") ||o.grid[i][atisBilgileri[1]].equals("4") )
{
o.grid[i][atisBilgileri[1]]="X"; atisSayaci++;
}
else {
o.grid[i][atisBilgileri[1]]="-";
}
}
}
for(int i=atisBilgileri[1]-1; i<atisBilgileri[1]+2;i++)
{
if(i<0||i>o.grid.length-1) { continue; }
else {
if(o.grid[atisBilgileri[2]][i].equals("X"))
{
continue;
}
else if(o.grid[atisBilgileri[2]][i].equals("1") || o.grid[atisBilgileri[2]][i].equals("2") || o.grid[atisBilgileri[2]][i].equals("3") || o.grid[atisBilgileri[2]][i].equals("4"))
{
o.grid[atisBilgileri[2]][i]="X"; atisSayaci++;
}
else {
o.grid[atisBilgileri[2]][i]="-";
}
}
}
if(atisSayaci==0) System.out.println("\n***** Bos atis yaptiniz. *****");
silahlar[0]--;
}else if(atisBilgileri[0]==1) {//Hand Bomb
if(atisBilgileri[3]==0){//dikey
int atisSayaci=0;
for(int i=atisBilgileri[2]-1; i<atisBilgileri[2]+2;i++)
{
if(i<0||i>o.grid.length-1) {atisSayaci++; continue; }
else {
if(o.grid[i][atisBilgileri[1]].equals("X"))
{
atisSayaci++;
}
else if(o.grid[i][atisBilgileri[1]].equals("1") || o.grid[i][atisBilgileri[1]].equals("2") || o.grid[i][atisBilgileri[1]].equals("3") || o.grid[i][atisBilgileri[1]].equals("4") )
{
o.grid[i][atisBilgileri[1]]="X";
}
else {
o.grid[i][atisBilgileri[1]]="-";
atisSayaci++;
}
}
}
if(atisSayaci==3) System.out.println("\n***** Bos atis yaptiniz. *****");
}else {//yatay
int atisSayaci=0;
for(int i=atisBilgileri[1]-1; i<atisBilgileri[1]+2;i++)
{
if(i<0||i>o.grid.length-1) {atisSayaci++; continue; }
else {
if(o.grid[atisBilgileri[2]][i].equals("X"))
{
atisSayaci++;
}
else if(o.grid[atisBilgileri[2]][i].equals("1") || o.grid[atisBilgileri[2]][i].equals("2") || o.grid[atisBilgileri[2]][i].equals("3") || o.grid[atisBilgileri[2]][i].equals("4"))
{
o.grid[atisBilgileri[2]][i]="X";
}
else {
o.grid[atisBilgileri[2]][i]="-";
atisSayaci++;
}
}
}
if(atisSayaci==3) System.out.println("\n***** Bos atis yaptiniz. *****");
}
silahlar[1]--;
}else {// Gun Shot
if(o.grid[atisBilgileri[2]][atisBilgileri[1]].equals("X"))
{
System.out.println("\n***** Vurulmus yeri tekrar vurdunuz. *****");
}
else if(o.grid[atisBilgileri[2]][atisBilgileri[1]].equals("1") || o.grid[atisBilgileri[2]][atisBilgileri[1]].equals("2") || o.grid[atisBilgileri[2]][atisBilgileri[1]].equals("3") || o.grid[atisBilgileri[2]][atisBilgileri[1]].equals("4"))
{
o.grid[atisBilgileri[2]][atisBilgileri[1]]="X";
}
else {
o.grid[atisBilgileri[2]][atisBilgileri[1]]="-";
System.out.println("\n***** Bos atis yaptiniz. *****");
}
silahlar[2]--;
}
//Grid.gridYazdir(o.grid);
Grid.gridSonYazdir(o.grid);
}
public static boolean duzlemKontrolu(int duzlem) {
if(duzlem<0 || duzlem>1) {
System.out.println("Gecersiz duzlem. Lutfen gecerli bir duzlem seciniz.\n");
return false;
}
return true;
}
public static boolean koordinatKontrolu(int xEkseni, int yEkseni, int uzunluk) {
if(xEkseni<0 || xEkseni>uzunluk-1 || yEkseni<0 || yEkseni>uzunluk-1 ) {
System.out.println("Gecersiz koordinat. Lutfen gecerli bir koordinat seciniz.\n");
return false;
}
return true;
}
public static boolean silahlarinKontrolu(Oyuncu o)
{
if(silahlar[0]==0 && silahlar[1]==0 && silahlar[2]==0)
{ Grid.gridSonYazdir(o.grid);
System.out.println("\n***** Oyun bitti. Tum cephaneniz tukendi. *****");
return false;
}
return true;
}
}
| true |
63be72c9ceeb41faf25ccfe732399a736f1423eb | Java | anahitkarhanian/week2 | /src/day5/exercise3.java | UTF-8 | 469 | 3.09375 | 3 | [] | no_license | package day5;
public class exercise3 {
public static void main(String[] args) {
int count1 = 0;
int count2 = 0;
int count3 = 0;
for (int i = 2; i <= 15; i ++){
count1++;
}
for (int i = 10; i <= 100; i = i+7){
count2++;
}
for (float i = 1.5f; i <= 10.3; i = i+0.4f){
count3++;
}
System.out.println(count1 + " " + count2 + " " + count3);
}
}
| true |
9d85c295ad1b9147fe63126b8a0c328e84dc502d | Java | EEIT10306/FinalShop | /TeamWork/src/main/java/model/repository/Impl/SellerDaoImpl.java | UTF-8 | 2,464 | 2.578125 | 3 | [] | no_license | package model.repository.Impl;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import model.bean.Seller;
import model.repository.SellerDao;
@Repository
public class SellerDaoImpl implements SellerDao {
@Autowired
private SessionFactory sessionFactory;
public Session getSession() {
return this.sessionFactory.getCurrentSession();
}
@Override
public List<Seller> selectAll() throws SQLException {
List<Seller> LS = getSession().createQuery("from Seller", Seller.class).list();
System.out.println(LS);
return LS;
}
@Override
public Seller selectByPk(Integer id) throws SQLException {
if (id == null)
return null;
Seller S = getSession().get(Seller.class, id);
System.out.println(S);
return S;
}
@Override
public List<Seller> selectHql(String hqlString) throws SQLException {
String hql = "from Seller ";
hql += hqlString;
List<Seller> LS = getSession().createQuery(hql, Seller.class).list();
System.out.println(LS);
return LS;
}
@Override
public Seller insert(Seller bean) throws SQLException {
// 查詢此ID有無資料
Seller S = selectByPk(bean.getSeller_id());
// 沒有才新增
if (S == null) {
bean.setSeller_stateId(9);
getSession().save(bean);
return bean;
}
return null;
}
@Override
public Seller update(Seller bean) throws SQLException {
// 查詢此ID有無資料
Seller S = selectByPk(bean.getSeller_id());
// 有才修改
if (S != null) {
if (bean.getM_id() != null)
S.setM_id(bean.getM_id());
if (bean.getSeller_bank() != null)
S.setSeller_bank(bean.getSeller_bank());
if (bean.getSeller_card() != null)
S.setSeller_card(bean.getSeller_card());
if (bean.getSeller_stateId() != null)
S.setSeller_stateId(bean.getSeller_stateId());
return S;
}
return null;
}
public Seller update(Seller S, Seller bean) throws SQLException {
if (bean.getM_id() != null)
S.setM_id(bean.getM_id());
if (bean.getSeller_bank() != null)
S.setSeller_bank(bean.getSeller_bank());
if (bean.getSeller_card() != null)
S.setSeller_card(bean.getSeller_card());
if (bean.getSeller_stateId() != null)
S.setSeller_stateId(bean.getSeller_stateId());
return S;
}
}
| true |
0c3a230177d0450afad4648cdf67c458b1c8b8a0 | Java | gagmic/ProjectB | /SBoardMVC/src/com/hb/model/MemberMapper.java | UTF-8 | 270 | 1.59375 | 2 | [] | no_license | package com.hb.model;
import java.util.List;
import com.hb.vo.MemberVO;
import com.hb.vo.ZipcodeVO;
public interface MemberMapper {
public int loginMember(MemberVO vo);
public int isExistId(String id);
public List<ZipcodeVO> getlistZip(String Dong);
}
| true |
e27c0809cb3924bc42f380522948fce165a660f3 | Java | al0ng/gpsclient | /app/src/main/java/com/mj/gpsclient/adapter/DeviceAdapter.java | UTF-8 | 7,024 | 1.945313 | 2 | [] | no_license | package com.mj.gpsclient.adapter;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.mj.gpsclient.Activity.PubUtil;
import com.mj.gpsclient.R;
import com.mj.gpsclient.Utils.PublicUtils;
import com.mj.gpsclient.global.DebugLog;
import com.mj.gpsclient.model.Devices;
import java.util.ArrayList;
import java.util.List;
public class DeviceAdapter extends BaseAdapter implements Filterable {
public List<Devices> array;
public List<Devices> devicelist;
public Context context;
private LayoutInflater mLayoutInfalater;
private MyFilter mFilter;
private boolean selected;// 是否需要将iv_item_device控件显示
private String Tag = "DeviceAdapter";
public DeviceAdapter(Context Context) {
this.context = Context;
mLayoutInfalater = LayoutInflater.from(Context);
}
public void setOriginalData(List<Devices> List) {
devicelist = List;
}
public void setData(List<Devices> List) {
array = List;
notifyDataSetChanged();
}
public void setLayout(boolean selected) {
this.selected = selected;
}
@Override
public int getCount() {
DebugLog.e("sgsfgdfgdf=");
return array == null ? 0 : array.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return array.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
ViewHolder viewHolder = null;
final Devices bean = array.get(arg0);
if (convertView == null) {
convertView = mLayoutInfalater.inflate(R.layout.item_list_devices,
null);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final ImageView iv_item_device = (ImageView) convertView
.findViewById(R.id.iv_item_device);
if (selected) {// select为true,表示进入编辑状态
// 跟踪列表选择编辑状态
iv_item_device.setVisibility(View.VISIBLE);
iv_item_device.setBackgroundResource(R.drawable.check);
} else {
iv_item_device.setVisibility(View.GONE);
iv_item_device.setBackgroundResource(R.drawable.check);
}
if (!PubUtil.followHash.isEmpty()) {
if (PubUtil.followHash.containsKey(bean.getIMEI())) {
iv_item_device.setBackgroundResource(R.drawable.checked);
} else {
iv_item_device.setBackgroundResource(R.drawable.check);
}
}
if (!PubUtil.split_sHash.isEmpty()) {
if (PubUtil.split_sHash.containsKey(bean.getIMEI())) {
iv_item_device.setBackgroundResource(R.drawable.checked);
} else {
iv_item_device.setBackgroundResource(R.drawable.check);
}
}
if (!PubUtil.followHash2.isEmpty()) {
if (PubUtil.followHash2.containsKey(bean.getIMEI())) {
iv_item_device.setBackgroundResource(R.drawable.checked);
} else {
iv_item_device.setBackgroundResource(R.drawable.check);
}
}
if (!PubUtil.split_sHash2.isEmpty()) {
if (PubUtil.split_sHash2.containsKey(bean.getIMEI())) {
iv_item_device.setBackgroundResource(R.drawable.checked);
} else {
iv_item_device.setBackgroundResource(R.drawable.check);
}
}
Devices devices = array.get(arg0);
if (devices != null) {
viewHolder.mTextName.setText(devices.getName());
if (devices.getLineStatus().equals("离线")) {
viewHolder.mOnoffline.setText("离线");
viewHolder.mHeard.setImageDrawable(context.getResources()
.getDrawable(R.drawable.carofflineimage));
} else {
viewHolder.mOnoffline.setText("在线");
viewHolder.mHeard.setImageDrawable(context.getResources()
.getDrawable(R.drawable.carstaticimage));
}
}
return convertView;
}
static class ViewHolder {
TextView mTextName;
ImageView mHeard;
TextView mOnoffline;
ViewHolder(View view) {
mTextName = (TextView) view.findViewById(R.id.device_name);
mHeard = (ImageView) view.findViewById(R.id.heard_icon);
mOnoffline = (TextView) view.findViewById(R.id.devices_onoffline);
}
}
@Override
public Filter getFilter() {
if (null == mFilter) {
mFilter = new MyFilter();
}
return mFilter;
}
// 自定义Filter类
class MyFilter extends Filter {
@Override
// 该方法在子线程中执行
// 自定义过滤规则
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
DebugLog.e("performFiltering=" + constraint);
List<Devices> newValues = new ArrayList<Devices>();
String filterString = constraint.toString().trim().toLowerCase();
Log.i(Tag, filterString + "++++++++++++");
newValues.clear();
// 如果搜索框内容为空,就恢复原始数据
if (TextUtils.isEmpty(filterString)) {
newValues.addAll(devicelist);
Log.i(Tag, devicelist.size() + "---------------");
} else {
// 过滤出新数据
for (Devices devices : devicelist) {
// DebugLog.e("devices.getName()=" + devices.getName());
if (-1 != devices.getName().trim().toLowerCase()
.indexOf(filterString)) {
newValues.add(devices);
}
}
}
results.values = newValues;
results.count = newValues.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// devicesList = (List<Devices>) results.values;
array.clear();
array.addAll((List<Devices>) results.values);
array = PublicUtils.SetOrderForDevices(array);
DebugLog.e("publishResults=" + results.count);
notifyDataSetChanged();
}
}
}
| true |
a138eab14a9ae80590bddd39c17c39b5e45a9a6c | Java | xxdzyyh/RTC | /app/src/main/java/com/tiilii/rtc/ui/me/MyContract.java | UTF-8 | 307 | 1.554688 | 2 | [] | no_license | package com.tiilii.rtc.ui.me;
import com.tiilii.rtc.base.mvp.BasePresenter;
import com.tiilii.rtc.base.mvp.BaseView;
/**
* Created by wangxuefeng on 2018/6/8.
*/
public interface MyContract {
interface Presenter extends BasePresenter<View> {
}
interface View extends BaseView {
}
}
| true |
35a9f259fa2f9e655f5cc272e2039dc018905cb9 | Java | EamonYin/Thinking-in-Java-Exercise | /src/Chapter9/Test11/Processor.java | UTF-8 | 179 | 2.109375 | 2 | [] | no_license | package Chapter9.Test11;
/**
* @author:YiMing
* @create:2020/7/26,21:13
* @version:1.0
*/
public interface Processor {
String name();
Object process(Object input);
}
| true |
21c466b4739dab03fd28710338f9bc5ce0c285d2 | Java | PedroAugusto115/desafio-neon | /app/src/main/java/neon/desafio/banktransfer/model/TransferTotalChart.java | UTF-8 | 1,615 | 2.59375 | 3 | [] | no_license | package neon.desafio.banktransfer.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
public class TransferTotalChart implements Comparable<TransferTotalChart>, Parcelable {
private UserVO userVO;
private double totalTransfered;
public TransferTotalChart(UserVO userVO) {
this.userVO = userVO;
this.totalTransfered = 0.0;
}
public void addValue(double value) {
totalTransfered += value;
}
public UserVO getUserVO() {
return userVO;
}
public double getTotalTransfered() {
return totalTransfered;
}
@Override
public int compareTo(@NonNull TransferTotalChart other) {
return Double.compare(other.getTotalTransfered(), getTotalTransfered());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(this.userVO, flags);
dest.writeDouble(this.totalTransfered);
}
protected TransferTotalChart(Parcel in) {
this.userVO = in.readParcelable(UserVO.class.getClassLoader());
this.totalTransfered = in.readDouble();
}
public static final Creator<TransferTotalChart> CREATOR = new Creator<TransferTotalChart>() {
@Override
public TransferTotalChart createFromParcel(Parcel source) {
return new TransferTotalChart(source);
}
@Override
public TransferTotalChart[] newArray(int size) {
return new TransferTotalChart[size];
}
};
}
| true |
52b7a7909afc791dca499bbf32b56415f097d8c6 | Java | bhawad/game-of-3ree | /src/main/java/com/go3/application/model/game/gameplayers/exception/PlayerAlreadyExistsException.java | UTF-8 | 275 | 2.125 | 2 | [] | no_license | package com.go3.application.model.game.gameplayers.exception;
import com.go3.infrastructure.exception.GameException;
public class PlayerAlreadyExistsException extends GameException {
public PlayerAlreadyExistsException(String message) {
super(message);
}
}
| true |
7900ed655e1cb097b65cb13a8f34f2e048184220 | Java | guangchao-li/FaceIdentify | /app/src/main/java/com/arcsoft/arcfacedemo/ui/viewmodel/DataCalculatorViewModel.java | UTF-8 | 3,079 | 2.53125 | 3 | [] | no_license | package com.arcsoft.arcfacedemo.ui.viewmodel;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.arcsoft.arcfacedemo.ArcFaceApplication;
import com.arcsoft.arcfacedemo.R;
public class DataCalculatorViewModel extends ViewModel {
private MutableLiveData<String> imageWidthNotice = new MutableLiveData<>();
private MutableLiveData<String> imageHeightNotice = new MutableLiveData<>();
private MutableLiveData<String> dataLengthNotice = new MutableLiveData<>();
public MutableLiveData<String> getDataLengthNotice() {
return dataLengthNotice;
}
public MutableLiveData<String> getImageWidthNotice() {
return imageWidthNotice;
}
public MutableLiveData<String> getImageHeightNotice() {
return imageHeightNotice;
}
public String getWidthHelperText(CharSequence s, int maxLength) {
if (s.length() == 0) {
return ArcFaceApplication.getApplication().getString(R.string.notice_input_width);
}
if (s.length() > maxLength) {
return ArcFaceApplication.getApplication().getString(R.string.large_resolution_not_recommended);
}
if (Integer.parseInt(s.toString()) % 4 != 0) {
return ArcFaceApplication.getApplication().getString(R.string.width_must_be_multiple_of_4);
}
return "";
}
public String getHeightHelperText(CharSequence s, int maxLength) {
if (s.length() == 0) {
return ArcFaceApplication.getApplication().getString(R.string.notice_input_height);
}
if (s.length() > maxLength) {
return ArcFaceApplication.getApplication().getString(R.string.large_resolution_not_recommended);
}
return "";
}
public void updateWidthHelperText(CharSequence s, int maxLength) {
imageWidthNotice.postValue(getWidthHelperText(s, maxLength));
}
public void updateHeightHelperText(CharSequence s, int maxLength) {
imageHeightNotice.postValue(getHeightHelperText(s, maxLength));
}
public void calculateSize(String imageWidthText, String imageHeightNotice) {
int width = Integer.parseInt(imageWidthText);
int height = Integer.parseInt(imageHeightNotice);
boolean widthValid = (width > 0 && width % 4 == 0);
if (widthValid) {
StringBuilder stringBuilder = new StringBuilder();
boolean isHeightEven = height > 0 && height % 2 == 0;
stringBuilder
.append("数据长度:").append("\n")
.append("BGR24: ").append(width * height * 3).append("\n")
.append("GRAY: ").append(width * height).append("\n")
.append("DEPTH_U16: ").append(width * height * 2).append("\n")
.append("NV21: ").append(isHeightEven ? String.valueOf(width * height * 3 / 2) : "NV21图像高度不合法");
getDataLengthNotice().postValue(stringBuilder.toString());
} else {
getDataLengthNotice().postValue(null);
}
}
}
| true |
8c2a8d206cf721c93410a0586842658d57efcf49 | Java | AppsCDN/news_api_android | /app/src/main/java/com/example/newsapp/Utils/Util.java | UTF-8 | 347 | 1.65625 | 2 | [] | no_license | package com.example.newsapp.Utils;
public class Util {
public static final String BASE_URL = "https://newsapi.org/v2/";
public static final String DEFAULT_QUERY_EVERYTHING = "Trump";
public static final int TABS_AMOUNT = 3;
public static final int AMOUNT_OF_NEWS_PER_PAGE = 15;
public static final String API_KEY = "e65ee0938a2a43ebb15923b48faed18d";
}
| true |
3a6a3986b43ddf453676dac91b727e3719718529 | Java | labbeh/semestre4 | /progRepartie/workspace/ProjetFinal/src/chat/ihm/panels/dessin/Selection.java | UTF-8 | 2,810 | 3.125 | 3 | [] | no_license | package chat.ihm.panels.dessin;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Panel qui affiche l'item que l'on veut dessiner (rond, rectangle ...)
* */
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import chat.Controleur;
public class Selection extends JPanel {
/**
* Pointeur vers l'instance du controleur de l'application
* */
private Controleur ctrl;
/**
* Permet de dessiner un carré
* */
private JButton carre;
/**
* Permet de dessiner un rond
* */
private JButton rond;
/**
* Permet de dessiner une flèche
* */
private JButton fleche;
/**
* Permet de gommer un élément de la zone de dessin
* */
private JButton gomme;
/**
* Annule la dernière action
* */
private JButton undo;
/**
* Permet d'ajouter du texte sur la zone de dessin
* */
private JButton texte;
/**
* Permet de choisir si on dessine un élément plein ou vide
* */
private JCheckBox plein;
public Selection(Controleur ctrl) {
super();
this.ctrl = ctrl;
this.carre = new JButton("Carré");
this.rond = new JButton("Rond");
this.fleche = new JButton("Flèche");
this.gomme = new JButton("Gomme");
this.undo = new JButton("Undo");
this.texte = new JButton("Texte");
//this.pleinVide = new JButton("Plein/vide");
plein = new JCheckBox("Plein");
EcouteurForme ecouteur = new EcouteurForme();
carre.addActionListener(ecouteur);
rond.addActionListener(ecouteur);
fleche.addActionListener(ecouteur);
gomme.addActionListener(ecouteur);
undo.addActionListener(ecouteur);
texte.addActionListener(ecouteur);
plein.addActionListener(ecouteur);
rond.setEnabled(false);
fleche.setEnabled(false);
gomme.setEnabled(false);
undo.setEnabled(false);
texte.setEnabled(false);
setLayout(new GridLayout());
add(carre);
add(rond);
add(fleche);
add(gomme);
add(undo);
add(texte);
add(plein);
}
/**
* Classe interne qui sera l'écouteur des boutons de sélection
* de la forme à dessiner
* */
private class EcouteurForme implements ActionListener {
@Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == carre ) System.out.println("carré");
else if(evt.getSource() == rond ) System.out.println("rond");
else if(evt.getSource() == fleche ) System.out.println("fleche");
else if(evt.getSource() == gomme ) System.out.println("gomme");
else if(evt.getSource() == undo ) System.out.println("undo");
else if(evt.getSource() == texte ) System.out.println("texte");
else if(evt.getSource() == plein){
if(plein.isSelected()) ctrl.setEstVide(false);
else ctrl.setEstVide(true );
}
}
}
}
| true |
a485920b4977e54162e65b4094866f60f0bbd61d | Java | Hamzawy63/BTree | /src/eg/edu/alexu/csd/filestructure/btree/BTreeNode.java | UTF-8 | 1,276 | 2.828125 | 3 | [] | no_license | package eg.edu.alexu.csd.filestructure.btree;
import java.util.List;
public class BTreeNode<K extends Comparable<K>, V> implements IBTreeNode<K, V> {
private int numberOfKeys;
private List<K> keys;
private List<V> values;
private List<IBTreeNode<K, V>> children;
private boolean leaf;
@Override
public int getNumOfKeys() {
return numberOfKeys;
}
@Override
public void setNumOfKeys(int numOfKeys) {
this.numberOfKeys = numOfKeys;
}
@Override
public boolean isLeaf() {
// return (children == null || children.size() == 0 ) ;
return leaf;
}
@Override
public void setLeaf(boolean isLeaf) {
leaf = isLeaf;
}
@Override
public List<K> getKeys() {
return keys;
}
@Override
public void setKeys(List<K> keys) {
this.keys = keys;
}
@Override
public List<V> getValues() {
return this.values;
}
@Override
public void setValues(List<V> values) {
this.values = values;
}
@Override
public List<IBTreeNode<K, V>> getChildren() {
return this.children;
}
@Override
public void setChildren(List<IBTreeNode<K, V>> children) {
this.children = children;
}
}
| true |
f4a4736775bb9d0ae22d931b151472f25b767deb | Java | liweibo/kyle-juhe-weather | /app/src/main/java/com/kyletung/kylejuheweather/DesktopWidget.java | UTF-8 | 8,645 | 1.9375 | 2 | [] | no_license | package com.kyletung.kylejuheweather;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;
import org.json.JSONException;
import org.json.JSONObject;
public class DesktopWidget extends AppWidgetProvider {
public static String city;
RemoteViews view;
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
}
@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
view = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
view.setImageViewResource(R.id.widget_background, R.drawable.widget_background);
//set onclick
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
view.setOnClickPendingIntent(R.id.widget, pendingIntent);
//update data
Parameters parameters = new Parameters();
//set city
if (city == null) {
city = "杭州";
}
parameters.add("cityname", city);
JuheData.executeWithAPI(context, 39, "http://v.juhe.cn/weather/index", JuheData.GET, parameters, new DataCallBack() {
@Override
public void onSuccess(int i, String s) {
try {
JSONObject result = new JSONObject(s).getJSONObject("result");
//today
JSONObject today = result.getJSONObject("today");
view.setTextViewText(R.id.widget_city, today.getString("city"));
view.setTextViewText(R.id.widget_temperature, today.getString("temperature"));
view.setTextViewText(R.id.widget_weather, today.getString("weather"));
view.setTextViewText(R.id.widget_wind, today.getString("wind"));
view.setTextViewText(R.id.widget_date_week, today.getString("date_y") + " " + today.getString("week"));
//weather image
view.setImageViewResource(R.id.widget_weather_image, setWeatherImage(today.getString("weather")));
//sk
JSONObject sk = result.getJSONObject("sk");
view.setTextViewText(R.id.widget_update_time, "更新于" + sk.getString("time"));
//commit
ComponentName componentName = new ComponentName(context, DesktopWidget.class);
appWidgetManager.updateAppWidget(componentName, view);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFinish() {
Toast.makeText(context, "天气组件更新完成", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int i, String s, Throwable throwable) {
Toast.makeText(context, "天气组件更新失败", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
}
@Override
public void onReceive(final Context context, Intent intent) {
if (intent.getAction().equals("com.kyletung.kylejuheweather.UPDATE_WIDGET")) {
view = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
view.setImageViewResource(R.id.widget_background, R.drawable.widget_background);
//update data
Parameters parameters = new Parameters();
//set city
if (city == null) {
city = "杭州";
}
parameters.add("cityname", city);
JuheData.executeWithAPI(context, 39, "http://v.juhe.cn/weather/index", JuheData.GET, parameters, new DataCallBack() {
@Override
public void onSuccess(int i, String s) {
try {
JSONObject result = new JSONObject(s).getJSONObject("result");
//today
JSONObject today = result.getJSONObject("today");
view.setTextViewText(R.id.widget_city, today.getString("city"));
view.setTextViewText(R.id.widget_temperature, today.getString("temperature"));
view.setTextViewText(R.id.widget_weather, today.getString("weather"));
view.setTextViewText(R.id.widget_wind, today.getString("wind"));
view.setTextViewText(R.id.widget_date_week, today.getString("date_y") + " " + today.getString("week"));
//weather image
view.setImageViewResource(R.id.widget_weather_image, setWeatherImage(today.getString("weather")));
//sk
JSONObject sk = result.getJSONObject("sk");
view.setTextViewText(R.id.widget_update_time, "更新于" + sk.getString("time"));
//commit
ComponentName componentName = new ComponentName(context, DesktopWidget.class);
AppWidgetManager.getInstance(context).updateAppWidget(componentName, view);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFinish() {
Toast.makeText(context, "天气组件更新完成", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int i, String s, Throwable throwable) {
Toast.makeText(context, "天气组件更新失败", Toast.LENGTH_SHORT).show();
}
});
}
super.onReceive(context, intent);
}
public int setWeatherImage(String weather) {
if (weather.equals("晴")) {
return R.drawable.ic_weather_sunny_grey600_24dp;
} else if (weather.equals("多云") || weather.equals("多云转晴")) {
return R.drawable.ic_weather_partlycloudy_grey600_24dp;
} else if (weather.equals("阴") || weather.equals("阵雨转阴") || weather.equals("阴转多云")) {
return R.drawable.ic_weather_cloudy_grey600_24dp;
} else if (weather.equals("阵雨") || weather.equals("雨夹雪") || weather.equals("小雨") || weather.equals("中雨") || weather.equals("冻雨") || weather.equals("小雨-中雨")) {
return R.drawable.ic_weather_rainy_grey600_24dp;
} else if (weather.equals("雷阵雨伴有冰雹")) {
return R.drawable.ic_weather_hail_grey600_24dp;
} else if (weather.equals("大雨") || weather.equals("暴雨") || weather.equals("大暴雨") || weather.equals("特大暴雨") || weather.equals("中雨-大雨") || weather.equals("大雨-暴雨") || weather.equals("暴雨-大暴雨") || weather.equals("大暴雨-特大暴雨")) {
return R.drawable.ic_weather_pouring_grey600_24dp;
} else if (weather.equals("阵雪") || weather.equals("小雪") || weather.equals("中雪") || weather.equals("大雪") || weather.equals("暴雪") || weather.equals("小雪-中雪") || weather.equals("中雪-大雪") || weather.equals("大雪-暴雪")) {
return R.drawable.ic_weather_snowy_grey600_24dp;
} else if (weather.equals("雾") || weather.equals("霾")) {
return R.drawable.ic_weather_fog_grey600_24dp;
} else if (weather.equals("沙尘暴") || weather.equals("扬沙") || weather.equals("强沙尘暴")) {
return R.drawable.ic_weather_windy_grey600_24dp;
} else if (weather.equals("浮尘")) {
return R.drawable.ic_weather_windy_variant_grey600_24dp;
} else if (weather.equals("雷阵雨")) {
return R.drawable.ic_weather_lightning_grey600_24dp;
} else {
return R.drawable.ic_weather_cloudy_grey600_24dp;
}
}
}
| true |
a19e731bf81d613e3e6343f077d77cd0ab5d3ccd | Java | earl86/heisenberg | /src/main/server/com/baidu/hsb/mysql/bio/executor/XAMultiNodeExecutor.java | UTF-8 | 25,090 | 1.648438 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright (C) 2019 Baidu, Inc. All Rights Reserved.
*/
package com.baidu.hsb.mysql.bio.executor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import com.baidu.hsb.config.ErrorCode;
import com.baidu.hsb.config.util.ByteUtil;
import com.baidu.hsb.config.util.LoggerUtil;
import com.baidu.hsb.mysql.PacketUtil;
import com.baidu.hsb.mysql.bio.Channel;
import com.baidu.hsb.mysql.bio.MySQLChannel;
import com.baidu.hsb.mysql.bio.executor.MultiNodeTask.ErrInfo;
import com.baidu.hsb.mysql.xa.XAOp;
import com.baidu.hsb.net.mysql.BinaryPacket;
import com.baidu.hsb.net.mysql.EOFPacket;
import com.baidu.hsb.net.mysql.ErrorPacket;
import com.baidu.hsb.net.mysql.FieldPacket;
import com.baidu.hsb.net.mysql.MySQLPacket;
import com.baidu.hsb.net.mysql.OkPacket;
import com.baidu.hsb.route.RouteResultset;
import com.baidu.hsb.route.RouteResultsetNode;
import com.baidu.hsb.server.ServerConnection;
import com.baidu.hsb.server.parser.ServerParse;
import com.baidu.hsb.server.session.BlockingSession;
import com.baidu.hsb.server.session.XASession;
import com.baidu.hsb.util.StringUtil;
/**
* 多节点多sql任务器
*
* @author brucexx
*
*/
public class XAMultiNodeExecutor {
protected static boolean IS_DEBUG = true;
protected static final Logger LOGGER = Logger.getLogger(XAMultiNodeExecutor.class);
protected static final int RECEIVE_CHUNK_SIZE = 16 * 1024;
protected AtomicBoolean isFail = new AtomicBoolean(false);
protected int unfinishedNodeCount;
protected AtomicBoolean fieldEOF = new AtomicBoolean(false);
protected byte packetId;
protected long affectedRows;
protected long insertId;
protected ByteBuffer buffer;
protected ReentrantLock lock = new ReentrantLock();
protected Condition taskFinished = lock.newCondition();
protected DefaultCommitExecutor icExecutor = new DefaultCommitExecutor() {
@Override
protected String getErrorMessage() {
return "Internal commit";
}
@Override
protected Logger getLogger() {
return MultiNodeTask.LOGGER;
}
};
protected long nodeCount = 0;
protected long totalCount = 0;
protected AtomicLong exeTime;
protected RouteResultsetNode[] nodes;
protected BlockingSession ss;
protected int flag;
protected String oSql;
protected Map<String, AtomicInteger> runData = new HashMap<String, AtomicInteger>();
protected byte[] funcCachedData;
protected int type;
protected int op;
int errno;
String errMessage;
protected void init(RouteResultsetNode[] nodes, final BlockingSession ss, final int flag, int type, int op) {
String xId = ss.getSource().getXaSession().getXid();
this.op = op;
this.nodes = nodes;
this.ss = ss;
this.flag = flag;
this.type = type;
this.funcCachedData = new byte[0];
this.isFail.set(false);
this.unfinishedNodeCount = 0;
this.nodeCount = 0;
// 重新组织rrn nodes里的sql
XAUtil.genMulti(op, xId, nodes);
totalCount = unfinishedNodeCount;
this.fieldEOF.set(false);
this.packetId = 0;
this.affectedRows = 0L;
this.insertId = 0L;
this.buffer = ss.getSource().allocate();
exeTime = new AtomicLong(0);
}
/**
*
* @param sql
*/
public XAMultiNodeExecutor() {
}
public void setSql(String sql) {
this.oSql = sql;
}
public void execute(RouteResultsetNode[] nodes, final BlockingSession ss, final int flag, int type, int op) {
init(nodes, ss, flag, type, op);
String xId = ss.getSource().getXaSession().getXid();
LOGGER.info("xId:" + xId + "," + (XAUtil.convert(op)));
if (ss.getSource().isClosed()) {
decrementCountToZero();
ss.getSource().recycle(this.buffer);
return;
}
RouteResultsetNode[] newNodes = XAUtil.genNodesByAddr(nodes);
for (RouteResultsetNode rrn : newNodes) {
unfinishedNodeCount += rrn.getSqlCount();
this.nodeCount++;
runData.put(rrn.getName(), new AtomicInteger(rrn.getSqlCount()));
}
ThreadPoolExecutor exec = ss.getSource().getProcessor().getExecutor();
for (final RouteResultsetNode rrn : newNodes) {
final Channel c = ss.getTarget().get(rrn);
if (c != null && !c.isClosed()) {
if (op == 1) {
exec.execute(new Runnable() {
@Override
public void run() {
execute0(rrn, c, ss, flag, exeTime);
}
});
} else {
if (!c.isRunning()) {
exec.execute(new Runnable() {
@Override
public void run() {
execute0(rrn, c, ss, flag, exeTime);
}
});
} else {
if (IS_DEBUG) {
//
LOGGER.info("op[" + op + "]新建之0。。。");
}
newExecute(rrn, ss, flag, exeTime);
}
}
} else {
if (IS_DEBUG) {
//
LOGGER.info("op[" + op + "]新建之1。。。");
}
newExecute(rrn, ss, flag, exeTime);
}
}
}
/**
* 新通道的执行
*/
protected void newExecute(final RouteResultsetNode rrn, final BlockingSession ss, final int flag,
final AtomicLong exeTime) {
final ServerConnection sc = ss.getSource();
// 提交执行任务
sc.getProcessor().getExecutor().execute(new Runnable() {
@Override
public void run() {
try {
runTask(rrn, ss, sc, flag, exeTime);
} catch (Exception e) {
killServerTask(rrn, ss);
failFinish(ss, ErrorCode.ER_MULTI_EXEC_ERROR, e.getMessage());
}
}
});
}
protected void killServerTask(RouteResultsetNode rrn, BlockingSession ss) {
ConcurrentMap<RouteResultsetNode, Channel> target = ss.getTarget();
Channel c = target.get(rrn);
if (c != null) {
c.kill();
}
}
/**
* 执行
*/
protected void execute0(RouteResultsetNode rrn, Channel c, BlockingSession ss, int flag, final AtomicLong exeTime) {
if (IS_DEBUG) {
//
LOGGER.info("op[" + op + "]复用之。。。");
}
ServerConnection sc = ss.getSource();
// 中间有中断就不执行了。。
if (isFail.get() || sc.isClosed()) {
// failFinish(ss, errno, errMessage);
// c.setRunning(false);
decrementCount(rrn.getSqlCount());
if (op > 0) {
c.setRunning(false);
}
return;
}
long s = System.currentTimeMillis();
int ac = 0;
extSql: for (final String stmt : rrn.getStatement()) {
// 这里再reuse op==1 必须要命中op==0执行过的连接,如果不是之前执行过的连接选择跳过
// if (op == 1) {
// if (!ss.getSource().getXaSession().xaMustReuse(c, stmt, flag)) {
// decrementCountBy(1);
// continue;
// }
// }
// xa 操作对于同一物理地址不可重复执行
// if (!ss.getSource().getXaSession().canRepeat(((MySQLChannel) c), stmt)) {
// decrementCount(1);
// continue;
// }
if (IS_DEBUG) {
LOGGER.info(rrn.getName() + "," + "stmt:" + stmt + ",execute-->" + ((MySQLChannel) c).getId()
+ ",unfinished->" + unfinishedNodeCount);
}
// op==0时 先buf conn
// ss.getSource().getXaSession().bufConn(c, stmt, flag);
try {
if (isFail.get() || sc.isClosed()) {
//
decrementCount(rrn.getSqlCount() - ac);
// 此处op=0以后必须要复用
if (op > 0) {
c.setRunning(false);
}
return;
}
// 执行并等待返回
BinaryPacket bin = ((MySQLChannel) c).execute(stmt, rrn, sc, false);
ac++;
// 接收和处理数据
final ReentrantLock lock = XAMultiNodeExecutor.this.lock;
lock.lock();
try {
switch (bin.data[0]) {
case ErrorPacket.FIELD_COUNT:
if (handleFailure(stmt, (MySQLChannel) c, ss, rrn, bin, null, exeTime)) {
continue;
} else {
break;
}
case OkPacket.FIELD_COUNT:
OkPacket ok = new OkPacket();
ok.read(bin);
affectedRows += ok.affectedRows;
if (ok.insertId > 0) {
insertId = (insertId == 0) ? ok.insertId : Math.min(insertId, ok.insertId);
}
handleSuccessOK((MySQLChannel) c, ss, rrn, ok);
break;
default: // HEADER|FIELDS|FIELD_EOF|ROWS|LAST_EOF
final MySQLChannel mc = (MySQLChannel) c;
if (fieldEOF.get()) {
for (;;) {
bin = mc.receive();
switch (bin.data[0]) {
case ErrorPacket.FIELD_COUNT:
// 此处不会忽略,因为xa系列都是非rows
handleFailure(stmt, (MySQLChannel) c, ss, rrn, bin, null, exeTime);
continue extSql;
case EOFPacket.FIELD_COUNT:
handleRowData(rrn, (MySQLChannel) c, ss, exeTime, stmt);
continue extSql;
default:
// 直接过滤掉fields
continue;
}
}
} else {
bin.packetId = ++packetId;// HEADER
List<MySQLPacket> headerList = new LinkedList<MySQLPacket>();
headerList.add(bin);
for (;;) {
bin = mc.receive();
// LOGGER.info("NO_FIELD_EOF:" +
// com.baidu.hsb.route.util.ByteUtil.formatByte(bin.data));
switch (bin.data[0]) {
case ErrorPacket.FIELD_COUNT:
handleFailure(stmt, (MySQLChannel) c, ss, rrn, bin, null, exeTime);
continue extSql;
case EOFPacket.FIELD_COUNT:
bin.packetId = ++packetId;// FIELD_EOF
for (MySQLPacket packet : headerList) {
buffer = packet.write(buffer, sc);
}
headerList = null;
buffer = bin.write(buffer, sc);
fieldEOF.set(true);
handleRowData(rrn, (MySQLChannel) c, ss, exeTime, stmt);
continue extSql;
default:
bin.packetId = ++packetId;// FIELDS
switch (flag) {
case RouteResultset.REWRITE_FIELD:
StringBuilder fieldName = new StringBuilder();
fieldName.append("Tables_in_").append(ss.getSource().getSchema());
FieldPacket field = PacketUtil.getField(bin, fieldName.toString());
headerList.add(field);
break;
default:
headerList.add(bin);
}
}
}
}
}
} finally {
lock.unlock();
}
} catch (final Exception e) {
LOGGER.error("exception " + ss.getSource() + ",sql[" + stmt + "]", e);
handleFailure(stmt, (MySQLChannel) c, ss, rrn, null, new SimpleErrInfo(e, ErrorCode.ER_YES, sc, rrn),
exeTime);
c.close();
} finally {
long e = System.currentTimeMillis() - s;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[" + rrn.getName() + "][" + stmt + "]" + "exetime:" + e + "ms pre:" + exeTime.get());
}
exeTime.getAndAdd(e);
}
}
}
/**
* @throws nothing never throws any exception
*/
protected void handleSuccessOK(MySQLChannel c, BlockingSession ss, RouteResultsetNode rrn, OkPacket ok) {
if (decrementCountAndIsZero(1)) {
if (isFail.get()) {
writeError(ss, errno, errMessage);
return;
}
try {
ServerConnection source = ss.getSource();
ok.packetId = ++packetId;// OK_PACKET
ok.affectedRows = affectedRows;
if (insertId > 0) {
ok.insertId = insertId;
source.setLastInsertId(insertId);
}
sucXaOp(c, ss, rrn, op, exeTime, new Runback() {
@Override
public void g() {
ok.write(source);
source.recycle(buffer);
}
});
} catch (Exception e) {
LOGGER.warn("exception happens in success notification: " + ss.getSource(), e);
}
}
}
protected void handleSuccessEOF(String stmt, MySQLChannel c, BlockingSession ss, final RouteResultsetNode rrn,
BinaryPacket bin, final AtomicLong exeTime) {
if (decrementCountAndIsZero(1)) {
try {
if (isFail.get()) {
writeError(ss, errno, errMessage);
return;
}
try {
ServerConnection source = ss.getSource();
// 忽略自动提交
// if (source.isAutocommit()) {
// ss.release();
// }
if (flag == RouteResultset.SUM_FLAG || flag == RouteResultset.MAX_FLAG
|| flag == RouteResultset.MIN_FLAG) {
BinaryPacket data = new BinaryPacket();
data.packetId = ++packetId;
data.data = funcCachedData;
buffer = data.write(buffer, source);
}
bin.packetId = ++packetId;// LAST_EOF
sucXaOp(c, ss, rrn, op, exeTime, new Runback() {
@Override
public void g() {
source.write(bin.write(buffer, source));
source.recycle(buffer);
}
});
} catch (Exception e) {
LOGGER.warn("exception happens in success notification: " + ss.getSource(), e);
}
} finally {
LoggerUtil.printDigest(LOGGER, (exeTime.get() / nodeCount),
com.baidu.hsb.route.util.StringUtil.join(rrn.getStatement(), '#'));
}
}
}
/**
* 成功操作
*
* @param ss
* @param bin
* @param op
*/
private void sucXaOp(MySQLChannel c, BlockingSession ss, final RouteResultsetNode rrn, int op,
final AtomicLong exeTime, Runback r) {
// 此处后台做一些额外操作
XASession xaSession = ss.getSource().getXaSession();
if (xaSession == null) {
writeError(ss, ErrorCode.ER_XA_CONTEXT_MISSING, "xa session lost");
return;
}
switch (op) {
// xa start ok
case 0:
// 回写ok
xaSession.setStatus(XAOp.START);
r.g();
// 此处先不停mysqlchannel
return;
// end & pre ok
case 1:
try {
// 存储至redis
xaSession.saveStore("prepare");
xaSession.setStatus(XAOp.END_PREPARE);
// 此处已经代表分布式事务整体成功
LOGGER.info("xid:" + xaSession.getXid() + " xa end&prepare suc!");
} catch (Exception e) {
LOGGER.error("save redis fail", e);
writeError(ss, ErrorCode.ER_XA_SAVE_REDIS_ERROR, "save redis error");
//
// writeError(ss, ErrorCode.ER_XA_SAVE_REDIS_ERROR, "save redis error");
break;
// 发起rollback,此处可异步
// ss.getSource().selfRollback();
} finally {
/**
*
* if (runData.get(rrn.getName()).decrementAndGet() == 0) { c.setRunning(false);
* }
*/
}
try {
// 成功后就commit,这里其实commit结果已经不重要,为了维持对上的复用,还是选择在commit之后 writeOK
xaCommit(rrn, ss, flag);
} catch (Exception e) {
LOGGER.error("commit request error", e);
// 此处不需要rollback,只需要异步来恢复即可
}
break;
// xa commit suc
case 2:
try {
// 这里删除key或保存key都可以
// xaSession.delKey();
xaSession.saveStore("commit");
xaSession.setStatus(XAOp.COMMIT);
// 代表
xaSession.release();
// 即使没有回写成功也可以
ss.writeOk();
// log
LOGGER.info("xid:" + xaSession.getXid() + " xa commit suc!");
} catch (Exception e) {
LOGGER.error("commit save error", e);
// 此处不需要rollback,只需要异步来恢复即可
}
break;
// xa rollback suc
case 3:
// 回写错误码
xaSession.setStatus(XAOp.ROLLBACK);
xaSession.release();
ss.writeOk();
LOGGER.info("xid:" + xaSession.getXid() + " xa rollback suc!");
// writeError(ss);
break;
}
//
c.setRunning(false);
}
// 提交之
private void xaCommit(RouteResultsetNode rrn, BlockingSession ss, int flag) {
// xa commit
execute(this.nodes, ss, flag, ServerParse.XA, 2);
}
protected void handleRowData(final RouteResultsetNode rrn, final MySQLChannel c, BlockingSession ss,
final AtomicLong exeTime, String stmt) throws IOException {
final ServerConnection source = ss.getSource();
BinaryPacket bin = null;
for (;;) {
bin = ((MySQLChannel) c).receive();
switch (bin.data[0]) {
case ErrorPacket.FIELD_COUNT:
handleFailure(stmt, c, ss, rrn, bin, null, exeTime);
return;
case EOFPacket.FIELD_COUNT:
handleSuccessEOF(stmt, c, ss, rrn, bin, exeTime);
return;
default:
if (flag == RouteResultset.SUM_FLAG || flag == RouteResultset.MAX_FLAG
|| flag == RouteResultset.MIN_FLAG) {
funcCachedData = ByteUtil.calc(funcCachedData, bin.getData(), flag);
} else {
bin.packetId = ++packetId;// ROWS
buffer = bin.write(buffer, source);
// size += bin.packetLength;
// if (size > RECEIVE_CHUNK_SIZE) {
// // LOGGER.info(rrn.getName() + "hasNext-->");
// handleNext(rrn, c, ss, exeTime, sql);
// return;
// }
}
}
}
}
private boolean failNeedAck(String stmt, int errno, int op) {
if (!XAUtil.isXAOp(stmt)) {
return true;
}
// rollback失败必须要返回 //过程commit中有失败呢?直接让上层超时吧
if (op == 3 || op == 1) {
return true;
}
if (XAUtil.isXAOp(stmt) && XAUtil.isXAIgnore(errno)) {
return false;
}
return true;
}
protected void runTask(final RouteResultsetNode rrn, final BlockingSession ss, final ServerConnection sc,
final int flag, final AtomicLong exeTime) {
// 取得数据通道
int i = rrn.getReplicaIndex();
Channel c = null;
try {
c = ss.getSource().getXaSession().getChannel(rrn, i);
} catch (final Exception e) {
LOGGER.error("get channel error", e);
failFinish(ss, ErrorCode.ER_BAD_DB_ERROR, "ER_BAD_DB_ERROR");
return;
}
c.setRunning(true);
Channel old = ss.getTarget().put(rrn, c);
if (old != null && c != old) {
old.close();
}
// 执行
execute0(rrn, c, ss, flag, exeTime);
}
private ErrorPacket g(BinaryPacket bin) {
ErrorPacket err = new ErrorPacket();
err.read(bin);
return err;
}
/**
* 如果出错,通过isFail在执行层包住 ,返回是否可忽略
*
* @param stmt
* @param c
* @param ss
* @param rrn
* @param bin
* @param errInfo
* @param exeTime
*/
protected boolean handleFailure(String stmt, MySQLChannel c, BlockingSession ss, RouteResultsetNode rrn,
BinaryPacket bin, ErrInfo errInfo, final AtomicLong exeTime) {
String sSql = com.baidu.hsb.route.util.StringUtil.join(rrn.getStatement(), '#');
try {
ErrorPacket err = bin != null ? g(bin) : null;
int errno = err != null ? err.errno : errInfo.getErrNo();
String errmsg = err != null ? StringUtil.decode(err.message, c.getCharset()) : errInfo.getErrMsg();
// 回写错误码
if (!failNeedAck(stmt, errno, op)) {
if (XAUtil.isXAIgnore(errno)) {
// 忽略错误
decrementCountBy(1);
return true;
} else {
// 有错误挺好
decrementCountBy(rrn.getSqlCount());
}
return false;
}
// 此处后台做一些额外操作
XASession xaSession = ss.getSource().getXaSession();
if (xaSession == null) {
writeError(ss, ErrorCode.ER_XA_CONTEXT_MISSING, "xa session lost");
return false;
}
if (op == 2) {
LOGGER.info("xid:" + xaSession.getXid() + " xa commit error :" + errno + ",msg:" + errmsg);
xaSession.release();
}
// 标记为执行失败,并记录第一次异常信息。
if (!isFail.getAndSet(true)) {
this.errno = errno;
this.errMessage = errmsg;
LOGGER.warn(
rrn.getName() + " error[" + err + "," + errmsg + "] in sql[" + stmt + "]node:" + rrn.getName());
} else {
// 如果有并发过来,直接忽略
return false;
}
// 此处做一些额外操作
switch (op) {
// sql错误,给客户端回滚
case 0:
LOGGER.info("xid:" + xaSession.getXid() + " xa start error:" + errno + ",msg:" + errmsg);
// 回写原错误,上层有回滚,下面也有回滚
notifyFailure(ss, err);
// 此处不能结束mysqlchannel
return false;
// end&prepare 错误 客户端发起回滚,如果客户端回滚不成异步recover(这里可能不需要)
case 1:
LOGGER.info("xid:" + xaSession.getXid() + " xa end&prepare error:" + errno + ",msg:" + errmsg);
// 回写原错误,上层有回滚,下面也有回滚
notifyFailure(ss, err);
break;
// 内部 commit error,不需要管了,异步recover
// case 2:
// LOGGER.info("xid:" + xaSession.getXid() + " xa commit error :" + err.errno + ",msg:"
// + com.baidu.hsb.util.StringUtil.decode(err.message, mc.getCharset()));
// // sc.write(err.write(sc.allocate(), sc));
// // err(err.errno, com.baidu.hsb.util.StringUtil.decode(err.message,
// // mc.getCharset()));
//
// // 全局rollback,可要可不要,因为客户端也会发起
// // ss.getSource().detectRollback();
// break;
case 3:
LOGGER.info("xid:" + xaSession.getXid() + " xa rollback error:" + errno + ",msg:" + errmsg);
// 如果rollback err暂时不用管
notifyFailure(ss, err);
xaSession.release();
break;
}
c.setRunning(false);
} catch (Exception e) {
LOGGER.warn("handleFailure failed in " + getClass().getSimpleName() + ", source = " + ss.getSource(), e);
} finally {
LoggerUtil
.printDigest(LOGGER,
(long) (exeTime.get()
/ ((double) (totalCount - unfinishedNodeCount) * nodeCount / (double) totalCount)),
sSql);
}
return false;
}
protected void failFinish(BlockingSession ss, int errno, String errMessage) {
forceFinish();
writeError(ss, errno, errMessage);
}
protected void notifyFailure(BlockingSession ss, ErrorPacket bin) {
try {
// 不需要清理
// ss.clear();
ServerConnection sc = ss.getSource();
// 清空buf
sc.recycle(this.buffer);
sc.write(bin.write(sc.allocate(), sc));
// sc.write(bin.write(buffer, sc));
} catch (Exception e) {
LOGGER.warn("exception happens in failure notification: " + ss.getSource(), e);
}
}
/**
* 通知,执行异常
*
* @throws nothing never throws any exception
*/
protected void writeError(BlockingSession ss, int errno, String errMessage) {
try {
// 不需要清理
// ss.clear();
ServerConnection sc = ss.getSource();
sc.setTxInterrupt();
// 通知
ErrorPacket err = new ErrorPacket();
err.packetId = ++packetId;// ERROR_PACKET
err.errno = errno;
err.message = StringUtil.encode(errMessage, sc.getCharset());
// 清空buf
sc.recycle(this.buffer);
sc.write(err.write(buffer, sc));
} catch (Exception e) {
LOGGER.warn("exception happens in failure notification: " + ss.getSource(), e);
}
}
/**
* 是否已完成
*
* @return
*/
public boolean isTaskFinish() {
return unfinishedNodeCount <= 0;
}
public void terminate() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
while (unfinishedNodeCount > 0) {
taskFinished.await();
}
} finally {
lock.unlock();
}
icExecutor.terminate();
}
protected void decrementCount(int c) {
unfinishedNodeCount = unfinishedNodeCount - c;
}
protected void decrementCountToZero() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
unfinishedNodeCount = 0;
taskFinished.signalAll();
} finally {
lock.unlock();
}
}
protected void forceFinish() {
decrementCountToZero();
}
protected void decrementCountBy(int c) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
unfinishedNodeCount = unfinishedNodeCount - c;
} finally {
lock.unlock();
}
}
protected boolean decrementCountAndIsZero(int c) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
unfinishedNodeCount = unfinishedNodeCount - c;
int ufc = unfinishedNodeCount;
taskFinished.signalAll();
return ufc <= 0;
} finally {
lock.unlock();
}
}
protected static interface Runback {
void g();
}
protected static class BinaryErrInfo implements ErrInfo {
private String errMsg;
private int errNo;
private ServerConnection source;
private RouteResultsetNode rrn;
private MySQLChannel mc;
public BinaryErrInfo(MySQLChannel mc, BinaryPacket bin, ServerConnection sc, RouteResultsetNode rrn) {
this.mc = mc;
this.source = sc;
this.rrn = rrn;
ErrorPacket err = new ErrorPacket();
err.read(bin);
this.errMsg = (err.message == null) ? null : StringUtil.decode(err.message, mc.getCharset());
this.errNo = err.errno;
}
@Override
public int getErrNo() {
return errNo;
}
@Override
public String getErrMsg() {
return errMsg;
}
@Override
public void logErr() {
try {
LOGGER.warn(mc.getErrLog(rrn.getLogger(), errMsg, source));
} catch (Exception e) {
}
}
}
protected static class SimpleErrInfo implements ErrInfo {
private Exception e;
private int errNo;
private String msg;
private ServerConnection source;
private RouteResultsetNode rrn;
public SimpleErrInfo(Exception e, int errNo, ServerConnection sc, RouteResultsetNode rrn) {
this(e, errNo, null, sc, rrn);
}
public SimpleErrInfo(Exception e, int errNo, String msg, ServerConnection sc, RouteResultsetNode rrn) {
this.e = e;
this.errNo = errNo;
this.source = sc;
this.rrn = rrn;
this.msg = msg;
}
@Override
public int getErrNo() {
return errNo;
}
@Override
public String getErrMsg() {
String msg = e == null ? this.msg : e.getMessage();
return msg == null ? e.getClass().getSimpleName() : msg;
}
@Override
public void logErr() {
try {
LOGGER.warn(new StringBuilder().append(source).append(rrn).toString(), e);
} catch (Exception e) {
}
}
}
}
| true |
6bd925a86198cc0b8f752dbca436066cacda51a6 | Java | qq56860/Advanced | /src/written_examination/toutiao_返回相同单词最多data.java | UTF-8 | 1,977 | 3.421875 | 3 | [] | no_license | package written_examination;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
/*
* n: 源数据条数
* m:查询数据条数
* data[]:源数据数组 每个元素都是一个英文单词,组成一个英文句子
* query[]:查询数据数组
*
* 要求:看作是 ---输入查询一个 查询句子query,去匹配data[]中,找出相同单词最多的一句data返回
*
* trick:单词的去重 包括data的去重,和query的去重(query没去重 0.0 好尴尬)
*
* */
public class toutiao_返回相同单词最多data {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String N_M[] = sc.nextLine().split(" ");
int n = Integer.valueOf(N_M[0]);
int m = Integer.valueOf(N_M[1]);
String data[] = new String[n];
String query[] = new String[m];
for (int i = 0; i < n; i++) {
data[i] = sc.nextLine();
}
for (int i = 0; i < m; i++) {
query[i] = sc.nextLine();
}
List<HashMap<String, Integer>> list = new ArrayList<HashMap<String,Integer>>();
for (int i = 0; i < n; i++) {
HashMap<String, Integer> dataMap = new HashMap<String, Integer>();
String dataSplit[] = data[i].split(" ");
for (int j = 0; j < dataSplit.length; j++) {
dataMap.put(dataSplit[j], i);
}
list.add(dataMap);
}
int[] same_count = new int[n];
for (int i = 0; i < query.length; i++) {
String querySplit[] = query[i].split(" ");
for (int j = 0; j < querySplit.length; j++) {
for (int j2 = 0; j2 < n; j2++) {
if(list.get(j2).containsKey(querySplit[j])){
same_count[j2] += 1 ;
}
}
}
int out = 0;
for (int j = 0; j < same_count.length; j++) {
if(same_count[j] > same_count[out]){
// System.out.println("di"+j+"句多");
out = j;
}
}
// System.out.println("输出第"+out);
System.out.println(data[out].toString());
}
}
}
| true |
ce74a2c684f7e2236074c8693279292a76e2f109 | Java | organization/ParfaitAuth | /src/main/java/hmhmmhm/ParfaitAuth/Commands/BanSubnetAddressCommand.java | UTF-8 | 3,407 | 2.75 | 3 | [] | no_license | package hmhmmhm.ParfaitAuth.Commands;
import cn.nukkit.command.Command;
import cn.nukkit.command.CommandSender;
import cn.nukkit.scheduler.TaskHandler;
import hmhmmhm.ParfaitAuth.ParfaitAuthPlugin;
import hmhmmhm.ParfaitAuth.PlayerIdentifier;
import hmhmmhm.ParfaitAuth.Tasks.BanAddressTask;
import hmhmmhm.ParfaitAuth.Tasks.SendMessageTask;
public class BanSubnetAddressCommand extends ParfaitAuthCommand {
public BanSubnetAddressCommand(ParfaitAuthPlugin plugin) {
super(plugin);
this.load("ban-subnet", true);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
// /s <식별번호|서브넷> <기간> <사유>
// 해당 서브넷 혹은 유저의 서브넷을 차단합니다.
// (기간에 숫자만 입력시 분단위가 되며)
// (앞에 h, d를 붙일 수 있고, 각각 시간,일자단위)
// (사유는 반드시 적어야하며 띄어쓰기가 가능함)
if (command.getName().toLowerCase() == this.commandName) {
if (args.length < 3) {
SendMessageTask task = new SendMessageTask(sender, this.commandKey + "-help-");
TaskHandler handler = this.getServer().getScheduler().scheduleRepeatingTask(task, 10);
task.setHandler(handler);
return true;
}
// IP나 UUID중 하나를 확인
String identifierUUID = null;
String address = null;
// 식별번호 확인
String identifierString = null;
int identifierInt = 0;
if (args[0].split("\\[").length == 2 && args[0].split("\\[")[1].split("\\]").length == 1)
identifierString = args[0].split("\\[")[1].split("\\]")[0];
if (identifierString == null)
identifierString = args[0];
// 정수형으로 변환
try {
identifierInt = Integer.valueOf(identifierString);
identifierUUID = PlayerIdentifier.get(identifierInt).toString();
} catch (NumberFormatException e) {
if (args[0].split("\\.").length == 2) {
address = args[0];
} else {
sender.sendMessage(plugin.getMessage("error-cant-find-player-identifier-or-address"));
return true;
}
}
// 기간 확인
String periodString = null;
int periodInt = 0;
if (periodString == null)
periodString = args[1];
// 정수형으로 변환
try {
periodInt = Integer.valueOf(periodString);
} catch (NumberFormatException e) {
// 시간과 일단위 분단위로 변경
try {
if (args[1].split("h").length == 2) {
periodString = args[1].split("h")[1];
periodInt = Integer.valueOf(periodString);
periodInt *= 60;
}
if (args[1].split("d").length == 2) {
periodString = args[1].split("d")[1];
periodInt = Integer.valueOf(periodString);
periodInt *= 60;
periodInt *= 24;
}
} catch (NumberFormatException e1) {
sender.sendMessage(plugin.getMessage("error-wrong-period"));
return true;
}
}
// 사유확인
String cause = "";
// shift 0 1 진행후 2부터 끝까지 합치기
for (int index = 2; index <= (args.length - 1); index++) {
cause += args[index];
// 문자열에 공백추가
if (index != 2)
cause += " ";
}
BanAddressTask task = new BanAddressTask();
task.uuid = identifierUUID;
task.address = address;
task.periodInt = periodInt;
task.cause = cause;
this.getServer().getScheduler().scheduleAsyncTask(task);
return true;
}
return false;
}
}
| true |
65c1303d05aca79c727b8ea4d1cb83f8ad7cc882 | Java | eltld/CommonJar | /src/com/froyo/commonjar/test/TestAdapter.java | UTF-8 | 711 | 2.421875 | 2 | [] | no_license | package com.froyo.commonjar.test;
import java.util.List;
import android.view.View;
import android.widget.TextView;
import com.froyo.commonjar.activity.BaseActivity;
import com.froyo.commonjar.adapter.SimpleAdapter;
public class TestAdapter extends SimpleAdapter<String> {
public TestAdapter(List<String> data, BaseActivity activity, int layoutId) {
super(data, activity, layoutId, ViewHolder.class);
}
@Override
public void doExtra(View convertView, String item, int position) {
ViewHolder h = (ViewHolder) holder;
h.tv_name.setText(item);
}
public static class ViewHolder{
//这里viewHolder的属性的名字必须和对应item的layout里面的id的名字一样
TextView tv_name;
}
}
| true |
f77e2c52b880a87ea160ee5b068cadefaa669537 | Java | maheshbharathinv/addressbook | /src/main/java/com/pwc/addressbook/controller/AddressBookController.java | UTF-8 | 2,947 | 2.390625 | 2 | [] | no_license | package com.pwc.addressbook.controller;
import com.pwc.addressbook.exception.ContactValidationException;
import com.pwc.addressbook.model.Contact;
import com.pwc.addressbook.service.AddressBookService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.Set;
import static com.pwc.addressbook.constants.StringConstants.COLON;
import static com.pwc.addressbook.constants.StringConstants.SLASH;
import static org.springframework.http.HttpHeaders.LOCATION;
import static org.springframework.http.HttpStatus.CREATED;
@Slf4j
@Tag(name = "Address Book")
@RestController
public class AddressBookController {
@Autowired
private AddressBookService addressBookService;
@Value("${base.uri:localhost}")
private String host;
@Value("${server.port}")
private String port;
@Value("${server.servlet.context-path}")
private String uri;
@Operation(summary = "This end point add a new contact to address book")
@PostMapping(path="/add")
public ResponseEntity<?> addContact(@RequestBody @Valid final Contact contact, final Errors errors) {
log.info("creating new contact");
if(errors.hasErrors()) {
throw new ContactValidationException(errors);
}
addressBookService.addContact(contact);
return ResponseEntity.status(CREATED).header(LOCATION, location(contact.getName())).build();
}
@Operation(summary = "This end point returns all the contacts in the address book. sortOrder = asc | desc")
@GetMapping(value = "/contacts")
public ResponseEntity<List<Contact>> getContacts(final @RequestParam(name = "sortOrder", defaultValue = "asc") String sortOrder) {
log.info("get all contacts");
return ResponseEntity.ok(addressBookService.getAllContacts(sortOrder));
}
@Operation(summary = "This end point returns unique contacts between two address books")
@PostMapping("/compare")
public ResponseEntity<Set<String>> getUniqueContacts(@RequestBody final List<String> contactNames) {
return ResponseEntity.ok(addressBookService.getUniqueContacts(contactNames));
}
@Operation(summary = "This end point returns phone no of a given contact name")
@GetMapping("/{name}")
public ResponseEntity<Contact> getContact(@PathVariable final String name) {
log.info("Get phone no for {}", name);
return ResponseEntity.ok(addressBookService.getContact(name));
}
private String location(final String name) {
return host + COLON + port + uri + SLASH + name;
}
}
| true |
9c9f6583d04781fd4795b5657dc4be4a0bd09ad5 | Java | MrLONGPENG/group | /module-core/src/main/java/com/mujugroup/core/service/AuthDataService.java | UTF-8 | 923 | 1.796875 | 2 | [] | no_license | package com.mujugroup.core.service;
import com.lveqia.cloud.common.objeck.DBMap;
import com.mujugroup.core.objeck.bo.TreeBo;
import com.mujugroup.core.objeck.vo.TreeVo;
import java.util.List;
import java.util.Map;
/**
* @author leolaurel
*/
public interface AuthDataService {
List<TreeBo> getAgentAuthData(long id);
List<TreeBo> getHospitalAuthData(long id);
List<TreeBo> getDepartmentAuthData(long id);
List<TreeBo> getAuthTreeByAid(String aid);
List<TreeBo> getAuthTreeByHid(String hid);
List<TreeVo> treeBoToVo(List<TreeBo> list);
String toJsonString(List<TreeBo> list);
int addAuthData(int uid, String[] authData);
int deleteByUid(int uid);
int updateAuthData(int uid, String[] authData);
List<String> getAuthDataList(int uid);
List<DBMap> getAuthData(int uid);
List<TreeBo> getAllAgentList();
Map<String, String> getAuthDataByUid(int uid);
}
| true |
bd9e74aedb2973e620730a3f1c83963b7b0b74f6 | Java | fluxitsoft/exception-manager | /em-server/src/main/java/ar/com/fluxit/em/controller/ErrorDetail.java | UTF-8 | 2,104 | 1.78125 | 2 | [
"Apache-2.0"
] | permissive | /*******************************************************************************
* FluxIT
* Copyright (c) 2013
* Argentina
*
* This 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 3 of
* the License, or (at your option) any later version.
*
* This 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. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package ar.com.fluxit.em.controller;
public class ErrorDetail {
private String id;
private String applicationName;
private String targetExceptionClassName;
private String targetExceptionShortClassName;
private String message;
private String time;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String getTargetExceptionClassName() {
return targetExceptionClassName;
}
public void setTargetExceptionClassName(String targetExceptionClassName) {
this.targetExceptionClassName = targetExceptionClassName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getTargetExceptionShortClassName() {
return targetExceptionShortClassName;
}
public void setTargetExceptionShortClassName(
String targetExceptionShortClassName) {
this.targetExceptionShortClassName = targetExceptionShortClassName;
}
}
| true |
0d52486d85fee4de3d5345fe8268dfb474f8c64d | Java | dpercoco/CRUDDemo | /ViewController/src/crud/JAVA/Recipe.java | UTF-8 | 36,624 | 2.03125 | 2 | [] | no_license | package crud.JAVA;
/**
* https://github.com/google/search-samples/blob/master/app-indexing/app/src/main/java/com/recipe_app/client/Recipe.java
*/
import crud.application.DBConnectionFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import javax.el.ValueExpression;
import oracle.adfmf.bindings.dbf.AmxIteratorBinding;
import oracle.adfmf.bindings.dbf.AmxTreeBinding;
import oracle.adfmf.bindings.iterator.BasicIterator;
import oracle.adfmf.framework.api.AdfmfJavaUtilities;
import oracle.adfmf.java.beans.PropertyChangeListener;
import oracle.adfmf.java.beans.PropertyChangeSupport;
import oracle.adfmf.java.beans.ProviderChangeListener;
import oracle.adfmf.java.beans.ProviderChangeSupport;
import oracle.adfmf.util.Utility;
import oracle.adfmf.util.logging.Trace;
import org.jsoup.Jsoup;
import org.jsoup.examples.HtmlToPlainText;
public class Recipe {
private int id = 0;
private String title="";
private String photo="";
private String description="";
private String prepTime="";
private String recipeUrl="";
private String item="";
private String googleRecipe="";
private List<Ingredient> recipeIngredients = new ArrayList<Ingredient>();
private static Map<String, Map<String, Ingredient>> shoppingItems = null;
private static shoppingListProcess slp = new shoppingListProcess();
private static AisleService aisle = new AisleService();
protected transient PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
protected transient ProviderChangeSupport providerChangeSupport = new ProviderChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
public void addProviderChangeListener(ProviderChangeListener l) {
providerChangeSupport.addProviderChangeListener(l);
}
public void removeProviderChangeListener(ProviderChangeListener l) {
providerChangeSupport.removeProviderChangeListener(l);
}
public Recipe() {
this.id = -1;
this.title = "";
this.recipeUrl = "";
this.prepTime = "";
}
public Recipe(int id, String title, String url) {
super();
this.id = id;
this.title = title;
this.recipeUrl = url;
}
public Recipe(int id, String title, String url, String description, String prepTime, String googleRecipe) {
super();
this.id = id;
this.title = title;
this.recipeUrl = url;
this.description = description;
this.prepTime = prepTime;
this.googleRecipe = googleRecipe;
}
public Recipe(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId() {
this.id = getRecipeID();
}
public Integer getRecipeID(){
Integer newId=0;
try {
Connection conn = DBConnectionFactory.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(RID) FROM RECIPES");
rs.beforeFirst();
if (rs.next()) {
newId = rs.getInt(1) + 1;
}
}
catch (Exception e) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "getRecipeID",
"#####EXCEPTION RECIPE ID:" + newId + " " + e.getMessage());
}
return newId;
}
public void setId(int id) {
int oldId = this.id;
this.id = id;
propertyChangeSupport.firePropertyChange("id", oldId, id);
}
public String getTitle() {
if (title.trim().length()==0) return "";
title = title.replace("\"", "");
title = title.replace("'","");
return title;
}
public void setTitle(String title) {
String oldTitle = this.title;
this.title = title;
//ValueExpression ve = AdfmfJavaUtilities.getValueExpression("#{applicationScope.selectedTitle}", String.class);
//ve.setValue(AdfmfJavaUtilities.getELContext(), title);
propertyChangeSupport.firePropertyChange("title", oldTitle, title);
}
public void setRecipeUrl(String url) {
String oldRecipeUrl = this.recipeUrl;
this.recipeUrl = url;
//ValueExpression ve = AdfmfJavaUtilities.getValueExpression("#{applicationScope.selectedUrl}", String.class);
//ve.setValue(AdfmfJavaUtilities.getELContext(), url);
propertyChangeSupport.firePropertyChange("recipeUrl", oldRecipeUrl, url);
}
public String getRecipeUrl() {
if (recipeUrl.trim().length()==0) return "";
recipeUrl = recipeUrl.replace("\"", "");
recipeUrl = recipeUrl.replace("'","''");
return recipeUrl;
}
public String getPhoto() {
return photo;
}
public String getItem() {
return item;
}
public void setItem(String item) {
String oldItem = this.item;
this.item = item;
propertyChangeSupport.firePropertyChange("photo", oldItem, item);
}
public String getDescription() {
description = description.replace("\"", "");
description = description.replace("'","");
return description;
}
public void setDescription(String description) {
String oldDescription = this.description;
this.description = description;
propertyChangeSupport.firePropertyChange("description", oldDescription, description);
}
public String getPrepTime() {
return prepTime;
}
public void setPrepTime(String prepTime) {
this.prepTime = prepTime;
}
public String getKey() {
Integer i = new Integer(id);
return i.toString();
}
public List<Ingredient> getIngredients() {
return getIngredientsFromStore();
}
public Recipe createRecipe(Recipe recipe) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, RecipeService.class, "addRecipe", recipe.getTitle());
//Recipe recipe = new Recipe();
try {
Connection conn = DBConnectionFactory.getConnection();
Statement stmt = conn.createStatement();
int newId = 1;
ResultSet rs = stmt.executeQuery("SELECT MAX(RID) FROM RECIPES");
rs.beforeFirst();
if (rs.next()) {
newId = rs.getInt(1) + 1;
}
recipe.setId(newId);
} catch (SQLException e) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, RecipeService.class, "addRecipe",
"##############SQL Exception: " + e.getMessage());
e.printStackTrace();
} catch (Exception exception) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, RecipeService.class, "addRecipe",
"##############Exception: " + exception.getMessage());
}
return recipe;
}
public Recipe (String url, String prepTime, String title) {
//Recipe recipe = new Recipe();
this.setId(0);
this.setPrepTime(prepTime);
this.setRecipeUrl(url);
this.setTitle(title);
}
public List<Recipe> getRecipesFromStore() {
List<Recipe> recipes = new ArrayList<Recipe>();
try {
Connection conn = DBConnectionFactory.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM RECIPES ORDER BY TITLE");
rs.beforeFirst();
while (rs.next()) {
int id = rs.getInt("RID");
String title = rs.getString("TITLE");
if (title.equals("null")) {
title = "";
}
String url = rs.getString("RECIPEURL");
if (url.equals("null")) {
url = "";
}
String description = rs.getString("DESCRIPTION");
if (description.equals("null")) {
description = "";
}
String preptime = rs.getString("PREPTIME");
if (preptime.equals("null")) {
preptime = "";
}
String googleRecipe = rs.getString("GOOGLERECIPE");
if (googleRecipe.equals("null")) {
googleRecipe = "";
}
Recipe r = new Recipe(id, title, url, description, preptime, googleRecipe);
if (!title.isEmpty()) {
recipes.add(r);
}
}
//providerChangeSupport.fireProviderRefresh("recipes");
} catch (SQLException e) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, RecipeService.class, "reloadRecipes",
"##############SQL Exception: " + e.getMessage());
e.printStackTrace();
} catch (Exception exception) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, RecipeService.class, "reloadRecipes",
"##############Exception: " + exception.getMessage());
}
return recipes;
}
public List<Ingredient> getIngredientsFromStore() {
ValueExpression ve = AdfmfJavaUtilities.getValueExpression("#{pageFlowScope.selectedRid}", Integer.class);
Object obj1 = ve.getValue(AdfmfJavaUtilities.getELContext());
Integer recipeId = (Integer) obj1;
this.id = recipeId;
Utility.ApplicationLogger.severe("getIngredientsFromStore RECIPE# " + this.getId());
recipeIngredients.clear();
try {
Connection conn = DBConnectionFactory.getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM INGREDIENTS WHERE RID =" + this.getId();
ResultSet result = stmt.executeQuery(sql);
result.beforeFirst();
if (!result.next() && this.getRecipeUrl()!=null) {
getIngredientsFromWeb(this.getRecipeUrl());
}
getIngredientsFromDB();
Utility.ApplicationLogger.severe("Recipe #" + this.getId() + " Ingredients: " + recipeIngredients.size());
} catch (Exception ex) {
Utility.ApplicationLogger.severe("EXCEPTION" + " " + ex.getMessage());
ex.printStackTrace();
throw new RuntimeException(ex);
}
return recipeIngredients;
}
private void getIngredientsFromDB() {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "##############getIngredientsFromDB", "RECIPE# " + id);
recipeIngredients.clear();
try {
Connection conn = DBConnectionFactory.getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM INGREDIENTS WHERE RID =" + id + " ORDER BY FOODGROUP, IID";;
ResultSet result = stmt.executeQuery(sql);
result.beforeFirst();
while (result.next()) {
Ingredient ingredient = new Ingredient();
ingredient.setRid(result.getInt("RID"));
ingredient.setId(result.getInt("IID"));
ingredient.setItem(result.getString("ITEM"));
ingredient.setFoodGroup(result.getString("FOODGROUP"));
ingredient.setMeasurement(result.getString("MEASUREMENT"));
ingredient.setContainer(result.getString("CONTAINR"));
ingredient.setQty(result.getDouble("QTY"));
ingredient.setAmount(result.getDouble("AMOUNT"));
ingredient.setNewItem(ingredient.getToString());
recipeIngredients.add(ingredient);
//Utility.ApplicationLogger.severe("Ingredient #" + ingredient.getId() + " " + ingredient.getItem());
}
Utility.ApplicationLogger.severe("Recipe #" + this.getId() + " Ingredients: " + recipeIngredients.size());
} catch (Exception ex) {
Utility.ApplicationLogger.severe("getIngredientsFromDB EXCEPTION" + " " + ex.getMessage());
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public String getIngredientFullString(Ingredient i) {
String toString = Fractions.intFraction(i.getQty());
String amt = Fractions.intFraction(i.getAmount());
String meas = i.getMeasurement();
String cont = i.getContainer();
String item = i.getFoodItem();
if (amt.trim().length()>0) toString += " " + amt;
if (meas.trim().length()>0) toString += " " + meas;
if (cont.trim().length()>0) toString += " " + cont;
if (item.trim().length()>0) toString += " " + item;
return toString;
}
public void getIngredientsFromHTTP() throws MalformedURLException, ProtocolException, IOException {
//http://www.rgagnon.com/javadetails/java-0085.html
int endOfIngredients;
Utility.ApplicationLogger.severe("getIngredientsFromHTTP: " + recipeUrl);
URL url = new URL(recipeUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(100000 /* milliseconds */);
conn.setConnectTimeout(250000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
Utility.ApplicationLogger.severe("getIngredientsFromWeb: CONNECTED!");
StringBuilder contentBuilder = new StringBuilder();
try {
String line;
int idx = -1;
Boolean foundIngredients=false;
InputStreamReader IS = new InputStreamReader(conn.getInputStream());
BufferedReader bufferedReader = new BufferedReader(IS);
while(!bufferedReader.ready()){
//Wait;
}
if (bufferedReader.ready()) {
Utility.ApplicationLogger.severe("getIngredientsFromHTTP: READING BUFFER!");
endOfIngredients = -1;
line = bufferedReader.readLine();
while (line!= null) {
idx = line.toUpperCase().indexOf("INGREDIENT");
if (idx>-1){
foundIngredients = true;
//if (line.length()>=10) line = line.substring(idx+10);
}
if (foundIngredients) {
contentBuilder.append(line.replaceAll("\\<.*?\\>", "") + "\n");
//slp.setEndOfIngredients(contentBuilder.toString());
}
line = bufferedReader.readLine();
}
Utility.ApplicationLogger.severe("getIngredientsFromHTTP: FINISHED READING BUFFER!");
String content = contentBuilder.toString();
if (endOfIngredients>-1) { //NEW JAN 2018
content = content.substring(0,endOfIngredients);
shoppingListProcess.findIngredients(content);
shoppingItems = slp.getShoppingItems();
Utility.ApplicationLogger.severe("getIngredientsFromHTTP: ShoppingItems Count:" + shoppingItems.size() + "\n");
if (shoppingItems.size()>0)
loadIngredientsIntoDB ();
}
else {
Utility.ApplicationLogger.severe("getIngredientsFromHTTP: ##### DID NOT FIND ANY INGREDIENTS!");
}
}
}
catch(Exception e) {
Utility.ApplicationLogger.severe("getIngredientsFromWeb: ERROR " + recipeUrl + " " + e.getMessage());
}
}
private void getIngredientsFromWeb(String recipeUrl) throws IOException {
if (recipeUrl.trim().length()==0) {
Utility.ApplicationLogger.severe("RECIPE - getIngredientsFromWeb: BLANK RECIPE URL");
return;
}
Utility.ApplicationLogger.severe("RECIPE - getIngredientsFromWeb: " + recipeUrl);
boolean bKeepGoing=true;
int ct=0;
String content = "";
while (bKeepGoing) {
ct++;
if (ct==1 | ct==3) content = setContentFromJSoup(recipeUrl);
if (ct==2 | ct==4) content = setContentFromUrl(recipeUrl);
if (content.trim().length()>0 | ct==4) bKeepGoing = false;
}
if (content.trim().length()>0) {
slp.setContent(content);
shoppingItems = slp.getShoppingItems();
if (shoppingItems!=null) {
Utility.ApplicationLogger.severe("getIngredientsFromWeb: " + recipeUrl + " ###ShoppingItems Count:" + shoppingItems.size() + "\n");
/** Load Ingredients Into Database **/
loadIngredientsIntoDB ();
}
else {
Utility.ApplicationLogger.severe("getIngredientsFromWeb: ShoppingItems is NULL!\n");
}
}
}
private static String setContentFromJSoup(String recipeUrl) throws IOException {
Utility.ApplicationLogger.severe("setContentFromJSoup: " + recipeUrl);
String content = "";
try {
org.jsoup.nodes.Document doc = (org.jsoup.nodes.Document) Jsoup.connect(recipeUrl).get();
org.jsoup.nodes.Document.OutputSettings settings = doc.outputSettings();
//settings.prettyPrint(true);
//settings.escapeMode(org.jsoup.nodes.Entities.EscapeMode.extended);
//settings.charset("ASCII");
String modifiedFileHtmlStr = doc.html();
content = new HtmlToPlainText().getPlainText(Jsoup.parse(modifiedFileHtmlStr));
}
catch (Exception e) {}
return content;
}
public static String setContentFromUrl(String inUrl) {
Utility.ApplicationLogger.severe("setContentFromUrl: " + inUrl);
StringBuilder contentBuilder = new StringBuilder();
String content = "";
try {
URL urlx = new URL(inUrl);
HttpURLConnection connection = (HttpURLConnection)urlx.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true); // You need to set it to true if you want to send (output) a request body, for example with POST or PUT requests. Sending the request body itself is done via the connection's output stream:<br />
connection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
contentBuilder.append(line + "\n");
}
content = contentBuilder.toString();
content = content.replaceAll("\\<.*?\\>", "");
content = content.replaceAll("\n", "");
}
catch(Exception e) {
}
return content;
}
public void loadIngredientsIntoDB () {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "loadIngredientsIntoDB",
"recipeID - " + id + ", shopping Items: " + shoppingItems.size());
Ingredient i;
Map.Entry<String, Map<String, Ingredient>> foodGroupEntry=null;
String foodGroup="";
if (shoppingItems!=null) {
List<Map.Entry<String, Map<String, Ingredient>>> shoppingGroups = slp.getSortedShoppingItemGroupsMap();
for (int g = 0; g < shoppingGroups.size(); g++) {
foodGroupEntry = shoppingGroups.get(g);
foodGroup = foodGroupEntry.getKey();
Map<String, Ingredient> foodGroupEntryItems = foodGroupEntry.getValue();
List<Map.Entry<String, Ingredient>> shoppingItems = slp.getSortedShoppingItemsMap(foodGroupEntryItems);
for (int j = 0; j < shoppingItems.size(); j++) {
Map.Entry<String, Ingredient> s = shoppingItems.get(j);
if (s!=null){
i = (Ingredient) s.getValue();
if (i.getFoodItem().trim().length()>0){
//Utility.ApplicationLogger.severe("ADDING Ingredient: " + i.getItem());
//ingredient.setFoodGroup(foodGroup);
i.setRid(id);
addIngredientLocal(i);
}
}
}
}
}
}
/** Used by CREATE Method **/
public void addRecipe(Recipe r) {
int newId = 0;
try {
Connection conn = DBConnectionFactory.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(RID) FROM RECIPES");
rs.beforeFirst();
if (rs.next()) {
newId = rs.getInt(1) + 1;
}
r.id = newId;
r.title="";
rs.close();
Utility.ApplicationLogger.info("addRecipe ********** ID:" + newId);
}
catch (Exception e) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "addRecipe",
"#####EXCEPTION RECIPE ID: " + newId + " " + e.getMessage());
}
}
public void addIngredientLocal(Ingredient ingredient) {
try {
Connection conn = DBConnectionFactory.getConnection();
Statement stmt = conn.createStatement();
int newId = 1;
ResultSet rs = stmt.executeQuery("SELECT MAX(IID) FROM INGREDIENTS");
rs.beforeFirst();
if (rs.next()) {
newId = rs.getInt(1) + 1;
}
String sql =
"INSERT INTO INGREDIENTS (RID,IID,QTY,AMOUNT,CONTAINR,MEASUREMENT,ITEM,FOODGROUP) VALUES (" +
ingredient.getRid() + "," + newId + "," + ingredient.getQty() + "," + ingredient.getAmount() + ",'" +
ingredient.getContainer() + "','" + ingredient.getMeasurement() + "','" +
ingredient.getItem() + "','" + ingredient.getFoodGroup() + "')";
int updateCount = stmt.executeUpdate(sql);
if (updateCount == 0) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "addIngredient", "Insert Failed!");
}
else {
//Utility.ApplicationLogger.severe("Recipe.addIngredientLocal Inserted RECIPE ID:" + id + ", INGREDIENT ID:" + newId + " " + ingredient.getItem() + "\n" + sql);
}
conn.commit();
} catch (SQLException e) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "addIngredient",
"##############SQL Exception: " + e.getMessage());
e.printStackTrace();
} catch (Exception exception) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "addIngredient",
"##############Exception: " + exception.getMessage());
}
}
public void reloadIngredientsXXX(Integer rid) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "reloadIngredients",
" ***** Recipe:" + rid);
this.id = rid;
recipeIngredients.clear();
getIngredientsFromDB();
//propertyChangeSupport.firePropertyChange("ingredients", null, recipeIngredients);
//providerChangeSupport.fireProviderRefresh("ingredients"); //Used to fire changes made to a collection
}
public void removeIngredient() throws MalformedURLException, ProtocolException, IOException {
ValueExpression ve = AdfmfJavaUtilities.getValueExpression("#{pageFlowScope.selectedId}", Integer.class);
Object obj1 = ve.getValue(AdfmfJavaUtilities.getELContext());
Integer ingredientId = (Integer)obj1;
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "removeIngredient",
"INGREDIENT ID: " + ingredientId);
for (Integer i=1; i<recipeIngredients.size(); i++) {
Ingredient ingredient = (Ingredient) recipeIngredients.get(i);
if (ingredient.getId() == ingredientId) {
recipeIngredients.remove(ingredient);
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "removeIngredient",
"##############REMOVED INGREDIENT ID: " + ingredientId + ", " + ingredient.getItem());
break;
}
}
propertyChangeSupport.firePropertyChange("ingredients", null, recipeIngredients);
//providerChangeSupport.fireProviderRefresh("ingredients");
/**
AmxTreeBinding ingredientList = (AmxTreeBinding) AdfmfJavaUtilities.getELValue("#{bindings.ingredients}");
AmxIteratorBinding amxListIterator = ingredientList.getIteratorBinding();
BasicIterator basicIterator = amxListIterator.getIterator();
try {
if (basicIterator.getRangeSize()>0) {
for (Integer i=1; i<basicIterator.getRangeSize(); i++) {
basicIterator.setCurrentIndex(i);
Ingredient ingredient = (Ingredient) basicIterator.getDataProvider();
if (ingredient.getId() == id) {
ingredients.remove(ingredient);
break;
}
}
}
}
catch(Exception e) {
Utility.ApplicationLogger.severe("Recipe - removeIngredient: NO RESULTS " + e.getMessage());
}
**/
}
//public void removeIngredient(Ingredient ingredient) {
// ingredient.deleteFromStore();
//}
public void reloadFromStoreXXX() {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "reloadFromStore",
"RECIPE ID: " + this.id);
try {
Connection conn = DBConnectionFactory.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM RECIPES WHERE RID = " + this.id);
rs.beforeFirst();
if (rs.next()) {
if (!rs.getString("RECIPEURL").isEmpty()) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "reloadFromStore",
"RECIPEURL: " + rs.getString("RECIPEURL"));
this.setTitle(rs.getString("TITLE"));
this.setRecipeUrl(rs.getString("RECIPEURL"));
this.setDescription(rs.getString("DESCRIPTION"));
this.setPrepTime(rs.getString("PREPTIME"));
//this.setItem(rs.getString("ITEM"));
if (getTitle().equals("null")) {
this.setTitle("");
}
if (getRecipeUrl().equals("null")) {
this.setRecipeUrl("");
}
if (getDescription().equals("null")) {
this.setDescription("");
}
if (getPrepTime().equals("null")) {
this.setPrepTime("");
}
}
}
} catch (SQLException e) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "reloadFromStore",
"##############SQL Exception: " + e.getMessage());
e.printStackTrace();
} catch (Exception exception) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "reloadFromStore",
"##############Exception: " + exception.getMessage());
}
}
public Boolean saveRecipeToStore(Recipe recipe) {
Boolean success = false;
String sqlType = "UPDATE";
this.id = recipe.id;
this.title = recipe.title;
this.recipeUrl = recipe.recipeUrl;
this.description = recipe.description;
this.prepTime = recipe.prepTime;
int newId = 1;
try {
Connection conn = DBConnectionFactory.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(RID) FROM RECIPES");
rs.beforeFirst();
if (rs.next()) {
newId = rs.getInt(1) + 1;
this.id = newId;
}
} catch (SQLException e) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, RecipeService.class, "addRecipe",
"##############SQL Exception: " + e.getMessage());
e.printStackTrace();
} catch (Exception exception) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, RecipeService.class, "addRecipe",
"##############Exception: " + exception.getMessage());
}
try {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "saveRecipeToStore", "Recipe: " + this.id + ", " + this.title);
//RecipeService rSvc = new RecipeService();
//rSvc.clearParms();
Connection conn = DBConnectionFactory.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = null;
String sql = "DELETE FROM RECIPES WHERE RID = " + this.id;
if (this.title.length()==0) {
rs = stmt.executeQuery(sql);
conn.commit();
return false;
}
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "saveToStore", "title: " + this.getTitle()
+ ", url: " + this.getRecipeUrl() + ",ID:" + this.id);
rs = stmt.executeQuery("SELECT * FROM RECIPES WHERE RID = " + this.id);
rs.beforeFirst();
if (rs.next()) {
sql =
"UPDATE RECIPES SET TITLE='" + this.getTitle() + "', RECIPEURL='" + this.getRecipeUrl() +
"', DESCRIPTION='" + this.getDescription() + "', PREPTIME='" + this.getPrepTime() +
"' WHERE RID=" + this.id;
} else {
sqlType = "INSERT";
sql =
"INSERT INTO RECIPES (RID,TITLE,RECIPEURL,DESCRIPTION,PREPTIME) VALUES (" +
this.id + ",'" + this.getTitle() + "','" + this.getRecipeUrl() + "','" +
this.getDescription() + "','" + getPrepTime() + "')";
}
int updateCount = stmt.executeUpdate(sql);
if (updateCount == 0) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "saveRecipeToStore", sqlType + " Failed! Recipe ID:" + this.id + " " + this.title + ", prepTime:" + this.prepTime);
}
else {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "saveRecipeToStore", sqlType + " PASSED! Recipe ID:" + this.id + " " + this.title + ", prepTime:" + this.prepTime);
success = true;
}
conn.commit();
ValueExpression ve = AdfmfJavaUtilities.getValueExpression("#{pageFlowScope.id}", String.class);
ve.setValue(AdfmfJavaUtilities.getELContext(), newId);
ve = AdfmfJavaUtilities.getValueExpression("#{pageFlowScope.url}", String.class);
ve.setValue(AdfmfJavaUtilities.getELContext(), "");
ve = AdfmfJavaUtilities.getValueExpression("#{pageFlowScope.title}", String.class);
ve.setValue(AdfmfJavaUtilities.getELContext(), "");
ve = AdfmfJavaUtilities.getValueExpression("#{pageFlowScope.prepTime}", String.class);
ve.setValue(AdfmfJavaUtilities.getELContext(), "");
} catch (SQLException e) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "saveRecipeToStore",
"##############SQL Exception: " + e.getMessage());
e.printStackTrace();
} catch (Exception exception) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "saveRecipeToStore",
"##############Exception: " + exception.getMessage());
}
return success;
}
public void deleteFromStore(Integer id) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "deleteFromStore", "RECIPE ID: " + id);
try {
Connection conn = DBConnectionFactory.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM RECIPES WHERE RID = " + id);
rs.beforeFirst();
if (rs.next()) {
//if (rs.getString("TITLE").trim().length()==0) {
String sql = "DELETE FROM RECIPES WHERE RID = " + id;
int updateCount = stmt.executeUpdate(sql);
if (updateCount == 0) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "deleteFromStore",
"Delete Failed!");
}
else {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "deleteFromStore",
"Delete Passed!");
}
//}
}
conn.commit();
//}
} catch (SQLException e) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, RecipeService.class, "deleteRecipe",
"##############SQL Exception: " + e.getMessage());
e.printStackTrace();
} catch (Exception exception) {
Trace.log(Utility.ApplicationLogger, Level.SEVERE, Recipe.class, "deleteRecipe",
"##############Exception: " + exception.getMessage());
}
}
public void setGoogleRecipe(String googleRecipe) {
String oldGoogleRecipe = this.googleRecipe;
this.googleRecipe = googleRecipe;
propertyChangeSupport.firePropertyChange("googleRecipe", oldGoogleRecipe, googleRecipe);
}
public String getGoogleRecipe() {
return googleRecipe;
}
}
| true |
565ffc4f645c5e883e7db43c022d863f281f35f6 | Java | loganBehnke/Rpg-Lab6-CS136L | /FireDamage.java | UTF-8 | 122 | 2.375 | 2 | [] | no_license | public class FireDamage extends Damage
{
public FireDamage(int amountDamage)
{
super(amountDamage, "fire");
}
}
| true |
8e8335c9a0217313d64de2bf78e8a2c98701b5e4 | Java | datainsect/All-About-SDE-Interview | /src/main/java/org/gnuhpc/interview/leetcode/solutions/WidthOfBinaryTree662.java | UTF-8 | 3,306 | 3.328125 | 3 | [] | no_license | package org.gnuhpc.interview.leetcode.solutions;
import org.gnuhpc.interview.leetcode.utils.TreeNode;
import java.util.*;
public class WidthOfBinaryTree662 {
/*
Method1 : BFS
*/
int max = Integer.MIN_VALUE;
public int widthOfBinaryTree(TreeNode root) {
if (root == null) return 0;
if (root.right == null && root.left == null) return 1;
traversalTreeByLevel(root);
return max;
}
private void traversalTreeByLevel(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
List<TreeNode> temp = new ArrayList<>();
int size = q.size();
for (int i = 0; i < size; i++) {
temp.add(q.poll());
}
List<TreeNode> trimedList = getTrimNull(temp);
if (trimedList.size() == 0) break;
max = Math.max(max, trimedList.size());
for (int i = 0; i < trimedList.size(); i++) {
TreeNode n = trimedList.get(i);
if (n != null) {
q.offer(n.left);
q.offer(n.right);
} else {
q.offer(null);
q.offer(null);
}
}
}
}
private List<TreeNode> getTrimNull(List<TreeNode> list) {
List<TreeNode> res = new ArrayList<>();
if (list == null) return res;
int left = 0, right = list.size() - 1;
while (left <= right && list.get(left) == null) {
left++;
}
while (left <= right && list.get(right) == null) {
right--;
}
return list.subList(left, right + 1);
}
/*
Method2: DFS
https://leetcode.com/articles/maximum-width-of-binary-tree/
*/
int ans;
Map<Integer, Integer> left;
public int widthOfBinaryTree2(TreeNode root) {
ans = 0;
left = new HashMap<>();
dfs(root, 0, 0);
return ans;
}
public void dfs(TreeNode root, int depth, int pos) {
if (root == null) return;
left.putIfAbsent(depth, pos);
ans = Math.max(ans, pos - left.get(depth) + 1);
dfs(root.left, depth + 1, 2 * pos);
dfs(root.right, depth + 1, 2 * pos + 1);
}
/*
Method3 : BFS
https://leetcode.com/articles/maximum-width-of-binary-tree/
*/
public int widthOfBinaryTree3(TreeNode root) {
Queue<AnnotatedNode> queue = new LinkedList<>();
queue.add(new AnnotatedNode(root, 0, 0));
int curDepth = 0, left = 0, ans = 0;
while (!queue.isEmpty()) {
AnnotatedNode n = queue.poll();
if (n.node != null) {
queue.add(new AnnotatedNode(n.node.left, n.depth + 1, n.pos * 2));
queue.add(new AnnotatedNode(n.node.right, n.depth + 1, n.pos * 2 + 1));
if (curDepth != n.depth) {
curDepth = n.depth;
left = n.pos;
}
ans = Math.max(ans, n.pos - left + 1);
}
}
return ans;
}
}
class AnnotatedNode {
TreeNode node;
int depth, pos;
AnnotatedNode(TreeNode n, int d, int p) {
node = n;
depth = d;
pos = p;
}
}
| true |
6b5bb0799b050b5ace44bc89aeb57dbeb7607e1a | Java | Foodwode/food | /src/main/java/com/example/utils/RedissonManager.java | UTF-8 | 1,424 | 2.203125 | 2 | [] | no_license | package com.example.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.redisson.Redisson;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import javax.annotation.PostConstruct;
/**
* @Describe
* @Author Gary
* @Create 2019-11-14 11:53
*/
@Component
public class RedissonManager {
@Value("${spring.redis.host}")
private String host;
private static final Logger logger = LoggerFactory.getLogger(RedissonManager.class);
private static Config config = new Config();
//声明redisso对象
private static Redisson redisson = null;
//获取redisson对象的方法
public Redisson getRedisson(){
if (redisson == null){
synchronized (this){
if (redisson == null){
SingleServerConfig singleServerConfig = config.useSingleServer();
singleServerConfig.setAddress("58.87.124.195:6379");
singleServerConfig.setPassword("123456");
//得到redisson对象
redisson = (Redisson) Redisson.create(config);
}
}
}
return redisson;
}
}
| true |
c966c9bf936f7d2072abb77be0a0ad5941964577 | Java | mariakryvokin/cinema_spring_boot | /src/main/java/app/repositories/EventHasAuditoriumRepository.java | UTF-8 | 429 | 1.96875 | 2 | [] | no_license | package app.repositories;
import app.models.EventHasAuditorium;
import app.models.compositePK.EventHasAuditoriumPK;
import org.springframework.data.jpa.repository.JpaRepository;
import java.sql.Timestamp;
import java.util.List;
public interface EventHasAuditoriumRepository extends JpaRepository<EventHasAuditorium, EventHasAuditoriumPK> {
List<EventHasAuditorium> getAllByAirDateBetween(Timestamp from, Timestamp to);
}
| true |
cfa46d84bc196a33e3c6df0707201e3f7bf10a6d | Java | aadarsha56/BMI | /app/src/main/java/com/example/bmi/MainActivity.java | UTF-8 | 1,877 | 2.59375 | 3 | [] | no_license | package com.example.bmi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
private TextView txtweight,txtResult,txtheight;
private Button btnCalculate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initiate();
setbutton();
}
private void initiate(){
txtweight=findViewById(R.id.txt_weight);
txtheight=findViewById(R.id.txt_height);
txtResult = findViewById(R.id.txt_result);
btnCalculate = findViewById(R.id.btnCalculate);
}
private void setbutton(){
btnCalculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CalculateBMI();
}
});
}
private void CalculateBMI(){
float weight=Float.parseFloat(txtweight.getText().toString());
float height=Float.parseFloat(txtheight.getText().toString())/100;
WeightModel wm=new WeightModel(weight,height);
float result=wm.getWeight()/(wm.getHeight()*wm.getHeight());
txtResult.setText(""+result);
if (result<18.5){
Toast.makeText(MainActivity.this,"Underweight",Toast.LENGTH_LONG).show();
}
else if (result>=18.5 && result<=24.9){
Toast.makeText(MainActivity.this,"Normal Weight",Toast.LENGTH_LONG).show();
}
else if (result>=25 && result<=29.9){
Toast.makeText(MainActivity.this,"Overweight",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(MainActivity.this,"Obesity",Toast.LENGTH_LONG).show();
}
}
}
| true |
906c96763b3c54c3a638f460916c3c140c679ee7 | Java | kirukas/proyectoRedes2Chido | /src/com/company/Paquete.java | UTF-8 | 3,323 | 2.953125 | 3 | [] | no_license | package com.company;
import java.nio.ByteBuffer;
public class Paquete extends Trama{
private final static int sizeInt = Integer.BYTES;
private final static int sizeCabecera = 5*sizeInt;
private int longitudPaquete;/// en bytes
private int paquteFinal;
private byte[] datos;
public Paquete(int tipoTrama, int hashCode, int worker ){
super(tipoTrama,hashCode,worker);
}
public Paquete(int tipoTrama, int hashCode, int worker,int longitudPaquete ){
super(tipoTrama,hashCode,worker);
this.longitudPaquete = longitudPaquete;
}
public Paquete(byte[] byteArray ){
setTipoTrama(ByteBuffer.wrap(byteArray,0,sizeInt).getInt());
setHashCode(ByteBuffer.wrap(byteArray,sizeInt,2*sizeInt).getInt());
setWorker(ByteBuffer.wrap(byteArray,2*sizeInt,3*sizeInt).getInt());
setLongitudPaquete(ByteBuffer.wrap(byteArray,3*sizeInt,4*sizeInt).getInt());
setPaquteFinal (ByteBuffer.wrap(byteArray,4*sizeInt,5*sizeInt).getInt());
datos = new byte[super.getLongitudTrama() - sizeCabecera];
System.arraycopy(byteArray,sizeCabecera,datos,0,getLongitudPaquete());
setDatos(datos);
}
public byte[] castByteArray(){
byte[] ArrayRaw = new byte[super.getLongitudTrama()];
ByteBuffer.wrap(ArrayRaw,0,sizeInt).putInt(super.getTipoTrama());
ByteBuffer.wrap(ArrayRaw,sizeInt,2*sizeInt).putInt(super.getHashCode());
ByteBuffer.wrap(ArrayRaw,2*sizeInt,3*sizeInt).putInt(super.getWorker());
ByteBuffer.wrap(ArrayRaw,3*sizeInt,4*sizeInt).putInt(getLongitudPaquete());
ByteBuffer.wrap(ArrayRaw,4*sizeInt,5*sizeInt).putInt(getPaqueteFinal());
System.arraycopy(datos,0,ArrayRaw,sizeCabecera, datos.length);
return ArrayRaw;
}
public int getLongitudMaximoPaquete(){ return (super.getLongitudTrama() - sizeCabecera); }
public int getLongitudPaquete(){return longitudPaquete;}
public void setLongitudPaquete(int l){longitudPaquete = l;}
public byte[] getDatos() {
byte [] auxDatos = new byte[getLongitudPaquete()];
System.arraycopy(datos,0,auxDatos,0,getLongitudPaquete());
return auxDatos;
}
public void setPaquteFinal(int f){ paquteFinal = f; }
public int getPaqueteFinal(){return paquteFinal;}
public void setDatos(byte[] datos) { this.datos = datos; }
public static int getSizeCabecera() { return sizeCabecera; }
///////////////Metodos de la clase Trama
@Override
public String toString() {
return super.toString()+" longitud de la info "+ getLongitudPaquete();
}
@Override
public int getHashCode() {
return super.getHashCode();
}
@Override
public int getLongitudTrama() {
return super.getLongitudTrama();
}
@Override
public int getTipoTrama() {
return super.getTipoTrama();
}
@Override
public int getWorker() {
return super.getWorker();
}
@Override
public void setHashCode(int hashCode) {
super.setHashCode(hashCode);
}
@Override
public void setLongitudTrama(int longitudTrama) {
super.setLongitudTrama(longitudTrama);
}
@Override
public void setTipoTrama(int tipoTrama) {
super.setTipoTrama(tipoTrama);
}
}
| true |
3ee3622f454c0ef2a7f4e574125224a0ab9162e7 | Java | himanshufernando/SPHTech | /app/build/tmp/kapt3/stubs/debug/emarge/project/caloriecaffe/network/api/APIInterface.java | UTF-8 | 1,179 | 1.773438 | 2 | [] | no_license | package emarge.project.caloriecaffe.network.api;
import java.lang.System;
/**
* Created by Himanshu on 9/6/19.
*/
@kotlin.Metadata(mv = {1, 1, 15}, bv = {1, 0, 3}, k = 1, d1 = {"\u0000 \n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u000e\n\u0000\n\u0002\u0010\b\n\u0000\bf\u0018\u00002\u00020\u0001J\"\u0010\u0002\u001a\b\u0012\u0004\u0012\u00020\u00040\u00032\b\b\u0001\u0010\u0005\u001a\u00020\u00062\b\b\u0001\u0010\u0007\u001a\u00020\bH\'\u00a8\u0006\t"}, d2 = {"Lemarge/project/caloriecaffe/network/api/APIInterface;", "", "getDataStore", "Lio/reactivex/Observable;", "Lhimanshu/projects/sphtech/model/datamodel/Datastore;", "resource_id", "", "offset", "", "app_debug"})
public abstract interface APIInterface {
@org.jetbrains.annotations.NotNull()
@retrofit2.http.GET(value = "action/datastore_search")
public abstract io.reactivex.Observable<himanshu.projects.sphtech.model.datamodel.Datastore> getDataStore(@org.jetbrains.annotations.NotNull()
@retrofit2.http.Query(value = "resource_id")
java.lang.String resource_id, @retrofit2.http.Query(value = "offset")
int offset);
} | true |
720ee8d1ad53f35e882ea3cec12d7a742e6797ec | Java | xiffent/zleadf-parent | /zleadf-app-service/src/main/java/com/zlead/entity/vo/AgentBillListVO.java | UTF-8 | 1,910 | 2.15625 | 2 | [] | no_license | package com.zlead.entity.vo;
import java.math.BigDecimal;
import java.util.Date;
public class AgentBillListVO {
/**
* 客户id
*/
private Integer agentId;
/**
* 客户名称
*/
private String agentName = "";
/**
* 帐单id
*/
private Long orderId;
/**
* 帐单编号
*/
private String sn;
/**
* 账单总金额
*/
private BigDecimal totalAmount = BigDecimal.ZERO;
/**
* 交易时间
*/
private Date tradeTime;
/**
* 账单状态 1.已结清 2.欠款
*/
private Integer status;
/**
* 包含的所有的账单状态
*/
private String statusStr;
public Integer getAgentId() {
return agentId;
}
public void setAgentId(Integer agentId) {
this.agentId = agentId;
}
public String getAgentName() {
return agentName;
}
public void setAgentName(String agentName) {
this.agentName = agentName;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public BigDecimal getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(BigDecimal totalAmount) {
this.totalAmount = totalAmount;
}
public Date getTradeTime() {
return tradeTime;
}
public void setTradeTime(Date tradeTime) {
this.tradeTime = tradeTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getStatusStr() {
return statusStr;
}
public void setStatusStr(String statusStr) {
this.statusStr = statusStr;
}
}
| true |
1a8fff5b24e9e179a15ea66b982af5e7210b6889 | Java | mmohanty/springboot-cache | /src/main/java/com/manas/learning/springboot/caching/service/CacheKeyGenerator.java | UTF-8 | 800 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | package com.manas.learning.springboot.caching.service;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
public class CacheKeyGenerator {
/**
* Append the method name , param to an array and create a deepHashCode of the array as redis cache key
* @param methodName
* @param params
* @return
*/
public String generateKey(String methodName , Object... params) {
if (params.length == 0) {
return Integer.toString(methodName.hashCode());
}
Object[] paramList = new Object[params.length+1];
paramList[0] = methodName;
System.arraycopy(params, 0, paramList, 1, params.length);
int hashCode = Arrays.deepHashCode(paramList);
return Integer.toString(hashCode);
}
}
| true |
841b170a7d8193a57cf9f7b8f895c90b69f36a88 | Java | hataka/codingground | /WisdomSoft/cs/cs048/cs048_4/main.cs | UTF-8 | 1,031 | 2.984375 | 3 | [] | no_license | // -*- mode: java -*- Time-stamp: <2016-10-03 06:15:22 kahata>
/*================================================================
* title:
* file:
* path; cs/cs048/cs048_4/main.cs
* url: cs/cs048/cs048_4/main.cs
* created: Time-stamp: <2016-10-03 06:15:22 kahata>
* revision: $Id$
* Programmed By: kahata
* To compile:
* To run:
* link: http://wisdom.sakura.ne.jp/
* link: http://wisdom.sakura.ne.jp/programming/cs/cs48.html
* description:
*
*================================================================*/
class Test {
static void Main(string[] args) {
try {
if (args[0] == "A") {
int x = 0;
x = 10 / x;
}
else if (args[0] == "B") {
System.Object obj = null;
string str = obj.ToString();
}
}
catch (System.IndexOutOfRangeException err) {
System.Console.WriteLine(err.Message);
}
catch (System.DivideByZeroException err) {
System.Console.WriteLine(err.Message);
}
catch (System.NullReferenceException err) {
System.Console.WriteLine(err.Message);
}
}
}
| true |
c0aca44ccc4c93a4139cff5f07c99d562ddd5c5d | Java | RunTim3T3rror/Space-Game | /src/application/controller/LostState.java | UTF-8 | 1,538 | 2.859375 | 3 | [] | no_license | package application.controller;
import application.Main;
import application.Utilities.Load;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import java.awt.event.KeyEvent;
public class LostState implements GameState{
//GameStateManager
private GameStateManager gsm;
//Fonts
private Font textFont, titleFont;
private Background background;
/***
* Constructor for lost sate
* Creates backgrounds
* Sets fonts
* @param gsm The game state manger
*/
public LostState(GameStateManager gsm){
this.gsm = gsm;
textFont = new Font(74);
titleFont = new Font(100);
background = new Background(Load.getImage("BackgroundMoving"));
gsm.setCurrentLevel(0);
}
public void update(){}
/**
* Used to draw the text and background to the screen
* @param g The graphics context to draw with
*/
public void draw(GraphicsContext g){
g.setFill(Color.WHITE);
g.fillRect(0, 0, Main.WIDTH, Main.HEIGHT);
background.draw(g);
//Draw Title
g.setFill(Color.WHITE);
g.setFont(titleFont);
g.fillText("You Lost.", 175, 150);
//Draw Text
g.setFont(textFont);
g.fillText("Press Enter to go to", 100, 250);
g.fillText("the main menu.", 100, 330);
}
/***
* Used to move between screens
* @param k The keycode of the pressed key
*/
public void keyPressed(int k){
if(k == KeyEvent.VK_ENTER)
gsm.changeState(GameStateManager.MENUSTATE);
if(k == KeyEvent.VK_ESCAPE)
System.exit(0);
}
public void keyReleased(int k){ }
}
| true |
dfbf4d95cf3ba37de12c179daf6142c7ae257107 | Java | harpreetoxyent/DataLyticxEngine | /src/components/DBComponent/bin/com/oxymedical/component/db/query/.svn/text-base/QueryHelper.java.svn-base | UTF-8 | 2,563 | 2.4375 | 2 | [] | no_license | /**
*
*/
package com.oxymedical.component.db.query;
import java.util.Iterator;
import java.util.List;
import com.oxymedical.component.db.DBComponent;
import com.oxymedical.component.db.constants.QueryConstants;
import com.oxymedical.component.db.query.data.From;
import com.oxymedical.component.db.query.data.Select;
import com.oxymedical.component.db.utilities.DBStructureUtil;
/**
* @author wkh
*
*/
public class QueryHelper {
/**
* selectQuery method create select class of hsql query
* @param selectList
* @return
*/
public StringBuffer selectQuery(List<Select> selectList)
{
if(selectList == null)
{
return null;
}
StringBuffer selectQuery = new StringBuffer();
Iterator<Select> itr = selectList.iterator();
int counter=0;
while(itr.hasNext())
{
Select select = itr.next();
selectQuery = (counter == 0) ? selectQuery.append(com.oxymedical.component.db.constants.QueryConstants.SELECT) : selectQuery.append(QueryConstants.SELECT_QUERY_FIELD_SEP);
selectQuery = (select.getTableAlias() != null) ? selectQuery.append(select.getTableAlias()).append(QueryConstants.SELECT_QUERY_TABLE_FIELD_SEP) : selectQuery;
selectQuery = selectQuery.append(select.getField());
//selectQuery = (select.getFieldAlias() != null) ? selectQuery.append(QueryConstants.SELECT_QUERY_FIELD_ALIAS_SEP).append(select.getFieldAlias()) : selectQuery;
counter++;
}
return selectQuery;
}
/**
* fromQuery method create from clause of query.
* @param fromList
* @param str
* @return
*/
public StringBuffer fromQuery(List<From> fromList,StringBuffer str)
{
StringBuffer fromQuery = new StringBuffer(str);
boolean firstTable = true;
String oldTableName = null;
Iterator<From> fromIterator = fromList.iterator();
while(fromIterator.hasNext())
{
From from = fromIterator.next();
if(!firstTable)
{
String nextTable = from.getTable();
if(nextTable.equalsIgnoreCase(oldTableName))
{
continue;
}
if(fromQuery.toString().contains(nextTable))
{
continue;
}
}
fromQuery = (firstTable) ? fromQuery.append(QueryConstants.FROM) : fromQuery.append(QueryConstants.FROM_QUERY_TABLE_SEP);
fromQuery = fromQuery.append(from.getTable());
fromQuery = fromQuery.append(QueryConstants.BLANK_SPACE);
fromQuery = fromQuery.append(from.getTableAlias());
firstTable = false;
oldTableName = from.getTable();
}
return fromQuery;
}
}
| true |
8c2a505fef9686a3582d7c4d04b42bf4874b9b2f | Java | isolic811/TBP | /client/app/src/main/java/com/example/model/Question.java | UTF-8 | 3,305 | 2.9375 | 3 | [] | no_license | package com.example.model;
import java.util.Vector;
public class Question {
private String questionText;
private String level;
private String correctAnswer;
private String ans1;
private String ans2;
private String ans3;
public Question(String questionText, String level, String correctAnswer, String ans1, String ans2, String ans3) {
this.questionText = questionText;
this.level = level;
this.correctAnswer = correctAnswer;
this.ans1 = ans1;
this.ans2 = ans2;
this.ans3 = ans3;
}
public String getAns3() {
return ans3;
}
public void setAns3(String ans3) {
this.ans3 = ans3;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getCorrectAnswer() {
return correctAnswer;
}
public void setCorrectAnswer(String correctAnswer) {
this.correctAnswer = correctAnswer;
}
public String getAns1() {
return ans1;
}
public void setAns1(String ans1) {
this.ans1 = ans1;
}
public String getAns2() {
return ans2;
}
public void setAns2(String ans2) {
this.ans2 = ans2;
}
public String getQuestionText() {
return questionText;
}
public void setQuestionText(String questionText) {
this.questionText = questionText;
}
public static Vector<Question> localQuestions(){
Vector<Question> questionList=new Vector<Question>();
Question question= new Question("Što je zdravo za zube?","easy","mlijeko","sok","sladoled","čokolada");
questionList.add(question);
question=new Question("Koliko puta dnevno moramo prati zube?","easy","barem dva puta","nijednom","jednom","sto puta");
questionList.add(question);
question=new Question("Što se ne nalazi u ustima?","easy","zjenica","zubi","jezik","nepce");
questionList.add(question);
question=new Question("Što nije vrsta zuba?","easy","mlječnjaci","kutnjaci","sjekutići","očnjaci");
questionList.add(question);
question=new Question("Kada dijete mora prvi put ići kod stomatologa?","medium","kada nikne prvi zub","1 mjesec","1 godina","4 godine");
questionList.add(question);
question=new Question("Od čega se sastoji zub?","medium","krune i korijena","vrha i baze","vrha i dna","krune i baze");
questionList.add(question);
question=new Question("Osim za žvakanje, zubi nam služe i za?","medium","pričanje","okus","slušanje","razmišljanje");
questionList.add(question);
question=new Question("Kako se zove sjajna tvrda tvar koja pokriva zub?","hard","caklina","karijes","vosak","dentin");
questionList.add(question);
question=new Question("Što u pulpi šalje signale u mozak ako je sladoled prehladan?","hard","živci","valovi","zvukovi","žile");
questionList.add(question);
question=new Question("Što se nalazi na površini korjena zuba?","hard","cement","pasta","hitin","vapnenac");
questionList.add(question);
return questionList;
}
}
| true |
55b08da57e9371a452ac6fe7cf41370d90ea3eec | Java | zole77/android_study | /ViewBindingStudy/app/src/main/java/org/techtown/viewbindingstudy/TestFragment.java | UTF-8 | 918 | 2.109375 | 2 | [] | no_license | package org.techtown.viewbindingstudy;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import org.techtown.viewbindingstudy.databinding.FragTestBinding;
public class TestFragment extends Fragment {
private FragTestBinding fragTestBinding;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
fragTestBinding = FragTestBinding.inflate(inflater, container, false);
fragTestBinding.btnFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragTestBinding.tvFragment.setText("Good !!");
}
});
return fragTestBinding.getRoot();
}
}
| true |
368805d669623f32a0ffd5687bb8ac5cacfd82b5 | Java | MGowsalya/Billing | /app/src/main/java/com/example/admin/gows/SecondActivity.java | UTF-8 | 24,080 | 1.671875 | 2 | [] | no_license | package com.example.admin.gows;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.admin.gows.facebookSignIn.FacebookHelper;
import com.example.admin.gows.facebookSignIn.FacebookResponse;
import com.example.admin.gows.facebookSignIn.FacebookUser;
import com.example.admin.gows.googleAuthSignin.GoogleAuthResponse;
import com.example.admin.gows.googleAuthSignin.GoogleAuthUser;
import com.example.admin.gows.googleAuthSignin.GoogleSignInHelper;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class SecondActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,Bill_adding.TextClicked,FacebookResponse, GoogleAuthResponse {
FragmentTransaction ft;
Fragment fragment = null;
FragmentManager fm;
Bill frag;
Button profile;
public static DrawerLayout drawer;
SQLiteDatabase db;
NavigationView navigationView;
public static BluetoothChatService mChatService = null;
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private Handler customHandler = new Handler();
private static final boolean D = true;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private static final String TAG = "BluetoothChat";
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
private FacebookHelper mFbHelper;
private GoogleSignInHelper mGAuthHelper;
private String mConnectedDeviceName = "";
BluetoothDevice device;
int logintype;
public static final String DEVICE_NAME = "device_name";
private Handler mHandlern = new Handler() {
@Override
public void handleMessage(Message msg) {
//Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),Toast.LENGTH_SHORT).show();
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
break;
case BluetoothChatService.STATE_CONNECTING:
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
break;
case MESSAGE_DEVICE_NAME:
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
break;
case MESSAGE_TOAST:
break;
default:
break;
}
}
};
int status=0;
// BillList billlist = new BillList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
db = getApplicationContext().openOrCreateDatabase("Master.db", Context.MODE_PRIVATE, null);
db.execSQL("create table if not exists Billing(ID integer primary key autoincrement,Bill_no bigint(11),bdate date,pcode int," +
"Product Varchar,Rate float,Tax int,Qty int,Amount float,Total float,Created_date Date,Created_time time,Enable int)");
db.execSQL("create table if not exists LoginDetails(Username varchar,Password varchar,Login_date date,Login_time time,Status int,Logintype int);");
// By Default app always begins with dashboard page.
// FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
// tx.replace(R.id.content_frame, new Dashboard());
// tx.commit();
// mChatService = new BluetoothChatService(getApplicationContext(), mHandlern);
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String time = mdformat.format(calendar.getTime());
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
// ActionBarDrawerToggle toggle1 = new ActionBarDrawerToggle()
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
showHome();
View headerView = navigationView . getHeaderView(0);
TextView company_name = headerView.findViewById(R.id.company_name_header);
String selection = "select Company_name from Company";
Cursor curs = db.rawQuery(selection,null);
if(curs.moveToFirst())
{
do{
String name = curs.getString(0);
company_name.setText(name);
}while (curs.moveToNext());
curs.close();
}
profile = headerView.findViewById(R.id.profile);
profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fragment = new Company_edit();
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
drawer.closeDrawers();
}
});
// findViewById(R.id.printdemo).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// StringBuilder Printxt= new StringBuilder();
// Printxt.append("--------------------------------------" + "\n");
// Printxt.append(" Thank you ! Visit Again " + "\n");
// Printxt.append("**************************************" + "\n" + "\n" + "\n" + "\n");
//// setupChat();
// sendMessage(Printxt.toString());
// }
// });
String uery = "SELECT Logintype FROM LoginDetails ";
Cursor cu = db.rawQuery(uery, null);
if (cu.moveToFirst()) {
do {
logintype = cu.getInt(0);
} while (cu.moveToNext());
cu.close();
}
mFbHelper = new FacebookHelper(this,
"id,name,email,gender,birthday,picture,cover",
this);
mGAuthHelper = new GoogleSignInHelper(this, null, this);
}
/* public void printed(SQLiteDatabase db1,int check) {
// BillList billlist = new BillList();
StringBuilder Printxt= new StringBuilder();
String prnName ;
String prnNos;String prnAmt ;
String prnQty ;
String prn ;
float tot2=0.00f ;
String select1 = "SELECT * FROM Billtype";
Cursor c = db1.rawQuery(select1, null);
Printxt.append("--------------------------------------" + "\n");
Printxt.append("SNo Product Rate Qty Amount" + "\n");
Printxt.append("--------------------------------------" + "\n");
if (c.moveToNext()) {
do {
prnName = String.format("%-4s", c.getString(0));
//+"-"+c.getString(10).toString());
String va = c.getString(1);
// String[] var1 = va.split("-");
prn = String.format("%-14s", va);
prnNos = String.format("%5s", c.getString(2));
prnQty = String.format("%5s", c.getString(3));
prnAmt = String.format("%11s", c.getString(4));
float ta = c.getFloat(4);
tot2 = tot2 + ta;
Printxt.append(prnName).append(prn).append(prnNos).append(prnQty).append(prnAmt).append("\n");
} while (c.moveToNext());
String total = String.format("%13s", Float.toString(tot2)); //= Float.toString(tot2);
Printxt.append("--------------------------------------" + "\n");
Printxt.append(" Total " + total + "\n");
// Printxt.append("--------------------------------------" + "\n");
// Printxt.append(" Thank you ! Visit Again " + "\n");
// Printxt.append("**************************************" + "\n" + "\n" + "\n" + "\n");
}
c.close();
// Printxt.append("--------------------------------------" + "\n");
// Printxt = Printxt + "Total " + String.format("%12s", ) + "\n";
if ( check!= BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
// billlist.toast();
return;
}else {
String message = Printxt.toString();
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
}
}
}
// public void sendMessage(String message) {
// // Check that we're actually connected before trying anything
// if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
// Toast.makeText(getApplicationContext(), R.string.not_connected, Toast.LENGTH_SHORT).show();
// return;
// }
// else{
// // Toast.makeText(getContext(), "Connected", Toast.LENGTH_SHORT).show();
// }
// if (message.length() > 0) {
// // Get the message bytes and tell the BluetoothChatService to write
// byte[] send = message.getBytes();
// mChatService.write(send);
// }
// }
*/
@Override
public void onBackPressed() {
// drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
if(fragment instanceof Dashboard)
{
new AlertDialog.Builder(this)
.setMessage("Do You Want to Exist")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getApplicationContext(),"app closed",Toast.LENGTH_SHORT).show();
finish();
System.exit(0);
}
})
.setNegativeButton("No", null)
.show();
// super.onBackPressed();
}
else {
showHome();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (item.getItemId()) {
case R.id.action_connect:
//mBtp.showDeviceList(this);
// // important 281 to 295
// if (mBluetoothAdapter.isEnabled()) {
// if (mChatService.getState() == BluetoothChatService.STATE_LISTEN) {
// Intent serverIntent = new Intent(SecondActivity.this, DeviceListActivity.class);
// startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
// return true;
// } else {
// Toast.makeText(getApplicationContext(), "Already Connected", Toast.LENGTH_SHORT).show();
// }
// }
// else{
// Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// if (mChatService == null)
// setupChat();
// }
// case R.id.action_dunpair:
// try {
// Method m = device.getClass()
// .getMethod("removeBond", (Class[]) null);
// m.invoke(device, (Object[]) null);
// Toast.makeText(getApplicationContext(),"Disconnected",Toast.LENGTH_SHORT).show();
// } catch (Exception e) {
// Log.e(TAG, e.getMessage());
// }
// return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void showHome()
{ fragment = new Dashboard();
if (fragment != null) {
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,fragment);
ft.commit();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
// item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
// @Override
// public boolean onMenuItemClick(MenuItem menuItem) {
// Toast.makeText(getApplicationContext(), "clicked", Toast.LENGTH_SHORT).show();
//
// return true;
// }
// });
// navigationView.setItemBackgroundResource(R.drawable.testing);
// Toast.makeText(getApplicationContext(), "clicked"+item, Toast.LENGTH_SHORT).show();
// item.setIcon(R.drawable.navigation_style);
if(id == R.id.nav_dashboard)
{
// Intent intent = new Intent(SecondActivity.this,SecondActivity.class);
// startActivity(intent);
//findViewById(R.id.company_name_header).setBackgroundResource(R.color.menu_color);
fragment = new Charts();
// item.setIcon(R.drawable.navigation_style);
}
else if(id == R.id.nav_category){
fragment = new CategoryActivity();
}
else if(id == R.id.nav_tax){
fragment = new TaxesActivity();
}
else if(id == R.id.nav_item){
fragment = new ItemActivity();
}
else if(id == R.id.nav_bill){
fragment = new Bill();
}
else if(id == R.id.nav_report){
fragment = new Reports();
}
else if(id==R.id.nav_Devices)
{
fragment = new Bluetooth();
}
else if(id == R.id.nav_Logout){
new AlertDialog.Builder(this)
.setMessage("Do You Want to Exist")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// switch (logintype){
// case 1:
//
// ContentValues cv = new ContentValues();
// cv.put("Status",status);
// db.update("LoginDetails",cv,null,null);
// finish();
// case 2:
// mGAuthHelper.performSignOut();
//
// case 3:
// mFbHelper.performSignOut();
//
//
// }
if(logintype == 1){
ContentValues cv = new ContentValues();
cv.put("Status",status);
db.update("LoginDetails",cv,null,null);
finish();
}
else if (logintype == 2){
mGAuthHelper.performSignOut();
}
else if (logintype == 3){
mFbHelper.performSignOut();
}
Intent intent = new Intent(SecondActivity.this,SiginActivity.class);
startActivity(intent);
}
})
.setNegativeButton("No", null)
.show();
}
if (fragment != null) {
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void inserttextview() {
fm = getSupportFragmentManager();
frag = (Bill) fm.findFragmentById(R.id.content_frame);
frag.getcode();
}
@Override
public void updatetextview(String bill) {
fm = getSupportFragmentManager();
frag = (Bill) fm.findFragmentById(R.id.content_frame);
frag.getUpdatecode(bill);
}
// public void onActivityResult(int requestCode, int resultCode, Intent data) {
// if(D) Log.d(TAG, "onActivityResult " + resultCode);
// switch (requestCode) {
// case REQUEST_CONNECT_DEVICE:
// // When DeviceListActivity returns with a device to connect
// if (resultCode == Activity.RESULT_OK) {
// // Get the device MAC address
// String address = data.getExtras()
// .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// // Get the BLuetoothDevice object
// device = mBluetoothAdapter.getRemoteDevice(address);
// // mTitle.setText(address.toString());
// // Attempt to connect to the device
// mChatService.connect(device);
//
//
// }
// break;
// case REQUEST_ENABLE_BT:
// // When the request to enable Bluetooth returns
// if (resultCode == Activity.RESULT_OK) {
// // Bluetooth is now enabled, so set up a chat session
// setupChat();
//
// } else {
// // User did not enable Bluetooth or an error occured
// Log.d(TAG, "BT not enabled");
// Toast.makeText(getApplicationContext(), "Turn on Your Bluetooth to Connect With Printer", Toast.LENGTH_SHORT).show();
//
// }
// }
// }
private void setupChat() {
Log.d(TAG, "setupChat()");
mChatService = new BluetoothChatService(getApplicationContext(), mHandlern);
if(D) Log.e(TAG, "- bluetoooooth -");
}
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mChatService == null)
setupChat();
}
// TextView txtbt = (TextView) findViewById(R.id.TXTBTSTATUS);
if(mBluetoothAdapter.isEnabled()) {
//text.setText("Status: Enabled");
// txtbt.setText("BT:Enabled");
}
}
@Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
// @Override
// public synchronized void onPause() {
// super.onPause();
// if(D) Log.e(TAG, "- ON PAUSE -");
// }
@Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
@Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
@Override
public void onGoogleAuthSignIn(GoogleAuthUser user) {
}
@Override
public void onGoogleAuthSignInFailed() {
}
@Override
public void onGoogleAuthSignOut(boolean isSuccess) {
Toast.makeText(this, isSuccess ? "Sign out success" : "Sign out failed", Toast.LENGTH_SHORT).show();
ContentValues cv1 = new ContentValues();
cv1.put("Status",status);
db.update("LoginDetails",cv1,null,null);
finish();
}
@Override
public void onFbSignInFail() {
}
@Override
public void onFbSignInSuccess() {
}
@Override
public void onFbProfileReceived(FacebookUser facebookUser) {
}
@Override
public void onFBSignOut() {
Toast.makeText(this, "Facebook sign out success", Toast.LENGTH_SHORT).show();
ContentValues cv2 = new ContentValues();
cv2.put("Status",status);
db.update("LoginDetails",cv2,null,null);
finish();
}
}
| true |
9aff489a54dae4f6dc8a1a8bafb609f860e359d5 | Java | BradleyWood/EA-Comparative-Study | /src/main/java/algorithms/project/benchmark/Discus.java | UTF-8 | 535 | 2.734375 | 3 | [] | no_license | package algorithms.project.benchmark;
import algorithms.project.algorithm.FitnessFunction;
import java.util.Vector;
public class Discus implements FitnessFunction {
@Override
public Double fitness(Vector<Double> params) {
double fitness = 1000000 * params.get(0) * params.get(0);
int n = params.size();
for (int i = 1; i < n; i++) {
fitness += params.get(i) * params.get(i);
}
return fitness;
}
@Override
public Double optimum() {
return 0d;
}
}
| true |
749066b3ee97fe0ae8c2cd943972bec9fb574d2a | Java | manojp1988/Training | /android/Testing/SampleWidget/app/src/main/java/com/example/manoj/samplewidget/MainActivity.java | UTF-8 | 2,199 | 2.25 | 2 | [] | no_license | package com.example.manoj.samplewidget;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Debug;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private ProgressDialog progressDoalog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Debug.startMethodTracing("sample");
Button progressDialogButton = (Button) findViewById(R.id.progress_dialog_button);
progressDialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressDoalog = new ProgressDialog(MainActivity.this);
progressDoalog.setMax(100);
progressDoalog.setMessage("Its loading....");
progressDoalog.setTitle("ProgressDialog bar example");
progressDoalog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDoalog.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
while (progressDoalog.getProgress() <= progressDoalog
.getMax()) {
Thread.sleep(200);
progressDoalog.incrementProgressBy(1);
if (progressDoalog.getProgress() == progressDoalog
.getMax()) {
progressDoalog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
);
Debug.stopMethodTracing();
}
}
| true |
72eac0a95c6b7224c25820d5a505fdd4fbb411ac | Java | claytonrsalgueiro/wishlist | /wishlist/src/main/java/br/com/wishlist/domain/product/ProductRepository.java | UTF-8 | 706 | 1.921875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.wishlist.domain.product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
/**
*
* @author clayton.salgueiro
*/
@Repository
public interface ProductRepository extends MongoRepository<Product, String> {
// @Query("{'name': {$regex: ?0 }})")
Page<Product> findByNameContainingIgnoreCase(String userName, final Pageable pageable);
}
| true |
c9f356ba68b1688b5bcd9e7f3af76d16797e6f82 | Java | cccxm/doServlet | /src/main/java/com/doservlet/plugin/security/SecurityHelper.java | UTF-8 | 932 | 2.40625 | 2 | [] | no_license | package com.doservlet.plugin.security;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class SecurityHelper {
private static final Logger l = LoggerFactory
.getLogger(SecurityHelper.class);
public static boolean login(String username, String password) {
Subject currentUser = SecurityUtils.getSubject();
if (currentUser != null) {
UsernamePasswordToken token = new UsernamePasswordToken(username,
password, true);
try {
currentUser.login(token);
return true;
} catch (Exception e) {
l.error("login failure", e);
return false;
}
}
return true;
}
public static void logout() {
Subject currentUser = SecurityUtils.getSubject();
if (currentUser != null) {
currentUser.logout();
}
}
}
| true |
34ad411af497cfb0d7c8aaca1b5f0f8919a5d16c | Java | dapeng-soa/dapeng-config-server | /src/main/java/com/github/dapeng/common/Resp.java | UTF-8 | 1,273 | 2.53125 | 3 | [] | no_license | package com.github.dapeng.common;
/**
* @author with struy.
* Create by 2018/6/1 14:53
* email :yq1724555319@gmail.com
*/
public class Resp {
private int code;
private String msg;
private Object context;
private Resp(int code, String msg) {
this.code = code;
this.msg = msg;
}
private Resp(int code, String msg, Object context) {
this.code = code;
this.context = context;
this.msg = msg;
}
public static Resp of(int code, String msg) {
return new Resp(code, msg);
}
public static Resp of(int code, String msg, Object context) {
return new Resp(code, msg, context);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getContext() {
return context;
}
public void setContext(Object context) {
this.context = context;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "Resp{" +
"code=" + code +
", msg='" + msg + '\'' +
", context=" + context +
'}';
}
}
| true |
70f8ff724c36218a730e8f3833d23bc2ce0deeb1 | Java | marcelosrodrigues/ellasa | /src/test/java/test/com/pmrodrigues/ellasa/repositories/TestEstadoRepository.java | UTF-8 | 1,019 | 1.945313 | 2 | [] | no_license | package test.com.pmrodrigues.ellasa.repositories;
import com.pmrodrigues.ellasa.models.Estado;
import com.pmrodrigues.ellasa.repositories.EstadoRepository;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import java.util.List;
@ContextConfiguration(locations = {"classpath:test-applicationContext.xml"})
public class TestEstadoRepository
extends
AbstractTransactionalJUnit4SpringContextTests {
@Autowired
private EstadoRepository repository;
@Test
public void testFindById() {
final Estado estado = repository.findById(313L);
Assert.assertNotNull(estado);
}
@Test
public void testList() {
final List<Estado> estados = repository.list();
Assert.assertFalse(estados.isEmpty());
}
}
| true |
46b03dd31d2bbb98969006648baacdec522cb0ee | Java | Bondarchuk-Dmitry/2021-05-otus-spring-bondarchuk | /lec13/src/test/java/ru/otus/lec13/util/MockEntityUtil.java | UTF-8 | 1,334 | 2.484375 | 2 | [] | no_license | package ru.otus.lec13.util;
import ru.otus.lec13.domain.Author;
import ru.otus.lec13.domain.Book;
import ru.otus.lec13.domain.CommentBook;
import ru.otus.lec13.domain.Genre;
import java.util.List;
public class MockEntityUtil {
public static Author getAuthor() {
return new Author("61601c1540cb0c51c1187048", "Кей", "Хорстман");
}
public static Author getAuthorPushkin() {
return new Author("61601c4040cb0c51c118704a", "Александр", "Пушкин");
}
public static Genre getGenre() {
return new Genre("61601c5e6592350e22a07fbb", "Нехудожественная литература");
}
public static Genre getGenrePoetry() {
return new Genre("61601c6f6592350e22a07fbd", "Поэзия");
}
public static Book getBook() {
Book book = new Book("615fffca547bf907bda74ed5", "Java. Библиотека профессионала. Том 1. Основы", getAuthor(), getGenre());
book.setGenre(getGenre());
book.setAuthor(getAuthor());
book.setBookComments(List.of(getCommentBookTest1(), getCommentBookTest2()));
return book;
}
public static CommentBook getCommentBookTest1() {
return new CommentBook("test1");
}
public static CommentBook getCommentBookTest2() {
return new CommentBook("test2");
}
}
| true |
d828f07d69d7d822698860feddf519b4358873f7 | Java | AndreaCimminoArriaga/EvA4LD | /tdg.link_discovery.connector.sparql/tdg/link_discovery/connector/sparql/evaluator/arq/linker/string_similarities/OverlapSimilarity.java | UTF-8 | 525 | 2.265625 | 2 | [] | no_license | package tdg.link_discovery.connector.sparql.evaluator.arq.linker.string_similarities;
import org.simmetrics.StringMetric;
import org.simmetrics.metrics.StringMetrics;
public class OverlapSimilarity extends AbstractARQStringSimilarity{
private StringMetric metric;
public OverlapSimilarity() {
super("OverlapSimilarity");
metric = StringMetrics.overlapCoefficient();
}
@Override
public Double compareStrings(String element1, String element2) {
return (double) metric.compare(element1, element2);
}
}
| true |
84b2741eb978fae077d35a6cc7cd5a25ac6632de | Java | mcardsx/Programas-Java | /eclipse workspace/sintaxe-variaveis-e-fluxo/src/TestaLaços.java | ISO-8859-1 | 394 | 3.140625 | 3 | [
"MIT"
] | permissive |
public class TestaLaos {
public static void main(String[] args) {
int linha, coluna;
for ( linha = 0; linha <= 10; linha++) {
//o segredo a condio de parada...
for ( coluna = 0; coluna <= linha; coluna++) {
System.out.print("*");
}
System.out.print(" linha = " + linha);
System.out.print(" coluna = " + coluna);
System.out.println();
}
}
}
| true |
aa306b2fc4a00820e25d21063a7f9c6f58908b30 | Java | SergeZoghbi/JavaProject | /src/DataAccess/UserRepository.java | UTF-8 | 6,081 | 2.640625 | 3 | [] | no_license | package DataAccess;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
public class UserRepository {
private CallableStatement statement;
private MySQLConnection mySQLConnection;
private ResultSet resultSet;
public UserRepository() {
try {
this.mySQLConnection = MySQLConnection.getMySQLConnection();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public ResultSet AccountInfo(String UNI_ID){
String query = "{ call AccountInfo(?) }";
try {
this.statement = this.mySQLConnection.connection.prepareCall(query);
this.statement.setObject(1, UNI_ID);
this.resultSet = this.statement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return this.resultSet;
}
public ResultSet getFacultyName(String UNI_ID) throws SQLException {
String query = "{ call getFacultyName(?) }";
this.statement = this.mySQLConnection.connection.prepareCall(query);
this.statement.setObject(1, UNI_ID);
this.resultSet = this.statement.executeQuery();
return this.resultSet;
}
public ResultSet GetLastTenUsers() throws SQLException {
String query = "{ call getLastTenUsers() }";
this.statement = this.mySQLConnection.connection.prepareCall(query);
this.resultSet = this.statement.executeQuery();
return this.resultSet;
}
public String AddUser(String FIRST_NAME, String LAST_NAME, Integer id_fac, Integer id_school, Integer id_type, Integer id_uni) {
String query = "{ ? = call addUser(?,?,?,?,?,?) }";
try {
this.statement = this.mySQLConnection.connection.prepareCall(query);
this.statement.registerOutParameter(1, Types.JAVA_OBJECT);
this.statement.setObject(2, FIRST_NAME);
this.statement.setObject(3, LAST_NAME);
this.statement.setObject(4, id_fac);
this.statement.setObject(5, id_school);
this.statement.setObject(6, id_type);
this.statement.setObject(7, id_uni);
this.resultSet = this.statement.executeQuery();
this.resultSet.next();
return this.resultSet.getString(1);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Integer UpdateUser(String ID_UNI, String FIRST_NAME, String LAST_NAME, Integer id_fac, Integer id_school, Integer id_type, Integer id_uni){
String query = "{ ? = call updateUser(?,?,?,?,?,?,?) }";
try {
this.statement = this.mySQLConnection.connection.prepareCall(query);
this.statement.registerOutParameter(1, Types.JAVA_OBJECT);
this.statement.setObject(2, ID_UNI);
this.statement.setObject(3, FIRST_NAME);
this.statement.setObject(4, LAST_NAME);
this.statement.setObject(5, id_fac);
this.statement.setObject(6, id_school);
this.statement.setObject(7, id_type);
this.statement.setObject(8, id_uni);
this.resultSet = this.statement.executeQuery();
this.resultSet.next();
return Integer.parseInt(this.resultSet.getString(1));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Integer ChangePassword(String UNI_ID, String Old_Pass, String New_Pass) {
String query = "{ ? = call ChangePassword(?,?,?) }";
try {
this.statement = this.mySQLConnection.connection.prepareCall(query);
this.statement.registerOutParameter(1, Types.JAVA_OBJECT);
this.statement.setObject(2, UNI_ID);
this.statement.setObject(3, Old_Pass);
this.statement.setObject(4, New_Pass);
this.resultSet = this.statement.executeQuery();
this.resultSet.next();
return Integer.parseInt(this.resultSet.getString(1));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Integer DeleteUser(String UNI_ID) {
String query = "{ ? = call deleteUser(?) }";
try {
this.statement = this.mySQLConnection.connection.prepareCall(query);
this.statement.registerOutParameter(1, Types.JAVA_OBJECT);
this.statement.setObject(2, UNI_ID);
this.resultSet = this.statement.executeQuery();
this.resultSet.next();
return Integer.parseInt(this.resultSet.getString(1));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Integer Login(String UNI_ID, String Password){
String query = "{ ? = call login(?,?) }";
try {
this.statement = this.mySQLConnection.connection.prepareCall(query);
this.statement.registerOutParameter(1, Types.JAVA_OBJECT);
this.statement.setObject(2, UNI_ID);
this.statement.setObject(3, Password);
this.resultSet = this.statement.executeQuery();
this.resultSet.next();
return Integer.parseInt(this.resultSet.getString(1));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public Integer ResetPassword(String UNI_ID){
String query = "{ ? = call resetPassword(?) }";
try {
this.statement = this.mySQLConnection.connection.prepareCall(query);
this.statement.registerOutParameter(1, Types.JAVA_OBJECT);
this.statement.setObject(2, UNI_ID);
this.resultSet = this.statement.executeQuery();
this.resultSet.next();
return Integer.parseInt(this.resultSet.getString(1));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
| true |
9b6e6873b0884cd0d9cb95b2e708e28cefb03631 | Java | aritrac/Java_DS_Advanced | /String_Algorithms/src/solution/aritra/util/Trie.java | UTF-8 | 342 | 2.484375 | 2 | [] | no_license | package solution.aritra.util;
/**
* Author: Aritra Chatterjee
* Description: Now this is a declaration of a Trie
*/
public class Trie {
private TrieNode root;
public Trie(){
root = new TrieNode(' ');
}
public void insertInTrie(String s){
//TODO
}
public void searchInTrie(String s){
//TODO
}
}
| true |
abfc426ad8c5bc04c701c2b06d6a4f71912007d6 | Java | VolVoX94/CarWikiFire | /app/src/main/java/com/example/alexa/carwiki/Activities/GalleryActivity.java | UTF-8 | 8,409 | 2.25 | 2 | [] | no_license | package com.example.alexa.carwiki.Activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.alexa.carwiki.Adapter.BrandAdapter;
import com.example.alexa.carwiki.Adapter.CarAdapter;
import com.example.alexa.carwiki.Adapter.OwnerAdapter;
import com.example.alexa.carwiki.Entities.CarBrandEntity2;
import com.example.alexa.carwiki.Entities.CarEntity;
import com.example.alexa.carwiki.Entities.CarEntity2;
import com.example.alexa.carwiki.Entities.OwnerEntity2;
import com.example.alexa.carwiki.Helper.Async.GetAllCars;
import com.example.alexa.carwiki.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class GalleryActivity extends AppCompatActivity {
private List<CarEntity2> carEntities = new ArrayList<>();
private List<CarBrandEntity2> brandEntities = new ArrayList<>();
private List<OwnerEntity2> ownerEntities = new ArrayList<>();
private ListView oldTimerGallery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_gallery);
//Sets Custom Action Bar
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setTitle("Car Wiki");
oldTimerGallery = findViewById(R.id.galleryView);
addEventFirebaseListenerBrand();
addEventFirebaseListenerOwner();
addEventFirebaseListener();
/*CarAdapter carAdapter;
carAdapter = new CarAdapter(this, carEntities);
oldTimerGallery.setAdapter(carAdapter);*/
//Creates an onClickListener to track user activity
oldTimerGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), DetailsActivity.class);
intent.putExtra("ContextItem",carEntities.get(i));
CarBrandEntity2 sentBrand = new CarBrandEntity2();
OwnerEntity2 sendOwner = new OwnerEntity2();
for(int q=0; q < brandEntities.size(); q++){
if(brandEntities.get(q).getIdBrand().equals(carEntities.get(i).getIdBrand())){
sentBrand = brandEntities.get(q);
}
}
for(int r=0; r < ownerEntities.size(); r++){
if(ownerEntities.get(r).getIdOwner().equals(carEntities.get(i).getIdOwner())){
sendOwner = ownerEntities.get(r);
}
}
intent.putExtra("ContextItemBrand", sentBrand);
intent.putExtra("ContextItemOwner", sendOwner);
startActivity(intent);
}
});
}
private void addEventFirebaseListenerOwner(){
FirebaseDatabase.getInstance()
.getReference("owners")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if(ownerEntities.size() > 0){
ownerEntities.clear();
}
for (DataSnapshot postSnapshot:dataSnapshot.getChildren()){
OwnerEntity2 ownerEntity2 = postSnapshot.getValue(OwnerEntity2.class);
ownerEntity2.setIdOwner(postSnapshot.getRef().getKey());
ownerEntities.add(ownerEntity2);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void addEventFirebaseListenerBrand(){
FirebaseDatabase.getInstance()
.getReference("brands")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if(brandEntities.size() > 0){
brandEntities.clear();
}
for (DataSnapshot postSnapshot:dataSnapshot.getChildren()){
CarBrandEntity2 carBrandEntity2 = postSnapshot.getValue(CarBrandEntity2.class);
carBrandEntity2.setIdBrand(postSnapshot.getRef().getKey());
System.out.println(carBrandEntity2.getIdBrand()+"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
brandEntities.add(carBrandEntity2);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void addEventFirebaseListener(){
oldTimerGallery.setVisibility(View.INVISIBLE);
FirebaseDatabase.getInstance()
.getReference("cars")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if(carEntities.size() > 0){
carEntities.clear();
}
for (DataSnapshot postSnapshot:dataSnapshot.getChildren()){
CarEntity2 carEntity2 = postSnapshot.getValue(CarEntity2.class);
carEntity2.setIdCar(postSnapshot.getRef().getKey());
carEntities.add(carEntity2);
}
CarAdapter adapter = new CarAdapter(GalleryActivity.this,carEntities, brandEntities, ownerEntities);
oldTimerGallery.setAdapter(adapter);
oldTimerGallery.setVisibility(View.VISIBLE);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//Inflates Menu to make items accessible
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_list, menu);
return true;
}
//Checks which menu items have been selected
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==R.id.actions_settings){
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
}
if(id==R.id.actions_add){
Intent intent = new Intent(getApplicationContext(), AddCarActivity.class);
startActivity(intent);
}
if(id==R.id.actions_seeBrands){
Intent intent = new Intent(getApplicationContext(), GalleryBrandsActivity.class);
startActivity(intent);
}
if(id==R.id.actions_seeOwners){
Intent intent = new Intent(getApplicationContext(), GalleryOwnersActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
| true |
6863dfe5958fd1c7fa09c209b010f1b41daac16f | Java | xyzq2017/rxlib | /src/main/java/org/rx/security/RSAUtil.java | UTF-8 | 7,587 | 2.8125 | 3 | [] | no_license | package org.rx.security;
import org.rx.App;
import org.rx.Contract;
import org.rx.SystemException;
import org.rx.bean.Const;
import javax.crypto.Cipher;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import static org.rx.Contract.require;
public class RSAUtil {
private static final String SIGN_ALGORITHMS = "MD5withRSA";
private static final String SIGN_ALGORITHMS2 = "SHA1WithRSA";
private static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";
public static String sign(TreeMap<String, Object> map, String privateKey) {
require(map, privateKey);
StringBuilder content = new StringBuilder();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() == null) {
continue;
}
content.append(entry.getValue());
}
return sign(content.toString(), privateKey);
}
public static String sign(String content, String privateKey) {
return sign(content, privateKey, false);
}
/**
* 使用{@code RSA}方式对字符串进行签名
*
* @param content 需要加签名的数据
* @param privateKey {@code RSA}的私钥
* @param isSHA1 数据的编码方式
* @return 返回签名信息
*/
public static String sign(String content, String privateKey, boolean isSHA1) {
require(content, privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(App.convertFromBase64String(privateKey));
try {
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(keySpec);
Signature signature = Signature.getInstance(isSHA1 ? SIGN_ALGORITHMS2 : SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(getContentBytes(content, Const.Utf8));
return App.convertToBase64String(signature.sign());
} catch (Exception ex) {
throw SystemException.wrap(ex);
}
}
public static boolean verify(TreeMap<String, Object> map, String sign, String publicKey) {
require(map, sign, publicKey);
StringBuilder content = new StringBuilder();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() == null) {
continue;
}
content.append(entry.getValue());
}
return verify(content.toString(), sign, publicKey);
}
public static boolean verify(String content, String sign, String publicKey) {
return verify(content, sign, publicKey, false);
}
/**
* 使用{@code RSA}方式对签名信息进行验证
*
* @param content 需要加签名的数据
* @param sign 签名信息
* @param publicKey {@code RSA}的公钥
* @param isSHA1 数据的编码方式
* @return 是否验证通过。{@code True}表示通过
*/
public static boolean verify(String content, String sign, String publicKey, boolean isSHA1) {
require(content, sign, publicKey);
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory
.generatePublic(new X509EncodedKeySpec(App.convertFromBase64String(publicKey)));
Signature signature = Signature.getInstance(isSHA1 ? SIGN_ALGORITHMS2 : SIGN_ALGORITHMS);
signature.initVerify(pubKey);
signature.update(getContentBytes(content, Const.Utf8));
return signature.verify(App.convertFromBase64String(sign));
} catch (Exception ex) {
throw SystemException.wrap(ex);
}
}
/**
* 使用给定的 charset 将此 String 编码到 byte 序列,并将结果存储到新的 byte 数组。
*
* @param content 字符串对象
* @param charset 编码方式
* @return 所得 byte 数组
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException ex) {
throw SystemException.wrap(ex);
}
}
/**
* 加密方法 source: 源数据
*/
public static String encrypt(String source, String publicKey) {
require(source, publicKey);
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(new X509EncodedKeySpec(App.convertFromBase64String(publicKey)));
/** 得到Cipher对象来实现对源数据的RSA加密 */
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] b = cipher.doFinal(source.getBytes());
/** 执行加密操作 */
return App.convertToBase64String(b);
} catch (Exception ex) {
throw SystemException.wrap(ex);
}
}
/**
* 解密算法 cryptograph:密文
*/
public static String decrypt(String cryptograph, String privateKey) {
require(cryptograph, privateKey);
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey key = keyFactory
.generatePrivate(new PKCS8EncodedKeySpec(App.convertFromBase64String(privateKey)));
/** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] b = App.convertFromBase64String(cryptograph);
/** 执行解密操作 */
return new String(cipher.doFinal(b));
} catch (Exception ex) {
throw SystemException.wrap(ex);
}
}
/**
* RSA生成签名与验证签名示例
*
* @param args
*/
public static void main(String[] args) {
UUID id = UUID.randomUUID();
String[] kp = RSAUtil.generateKeyPair();
System.out.println("id=" + id + ", kp=" + Contract.toJsonString(kp));
String publicKey = kp[0];
String privateKey = kp[1];
String content = "这是一个使用RSA公私钥对加解密的例子";
String signMsg = sign(content, privateKey);
System.out.println("sign: " + signMsg);
boolean verifySignResult = verify(content, signMsg, publicKey);
System.out.println("verify: " + verifySignResult);
signMsg = encrypt(content, publicKey);
System.out.println("encrypt: " + signMsg);
System.out.println("decrypt: " + decrypt(signMsg, privateKey));
}
private static String[] generateKeyPair() {
KeyPairGenerator keygen;
try {
keygen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException ex) {
throw SystemException.wrap(ex);
}
keygen.initialize(1024, new SecureRandom());
KeyPair keys = keygen.genKeyPair();
PublicKey pubkey = keys.getPublic();
PrivateKey prikey = keys.getPrivate();
String pubKeyStr = App.convertToBase64String(pubkey.getEncoded());
String priKeyStr = App.convertToBase64String(prikey.getEncoded());
return new String[] { pubKeyStr, priKeyStr };
}
}
| true |
c9dfe6705bd137e5bd9643be581ef9e2b72af6f8 | Java | jerzypirog/datacollector | /src/main/java/pl/pirog/datacollector/model/Image.java | UTF-8 | 593 | 2.5 | 2 | [] | no_license | package pl.pirog.datacollector.model;
import com.google.common.io.Files;
import lombok.Getter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class Image {
private final File file;
@Getter
private final String originalFileName;
public Image(File file, String fileNameFromUrl) {
this.file = file;
this.originalFileName = fileNameFromUrl;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(Files.toByteArray(this.file));
}
} | true |
988436e2899519970e6542876867f14da507db34 | Java | Fahim227/Android_ApartmentManagementSystem | /app/src/main/java/com/example/appertmentmanagementsystem/Presenters/Report/ReportPresenter.java | UTF-8 | 194 | 1.6875 | 2 | [] | no_license | package com.example.appertmentmanagementsystem.Presenters.Report;
import com.example.appertmentmanagementsystem.models.ReportModel;
public interface ReportPresenter {
void sendReport();
}
| true |
c93d8ae5686dadea23d8280ee153dd46d43ce186 | Java | Errans93/Project-Java | /Studio/p002_Primitivi/C04_EspressioniAritmetiche.java | UTF-8 | 1,139 | 4.15625 | 4 | [] | no_license | package p002_Primitivi;
//Le espressioni aritmetiche più semplici sono costituite da singoli letterali
//--> Letterali interi: 1, 2, 3, -1, -2, -3, ...
//--> Letterali frazionari: 1.0, 2.0, 3.0, -1.2, -2.0, -3.3...
//Espressioni più complesse si ottengono utilizzando operatori aritmetici:
//--> *
//--> % (MODULO - resto di divisione tra interi)
//--> -
//--> +
//--> /
//L'operatore "/" si comporta diversamente a seconda che sia applicato a
//letterali interi o frazionari:
//25/2 = 12 (Divisione intera) 25.0/2.0 = 12.5 (Divisione reale)
//Un'operazione tra un letterale intero e uno frazionario viene eseguita
//come tra due frazionari.
//--> int/fraz = fraz
public class C04_EspressioniAritmetiche {
public static void main(String[] args) {
int a = 10;
int b = 3;
double c = 3.0;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % b);
System.out.println();
System.out.println(a + c);
System.out.println(a - c);
System.out.println(a * c);
System.out.println(a / c);
System.out.println(a % c);
}
}
| true |
44f20587187676587fff2faa1d4dafe35ed7c330 | Java | nitin2813/NitinKumarHybrisTraining | /training/trainingstorefront/web/addonsrc/trainingaddon/com/hybris/training/controllers/pages/TrainingAddonController.java | UTF-8 | 1,710 | 2.03125 | 2 | [] | no_license | package com.hybris.training.controllers.pages;
import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException;
import de.hybris.platform.commercefacades.product.ProductFacade;
import de.hybris.platform.commercefacades.product.ProductOption;
import de.hybris.platform.commercefacades.product.data.ProductData;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Arrays;
@Controller
@RequestMapping("/addon/product")
public class TrainingAddonController {
@Autowired
private ProductFacade productFacade;
private static final Logger LOG = Logger.getLogger(TrainingAddonController.class);
private static final String PRODUCT_CODE_PATH_VARIABLE_PATTERN = "/{code:.*}";
@RequestMapping(value = PRODUCT_CODE_PATH_VARIABLE_PATTERN, method = RequestMethod.GET)
public String getProductDetails(@RequestParam("code") final String code,final Model model) throws CMSItemNotFoundException
{
final ProductData productData = productFacade.getProductForCodeAndOptions(code, Arrays.asList(ProductOption.BASIC, ProductOption.PRICE,
ProductOption.URL, ProductOption.STOCK, ProductOption.VARIANT_MATRIX_BASE, ProductOption.VARIANT_MATRIX_URL,
ProductOption.VARIANT_MATRIX_MEDIA));
model.addAttribute("productData", productData);
return "addon:/trainingaddon/pages/trainingaddonproductdetails";
}
}
| true |
4bfcde6c8ce1f37667f94eb91e45e527ac0b949e | Java | Fall2019COMP401-001/a1-schalb | /src/a1/A1Adept.java | UTF-8 | 3,304 | 3.859375 | 4 | [] | no_license | package a1;
import java.util.Scanner;
public class A1Adept {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
// first value is always numbers of items in store
String biggest;
String smallest;
double big = 0;
double small = 0;
/* these are to store the names and amounts spent of the
top and bottom shoppers */
String[] items = new String[count];
double[] prices = new double[count];
// these establish arrays for the items and prices
for (int i = 0; i < count; i++) {
items[i] = scan.next();
prices[i] = scan.nextDouble();
}
// this fills both items and prices arrays with their values
int customers = scan.nextInt();
// this establishes the number of customers
String[] shoppers = new String[customers];
double[] totals = new double[customers];
/* this establishes arrays for the shoppers and their totals
corresponding to their customer index */
for (int i = 0; i < customers; i++) {
totals[i] = 0;
}
// this sets the default totals to 0 for each customer
for (int i = 0; i < customers; i++) {
// this cycles through each customer
shoppers[i] = scan.next() + " " + scan.next();
/* this fills the shoppers array with the first and last
names of each customer */
int num = scan.nextInt();
/* this establishes the number of items bought by each
customer */
for (int u = 0; u < num; u++) {
// this cycles through each item purchased
int a = scan.nextInt();
// this holds the number of each item purchased
String item = scan.next();
// this holds the name of each item purchased
double b = 0;
// this establishes a variable to hold the item price
for (int v = 0; v < count; v++) {
// this cycles through the known items in the store
if (item.equals(items[v])) {
// if the item bought matches the cycled store item
b = prices[v];
/* set the price of the store item equal to the
bought item price */
}
}
totals[i] += a * b;
/* this adds the amount spent on each item to the customer's
total */
}
}
small = totals[0];
smallest = shoppers[0];
/* this sets an initial maximum for the smallest and who spent the
least */
big = totals[0];
biggest = shoppers[0];
double totalssum = 0;
// this sets a sum for the totals
for (int i = 0; i < customers; i++) {
// this cycles through each customer
if (totals[i] > big) {
big = totals[i];
biggest = shoppers[i];
/* this sets the name of the biggest shopper and the amount
they spent */
}else if (totals[i] < small) {
small = totals[i];
smallest = shoppers[i];
/* this sets the name of the smallest shopper and the amount
they spent */
}
totalssum += totals[i];
}
double average = totalssum / customers;
System.out.println("Biggest: " + biggest + " (" + String.format("%.2f", big) + ")");
// this prints the first expected line
System.out.println("Smallest: " + smallest + " (" + String.format("%.2f", small) + ")");
// this prints the second expected line
System.out.println("Average: " + String.format("%.2f", average));
// this prints the third expected line
}
}
| true |
40c71a97e5248eecb188addcfd05126ad22432ea | Java | ychost/codeoffer | /src/main/java/com/ychost/codeoffer/model/RandomListNode.java | UTF-8 | 700 | 3.046875 | 3 | [] | no_license | package com.ychost.codeoffer.model;
import java.util.HashMap;
import java.util.Map;
public class RandomListNode {
public int label;
public RandomListNode next, random;
public RandomListNode(int x) { this.label = x; }
public static Map<Integer,RandomListNode> create(int[] array){
Map<Integer,RandomListNode> map = new HashMap<>();
Integer preLabel = null;
for (int label : array) {
RandomListNode node = new RandomListNode(label);
map.put(label,node);
if(preLabel != null){
map.get(preLabel).next= map.get(label);
}
preLabel = label;
}
return map;
}
}
| true |
6fb43fff8c28d4de4922109a8f19c4301b24cefd | Java | oleolema/friend | /server/src/main/java/com/example/test1/demo/service/impl/FriendServiceImpl.java | UTF-8 | 1,064 | 1.992188 | 2 | [] | no_license | package com.example.test1.demo.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.test1.demo.bean.Friend;
import com.example.test1.demo.mapper.FriendMapper;
import com.example.test1.demo.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class FriendServiceImpl extends ServiceImpl
<FriendMapper, Friend> implements FriendService {
@Autowired
FriendMapper friendMapper;
@Override
public IPage<Friend> pageList(QueryWrapper<Friend> wrapper, Integer pageNo, Integer pageSize) {
IPage<Friend> page = new Page<>(pageNo, pageSize);
return baseMapper.selectPage(page, wrapper);
}
@Override
public Friend findByQQ(Integer qq) {
return friendMapper.findByQQ(qq);
}
} | true |