text
stringlengths 10
2.72M
|
|---|
package com.cngl.bilet.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Entity
@Table(name="biletler",indexes = {@Index(name="bilet_pnr_index",columnList = "pnr",unique=true)})
@AllArgsConstructor
@NoArgsConstructor
public class Bilet implements Serializable {
private static final long serialVersionUID = -9181015684860393170L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(nullable =false)
private String pnr;
@Column(name = "koltuk_no",nullable = false)
private Integer koltukNo;
@Column(name = "toplam_tutar")
private BigDecimal toplamTutar;
private Boolean ödendiMi=Boolean.FALSE;
private Boolean aktifMi=Boolean.TRUE;
@ManyToOne(
fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
optional = false
)
@JoinColumn(name = "musteri_id")
private Musteri musteri=new Musteri();
@ManyToOne(
fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
optional = false
)
@JoinColumn(name = "sefer_id")
private Sefer sefer=new Sefer();
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "koltuk_id", referencedColumnName = "id")
private Koltuk koltuk;
}
|
package model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import model.ImageBean;
import model.ImageDAO;
public class ImageDAOjdbc implements ImageDAO {
private DataSource dataSource;
public ImageDAOjdbc() {
try {
Context ctx = new InitialContext();
this.dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/vetash");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static final String SELECT_BY_IMAGEID = "select * from Image where ImageId=?";
@Override
public ImageBean selectById(int imageId) {
ImageBean result = null;
ResultSet rset = null;
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(SELECT_BY_IMAGEID);) {
stmt.setInt(1, imageId);
rset = stmt.executeQuery();
while (rset.next()) {
result = new ImageBean();
result.setImageId(rset.getInt("ImageId"));
result.setImageName(rset.getString("ImageName"));
result.setImageDate(rset.getDate("ImageDate"));
result.setImagePath(rset.getString("ImagePath"));
result.setImgCategoryName(rset.getString("ImgCategoryName"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
private static final String SELECT_BY_IMAGENAME = "select * from Image where ImageName like ?";
@Override
public List<ImageBean> selectByName(String imageName) {
List<ImageBean> result = null;
ResultSet rset = null;
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(SELECT_BY_IMAGENAME);) {
stmt.setString(1, "%" + imageName + "%");
rset = stmt.executeQuery();
result = new ArrayList<ImageBean>();
while (rset.next()) {
ImageBean bean = new ImageBean();
bean.setImageId(rset.getInt("ImageId"));
bean.setImageName(rset.getString("ImageName"));
bean.setImageDate(rset.getDate("ImageDate"));
bean.setImagePath(rset.getString("ImagePath"));
bean.setImgCategoryName(rset.getString("ImgCategoryName"));
result.add(bean);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
private static final String SELECT_ALL = "select * from Image";
@Override
public List<ImageBean> selectAll() {
List<ImageBean> result = null;
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(SELECT_ALL);
ResultSet rset = stmt.executeQuery();) {
result = new ArrayList<ImageBean>();
while (rset.next()) {
ImageBean bean = new ImageBean();
bean.setImageId(rset.getInt("ImageId"));
bean.setImageDate(rset.getDate("ImageDate"));
bean.setImageName(rset.getString("ImageName"));
bean.setImagePath(rset.getString("ImagePath"));
bean.setImgCategoryName(rset.getString("ImgCategoryName"));
result.add(bean);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
private static final String SELECT_TYPE = "select DISTINCT ImgCategoryName from Image";
@Override
public List<String> selectByType() {
List<String> result = null;
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(SELECT_TYPE);
ResultSet rset = stmt.executeQuery();) {
result = new ArrayList<String>();
while (rset.next()) {
result.add(rset.getString("ImgCategoryName"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
private static final String INSERT = "insert into Image (ImageName, ImageDate, ImagePath, ImgCategoryName) values (?,?,?,?)";
@Override
public int insert(ImageBean bean) {
int result = 0;
try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement(INSERT);) {
if (bean != null) {
stmt.setString(1, bean.getImageName());
stmt.setDate(2, new java.sql.Date(new java.util.Date().getTime()));
stmt.setString(3, bean.getImagePath());
stmt.setString(4, bean.getImgCategoryName());
result = stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
private static final String UPDATE = "update Image set ImageName=? ,ImagePath=?,ImgCategoryname=? where ImageId=?";
@Override
public int update(String imageName, String imagePath, String imageCategoryname, int imageId) {
int result = 0;
try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement(UPDATE);) {
stmt.setString(1, imageName);
stmt.setString(2, imagePath);
stmt.setString(3, imageCategoryname);
stmt.setInt(4, imageId);
result = stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
private static final String DELETE = "delete from Image where ImageId=?";
@Override
public int delete(int imageId) {
int result = 0;
try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement(DELETE);) {
stmt.setInt(1, imageId);
result = stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
private static final String SELECT_BY_IMGCATEGORYNAME = "select * from Image where ImgCategoryName like ?";
@Override
public List<ImageBean> selectByImgCategoryName(String imgCategoryName) {
List<ImageBean> result = null;
ResultSet rset = null;
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(SELECT_BY_IMGCATEGORYNAME);) {
stmt.setString(1, "%" + imgCategoryName + "%");
rset = stmt.executeQuery();
result = new ArrayList<ImageBean>();
while (rset.next()) {
ImageBean bean = new ImageBean();
bean.setImageId(rset.getInt("ImageId"));
bean.setImageName(rset.getString("ImageName"));
bean.setImageDate(rset.getDate("ImageDate"));
bean.setImagePath(rset.getString("ImagePath"));
bean.setImgCategoryName(rset.getString("ImgCategoryName"));
result.add(bean);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
|
package com.javaex.practice3;
import java.util.Scanner;
public class Ex16 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
/* 5의 배수가 아닌 % -> 0 인 코드. WRONG
System.out.print("숫자를 입력하세요: ");
int num = input.nextInt();
int factor = 1;
int a = 0;
int sum = 0;
while (factor <= num) {
if (num % factor == 0) {
a = a + 1;
sum = sum + factor;
}
factor++;
}
System.out.println("5의배수의 개수: " + a);
System.out.println("5의배수의 합:" + sum);
input.close();
*/
// ** 합 부분이 마음에 안들어 다시 한번 검토 !!!
System.out.print("숫자를 입력하세요: ");
int num = input.nextInt();
int factor = 1;
int a = 0;
int sum = 0;
while (factor <= num) {
if (factor%5==0) {
a = a + 1;
sum = sum + (5*a);
}
factor++;
}
System.out.println("5의배수의 개수: " + a);
System.out.println("5의배수의 합:" + sum);
input.close();
}
}
|
package com.rui.cn.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* todo
*
* @author zhangrl
* @time 2018/11/28-14:04
**/
@Configuration
@EnableWebMvc
public class ApplicationExceptionAdapter extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars")
.addResourceLocations("classpath:/META-INF/webjars/");
}
}
|
package 배열사용;
public class 배열복습 {
public static void main(String[] args) {
// 배열을 마나들 때 값을 처음부터 알고 있는 경우
int[] num = {100, 200, 300};
num[1] = 500;
for (int i = 0; i < num.length; i++) {
System.out.println(num[i]);
}
for (int x : num) {
System.out.println(x);
}
// 값을 처음에 모르고 있다가 나중에 넣는 경우
int[] num2 = new int[3]; // { 0, 0, 0 }로 자동 초기화
num2[0] = 1000;
num2[num2.length - 1] = 1000;
for (int c : num2) {
System.out.println(c);
}
}
}
|
package capitulo08;
public class ComplexTest {
public static void main(String[] args) {
float i = -1;
Complex c1 = new Complex (12.066f,14.006f);
Complex c2 = new Complex (6.333f,2.004f);
displayEquation("Equacao 1: ", c1);
displayEquation("Equacao 2: ", c2);
sumReal(i, c1, c2);
}
private static void sumReal(float i, Complex... c) {
float realParts = 0;
float imaginaryParts = 0;
for (Complex complexes : c) {
realParts += complexes.getRealPart();
imaginaryParts += complexes.getImaginaryPart();
complexes.calculateComplex(i,realParts, imaginaryParts);
}
}
private static void displayEquation(String header, Complex c) {
System.out.printf("%s%n%s%n", header, c.toString());
}
}
|
package oop.ex6.classification;
import oop.ex6.fileanalyzer.BadLineFormatException;
/**
* bad condition exception
*/
public class BadConditionException extends BadLineFormatException {
/** prevents annoying warning */
private static final long serialVersionUID = 1L;
}
|
package com.simplilearn.set;
import java.util.HashSet;
import java.util.Set;
class User{
public String name;
public String gender;
User(){}
User(String name,String gender){
this.name = name;
this.gender = gender;
}
}
public class ExUserHashset {
public static void main(String[] args) {
Set<User> users = new HashSet<User>();
users.add( new User("John","male") );
users.add( new User("Mike","male") );
users.add( new User("Marry","female") );
users.add( new User("Will","male") );
//print user ser
System.out.println(users);
// iterate
for(User u : users) {
System.out.println(u.name +" => " + u.gender);
}
}
}
// Ex :
// Set Collection of Dimond :
// Set Collection of back user: , name,gender and balance
|
package com.bridgeit.batchprocessing;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class BatchStatement {
static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
batchProcessing();
}
public static void batchProcessing()
{
Connection connection=null;
Statement statement=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Enter Name:");
String name=scanner.next();
System.out.println("Enter Salary:");
int salary=scanner.nextInt();
System.out.println("Enter Department Id:");
int department_id=scanner.nextInt();
String insert="insert into employees(name,salary,department_id) values"+"('"+name+"',"+salary+","+department_id+")";
connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","root");
statement=connection.createStatement();
statement.addBatch(insert);
System.out.println("Enter Name to be replaced");
String replaceName=scanner.next();
System.out.println("Enter Name from where to replace");
String name1=scanner.next();
String updatequery="update employees set name='"+replaceName+"' where name='"+name1+"'";
statement=connection.createStatement();
statement.addBatch(updatequery);
System.out.println("Enter id of user to be deleted");
int id=scanner.nextInt();
String deleteQuery="delete from employees where id="+id;
statement.addBatch(deleteQuery);
statement.executeBatch();
}
catch (SQLException | ClassNotFoundException e)
{
e.printStackTrace();
}
finally
{
if(connection!=null)
{
try
{
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if(statement!=null)
{
try
{
statement.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
}
|
package com.tencent.mm.plugin.fav.ui.detail;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import com.tencent.mm.a.e;
import com.tencent.mm.g.a.cb;
import com.tencent.mm.plugin.fav.a.b;
import com.tencent.mm.plugin.fav.a.h;
import com.tencent.mm.plugin.fav.ui.detail.FavoriteImgDetailUI.a;
import com.tencent.mm.plugin.fav.ui.m.i;
import com.tencent.mm.sdk.platformtools.o;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.n.d;
class FavoriteImgDetailUI$7 implements d {
final /* synthetic */ FavoriteImgDetailUI jcT;
final /* synthetic */ a jcX;
FavoriteImgDetailUI$7(FavoriteImgDetailUI favoriteImgDetailUI, a aVar) {
this.jcT = favoriteImgDetailUI;
this.jcX = aVar;
}
public final void onMMMenuItemSelected(MenuItem menuItem, int i) {
String b = b.b(this.jcX.bOz);
if (e.cn(b)) {
switch (menuItem.getItemId()) {
case 1:
b.d(b, this.jcT.mController.tml);
h.f(FavoriteImgDetailUI.b(this.jcT).field_localId, 0, 0);
return;
case 2:
if (o.Wf(b)) {
Intent intent = new Intent();
intent.putExtra("Select_Conv_Type", 3);
intent.putExtra("select_is_ret", true);
com.tencent.mm.bg.d.b(this.jcT, ".ui.transmit.SelectConversationUI", intent, 1);
} else {
b.c(b, this.jcT.mController.tml);
}
h.f(FavoriteImgDetailUI.b(this.jcT).field_localId, 1, 0);
return;
case 3:
FavoriteImgDetailUI.a(b, this.jcT.getString(i.favorite_save_fail), this.jcT.mController.tml);
return;
case 4:
x.i("MicroMsg.FavoriteImgDetailUI", "request deal QBAR string");
cb cbVar = new cb();
cbVar.bJq.activity = this.jcT;
cbVar.bJq.bHL = this.jcX.jdb;
cbVar.bJq.bJr = this.jcX.bJr;
cbVar.bJq.bJt = 7;
if (this.jcX.bOz != null) {
cbVar.bJq.imagePath = this.jcX.bOz.rzo;
cbVar.bJq.bJw = this.jcX.bOz.rzq;
}
cbVar.bJq.bJs = this.jcX.bJs;
Bundle bundle = new Bundle(1);
bundle.putInt("stat_scene", 5);
cbVar.bJq.bJx = bundle;
com.tencent.mm.sdk.b.a.sFg.m(cbVar);
return;
default:
return;
}
}
x.w("MicroMsg.FavoriteImgDetailUI", "file not exists");
}
}
|
package com.allianz.ExpenseTracker.Reports;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang.ArrayUtils;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.RefineryUtilities;
import com.allianz.ExpenseTracker.Objects.DefaultComponents;
import com.allianz.ExpenseTracker.Objects.ObjectsCategoryAmount;
import com.allianz.ExpenseTracker.Objects.ObjectsCategoryReport;
import com.allianz.ExpenseTracker.Objects.ObjectsExpenseTracker;
import com.allianz.ExpenseTracker.Steurung.Categories;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class PnlMonthlygraphical3DChart
{
private static PnlStatiticsReport instance;
ObjectsExpenseTracker expenseObj;
JFrame frmStatiticsReport;
JFrame frmMonthlyGraphical3DChart;
JLabel lblMain;
JButton btnMain;
JButton btnHome;
JButton btnJPG;
JButton btnBack;
JLabel lblDatumVon;
JTextField txtDatumVon;
JLabel lblDatumBis;
JTextField txtDatumBis;
ChartPanel chartPanel;
JLabel lblMessage;
JFreeChart threeDChart;
PnlGraphicalReport objGraph;
PnlStatiticsReport objstatitics;
public String vonDate;
public String bisDate;
public PnlMonthlygraphical3DChart(String vonDate, String bisDate) {
this.vonDate = vonDate;
this.bisDate = bisDate;
initialize();
}
private void initialize() {
// TODO Auto-generated method stub
DefaultComponents expenseTracker = new DefaultComponents();
frmMonthlyGraphical3DChart = expenseTracker.getMainFrame();
lblMain = expenseTracker.getMainLabel();
btnMain = expenseTracker.getMainButton();
btnHome = expenseTracker.getHomeButton();
lblDatumVon = new JLabel("Date From:");
lblDatumVon.setBounds(150, 70, 100, 25);
txtDatumVon = new JTextField();
txtDatumVon.setBounds(275, 70, 80, 25);
txtDatumVon.setText(vonDate);
txtDatumVon.setEnabled(false);
lblDatumBis = new JLabel("Date Till:");
lblDatumBis.setBounds(450, 70, 100, 25);
txtDatumBis = new JTextField();
txtDatumBis.setBounds(575, 70, 80, 25);
txtDatumBis.setText(bisDate);
txtDatumBis.setEnabled(false);
getCharPane();
btnBack = new JButton("BACK");
btnBack.setBounds(320, 700, 150, 30);
btnBack.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
frmMonthlyGraphical3DChart.dispose();
getFrmStatiticsReport().setVisible(true);
}
});
btnJPG = new JButton("Get As Jpeg");
btnJPG.setBounds(600, 120, 150, 25);
btnJPG.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int width = 640; /* Width of the image */
int height = 480; /* Height of the image */
String fileName = "C:\\h\\3DChart"+UUID.randomUUID()+".jpeg";
File lineChartFile = new File( fileName );
try {
ChartUtilities.saveChartAsJPEG(lineChartFile ,getthreeDChart(), width ,height);
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
lblMessage.setText("Line Chart stored in location C:\\h");
lblMessage.setFont(new Font("Arial", Font.BOLD, 16));
}
});
lblMessage = new JLabel();
lblMessage.setBounds(275, 735, 500, 30);
frmMonthlyGraphical3DChart.add(lblMain);
frmMonthlyGraphical3DChart.add(btnMain);
frmMonthlyGraphical3DChart.add(btnHome);
frmMonthlyGraphical3DChart.add(lblDatumVon);
frmMonthlyGraphical3DChart.add(txtDatumVon);
frmMonthlyGraphical3DChart.add(lblDatumBis);
frmMonthlyGraphical3DChart.add(txtDatumBis);
frmMonthlyGraphical3DChart.add(btnJPG);
frmMonthlyGraphical3DChart.add(lblMessage);
frmMonthlyGraphical3DChart.getContentPane().add(chartPanel);
frmMonthlyGraphical3DChart.add(btnBack);
RefineryUtilities.centerFrameOnScreen(frmMonthlyGraphical3DChart);
setfrmMonthlyGraphical3DChart(frmMonthlyGraphical3DChart);
}
private void getCharPane() {
// TODO Auto-generated method stub
JFreeChart threeDChart = ChartFactory.createBarChart3D(
"3D Chart Report",
"Category",
"Amount",
createDataset(),
PlotOrientation.VERTICAL,
true, true, false);
chartPanel = new ChartPanel( threeDChart );
chartPanel.setBounds(20, 150, 750, 510);
setthreeDChart(threeDChart);
}
private CategoryDataset createDataset( ) {
final DefaultCategoryDataset dataset =
new DefaultCategoryDataset( );
ObjectsCategoryAmount objCategoryAmount = new ObjectsCategoryAmount();
ObjectsCategoryReport obj = new ObjectsCategoryReport();
Categories categ = new Categories();
obj.setVonDatum(vonDate);
obj.setBisDatum(bisDate);
ArrayList<ObjectsCategoryAmount> arrayCategundAmount = categ.getMonthsandAmount(obj);
Iterator<ObjectsCategoryAmount> itr = arrayCategundAmount.iterator();
while (itr.hasNext()) {
objCategoryAmount = (ObjectsCategoryAmount) itr.next();
dataset.addValue(objCategoryAmount.getAmount(), objCategoryAmount.getCategory(),"Expense");
}
return dataset;
}
public JFrame getfrmMonthlyGraphical3DChart() {
return frmMonthlyGraphical3DChart;
}
public void setfrmMonthlyGraphical3DChart(JFrame frmMonthlyGraphical3DChart) {
this.frmMonthlyGraphical3DChart = frmMonthlyGraphical3DChart;
}
public JFreeChart getthreeDChart() {
return threeDChart;
}
public void setthreeDChart(JFreeChart threeDChart) {
this.threeDChart = threeDChart;
}
public JFrame getFrmStatiticsReport() {
return frmStatiticsReport;
}
public void setFrmStatiticsReport(JFrame frmStatiticsReport) {
this.frmStatiticsReport = frmStatiticsReport;
}
}
|
package edu.bu.met622.threadtest;
public class SecondThread implements Runnable{
@Override
public void run() {
for (int j =0; j<100 ; j++) {
System.out.println("-from SecondThread: ===> j:"+j);
}
}
}
|
package com.tencent.mm.plugin.shake.c.a;
public final class e {
public String cad = "";
public String dxh = "";
public int end_time;
public String huU = "";
public String huW = "";
public String huX = "";
public String huY = "";
public int hwF = 0;
public String hwh = "";
public int mXk = 0;
public int mXn = 0;
public String mXo = "";
public String mXp = "";
public String mXq = "";
public String mXr = "";
public String mXs = "";
public boolean mXt;
public String title = "";
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.order.strategies.impl;
import static org.mockito.BDDMockito.given;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.core.model.order.QuoteModel;
import de.hybris.platform.servicelayer.time.TimeService;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
/**
* Unit test for DefaultQuoteExpirationTimeValidationStrategy
*/
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class DefaultQuoteExpirationTimeValidationStrategyTest
{
@InjectMocks
private final DefaultQuoteExpirationTimeValidationStrategy defaultQuoteExpiryDateValidationStrategy = new DefaultQuoteExpirationTimeValidationStrategy();
@Mock
private TimeService timeService;
@Mock
private QuoteModel quoteModel;
@Before
public void setUp()
{
MockitoAnnotations.initMocks(this);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentExceptionForNullQuote()
{
defaultQuoteExpiryDateValidationStrategy.hasQuoteExpired(null);
}
@Test
public void shouldReturnFalseIfExpirationTimeAfterCurrentTime()
{
final Date currentTime = Calendar.getInstance().getTime();
given(quoteModel.getExpirationTime()).willReturn(DateUtils.addDays(currentTime, 5));
given(timeService.getCurrentTime()).willReturn(currentTime);
Assert.assertFalse(defaultQuoteExpiryDateValidationStrategy.hasQuoteExpired(quoteModel));
}
@Test
public void shouldReturnFalseIfExpirationTimeEqualToCurrentTime()
{
final Date currentTime = Calendar.getInstance().getTime();
given(quoteModel.getExpirationTime()).willReturn(currentTime);
given(timeService.getCurrentTime()).willReturn(currentTime);
Assert.assertFalse(defaultQuoteExpiryDateValidationStrategy.hasQuoteExpired(quoteModel));
}
@Test
public void shouldReturnTrueForNullExpirationTime()
{
given(quoteModel.getExpirationTime()).willReturn(null);
Assert.assertTrue(defaultQuoteExpiryDateValidationStrategy.hasQuoteExpired(quoteModel));
}
@Test
public void shouldReturnTrueIfExpirationTimeBeforeCurrentTime()
{
final Date currentTime = Calendar.getInstance().getTime();
given(quoteModel.getExpirationTime()).willReturn(DateUtils.addDays(currentTime, -5));
given(timeService.getCurrentTime()).willReturn(currentTime);
Assert.assertTrue(defaultQuoteExpiryDateValidationStrategy.hasQuoteExpired(quoteModel));
}
}
|
package com.leetcode.easy.array;
/**
* Created by saml on 9/25/2017.
* <p>
* Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
* <p>
* You may assume the integer do not contain any leading zero, except the number 0 itself.
* <p>
* The digits are stored such that the most significant digit is at the head of the list.
*/
public class PlusOneSolution {
public static void main(String[] args) {
PlusOneSolution plusOneSolution = new PlusOneSolution();
int[] a = {8, 9, 9, 9};
int[] result = plusOneSolution.plusOne(a);
for (int n : result) {
System.out.println(n);
}
}
public int[] plusOne(int[] digits) {
//return array after plus one
if (digits[digits.length - 1] != 9) {
digits[digits.length - 1] = digits[digits.length - 1] + 1;
return digits;
}
//check if all digits are 9
boolean isAll9 = true;
for (int i = 0; i < digits.length; i++) {
if (digits[i] != 9) {
isAll9 = false;
break;
}
}
//if so, add one digit at the beginning and set to one
//the rest of the digits are all 0
if (isAll9) {
int[] result = new int[digits.length + 1];
result[0] = 1;
return result;
} else {
//Process carry over in recursion
digits = getResultArr(digits, digits.length - 1);
}
return digits;
}
public int[] getResultArr(int[] digits, int index) {
if (digits[index] == 9) {
digits[index] = 0;
getResultArr(digits, --index);
} else {
digits[index] = digits[index] + 1;
}
return digits;
}
}
|
package com.ntxdev.zuptecnico;
/**
* Created by igorlira on 4/27/14.
*/
public interface SearchBarListener {
public void onSearchTextChanged(String text);
}
|
package ch.gelion.searchcolumn;
import java.sql.SQLException;
import java.text.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author gP
*/
public class Main {
private Logger log;
private SearchColumn searchcolumn;
private final String sSearch;
public Main(String[] args) {
this.sSearch = args[0];
}
protected void doIt() throws SQLException, ParseException {
this.log = LoggerFactory.getLogger(this.getClass());
log.info("application started successfully");
log.debug("search text: {}", sSearch);
Config.initialize();
searchcolumn = new SearchColumn();
searchcolumn.openDatabase();
searchcolumn.doIt(sSearch);
searchcolumn.closeDatabase();
log.info("application terminated successfully");
}
public static void main(String[] args) throws SQLException, ParseException {
Main m = new Main(args);
m.doIt();
}
}
|
import javax.print.DocFlavor;
/**
* Created by djawed on 22/06/17.
*/
abstract class animal {
protected String couleur;
protected int poid;
protected void manger() {
System.out.print("je suis");
}
protected void boire() {
System.out.print("je bois de leau ");
}
abstract void deplacement();
abstract void crier();
public String toString() {
String str = "je suis un objet de la " + this.getClass() + "je suis " + this.couleur + "je pése" + this.poid;
return str;
}
}
|
package com.suntiago.network.network.rsp;
/**
* Created by 潮雪野 on 2017/10/28.
*/
public class FileUploadResponse extends BaseResponse {
public String extra;
}
|
package com.example.passin.domain.password;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class SavePasswordDto {
private String hostName;
private String email;
private String password;
private String originalPassword;
private long userId;
}
|
package com.kunsoftware.service;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.kunsoftware.bean.OrdersStatusRequestBean;
import com.kunsoftware.entity.OrdersStatus;
import com.kunsoftware.exception.KunSoftwareException;
import com.kunsoftware.mapper.OrdersStatusMapper;
import com.kunsoftware.util.WebUtil;
@Service
public class OrdersStatusService {
private static Logger logger = LoggerFactory.getLogger(OrdersStatusService.class);
@Autowired
private OrdersStatusMapper mapper;
public List<OrdersStatus> getOrdersStatusListAll(Integer ordersId) {
logger.info("query");
return mapper.getOrdersStatusListAll(ordersId,null);
}
@Transactional
public OrdersStatus insert(OrdersStatusRequestBean requestBean) throws KunSoftwareException {
OrdersStatus record = new OrdersStatus();
BeanUtils.copyProperties(requestBean, record);
record.setDealDate(new Date());
record.setUserId(WebUtil.getUserId());
record.setUserName(WebUtil.getUserName());
mapper.insert(record);
return record;
}
public OrdersStatus selectByPrimaryKey(Integer id) throws KunSoftwareException {
return mapper.selectByPrimaryKey(id);
}
@Transactional
public int updateByPrimaryKey(OrdersStatusRequestBean requestBean,Integer id) throws KunSoftwareException {
OrdersStatus record = mapper.selectByPrimaryKey(id);
BeanUtils.copyProperties(requestBean, record);
record.setDealDate(new Date());
record.setUserId(WebUtil.getUserId());
record.setUserName(WebUtil.getUserName());
return mapper.updateByPrimaryKeySelective(record);
}
@Transactional
public int deleteByPrimaryKey(Integer id) throws KunSoftwareException {
return mapper.deleteByPrimaryKey(id);
}
@Transactional
public void deleteByPrimaryKey(Integer[] id) throws KunSoftwareException {
for(int i = 0;i < id.length;i++) {
mapper.deleteByPrimaryKey(id[i]);
}
}
}
|
package com.qa.accessmods;
public class BankRunner {
public static void main(String[] args) {
BankAccount hsbc = new BankAccount();
hsbc.setName("randName");
}
}
|
/*
* Copyright (C) 2022-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.grpc.controller;
import com.google.protobuf.ByteString;
import com.hedera.mirror.api.proto.AddressBookQuery;
import com.hedera.mirror.api.proto.ReactorNetworkServiceGrpc;
import com.hedera.mirror.common.domain.addressbook.AddressBookEntry;
import com.hedera.mirror.common.domain.entity.EntityId;
import com.hedera.mirror.grpc.domain.AddressBookFilter;
import com.hedera.mirror.grpc.service.NetworkService;
import com.hedera.mirror.grpc.util.ProtoUtil;
import com.hederahashgraph.api.proto.java.NodeAddress;
import com.hederahashgraph.api.proto.java.ServiceEndpoint;
import java.net.InetAddress;
import java.net.UnknownHostException;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import net.devh.boot.grpc.server.service.GrpcService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@GrpcService
@Log4j2
@RequiredArgsConstructor
public class NetworkController extends ReactorNetworkServiceGrpc.NetworkServiceImplBase {
private final NetworkService networkService;
@Override
public Flux<NodeAddress> getNodes(Mono<AddressBookQuery> request) {
return request.map(this::toFilter)
.flatMapMany(networkService::getNodes)
.map(this::toNodeAddress)
.onErrorMap(ProtoUtil::toStatusRuntimeException);
}
private AddressBookFilter toFilter(AddressBookQuery query) {
var filter = AddressBookFilter.builder().limit(query.getLimit());
if (query.hasFileId()) {
filter.fileId(EntityId.of(query.getFileId()));
}
return filter.build();
}
@SuppressWarnings("deprecation")
private NodeAddress toNodeAddress(AddressBookEntry addressBookEntry) {
var nodeAddress = NodeAddress.newBuilder()
.setNodeAccountId(ProtoUtil.toAccountID(addressBookEntry.getNodeAccountId()))
.setNodeId(addressBookEntry.getNodeId());
if (addressBookEntry.getDescription() != null) {
nodeAddress.setDescription(addressBookEntry.getDescription());
}
if (addressBookEntry.getMemo() != null) {
nodeAddress.setMemo(ByteString.copyFromUtf8(addressBookEntry.getMemo()));
}
if (addressBookEntry.getNodeCertHash() != null) {
nodeAddress.setNodeCertHash(ProtoUtil.toByteString(addressBookEntry.getNodeCertHash()));
}
if (addressBookEntry.getPublicKey() != null) {
nodeAddress.setRSAPubKey(addressBookEntry.getPublicKey());
}
if (addressBookEntry.getStake() != null) {
nodeAddress.setStake(addressBookEntry.getStake());
}
for (var s : addressBookEntry.getServiceEndpoints()) {
try {
var ipAddressV4 = InetAddress.getByName(s.getIpAddressV4()).getAddress();
var serviceEndpoint = ServiceEndpoint.newBuilder()
.setIpAddressV4(ProtoUtil.toByteString(ipAddressV4))
.setPort(s.getPort())
.build();
nodeAddress.addServiceEndpoint(serviceEndpoint);
} catch (UnknownHostException e) {
// Shouldn't occur since we never pass hostnames to InetAddress.getByName()
log.warn("Unable to convert IP address to byte array", e.getMessage());
}
}
return nodeAddress.build();
}
}
|
package material.events;
import material.components.*;
public abstract class Event
{
public _InteractiveComponent source;
protected Event(_InteractiveComponent source) {
this.source = source;
}
}
|
/**
* @Title: OfficeServiceImpl.java
* @package com.rofour.baseball.service.officemanage.impl
* @Project: baseball-yeah
* @author WJ
* ──────────────────────────────────
* Copyright (c) 2016, 指端科技.
*/
package com.rofour.baseball.service.officemanage.impl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rofour.baseball.common.Constant;
import com.rofour.baseball.common.HttpClientUtils;
import com.rofour.baseball.controller.model.ResultInfo;
import com.rofour.baseball.controller.model.office.OfficeQueryInfo;
import com.rofour.baseball.dao.officemanage.bean.*;
import com.rofour.baseball.dao.officemanage.mapper.OfficeMapper;
import com.rofour.baseball.exception.BusinessException;
import com.rofour.baseball.service.officemanage.OfficeService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @ClassName: OfficeServiceImpl
* @Description 职务管理实现类
* @author WJ
* @date 2016年10月12日 下午1:51:16
*
*/
@Service("officeService")
public class OfficeServiceImpl implements OfficeService {
/**
* 职务,1:普通小派 ,2:校园COO,3: 校园CEO
*/
private static final int CEO = 3;
private static final int COO = 2;
private static final int OPT_TYPE_CEO = 1;
private static final int OPT_TYPE_COO = 2;
@Autowired
private OfficeMapper officeMapper;
/**
* @Description 查询COO, CEO
* @param info
* @return List<OfficeBean> 返回类型
* @author WJ
* @date 2016年10月12日 下午1:56:02
**/
@Override
public List<OfficeBean> list(OfficeQueryInfo info) {
List<OfficeBean> list = officeMapper.queryAll(info);
for (OfficeBean bean : list) {
if (bean.getOffice() == CEO) {
//统计小派和COO
bean.setPacketUser(officeMapper.queryUserAndCOOTotal(bean.getUserId()));
bean.setStore(officeMapper.queryStoreAndCOOTotal(bean.getUserId()));
} else {
bean.setPacketUser(officeMapper.queryUserTotal(bean.getUserId()));
bean.setStore(officeMapper.queryStoreTotal(bean.getUserId()));
}
}
return list;
}
/**
* @Description 查询普通小派
* @param info
* @return List<OfficeBean> 返回类型
* @author WJ
* @date 2016年10月12日 下午1:56:02
**/
@Override
public List<OfficeBean> listPuser(OfficeQueryInfo info) {
List<OfficeBean> list = officeMapper.queryAllPuser(info);
return list;
}
/**
* @Description 统计
* @param info
* @return int 返回类型
* @author WJ
* @date 2016年10月12日 下午1:56:05
**/
@Override
public int getTotal(OfficeQueryInfo info) {
return officeMapper.getTotal(info);
}
/**
* @Description 统计普通小派
* @param info
* @return int 返回类型
* @author WJ
* @date 2016年10月12日 下午1:56:05
**/
@Override
public int getPuserTotal(OfficeQueryInfo info) {
return officeMapper.queryAllPuserTotal(info);
}
/**
* @Description 解除职务
* @return ResultInfo<Object> 返回类型
**/
@Override
public ResultInfo<Object> dismiss(Long userId, int office) {
//step1:更新自身职务属性
int result = officeMapper.updateRoleType(userId);
//step2:判断CEO还是COO
if (office == CEO) {
officeMapper.updatePuserCEO(userId);
officeMapper.updateStoreCEO(userId);
} else {
//step3:清除属下小派
officeMapper.updatePuserCOO(userId);
//step4:清除属下商户
officeMapper.updateStoreCOO(userId);
}
return result > 0 ? new ResultInfo<Object>(0, "", "操作成功") : new ResultInfo<Object>(-1, "", "操作失败");
}
/**
* @Description 更新审核状态
**/
@Override
public void audit(Long auditId, Boolean isPass, Long managerId) throws Exception {
OfficeAuditBean officeAuditBean = officeMapper.getOfficeAuditById(auditId);
if (officeAuditBean == null) {
//未查询到有效审核信息
throw new BusinessException("06001");
}
HashMap<String, Object> map = new HashMap<>();
map.put("auditId", auditId);
map.put("managerId", managerId);
map.put("userId", officeAuditBean.getPacketUserId());
if (isPass) {
map.put("auditState", "1");
int optType = officeAuditBean.getOptType();
//1-新建ceo 2-新建coo
if (optType == OPT_TYPE_CEO) {
map.put("roleType", "3");
} else {
map.put("roleType", "2");
}
officeMapper.updatePacketRole(map);
} else {
map.put("auditState", "2");
}
officeMapper.updateAuditState(map);
}
/**
* @Description 职务编辑细节
* @param userId
* @throws IOException
**/
@Override
public ResultInfo<Object> officeDetail(Long userId) throws IOException {
OfficeDetailBean bean = officeMapper.queryByUserId(userId);
return bean != null ? new ResultInfo<Object>(0, "", "操作成功", bean)
: new ResultInfo<Object>(-1, "", "未查询到此小派详细信息");
}
/**
*
* @Description 获取头像等图片信息
* @param bizId
* @param attachType
*
*/
public ResultInfo<Object> getUrl(Long bizId, String attachType) throws IOException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("bizId", bizId);
map.put("attachType", attachType);
String url = Constant.axpurl.get("resource_getOriginAttachList_serv");
// 定义反序列化 数据格式
final TypeReference<ResultInfo<?>> TypeRef = new TypeReference<ResultInfo<?>>() {
};
List<String> list = new ArrayList<>();
ResultInfo<?> credentialUrls = (ResultInfo<?>) HttpClientUtils.post(url, map, TypeRef);
if (null != credentialUrls && credentialUrls.getSuccess() == 1) {
List<?> credentialURLInfo = (List<?>) credentialUrls.getData();
if (CollectionUtils.isNotEmpty(credentialURLInfo)) {
for (Object o : credentialURLInfo) {
if (o instanceof Map) {
Map<?, ?> imageMap = (Map<?, ?>) o;
list.add(imageMap.get("fileUrl").toString());
}
}
}
}
return !list.isEmpty() ? new ResultInfo<Object>(0, "", "操作成功", list)
: new ResultInfo<Object>(-1, "", "未查询到图片信息");
}
/**
*
* @Description 查询属下小派和coo
* @param info
*
*/
public List<OfficeBean> queryAttached(OfficeQueryInfo info) {
return officeMapper.queryAttached(info);
}
/**
*
* @Description 统计属下小派或者coo人数
* @param info
*
*/
public int userTotal(OfficeQueryInfo info) {
int result = 0;
if (info.getOffice() == CEO) {
result = officeMapper.queryUserAndCOOTotal(info.getUserId());
} else if (info.getOffice() == COO) {
result = officeMapper.queryUserTotal(info.getUserId());
}
return result;
}
/**
* @Description 查询属下的商户
* @param info
**/
@Override
public List<OfficeStoreBean> queryAttachedStores(OfficeQueryInfo info) {
return officeMapper.queryAttachedStores(info);
}
/**
*
* @Description 统计属下商户数
* @param info
*
*/
@Override
public int storeTotal(OfficeQueryInfo info) {
int result = 0;
if (info.getOffice() == CEO) {
result = officeMapper.queryStoreAndCOOTotal(info.getUserId());
} else if (info.getOffice() == COO) {
result = officeMapper.queryStoreTotal(info.getUserId());
}
return result;
}
/**
* @Description 小派删除, 支持批量
* @param ids
**/
@Override
public ResultInfo<Object> pDel(Map<String, Object> map) {
int result = officeMapper.deletePuserBoss(map);
return result > 0 ? new ResultInfo<Object>(0, "", "删除成功") : new ResultInfo<Object>(-1, "", "删除失败");
}
/**
* @Description 商户删除, 支持批量
* @param map
**/
@Override
public ResultInfo<Object> sDel(Map<String, Object> map) {
int result = officeMapper.deleteStoreBoss(map);
return result > 0 ? new ResultInfo<Object>(0, "", "删除成功") : new ResultInfo<Object>(-1, "", "删除失败");
}
/**
* @Description 小派增加, 支持批量
* @param map
**/
@Override
public ResultInfo<Object> pAdd(Map<String, Object> map) {
int result = officeMapper.addPuserBoss(map);
return result > 0 ? new ResultInfo<Object>(0, "", "添加成功") : new ResultInfo<Object>(-1, "", "添加失败");
}
/**
* @Description: 获取审核记录
* @param queryInfo
* @return
* @throws
* @author ZXY
*/
@Override
public Map getOfficeAudit(OfficeQueryInfo queryInfo) throws Exception {
if (StringUtils.isBlank(queryInfo.getSort())) {
queryInfo.setSort("signupTime");//默认以时间排序
queryInfo.setOrder("desc");//默认倒序
}
List<OfficeAuditInfo> infoList = officeMapper.getOfficeAudit(queryInfo);
int count = officeMapper.getOfficeAuditCount(queryInfo);
Map map = new HashMap();
map.put("list", infoList);
map.put("count", count);
return map;
}
}
|
package com.a1tSign.techBoom.data.dto.user;
import lombok.*;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class UserStatisticDTO {
String username;
double xCoordinate;
double yCoordinate;
}
|
package LC0_200.LC150_200;
import java.util.Arrays;
public class LC164_Maximum_Gap {
public int maximumGap(int[] nums) {
if (nums.length < 2) return 0;
Arrays.sort(nums);
int max = 0;
for (int i = 0; i < nums.length - 1; ++i) {
int gap = nums[i + 1] - nums[i];
max = max > gap ? max : gap;
}
return max;
}
}
|
package boj1011;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main1 {
// 문제가 잘못된 듯 함
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer stz;
int testcase = Integer.parseInt(br.readLine());
for(int i=0; i<testcase; i++) {
stz = new StringTokenizer(br.readLine());
int x = Integer.parseInt(stz.nextToken());
int y = Integer.parseInt(stz.nextToken());
int distance = y - x;
int n =(int)Math.round(Math.sqrt(distance));
if( distance <= n*n) {
bw.write(2*n-1+"\n");
}else {
bw.write(2*n+"\n");
}
}
bw.flush();
bw.close();
br.close();
}
}
|
package com.zhouyi.business.core.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 账号流水
*
*
*/
public class PersonExchangeDetail implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String accNo;
private BigDecimal totalBalance;
private BigDecimal oldAvaBalance;
private BigDecimal oldFreBalance;
private BigDecimal newAvaBalance;
private BigDecimal newFreBalance;
private Long serialNo;
private Date createTime;
private String remark;
private String operateType;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccNo() {
return accNo;
}
public void setAccNo(String accNo) {
this.accNo = accNo;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public BigDecimal getTotalBalance() {
return totalBalance;
}
public void setTotalBalance(BigDecimal totalBalance) {
this.totalBalance = totalBalance;
}
public BigDecimal getOldAvaBalance() {
return oldAvaBalance;
}
public void setOldAvaBalance(BigDecimal oldAvaBalance) {
this.oldAvaBalance = oldAvaBalance;
}
public BigDecimal getOldFreBalance() {
return oldFreBalance;
}
public void setOldFreBalance(BigDecimal oldFreBalance) {
this.oldFreBalance = oldFreBalance;
}
public BigDecimal getNewAvaBalance() {
return newAvaBalance;
}
public void setNewAvaBalance(BigDecimal newAvaBalance) {
this.newAvaBalance = newAvaBalance;
}
public BigDecimal getNewFreBalance() {
return newFreBalance;
}
public void setNewFreBalance(BigDecimal newFreBalance) {
this.newFreBalance = newFreBalance;
}
public Long getSerialNo() {
return serialNo;
}
public void setSerialNo(Long serialNo) {
this.serialNo = serialNo;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getOperateType() {
return operateType;
}
public void setOperateType(String operateType) {
this.operateType = operateType;
}
}
|
import java.io.*;
import java.net.*;
public class mst1
{
public static void main(String args[]) throws IOException
{
InetAddress g=null;
MulticastSocket s=null;
int port=0;
String msg;
try
{
g=InetAddress.getByName("239.1.2.4");
port=3457;
msg="Hey there we are threaded!";
DatagramPacket ps=new DatagramPacket(msg.getBytes(),msg.length(),g,port);
Thread tt1=new Thread(new mst2(g,port));
tt1.start();
System.out.println("Press Enter to Start:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
br.readLine();
s=new MulticastSocket(port);
s.setTimeToLive(1);
s.send(ps);
s.close();
}
catch(Exception se)
{
se.printStackTrace();
}
}
}
|
/*
* 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 com.agfa.dach.support.internal.atms.dao;
import com.agfa.dach.support.internal.atms.entity.User;
import javax.enterprise.inject.Model;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author leandros
*/
@Model
public class UserDAO {
@PersistenceContext(unitName = "atms-persunit")
private EntityManager entityManager;
public User findById(String id) {
return entityManager.find(User.class, id);
}
public void persist(User user) {
entityManager.persist(user);
}
public void delete(User user) {
entityManager.remove(user);
}
}
|
package naruter.com.outsourcing.vo;
import org.apache.ibatis.type.Alias;
import org.springframework.stereotype.Component;
@Alias("ci")
public class ClientInfo {
private Integer membernum;
private String companyname; /*회사이름*/
private String companynumber; /*사업자번호*/
private String companyaddress; /*회사 주소*/
private String companytype /*기업형태 -> 공공기업, 중소기업 등등*/;
private String companysite /*회사 홈페이지*/;
public ClientInfo() {}
public ClientInfo(Integer membernum, String companyname, String companynumber, String companyaddress,
String companytype, String companysite) {
super();
this.membernum = membernum;
this.companyname = companyname;
this.companynumber = companynumber;
this.companyaddress = companyaddress;
this.companytype = companytype;
this.companysite = companysite;
}
public Integer getMembernum() {
return membernum;
}
public void setMembernum(Integer membernum) {
this.membernum = membernum;
}
public String getCompanyname() {
return companyname;
}
public void setCompanyname(String companyname) {
this.companyname = companyname;
}
public String getCompanynumber() {
return companynumber;
}
public void setCompanynumber(String companynumber) {
this.companynumber = companynumber;
}
public String getCompanyaddress() {
return companyaddress;
}
public void setCompanyaddress(String companyaddress) {
this.companyaddress = companyaddress;
}
public String getCompanytype() {
return companytype;
}
public void setCompanytype(String companytype) {
this.companytype = companytype;
}
public String getCompanysite() {
return companysite;
}
public void setCompanysite(String companysite) {
this.companysite = companysite;
}
@Override
public String toString() {
return "ClientInfo [membernum=" + membernum + ", companyname=" + companyname + ", companynumber="
+ companynumber + ", companyaddress=" + companyaddress + ", companytype=" + companytype
+ ", companysite=" + companysite + "]";
}
}
|
package com.itheima.dao;
import com.itheima.pojo.OrderSetting;
import java.util.Date;
import java.util.List;
import java.util.Map; /**
* 预约设置接口
*/
public interface OrderSettingDao {
/**
* 根据预约日期查询是否已经设置预约
* @param orderDate
* @return
*/
int findCountByOrderDate(Date orderDate);
/**
* 根据预约日期修改预约人数number
* @param orderSetting
*/
void editNumberByOrderDate(OrderSetting orderSetting);
/**
* 新增预约设置
* @param orderSetting
*/
void add(OrderSetting orderSetting);
/**
* 根据起始时间和结束时间查询当前月份预约设置所有数据
* @param parmMap
* @return
*/
List<OrderSetting> getOrderSettingByMonth(Map<String, String> parmMap);
/**
* 根据预约日期查询预约数据
* @param orderDate
* @return
*/
OrderSetting findByOrderDate(String orderDate);
/**
* 根据预约日期修改已经预约数量 每次+1
* @param orderSetting
*/
void editReservationsByOrderDate(OrderSetting orderSetting);
//删除过期预约设置
void deleteOrderSetting(String date);
}
|
package in.dailyhunt.internship.userprofile.endpoints;
import in.dailyhunt.internship.userprofile.client_model.request.NewsComponentsRequest;
import in.dailyhunt.internship.userprofile.client_model.request.SourceRequest;
import in.dailyhunt.internship.userprofile.client_model.response.*;
import in.dailyhunt.internship.userprofile.entities.GenreData;
import in.dailyhunt.internship.userprofile.entities.LanguageData;
import in.dailyhunt.internship.userprofile.entities.LocalityData;
import in.dailyhunt.internship.userprofile.entities.TagData;
import in.dailyhunt.internship.userprofile.services.interfaces.NewsComponentsService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.config.RepositoryNameSpaceHandler;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import javax.validation.Valid;
import java.util.List;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(NewsComponentsEndpoint.BASE_URL)
public class NewsComponentsEndpoint {
static final String BASE_URL = "api/v1/injestion/user_profile/newsComponents";
// private final WebClient.Builder webclientBuilder;
private final NewsComponentsService newsComponentsService;
@Autowired
public NewsComponentsEndpoint(NewsComponentsService newsComponentsService) {
this.newsComponentsService = newsComponentsService;
}
@GetMapping("/generic")
ResponseEntity<AllGenres> getGenericGenres() {
return ResponseEntity.ok().body(newsComponentsService.getAllGenericGenres());
}
@GetMapping("/genres")
ResponseEntity<AllGenres> getAllGenres() {
return ResponseEntity.ok().body(newsComponentsService.getAllGenres());
}
@PostMapping("/genre")
public ResponseEntity<String> addGenre(@RequestBody NewsComponentsRequest newsComponentsRequest) {
newsComponentsService.addGenre(newsComponentsRequest);
return ResponseEntity.ok().body("Genre has been added successfully");
}
@DeleteMapping("/genre/{id}")
public ResponseEntity<String> deleteGenre(@PathVariable Long id) {
newsComponentsService.deleteGenre(id);
return ResponseEntity.ok().body("Genre has been deleted successfully");
}
@PutMapping("/genre/{id}")
public ResponseEntity<String> updateGeneric(@PathVariable Long id) {
newsComponentsService.updateGeneric(id);
return ResponseEntity.ok().body("Genre generic updated successfully");
}
@GetMapping("/languages")
ResponseEntity<AllLanguages> getAllLanguages() {
return ResponseEntity.ok().body(newsComponentsService.getAllLanguages());
}
@PostMapping("/language")
public ResponseEntity<String> addLanguage(@Valid @RequestBody NewsComponentsRequest newsComponentsRequest) {
newsComponentsService.addLanguage(newsComponentsRequest);
return ResponseEntity.ok().body("Language has been added successfully");
}
@DeleteMapping("/language/{id}")
public ResponseEntity<String> deleteLanguage(@PathVariable Long id) {
newsComponentsService.deleteLanguage(id);
return ResponseEntity.ok().body("Language has been deleted successfully");
}
@GetMapping("/localities")
ResponseEntity<AllLocalities> getAllLocalities() {
return ResponseEntity.ok().body(newsComponentsService.getAllLocalities());
}
@PostMapping("/locality")
public ResponseEntity<String> addLocality(@Valid @RequestBody NewsComponentsRequest newsComponentsRequest) {
newsComponentsService.addLocality(newsComponentsRequest);
return ResponseEntity.ok().body("Locality has been added successfully");
}
@DeleteMapping("/locality/{id}")
public ResponseEntity<String> deleteLocality(@PathVariable Long id) {
newsComponentsService.deleteLocality(id);
return ResponseEntity.ok().body("Locality has been deleted successfully");
}
@GetMapping("/tags")
ResponseEntity<AllTags> getAllTags() {
return ResponseEntity.ok().body(newsComponentsService.getAllTags());
}
@PostMapping("/tag")
public ResponseEntity<String> addTag(@Valid @RequestBody NewsComponentsRequest newsComponentsRequest) {
newsComponentsService.addTag(newsComponentsRequest);
return ResponseEntity.ok().body("Tag has been added successfully");
}
@DeleteMapping("/tag/{id}")
public ResponseEntity<String> deleteTag(@PathVariable Long id) {
newsComponentsService.deleteTag(id);
return ResponseEntity.ok().body("Tag has been deleted successfully");
}
@GetMapping("/sources")
ResponseEntity<AllSources> getAllSources() {
return ResponseEntity.ok().body(newsComponentsService.getAllSources());
}
@PostMapping("/source")
public ResponseEntity<String> addSource(@Valid @RequestBody SourceRequest sourceRequest) {
newsComponentsService.addSource(sourceRequest);
return ResponseEntity.ok().body("Source has been added successfully");
}
@DeleteMapping("/source/{id}")
public ResponseEntity<String> deleteSource(@PathVariable Long id) {
newsComponentsService.deleteSource(id);
return ResponseEntity.ok().body("Source has been deleted successfully");
}
}
|
package com.jim.multipos.ui.signing.sign_up.view;
import com.jim.multipos.core.BaseView;
/**
* Created by DEV on 31.07.2017.
*/
public interface RegistrationConfirmView extends BaseView {
}
|
package com.tencent.mm.ak.a.a;
import com.tencent.mm.ak.a.c.h;
import com.tencent.mm.sdk.platformtools.x;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class a$b extends ThreadPoolExecutor implements h {
private ReentrantLock dXd = new ReentrantLock();
private Condition dXe = this.dXd.newCondition();
private BlockingQueue<Runnable> dXf;
private boolean isPaused;
public a$b(int i, int i2, TimeUnit timeUnit, BlockingQueue<Runnable> blockingQueue, ThreadFactory threadFactory) {
super(i, i2, 0, timeUnit, blockingQueue, threadFactory);
this.dXf = blockingQueue;
}
protected final void beforeExecute(Thread thread, Runnable runnable) {
super.beforeExecute(thread, runnable);
this.dXd.lock();
while (this.isPaused) {
try {
this.dXe.await();
} catch (Exception e) {
thread.interrupt();
x.w("MicroMsg.imageloader.DefaultThreadPoolExecutor", "[cpan] before execute exception:%s", new Object[]{e.toString()});
} finally {
this.dXd.unlock();
}
}
}
public final void pause() {
this.dXd.lock();
try {
this.isPaused = true;
} finally {
this.dXd.unlock();
}
}
public final void resume() {
this.dXd.lock();
try {
this.isPaused = false;
this.dXe.signalAll();
} finally {
this.dXd.unlock();
}
}
public final void execute(Runnable runnable) {
super.execute(runnable);
}
public final boolean wc() {
return this.isPaused;
}
public final void remove(Object obj) {
if (this.dXf != null) {
this.dXf.remove(obj);
}
}
}
|
package com.example.raktseva;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
List<UserProfile> usersList;
Context context;
public RecyclerViewAdapter(List<UserProfile> usersList, Context context) {
this.usersList = usersList;
this.context = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_rv_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerViewAdapter.MyViewHolder holder, int position) {
holder.rvtv_userName.setText(usersList.get(position).getName());
holder.rvtv_userPhoneNumber.setText(usersList.get(position).getPhoneNumber());
holder.rvtv_userBloodGroup.setText(usersList.get(position).getBloodGroup());
holder.rtrv_userState.setText(usersList.get(position).getState());
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// send the control to UserProfileActivity
Intent intent = new Intent(context, UserProfileActivity.class);
intent.putExtra("userPhoneNumber", usersList.get(position).getPhoneNumber());
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return usersList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView rvtv_userName;
TextView rvtv_userPhoneNumber;
TextView rvtv_userBloodGroup;
TextView rtrv_userState;
CardView parentLayout;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
rvtv_userName = itemView.findViewById(R.id.rvtv_userName);
rvtv_userPhoneNumber = itemView.findViewById(R.id.rvtv_userPhoneNumber);
rvtv_userBloodGroup = itemView.findViewById(R.id.rvtv_userBloodGroup);
rtrv_userState = itemView.findViewById(R.id.rvtv_userState);
parentLayout = itemView.findViewById(R.id.cardview_user_rv_row);
}
}
}
|
//
// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.3.0
// Vedere <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine.
// Generato il: 2021.06.10 alle 04:43:49 PM CEST
//
package com.ricettadem.soap.certificatiMalattia;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Giornata lavorata: se true indica che il lavoratore ha dichiarato di aver completato la propria attivita' lavorativa alla data del
* ricovero,
* false altrimenti.
* Trauma: indica l'occorrenza di un evento traumatico.
*
*
* <p>Classe Java per malattia complex type.
*
* <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe.
*
* <pre>
* <complexType name="malattia">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ruoloMedico" type="{http://cert.sanita.finanze.it/}ruolo"/>
* <element name="dataRilascio" type="{http://cert.sanita.finanze.it/}dateString"/>
* <element name="dataInizio" type="{http://cert.sanita.finanze.it/}dateString"/>
* <element name="dataFine" type="{http://cert.sanita.finanze.it/}dateString"/>
* <element name="visita" type="{http://cert.sanita.finanze.it/}tipoVisita"/>
* <element name="tipoCertificato" type="{http://cert.sanita.finanze.it/}tipoCertificato"/>
* <element name="diagnosi" type="{http://cert.sanita.finanze.it/}diagnosi"/>
* <element name="giornataLavorata" type="{http://cert.sanita.finanze.it/}booleanString" minOccurs="0"/>
* <element name="trauma" type="{http://cert.sanita.finanze.it/}booleanString" minOccurs="0"/>
* <element name="agevolazioni" type="{http://cert.sanita.finanze.it/}agevolazioni" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "malattia", propOrder = {
"ruoloMedico",
"dataRilascio",
"dataInizio",
"dataFine",
"visita",
"tipoCertificato",
"diagnosi",
"giornataLavorata",
"trauma",
"agevolazioni"
})
public class Malattia {
@XmlElement(required = true)
protected String ruoloMedico;
@XmlElement(required = true)
protected String dataRilascio;
@XmlElement(required = true)
protected String dataInizio;
@XmlElement(required = true)
protected String dataFine;
@XmlElement(required = true)
protected String visita;
@XmlElement(required = true)
protected String tipoCertificato;
@XmlElement(required = true)
protected Diagnosi diagnosi;
protected String giornataLavorata;
protected String trauma;
protected String agevolazioni;
/**
* Recupera il valore della proprietà ruoloMedico.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRuoloMedico() {
return ruoloMedico;
}
/**
* Imposta il valore della proprietà ruoloMedico.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRuoloMedico(String value) {
this.ruoloMedico = value;
}
/**
* Recupera il valore della proprietà dataRilascio.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDataRilascio() {
return dataRilascio;
}
/**
* Imposta il valore della proprietà dataRilascio.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDataRilascio(String value) {
this.dataRilascio = value;
}
/**
* Recupera il valore della proprietà dataInizio.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDataInizio() {
return dataInizio;
}
/**
* Imposta il valore della proprietà dataInizio.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDataInizio(String value) {
this.dataInizio = value;
}
/**
* Recupera il valore della proprietà dataFine.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDataFine() {
return dataFine;
}
/**
* Imposta il valore della proprietà dataFine.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDataFine(String value) {
this.dataFine = value;
}
/**
* Recupera il valore della proprietà visita.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVisita() {
return visita;
}
/**
* Imposta il valore della proprietà visita.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVisita(String value) {
this.visita = value;
}
/**
* Recupera il valore della proprietà tipoCertificato.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTipoCertificato() {
return tipoCertificato;
}
/**
* Imposta il valore della proprietà tipoCertificato.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTipoCertificato(String value) {
this.tipoCertificato = value;
}
/**
* Recupera il valore della proprietà diagnosi.
*
* @return
* possible object is
* {@link Diagnosi }
*
*/
public Diagnosi getDiagnosi() {
return diagnosi;
}
/**
* Imposta il valore della proprietà diagnosi.
*
* @param value
* allowed object is
* {@link Diagnosi }
*
*/
public void setDiagnosi(Diagnosi value) {
this.diagnosi = value;
}
/**
* Recupera il valore della proprietà giornataLavorata.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGiornataLavorata() {
return giornataLavorata;
}
/**
* Imposta il valore della proprietà giornataLavorata.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGiornataLavorata(String value) {
this.giornataLavorata = value;
}
/**
* Recupera il valore della proprietà trauma.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTrauma() {
return trauma;
}
/**
* Imposta il valore della proprietà trauma.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTrauma(String value) {
this.trauma = value;
}
/**
* Recupera il valore della proprietà agevolazioni.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAgevolazioni() {
return agevolazioni;
}
/**
* Imposta il valore della proprietà agevolazioni.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAgevolazioni(String value) {
this.agevolazioni = value;
}
}
|
package com.example.ocenika.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.example.ocenika.R;
import com.example.ocenika.model.Comment;
import com.example.ocenika.util.StringUtils;
import java.util.List;
public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CommentViewHolder> {
public List<Comment> commentList;
public CommentAdapter(@Nullable List<Comment> commentList) {
this.commentList = commentList;
}
@NonNull
@Override
public CommentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.comment_item, parent, false);
return new CommentViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CommentViewHolder holder, int position) {
final Comment comment = commentList.get(position);
holder.dateView.setText(StringUtils.dateFormatted(comment.getCreated_at()));
if (comment.getReview() != null && !comment.getReview().isEmpty()) {
holder.textView.setText(comment.getReview());
}
}
@Override
public int getItemCount() {
return commentList.size();
}
public class CommentViewHolder extends RecyclerView.ViewHolder {
TextView textView;
TextView dateView;
public CommentViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.comment_item_text);
dateView = itemView.findViewById(R.id.comment_item_date);
}
}
}
|
package leecode.Array;
import java.util.ArrayList;
import java.util.List;
public class 寻找旋转排序树组的最小值_153 {
public static int findMin(int[] nums) {
int start=0;
int end=nums.length-1;
while (start<=end){
if(nums[start]<=nums[end]){//数组没有旋转
return nums[start];
}
int mid=(start+end)/2;
if(nums[start]<=nums[mid]){//[start,mid]连续递增,则最小值在[mid+1,end]
start=mid+1;
}else {
end=mid;//不是mid-1 nums[start]>nums[mid] 最小值在[start,mid]
}
}
return -1;
}
//liweiwei 二分 在数组中查找符合条件的元素的下标
public int findMin2(int[] nums) {
int left=0;
int right=nums.length-1;
while (left<right){
int mid=(left+right)>>>2;//>>>1 不是 >>>2 !!!
//找统一的判断方法,需要自己推论
//https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/solution/er-fen-fa-fen-zhi-fa-python-dai-ma-java-dai-ma-by-/
//统一规律
/*
1 2 3 4 5
列出如下情况:移动1的开始位置
1 2 3 4 5
5 1 2 3 4
4 5 1 2 3
3 4 5 1 2
2 3 4 5 1
中间>左边 min可能在左边或者右边
中间<左边 [left,mid]
中间>右边 [mid+1,right] //中间数左边的数(包括中间数)都不是「旋转排序数组」的最小值
中间<右边 [left,mid] //中间数到右边界是递增的,所以中间的右边一定不是
所以对于两个if分支,选择中间位置和右边比较,这样的话,两个分支可以把数组分为[left,mid]和[mid+1,right]两个区间
如果选择中间位置和左边比较,因为 中间>左边 min可能在左边或者右边 所以不能分成两个区间
*/
if(nums[mid]<=nums[right]){
//[mid,right]局部有序
right=mid;
}else {
left=mid+1;
}
}
return nums[left];
}
public static void main(String[] args) {
int[]arr={4,5,6,7,1,2,3};
List<Integer>list=new ArrayList<>();
list.add(1);
list.add(1);
list.remove(1);
int[]num=new int[list.size()];
// list.contains()
for(int i:list){
System.out.println(i);
}
// System.out.println(findMin(arr));
}
}
|
package springbook.user.service;
import java.util.List;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import springbook.user.domain.User;
public class UserServiceTx implements UserService {
UserService userService;
PlatformTransactionManager transactionManager;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Override
public void add(User user) {
userService.add(user);
}
/**
* Wrap the try-catch statment for the transaction
*/
@Override
public void upgradeLevels() {
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try{
userService.upgradeLevels();
transactionManager.commit(status);
}catch(RuntimeException e){
System.out.println("Called rollback!!!");
transactionManager.rollback(status);
throw e;
}
}
@Override
public User get(String id) {
return userService.get(id);
}
@Override
public List<User> getAll() {
return userService.getAll();
}
@Override
public void deleteAll() {
userService.deleteAll();
}
@Override
public void delete(String id) {
userService.delete(id);
}
@Override
public void update(User user) {
userService.update(user);
}
}
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Muzyk
*/
public class FlightService {
private Scanner reader;
private ArrayList<Plane> planes;
private ArrayList<Flight> flights;
public FlightService(Scanner reader, ArrayList<Plane> planes, ArrayList<Flight> flights) {
this.reader = reader;
this.planes = planes;
this.flights = flights;
}
public void start() {
System.out.println("Flight service");
System.out.println("----------------------\n");
while (true) {
commands();
String input = reader.nextLine();
if (input.equals("x")) {
break;
}
handleStatement(input);
System.out.println("");
}
}
public void commands() {
System.out.println("Chooce operation:");
System.out.println("[1] Print planes");
System.out.println("[2] Print flights");
System.out.println("[3] Print plane info");
System.out.println("[x] Quit");
}
public void handleStatement(String statement) {
if (statement.equals("1")) {
printPlanes();
} else if (statement.equals("2")) {
printFlights();
} else if (statement.equals("3")) {
printPlane();
} else {
System.out.println("Unknown command.");
}
}
public void printPlanes() {
for (Plane p : planes) {
System.out.println(p);
}
}
public void printPlane() {
System.out.print("Give plane ID: ");
String name = reader.nextLine();
for (Plane p : planes) {
if (p.getID().equals(name)) {
System.out.println(p);
}
}
}
public void printFlights() {
for (Flight f : flights) {
for (Plane p : planes) {
if (p.getID().equals(f.getID())) {
System.out.print(p);
System.out.print(" ");
System.out.println(f);
}
}
}
}
}
|
package cn.wycclub.service;
import cn.wycclub.dto.CartBean;
import cn.wycclub.dto.CartInfo;
import java.util.List;
/**
* 购物车业务逻辑层接口
*
* @author WuYuchen
* @create 2018-02-14 23:59
**/
public interface BusinessCartService {
boolean insertCart(CartInfo cartInfo) throws Exception;
boolean deleteCart(Integer cid) throws Exception;
CartBean updateCart(CartInfo cartInfo) throws Exception;
List<CartBean> selectCart(Integer uid) throws Exception;
}
|
public class Task {
private int id;
private static int i =1;
private TaskType taskType;
private TaskStatus taskStatus;
private User user;
public void setTaskStatus(TaskStatus taskStatus,User user) {
if(this.user.getId()== user.getId())
this.taskStatus = taskStatus;
else
System.out.println("You cannot chnage the statius of task not created by you");
}
public Task(TaskType taskType,User user) {
super();
this.id = getUniqueId();
this.taskType = taskType;
this.taskStatus = TaskStatus.OPEN;
this.user = user;
}
private static int getUniqueId() {
return i++;
}
@Override
public String toString() {
return "Task [id=" + id + ", taskType=" + taskType + ", taskStatus=" + taskStatus + ", user=" + user.getId()
+ "]";
}
}
|
package com.fitpolo.support.entity.req;
/**
* @Date 2017/5/14 0014
* @Author wenzheng.liu
* @Description 久坐提醒
* @ClassPath com.fitpolo.support.entity.req.SitLongTimeAlert
*/
public class SitLongTimeAlert {
public int alertSwitch; // 久坐提醒开关,1:开;0:关;
public String startTime;// 开始时间,格式:HH:mm;
public String endTime;// 结束时间,格式:HH:mm;
@Override
public String toString() {
return "SitLongTimeAlert{" +
"alertSwitch=" + alertSwitch +
", startTime='" + startTime + '\'' +
", endTime='" + endTime + '\'' +
'}';
}
}
|
/**
*
*/
package game.menubar;
import game.help.HelpWindow;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
/**
* @author Jan
*
*/
public class OpenHelpAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 1L;
public OpenHelpAction(String text, ImageIcon icon) {
super(text, icon);
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent pArg0) {
// TODO HilfeSeite aufrufen
HelpWindow.getInstance();
}
}
|
package khmil;
public class BinarySearch {
public static void modifiedBinarySearch(int key, int[] arr) {
int first = 0;
int last = arr.length - 1;
int target = -1;
while (first <= last) {
int mid = (last + first) / 2;
if (arr[mid] == key) {
target = mid;
}
if (arr[mid] <= arr[last]) {
if (key > arr[mid] && key <= arr[last] && key == arr[first]) {
last = mid - 1;
} else if (key > arr[mid] && key <= arr[last]) {
first = mid + 1;
} else {
last = mid - 1;
}
} else {
if (arr[first] <= key && key <= arr[mid]) {
last = mid - 1;
} else {
first = mid + 1;
}
}
}
System.out.println("Index of required element: " + target);
}
public static void main(String[] args) {
int arr[] = {5, 6, 9, 10, 15, 1, 3, 4};
int array[] = {5, 5, 1, 3, 4, 5, 5, 5, 5};
int key =3;
modifiedBinarySearch(key, array);
}
}
|
package cs3500.animator.model.featurestate;
import cs3500.animator.view.DrawingStrategy;
import java.awt.Color;
/**
* This abstract class AbstractFeatureState implements all operations specified by the FeatureState
* interface. An instance of this class represents the instantaneous state of a shape at a given
* tick in an animation. This class represents the state with its position, x dimension, y
* dimension, color, drawing strategy, and the motion number. The drawing strategy provides the
* visual view with how to draw this shape. And thee motion number corresponds to the motion this
* state is associated with.
*/
public abstract class AbstractFeatureState implements FeatureState {
protected DrawingStrategy howToDraw;
private Posn location;
private double xDimension;
private double yDimension;
private Color color;
private int motionNumber;
protected AbstractFeatureState(Posn loc, double xDimension, double yDimension, Color c) {
if (xDimension <= 0 || yDimension <= 0) {
throw new IllegalArgumentException("Dimensions must positive");
}
this.location = loc;
this.xDimension = xDimension;
this.yDimension = yDimension;
this.color = c;
}
protected AbstractFeatureState(double xPos, double yPos, double xDim, double yDim, int r, int g,
int b) {
if (xDim <= 0 || yDim <= 0) {
throw new IllegalArgumentException("Dimensions must positive");
}
this.xDimension = xDim;
this.yDimension = yDim;
try {
this.location = new Posn(xPos, yPos);
this.color = new Color(r, g, b);
} catch (IllegalArgumentException iae) {
throw new IllegalArgumentException("Cannot construct this FeatureState:" + iae.getMessage());
}
}
@Override
public Posn getLocation() {
return new Posn(this.location);
}
@Override
public Color getColor() {
return new Color(this.color.getRGB());
}
@Override
public double getXDimension() {
return this.xDimension;
}
@Override
public double getYDimension() {
return this.yDimension;
}
@Override
public int hashCode() {
return (int) (this.getColor().getRGB() * this.getLocation().getX() * this.getLocation().getY()
* this.getXDimension() * this.getYDimension());
}
@Override
public abstract boolean equals(Object obj);
@Override
public DrawingStrategy getDrawingStrategy() {
return this.howToDraw;
}
@Override
public void setMotionNumber(int motionNumber) {
this.motionNumber = motionNumber;
}
@Override
public int getMotionNumber() {
return this.motionNumber;
}
}
|
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Player implements Runnable {
// Methode die den Player bewegt
private int highscore;
static int xkoordinate, ykoordinate, max_xkoordinate, max_ykoordinate;
// private byte herzen;
// public int level, aktuelles_level;
Spielplan plan;
// private char alteposition;
Lazers laser;
Coin c;
static boolean sleep = false;
public static void setSleep(boolean sleepy) {
sleep = sleepy;
}
public void run() {
while (true) {
try {
if (sleep) {
try {
Thread.sleep(2000l);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
sleep = false;
}
Spielplan plan = new Spielplan();
move();
if (c.letzterCoin[0] == xkoordinate && c.letzterCoin[1] == ykoordinate) {
c.deleteCoin();
c.generateCoin();
Game.HIGHSCORE += 5000;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public Player(Spielplan Plan, Lazers laser, Coin coin) {
// highscore = HIGHSCORE;
// herzen = (byte) LEBEN;
// level = SCHWIERIGKEIT;
this.laser = laser;
plan = Plan;
c = coin;
max_xkoordinate = 12;
max_ykoordinate = 12;
xkoordinate = (int) (Math.random() * max_xkoordinate);
ykoordinate = (int) (Math.random() * max_ykoordinate);
}
public static int getX() {
return xkoordinate;
}
public static int getY() {
return ykoordinate;
}
public synchronized void move() throws IOException {
String name = "";
long endTime = System.currentTimeMillis() + 5000l;
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Reading data using readLine
if (reader.ready()) {
name = reader.readLine();
if (!name.equals("")) {
char eingabe = name.charAt(0);
switch (eingabe) {
case 'w' -> {
ykoordinate--;
if (außerhalb_des_feldes()) {
ykoordinate++;
} else {
plan.printIndicator();
}
}
case 'a' -> {
xkoordinate--;
if (außerhalb_des_feldes()) {
xkoordinate++;
} else {
plan.printIndicator();
}
}
case 'd' -> {
xkoordinate++;
if (außerhalb_des_feldes()) {
xkoordinate--;
} else {
plan.printIndicator();
}
}
case 's' -> {
ykoordinate++;
if (außerhalb_des_feldes()) {
ykoordinate--;
} else {
plan.printIndicator();
}
}
}
}
}
// Printing the read line
}
private boolean außerhalb_des_feldes() {
if (ykoordinate < 0 || ykoordinate >= max_ykoordinate || xkoordinate < 0 || xkoordinate >= max_xkoordinate) {
return true;
}
return false;
}
// public int getHerzen() {
// return herzen;
//}
//
////public char[][] setPlayer(char[][] spielfeld) throws IOException {
//
// {
// spielfeld[xkoordinate][ykoordinate] = alteposition;
// alteposition = spielfeld[xkoordinate][ykoordinate];
// spielfeld[xkoordinate][ykoordinate] = 'P';
// }
//
//}
// public void setHerzen(byte herzen) {
// this.herzen = herzen;
//}
// public boolean treffer() {
// // Gibt zurück ob er tot ist, wobei false = tot und true = lebend
// if (herzen == 1) {
// return false;
// }
// --herzen;
// return true;
// }
// Methode die Input abfragt
// private char input() {
//
// /*
// * // Enter data using BufferReader BufferedReader reader = new
// * BufferedReader(new InputStreamReader(System.in));
// *
// * // Reading data using readLine String name = reader.readLine();
// *
// * return name;
// */
//
// return 'g';
// }
// private boolean gewonnen() {
// if (level == aktuelles_level && herzen > 0) {
// return true;
// }
// return false;
// }
//
// public boolean nichtzuende() {
// if (aktuelles_level <= level && herzen > 0) {
// return true;
// }
// return false;
// }
}
|
package beanfactory;
import annotation.Autowire;
import annotation.Component;
import reader.BeanDefinitionReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/***
*
*@Author ChenjunWang
*@Description:
*@Date: Created in 13:43 2020/3/1
*@Modified By:
*
*/
public class DefaultBeanFactory implements BeanFactory {
private BeanDefinitionReader bdr;
private String[] configLocations = {"application.properties"};
Map<String, Object> beanMap = new ConcurrentHashMap();
private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap();
private final List<BeanPostProcessor> beanPostProcessors = new LinkedList<>();
String baseDir = "com/sio/demo";
public DefaultBeanFactory() {
//加载指定包下面的所有类
bdr = new BeanDefinitionReader(configLocations);
//将类注册成beanDefinition
registryBeanDefinitions(bdr.getRegistryBeanClasses());
//初始化postProcessor
PostProcessorRegistrationDelegate.registerBeanPostProcessors(this);
//初始化所有的类
initBeans();
//
//
// //获得要扫描类的文件目录
// URL systemResource = ClassLoader.getSystemResource(baseDir);
// File file = new File(systemResource.getPath());
// String[] list = file.list();
// //在目录下找到需要给框架容器托管的bean,并加入到容器
// for (String f : list) {
//
// String base = baseDir.replace("/", ".");
// String clazzPath = base + "." +f.replace(".class", "");
// try {
// Class<?> clazz = Class.forName(clazzPath);
//
// if (clazz.isAnnotationPresent(Component.class)) {
// Component component = clazz.getAnnotation(Component.class);
// String name = component.value();
// if (name.equals("")) {
// name = clazz.getSimpleName();
// }
// beanMap.put(lowerFirstCase(name), clazz.newInstance());
//
// }
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (InstantiationException e) {
// e.printStackTrace();
// }
// }
}
private void initBeans() {
for (Map.Entry<String, BeanDefinition> beanDefinitionEntry : beanDefinitionMap.entrySet()) {
String beanName = beanDefinitionEntry.getKey();
Object instant = beanMap.get(beanName);
if (instant != null) {
continue;
}
//实例化
doGetBean(beanName, null);
//初始化
populateBean(beanName, beanDefinitionEntry.getValue());
}
}
private void populateBean(String beanName, BeanDefinition bd) {
String beanClassName = bd.getBeanClassName();
Object instance = beanMap.get(beanName);
for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessAfterInstantiation(instance, beanClassName);
}
}
Object wrappedBean = instance;
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanClassName);
Field[] fields = instance.getClass().getDeclaredFields();
for (Field field : fields) {
boolean present = field.isAnnotationPresent(Autowire.class);
if (present) {
Autowire autowire = field.getAnnotation(Autowire.class);
//要注入的类型
Class<?> clazz = field.getType();
String name = clazz.getName();
Object o = beanMap.get(name);
try {
field.setAccessible(true);
field.set(instance, o);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanClassName);
beanMap.put(beanName,wrappedBean);
}
private Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) {
Object result = existingBean;
for (BeanPostProcessor processor : beanPostProcessors) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
private Object doGetBean(String beanName, Class<?> requiredType) {
Object o = beanMap.get(beanName);
if (o != null) {
if (requiredType == null) {
return o;
}
if (requiredType.isInstance(o)) {//对象能不能转化成这个类
return o;
}
return null;
}
BeanDefinition value = beanDefinitionMap.get(beanName);
String beanClassName = value.getBeanClassName();
try {
Class<?> clazz = Class.forName(beanClassName);
Object instance = beanMap.get(beanClassName);
Object bean = resolveBeforeInstantiation(beanClassName, value);
if (bean != null) {
beanMap.put(beanName, instance);
return bean;
}
if (instance == null) {
instance = clazz.newInstance();
}
beanMap.put(beanName, instance);
return instance;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
private Object resolveBeforeInstantiation(String beanName, BeanDefinition beanDefinition) throws ClassNotFoundException {
Object bean = null;
String beanClassName = beanDefinition.getBeanClassName();
Class<?> targetType = Class.forName(beanClassName);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
return bean;
}
private Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) {
Object result = existingBean;
for (BeanPostProcessor processor : beanPostProcessors) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
private Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (BeanPostProcessor bp : beanPostProcessors) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
public Object getBean(String beanName) {
Object instant = doGetBean(beanName, null);
return instant;
}
@Override
public <T> T getBean(Class<T> requiredType) {
return null;
}
@Override
public List<String> getBeanNamesForType(Class<?> type) {
List<String> result = new ArrayList<>();
for (String beanDefinitionName : beanDefinitionNames) {
if (isTypeMatch(beanDefinitionName, type)) {
result.add(beanDefinitionName);
}
}
return result;
}
@Override
public void addBeanPostProcessor(BeanPostProcessor postProcessor) {
//先删除重复的
beanPostProcessors.remove(postProcessor);
//添加后置处理器
beanPostProcessors.add(postProcessor);
}
@Override
public Object getBean(String beanName, Class<?> requiredType) {
doGetBean(beanName, requiredType);
Object o = beanMap.get(beanName);
if (requiredType != null && requiredType.isInstance(o)) {
return o;
}
return null;
}
private boolean isTypeMatch(String beanDefinitionName, Class<?> type) {
// Object beanInstance = getBean(beanDefinitionName);
boolean assignableFrom = false;
try {
Class<?> clazz = Class.forName(beanDefinitionName);
assignableFrom = type.isAssignableFrom(clazz);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (assignableFrom) {
return true;
}
return false;
}
private void registryBeanDefinitions(List<String> registryBeanClasses) {
registryBeanClasses.forEach(beanClass -> {
try {
Class<?> clazz = Class.forName(beanClass);
if (clazz.isAnnotationPresent(Component.class)) {
Component component = clazz.getAnnotation(Component.class);
String name = component.value();
if (name == null || name.equals("")) {
name = clazz.getName();
}
BeanDefinition beanDefinition = new BeanDefinition();
beanDefinition.setBeanClassName(beanClass);
beanDefinition.setFactoryBeanName(lowerFirstCase(clazz.getSimpleName()));
beanDefinition.setLazyInit(false);
beanDefinition.setScope(BeanFactory.SCOPE_SINGLETON);
beanDefinitionMap.put(name, beanDefinition);
beanDefinitionNames.add(name);
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> i : interfaces) {
String fullName = i.getName();
beanDefinitionMap.put(fullName, beanDefinition);
beanDefinitionNames.add(fullName);
}
} else {
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
});
}
private String lowerFirstCase(String str) {
char[] chars = str.toCharArray();
chars[0] += 32;
return String.valueOf(chars);
}
}
|
package Selinium;
public class Q5Arrylist {
public static void main(String[] args) {
int a[] = {12,1,32,3};
int b[] = {0,12,2,23};
int c []=new int[a.length+b.length];
int location =0;
for(int i=1;i<a.length;i=i+2) {
c[i]=a[i];
location++;
}
for(int i=0; i<b.length;i=i+2) {
c[i]=b[i];
location++;
}
for(int i=0; i<location;i++) {
System.out.println(c[i]);
}
}
}
|
package com.tencent.mm.ui;
import com.tencent.mm.ui.ae.d;
public class ae$c {
int bGz = 0;
boolean tpO = false;
boolean tpP = false;
d tpQ;
public ae$c(d dVar) {
this.tpQ = dVar;
}
}
|
//package falconrobotics.scoutingprogram;
//
//import android.bluetooth.BluetoothAdapter;
//import android.bluetooth.BluetoothServerSocket;
//import android.bluetooth.BluetoothSocket;
//import android.content.Intent;
//import android.util.Log;
//
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.util.ArrayList;
//import falconrobotics.scoutingprogram.SyncPitData.*;
//
//public class Server extends Thread {
//
//
// /*package-protected*/
// static final String ACTION = "Bluetooth socket is connected";
// private static final String TAG2 = "MessageListener thread";
// private final String TAG = "Server";
// private BluetoothAdapter btAdapter;
// private String socketString = "a random string";
// private BluetoothServerSocket btServerSocket;
// private BluetoothSocket btConnectedSocket;
// private boolean connected;
// private InputStream inStream;
// private OutputStream outStream;
//
// public Server()
// {
// connected = false;
// }
//
// @Override
// public void run() {
// btAdapter = BluetoothAdapter.getDefaultAdapter();
//
// try {
// Log.i(TAG, "getting socket from adapter");
// btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord(socketString, MainActivity.BT_UUID);
// listen();
//
// } catch (IOException ex) {
// Log.e(TAG, "error while initializing");
//
//
// }
//
// }
//
// private void listen() {
// Log.i(TAG, "listening");
// btConnectedSocket = null;
// while (!connected) {
// try {
// btConnectedSocket = btServerSocket.accept();
// inStream = btConnectedSocket.getInputStream();
// outStream = btConnectedSocket.getOutputStream();
//
// Log.v(TAG, "connected and listening");
//
// byte[] buffer = new byte[1024];
// int bytes;
// Log.d(TAG2,"About to send msg");
//
//
// while (true) {
// try {
// bytes = inStream.read(buffer);
//
//
//
// } catch (IOException ex) {
// Log.e(TAG, "error while reading from bt socket");
//
// }
//
//
// SyncPitData.updatePitRecord("2016", "SCMBSrv1", new String(buffer));
// Log.d(TAG2,"Message Sent");
//
//
//
//
//
//// parent.doStuffWithTheMessage(buffer); // pay attention: its in bytes. u need to convert it to a string
//
// }
// } catch (IOException ex) {
// Log.e(TAG, "connection failed");
// connectionFailed();
//
// }
// if (btConnectedSocket != null) {
// broadcast();
// closeServerSocket();
// } else {
// Log.i(TAG, "socket is null");
// connectionFailed();
// }
// }
//
// }
//
// private void broadcast() {
// try {
//
// Intent intent = new Intent();
// intent.setAction(ACTION);
//// parent.sendBroadcast(intent);
// connected = true;
// } catch (RuntimeException runTimeEx) {
// Log.e("RunTimeException",runTimeEx.toString());
//
// }
//
// closeServerSocket();
// }
//
//
// private void connectionFailed() {
//
// }
//
// public void closeServerSocket() {
// try {
// btServerSocket.close();
// } catch (IOException ex) {
// Log.e(TAG + ":cancel", "error while closing server socket");
// }
// }
//}
|
package org.sqlflow.parser;
import java.util.ArrayList;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.parser.SqlParseException;
import org.apache.calcite.sql.parser.SqlParser;
public class CalciteParserAdaptor {
public CalciteParserAdaptor() {}
// ParseAndSplit calls Calcite parser to parse a SQL program and returns a ParseResult.
//
// It returns <statements, -1, ""> if Calcite parser accepts the SQL program.
// input: "select 1; select 1;"
// output: {"select 1;", "select 1;"}, -1 , nil
// It returns <statements, idx, ""> if Calcite parser accepts part of the SQL program, indicated
// by idx.
// input: "select 1; select 1 to train; select 1"
// output: {"select 1;", "select 1"}, 19, nil
// It returns <nil, -1, error> if an error is occurred.
public ParseResult ParseAndSplit(String sql) {
ParseResult parse_result = new ParseResult();
parse_result.Statements = new ArrayList<String>();
parse_result.Position = -1;
parse_result.Error = "";
int accumulated_position = 0;
while (true) {
try {
SqlParser parser = SqlParser.create(sql);
SqlNode sqlnode = parser.parseQuery();
parse_result.Statements.add(sql);
return parse_result;
} catch (SqlParseException e) {
int line = e.getPos().getLineNum();
int column = e.getPos().getColumnNum();
int epos = posToIndex(sql, line, column);
try {
SqlParser parser = SqlParser.create(sql.substring(0, epos));
SqlNode sqlnode = parser.parseQuery();
// parseQuery doesn't throw exception
parse_result.Statements.add(sql.substring(0, epos));
// multiple SQL statements
if (sql.charAt(epos) == ';') {
sql = sql.substring(epos + 1);
accumulated_position += epos + 1;
// FIXME(tony): trim is not enough to handle statements
// like "select 1; select 1; -- this is a comment"
// So maybe we need some preprocessors to remove all the comments first.
if (sql.trim().equals("")) {
return parse_result;
}
continue;
}
// Make sure the left hand side is a select statement, so that
// we can try parse the right hand side with the SQLFlow parser
if (sqlnode.getKind() != SqlKind.SELECT) {
// return original error
parse_result.Statements = new ArrayList<String>();
parse_result.Position = -1;
parse_result.Error = e.getCause().getMessage();
return parse_result;
}
parse_result.Position = accumulated_position + epos;
return parse_result;
} catch (SqlParseException ee) {
// return original error
parse_result.Statements = new ArrayList<String>();
parse_result.Position = -1;
parse_result.Error = e.getCause().getMessage();
return parse_result;
}
}
}
}
// posToIndex converts line and column number into string index.
private static int posToIndex(String query, int line, int column) {
int l = 0, c = 0;
for (int i = 0; i < query.length(); i++) {
if (l == line - 1 && c == column - 1) {
return i;
}
if (query.charAt(i) == '\n') {
l++;
c = 0;
} else {
c++;
}
}
return query.length();
}
}
|
package com.claycorp.nexstore.api.entity;
public class ShipmentItems {
private String shipmentId;
private OrderItem orderItem;
public ShipmentItems() {
}
public String getShipmentId() {
return shipmentId;
}
public ShipmentItems setShipmentId(String shipmentId) {
this.shipmentId = shipmentId;
return this;
}
public OrderItem getOrderItem() {
return orderItem;
}
public ShipmentItems setOrderItem(OrderItem orderItem) {
this.orderItem = orderItem;
return this;
}
@Override
public String toString() {
return "ShipmentItems [shipmentId=" + shipmentId + ", orderItem=" + orderItem + "]";
}
}
|
/*
Мастям игральных карт присвоены порядковые номера: 1 — пики, 2 — трефы, 3 — бубны, 4 — червы. Достоинству карт, старших десятки, присвоены номера: 11 — валет, 12 — дама, 13 — король, 14 — туз. Даны два целых числа: N — достоинство (6 ≤ N ≤ 14) и M — масть карты (1 ≤ M ≤ 4). Вывести название соответствующей карты вида «шестерка бубен», «дама червей», «туз треф» и т. п.
*/
public class Ex_25_func {
public static String weight(int N){
String[] weightArr = {"Six ", "Seven ", "Eight ", "Nine ", "Ten ", "Jack ", "Queen ", "King ", "Ace "};
return weightArr[N-6];
}
public static String mark(int M){
String[] markArr = {"Spade", "Club", "Dimond", "Heart"};
return markArr[M-1];
}
public static boolean cond(int N, int M){
boolean cond = false;
if (N < 6 || N > 14) {
System.err.println("Entered digit doesn't satisfy condition. First one should be positive value in array from 6 to 14!");
cond = true;
}
if (M < 1 || M > 4) {
System.err.println("Entered digit doesn't satisfy condition. Second one should be positive value in array from 1 to 4!");
cond = true;
}
return cond;
}
public static boolean generalCond(String[] args, int conditionLength){
boolean cond = false;
if (args.length < conditionLength) {
System.err.println("You haven't entered arguments! The task requires entering two arguments.");
cond = true;
}
if (args.length > conditionLength) System.out.println("You entered more arguments, than programm needs. \nIt will use only first two.");
return cond;
}
public static void main(String[] args){
if(generalCond(args,2)) return;
Integer N = Integer.parseInt(args[0]);
Integer M = Integer.parseInt(args[1]);
if (cond(N,M)) return;
System.out.println(weight(N) + "" + mark(M));
}
}
|
package com.vilio.wct.glob;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.vilio.wct.pojo.SqlConfig;
import com.vilio.wct.util.PropertiesManager;
/**
* 类名: InitClobDispatcher<br>
* 功能:初始化全局变量<br>
* 版本: 1.0<br>
* 日期: 2017年6月7日<br>
* 作者: wangxf<br>
* 版权:vilio<br>
* 说明:<br>
*/
public class InitClobDispatcher extends HttpServlet {
private static final long serialVersionUID = -5716647045215874374L;
protected static Logger logger = Logger.getLogger(InitClobDispatcher.class);
public final void init(ServletConfig config) throws ServletException {
// 循环读取sql文件夹下的所有xml文件
String basePach = InitClobDispatcher.class.getClassLoader().getResource("").getPath();
load(basePach + File.separator + "conf" + File.separator + "sql");
// 加载错误码信息
loadErrorCode(basePach + File.separator + "conf" + File.separator + "error-code.properties");
}
/**
* 加载错误码信息到缓存
*/
private void loadErrorCode(String filePath) {
logger.info("开始加载错误码");
Properties propTmp = PropertiesManager.getProperties(filePath);
Iterator it = propTmp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
GlobParam.ERROR_CODE.put(key.toString(), value);
}
logger.info("加载错误码完成");
}
/**
* 加载当前文件夹下的所有xml结尾文件
*
* @param file
*/
private void load(File file) {
if (!file.isDirectory()) {
if (file.getName().endsWith(".xml")) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document doc = null;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(file);
} catch (ParserConfigurationException e) {
e.printStackTrace();
logger.error("加载配置文件失败:" + e.getMessage());
} catch (SAXException e) {
e.printStackTrace();
logger.error("加载配置文件失败:" + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
logger.error("加载配置文件失败:" + e.getMessage());
}
NodeList nl = doc.getElementsByTagName("sqlinfo");
for (int i = 0; i < nl.getLength(); i++) {
String sqlid = doc.getElementsByTagName("sqlid").item(i).getFirstChild().getNodeValue();
String sqlname = doc.getElementsByTagName("sqlname").item(i).getFirstChild().getNodeValue();
String sql = doc.getElementsByTagName("sql").item(i).getFirstChild().getNodeValue();
SqlConfig sc = new SqlConfig(sqlid, sqlname, sql);
GlobParam.sqlConfig.put(sqlid, sc);
}
logger.info("加载配置文件:" + file.getName());
}
} else {
File fa[] = file.listFiles();
for (File file2 : fa) {
load(file2);
}
}
}
/**
* 加载当前文件夹下的所有xml结尾文件
*
* @param filePath
*/
private void load(String filePath) {
File file = new File(filePath);
load(file);
}
}
|
package edu.illinois.finalproject;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import edu.illinois.finalproject.PlayerGuides.PlayerGuides;
import edu.illinois.finalproject.PlayerProfile.PlayerProfile;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LolConstants.getData();
// seeting up the redirect buttons
Button guides = findViewById(R.id.Guides_button);
Button profiles = findViewById(R.id.Player_Profiles_button);
// Button champstats = findViewById(R.id.Champion_statistics_button);
guides.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Context context = view.getContext();
Intent guideIntent = new Intent(context, PlayerGuides.class);
context.startActivity(guideIntent);
}
});
profiles.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Context context = view.getContext();
Intent profilesIntent = new Intent(context, PlayerProfile.class);
context.startActivity(profilesIntent);
}
});
// champstats.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// final Context context = view.getContext();
// Intent champstatsIntent = new Intent(context, ChampionStatistics.class);
// context.startActivity(champstatsIntent);
// }
// });
}
}
|
/* */ package datechooser.autorun;
/* */
/* */ import datechooser.beans.DateChooserBean;
/* */ import datechooser.beans.locale.LocaleUtils;
/* */ import datechooser.events.SelectionChangedEvent;
/* */ import java.awt.Dimension;
/* */ import java.awt.Toolkit;
/* */ import java.awt.event.ActionEvent;
/* */ import java.awt.event.ActionListener;
/* */ import java.io.File;
/* */ import javax.swing.ButtonGroup;
/* */ import javax.swing.ImageIcon;
/* */ import javax.swing.JCheckBoxMenuItem;
/* */ import javax.swing.JFileChooser;
/* */ import javax.swing.JFrame;
/* */ import javax.swing.JLabel;
/* */ import javax.swing.JMenu;
/* */ import javax.swing.JMenuBar;
/* */ import javax.swing.JMenuItem;
/* */ import javax.swing.JOptionPane;
/* */ import javax.swing.JPanel;
/* */ import javax.swing.JTextArea;
/* */ import javax.swing.LookAndFeel;
/* */ import javax.swing.SwingUtilities;
/* */ import javax.swing.UIManager;
/* */ import javax.swing.UIManager.LookAndFeelInfo;
/* */
/* */ public class ConfigWindow extends JFrame implements datechooser.events.CommitListener, datechooser.events.SelectionChangedListener
/* */ {
/* */ private static final int WIDTH = 630;
/* */ private static final int HEIGHT = 380;
/* */ private static final String MENU_PROPERTY_ID = "MenuItemID";
/* */ private static final String MENU_LOAD = "load";
/* */ private static final String MENU_SAVE = "save";
/* */ private static final String MENU_SAVE_AS = "save as";
/* */ private JPanel mainPane;
/* */ private ConfigBean[] configurators;
/* */ private JLabel selectedBeanNameLabel;
/* */ private int selected;
/* */ private JTextArea output;
/* */ private ButtonGroup selLookFeel;
/* */ private String about;
/* */ private ImageIcon aboutImage;
/* */ private JFileChooser fileChooser;
/* */
/* */ public ConfigWindow() throws java.beans.IntrospectionException
/* */ {
/* 48 */ LocaleUtils.prepareStandartDialogButtonText();
/* 49 */ setDefaultCloseOperation(0);
/* 50 */ setTitle(LocaleUtils.getConfigLocaleString("Caption"));
/* 51 */ this.mainPane = new JPanel(new java.awt.BorderLayout(5, 2));
/* 52 */ this.configurators = new ConfigBean[] { new ConfigPanel(), new ConfigCombo(), new ConfigDialog() };
/* */
/* */
/* */
/* */
/* 57 */ this.selected = 0;
/* 58 */ setJMenuBar(createMenuBar());
/* 59 */ this.selectedBeanNameLabel = createBeanNameOutput();
/* 60 */ this.mainPane.add(this.selectedBeanNameLabel, "North");
/* 61 */ this.mainPane.add(getCurrentConfigBean(), "Center");
/* 62 */ this.output = createOutput();
/* 63 */ this.mainPane.add(this.output, "South");
/* */
/* 65 */ setContentPane(this.mainPane);
/* 66 */ updateOutput();
/* 67 */ setCentered();
/* 68 */ synchronized (getTreeLock()) {
/* 69 */ validateTree();
/* */ }
/* 71 */ registerAsListener();
/* 72 */ setAllSaved();
/* */
/* 74 */ this.fileChooser = new JFileChooser();
/* 75 */ this.fileChooser.setFileFilter(new ComponentFileFilter(null));
/* */
/* 77 */ addWindowListener(new OnWindowClose(null));
/* */ }
/* */
/* */ private void setAllSaved() {
/* 81 */ for (ConfigBean configBean : this.configurators) {
/* 82 */ configBean.setSaved(true);
/* */ }
/* */ }
/* */
/* */ private JLabel createBeanNameOutput() {
/* 87 */ JLabel selectedBean = new JLabel(getCurrentConfigBean().getBeanDisplayName());
/* 88 */ selectedBean.setHorizontalAlignment(0);
/* 89 */ selectedBean.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5));
/* 90 */ return selectedBean;
/* */ }
/* */
/* */ private JTextArea createOutput() {
/* 94 */ JTextArea output = new JTextArea("");
/* 95 */ output.setRows(2);
/* 96 */ output.setLineWrap(true);
/* 97 */ output.setWrapStyleWord(true);
/* 98 */ output.setOpaque(false);
/* 99 */ output.setEditable(false);
/* 100 */ return output;
/* */ }
/* */
/* */ private JMenuBar createMenuBar() {
/* 104 */ JMenuBar menuBar = new JMenuBar();
/* */
/* 106 */ menuBar.add(createMenuFile());
/* 107 */ menuBar.add(createMenuBean());
/* 108 */ menuBar.add(createMenuLF());
/* 109 */ menuBar.add(createMenuHelp());
/* */
/* 111 */ return menuBar;
/* */ }
/* */
/* */ private JFrame getFrame() {
/* 115 */ return this;
/* */ }
/* */
/* */ private JMenu createMenuHelp()
/* */ {
/* 120 */ JMenu menuHelp = new JMenu(LocaleUtils.getConfigLocaleString("Help"));
/* 121 */ JMenuItem menuAbout = new JMenuItem(LocaleUtils.getConfigLocaleString("About"));
/* */
/* 123 */ StringBuffer aboutString = new StringBuffer("<html>");
/* 124 */ aboutString.append(LocaleUtils.getConfigLocaleString("ProjectName"));
/* 125 */ aboutString.append("<br><br>(c) ");
/* 126 */ aboutString.append(LocaleUtils.getConfigLocaleString("Author"));
/* 127 */ aboutString.append(", 2014<br>");
/* 128 */ aboutString.append("e-mail: <i>androsovvi@gmail.com</i>");
/* 129 */ this.about = aboutString.toString();
/* */
/* 131 */ this.aboutImage = new ImageIcon(datechooser.beans.pic.Pictures.getResource("logo_small.gif"));
/* */
/* 133 */ menuAbout.addActionListener(new ActionListener() {
/* */ public void actionPerformed(ActionEvent e) {
/* 135 */ JOptionPane.showMessageDialog(ConfigWindow.this.getFrame(), ConfigWindow.this.about, LocaleUtils.getConfigLocaleString("About"), 1, ConfigWindow.this.aboutImage);
/* */
/* */ }
/* */
/* */
/* 140 */ });
/* 141 */ menuHelp.add(menuAbout);
/* 142 */ return menuHelp;
/* */ }
/* */
/* */ private JMenu createMenuLF() {
/* 146 */ JMenu menuLF = new JMenu(LocaleUtils.getConfigLocaleString("LookFeel"));
/* 147 */ UIManager.LookAndFeelInfo[] lf = UIManager.getInstalledLookAndFeels();
/* 148 */ this.selLookFeel = new ButtonGroup();
/* 149 */ LookAndFeel current = UIManager.getLookAndFeel();
/* 150 */ OnLookAndFeelChange onChange = new OnLookAndFeelChange(null);
/* 151 */ for (UIManager.LookAndFeelInfo lookAndFeel : lf) {
/* 152 */ String lfName = lookAndFeel.getName();
/* 153 */ JCheckBoxMenuItem miLF = new JCheckBoxMenuItem(lfName);
/* 154 */ miLF.putClientProperty("MenuItemID", lookAndFeel.getClassName());
/* 155 */ miLF.addActionListener(onChange);
/* 156 */ if ((current != null) && (current.getName().equals(lfName))) {
/* 157 */ miLF.setSelected(true);
/* */ }
/* 159 */ this.selLookFeel.add(miLF);
/* 160 */ menuLF.add(miLF);
/* */ }
/* 162 */ return menuLF;
/* */ }
/* */
/* */ private JMenu createMenuFile() {
/* 166 */ OnStoreAction onStore = new OnStoreAction(null);
/* 167 */ JMenu menuFile = new JMenu(LocaleUtils.getConfigLocaleString("File"));
/* 168 */ JMenuItem menuLoad = new JMenuItem(LocaleUtils.getConfigLocaleString("Load"));
/* 169 */ menuLoad.putClientProperty("MenuItemID", "load");
/* 170 */ menuLoad.addActionListener(onStore);
/* 171 */ menuFile.add(menuLoad);
/* 172 */ menuFile.addSeparator();
/* 173 */ JMenuItem menuSave = new JMenuItem(LocaleUtils.getConfigLocaleString("Save"));
/* 174 */ menuSave.putClientProperty("MenuItemID", "save");
/* 175 */ menuSave.addActionListener(onStore);
/* 176 */ menuFile.add(menuSave);
/* 177 */ JMenuItem menuSaveAs = new JMenuItem(LocaleUtils.getConfigLocaleString("SaveAs"));
/* 178 */ menuSaveAs.putClientProperty("MenuItemID", "save as");
/* 179 */ menuSaveAs.addActionListener(onStore);
/* 180 */ menuFile.add(menuSaveAs);
/* 181 */ menuFile.addSeparator();
/* 182 */ JMenuItem menuExit = new JMenuItem(LocaleUtils.getConfigLocaleString("Exit"));
/* 183 */ menuExit.addActionListener(new ActionListener() {
/* */ public void actionPerformed(ActionEvent e) {
/* 185 */ ConfigWindow.this.tryToExit();
/* */ }
/* 187 */ });
/* 188 */ menuFile.add(menuExit);
/* 189 */ return menuFile;
/* */ }
/* */
/* */ private void tryToExit() {
/* 193 */ String unsaved = getUnsaved();
/* 194 */ if (!getUnsaved().equals("")) {
/* 195 */ int ans = JOptionPane.showConfirmDialog(getFrame(), "<html> " + LocaleUtils.getConfigLocaleString("Exit_no_save") + " <br><UL>" + unsaved + "</UL>", LocaleUtils.getConfigLocaleString("Exit"), 0);
/* */
/* */
/* */
/* 199 */ if (ans == 1) return;
/* */ }
/* 201 */ System.exit(0);
/* */ }
/* */
/* */ private String getUnsaved() {
/* 205 */ StringBuffer unsaved = new StringBuffer("");
/* 206 */ for (ConfigBean configurator : this.configurators) {
/* 207 */ if (!configurator.isSaved()) {
/* 208 */ unsaved.append("<LI>");
/* 209 */ unsaved.append(configurator.getBeanDisplayName());
/* */ }
/* */ }
/* 212 */ return unsaved.toString();
/* */ }
/* */
/* */ private JMenu createMenuBean() {
/* 216 */ JMenu menuBean = new JMenu(LocaleUtils.getConfigLocaleString("Bean"));
/* 217 */ OnBeanChange onBeanChange = new OnBeanChange(null);
/* 218 */ ButtonGroup group = new ButtonGroup();
/* 219 */ for (int i = 0; i < this.configurators.length; i++) {
/* 220 */ String beanName = this.configurators[i].getBeanDisplayName();
/* 221 */ JCheckBoxMenuItem menuCurrentBean = new JCheckBoxMenuItem(beanName);
/* 222 */ menuCurrentBean.putClientProperty("MenuItemID", new Integer(i));
/* 223 */ menuCurrentBean.addActionListener(onBeanChange);
/* 224 */ menuCurrentBean.setSelected(getSelected() == i);
/* 225 */ group.add(menuCurrentBean);
/* 226 */ menuBean.add(menuCurrentBean);
/* */ }
/* 228 */ return menuBean;
/* */ }
/* */
/* */ private void registerAsListener() {
/* 232 */ for (ConfigBean beanConfigurator : this.configurators) {
/* 233 */ beanConfigurator.getBean().addCommitListener(this);
/* 234 */ beanConfigurator.getBean().addSelectionChangedListener(this);
/* */ }
/* */ }
/* */
/* */ private int getSelected() {
/* 239 */ return this.selected;
/* */ }
/* */
/* */ private void updateOutput() {
/* 243 */ this.output.setText(getCurrentConfigBean().getBean().getSelectedPeriodSet().toString());
/* */ }
/* */
/* */ private ConfigBean getCurrentConfigBean() {
/* 247 */ return this.configurators[getSelected()];
/* */ }
/* */
/* */ private void setSelected(int selected) {
/* 251 */ if (selected == getSelected()) return;
/* 252 */ this.mainPane.remove(getCurrentConfigBean());
/* 253 */ this.selected = selected;
/* 254 */ this.mainPane.add(getCurrentConfigBean(), "Center");
/* 255 */ this.selectedBeanNameLabel.setText(getCurrentConfigBean().getBeanDisplayName());
/* 256 */ this.mainPane.validate();
/* 257 */ updateOutput();
/* */ }
/* */
/* */ private void setCentered() {
/* 261 */ setSize(630, 380);
/* 262 */ Toolkit kit = Toolkit.getDefaultToolkit();
/* 263 */ Dimension screenSize = kit.getScreenSize();
/* 264 */ if ((getWidth() > screenSize.width) || (getHeight() > screenSize.height)) {
/* 265 */ setLocation(0, 0);
/* */ } else {
/* 267 */ setLocation((screenSize.width - getWidth()) / 2, (screenSize.height - getHeight()) / 2);
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void onCommit(datechooser.events.CommitEvent evt)
/* */ {
/* 280 */ updateOutput();
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */ public void onSelectionChange(SelectionChangedEvent evt)
/* */ {
/* 289 */ updateOutput();
/* */ }
/* */
/* */ private File getFileName(File start, String title, String approveName, boolean isOpen) {
/* 293 */ this.fileChooser.setDialogType(isOpen ? 0 : 1);
/* 294 */ if (start != null) this.fileChooser.setSelectedFile(start);
/* 295 */ if (approveName != null) this.fileChooser.setApproveButtonText(approveName);
/* 296 */ this.fileChooser.setApproveButtonText(approveName);
/* 297 */ this.fileChooser.setDialogTitle(title);
/* 298 */ int result = this.fileChooser.showDialog(this, null);
/* 299 */ if (result != 0) {
/* 300 */ return null;
/* */ }
/* 302 */ return this.fileChooser.getSelectedFile();
/* */ }
/* */
/* */ private class OnWindowClose extends java.awt.event.WindowAdapter { private OnWindowClose() {}
/* */
/* 307 */ public void windowClosing(java.awt.event.WindowEvent e) { ConfigWindow.this.tryToExit(); }
/* */ }
/* */
/* */ private class OnStoreAction implements ActionListener {
/* */ private OnStoreAction() {}
/* */
/* */ public void actionPerformed(ActionEvent e) {
/* 314 */ String action = (String)((JMenuItem)e.getSource()).getClientProperty("MenuItemID");
/* 315 */ if (action.equals("load")) {
/* 316 */ loadFromFile();
/* */ }
/* 318 */ if (action.equals("save")) {
/* 319 */ saveToFile(false);
/* */ }
/* 321 */ if (action.equals("save as")) {
/* 322 */ saveToFile(true);
/* */ }
/* */ }
/* */
/* */ private void sayIfNotOK(String status) {
/* 327 */ if (status.equals("ok")) return;
/* 328 */ StringBuffer mess = new StringBuffer("<html><i>");
/* 329 */ mess.append(LocaleUtils.getConfigLocaleString("OperationErrorMessage"));
/* 330 */ mess.append("</i><br><br>");
/* 331 */ mess.append(status);
/* 332 */ JOptionPane.showMessageDialog(ConfigWindow.this.getFrame(), mess.toString(), LocaleUtils.getConfigLocaleString("OperationError"), 0);
/* */ }
/* */
/* */
/* */
/* */ private void loadFromFile()
/* */ {
/* 339 */ ConfigBean configBean = ConfigWindow.this.getCurrentConfigBean();
/* 340 */ if (!configBean.isSaved()) {
/* 341 */ int result = JOptionPane.showConfirmDialog(ConfigWindow.this.getFrame(), LocaleUtils.getConfigLocaleString("ConfigLost"), LocaleUtils.getConfigLocaleString("Load"), 2);
/* */
/* */
/* */
/* 345 */ if (result == 2) return;
/* */ }
/* 347 */ File file = ConfigWindow.this.getFileName(configBean.getFile(), configBean.getBeanDisplayName(), LocaleUtils.getConfigLocaleString("Load"), true);
/* */
/* */
/* 350 */ if (file == null) return;
/* 351 */ sayIfNotOK(configBean.readFromFile(file));
/* */ }
/* */
/* */ private void saveToFile(boolean saveAs) {
/* 355 */ ConfigBean configBean = ConfigWindow.this.getCurrentConfigBean();
/* 356 */ if ((!saveAs) && (configBean.isSaved()) && (configBean.getFile() != null)) return;
/* 357 */ File file = configBean.getFile();
/* 358 */ if ((saveAs) || (file == null)) {
/* 359 */ if (file == null) file = new File(configBean.getBeanInfo().getBeanDescriptor().getName());
/* 360 */ file = ConfigWindow.this.getFileName(file, configBean.getBeanDisplayName(), LocaleUtils.getConfigLocaleString("Save"), false);
/* */
/* */
/* 363 */ if (file == null) return;
/* 364 */ if (!file.getPath().endsWith(configBean.getFileExt())) {
/* 365 */ file = new File(file.getPath() + "." + configBean.getFileExt());
/* */ }
/* */ }
/* 368 */ sayIfNotOK(configBean.writeToFile(file));
/* */ }
/* */ }
/* */
/* */ private class ComponentFileFilter extends javax.swing.filechooser.FileFilter {
/* */ private ComponentFileFilter() {}
/* */
/* 375 */ public boolean accept(File f) { return (f.isDirectory()) || (f.getName().endsWith(ConfigWindow.this.getCurrentConfigBean().getFileExt())); }
/* */
/* */
/* */
/* */
/* 380 */ public String getDescription() { return ConfigWindow.this.getCurrentConfigBean().getBeanDisplayName(); }
/* */ }
/* */
/* */ private class OnLookAndFeelChange implements ActionListener {
/* */ private OnLookAndFeelChange() {}
/* */
/* 386 */ public void actionPerformed(ActionEvent e) { String newLFClassName = (String)((JCheckBoxMenuItem)e.getSource()).getClientProperty("MenuItemID");
/* 387 */ if (newLFClassName.equals(UIManager.getLookAndFeel().getClass().getName())) return;
/* */ try {
/* 389 */ UIManager.setLookAndFeel(newLFClassName);
/* 390 */ SwingUtilities.updateComponentTreeUI(ConfigWindow.this.getFrame());
/* 391 */ for (ConfigBean beanConfigurator : ConfigWindow.this.configurators) {
/* 392 */ SwingUtilities.updateComponentTreeUI(beanConfigurator);
/* 393 */ SwingUtilities.updateComponentTreeUI(ConfigWindow.this.fileChooser);
/* */ }
/* 395 */ ConfigWindow.this.getFrame().repaint();
/* */ } catch (Exception ex) {
/* 397 */ ex.printStackTrace();
/* */ }
/* */ }
/* */ }
/* */
/* */ private class OnBeanChange implements ActionListener { private OnBeanChange() {}
/* */
/* 404 */ public void actionPerformed(ActionEvent e) { Integer newBeanIndex = (Integer)((JCheckBoxMenuItem)e.getSource()).getClientProperty("MenuItemID");
/* 405 */ ConfigWindow.this.setSelected(newBeanIndex.intValue());
/* */ }
/* */ }
/* */ }
/* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/autorun/ConfigWindow.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 0.7.1
*/
|
package com.edgedx.covid.util;
public class Constants {
public static final String IMAGES_FOLDER_PATH = "/home/ubuntu/images/";
}
|
package cs213.photoAlbum.simpleview;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JList;
import javax.swing.JScrollPane;
import cs213.photoAlbum.util.DefaultListModelAction;
/**
* Creates the GUI for Admin.
*
* @author Truong Pham
*/
public class Admin {
/** The gui view. */
GuiView guiView;
/** The frame2. */
JFrame frame, frame2;
/** The button listener. */
ActionListener buttonListener;
/** The panel. */
JPanel[] panel = new JPanel[6];
/** The button. */
JButton[] button = new JButton[3];
/** The close button. */
JButton closeButton;
/** The label. */
JLabel[] label = new JLabel[2];
/** The error label. */
JLabel errorLabel;
/** The tf. */
JTextField[] tf = new JTextField[2];
/** The list. */
JList<DefaultListModel<String>> list;
/** The sp. */
JScrollPane sp;
/** The user model. */
DefaultListModel<String> userModel = new DefaultListModel<String>();
/** The model action. */
DefaultListModelAction modelAction = new DefaultListModelAction();
/**
* Constructor that initializes GUI components
*
* @param gv guiView object
*/
public Admin(GuiView gv) {
guiView = gv;
frame = new JFrame("Admin");
buttonListener = new ButtonListener(this);
panel[0] = new JPanel();
panel[0].setLayout(new BoxLayout(panel[0], BoxLayout.Y_AXIS));
panel[1] = new JPanel();
panel[1].setLayout(new BoxLayout(panel[1], BoxLayout.X_AXIS));
panel[2] = new JPanel();
panel[2].setLayout(new BoxLayout(panel[2], BoxLayout.X_AXIS));
panel[3] = new JPanel();
panel[3].setLayout(new BoxLayout(panel[3], BoxLayout.X_AXIS));
panel[4] = new JPanel();
panel[4].setLayout(new BoxLayout(panel[4], BoxLayout.X_AXIS));
button[0] = new JButton("Logout");
button[0].addActionListener(buttonListener);
button[1] = new JButton("Add User");
button[1].addActionListener(buttonListener);
button[2] = new JButton("Delete");
button[2].addActionListener(buttonListener);
tf[0] = new JTextField();
tf[1] = new JTextField();
List<String> listUsers = guiView.viewContainer.listUser();
String[] users = new String[listUsers.size()];
listUsers.toArray(users);
modelAction.newList(userModel, users);
list = new JList(userModel);
if(!userModel.isEmpty())
list.setSelectedIndex(0);
sp = new JScrollPane(list);
label[0] = new JLabel("User ID: ");
label[1] = new JLabel("Full Name: ");
createAdminPanel();
createUserExistErrorPanel();
}
/**
* Creates the admin panel.
*/
public void createAdminPanel() {
frame.setSize(500, 515);
frame.setMaximumSize(new Dimension(500,515));
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tf[0].setEditable(true);
tf[0].setMaximumSize(new Dimension(125,20));
tf[1].setEditable(true);
tf[1].setMaximumSize(new Dimension(125,20));
sp.setMaximumSize(new Dimension(350, 350));
panel[1].add(Box.createRigidArea(new Dimension(420,0)));
panel[1].add(button[0]);
panel[2].add(label[0]);
panel[2].add(tf[0]);
panel[2].add(Box.createRigidArea(new Dimension(10,0)));
panel[2].add(button[1]);
panel[3].add(Box.createRigidArea(new Dimension(17,0)));
panel[3].add(sp);
panel[3].add(Box.createRigidArea(new Dimension(20,0)));
panel[3].add(button[2]);
panel[4].add(label[1]);
panel[4].add(tf[1]);
panel[4].add(Box.createRigidArea(new Dimension(110,0)));
panel[0].add(panel[1]);
panel[0].add(Box.createRigidArea(new Dimension(0,15)));
panel[0].add(panel[4]);
panel[0].add(Box.createRigidArea(new Dimension(0,10)));
panel[0].add(panel[2]);
panel[0].add(Box.createRigidArea(new Dimension(0,15)));
panel[0].add(panel[3]);
frame.add(panel[0]);
frame.setVisible(false);
}
/**
* Creates the error panel for error handling.
*/
public void createUserExistErrorPanel() {
frame2 = new JFrame("Error");
panel[5] = new JPanel();
panel[5].setLayout(new BoxLayout(panel[5], BoxLayout.Y_AXIS));
closeButton = new JButton("Close");
closeButton.addActionListener(new ButtonListener(this));
errorLabel = new JLabel();
errorLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
closeButton.setAlignmentX(JButton.CENTER_ALIGNMENT);
panel[5].add(Box.createRigidArea(new Dimension (0, 30)));
panel[5].add(errorLabel);
panel[5].add(Box.createRigidArea(new Dimension(0, 35)));
panel[5].add(closeButton);
frame2.add(panel[5]);
frame2.setLocationRelativeTo(null);
frame2.setResizable(false);
frame2.setVisible(false);
frame2.addWindowListener(new PanelListener(this));
}
/**
* Shows the admin panel.
*/
public void show() {
frame.setVisible(true);
}
/**
* The listener interface for receiving button events.
* The class that is interested in processing a button
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addButtonListener<code> method. When
* the button event occurs, that object's appropriate
* method is invoked.
*
* @see ButtonEvent
*/
class ButtonListener implements ActionListener {
/** The admin. */
Admin admin;
/**
* Instantiates a new button listener.
*
* @param ad the ad
*/
public ButtonListener(Admin ad) {
admin = ad;
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
if(e.getSource() == admin.button[0]) {
admin.tf[0].setText(null);
admin.tf[1].setText(null);
admin.frame.setVisible(false);;
admin.guiView.login.show();
}
else if(e.getSource() == admin.button[1]) {
String userID = admin.tf[0].getText().trim();
String fullName = admin.tf[1].getText().trim();
if(userID.equals("") || fullName.equals("")) {
admin.errorLabel.setText("Must enter in User ID and Full Name");
admin.frame.disable();
admin.frame2.setSize(250, 150);
admin.frame2.setVisible(true);
}
else {
boolean isExist = admin.guiView.viewContainer.addUser(userID, fullName);
if(!isExist) {
admin.tf[0].setText(null);
admin.tf[1].setText(null);
admin.errorLabel.setText("User already exists");
admin.frame2.setSize(200, 150);
admin.frame.disable();
admin.frame2.setVisible(true);
}
else {
List<String> users = admin.guiView.viewContainer.listUser();
String[] tempUser = new String[users.size()];
users.toArray(tempUser);
admin.modelAction.newList(admin.userModel, tempUser);
admin.list.setSelectedIndex(0);
admin.tf[0].setText(null);
admin.tf[1].setText(null);
}
}
}
else if(e.getSource() == admin.button[2]) {
int index = admin.list.getSelectedIndex();
String user = admin.userModel.get(index);
admin.guiView.viewContainer.deleteUser(user);
List<String> users = admin.guiView.viewContainer.listUser();
String[] tempUser = new String[users.size()];
users.toArray(tempUser);
admin.modelAction.newList(admin.userModel, tempUser);
if(!admin.userModel.isEmpty())
admin.list.setSelectedIndex(0);
}
else if(e.getSource() == admin.closeButton) {
admin.frame.enable();
admin.frame2.setVisible(false);
}
}
}
/**
* The listener interface for receiving panel events.
* The class that is interested in processing a panel
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addPanelListener<code> method. When
* the panel event occurs, that object's appropriate
* method is invoked.
*
* @see PanelEvent
*/
class PanelListener implements WindowListener {
/** The admin. */
Admin admin;
/**
* Instantiates a new panel listener.
*
* @param ad the ad
*/
public PanelListener(Admin ad) {
admin = ad;
}
/* (non-Javadoc)
* @see java.awt.event.WindowListener#windowClosing(java.awt.event.WindowEvent)
*/
@SuppressWarnings("deprecation")
public void windowClosing(WindowEvent arg0) {
admin.frame.enable();
}
/* (non-Javadoc)
* @see java.awt.event.WindowListener#windowActivated(java.awt.event.WindowEvent)
*/
public void windowActivated(WindowEvent arg0) {}
/* (non-Javadoc)
* @see java.awt.event.WindowListener#windowClosed(java.awt.event.WindowEvent)
*/
public void windowClosed(WindowEvent arg0) {}
/* (non-Javadoc)
* @see java.awt.event.WindowListener#windowDeactivated(java.awt.event.WindowEvent)
*/
public void windowDeactivated(WindowEvent arg0) {}
/* (non-Javadoc)
* @see java.awt.event.WindowListener#windowDeiconified(java.awt.event.WindowEvent)
*/
public void windowDeiconified(WindowEvent arg0) {}
/* (non-Javadoc)
* @see java.awt.event.WindowListener#windowIconified(java.awt.event.WindowEvent)
*/
public void windowIconified(WindowEvent arg0) {}
/* (non-Javadoc)
* @see java.awt.event.WindowListener#windowOpened(java.awt.event.WindowEvent)
*/
public void windowOpened(WindowEvent arg0) {}
}
}
|
package com.hew.data_pre_process.controller;
import com.hew.data_pre_process.service.DataInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author hw
* @date 2018/5/9 12:58
*/
@Controller
public class DataPreController {
@Autowired
private DataInstance instance;
@RequestMapping({"/"})
public String Index() {
return "dataPreProcess";
}
@RequestMapping(
value = {"/data"},
method = {RequestMethod.POST}
)
@ResponseBody
public Map HomePage(@RequestParam("fileName") String fileName) {
Map<String, Object> result = new HashMap();
this.instance.getFileName(fileName);
Map relation = this.instance.getRelation();
List attributes = this.instance.getAttributes();
Map selectedAttrbute = this.instance.getSelectedAttrbute();
Map statistic = this.instance.getStatistic();
Map chartData = this.instance.getVarData(0);
result.put("relation", relation);
result.put("attributes", attributes);
result.put("selectedAttrbute", selectedAttrbute);
result.put("statistic", statistic);
result.put("chartData", chartData);
return result;
}
@PostMapping({"/varIndex"})
@ResponseBody
public Map getVarIndex(@RequestParam("index") int varIndex) {
Map<String, Object> result = new HashMap();
Map selectedAttrbute = this.instance.getSelectedAttrbuteVar(varIndex);
Map statistic = this.instance.getStatisticVar(varIndex);
Map varData = this.instance.getVarData(varIndex);
result.put("selectedAttrbute", selectedAttrbute);
result.put("statistic", statistic);
result.put("chartData", varData);
return result;
}
}
|
package com.dayuanit.shop.serviceImpl;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dayuanit.shop.exception.ShopException;
import com.dayuanit.shop.mapper.ProvinceAndCityMapper;
import com.dayuanit.shop.service.ProvinceAndCityService;
import com.dayuanit.shop.service.RedisService;
@Service
public class ProvinceAndCityServiceImpl implements ProvinceAndCityService {
private static final Logger log = LoggerFactory.getLogger(ProvinceAndCityServiceImpl.class);
@Autowired
private ProvinceAndCityMapper provinceAndCityMapper;
@Resource(name="redisTempServiceImpl")
private RedisService redisService;
@Override
public List<Map<String, String>> listProvince() {
// TODO Auto-generated method stub
String provinceKey = "mall:province";
boolean flag = redisService.hasKey(provinceKey);
if (flag) {
log.info(">>>>>省份走缓存");
return redisService.getPCA(provinceKey);
}
List<Map<String, String>> listProvince = provinceAndCityMapper.listProvince();
if (null == listProvince) {
throw new ShopException("新增地址 查询省代码失败 ");
}
redisService.setListPCA(provinceKey, listProvince);
return listProvince;
}
@Override
public List<Map<String, String>> listCity(String provincecode) {
// TODO Auto-generated method stub
String cityKey = String.format("mall:city:%s", provincecode);
boolean flag = redisService.hasKey(cityKey);
if (flag) {
log.info(">>>>>city走缓存");
return redisService.getPCA(cityKey);
}
List<Map<String, String>> listCity = provinceAndCityMapper.listCity(provincecode);
if (null == listCity) {
throw new ShopException("新增地址 查询市区代码失败 ");
}
redisService.setListPCA(cityKey, listCity);
return listCity;
}
@Override
public List<Map<String, String>> listArea(String citycode) {
String areaKey = String.format("mall:area:%s", citycode);
boolean flag = redisService.hasKey(areaKey);
if (flag) {
log.info(">>>>>area走缓存");
return redisService.getPCA(areaKey);
}
List<Map<String, String>> listArea = provinceAndCityMapper.listArea(citycode);
if (null == listArea) {
throw new ShopException("新增地址 查询区域代码失败 ");
}
redisService.setListPCA(areaKey, listArea);
return listArea;
}
@Override
public String getProvince(String code) {
// TODO Auto-generated method stub
String provincename = provinceAndCityMapper.getProvince(code);
if (null == provincename) {
throw new ShopException("新增地址 查询省名字失败 ");
}
return provincename;
}
@Override
public String getCity(String code) {
// TODO Auto-generated method stub
String cityname = provinceAndCityMapper.getCity(code);
if (null == cityname) {
throw new ShopException("新增地址 查询市名字失败 ");
}
return cityname;
}
@Override
public String getArea(String code) {
// TODO Auto-generated method stub
String areaname = provinceAndCityMapper.getArea(code);
if (null == areaname) {
throw new ShopException("新增地址 查询区名字失败 ");
}
return areaname;
}
}
|
//
// Este archivo ha sido generado por la arquitectura JavaTM para la implantación de la referencia de enlace (JAXB) XML v2.2.11
// Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Todas las modificaciones realizadas en este archivo se perderán si se vuelve a compilar el esquema de origen.
// Generado el: 2017.03.09 a las 11:31:33 AM CET
//
package com.epl.a2btransfer.model;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}pasid"/>
* <element ref="{}impnoc"/>
* <element ref="{}impcom"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"pasid",
"impnoc",
"impcom"
})
@XmlRootElement(name = "estpas")
public class Estpas {
@XmlElement(required = true)
protected BigInteger pasid;
@XmlElement(required = true)
protected BigInteger impnoc;
@XmlElement(required = true)
protected BigDecimal impcom;
/**
* Obtiene el valor de la propiedad pasid.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getPasid() {
return pasid;
}
/**
* Define el valor de la propiedad pasid.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setPasid(BigInteger value) {
this.pasid = value;
}
/**
* Obtiene el valor de la propiedad impnoc.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getImpnoc() {
return impnoc;
}
/**
* Define el valor de la propiedad impnoc.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setImpnoc(BigInteger value) {
this.impnoc = value;
}
/**
* Obtiene el valor de la propiedad impcom.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getImpcom() {
return impcom;
}
/**
* Define el valor de la propiedad impcom.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setImpcom(BigDecimal value) {
this.impcom = value;
}
}
|
public class EmployeeManager {
}
|
package com.bank.service.ui.userlogin;
import android.content.Context;
import com.bank.service.ui.statements.domain.model.StatementList;
import com.bank.service.ui.statements.domain.model.Statements;
import java.util.ArrayList;
import java.util.List;
public class UserLoginPresenter implements ILogin.Presenter {
private String TAG = "USERLOGIN";
// private FundModelTemplate template;
private ILogin.Interactor interactor;
private ILogin.Views views;
private StatementList stmList;
// private Statements stmItem;
// private Alert alert;
private List<StatementList> listStm = new ArrayList<>();
private List<Statements> listItem = new ArrayList<>();
// private List<UseAccount> listUseraAccount = new ArrayList<>();
UserLoginPresenter(ILogin.Views views) {
//template = new FundModelTemplate();
//interactor = new StatmentsInteractor(this);
//alert = new Alert();
// this.views = views;
}
//@Override
public Context getContext() {
return (Context) views;
}
public void loadLogin() {
// listItem = interactor.loadListTest("teste");
// listStm = interactor.loadDetail("teste");
if (listItem != null) {
views.updateLogin(listItem);
} else {
loadAlert(1, getContext());
}
}
public void loadAlert(int msgCode, Context context) {
msgCode = (msgCode >= 0 && msgCode <= 5) ? msgCode : 0;
views.updateAlert(msgCode, context);
}
}
|
package com.appg.remote_control_part;
import android.app.Application;
/*
UserClass
유저 정보 및 차량 정보, 상태 등을 저장하고 있는 클래스입니다.
*/
public class UserClass extends Application {
private static String userName; //이름
private static String userID; //유저의 로그인 ID
private static String userEmail; //유저의 이메일
private static String userMobileNum; // 유저의 핸드폰번호
private static String userAccessToken; // 액세스 토큰
private static String accessTokenType; // 액세스 토큰 타입
private static String refreshAccessToken; // 액세스 토큰 새로받은거
private static String accessTokenExpires; // 유효기간
private static String deviceID; // 등록된 휴대폰ID
private static String controlToken; // ?
private static String controlTokenExpires; // ?
private static String[] vehicleId; // 차량 ID
private static String[] vehicleName; // 차량 이름
private static String[] vehicleNickname; // 차량 닉네임..
private static int vehicleCount; // 차량 개수
private static int pinWrongCount; // 핀 잘못친 횟수
private static Boolean isPinLimited; // 핀 제한여부
private static Boolean isConnectedKeyOn; // ConnectedKeyOn 상태
@Override
public void onCreate(){
userName = "";
userID= "";
userEmail= "";
userMobileNum= "";
userAccessToken= "";
accessTokenType = "";
refreshAccessToken = "";
accessTokenExpires = "";
controlToken = "";
controlTokenExpires = "";
deviceID = "";
vehicleCount = 0;
pinWrongCount = 0;
isPinLimited = false;
isConnectedKeyOn = false;
super.onCreate();
}
public void setUserName(String str){
userName = str;
}
public void setUserID(String str){
userID = str;
}
public void setUserEmail(String str){
userEmail = str;
}
public void setUserMobileNum(String str){
userMobileNum = str;
}
public void setUserAccessToken(String str){
userAccessToken = str;
}
public void setAccessTokenType(String str){
accessTokenType = str;
}
public void setRefreshAccessToken(String str){
refreshAccessToken = str;
}
public void setAccessTokenExpires(String str){
accessTokenExpires = str;
}
public void setDeviceID(String str) { deviceID = str; }
public void setControlToken(String str){
controlToken = str;
}
public void setControlTokenExpires(String str){
controlTokenExpires = str;
}
public void setVehicleCount(int cnt){
vehicleCount = cnt;
if (vehicleCount > 0) {
vehicleId = new String[vehicleCount - 1];
vehicleName = new String[vehicleCount - 1];
vehicleNickname = new String[vehicleCount - 1];
for (int i = 0; i < vehicleCount - 1; i++) {
vehicleId[i] = "";
vehicleName[i] = "";
vehicleNickname[i] = "";
}
}
}
public void setVehicleId(String str, int cnt) { vehicleId[cnt] = str; }
public void setVehicleName(String str, int cnt) { vehicleName[cnt] = str; }
public void setVehicleNickname(String str, int cnt) { vehicleNickname[cnt] = str; }
public void setPinWrongCount(int cnt){ pinWrongCount = cnt; }
public void setPinLimited(Boolean result) { isPinLimited = result; }
public void setConnectedKey(Boolean result) { isConnectedKeyOn = result; }
////////////////////////////////////////////////////////////////////////////
public String getUserName(){
return userName;
}
public String getUserID(){
return userID;
}
public String getUserEmail(){
return userEmail;
}
public String getUserMobileNum(){
return userMobileNum;
}
public String getUserAccessToken(){
return userAccessToken;
}
public String getAccessTokenType(){
return accessTokenType;
}
public String getRefreshAccessToken(){
return refreshAccessToken;
}
public String getAccessTokenExpires(){
return accessTokenExpires;
}
public String getDeviceID() { return deviceID; }
public String getControlToken(){
return controlToken;
}
public String getControlTokenExpires(){
return controlTokenExpires;
}
public int getVehicleCount() { return vehicleCount; }
public String getVehicleId(int cnt) { return vehicleId[cnt]; }
public String getVehicleName(int cnt) { return vehicleName[cnt]; }
public String getVehicleNickname(int cnt) { return vehicleNickname[cnt]; }
public int getPinWrongCount() { return pinWrongCount; }
public Boolean getPinLimited() { return isPinLimited; }
public Boolean getConnectedKey() { return isConnectedKeyOn; }
}
|
package com.example.crud;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoUpdate {
public static void main(String[] args) {
//获取连接
MongoClient client = new MongoClient();
//得到数据库
MongoDatabase database = client.getDatabase("test");
//得到集合封装对象
MongoCollection<Document> collection = database.getCollection("student");
//修改的条件
BasicDBObject filter = new BasicDBObject("name", "铁扇公主");
//修改后的值
BasicDBObject update = new BasicDBObject("$set",
new BasicDBObject("name", "玉面狐狸").append("address", "积雷山摩云洞").append("age", 18));
//参数1:修改条件 参数2:修改后的值
collection.updateOne(filter, update);
//collection.updateMany(filter, update);//修改符合条件的所有记录
}
}
|
package com.example.lianxi2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.lianxi2.base.BaseActivity;
import com.example.lianxi2.base.BasePresenter;
import com.example.lianxi2.bean.Zbean;
import com.example.lianxi2.presenter.Presenter;
import com.google.gson.Gson;
import java.util.HashMap;
public class ZhuCeActivity extends BaseActivity {
private String str = "http://172.17.8.100/small/user/v1/register";
private EditText edit_name;
private EditText edit_pwd;
private Button button_z;
@Override
protected int layoutId() {
return R.layout.activity_zhu_ce;
}
@Override
protected BasePresenter getPresenter() {
return new Presenter();
}
@Override
protected void initView() {
edit_name = findViewById(R.id.edit_name);
edit_pwd = findViewById(R.id.edit_pwd);
button_z = findViewById(R.id.button_Z);
button_z.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = edit_pwd.getText().toString().trim();
String pwd = edit_pwd.getText().toString().trim();
if (name.isEmpty() && pwd.isEmpty()) {
Toast.makeText(ZhuCeActivity.this, "账号密码不能为空", Toast.LENGTH_SHORT).show();
} else {
HashMap<String, String> map = new HashMap<>();
map.put("phone", name);
map.put("pwd", pwd);
mPresenter.startRequest(str, map);
}
}
});
}
@Override
public void onSuccess(String json) {
Gson gson = new Gson();
Zbean zbean = gson.fromJson(json, Zbean.class);
String message = zbean.getMessage();
String status = zbean.getStatus();
if (status.equals("0000") || status.equals("1001")) {
Intent intent = new Intent(ZhuCeActivity.this, MainActivity.class);
intent.putExtra("phone", edit_name.getText().toString().trim());
intent.putExtra("pwd", edit_pwd.getText().toString().trim());
setResult(200, intent);
finish();
}
}
@Override
public void onError(String json) {
}
}
|
package com.ibeiliao.trade.api.dto.request;
import java.io.Serializable;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import com.ibeiliao.trade.api.enums.TradeStatus;
/**
* 取消或关闭订单请求
* @author jingyesi
*
*/
public class CancelOrCloseOrderRequest implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3336083588869602723L;
/**
* 业务订单id
*/
@NotEmpty(message="业务系统订单不能为空")
@Length(max=32, message="业务系统订单id长度不能超过32位")
private String outerOrderId;
/**
* 订单状态
*/
@NotNull(message="订单状态不能为空")
private TradeStatus tradeStatus;
public TradeStatus getTradeStatus() {
return tradeStatus;
}
public void setTradeStatus(TradeStatus tradeStatus) {
this.tradeStatus = tradeStatus;
}
public String getOuterOrderId() {
return outerOrderId;
}
public void setOuterOrderId(String outerOrderId) {
this.outerOrderId = outerOrderId;
}
}
|
package com.mantouland.atool.callback.impl;
import com.mantouland.atool.callback.UniCallBack;
/**
* Created by asparaw on 2019/3/29.
*/
public abstract class JsonCallBack extends UniCallBack {
public abstract void onSuccess(Object jsonBean);
}
|
package edu.bupt.cbh.testing.entity;
/**
* Created by scarlett on 2017/8/6.
*/
public class TestingOutputResult {
private String key;
private String expectedOutput;
private String output;
private Boolean result;
public Boolean getResult() {
return result;
}
public void setResult(Boolean result) {
this.result = result;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getExpectedOutput() {
return expectedOutput;
}
public void setExpectedOutput(String expectedOutput) {
this.expectedOutput = expectedOutput;
}
public String getOutput() {
return output;
}
public void setOutput(String output) {
this.output = output;
}
}
|
package com.kush.lib.expressions.clauses;
import com.kush.lib.expressions.commons.BinomialExpression;
public interface AndExpression extends BinomialExpression {
}
|
package com.ssgl.util;
import java.text.SimpleDateFormat;
import java.util.*;
public class Util {
/**
*
* @功能:生成主键id
* @return
*/
public static String makeId(){
long t1 = System.currentTimeMillis();
return t1+makeRandom();
}
/**
*
* @功能:生成随机数
* @return
*/
public static String makeRandom(){
Random r = new Random();
String string = "";
for(int i =0;i<6;i++){
string += r.nextInt(10);
}
return string;
}
/**
*
* @功能:获取当前时间并以字符串方式返回
* @return
*/
public static String getStringDate(){
Date d = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(d);
}
public static String getDateTime(String time){
if(null==time||time.trim().equals("")){
return new Date().toString();
}
return time;
}
}
|
package com.dev.lungyu.find_rip;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.dev.lungyu.find_rip.util.PermissionManagement;
import java.util.List;
import static android.Manifest.permission.READ_CONTACTS;
public class SplashActivity extends AppCompatActivity {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
//direct();
checkAllowAllPermission();
}
private static final int REQUEST_CODE_ASK = 1055;
private void checkAllowAllPermission(){
PermissionManagement permissionManagement = new PermissionManagement(this);
List<String> list = permissionManagement.getNotAllowPermission();
if(list.size() == 0){
directActivity();
return;
}
String[] reqs = new String[list.size()];
for(int i=0;i<reqs.length;i++)
reqs[i] = list.get(i);
ActivityCompat.requestPermissions(
this,
reqs,
REQUEST_CODE_ASK
);
}
private void directActivity(){
//Intent intent = new Intent(this,LoginActivity.class);
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
finish();
}
/**
* Callback received when a permissions request has been completed.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
switch (requestCode){
case REQUEST_CODE_ASK:
checkAllowAllPermission();
break;
case REQUEST_READ_CONTACTS:
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//populateAutoComplete();
}
break;
}
}
}
|
package com.rofour.baseball.service.crowdsource;
import com.rofour.baseball.controller.model.DataGrid;
import com.rofour.baseball.dao.crowdsource.bean.CollegePieBean;
import com.rofour.baseball.dao.crowdsource.bean.CrowdsourceBean;
import com.rofour.baseball.dao.order.bean.PacketOrderBean;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* Created by Administrator on 2016/10/11.
*/
public interface CrowdUserService {
/**
* 查询小派列表
* @param crowdsourceBean
* @return
* @throws Exception
*/
DataGrid<CrowdsourceBean> getCrowdsourceList(CrowdsourceBean crowdsourceBean) throws Exception;
/**
* 查询小派列表总数
* @param crowdsourceBean
* @return
* @throws Exception
*/
int getCrowdsourceListCount(CrowdsourceBean crowdsourceBean) throws Exception;
/**
* 根据UserId查询小派详情
* @param crowdsourceBean
* @return
* @throws Exception
*/
CrowdsourceBean getCrowdUserDetail(CrowdsourceBean crowdsourceBean) throws Exception;
/**
* 根据校园ID查询校园详情
* @param collegePieBean
* @return
* @throws Exception
*/
CollegePieBean getCollegeDetail(CollegePieBean collegePieBean)throws Exception;
/**
* 修改账户状态(支持批量)
* @param crowdsourceBean
* @return
* @throws Exception
*/
int updateState(CrowdsourceBean crowdsourceBean,HttpServletRequest request)throws Exception;
int UpdateUser(CrowdsourceBean crowdsourceBean)throws Exception;
/**
* 查询小派订单详情
* @param bean
* @return
* @throws Exception
*/
PacketOrderBean getOrderDetail(PacketOrderBean bean)throws Exception;
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.cmsitems.validator;
import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.FIELD_CONTAINS_INVALID_CHARS;
import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.FIELD_REQUIRED;
import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.FIELD_REQUIRED_L10N;
import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.NO_RESTRICTION_SET_FOR_VARIATION_PAGE;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.cms2.model.pages.AbstractPageModel;
import de.hybris.platform.cmsfacades.common.validator.ValidationErrors;
import de.hybris.platform.cmsfacades.common.validator.ValidationErrorsProvider;
import de.hybris.platform.cmsfacades.common.validator.impl.DefaultValidationErrors;
import de.hybris.platform.cmsfacades.languages.LanguageFacade;
import de.hybris.platform.cmsfacades.validator.data.ValidationError;
import de.hybris.platform.commercefacades.storesession.data.LanguageData;
import de.hybris.platform.servicelayer.i18n.CommonI18NService;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.function.Predicate;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class DefaultBaseAbstractPageValidatorTest
{
private static final String TEST_UID = "test-uid";
private static final String TEST_NAME = "test-name";
private static final String TEST_TITLE = "test-title";
private static final String INVALID = "invalid";
private static final String EN = "en";
@InjectMocks
private DefaultBaseAbstractPageValidator validator;
@Mock
private Predicate<String> onlyHasSupportedCharactersPredicate;
@Mock
private LanguageFacade languageFacade;
@Mock
private CommonI18NService commonI18NService;
@Mock
private LanguageData enLanguage;
@Mock
private ValidationErrorsProvider validationErrorsProvider;
private ValidationErrors validationErrors = new DefaultValidationErrors();
@Before
public void setup()
{
when(validationErrorsProvider.getCurrentValidationErrors()).thenReturn(validationErrors);
when(onlyHasSupportedCharactersPredicate.test(TEST_UID)).thenReturn(true);
when(onlyHasSupportedCharactersPredicate.test(INVALID)).thenReturn(false);
when(languageFacade.getLanguages()).thenReturn(Arrays.asList(enLanguage));
when(enLanguage.getIsocode()).thenReturn(EN);
when(enLanguage.isRequired()).thenReturn(true);
when(commonI18NService.getLocaleForIsoCode(EN)).thenReturn(Locale.US);
}
@Test
public void testValidateWithoutRequiredAttributeUid()
{
final AbstractPageModel pageModel = new AbstractPageModel();
pageModel.setUid(null);
pageModel.setName(TEST_NAME);
pageModel.setDefaultPage(true);
pageModel.setTitle(TEST_TITLE, Locale.US);
validator.validate(pageModel);
final List<ValidationError> errors = validationErrorsProvider.getCurrentValidationErrors().getValidationErrors();
assertEquals(1, errors.size());
assertThat(errors.get(0).getField(), is(AbstractPageModel.UID));
assertThat(errors.get(0).getErrorCode(), is(FIELD_REQUIRED));
}
@Test
public void testValidateUidHasSupportedCharacters()
{
final AbstractPageModel pageModel = new AbstractPageModel();
pageModel.setUid(INVALID);
pageModel.setName(TEST_NAME);
pageModel.setDefaultPage(true);
pageModel.setTitle(TEST_TITLE, Locale.US);
validator.validate(pageModel);
final List<ValidationError> errors = validationErrorsProvider.getCurrentValidationErrors().getValidationErrors();
assertEquals(1, errors.size());
assertThat(errors.get(0).getField(), is(AbstractPageModel.UID));
assertThat(errors.get(0).getErrorCode(), is(FIELD_CONTAINS_INVALID_CHARS));
}
@Test
public void testValidateVariationPageWithoutRestrictions()
{
final AbstractPageModel pageModel = new AbstractPageModel();
pageModel.setUid(TEST_UID);
pageModel.setName(TEST_NAME);
pageModel.setDefaultPage(false);
pageModel.setRestrictions(Collections.emptyList());
pageModel.setTitle(TEST_TITLE, Locale.US);
validator.validate(pageModel);
final List<ValidationError> errors = validationErrorsProvider.getCurrentValidationErrors().getValidationErrors();
assertEquals(1, errors.size());
assertThat(errors.get(0).getField(), is(AbstractPageModel.RESTRICTIONS));
assertThat(errors.get(0).getErrorCode(), is(NO_RESTRICTION_SET_FOR_VARIATION_PAGE));
}
@Test
public void testValidateWithoutRequiredAttributeTitle()
{
final AbstractPageModel pageModel = new AbstractPageModel();
pageModel.setUid(TEST_UID);
pageModel.setName(TEST_NAME);
pageModel.setDefaultPage(true);
validator.validate(pageModel);
final List<ValidationError> errors = validationErrorsProvider.getCurrentValidationErrors().getValidationErrors();
assertEquals(1, errors.size());
assertThat(errors.get(0).getField(), is(AbstractPageModel.TITLE));
assertThat(errors.get(0).getErrorCode(), is(FIELD_REQUIRED_L10N));
}
}
|
public class BankISFraudTrue extends Bank {
@Override
public synchronized boolean isFraud(String fromAccountNum, String toAccountNum, long amount) throws InterruptedException {
return true;
}
}
|
/*
The MIT License
Copyright (c) 2010-2016 Paul R. Holser, Jr.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.jqwik;
import static java.util.Arrays.asList;
import java.lang.reflect.Method;
import java.util.function.Consumer;
import org.junit.gen5.commons.util.ReflectionUtils;
import org.opentest4j.AssertionFailedError;
import org.opentest4j.TestAbortedException;
class PropertyVerifier {
private final Method method;
private final Object[] args;
private final Consumer<Void> onSuccess;
private final Consumer<TestAbortedException> onAssumptionViolated;
private final Consumer<AssertionError> onFailure;
private final Class<?> testClass;
PropertyVerifier(Class<?> clazz, Method method, Object[] args, Consumer<Void> onSuccess,
Consumer<TestAbortedException> onAssumptionViolated, Consumer<AssertionError> onFailure) {
this.testClass = clazz;
this.method = method;
this.args = args;
this.onSuccess = onSuccess;
this.onAssumptionViolated = onAssumptionViolated;
this.onFailure = onFailure;
}
void verify() throws Throwable {
try {
Object instance = null;
if (!ReflectionUtils.isStatic(method))
instance = ReflectionUtils.newInstance(testClass);
Object result = ReflectionUtils.invokeMethod(method, instance, args);
Class<?> returnType = method.getReturnType();
if (returnType.equals(Boolean.class) || returnType.equals(boolean.class)) {
if ((boolean) result)
onSuccess.accept(null);
else {
String methodDescription = testClass.getName() + "#" + method.getName();
String message = String.format("Method %s returned false", methodDescription);
onFailure.accept(new AssertionFailedError(message));
}
}
else {
onSuccess.accept(null);
}
}
catch (TestAbortedException e) {
onAssumptionViolated.accept(e);
}
catch (AssertionError e) {
onFailure.accept(e);
}
catch (Throwable e) {
reportErrorWithArguments(e);
}
}
private void reportErrorWithArguments(Throwable e) {
throw new AssertionFailedError(
String.format("Unexpected error in property %s with args %s", method.getName(), asList(args)), e);
}
}
|
package com.sixmac.service;
import com.sixmac.entity.HostRace;
import com.sixmac.entity.WatchingRace;
import com.sixmac.service.common.ICommonService;
import org.springframework.data.domain.Page;
import java.util.List;
/**
* Created by Administrator on 2016/5/23 0023 上午 11:21.
*/
public interface HostRaceService extends ICommonService<HostRace> {
public List<HostRace> findNew();
}
|
package ru.innopolis.mputilov.expression;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Created by mputilov on 04.09.16.
*/
public class Logical extends Expression {
private OpCode opCode;
private Expression left;
private Expression right;
public Logical(OpCode op, Expression left, Expression right) {
opCode = op;
this.left = left;
this.right = right;
}
@Override
protected void recursiveToXml(Document doc, Node parent) {
Element element = doc.createElement(opCode.name());
parent.appendChild(element);
left.recursiveToXml(doc, element);
right.recursiveToXml(doc, element);
}
@Override
public String evaluate() {
Boolean leftEvaluated = Boolean.valueOf(left.evaluate());
Boolean rightEvaluated = Boolean.valueOf(right.evaluate());
switch (opCode) {
case AND:
return String.valueOf(leftEvaluated && rightEvaluated);
case OR:
return String.valueOf(leftEvaluated || rightEvaluated);
default:
return null;
}
}
public enum OpCode {AND, OR, XOR, NONE}
}
|
package com.hcp.objective.jpa.bean;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "FORM")
public class Form implements Serializable {
/**
* Generated serial version uid
*/
private static final long serialVersionUID = 2949217745622079056L;
@Id
@Column(name = "FORM_ID", nullable = false)
private Long id;
@Column(name = "USER_ID")
private String userId;
@Column(name = "SCORE")
private Double score;
@Column(name = "COMPELETE_DATE")
private Timestamp compeleteDate;
@Column(name = "STATUS")
private String status;
@Column(name = "ROUTE_MAP_ID")
private Integer routeMapId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
public Timestamp getCompeleteDate() {
return compeleteDate;
}
public void setCompeleteDate(Timestamp compeleteDate) {
this.compeleteDate = compeleteDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getRouteMapId() {
return routeMapId;
}
public void setRouteMapId(Integer routeMapId) {
this.routeMapId = routeMapId;
}
}
|
/*
* 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 sigu.controller;
import aplikasisigu.Home;
import java.io.IOException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import sigu.model.modelBarangKeluar;
import sigu.model.modelBarangKeluar;
/**
*
* @author Luky Mulana
*/
public class controllerBarangKeluar {
private modelBarangKeluar mBK;
private Home ho;
public controllerBarangKeluar(Home ho) {
this.ho = ho;
}
public void bersihBarangKeluar() {
ho.getTfKodeBarangKeluar().setText("");
ho.getTfNamaBarangKeluar().setText("");
ho.getTfNoFakturBarangKeluar().setText("");
ho.getTfJumlahBarangKeluar().setText("");
Date date = new Date();
ho.getDateTanggalBarangKeluar().setDate(date);
ho.getTfSupplierBarangKeluar().setText("");
ho.getCbKondisiBarangKeluar().setSelectedIndex(0);
ho.getTaKeteranganBarangKeluar().setText("");
}
public void kontrolButton() {
ho.getBtnTambahBarangKeluar().setEnabled(false);
ho.getBtnHapusBarangKeluar().setEnabled(false);
ho.getBtnBatalBarangKeluar().setEnabled(true);
}
public void kontrolButtonDua() {
ho.getBtnTambahBarangKeluar().setEnabled(false);
ho.getBtnHapusBarangKeluar().setEnabled(true);
ho.getBtnBatalBarangKeluar().setEnabled(true);
}
public void kontrolButtonTiga() {
ho.getBtnTambahBarangKeluar().setEnabled(true);
ho.getBtnHapusBarangKeluar().setEnabled(false);
ho.getBtnBatalBarangKeluar().setEnabled(true);
}
public void simpanDataBarangKeluar() throws IOException, SQLException {
mBK = new modelBarangKeluar();
mBK.setNoFaktur(ho.getTfNoFakturBarangKeluar().getText());
Date date = ho.getDateTanggalBarangKeluar().getDate();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date);
mBK.setTanggalKeluar(strDate);
mBK.setKodeBarang(ho.getTfKodeBarangKeluar().getText());
mBK.setJumlah(Integer.parseInt(ho.getTfJumlahBarangKeluar().getText()));
mBK.setKodeSupplier(ho.getTfKodeSupplierBarangKeluar().getText());
mBK.setUserID(ho.getLblUserID().getText());
mBK.setKeterangan(ho.getTaKeteranganBarangKeluar().getText());
mBK.setKondisi(ho.getCbKondisiBarangKeluar().getSelectedItem().toString());
mBK.kurangStok();
mBK.simpanDataBarangKeluar();
bersihBarangKeluar();
kontrolButton();
}
public void hapusDataBarangKeluar() throws IOException {
mBK = new modelBarangKeluar();
mBK.setNoFaktur(ho.getTfNoFakturBarangKeluar().getText());
mBK.setKodeBarang(ho.getTfKodeBarangKeluar().getText());
mBK.tambahStok();
mBK.hapusDataBarangKeluar();
bersihBarangKeluar();
kontrolButton();
}
}
|
import java.util.HashMap;
public class Vliegtuig {
protected int vluchtnummer;
protected String vertrekpunt;
protected String bestemming;
protected HashMap<Passagier, String> passergierlijst;
protected Piloot piloot;
public Vliegtuig(int vluchtnummer, String vertrekpunt, String bestemming, HashMap<Passagier,String> passergierlijst) {
this.vluchtnummer=vluchtnummer;
this.vertrekpunt = vertrekpunt;
this.bestemming = bestemming;
this.piloot = piloot;
this.passergierlijst =new HashMap<>();
}
public void board(Passagier p, String zitplaats){
passergierlijst.put(p, zitplaats);
}
}
|
package thread;
import java.util.concurrent.ThreadLocalRandom;
public class Messenger extends Thread{
private MessageQueue mq = null;
public Messenger(MessageQueue mq){
this.mq = mq;
}
public void run(){
for (int i = 0; i < 20; i++){
String message = "Message #"+(i+1);
mq.addMessage(message);
Util.print(Util.getDate()+" Messenger - inserting \""+ message +"\"");
try {
long v = ThreadLocalRandom.current().nextLong(0,1000);
//System.out.println("this is the random number"+ v);
Thread.sleep(v);
} catch (InterruptedException e) {
Util.print("interrupted exception: "+ e.getMessage());
}
}
}
}
|
package com.leetcode.oj;
public class ReverseLinkedListII_92 {
// Definition for singly-linked list.
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode p = head;
int length = 0;
while(p!=null){
length++;
p = p.next;
}
if(length<n){
return head;
}
final int diff = n-m;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode mprev = dummy;
ListNode nprev = dummy;
int d = diff;
while(d>0){
nprev = nprev.next;
d--;
}
while(m>1){
mprev = mprev.next;
nprev = nprev.next;
m--;
}
ListNode np = nprev.next;
ListNode npost = np.next;
ListNode reverseHead = npost;
p = mprev.next;
while(p!=null&&p!=npost){
ListNode tmpListNode = p.next;
p.next = reverseHead;
reverseHead = p;
p = tmpListNode;
}
mprev.next = reverseHead;
return dummy.next;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
new ReverseLinkedListII_92().reverseBetween(head, 1, 2);
}
}
|
package Chapter4;
import java.util.*;
public class Execise4_14 {
//숫자맞추기 게임
public static void main(String args[]) {
//1~100 사이의 임의의 값을 얻어 answer에 저장
int answer = (int)(Math.random()*100)+1;
int input = 0; //사용자 입력을 저장할 공간
int count = 0; //시도 횟수
Scanner s = new Scanner(System.in);
do {
count++;
System.out.print("1과 100 사이의 값을 입력하세요 : ");
input = s.nextInt(); //입력받은 값을 변수 input에 넣음
if(answer > input)
System.out.println("더 큰 수를 입력하세요.");
else if(answer == input) {
System.out.println("맞췄습니다.");
System.out.println("시도횟수는 "+count+"번입니다.");
break;
}
else if(answer < input)
System.out.println("더 작은 수를 입력하세요.");
} while(true); //무한 반복문
}
}
|
package pe.gob.trabajo.web.rest;
import com.codahale.metrics.annotation.Timed;
import pe.gob.trabajo.domain.Docpresate;
import pe.gob.trabajo.repository.DocpresateRepository;
import pe.gob.trabajo.repository.search.DocpresateSearchRepository;
import pe.gob.trabajo.web.rest.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing Docpresate.
*/
@RestController
@RequestMapping("/api")
public class DocpresateResource {
private final Logger log = LoggerFactory.getLogger(DocpresateResource.class);
private static final String ENTITY_NAME = "docpresate";
private final DocpresateRepository docpresateRepository;
private final DocpresateSearchRepository docpresateSearchRepository;
public DocpresateResource(DocpresateRepository docpresateRepository, DocpresateSearchRepository docpresateSearchRepository) {
this.docpresateRepository = docpresateRepository;
this.docpresateSearchRepository = docpresateSearchRepository;
}
/**
* POST /docpresates : Create a new docpresate.
*
* @param docpresate the docpresate to create
* @return the ResponseEntity with status 201 (Created) and with body the new docpresate, or with status 400 (Bad Request) if the docpresate has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/docpresates")
@Timed
public ResponseEntity<Docpresate> createDocpresate(@Valid @RequestBody Docpresate docpresate) throws URISyntaxException {
log.debug("REST request to save Docpresate : {}", docpresate);
if (docpresate.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new docpresate cannot already have an ID")).body(null);
}
Docpresate result = docpresateRepository.save(docpresate);
docpresateSearchRepository.save(result);
return ResponseEntity.created(new URI("/api/docpresates/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /docpresates : Updates an existing docpresate.
*
* @param docpresate the docpresate to update
* @return the ResponseEntity with status 200 (OK) and with body the updated docpresate,
* or with status 400 (Bad Request) if the docpresate is not valid,
* or with status 500 (Internal Server Error) if the docpresate couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/docpresates")
@Timed
public ResponseEntity<Docpresate> updateDocpresate(@Valid @RequestBody Docpresate docpresate) throws URISyntaxException {
log.debug("REST request to update Docpresate : {}", docpresate);
if (docpresate.getId() == null) {
return createDocpresate(docpresate);
}
Docpresate result = docpresateRepository.save(docpresate);
docpresateSearchRepository.save(result);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, docpresate.getId().toString()))
.body(result);
}
/**
* GET /docpresates : get all the docpresates.
*
* @return the ResponseEntity with status 200 (OK) and the list of docpresates in body
*/
@GetMapping("/docpresates")
@Timed
public List<Docpresate> getAllDocpresates() {
log.debug("REST request to get all Docpresates");
return docpresateRepository.findAll();
}
/**
* GET /docpresates/:id : get the "id" docpresate.
*
* @param id the id of the docpresate to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the docpresate, or with status 404 (Not Found)
*/
@GetMapping("/docpresates/{id}")
@Timed
public ResponseEntity<Docpresate> getDocpresate(@PathVariable Long id) {
log.debug("REST request to get Docpresate : {}", id);
Docpresate docpresate = docpresateRepository.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(docpresate));
}
/** JH
* GET /docpresates : get all the docpresates.
*
* @return the ResponseEntity with status 200 (OK) and the list of docpresates in body
*/
@GetMapping("/docpresates/activos")
@Timed
public List<Docpresate> getAll_Activos() {
log.debug("REST request to get all docpresates");
return docpresateRepository.findAll_Activos();
}
/** JH
* GET /docpresates/atencion/id/:id_aten/id_oficina/:id_ofic :
* @param id_aten es el id de la atencion
* id_ofic
* @return the ResponseEntity with status 200 (OK) and with body the Docpresate, or with status 404 (Not Found)
*/
@GetMapping("/docpresates/atencion/id/{id_aten}/id_oficina/{id_ofic}")
@Timed
public List<Docpresate> getListDocpresentaByIdAtencion(@PathVariable Long id_aten,@PathVariable Long id_ofic) {
log.debug("REST request to get Docpresate : id_aten {}", id_aten,id_ofic);
return docpresateRepository.findListDocPresentaById_Atencion(id_aten,id_ofic);
}
/** JH
* GET /docpresates/atencion/id_aten/:id_aten/id_oficina/:id_ofic
* @param id_aten es el id de la atencion
* id_ofic
* @return the ResponseEntity with status 200 (OK) and with body the docpresates, or with status 404 (Not Found)
*/
@GetMapping("/docpresates/seleccion/atencion/id_aten/{id_aten}/id_oficina/{id_ofic}")
@Timed
public List<Docpresate> getListDocumento_ySeleccionadosByIdAtencion(@PathVariable Long id_aten,@PathVariable Long id_ofic) {
log.debug("REST request to get Atenaccadop : id_aten {} id_ofic {}", id_aten,id_ofic);
return docpresateRepository.findListDocumento_ySeleccionadosByIdAtencion(id_aten,id_ofic);
}
/**
* DELETE /docpresates/:id : delete the "id" docpresate.
*
* @param id the id of the docpresate to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/docpresates/{id}")
@Timed
public ResponseEntity<Void> deleteDocpresate(@PathVariable Long id) {
log.debug("REST request to delete Docpresate : {}", id);
docpresateRepository.delete(id);
docpresateSearchRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
/**
* SEARCH /_search/docpresates?query=:query : search for the docpresate corresponding
* to the query.
*
* @param query the query of the docpresate search
* @return the result of the search
*/
@GetMapping("/_search/docpresates")
@Timed
public List<Docpresate> searchDocpresates(@RequestParam String query) {
log.debug("REST request to search Docpresates for query {}", query);
return StreamSupport
.stream(docpresateSearchRepository.search(queryStringQuery(query)).spliterator(), false)
.collect(Collectors.toList());
}
}
|
package cn.edu.hebtu.software.sharemate.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import cn.edu.hebtu.software.sharemate.Bean.UserBean;
import cn.edu.hebtu.software.sharemate.R;
import cn.edu.hebtu.software.sharemate.tools.PasswordUtils;
import cn.edu.hebtu.software.sharemate.tools.TelephoneUtils;
public class PhonePswdLoginActivity extends AppCompatActivity {
private TextView tvSpinner;
private Button btnSpinner;
private ImageView back;
private Button btnLogin;
private TextView forgetPswd;
private TextView codeLogin;
private EditText etPhone;
private String phone;
private EditText etPassword;
private String password;
private UserBean user = new UserBean();
private boolean resultPhone;
private boolean resultPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_pswd_login);
findViews();
back.setOnClickListener(new backClickListener());
btnLogin.setOnClickListener(new ButtonClickListener());
forgetPswd.setOnClickListener(new forgetPswdClickListener());
// codeLogin.setOnClickListener(new codeLoginClickListener());
btnSpinner.setOnClickListener(new SpinnerClickListener());
tvSpinner.setOnClickListener(new SpinnerClickListener());
etPhone.setOnFocusChangeListener(new FocusChangeListener());
etPassword.setOnFocusChangeListener(new FocusChangeListener());
}
private void findViews(){
back = findViewById(R.id.iv_back);
btnLogin = findViewById(R.id.btn_login);
forgetPswd = findViewById(R.id.tv_forget_password);
// codeLogin = findViewById(R.id.tv_code_login);
btnSpinner = findViewById(R.id.btn_spinner);
tvSpinner = findViewById(R.id.tv_spinner);
etPhone = findViewById(R.id.et_phone);
etPassword = findViewById(R.id.et_password);
}
/**
* 根据手机号和密码判断该用户是否存在
*/
private class FocusChangeListener implements View.OnFocusChangeListener{
@Override
public void onFocusChange(View v, boolean hasFocus) {
switch (v.getId()){
case R.id.et_phone:
if (hasFocus){
}else {
phone = etPhone.getText().toString();
Log.e("phone",phone);
//判断手机号码格式,11位数字
resultPhone = TelephoneUtils.isPhone(phone);
if (resultPhone == true){
user.setUserPhone(phone);
}else {
Toast.makeText(PhonePswdLoginActivity.this,"请输入正确的手机号码",Toast.LENGTH_SHORT).show();
}
}
break;
case R.id.et_password:
if (hasFocus){
}else {
password = etPassword.getText().toString();
Log.e("password",password);
//判断密码格式,8-16位数字和字母
resultPassword = PasswordUtils.isPassword(password);
if (resultPassword == true){
user.setUserPassword(password);
}else {
Toast.makeText(PhonePswdLoginActivity.this,"请输入正确的密码",Toast.LENGTH_SHORT).show();
}
}
break;
}
}
}
//选择地区和地区代码
private class SpinnerClickListener implements View.OnClickListener{
@Override
public void onClick(View v) {
Intent intent = new Intent(PhonePswdLoginActivity.this,CountryActivity.class);
startActivity(intent);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
switch (requestCode)
{
case 12:
if (resultCode == RESULT_OK)
{
Bundle bundle = data.getExtras();
String countryNumber = bundle.getString("countryNumber");
tvSpinner.setText(countryNumber);
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
//点击返回
private class backClickListener implements View.OnClickListener{
@Override
public void onClick(View v) {
Intent intent = new Intent(PhonePswdLoginActivity.this,LoginActivity.class);
startActivity(intent);
}
}
//点击登录按钮
private class ButtonClickListener implements View.OnClickListener{
@Override
public void onClick(View v) {
btnLogin.setFocusable(true);//设置可以获取焦点,但不一定获得
btnLogin.setFocusableInTouchMode(true);
btnLogin.requestFocus();//要获取焦点
if (!phone.equals("") && !password.equals("")){
PhonePswdLoginUtil phonePswdLoginUtil = new PhonePswdLoginUtil();
phonePswdLoginUtil.execute(user);
}else {
Toast.makeText(PhonePswdLoginActivity.this,"请输入手机号或密码",Toast.LENGTH_SHORT).show();
}
}
}
/**
* 异步任务
*/
public class PhonePswdLoginUtil extends AsyncTask {
@Override
protected Object doInBackground(Object[] objects) {
Log.e("PhonePswdLoginUtil", "异步任务");
UserBean user = (UserBean) objects[0];
List<Integer> type=null;
String msg="";
int userId=0;
List<Object> objectList=new ArrayList<>();
try {
URL url = new URL(getResources().getString(R.string.server_path)+"PhonePswdLoginServlet");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter writer = new BufferedWriter(osw);
JSONObject jsonObject = new JSONObject();
Log.e("1111",user.getUserPassword());
jsonObject.put("userPhone", user.getUserPhone())
.put("userPassword", user.getUserPassword());
String str = jsonObject.toString();
writer.write(str);
writer.flush();
writer.close();
connection.connect();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String back = reader.readLine();
type=new ArrayList<>();
JSONArray jsonArray=new JSONArray(back);
Log.e("array",jsonArray.length()+"");
for (int i=0;i<jsonArray.length();i++){
JSONObject obj=jsonArray.getJSONObject(i);
int typeId=obj.getInt("typeId");
type.add(typeId);
msg=obj.getString("msg");
userId=obj.getInt("userId");
}
objectList.add(type);
objectList.add(msg);
objectList.add(userId);
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return objectList;
}
@Override
protected void onPostExecute(Object o) {
List<Object> objectList = (List<Object>)o;
Log.e("onPostExecute",objectList.toString());
String result = (String)objectList.get(1);
Log.e("result", result);
if (result.equals("该用户存在")) {
int userId = (Integer)objectList.get(2);
Log.e("userId",userId+"");
Intent intent = new Intent(PhonePswdLoginActivity.this, MainActivity.class);
intent.putExtra("userId", userId);
intent.putIntegerArrayListExtra("type",(ArrayList<Integer>)objectList.get(0));
intent.putExtra("flag","main");
startActivity(intent);
} else if (result.equals("该用户不存在")) {
Toast.makeText(PhonePswdLoginActivity.this, "该用户不存在", Toast.LENGTH_SHORT).show();
}
}
}
//忘记密码
private class forgetPswdClickListener implements View.OnClickListener{
@Override
public void onClick(View v) {
Intent intent = new Intent(PhonePswdLoginActivity.this,ForgetPasswordActivity.class);
startActivity(intent);
}
}
}
|
package com.moon.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MoonConfig {
private static Properties towerConfig=null;
static{
towerConfig = loadProperties();
}
public synchronized static String getConfig(String key){
return towerConfig.getProperty(key);
}
public synchronized static String getConfig(String key,String defaultValue){
return towerConfig.getProperty(key)==null?defaultValue:towerConfig.getProperty(key);
}
private static Properties loadProperties(){
towerConfig=new Properties();
try {
InputStream is = MoonConfig.class.getResourceAsStream("/META-INF/tower.properties");
towerConfig.load(is);
} catch (IOException e) {
e.printStackTrace();
}
return towerConfig;
}
public static void main(String[] args){
System.out.println(MoonConfig.getConfig("db.user"));
}
}
|
package thsst.calvis.configuration.model.engine;
import bsh.EvalError;
import bsh.Interpreter;
import thsst.calvis.configuration.model.exceptions.MemoryRestrictedAccessException;
/**
* Created by Goodwin Chua on 1/27/2016.
*/
public class MemoryAddressCalculator {
public static String extend(String value, int bitLength, String extension) {
int missingZeroes = bitLength / 4 - value.length();
for ( int k = 0; k < missingZeroes; k++ ) {
value = extension + value;
}
return value.toUpperCase();
}
public static Token evaluateExpression(Token[] matched, RegisterList registers, Memory memory)
throws NumberFormatException, EvalError, MemoryRestrictedAccessException {
Token token1 = matched[0];
String baseAddress = "";
int equationStartIndex = 1;
if ( token1.isMemory() ) {
token1 = matched[1];
equationStartIndex++;
}
if ( token1.isRegister() ) {
baseAddress = registers.get(token1);
if ( baseAddress.length() > 8 ) {
baseAddress = baseAddress.substring(baseAddress.length() - 8);
}
} else if ( token1.isHex() ) {
baseAddress = extend(token1.getValue(), Memory.MAX_ADDRESS_SIZE, "0");
} else if ( token1.isLabel() ) {
baseAddress = memory.getFromVariableMap(token1.getValue());
}
String result = "";
if ( memory.read(baseAddress) != null ) {
Integer base = Integer.parseInt(baseAddress, 16);
for ( int i = equationStartIndex; i < matched.length; i++ ) {
Token token = matched[i];
String equation = token.getValue();
String[] operands = equation.split(" ");
String semiEquation = base + " ";
for ( String operand : operands ) {
if ( registers.isExisting(operand) ) {
semiEquation += Integer.parseInt(registers.get(operand), 16) + " ";
} else if ( operand.matches("[0-9a-fA-F]{1," + Memory.MAX_ADDRESS_SIZE + "}") ) {
semiEquation += Integer.parseInt(operand, 16);
} else {
semiEquation += operand + " ";
}
}
Interpreter interpreter = new Interpreter();
base = (Integer) interpreter.eval(semiEquation);
}
result = Integer.toHexString(base);
result = extend(result, Memory.MAX_ADDRESS_SIZE, "0");
if ( matched[0].isMemory() ) {
result = matched[0].getValue() + "/" + result;
}
} else {
throw new MemoryRestrictedAccessException(baseAddress);
}
return new Token(Token.MEM, result);
}
}
|
/*
Дано 3 числа. Написать функцию, которая вычисляет сумму квадратов двух больших из этих трех чисел.
*/
import java.util.*;
public class Ex_52 {
public static int sqSumOfTwo(int[] array){
int sqSum = 0;
int smallest = searchOfSmallest(array);
for(int i = 0; i < array.length; i++){
if(array[i] != smallest)
sqSum += array[i]*array[i];
}
return sqSum;
}
public static int searchOfSmallest(int[] array){
int smallest = array[0];
for(int i = 1; i < array.length; i++){
if(smallest > array[i])
smallest = array[i];
}
return smallest;
}
public static int[] randomArrayCreate(int N){
int sizeArr = N;
int maxVal = 100;
int[] array = new int[sizeArr];
for (int i = 0; i < sizeArr; i++)
array[i] = new Random().nextInt(maxVal);
return array;
}
public static void main(String[] args){
if (args.length > 0) System.out.println("This programm don't needs any arguments!");
Integer N = 3;
int[] array = randomArrayCreate(N);
System.out.println(Arrays.toString(array));
int sqSum = sqSumOfTwo(array);
System.out.println(sqSum);
}
}
|
package no.ntnu.apotychia.event;
import no.ntnu.apotychia.Application;
import no.ntnu.apotychia.model.Event;
import no.ntnu.apotychia.model.Participant;
import no.ntnu.apotychia.model.User;
import no.ntnu.apotychia.service.EventService;
import no.ntnu.apotychia.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.util.HashSet;
import static org.junit.Assert.*;
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class EventServiceTest {
@Autowired
EventService eventService;
@Autowired
UserService userService;
private User testUser;
Event testEvent;
@Before
public void before() {
testUser = new User("testUser");
testUser.setPasswordAndEncode("testPassword");
testUser.setFirstName("TestFirstName");
testUser.setLastName("TestLastName");
testUser.setEmail("TestEmail@test.com");
userService.addNewUser(testUser);
testEvent = new Event();
testEvent.setEventName("TestEvent");
testEvent.setStartTime(new Timestamp(1394873100000L));
testEvent.setEndTime(new Timestamp(1394876700000L));
testEvent.setActive(true);
testEvent.setEventAdmin(testUser.getUsername());
testEvent.setDescription("This is a test event");
}
@Test
public void thatEventsAreAdded() {
Long eventId = eventService.addEvent(testEvent);
eventService.addAttending(eventId, testUser);
assertEquals(1, eventService.findAttendingEventsForUserByUsername(testUser.getUsername()).size());
}
@Test
public void thatParticipantsAreAddedAndCanBeRetrieved() {
long eventId = eventService.addEvent(testEvent);
eventService.addAttending(eventId, testUser);
assertEquals(1, eventService.findAttendingForEventByEventId(eventId).size());
}
}
|
package Database;
import java.util.LinkedList;
import java.util.List;
public class Database {
private List<User> users;
public Database(){
users = new LinkedList<User>();
try{
this.users.add(new User("Bai Ivan", "123456"));
this.users.add(new User("Bai Ivan1", "123456"));
this.users.add(new User("Bai Ivan2", "123456"));
//this.users.add(new User("", "123456"));
}catch(DatabaseCorruptedException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void add(User user){
try{
this.users.add(user);
}catch(DatabaseCorruptedException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
|
package Concrete;
import Abstract.AuthenticationService;
import Abstract.PersonVerificationService;
import Entities.User;
public class AuthenticationManager implements AuthenticationService
{
PersonVerificationService personVerificationService;
public AuthenticationManager(PersonVerificationService personVerificationService)
{
this.personVerificationService = personVerificationService;
}
@Override
public void register(User user)
{
if (personVerificationService.isPersonReal(user))
{
System.out.println(
user.getFirstName() + " " + user.getLastName() + " kaydınız başarıyla tamamlanmıştır.");
} else
{
System.out.println("Kimlik bilgillerinizde hata mevcut. Lütfen kontrol ediniz.");
}
}
}
|
package fr.antoinelaunay.resultsanalysis.endpoint;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiNamespace;
import fr.antoinelaunay.resultsanalysis.bean.Athlete;
/**
* Created by herve on 17/08/14.
*/
@Api(name = "athleteapi",
version = "v1",
scopes = {Constants.EMAIL_SCOPE},
clientIds = {Constants.WEB_CLIENT_ID, Constants.ANDROID_CLIENT_ID, Constants.IOS_CLIENT_ID},
audiences = {Constants.ANDROID_AUDIENCE},
namespace = @ApiNamespace(ownerDomain = "antoinelaunay.fr",
ownerName = "antoinelaunay.fr",
packagePath=""))
public class AthleteEndPoint {
public Athlete getAthlete() {
Athlete found = new Athlete();
found.setFname("Antoine");
found.setLname("Launay");
found.setCategory("K1H");
return found;
}
}
|
package com.bb.bahaudin.myapplication;
import android.content.Intent;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.net.Uri;
import android.widget.MediaController;
import android.widget.VideoView;
import static android.provider.MediaStore.INTENT_ACTION_VIDEO_CAMERA;
public class cameraView extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_view);
VideoView vidView = (VideoView)findViewById(R.id.myVideo);
String vidAddress="https://www.youtube.com/watch?v=EIYtubRrMc4";
Uri vidUri = Uri.parse(vidAddress);
vidView.setVideoURI(vidUri);
vidView.start();
}
}
|
package com.tencent.mm.plugin.brandservice.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.kernel.g;
class SearchOrRecommendBizUI$6 implements OnCancelListener {
final /* synthetic */ SearchOrRecommendBizUI hpX;
SearchOrRecommendBizUI$6(SearchOrRecommendBizUI searchOrRecommendBizUI) {
this.hpX = searchOrRecommendBizUI;
}
public final void onCancel(DialogInterface dialogInterface) {
BizSearchResultItemContainer a = SearchOrRecommendBizUI.a(this.hpX);
g.DF().c(a.hoL);
a.hoJ.hoW = false;
}
}
|
package Threads;
import controller.PrincipalController;
import javafx.application.Platform;
public class ThreadTimeRematch extends Thread {
private boolean iniciaHilo = true;
private boolean corriendo = false;
private int seconds = 0;
private int minutes = 0;
private PrincipalController principalCon;
public ThreadTimeRematch(PrincipalController principalCon) {
super();
this.principalCon = principalCon;
setDaemon(true);
}
public boolean isCorriendo() {
return corriendo;
}
public void setCorriendo(boolean corriendo) {
this.corriendo = corriendo;
}
public boolean isIniciaHilo() {
return iniciaHilo;
}
public void setIniciaHilo(boolean iniciaHilo) {
this.iniciaHilo = iniciaHilo;
}
public void run() {
if(principalCon.isTf() == true) {
principalCon.setTf(false);
}
while(iniciaHilo && !principalCon.isTf()) {
corriendo = true;
String msj = "";
ejecutarHiloCronometro();
if(seconds < 10) {
msj = "0"+ minutes + ":" + "0" + seconds;
}else {
msj = "0"+ minutes + ":" + seconds;
}
ThreadUpdateTimeRematch timer1 = new ThreadUpdateTimeRematch(msj,principalCon);
Platform.runLater(timer1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ThreadFinishRematch m1 = new ThreadFinishRematch(principalCon);
m1.start();
}
public void ejecutarHiloCronometro() {
seconds++;
if(seconds > 59) {
seconds = 00;
minutes++;
}
if(minutes == 3){
corriendo =false;
iniciaHilo = false;
minutes = 00;
seconds = 00;
principalCon.setTf(false);
}
}
}
|
/*
* 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 klm4.ScreenControllers;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import klm4.Database;
import static klm4.ScreenControllers.FXMLQRScanner.barCode;
/**
* FXML Controller class
*
* @author Michiel
*/
public class FXMLChecklistScreenController implements Initializable
{
String booked;
String onTime;
String awb;
String volume;
String lableCheck;
String condition1;
String weight;
//Booked buttons
@FXML
public ToggleButton NegativeBooked, NeutralBooked ,PositiveBooked ;
//On time buttons
@FXML
private ToggleButton NegativeOnTime, NeutralOnTime , PositiveOnTime ;
//AWB Check Buttons
@FXML
private ToggleButton NegativeAWB, NeutralAWB, PositveAWB;
//Volume Buttons
@FXML
private ToggleButton NegativeVolume, NeutralVolume, PositveVolume;
//Weight buttons
@FXML
private ToggleButton NegativeWeight, NeutralWeight, PositiveWeight;
//Label Check
@FXML
private ToggleButton NegativeLabel, NeutralLabel, PositiveLabel;
@FXML
private ToggleButton NegativeCondition, NeutralCondition, PositiveCondition;
@Override
public void initialize(URL url, ResourceBundle rb)
{
try {
String barCode2 = "0101234567890128";
ResultSet resultSet = Database.selectQuery("SELECT booked FROM barcode_gegevens WHERE barcodeID = " + barCode);
resultSet.next();
booked = resultSet.getString("booked");
resultSet = Database.selectQuery("SELECT ontime FROM barcode_gegevens WHERE barcodeID = " + barCode);
resultSet.next();
onTime = resultSet.getString("ontime");
resultSet = Database.selectQuery("SELECT awb FROM barcode_gegevens WHERE barcodeID = " + barCode);
resultSet.next();
awb = resultSet.getString("awb");
resultSet = Database.selectQuery("SELECT volume FROM barcode_gegevens WHERE barcodeID = " + barCode);
resultSet.next();
volume = resultSet.getString("volume");
resultSet = Database.selectQuery("SELECT weight FROM barcode_gegevens WHERE barcodeID = " + barCode);
resultSet.next();
weight = resultSet.getString("weight");
resultSet = Database.selectQuery("SELECT lable FROM barcode_gegevens WHERE barcodeID = " + barCode);
resultSet.next();
lableCheck = resultSet.getString("lable");
resultSet = Database.selectQuery("SELECT condition1 FROM barcode_gegevens WHERE barcodeID = " + barCode);
resultSet.next();
condition1 = resultSet.getString("condition1");
} catch (SQLException ex) {
Logger.getLogger(FXMLChecklistScreenController.class.getName()).log(Level.SEVERE, null, ex);
}
NeutralBooked.setText("Booked\n " + booked);
NeutralOnTime.setText("OnTime\n " + onTime);
NeutralAWB.setText("AWB\n " + awb);
NeutralVolume.setText("Volume\n " + volume);
NeutralLabel.setText("Lable Check\n " + lableCheck);
NeutralCondition.setText("Condition\n " + condition1);
NeutralWeight.setText("Weight\n " + weight);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.