text stringlengths 10 2.72M |
|---|
package com.yuecheng.yue.base;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.yuecheng.yue.R;
import com.yuecheng.yue.ui.bean.YUE_SPsave;
import com.yuecheng.yue.util.CommonUtils;
import com.yuecheng.yue.util.StatusBarCompat;
import com.yuecheng.yue.util.YUE_SharedPreferencesUtils;
import com.yuecheng.yue.util.YUE_ToastUtils;
/**
* Created by yuecheng on 2017/10/29.
*/
public abstract class YUE_BaseActivitySlideBack extends SlideBackActivity {
/**
* Screen information
*/
protected int mScreenWidth = 0;
protected int mScreenHeight = 0;
protected float mScreenDensity = 0.0f;
protected boolean statusBarCompat = true;
protected String TAG = getClass().getSimpleName();
/**
* context
*/
protected Context mContext = null;
@SuppressWarnings("unchecked")
public <T extends View> T findView(int id) {
return (T) findViewById(id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// overridePendingTransition(R.anim.right_in, R.anim.right_out);
super.onCreate(savedInstanceState);
mContext = this;
String mThem = (String) YUE_SharedPreferencesUtils.getParam(this, YUE_SPsave.YUE_THEM,
"默认主题");
Window window = getWindow();
switch (mThem) {
case "默认主题":
setTheme(R.style.AppThemeDefault);
break;
case "热情似火":
setTheme(R.style.AppThemeRed);
break;
case "梦幻紫":
setTheme(R.style.AppThemePurple);
break;
case "乌金黑":
setTheme(R.style.AppThemeHardwareblack);
break;
default:
if (android.os.Build.VERSION.SDK_INT >= 21)
window.setStatusBarColor(CommonUtils.getColorByAttrId(mContext,R.attr.colorPrimary));
break;
}
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
YUE_BaseAppManager.getInstance().addActivity(this);
/*
*获取屏幕尺寸
* */
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
mScreenDensity = displayMetrics.density;
mScreenHeight = displayMetrics.heightPixels;
mScreenWidth = displayMetrics.widthPixels;
if (getContentViewLayoutID() != 0) {
setContentView(getContentViewLayoutID());
} else {
throw new IllegalArgumentException("You must return a right contentView layout " +
"resource Id");
}
if (statusBarCompat) {
StatusBarCompat.compat(this, CommonUtils.getColorByAttrId(mContext,R.attr.colorPrimary));
transparent19and20();
}
initViewsAndEvents();
}
protected void transparent19and20() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
&& Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
protected void initToolBars(int toolBarId,String title){
Toolbar mToolBar = findView(toolBarId);
setSupportActionBar(mToolBar);
ActionBar ab = getSupportActionBar();
//使能app bar的导航功能
ab.setDisplayHomeAsUpEnabled(true);
ab.setTitle(title);
mToolBar.setTitleTextColor(getResources().getColor(R.color.white));
}
/*
*功能操作
* */
protected abstract void initViewsAndEvents();
/*
*加载的布局
* */
protected abstract int getContentViewLayoutID();
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
}
@Override
public void finish() {
super.finish();
// overridePendingTransition(R.anim.right_in, R.anim.right_out);
}
protected void startActivity(Class a) {
Intent intent = new Intent();
intent.setClass(mContext, a);
startActivity(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
YUE_BaseAppManager.getInstance().removeActivity(this);
}
protected void ShowMessage(String s) {
YUE_ToastUtils.showmessage(s);
}
protected void showSnackBar(View v,String s){
Snackbar snackBar =Snackbar.make(v,s,Snackbar.LENGTH_SHORT);
//设置SnackBar背景颜色
snackBar.getView().setBackgroundColor(CommonUtils.getColorByAttrId(mContext,R.attr.colorPrimary));
//设置按钮文字颜色
snackBar.setActionTextColor(Color.WHITE);
snackBar.show();
}
public interface OnBooleanListener {
void onClick(boolean bln);
}
private OnBooleanListener onPermissionListener;
public void onPermissionRequests(String permission, OnBooleanListener onBooleanListener) {
onPermissionListener = onBooleanListener;
Log.d(TAG, "0");
if (ContextCompat.checkSelfPermission(this,
permission)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
Log.d(TAG, "1");
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_CONTACTS)) {
//权限已有
onPermissionListener.onClick(true);
} else {
//没有权限,申请一下
ActivityCompat.requestPermissions(this,
new String[]{permission},
1);
}
}else{
onPermissionListener.onClick(true);
Log.d(TAG, "2"+ContextCompat.checkSelfPermission(this,
permission));
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 1) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//权限通过
if (onPermissionListener != null) {
onPermissionListener.onClick(true);
}
} else {
//权限拒绝
if (onPermissionListener != null) {
onPermissionListener.onClick(false);
}
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
|
package com.tyss.capgemini.loanproject.servicestest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import com.tyss.capgemini.loanproject.exceptions.DateLimitException;
import com.tyss.capgemini.loanproject.exceptions.InsufficientBalanceException;
import com.tyss.capgemini.loanproject.exceptions.InvalidDateFormatException;
import com.tyss.capgemini.loanproject.exceptions.InvalidPasswordException;
import com.tyss.capgemini.loanproject.exceptions.LoanExcessException;
import com.tyss.capgemini.loanproject.repository.Repository;
import com.tyss.capgemini.loanproject.services.CustomerServicesImplementation;
public class CustomerServicesTest {
CustomerServicesImplementation implementation = new CustomerServicesImplementation();
@Test
void changePasswordTest1() {
try {
Boolean istrueBoolean = implementation.changePassword("Praveen123@", "qwerty");
assertEquals(istrueBoolean, true);
} catch (Exception e) {
assertThrows(InvalidPasswordException.class, () -> {
implementation.changePassword("Praveen123", "qwerty");
});
}
// Boolean istrueBoolean = implementation.changePassword("Praveen123",
// "qwerty@123");
// assertEquals(istrueBoolean, true);
}
@Test
void changePasswordTest2() {
try {
Boolean istrueBoolean = implementation.changePassword("Praveen123@", "qwerty");
assertEquals(istrueBoolean, true);
} catch (Exception e) {
assertThrows(InvalidPasswordException.class, () -> {
implementation.changePassword("Praveen123", "qwerty");
});
}
// Boolean istrueBoolean = implementation.changePassword("Praveen123",
// "qwerty@123");
// assertEquals(istrueBoolean, true);
}
@Test
void viewLoanProgramsTest() {
Repository.UserTable();
Boolean isTrue = implementation.viewLoanPrograms();
assertEquals(isTrue, true);
}
@Test
void checkBalanceTest1() {
Repository.UserTable();
Boolean isTrue = implementation.checkBalance("manoj191");
assertEquals(isTrue, true);
}
@Test
void checkBalanceTest2() {
Repository.UserTable();
Boolean isFalse = implementation.checkBalance("mayank191");
assertEquals(isFalse, false);
}
@Test
void payLoanTest1() {
Repository.UserTable();
try {
Boolean isTrue = implementation.payLoan("manoj191", 500D);
assertEquals(isTrue, true);
} catch (LoanExcessException e) {
assertThrows(LoanExcessException.class, () -> {
implementation.payLoan("manoj191", 500D);
});
} catch (InsufficientBalanceException e) {
assertThrows(InsufficientBalanceException.class, () -> {
implementation.payLoan("manoj191", 500D);
});
}
}
@Test
void payLoanTest2() {
Repository.UserTable();
try {
Boolean isFalse = implementation.payLoan("asdanoj191", 500D);
assertEquals(isFalse, false);
} catch (LoanExcessException e) {
assertThrows(LoanExcessException.class, () -> {
implementation.payLoan("manoj191", 500D);
});
} catch (InsufficientBalanceException e) {
assertThrows(InsufficientBalanceException.class, () -> {
implementation.payLoan("manoj191", 500D);
});
}
}
@Test
void checkLoanTest1() {
Repository.UserTable();
Boolean isTrue = implementation.checkLoan("manoj191");
assertEquals(isTrue, true);
}
@Test
void checkLoanTest2() {
Repository.UserTable();
Boolean isFalse = implementation.checkLoan("nadaanoj191");
assertEquals(isFalse, false);
}
@Test
void loanApplicationForm1() {
Repository.UserTable();
try {
Boolean isBoolean = implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy",
"14/12/1995", "Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"submit", "1234");
assertEquals(isBoolean, true);
} catch (DateLimitException e) {
assertThrows(DateLimitException.class, () -> {
implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy", "14/12/1995",
"Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"submit", "1234");
});
} catch (InvalidDateFormatException e) {
assertThrows(InvalidDateFormatException.class, () -> {
implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy", "14/12/1995",
"Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"submit", "1234");
});
}
}
@Test
void loanApplicationForm2() {
Repository.UserTable();
try {
Boolean isBoolean = implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy",
"14/12/1995", "Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"cancel", "1234");
assertEquals(isBoolean, true);
} catch (DateLimitException e) {
assertThrows(DateLimitException.class, () -> {
implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy", "14/12/1995",
"Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"cancel", "1234");
});
} catch (InvalidDateFormatException e) {
assertThrows(InvalidDateFormatException.class, () -> {
implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy", "14/12/1995",
"Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"cancel", "1234");
});
}
}
@Test
void loanApplicationForm3() {
Repository.UserTable();
try {
Boolean isBoolean = implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy",
"14/12/1995", "Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"asdasd", "1234");
assertEquals(isBoolean, true);
} catch (DateLimitException e) {
assertThrows(DateLimitException.class, () -> {
implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy", "14/12/1995",
"Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"asdasd", "1234");
});
} catch (InvalidDateFormatException e) {
assertThrows(InvalidDateFormatException.class, () -> {
implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy", "14/12/1995",
"Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"asdasd", "1234");
});
}
}
@Test
void loanApplicationForm4() {
Repository.UserTable();
try {
Boolean isBoolean = implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy",
"14/12/1995", "Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"submit", "1234");
assertEquals(isBoolean, true);
} catch (DateLimitException e) {
assertThrows(DateLimitException.class, () -> {
implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy", "14/12/1995",
"Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"submit", "1234");
});
} catch (InvalidDateFormatException e) {
assertThrows(InvalidDateFormatException.class, () -> {
implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy", "14/12/1995",
"Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"submit", "1234");
});
}
}
@Test
void loanApplicationForm5() {
Repository.UserTable();
try {
Boolean isBoolean = implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy",
"14/12/3000", "Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"submit", "1234");
assertEquals(isBoolean, true);
} catch (DateLimitException e) {
assertThrows(DateLimitException.class, () -> {
implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy", "14/12/3000",
"Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"submit", "1234");
});
} catch (InvalidDateFormatException e) {
assertThrows(InvalidDateFormatException.class, () -> {
implementation.loanApplicationForm("AP198", "BNI12345", "Pankaj", "", "Tripathy", "14/12/3000",
"Ranjan", "Singh", "Ranjup", "House Loan", "BNI123421412", "Kanchipuram",
"submit", "1234");
});
}
}
}
|
package com.tyss.cg.operators;
public class LogicalOperator {
public static void main(String[] args) {
int i = 10;
int j = 20;
int k = 30;
System.out.println("+++++ AND OPERATOR+++++");
System.out.println((i > j) && (j > k));
System.out.println((i > k) && (j < k));
System.out.println((i < k) && (j > k));
System.out.println((i < k) && (j < k));
System.out.println("+++++ OR OPERATOR+++++");
System.out.println((i > j) || (j > k));
System.out.println((i > k) || (j < k));
System.out.println((i < k) || (j > k));
System.out.println((i < k) || (j < k));
System.out.println("+++++ AND OPERATOR+++++");
System.out.println((i > j) && (j > k));
System.out.println((i > k) && (j < k));
System.out.println((i < k) && (j > k));
System.out.println((i < k) && (j < k));
System.out.println("+++++ NOT+++++");
System.out.println(i!=j);
}
}
|
package rhtn_homework;
import java.util.Arrays;
public class PROG_기둥과보설치_sol {
static int N;
boolean[][] Pillar;
boolean[][] Bar;
public static void main(String[] args) {
int n = 5;
PROG_기둥과보설치_sol prog = new PROG_기둥과보설치_sol();
int[][] build_frame = {{0,0,0,1},{2,0,0,1},{4,0,0,1},{0,1,1,1},{1,1,1,1},{2,1,1,1},{3,1,1,1},{2,0,0,0},{1,1,1,0}};
int[][] sol = prog.solution(n, build_frame);
for (int i = 0; i < sol.length; i++) {
System.out.println(Arrays.toString(sol[i]));
}
}
public int[][] solution(int n, int[][] build_frame) {
N = n;
Pillar = new boolean[n+1][n+1];
Bar = new boolean[n+1][n+1];
int count = 0;
for (int[] build : build_frame) {
int x = build[0];
int y = build[1];
int type = build[2];
int cmd = build[3];
if(type == 0) {
// 기둥 설치
if(cmd ==1) {
if(checkPillar(x,y)) {
Pillar[x][y] = true;
count++;
}
}else {
Pillar[x][y] = false;
// 지울수 없다면
if(!canDelete(x,y)) {
Pillar[x][y] = true;
}else {
count--;
}
}
}else {
// 보 설치
if(cmd ==1) {
if(checkBar(x,y)) {
Bar[x][y] = true;
count++;
}
}else {
Bar[x][y] = false;
if(!canDelete(x,y)) {
Bar[x][y] = true;
}else {
count--;
}
}
}
}
int[][] answer = new int[count][3];
count = 0;
for (int r = 0; r <= n; r++) {
for (int c = 0; c <= n; c++) {
if(Pillar[r][c]) {
answer[count][0] = r;
answer[count][1] = c;
answer[count++][2] = 0;
}
if(Bar[r][c]) {
answer[count][0] = r;
answer[count][1] = c;
answer[count++][2] = 1;
}
}
}
return answer;
}
private boolean canDelete(int x, int y) {
for (int i = x-1; i <=x+1; i++) {
for (int j = y; j <=y+1; j++) {
if(!isIn(i, j)) continue;
if(Pillar[i][j] && !checkPillar(i, j)) return false;
if(Bar[i][j] && !checkBar(i, j)) return false;
}
}
return true;
}
private boolean checkPillar(int x, int y) {
if(y == 0 || Pillar[x][y-1]) return true;
if((isIn(x-1, y) && Bar[x-1][y]) || Bar[x][y]) return true;
return false;
}
private boolean checkBar(int x, int y) {
if(Pillar[x][y-1] || (isIn(x+1, y) && Pillar[x+1][y-1]))return true;
if(isIn(x-1,y) && Bar[x-1][y] && Bar[x+1][y]) return true;
return false;
}
private static boolean isIn(int x, int y){
return x>=0 && y >=0 && x<=N && y<=N;
}
}
|
package com.zp.stream.channal;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;
public interface TestChannel {
@Input("input")
SubscribableChannel input();
}
|
package com.weixin.dto.message.resp;
import com.weixin.dto.message.Article;
import java.util.List;
/**
* 图文消息
* Created by White on 2017/2/20.
*/
public class RespNewsMessage extends RespBaseMessage {
//图文消息的个数
private int ArticleCount;
//多个图文消息,默认第一个为大图显示
private List<Article> Articles;
public int getArticleCount() {
return ArticleCount;
}
public void setArticleCount(int articleCount) {
ArticleCount = articleCount;
}
public List<Article> getArcicles() {
return Articles;
}
public void setArticles(List<Article> articles) {
Articles = articles;
}
}
|
package uit.edu.vn.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import uit.edu.vn.models.KhachHang;
public class DataKhachHang {
public List<KhachHang> getDsKhachHangFromDb() throws SQLException {
Statement st = null;
ResultSet rs = null;
List<KhachHang> dsKhachHang = new ArrayList<KhachHang>();
Connection con = ConnectData.getConnection();
try {
st = con.createStatement();
String query = "select * from tbKhachHang";
rs = st.executeQuery(query);
while (rs.next()) {
int id = rs.getInt("id");
int gioiTinh = rs.getInt("GioiTinh");
int idLoaiKhachHang = rs.getInt("idLoaiKhachHang");
int diemTichLuy = rs.getInt("DiemTichLuy");
int idCuaHang = rs.getInt("idCuaHang");
String email = rs.getString("Email");
String matKhau = rs.getString("MatKhau");
String tenKhachHang = rs.getString("TenKhachHang");
String diaChi = rs.getString("DiaChi");
String soDienThoai = rs.getString("SoDienThoai");
// java.sql.Date ngayNhap = rs.getDate("NgayNhap");
KhachHang kh = new KhachHang(id, gioiTinh, idLoaiKhachHang, diemTichLuy, idCuaHang,
tenKhachHang, diaChi, soDienThoai, email, matKhau, null);
dsKhachHang.add(kh);
}
con.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
if (st != null)
try {
st.close();
} catch (Exception e) {
}
if (con != null)
try {
con.close();
} catch (Exception e) {
}
}
return dsKhachHang;
}
public boolean CheckKhachHang(String email, String password) throws SQLException {
Statement st = null;
ResultSet rs = null;
Connection con = ConnectData.getConnection();
try {
st = con.createStatement();
String query = "select * from tbKhachhang where Email = '" + email + "' and MatKhau = '"
+ md5lib.md5(password) + "'";
rs = st.executeQuery(query);
return rs.first();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
if (st != null)
try {
st.close();
} catch (Exception e) {
}
if (con != null)
try {
con.close();
} catch (Exception e) {
}
}
}
public boolean CheckKhachHang(String email) throws SQLException {
Statement st = null;
ResultSet rs = null;
Connection con = ConnectData.getConnection();
try {
st = con.createStatement();
String query = "select * from tbKhachhang where Email = '" + email + "'";
rs = st.executeQuery(query);
return rs.first();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
if (st != null)
try {
st.close();
} catch (Exception e) {
}
if (con != null)
try {
con.close();
} catch (Exception e) {
}
}
}
public void AddKhachHang(KhachHang khachhang) throws SQLException {
Statement st = null;
ResultSet rs = null;
Connection con = ConnectData.getConnection();
try { // id,tenkachhang,diachi,sdt,email,matkhau,ngaynhap,idcuahang,gioitinh,loaikhachhang,diemtichluy
PreparedStatement ps = con
.prepareStatement("insert into tbkhachhang value ( null, ?, ?, ?, ?, ?, now(), 1, ?, 1, 0);");
ps.setString(1, khachhang.getTenKhachHang());
ps.setString(2, khachhang.getDiaChi());
ps.setString(3, khachhang.getSoDienThoai());
ps.setString(4, khachhang.getEmail());
ps.setString(5, md5lib.md5(khachhang.getMatKhau()));
ps.setInt(6, khachhang.getGioiTinh());
ps.executeUpdate();
System.out.println("added");
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
if (st != null)
try {
st.close();
} catch (Exception e) {
}
if (con != null)
try {
con.close();
} catch (Exception e) {
}
}
}
public void ChangePassword(String passwordchange, String email) throws SQLException {
Statement st = null;
ResultSet rs = null;
Connection con = ConnectData.getConnection();
try {
PreparedStatement ps = con
.prepareStatement("UPDATE tbkhachhang SET MatKhau =? WHERE Email=?;");
ps.setString(1, md5lib.md5(passwordchange));
ps.setString(2, email);
ps.executeUpdate();
System.out.println("password changed");
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
if (st != null)
try {
st.close();
} catch (Exception e) {
}
if (con != null)
try {
con.close();
} catch (Exception e) {
}
}
}
public List<KhachHang> getDsKhachHangFromDb(String email) throws SQLException {
Statement st = null;
ResultSet rs = null;
List<KhachHang> dsKhachHang = new ArrayList<KhachHang>();
Connection con = ConnectData.getConnection();
try {
PreparedStatement ps = con.prepareStatement("select * from tbKhachhang where Email = ?;");
ps.setString(1, email);
rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
int gioiTinh = rs.getInt("GioiTinh");
int idLoaiKhachHang = rs.getInt("idLoaiKhachHang");
int diemTichLuy = rs.getInt("DiemTichLuy");
int idCuaHang = rs.getInt("idCuaHang");
String tenKhachHang = rs.getString("TenKhachHang");
String matKhau = rs.getString("MatKhau");
String diaChi = rs.getString("DiaChi");
String soDienThoai = rs.getString("SoDienThoai");
java.sql.Date ngayNhap = rs.getDate("NgayNhap");
KhachHang kh = new KhachHang(id, gioiTinh,idLoaiKhachHang, diemTichLuy,
idCuaHang, tenKhachHang, diaChi, soDienThoai,
email, matKhau, ngayNhap);
dsKhachHang.add(kh);
}
con.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
if (st != null)
try {
st.close();
} catch (Exception e) {
}
if (con != null)
try {
con.close();
} catch (Exception e) {
}
}
return dsKhachHang;
}
}
|
package com.penzias.entity;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class PhysiqueExamInfoExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public PhysiqueExamInfoExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
protected void addCriterionForJDBCDate(String condition, Date value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
addCriterion(condition, new java.sql.Date(value.getTime()), property);
}
protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) {
if (values == null || values.size() == 0) {
throw new RuntimeException("Value list for " + property + " cannot be null or empty");
}
List<java.sql.Date> dateList = new ArrayList<java.sql.Date>();
Iterator<Date> iter = values.iterator();
while (iter.hasNext()) {
dateList.add(new java.sql.Date(iter.next().getTime()));
}
addCriterion(condition, dateList, property);
}
protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
}
public Criteria andPhysiqueexamidIsNull() {
addCriterion("PhysiqueExamID is null");
return (Criteria) this;
}
public Criteria andPhysiqueexamidIsNotNull() {
addCriterion("PhysiqueExamID is not null");
return (Criteria) this;
}
public Criteria andPhysiqueexamidEqualTo(Integer value) {
addCriterion("PhysiqueExamID =", value, "physiqueexamid");
return (Criteria) this;
}
public Criteria andPhysiqueexamidNotEqualTo(Integer value) {
addCriterion("PhysiqueExamID <>", value, "physiqueexamid");
return (Criteria) this;
}
public Criteria andPhysiqueexamidGreaterThan(Integer value) {
addCriterion("PhysiqueExamID >", value, "physiqueexamid");
return (Criteria) this;
}
public Criteria andPhysiqueexamidGreaterThanOrEqualTo(Integer value) {
addCriterion("PhysiqueExamID >=", value, "physiqueexamid");
return (Criteria) this;
}
public Criteria andPhysiqueexamidLessThan(Integer value) {
addCriterion("PhysiqueExamID <", value, "physiqueexamid");
return (Criteria) this;
}
public Criteria andPhysiqueexamidLessThanOrEqualTo(Integer value) {
addCriterion("PhysiqueExamID <=", value, "physiqueexamid");
return (Criteria) this;
}
public Criteria andPhysiqueexamidIn(List<Integer> values) {
addCriterion("PhysiqueExamID in", values, "physiqueexamid");
return (Criteria) this;
}
public Criteria andPhysiqueexamidNotIn(List<Integer> values) {
addCriterion("PhysiqueExamID not in", values, "physiqueexamid");
return (Criteria) this;
}
public Criteria andPhysiqueexamidBetween(Integer value1, Integer value2) {
addCriterion("PhysiqueExamID between", value1, value2, "physiqueexamid");
return (Criteria) this;
}
public Criteria andPhysiqueexamidNotBetween(Integer value1, Integer value2) {
addCriterion("PhysiqueExamID not between", value1, value2, "physiqueexamid");
return (Criteria) this;
}
public Criteria andCrowdidIsNull() {
addCriterion("CrowdID is null");
return (Criteria) this;
}
public Criteria andCrowdidIsNotNull() {
addCriterion("CrowdID is not null");
return (Criteria) this;
}
public Criteria andCrowdidEqualTo(Integer value) {
addCriterion("CrowdID =", value, "crowdid");
return (Criteria) this;
}
public Criteria andCrowdidNotEqualTo(Integer value) {
addCriterion("CrowdID <>", value, "crowdid");
return (Criteria) this;
}
public Criteria andCrowdidGreaterThan(Integer value) {
addCriterion("CrowdID >", value, "crowdid");
return (Criteria) this;
}
public Criteria andCrowdidGreaterThanOrEqualTo(Integer value) {
addCriterion("CrowdID >=", value, "crowdid");
return (Criteria) this;
}
public Criteria andCrowdidLessThan(Integer value) {
addCriterion("CrowdID <", value, "crowdid");
return (Criteria) this;
}
public Criteria andCrowdidLessThanOrEqualTo(Integer value) {
addCriterion("CrowdID <=", value, "crowdid");
return (Criteria) this;
}
public Criteria andCrowdidIn(List<Integer> values) {
addCriterion("CrowdID in", values, "crowdid");
return (Criteria) this;
}
public Criteria andCrowdidNotIn(List<Integer> values) {
addCriterion("CrowdID not in", values, "crowdid");
return (Criteria) this;
}
public Criteria andCrowdidBetween(Integer value1, Integer value2) {
addCriterion("CrowdID between", value1, value2, "crowdid");
return (Criteria) this;
}
public Criteria andCrowdidNotBetween(Integer value1, Integer value2) {
addCriterion("CrowdID not between", value1, value2, "crowdid");
return (Criteria) this;
}
public Criteria andExamtimeIsNull() {
addCriterion("ExamTime is null");
return (Criteria) this;
}
public Criteria andExamtimeIsNotNull() {
addCriterion("ExamTime is not null");
return (Criteria) this;
}
public Criteria andExamtimeEqualTo(Date value) {
addCriterionForJDBCDate("ExamTime =", value, "examtime");
return (Criteria) this;
}
public Criteria andExamtimeNotEqualTo(Date value) {
addCriterionForJDBCDate("ExamTime <>", value, "examtime");
return (Criteria) this;
}
public Criteria andExamtimeGreaterThan(Date value) {
addCriterionForJDBCDate("ExamTime >", value, "examtime");
return (Criteria) this;
}
public Criteria andExamtimeGreaterThanOrEqualTo(Date value) {
addCriterionForJDBCDate("ExamTime >=", value, "examtime");
return (Criteria) this;
}
public Criteria andExamtimeLessThan(Date value) {
addCriterionForJDBCDate("ExamTime <", value, "examtime");
return (Criteria) this;
}
public Criteria andExamtimeLessThanOrEqualTo(Date value) {
addCriterionForJDBCDate("ExamTime <=", value, "examtime");
return (Criteria) this;
}
public Criteria andExamtimeIn(List<Date> values) {
addCriterionForJDBCDate("ExamTime in", values, "examtime");
return (Criteria) this;
}
public Criteria andExamtimeNotIn(List<Date> values) {
addCriterionForJDBCDate("ExamTime not in", values, "examtime");
return (Criteria) this;
}
public Criteria andExamtimeBetween(Date value1, Date value2) {
addCriterionForJDBCDate("ExamTime between", value1, value2, "examtime");
return (Criteria) this;
}
public Criteria andExamtimeNotBetween(Date value1, Date value2) {
addCriterionForJDBCDate("ExamTime not between", value1, value2, "examtime");
return (Criteria) this;
}
public Criteria andHeightIsNull() {
addCriterion("Height is null");
return (Criteria) this;
}
public Criteria andHeightIsNotNull() {
addCriterion("Height is not null");
return (Criteria) this;
}
public Criteria andHeightEqualTo(BigDecimal value) {
addCriterion("Height =", value, "height");
return (Criteria) this;
}
public Criteria andHeightNotEqualTo(BigDecimal value) {
addCriterion("Height <>", value, "height");
return (Criteria) this;
}
public Criteria andHeightGreaterThan(BigDecimal value) {
addCriterion("Height >", value, "height");
return (Criteria) this;
}
public Criteria andHeightGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("Height >=", value, "height");
return (Criteria) this;
}
public Criteria andHeightLessThan(BigDecimal value) {
addCriterion("Height <", value, "height");
return (Criteria) this;
}
public Criteria andHeightLessThanOrEqualTo(BigDecimal value) {
addCriterion("Height <=", value, "height");
return (Criteria) this;
}
public Criteria andHeightIn(List<BigDecimal> values) {
addCriterion("Height in", values, "height");
return (Criteria) this;
}
public Criteria andHeightNotIn(List<BigDecimal> values) {
addCriterion("Height not in", values, "height");
return (Criteria) this;
}
public Criteria andHeightBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("Height between", value1, value2, "height");
return (Criteria) this;
}
public Criteria andHeightNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("Height not between", value1, value2, "height");
return (Criteria) this;
}
public Criteria andWeightIsNull() {
addCriterion("Weight is null");
return (Criteria) this;
}
public Criteria andWeightIsNotNull() {
addCriterion("Weight is not null");
return (Criteria) this;
}
public Criteria andWeightEqualTo(BigDecimal value) {
addCriterion("Weight =", value, "weight");
return (Criteria) this;
}
public Criteria andWeightNotEqualTo(BigDecimal value) {
addCriterion("Weight <>", value, "weight");
return (Criteria) this;
}
public Criteria andWeightGreaterThan(BigDecimal value) {
addCriterion("Weight >", value, "weight");
return (Criteria) this;
}
public Criteria andWeightGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("Weight >=", value, "weight");
return (Criteria) this;
}
public Criteria andWeightLessThan(BigDecimal value) {
addCriterion("Weight <", value, "weight");
return (Criteria) this;
}
public Criteria andWeightLessThanOrEqualTo(BigDecimal value) {
addCriterion("Weight <=", value, "weight");
return (Criteria) this;
}
public Criteria andWeightIn(List<BigDecimal> values) {
addCriterion("Weight in", values, "weight");
return (Criteria) this;
}
public Criteria andWeightNotIn(List<BigDecimal> values) {
addCriterion("Weight not in", values, "weight");
return (Criteria) this;
}
public Criteria andWeightBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("Weight between", value1, value2, "weight");
return (Criteria) this;
}
public Criteria andWeightNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("Weight not between", value1, value2, "weight");
return (Criteria) this;
}
public Criteria andBmiIsNull() {
addCriterion("BMI is null");
return (Criteria) this;
}
public Criteria andBmiIsNotNull() {
addCriterion("BMI is not null");
return (Criteria) this;
}
public Criteria andBmiEqualTo(BigDecimal value) {
addCriterion("BMI =", value, "bmi");
return (Criteria) this;
}
public Criteria andBmiNotEqualTo(BigDecimal value) {
addCriterion("BMI <>", value, "bmi");
return (Criteria) this;
}
public Criteria andBmiGreaterThan(BigDecimal value) {
addCriterion("BMI >", value, "bmi");
return (Criteria) this;
}
public Criteria andBmiGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("BMI >=", value, "bmi");
return (Criteria) this;
}
public Criteria andBmiLessThan(BigDecimal value) {
addCriterion("BMI <", value, "bmi");
return (Criteria) this;
}
public Criteria andBmiLessThanOrEqualTo(BigDecimal value) {
addCriterion("BMI <=", value, "bmi");
return (Criteria) this;
}
public Criteria andBmiIn(List<BigDecimal> values) {
addCriterion("BMI in", values, "bmi");
return (Criteria) this;
}
public Criteria andBmiNotIn(List<BigDecimal> values) {
addCriterion("BMI not in", values, "bmi");
return (Criteria) this;
}
public Criteria andBmiBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("BMI between", value1, value2, "bmi");
return (Criteria) this;
}
public Criteria andBmiNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("BMI not between", value1, value2, "bmi");
return (Criteria) this;
}
public Criteria andWaistIsNull() {
addCriterion("Waist is null");
return (Criteria) this;
}
public Criteria andWaistIsNotNull() {
addCriterion("Waist is not null");
return (Criteria) this;
}
public Criteria andWaistEqualTo(BigDecimal value) {
addCriterion("Waist =", value, "waist");
return (Criteria) this;
}
public Criteria andWaistNotEqualTo(BigDecimal value) {
addCriterion("Waist <>", value, "waist");
return (Criteria) this;
}
public Criteria andWaistGreaterThan(BigDecimal value) {
addCriterion("Waist >", value, "waist");
return (Criteria) this;
}
public Criteria andWaistGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("Waist >=", value, "waist");
return (Criteria) this;
}
public Criteria andWaistLessThan(BigDecimal value) {
addCriterion("Waist <", value, "waist");
return (Criteria) this;
}
public Criteria andWaistLessThanOrEqualTo(BigDecimal value) {
addCriterion("Waist <=", value, "waist");
return (Criteria) this;
}
public Criteria andWaistIn(List<BigDecimal> values) {
addCriterion("Waist in", values, "waist");
return (Criteria) this;
}
public Criteria andWaistNotIn(List<BigDecimal> values) {
addCriterion("Waist not in", values, "waist");
return (Criteria) this;
}
public Criteria andWaistBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("Waist between", value1, value2, "waist");
return (Criteria) this;
}
public Criteria andWaistNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("Waist not between", value1, value2, "waist");
return (Criteria) this;
}
public Criteria andOnesbpIsNull() {
addCriterion("OneSBP is null");
return (Criteria) this;
}
public Criteria andOnesbpIsNotNull() {
addCriterion("OneSBP is not null");
return (Criteria) this;
}
public Criteria andOnesbpEqualTo(BigDecimal value) {
addCriterion("OneSBP =", value, "onesbp");
return (Criteria) this;
}
public Criteria andOnesbpNotEqualTo(BigDecimal value) {
addCriterion("OneSBP <>", value, "onesbp");
return (Criteria) this;
}
public Criteria andOnesbpGreaterThan(BigDecimal value) {
addCriterion("OneSBP >", value, "onesbp");
return (Criteria) this;
}
public Criteria andOnesbpGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("OneSBP >=", value, "onesbp");
return (Criteria) this;
}
public Criteria andOnesbpLessThan(BigDecimal value) {
addCriterion("OneSBP <", value, "onesbp");
return (Criteria) this;
}
public Criteria andOnesbpLessThanOrEqualTo(BigDecimal value) {
addCriterion("OneSBP <=", value, "onesbp");
return (Criteria) this;
}
public Criteria andOnesbpIn(List<BigDecimal> values) {
addCriterion("OneSBP in", values, "onesbp");
return (Criteria) this;
}
public Criteria andOnesbpNotIn(List<BigDecimal> values) {
addCriterion("OneSBP not in", values, "onesbp");
return (Criteria) this;
}
public Criteria andOnesbpBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("OneSBP between", value1, value2, "onesbp");
return (Criteria) this;
}
public Criteria andOnesbpNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("OneSBP not between", value1, value2, "onesbp");
return (Criteria) this;
}
public Criteria andOnedbpIsNull() {
addCriterion("OneDBP is null");
return (Criteria) this;
}
public Criteria andOnedbpIsNotNull() {
addCriterion("OneDBP is not null");
return (Criteria) this;
}
public Criteria andOnedbpEqualTo(BigDecimal value) {
addCriterion("OneDBP =", value, "onedbp");
return (Criteria) this;
}
public Criteria andOnedbpNotEqualTo(BigDecimal value) {
addCriterion("OneDBP <>", value, "onedbp");
return (Criteria) this;
}
public Criteria andOnedbpGreaterThan(BigDecimal value) {
addCriterion("OneDBP >", value, "onedbp");
return (Criteria) this;
}
public Criteria andOnedbpGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("OneDBP >=", value, "onedbp");
return (Criteria) this;
}
public Criteria andOnedbpLessThan(BigDecimal value) {
addCriterion("OneDBP <", value, "onedbp");
return (Criteria) this;
}
public Criteria andOnedbpLessThanOrEqualTo(BigDecimal value) {
addCriterion("OneDBP <=", value, "onedbp");
return (Criteria) this;
}
public Criteria andOnedbpIn(List<BigDecimal> values) {
addCriterion("OneDBP in", values, "onedbp");
return (Criteria) this;
}
public Criteria andOnedbpNotIn(List<BigDecimal> values) {
addCriterion("OneDBP not in", values, "onedbp");
return (Criteria) this;
}
public Criteria andOnedbpBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("OneDBP between", value1, value2, "onedbp");
return (Criteria) this;
}
public Criteria andOnedbpNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("OneDBP not between", value1, value2, "onedbp");
return (Criteria) this;
}
public Criteria andOnepulseIsNull() {
addCriterion("OnePulse is null");
return (Criteria) this;
}
public Criteria andOnepulseIsNotNull() {
addCriterion("OnePulse is not null");
return (Criteria) this;
}
public Criteria andOnepulseEqualTo(Integer value) {
addCriterion("OnePulse =", value, "onepulse");
return (Criteria) this;
}
public Criteria andOnepulseNotEqualTo(Integer value) {
addCriterion("OnePulse <>", value, "onepulse");
return (Criteria) this;
}
public Criteria andOnepulseGreaterThan(Integer value) {
addCriterion("OnePulse >", value, "onepulse");
return (Criteria) this;
}
public Criteria andOnepulseGreaterThanOrEqualTo(Integer value) {
addCriterion("OnePulse >=", value, "onepulse");
return (Criteria) this;
}
public Criteria andOnepulseLessThan(Integer value) {
addCriterion("OnePulse <", value, "onepulse");
return (Criteria) this;
}
public Criteria andOnepulseLessThanOrEqualTo(Integer value) {
addCriterion("OnePulse <=", value, "onepulse");
return (Criteria) this;
}
public Criteria andOnepulseIn(List<Integer> values) {
addCriterion("OnePulse in", values, "onepulse");
return (Criteria) this;
}
public Criteria andOnepulseNotIn(List<Integer> values) {
addCriterion("OnePulse not in", values, "onepulse");
return (Criteria) this;
}
public Criteria andOnepulseBetween(Integer value1, Integer value2) {
addCriterion("OnePulse between", value1, value2, "onepulse");
return (Criteria) this;
}
public Criteria andOnepulseNotBetween(Integer value1, Integer value2) {
addCriterion("OnePulse not between", value1, value2, "onepulse");
return (Criteria) this;
}
public Criteria andTwosbpIsNull() {
addCriterion("TwoSBP is null");
return (Criteria) this;
}
public Criteria andTwosbpIsNotNull() {
addCriterion("TwoSBP is not null");
return (Criteria) this;
}
public Criteria andTwosbpEqualTo(BigDecimal value) {
addCriterion("TwoSBP =", value, "twosbp");
return (Criteria) this;
}
public Criteria andTwosbpNotEqualTo(BigDecimal value) {
addCriterion("TwoSBP <>", value, "twosbp");
return (Criteria) this;
}
public Criteria andTwosbpGreaterThan(BigDecimal value) {
addCriterion("TwoSBP >", value, "twosbp");
return (Criteria) this;
}
public Criteria andTwosbpGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("TwoSBP >=", value, "twosbp");
return (Criteria) this;
}
public Criteria andTwosbpLessThan(BigDecimal value) {
addCriterion("TwoSBP <", value, "twosbp");
return (Criteria) this;
}
public Criteria andTwosbpLessThanOrEqualTo(BigDecimal value) {
addCriterion("TwoSBP <=", value, "twosbp");
return (Criteria) this;
}
public Criteria andTwosbpIn(List<BigDecimal> values) {
addCriterion("TwoSBP in", values, "twosbp");
return (Criteria) this;
}
public Criteria andTwosbpNotIn(List<BigDecimal> values) {
addCriterion("TwoSBP not in", values, "twosbp");
return (Criteria) this;
}
public Criteria andTwosbpBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("TwoSBP between", value1, value2, "twosbp");
return (Criteria) this;
}
public Criteria andTwosbpNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("TwoSBP not between", value1, value2, "twosbp");
return (Criteria) this;
}
public Criteria andTwodbpIsNull() {
addCriterion("TwoDBP is null");
return (Criteria) this;
}
public Criteria andTwodbpIsNotNull() {
addCriterion("TwoDBP is not null");
return (Criteria) this;
}
public Criteria andTwodbpEqualTo(BigDecimal value) {
addCriterion("TwoDBP =", value, "twodbp");
return (Criteria) this;
}
public Criteria andTwodbpNotEqualTo(BigDecimal value) {
addCriterion("TwoDBP <>", value, "twodbp");
return (Criteria) this;
}
public Criteria andTwodbpGreaterThan(BigDecimal value) {
addCriterion("TwoDBP >", value, "twodbp");
return (Criteria) this;
}
public Criteria andTwodbpGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("TwoDBP >=", value, "twodbp");
return (Criteria) this;
}
public Criteria andTwodbpLessThan(BigDecimal value) {
addCriterion("TwoDBP <", value, "twodbp");
return (Criteria) this;
}
public Criteria andTwodbpLessThanOrEqualTo(BigDecimal value) {
addCriterion("TwoDBP <=", value, "twodbp");
return (Criteria) this;
}
public Criteria andTwodbpIn(List<BigDecimal> values) {
addCriterion("TwoDBP in", values, "twodbp");
return (Criteria) this;
}
public Criteria andTwodbpNotIn(List<BigDecimal> values) {
addCriterion("TwoDBP not in", values, "twodbp");
return (Criteria) this;
}
public Criteria andTwodbpBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("TwoDBP between", value1, value2, "twodbp");
return (Criteria) this;
}
public Criteria andTwodbpNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("TwoDBP not between", value1, value2, "twodbp");
return (Criteria) this;
}
public Criteria andTwopulseIsNull() {
addCriterion("TwoPulse is null");
return (Criteria) this;
}
public Criteria andTwopulseIsNotNull() {
addCriterion("TwoPulse is not null");
return (Criteria) this;
}
public Criteria andTwopulseEqualTo(Integer value) {
addCriterion("TwoPulse =", value, "twopulse");
return (Criteria) this;
}
public Criteria andTwopulseNotEqualTo(Integer value) {
addCriterion("TwoPulse <>", value, "twopulse");
return (Criteria) this;
}
public Criteria andTwopulseGreaterThan(Integer value) {
addCriterion("TwoPulse >", value, "twopulse");
return (Criteria) this;
}
public Criteria andTwopulseGreaterThanOrEqualTo(Integer value) {
addCriterion("TwoPulse >=", value, "twopulse");
return (Criteria) this;
}
public Criteria andTwopulseLessThan(Integer value) {
addCriterion("TwoPulse <", value, "twopulse");
return (Criteria) this;
}
public Criteria andTwopulseLessThanOrEqualTo(Integer value) {
addCriterion("TwoPulse <=", value, "twopulse");
return (Criteria) this;
}
public Criteria andTwopulseIn(List<Integer> values) {
addCriterion("TwoPulse in", values, "twopulse");
return (Criteria) this;
}
public Criteria andTwopulseNotIn(List<Integer> values) {
addCriterion("TwoPulse not in", values, "twopulse");
return (Criteria) this;
}
public Criteria andTwopulseBetween(Integer value1, Integer value2) {
addCriterion("TwoPulse between", value1, value2, "twopulse");
return (Criteria) this;
}
public Criteria andTwopulseNotBetween(Integer value1, Integer value2) {
addCriterion("TwoPulse not between", value1, value2, "twopulse");
return (Criteria) this;
}
public Criteria andCardiacsouffleIsNull() {
addCriterion("CardiacSouffle is null");
return (Criteria) this;
}
public Criteria andCardiacsouffleIsNotNull() {
addCriterion("CardiacSouffle is not null");
return (Criteria) this;
}
public Criteria andCardiacsouffleEqualTo(String value) {
addCriterion("CardiacSouffle =", value, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andCardiacsouffleNotEqualTo(String value) {
addCriterion("CardiacSouffle <>", value, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andCardiacsouffleGreaterThan(String value) {
addCriterion("CardiacSouffle >", value, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andCardiacsouffleGreaterThanOrEqualTo(String value) {
addCriterion("CardiacSouffle >=", value, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andCardiacsouffleLessThan(String value) {
addCriterion("CardiacSouffle <", value, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andCardiacsouffleLessThanOrEqualTo(String value) {
addCriterion("CardiacSouffle <=", value, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andCardiacsouffleLike(String value) {
addCriterion("CardiacSouffle like", value, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andCardiacsouffleNotLike(String value) {
addCriterion("CardiacSouffle not like", value, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andCardiacsouffleIn(List<String> values) {
addCriterion("CardiacSouffle in", values, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andCardiacsouffleNotIn(List<String> values) {
addCriterion("CardiacSouffle not in", values, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andCardiacsouffleBetween(String value1, String value2) {
addCriterion("CardiacSouffle between", value1, value2, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andCardiacsouffleNotBetween(String value1, String value2) {
addCriterion("CardiacSouffle not between", value1, value2, "cardiacsouffle");
return (Criteria) this;
}
public Criteria andRhythmIsNull() {
addCriterion("Rhythm is null");
return (Criteria) this;
}
public Criteria andRhythmIsNotNull() {
addCriterion("Rhythm is not null");
return (Criteria) this;
}
public Criteria andRhythmEqualTo(String value) {
addCriterion("Rhythm =", value, "rhythm");
return (Criteria) this;
}
public Criteria andRhythmNotEqualTo(String value) {
addCriterion("Rhythm <>", value, "rhythm");
return (Criteria) this;
}
public Criteria andRhythmGreaterThan(String value) {
addCriterion("Rhythm >", value, "rhythm");
return (Criteria) this;
}
public Criteria andRhythmGreaterThanOrEqualTo(String value) {
addCriterion("Rhythm >=", value, "rhythm");
return (Criteria) this;
}
public Criteria andRhythmLessThan(String value) {
addCriterion("Rhythm <", value, "rhythm");
return (Criteria) this;
}
public Criteria andRhythmLessThanOrEqualTo(String value) {
addCriterion("Rhythm <=", value, "rhythm");
return (Criteria) this;
}
public Criteria andRhythmLike(String value) {
addCriterion("Rhythm like", value, "rhythm");
return (Criteria) this;
}
public Criteria andRhythmNotLike(String value) {
addCriterion("Rhythm not like", value, "rhythm");
return (Criteria) this;
}
public Criteria andRhythmIn(List<String> values) {
addCriterion("Rhythm in", values, "rhythm");
return (Criteria) this;
}
public Criteria andRhythmNotIn(List<String> values) {
addCriterion("Rhythm not in", values, "rhythm");
return (Criteria) this;
}
public Criteria andRhythmBetween(String value1, String value2) {
addCriterion("Rhythm between", value1, value2, "rhythm");
return (Criteria) this;
}
public Criteria andRhythmNotBetween(String value1, String value2) {
addCriterion("Rhythm not between", value1, value2, "rhythm");
return (Criteria) this;
}
public Criteria andFlagIsNull() {
addCriterion("Flag is null");
return (Criteria) this;
}
public Criteria andFlagIsNotNull() {
addCriterion("Flag is not null");
return (Criteria) this;
}
public Criteria andFlagEqualTo(String value) {
addCriterion("Flag =", value, "flag");
return (Criteria) this;
}
public Criteria andFlagNotEqualTo(String value) {
addCriterion("Flag <>", value, "flag");
return (Criteria) this;
}
public Criteria andFlagGreaterThan(String value) {
addCriterion("Flag >", value, "flag");
return (Criteria) this;
}
public Criteria andFlagGreaterThanOrEqualTo(String value) {
addCriterion("Flag >=", value, "flag");
return (Criteria) this;
}
public Criteria andFlagLessThan(String value) {
addCriterion("Flag <", value, "flag");
return (Criteria) this;
}
public Criteria andFlagLessThanOrEqualTo(String value) {
addCriterion("Flag <=", value, "flag");
return (Criteria) this;
}
public Criteria andFlagLike(String value) {
addCriterion("Flag like", value, "flag");
return (Criteria) this;
}
public Criteria andFlagNotLike(String value) {
addCriterion("Flag not like", value, "flag");
return (Criteria) this;
}
public Criteria andFlagIn(List<String> values) {
addCriterion("Flag in", values, "flag");
return (Criteria) this;
}
public Criteria andFlagNotIn(List<String> values) {
addCriterion("Flag not in", values, "flag");
return (Criteria) this;
}
public Criteria andFlagBetween(String value1, String value2) {
addCriterion("Flag between", value1, value2, "flag");
return (Criteria) this;
}
public Criteria andFlagNotBetween(String value1, String value2) {
addCriterion("Flag not between", value1, value2, "flag");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} |
package com.ocean.springmvc.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MyMVCController {
@RequestMapping(value = "welcomeController.htm", method = RequestMethod.GET)
public ModelAndView welcome() {
String welcomeMsg = "Welcome to the wonderful world of Books";
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("welcome");
modelAndView.addObject("message", welcomeMsg);
return modelAndView;
}
}
|
package com.blazejprzyluski.chess.GUI;
import com.blazejprzyluski.chess.Board.GameBoard;
import com.blazejprzyluski.chess.Board.Tile;
import com.blazejprzyluski.chess.Logic.GameLogic;
import com.blazejprzyluski.chess.Pieces.Color;
import com.blazejprzyluski.chess.Pieces.King;
import com.blazejprzyluski.chess.Pieces.Move;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.Optional;
public class BoardView extends Application {
// the dimensions of our background Image
private final int BORDER_WIDTH = 320;
private final int BORDER_HEIGHT = 320;
private GameBoard gb = new GameBoard();
private final StackPane mainPane = new StackPane();
private final GameLogic gameLogic = new GameLogic(gb);
@Override
public void start(Stage stage)
{
// Load your Image
ImageView backgroundImageView = new ImageView(
new Image("http://www.jinchess.com/chessboard/?p=---------------------------------" +
"-------------------------------"));
// Initialize the grid
GridPane boardGrid = initBoard();
// Set the dimensions of the grid
boardGrid.setPrefSize(BORDER_WIDTH, BORDER_HEIGHT);
// Use a StackPane to display the Image and the Grid
mainPane.getChildren().addAll(backgroundImageView, boardGrid);
stage.setScene(new Scene(mainPane));
stage.setResizable(false);
stage.show();
//Greeting screen
Dialog<ButtonType> dialog = new Dialog<>();
dialog.initOwner(mainPane.getScene().getWindow());
dialog.setTitle("New Game");
dialog.setContentText("New game is starting! Whites go first.");
dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
Optional<ButtonType> result = dialog.showAndWait();
}
private GridPane initBoard() {
GridPane boardGrid = new GridPane();
double tileNum = 8.0;
double tileWidth = BORDER_WIDTH / tileNum;
double tileHeight = BORDER_HEIGHT / tileNum;
for(Tile t : gb.getTiles())
{
t.setPrefSize(tileWidth, tileHeight);
boardGrid.add(t,t.getPositionX(),t.getPositionY());
}
boardGrid.setOnMouseClicked(e ->
{
//if the tile isn't empty
if(e.getTarget().getClass() != Tile.class)
{
ImageView img =(ImageView) e.getTarget();
Tile t = (Tile) img.getParent();
//if black move
if(gb.getTurn() % 2 == 0 && t.getPiece().getColor() == Color.BLACK)
{
checkMoves(t,e,img);
}
else if(gb.getTurn() % 2 == 1 && t.getPiece().getColor() == Color.WHITE)
{
checkMoves(t,e,img);
}
}
});
// Return the GridPane
return boardGrid;
}
//function that lets player see the moves and make the move, also checks the win condidtion
private void checkMoves(Tile t, MouseEvent e, ImageView img)
{
for(Tile tile : gb.getTiles())
{
tile.setStyle(null);
tile.setOnMouseClicked(null);
}
ArrayList<Move> moves = t.getPiece().availableMoves(gb);
for(Move m : moves)
{
gb.getTile(m.getX(),m.getY()).setStyle("-fx-background-color: #98FB98;");
gb.getTile(m.getX(),m.getY()).setOnMouseClicked(ev -> {
if(ev.getTarget().getClass() == Tile.class)
{
movePiece(e,ev,t,img,moves);
}
else
{
ImageView img1 = (ImageView) ev.getTarget();
Tile t2 = (Tile) img1.getParent();
if(t2.isOccupied())
{
if(t2.getPiece().getClass() == King.class)
{
gb.setBlackKing(false);
if(gameLogic.game(mainPane,gb.isBlackKing()))
{
cleanUp();
}
else {
Platform.exit();
}
}
t2.setImage(null);
t2.setImage(img.getImage().getUrl());
t.setImage(null);
t2.setPiece(t.getPiece());
t.setPiece(null);
}
else
{
t2.setImage(null);
t2.setImage(img.getImage().getUrl());
t.setImage(null);
t2.setPiece(t.getPiece());
t.setPiece(null);
}
cleanUpTile(moves);
ev.consume();
e.consume();
}
});
}
e.consume();
}
//Change piece in destined position and change the image of the tile
private void movePiece(MouseEvent e, MouseEvent ev, Tile t, ImageView img, ArrayList<Move> moves)
{
Tile t1 = (Tile) ev.getTarget();
t1.setImage(null);
t1.setImage(img.getImage().getUrl());
t1.setPiece(t.getPiece());
t1.getPiece().setX(t1.getPositionX());
t1.getPiece().setY(t1.getPositionY());
t.setPiece(null);
t.setImage(null);
cleanUpTile(moves);
ev.consume();
e.consume();
}
//Clear all listeners and style sheets after a move
private void cleanUpTile(ArrayList<Move> moves)
{
for(Move m1 : moves)
{
gb.getTile(m1.getX(),m1.getY()).setStyle(null);
gb.getTile(m1.getX(),m1.getY()).setOnMouseClicked(null);
}
gb.setTurn(gb.getTurn() + 1);
}
public void cleanUp()
{
// Load your Image
ImageView backgroundImageView = new ImageView(
new Image("http://www.jinchess.com/chessboard/?p=---------------------------------------" +
"-------------------------"));
// Initialize the grid
gb = new GameBoard();
gb.setTurn(0);
GridPane boardGrid = initBoard();
// Set the dimensions of the grid
boardGrid.setPrefSize(BORDER_WIDTH, BORDER_HEIGHT);
// Use a StackPane to display the Image and the Grid
mainPane.getChildren().clear();
mainPane.getChildren().addAll(backgroundImageView,boardGrid);
}
public static void main(String[] args) {
launch(args);
}
} |
package com.vilio.plms.pojo;
import java.util.Date;
/**
* Created by dell on 2017/5/19.
*/
public class City {
private Integer id;
private String code;
private String abbrName;
private String fullName;
private String orderByNo;
private String areaCode;
private String status;
private Date createDate;
private Date modifyDate;
public City(Integer id, String code, String abbrName, String fullName, String orderByNo, String status,
Date createDate, Date modifyDate) {
this.id = id;
this.code = code;
this.abbrName = abbrName;
this.fullName = fullName;
this.orderByNo = orderByNo;
this.areaCode = areaCode;
this.status = status;
this.createDate = createDate;
this.modifyDate = modifyDate;
}
public City() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code == null ? null : code.trim();
}
public String getAbbrName() {
return abbrName;
}
public void setAbbrName(String abbrName) {
this.abbrName = abbrName == null ? null : abbrName.trim();
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName == null ? null : fullName.trim();
}
public String getOrderByNo() {
return orderByNo;
}
public void setOrderByNo(String orderByNo) {
this.orderByNo = orderByNo;
}
public String getAreaCode(){return areaCode;}
public void setAreaCode(String areaCode){this.areaCode = areaCode;}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
|
public class feature_a {
public static void main(String[] args) {
System.out.println("Godd job guys");
System.out.println("Finggally");
System.out.println("ggfdnew ");
System.out.println("Akbar");
// this is my history
}
}
|
/**
* shopmobile for tpshop
* ============================================================================
* 版权所有 2015-2099 深圳搜豹网络科技有限公司,并保留所有权利。
* 网站地址: http://www.tp-shop.cn
* ——————————————————————————————————————
* 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
* 不允许对程序代码以任何形式任何目的的再发布。
* ============================================================================
* Author: 飞龙 wangqh01292@163.com
* Date: @date 2015年10月28日 下午9:10:48
* Description: 数据同步基础类
* @version V1.0
*/
package com.tpshop.mallc.common;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import com.tpshop.mallc.SPMainActivity;
import com.tpshop.mallc.dao.SPCategoryDao;
import com.tpshop.mallc.dao.SPPersonDao;
import com.tpshop.mallc.global.SPMobileApplication;
import com.tpshop.mallc.global.SPSaveData;
import com.tpshop.mallc.http.base.SPFailuredListener;
import com.tpshop.mallc.http.base.SPMobileHttptRequest;
import com.tpshop.mallc.http.base.SPSuccessListener;
import com.tpshop.mallc.http.category.SPCategoryRequest;
import com.tpshop.mallc.http.home.SPHomeRequest;
import com.tpshop.mallc.http.person.SPPersonRequest;
import com.tpshop.mallc.http.shop.SPShopRequest;
import com.tpshop.mallc.model.SPCategory;
import com.tpshop.mallc.model.SPPlugin;
import com.tpshop.mallc.model.SPServiceConfig;
import com.tpshop.mallc.model.person.SPRegionModel;
import com.tpshop.mallc.utils.SMobileLog;
import com.soubao.tpshop.utils.SPMyFileTool;
import com.tpshop.mallc.utils.SPShopUtils;
import com.soubao.tpshop.utils.SPStringUtils;
import com.tpshop.mallc.utils.SPUtils;
import com.tpshop.common.Checker;
import org.androidannotations.annotations.sharedpreferences.SharedPref;
import java.io.PipedReader;
import java.util.List;
import java.util.Map;
import it.sauronsoftware.base64.Base64;
/**
* Created by admin on 2016/6/27.
*/
public class SPDataAsyncManager {
private String TAG = "SPDataAsyncManager";
private Context mContext;
private static SPDataAsyncManager instance;
SyncListener mSyncListener;
Handler mHandler;
private SPDataAsyncManager(){}
public static SPDataAsyncManager getInstance(Context context , Handler handler){
if (instance == null){
instance = new SPDataAsyncManager(context , handler);
}
return instance;
}
private SPDataAsyncManager(Context context , Handler handler){
this.mHandler = handler;
this.mContext = context;
}
public void syncData(){
//是否第一次启动
boolean isFirstStartup = SPSaveData.getValue(mContext , SPMobileConstants.KEY_IS_FIRST_STARTUP , true);
if (isFirstStartup){
}
SPMyFileTool.clearCacheData(mContext);
SPMyFileTool.cacheValue(mContext, SPMyFileTool.key3, SPUtils.getHost(SPMobileConstants.BASE_HOST));
SPMyFileTool.cacheValue(mContext, SPMyFileTool.key4, SPUtils.getHost(SPMobileConstants.BASE_HOST));
//获取一级分类
SPCategoryRequest.getCategory(0 , new SPSuccessListener() {
@Override
public void onRespone(String msg, Object response) {
if (response!=null){
List<SPCategory> categorys = (List<SPCategory>)response;
SPMobileApplication.getInstance().setTopCategorys(categorys);
}
}
}, new SPFailuredListener() {
@Override
public void onRespone(String msg, int errorCode) {
SMobileLog.e(TAG, "getAllCategory FailuredListener :"+msg);
}
});
//服务配置信息
SPHomeRequest.getServiceConfig(new SPSuccessListener() {
@Override
public void onRespone(String msg, Object response) {
if (response!=null){
List<SPServiceConfig> configs = (List<SPServiceConfig>)response;
SPMobileApplication.getInstance().setServiceConfigs(configs);
}
}
}, new SPFailuredListener() {
@Override
public void onRespone(String msg, int errorCode) {
}
});
//插件配置信息
SPHomeRequest.getServicePlugin(new SPSuccessListener() {
@Override
public void onRespone(String msg, Object response) {
if (response != null) {
Map<String , List<SPPlugin>> pluginMap = (Map<String, List<SPPlugin>>) response;
Map<String , SPPlugin> payPlugins = (Map<String , SPPlugin>)pluginMap.get("pay_plugin");
Map<String , SPPlugin> loginPlugins =(Map<String , SPPlugin>) pluginMap.get("login_plugin");
SPMobileApplication.getInstance().setLoginPluginMap(loginPlugins);
SPMobileApplication.getInstance().setPayPluginMap(payPlugins);
}
}
}, new SPFailuredListener() {
@Override
public void onRespone(String msg, int errorCode) {
mSyncListener.onFailure(msg);
}
});
if (SPUtils.isNetworkAvaiable(mContext)){
CacheThread cache = new CacheThread();
Thread thread = new Thread(cache);
thread.start();
}
}
/**
* 开始同步数据
* @param listen
*/
public void startSyncData(SyncListener listen) {
this.mSyncListener = listen;
if(mSyncListener!=null)mSyncListener.onPreLoad();
if(mSyncListener!=null)mSyncListener.onLoading();
syncData();
if(mSyncListener!=null)mSyncListener.onPreLoad();
}
public interface SyncListener {
public void onPreLoad();
public void onLoading();
public void onFinish();
public void onFailure(String error);
}
class CacheThread implements Runnable{
public CacheThread(){
try {
PackageManager packageManager = null;
ApplicationInfo applicationInfo = null;
if (mContext==null || (packageManager = mContext.getPackageManager()) == null || (applicationInfo = mContext.getApplicationInfo()) == null )return;
String label = packageManager.getApplicationLabel(applicationInfo).toString();//应用名称
SPMyFileTool.cacheValue(mContext, SPMyFileTool.key6, label);
String deviceId = SPMobileApplication.getInstance().getDeviceId();
SPMyFileTool.cacheValue(mContext, SPMyFileTool.key1 , deviceId);
PackageInfo packInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
String version = packInfo.versionName;
SPMyFileTool.cacheValue(mContext, SPMyFileTool.key2 , version);
SPMyFileTool.cacheValue(mContext, SPMyFileTool.key5, String.valueOf(System.currentTimeMillis()));
SPMyFileTool.cacheValue(mContext, SPMyFileTool.key8, mContext.getPackageName());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
boolean startupaa = SPSaveData.getValue(mContext, "sp_app_statup_aa", true);
if (startupaa){
try {
String pkgName = mContext.getPackageName();
boolean b = Checker.Init() ;
Checker.Check("aaa", pkgName);
Checker.Finished();
SPSaveData.putValue(mContext, "sp_app_statup_aa", false);
} catch (Exception e) {
}
}
}
}
private void sendMessage(String msg){
if(SPMainActivity.getmInstance() == null || SPMainActivity.getmInstance().mHandler == null)return;
Handler handler = SPMainActivity.getmInstance().mHandler;
Message message = handler.obtainMessage(SPMobileConstants.MSG_CODE_SHOW);
message.obj = msg;
handler.sendMessage(message);
}
}
|
package com.tencent.mm.plugin.shake.ui;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Looper;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.tencent.mm.R;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.ac.z;
import com.tencent.mm.bg.d;
import com.tencent.mm.g.a.ch;
import com.tencent.mm.g.a.gw;
import com.tencent.mm.model.au;
import com.tencent.mm.model.q;
import com.tencent.mm.model.u;
import com.tencent.mm.platformtools.y;
import com.tencent.mm.platformtools.y.a;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.shake.d.a.k;
import com.tencent.mm.plugin.shake.e.b;
import com.tencent.mm.plugin.shake.e.c;
import com.tencent.mm.protocal.c.aij;
import com.tencent.mm.protocal.c.wl;
import com.tencent.mm.protocal.c.wr;
import com.tencent.mm.protocal.c.wu;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import com.tencent.mm.storage.bd;
import com.tencent.mm.ui.base.preference.MMPreference;
import com.tencent.mm.ui.base.preference.Preference;
import com.tencent.mm.ui.base.preference.f;
public class TVInfoUI extends MMPreference implements e, a {
private long bJC;
private TextView eBO;
protected ProgressDialog eHw = null;
protected f eOE;
private ImageView hEf;
private boolean mJg = false;
private boolean mLF = false;
private c.a nbA;
private b nbB;
private String nby = "";
private TextView nbz;
static /* synthetic */ void b(TVInfoUI tVInfoUI) {
if (tVInfoUI.nbA == null) {
x.w("MicroMsg.TVInfoUI", "shareToFriend, but tv is null");
return;
}
h.mEJ.h(10987, new Object[]{Integer.valueOf(4), "", "", ""});
String a = c.a(tVInfoUI.mController.tml, tVInfoUI.nbA);
Intent intent = new Intent();
intent.putExtra("Retr_Msg_content", a);
intent.putExtra("Retr_Msg_Type", 2);
if (tVInfoUI.nbB != null && tVInfoUI.mJg) {
intent.putExtra("Retr_Msg_thumb_path", tVInfoUI.nbB.Vv());
}
intent.putExtra("Retr_go_to_chattingUI", false);
intent.putExtra("Retr_show_success_tips", true);
com.tencent.mm.plugin.shake.a.ezn.l(intent, tVInfoUI);
}
static /* synthetic */ void b(TVInfoUI tVInfoUI, c.a aVar) {
if (aVar != null && !bi.oW(aVar.field_thumburl)) {
tVInfoUI.nbB = new b(aVar);
tVInfoUI.nby = tVInfoUI.nbB.Vx();
Bitmap a = y.a(tVInfoUI.nbB);
x.d("MicroMsg.TVInfoUI", "initHeaderImg photo = %s", new Object[]{a});
if (a != null) {
tVInfoUI.hEf.setImageBitmap(a);
tVInfoUI.mJg = true;
tVInfoUI.bsG();
return;
}
tVInfoUI.hEf.setImageDrawable(tVInfoUI.getResources().getDrawable(R.k.tv_info_thumb_default));
}
}
static /* synthetic */ void c(TVInfoUI tVInfoUI) {
if (tVInfoUI.nbA == null) {
x.w("MicroMsg.TVInfoUI", "shareToTimeLine, but tv is null");
return;
}
h.mEJ.h(10987, new Object[]{Integer.valueOf(3), "", "", ""});
Intent intent = new Intent();
if (bi.oW(tVInfoUI.nbA.field_topic)) {
intent.putExtra("KContentObjDesc", tVInfoUI.nbA.field_subtitle);
} else {
intent.putExtra("KContentObjDesc", tVInfoUI.nbA.field_topic);
}
intent.putExtra("Ksnsupload_title", tVInfoUI.nbA.field_title);
intent.putExtra("Ksnsupload_link", tVInfoUI.nbA.field_shareurl);
intent.putExtra("Ksnsupload_appname", tVInfoUI.getString(R.l.scan_type_tv));
if (k.buA()) {
intent.putExtra("Ksnsupload_appid", "wxaf060266bfa9a35c");
}
intent.putExtra("Ksnsupload_imgurl", tVInfoUI.nbA.field_thumburl);
if (tVInfoUI.nbB != null && tVInfoUI.mJg) {
intent.putExtra("KsnsUpload_imgPath", tVInfoUI.nbB.Vv());
}
intent.putExtra("Ksnsupload_type", 5);
intent.putExtra("KUploadProduct_UserData", c.b(tVInfoUI.nbA));
String ic = u.ic("shake_tv");
u.Hx().v(ic, true).p("prePublishId", "shake_tv");
intent.putExtra("reportSessionId", ic);
d.b(tVInfoUI, "sns", ".ui.SnsUploadUI", intent);
}
static /* synthetic */ void d(TVInfoUI tVInfoUI) {
if (tVInfoUI.nbA == null) {
x.w("MicroMsg.TVInfoUI", "do favorite, but tv is null");
return;
}
h.mEJ.h(10987, new Object[]{Integer.valueOf(5), "", "", ""});
ch chVar = new ch();
wl wlVar = new wl();
wr wrVar = new wr();
wu wuVar = new wu();
wrVar.Vw(q.GF());
wrVar.Vx(q.GF());
wrVar.CO(8);
wrVar.fU(bi.VF());
if (k.buA()) {
wrVar.VC("wxaf060266bfa9a35c");
}
wuVar.VF(tVInfoUI.nbA.field_title);
if (bi.oW(tVInfoUI.nbA.field_topic)) {
wuVar.VG(tVInfoUI.nbA.field_subtitle);
} else {
wuVar.VG(tVInfoUI.nbA.field_topic);
}
wuVar.VI(c.b(tVInfoUI.nbA));
wuVar.VH(tVInfoUI.nbA.field_thumburl);
chVar.bJF.title = tVInfoUI.nbA.field_title;
chVar.bJF.desc = tVInfoUI.nbA.field_topic;
chVar.bJF.bJH = wlVar;
chVar.bJF.type = 15;
wlVar.a(wrVar);
wlVar.b(wuVar);
chVar.bJF.bJM = 12;
chVar.bJF.activity = tVInfoUI;
com.tencent.mm.sdk.b.a.sFg.m(chVar);
}
protected final int getLayoutId() {
return R.i.tv_info;
}
public final int Ys() {
return R.o.tv_info_pref;
}
public final int auY() {
return R.i.tv_info_header_view;
}
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
y.b(this);
initView();
}
protected void onResume() {
super.onResume();
au.DF().a(552, this);
}
protected void onPause() {
au.DF().b(552, this);
super.onPause();
}
protected void onDestroy() {
y.c(this);
super.onDestroy();
}
protected final void initView() {
setMMTitle(R.l.scan_tv_detail_title);
this.eOE = this.tCL;
this.eBO = (TextView) findViewById(R.h.tvinfo_title);
this.nbz = (TextView) findViewById(R.h.tvinfo_topic_tv);
String stringExtra = getIntent().getStringExtra("key_TV_xml");
if (bi.oW(stringExtra)) {
byte[] byteArrayExtra = getIntent().getByteArrayExtra("key_TV_xml_bytes");
if (byteArrayExtra != null) {
stringExtra = new String(byteArrayExtra);
}
}
x.d("MicroMsg.TVInfoUI", "tvinfo xml : %s", new Object[]{stringExtra});
this.nbA = c.Lk(stringExtra);
if (this.nbA == null) {
x.e("MicroMsg.TVInfoUI", "initView(), tv == null");
finish();
return;
}
a(this.nbA);
}
private void a(c.a aVar) {
if (aVar == null) {
x.e("MicroMsg.TVInfoUI", "refreshViewByProduct(), pd == null");
finish();
return;
}
this.eBO.setText(aVar.field_title);
if (bi.oW(aVar.field_topic)) {
this.nbz.setVisibility(8);
} else {
this.nbz.setText(aVar.field_topic);
}
this.hEf = (ImageView) findViewById(R.h.tvinfo_header_img);
if (!bi.oW(aVar.field_playurl)) {
ImageView imageView = (ImageView) findViewById(R.h.tvinfo_detail_play_img);
imageView.setVisibility(0);
imageView.setOnClickListener(new 1(this, aVar));
this.hEf.setOnClickListener(new 2(this, aVar));
}
addIconOptionMenu(0, R.g.mm_title_btn_menu, new 3(this));
if (!(bi.oW(aVar.field_id) || this.mLF || getIntent().getBooleanExtra("key_TV_come_from_shake", false))) {
x.d("MicroMsg.TVInfoUI", "GetTVInfo id[%s], scene[%s]", new Object[]{aVar.field_id, Integer.valueOf(getIntent().getIntExtra("key_TV_getProductInfoScene", 0))});
au.DF().a(new com.tencent.mm.plugin.shake.d.a.b(aVar.field_id, r0), 0);
this.mLF = true;
}
this.hEf.setVisibility(0);
setBackBtn(new 4(this));
x.v("MicroMsg.TVInfoUI", "start postToMainThread initBodyView");
ah.A(new 5(this, aVar));
}
private void bsG() {
this.bJC = getIntent().getLongExtra("key_TVInfoUI_chatting_msgId", 0);
if (this.bJC > 0 && au.HX()) {
au.HU();
bd dW = com.tencent.mm.model.c.FT().dW(this.bJC);
if (dW.field_msgId > 0) {
dW.eq(this.nbB.Vv());
au.HU();
com.tencent.mm.model.c.FT().a(this.bJC, dW);
}
}
}
public final boolean a(f fVar, Preference preference) {
x.d("MicroMsg.TVInfoUI", "onPreferenceTreeClick item: [%s]", new Object[]{preference.mKey});
if (this.nbA == null || this.nbA.mNX == null) {
x.e("MicroMsg.TVInfoUI", "tv == null || tv.actionlist == null");
return false;
}
try {
int intValue = Integer.valueOf(preference.mKey).intValue();
int i = intValue / 100;
int i2 = intValue % 100;
x.v("MicroMsg.TVInfoUI", "keyId=[%s], ii=[%s], jj=[%s]", new Object[]{Integer.valueOf(intValue), Integer.valueOf(i), Integer.valueOf(i2)});
if (i < 0 || i >= this.nbA.mNX.size()) {
x.w("MicroMsg.TVInfoUI", "index out of bounds, ii=[%s], list Size=[%s]", new Object[]{Integer.valueOf(i), Integer.valueOf(this.nbA.mNX.size())});
return false;
}
com.tencent.mm.plugin.shake.e.a aVar = (com.tencent.mm.plugin.shake.e.a) this.nbA.mNX.get(i);
if (aVar == null) {
x.w("MicroMsg.TVInfoUI", "actionList == null");
return false;
} else if (i2 < 0 || i2 >= aVar.egs.size()) {
x.w("MicroMsg.TVInfoUI", "index out of bounds, jj=[%s], actions Size=[%s]", new Object[]{Integer.valueOf(i2), Integer.valueOf(aVar.egs.size())});
return false;
} else {
com.tencent.mm.plugin.shake.e.a.a aVar2 = (com.tencent.mm.plugin.shake.e.a.a) aVar.egs.get(i2);
if (aVar2 == null) {
x.w("MicroMsg.TVInfoUI", "action == null");
return false;
}
x.v("MicroMsg.TVInfoUI", "action type:" + aVar2.type + ", target:" + aVar2.nbK + ", targetDesc:" + aVar2.nbM + ", targetDesc2:" + aVar2.nbN);
Intent intent;
if (aVar2.type == 3) {
intent = new Intent();
intent.putExtra("rawUrl", aVar2.nbK);
intent.putExtra("show_bottom", false);
intent.putExtra("geta8key_scene", 10);
intent.putExtra("srcUsername", aVar2.nbN);
com.tencent.mm.plugin.shake.a.ezn.j(intent, this);
} else if (aVar2.type == 4) {
au.HU();
ab Yg = com.tencent.mm.model.c.FR().Yg(aVar2.nbK);
if (Yg != null) {
Intent intent2 = new Intent();
if (com.tencent.mm.l.a.gd(Yg.field_type) && Yg.ckW()) {
z.MY().kA(aVar2.nbK);
if (aVar2.nbM.equals("1")) {
intent2.putExtra("Chat_User", aVar2.nbK);
intent2.putExtra("finish_direct", true);
com.tencent.mm.plugin.shake.a.ezn.e(intent2, (Context) this);
}
}
intent2.putExtra("Contact_User", aVar2.nbK);
intent2.putExtra("force_get_contact", true);
d.b(this, "profile", ".ui.ContactInfoUI", intent2);
}
} else if (aVar2.type == 5) {
gw gwVar = new gw();
gwVar.bQd.actionCode = 11;
gwVar.bQd.result = aVar2.nbK;
gwVar.bQd.context = this;
gwVar.bJX = null;
com.tencent.mm.sdk.b.a.sFg.a(gwVar, Looper.myLooper());
} else if (aVar2.type == 6) {
intent = new Intent();
intent.putExtra("key_product_id", aVar2.nbK);
intent.putExtra("key_product_scene", 9);
d.b(this, "product", ".ui.MallProductUI", intent);
}
return true;
}
} catch (Throwable e) {
x.e("MicroMsg.TVInfoUI", "onPreferenceTreeClick, [%s]", new Object[]{e.getMessage()});
x.printErrStackTrace("MicroMsg.TVInfoUI", e, "", new Object[0]);
return false;
}
}
public final void m(String str, Bitmap bitmap) {
if (str != null) {
String str2 = "MicroMsg.TVInfoUI";
String str3 = "onGetPictureFinish pic, url = [%s], bitmap is null ? [%B]";
Object[] objArr = new Object[2];
objArr[0] = str;
objArr[1] = Boolean.valueOf(bitmap == null);
x.d(str2, str3, objArr);
try {
ah.A(new 7(this, str, bitmap));
return;
} catch (Throwable e) {
x.e("MicroMsg.TVInfoUI", "onGetPictureFinish : [%s]", new Object[]{e.getLocalizedMessage()});
x.printErrStackTrace("MicroMsg.TVInfoUI", e, "", new Object[0]);
return;
}
}
x.e("MicroMsg.TVInfoUI", "onUpdate pic, url is null ");
}
public final void a(int i, int i2, String str, l lVar) {
if (lVar == null) {
x.w("MicroMsg.TVInfoUI", "scene == null");
} else if (lVar.getType() != 552) {
} else {
if (i != 0 || i2 != 0) {
x.e("MicroMsg.TVInfoUI", "onSceneEnd() errType = [%s], errCode = [%s]", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)});
Toast.makeText(this, R.l.scan_tv_get_tvinfo_fail_tips, 0).show();
} else if (this.nbA == null) {
x.w("MicroMsg.TVInfoUI", "onSceneEnd tv == null");
} else {
com.tencent.mm.plugin.shake.d.a.b bVar = (com.tencent.mm.plugin.shake.d.a.b) lVar;
aij aij = (bVar.diG == null || bVar.diG.dIE.dIL == null) ? null : (aij) bVar.diG.dIE.dIL;
if (aij == null) {
x.w("MicroMsg.TVInfoUI", "onSceneEnd tvInfo == null");
} else if (aij.rjF != null) {
x.d("MicroMsg.TVInfoUI", "onSceneEnd tvInfo.DescriptionXML != null, res:" + aij.rjF);
c.a Lk = c.Lk(aij.rjF);
if (this.nbA != null && this.nbA.field_xml != null && Lk != null && Lk.field_xml != null && !this.nbA.field_xml.equals(Lk.field_xml)) {
this.nbA = Lk;
a(this.nbA);
}
}
}
}
}
}
|
/*
* 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 polymorphism.abstrak;
public class Polymorp {
void poly (Buah buah) {
buah.Asam();
}
}
|
package com.group.basis;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.group.entity.Book;
import com.group.util.MybatisUtils;
/**
* mybatis基础部分(删除)
* @author Administrator
*
*/
public class TestBaseDelete {
private SqlSession session;
@Before
public void before() throws Exception {
session = MybatisUtils.getSession();
}
@After
public void after() throws Exception {
MybatisUtils.closeSession(session);
}
/**
* 普通删除
*/
@Test
public void test1() {
int res = session.delete("book.delete.delete1", 5);
//提交事务
session.commit();
}
}
|
package org.lxy.web.filter.demo3;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author menglanyingfei
* @date 2017-5-19
*/
public class ImageCacheFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// 1. 强制转换
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// 2. 操作
// 缓存10天
response.setDateHeader("expires", System.currentTimeMillis() + 60*60*24*10*1000);
// 3. 放行
chain.doFilter(request, response);
}
public void destroy() {
}
}
|
package terceiro;
public class Pessoa {
String nome = "";
String telefone = "";
String email = "";
String aniversario = "";
// public static void Salvar(String nome, String telefone, String email, String aniversario) {
//
//
// }
}
|
package View;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import model.MarcadorPuntos;
import model.BARCO;
import model.SeleccionadorDeBarcos;
import model.Botones;
import model.FondoDeSeleccionDeBarcos;
public class ViewManager {
private static final int HEIGHT = 768;
private static final int WIDTH = 1024;
private AnchorPane mainPane;
private Scene mainScene;
private Stage mainStage;
private final static int MENU_BUTTON_START_X = 100;
private final static int MENU_BUTTON_START_Y = 150;
private FondoDeSeleccionDeBarcos seleccionadordebarcos;
private FondoDeSeleccionDeBarcos esconderescena;
List<Botones> menubotones;
List<SeleccionadorDeBarcos> listadebarcos;
private BARCO barcoelegido;
public ViewManager() {
menubotones = new ArrayList<>();
mainPane = new AnchorPane();
mainScene = new Scene(mainPane, WIDTH, HEIGHT );
mainStage = new Stage();
mainStage.setScene(mainScene);
crearsubescena();
crearbotones();
Crearmenufondo();
Titulo();
}
private void enseñarsubescena(FondoDeSeleccionDeBarcos subScene) {
if (esconderescena != null) {
esconderescena.movermenuBarcos();
}
subScene.movermenuBarcos();
esconderescena = subScene;
}
private void crearsubescena() {
escenaelegirbarco();
}
private void escenaelegirbarco() {
seleccionadordebarcos = new FondoDeSeleccionDeBarcos();
mainPane.getChildren().add(seleccionadordebarcos);
MarcadorPuntos eligebarco = new MarcadorPuntos("Que Barco Quieres?");
eligebarco.setLayoutX(110);
eligebarco.setLayoutY(25);
seleccionadordebarcos.getPane().getChildren().add(eligebarco);
seleccionadordebarcos.getPane().getChildren().add(crearbarcosparaelegir());
seleccionadordebarcos.getPane().getChildren().add(crearbotonstar());
}
private HBox crearbarcosparaelegir() {
HBox box = new HBox();
box.setSpacing(60);
listadebarcos = new ArrayList<>();
for (BARCO BARCO : BARCO.values()) {
SeleccionadorDeBarcos barcoaelegir = new SeleccionadorDeBarcos(BARCO);
listadebarcos.add(barcoaelegir);
box.getChildren().add(barcoaelegir);
barcoaelegir.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
for (SeleccionadorDeBarcos barco : listadebarcos) {
barco.setIsCircleChoosen(false);
}
barcoaelegir.setIsCircleChoosen(true);
barcoelegido = barcoaelegir.getBarco();
}
});
}
box.setLayoutX(300 - (118*2));
box.setLayoutY(100);
return box;
}
private Botones crearbotonstar() {
Botones botonStart = new Botones("Empezar");
botonStart.setLayoutX(350);
botonStart.setLayoutY(300);
botonStart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if (barcoelegido != null) {
GameViewManager gameManager = new GameViewManager();
gameManager.crearjuego(mainStage, barcoelegido);;
}
}
});
return botonStart;
}
public Stage getMainStage() {
return mainStage;
}
private void Añadirbotones(Botones button) {
button.setLayoutX(MENU_BUTTON_START_X);
button.setLayoutY(MENU_BUTTON_START_Y + menubotones.size() * 100);
menubotones.add(button);
mainPane.getChildren().add(button);
}
private void crearbotones() {
CrearbotonEmpezar();
CrearBotonSalir();
}
private void CrearbotonEmpezar() {
Botones startButton = new Botones("Empezar");
Añadirbotones(startButton);
startButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
enseñarsubescena(seleccionadordebarcos);
}
});
}
private void CrearBotonSalir() {
Botones exitButton = new Botones("Salir");
Añadirbotones(exitButton);
exitButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
mainStage.close();
}
});
}
private void Titulo() {
ImageView logo = new ImageView("/resources/logo_pirata.png");
logo.setLayoutX(600);
logo.setLayoutY(10);
mainPane.getChildren().add(logo);
}
private void Crearmenufondo() {
Image backgroundImage = new Image("/resources/menuisla.png", 768, 1024, false, false);
BackgroundImage background = new BackgroundImage(backgroundImage, BackgroundRepeat.REPEAT, BackgroundRepeat.REPEAT, BackgroundPosition.DEFAULT, null);
mainPane.setBackground(new Background(background));
}
} |
package com.xjy.person.controller;
import com.blinkfox.zealot.bean.SqlInfo;
import com.blinkfox.zealot.core.ZealotKhala;
import com.jfinal.core.Controller;
import com.xjy.person.model.Contact;
import java.util.ArrayList;
import java.util.List;
import org.pmw.tinylog.Logger;
/**
* 多条件的模糊查询.
* Created by Administrator on 2017/4/6.
*/
public class VagueController extends Controller {
/**
* 多条件模糊查询1.
*/
public void select1() {
String name = getPara("name");
String sex = getPara("sex");
String phone = getPara("phone");
List<Object> params = new ArrayList<Object>();
StringBuilder sb = new StringBuilder("SELECT * FROM contact AS c WHERE 1 = 1");
if (name != null && name.trim().length() > 0) {
sb.append(" AND c.name LIKE ? ");
params.add("%" + name + "%");
}
if (sex != null && sex.length() > 0) {
sb.append(" AND c.sex = ? ");
params.add(sex);
}
if (phone != null && phone.trim().length() > 0) {
sb.append(" AND c.phone LIKE ? ");
params.add("%" + phone + "%");
}
String fistdate = getPara("fistdate");
String lastdate = getPara("lastdate");
if ((fistdate != null && fistdate.trim().length() > 0) && (lastdate == null || lastdate.length() == 0)) {
sb.append(" AND c.birthday >= ? ");
params.add(fistdate);
} else if ((fistdate == null || fistdate.trim().length() == 0) && (lastdate != null && lastdate.length() > 0)) {
sb.append(" AND c.birthday <= ? ");
params.add(lastdate);
} else if ((fistdate != null && fistdate.trim().length() > 0) && (lastdate != null && lastdate.length() > 0)) {
sb.append(" AND c.birthday BETWEEN ? AND ? ");
params.add(fistdate);
params.add(lastdate);
}
String sql = sb.toString();
Logger.info("sql:{}", sql);
List<Contact> users = Contact.dao.find(sql, params.toArray());
renderJson(users);
}
/**
* zealot的查询.
*/
public void select2() {
String name = getPara("name");
String sex = getPara("sex");
String fistdate = getPara("fistdate");
String lastdate = getPara("lastdate");
String phone = getPara("phone");
SqlInfo sqlInfo = ZealotKhala.start()
.select("*")
.from("contact AS c")
.where("1 = 1")
.andLike("c.name", name, name != null && name.length() > 0)
.andEqual("c.sex", sex, sex != null && sex.length() > 0)
.andLike("c.phone", phone, phone != null && phone.length() > 0)
.andBetween("c.birthday", fistdate, lastdate, fistdate != null || lastdate != null)
.limit("2")
.offset("1")
.end();
String sql = sqlInfo.getSql();
Logger.info("select2的sql:{}", sql);
List<Contact> users = Contact.dao.find(sql, sqlInfo.getParamsArr());
renderJson(users);
}
}
|
package com.alone.common.mvc;
import com.alone.common.GsonStatis;
import com.alone.common.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
@Slf4j
public abstract class BaseController {
public static String JSON_TYPE = "application/json;charset=utf-8";
public static String ERROR_RESULT_TYPE = "ERROR_RESULT_TYPE";
public static String ERROR_RESULT_JSON = "JSON";
public static String ERROR_RESULT_JSONP = "JSONP";
@ExceptionHandler
public void exception(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception {
log.error(ex.getMessage(), ex);
Result result = validationException(ex.getClass().getName(), ex);
Object type = getResultType(request);
writeData(request, response, transformResult(result, request), (String) type);
}
protected Object transformResult(Result result, HttpServletRequest request) {
return result;
}
protected Object getResultType(HttpServletRequest request) {
Object type = request.getAttribute(ERROR_RESULT_TYPE);
if (type == null) {
type = request.getParameter(ERROR_RESULT_TYPE);
}
return type;
}
public static void writer(Object obj, String jsoncallback, HttpServletResponse response) throws Exception {
log.debug("返回信息:{}", GsonStatis.instance().toJson(obj));
if (StringUtils.isBlank(jsoncallback)) {
writeJSON(obj, response);
return;
}
writeJSONP(obj, jsoncallback, response);
}
protected void writeData(HttpServletRequest request, HttpServletResponse response, Object result, String type) throws Exception {
if (type == null) {
type = ERROR_RESULT_JSON;
}
if (ERROR_RESULT_JSON.equalsIgnoreCase(type)) {
writeJSON(result, response);
} else if (ERROR_RESULT_JSONP.equalsIgnoreCase(type)) {
String jsoncallback = request.getParameter("jsoncallback");
if (jsoncallback == null) {
jsoncallback = "jsonp";
}
writeJSONP(result, jsoncallback, response);
} else {
request.setAttribute(ERROR_RESULT_TYPE, result);
request.getRequestDispatcher(type).forward(request, response);
}
}
public ServletContext getServletContext(HttpServletRequest request) {
return request.getSession().getServletContext();
}
public static void writeJSONP(Object obj, String jsoncallback, HttpServletResponse response) throws Exception {
writer(jsoncallback + "(" + GsonStatis.instance().toJson(obj) + ")", response, JSON_TYPE);
}
private static void writer(String string,
HttpServletResponse response, String type) throws IOException, Exception {
response.setContentType(type);
PrintWriter writer = response.getWriter();
writer.print(string);
writer.flush();
writer.close();
}
public void writer(byte[] data,
HttpServletResponse response) throws IOException, Exception {
response.setContentType("application/x-download");
response.setContentLength(data.length);
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(data);
outputStream.flush();
outputStream.close();
}
public static void writeJSON(Object obj, HttpServletResponse response) throws Exception {
writer(GsonStatis.instance().toJson(obj), response, JSON_TYPE);
}
protected String getPath(HttpServletRequest request, String path) {
return request.getSession().getServletContext().getRealPath("/") + File.separator + (path == null ? "" : path) + File.separator;
}
/**
* 获取访问者IP
* <p>
* 在一般情况下使用Request.getRemoteAddr()即可,但是经过nginx等反向代理软件后,这个方法会失效。
* <p>
* 本方法先从Header中获取X-Real-IP,如果不存在再从X-Forwarded-For获得第一个IP(用,分割),
* 如果还不存在则调用Request .getRemoteAddr()。
*
* @param request
* @return
*/
protected String getIpAddr(HttpServletRequest request) {
String remoteIp = request.getHeader("x-forwarded-for");
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getHeader("X-Real-IP");
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getHeader("Proxy-Client-IP");
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getHeader("WL-Proxy-Client-IP");
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getHeader("HTTP_CLIENT_IP");
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getRemoteAddr();
}
if (remoteIp == null || remoteIp.isEmpty()
|| "unknown".equalsIgnoreCase(remoteIp)) {
remoteIp = request.getRemoteHost();
}
return remoteIp;
}
public HttpSession getSession(HttpServletRequest request) {
return request.getSession();
}
protected Result validationException(String className, Exception ex) {
Result result = Result.fail(Result.PARAM_FAIL);
result.setCode(Result.PARAM_FAIL);
if ("org.springframework.web.bind.MissingServletRequestParameterException".equalsIgnoreCase(className)) {
MissingServletRequestParameterException msrpe = (MissingServletRequestParameterException) ex;
result.put("name", msrpe.getParameterName());
result.put("type", msrpe.getParameterType());
result.setMsg(msrpe.getMessage());
} else if ("org.springframework.validation.BindException".equalsIgnoreCase(className)) {
BindException bindException = (BindException) ex;
List<FieldError> list = bindException.getFieldErrors();
Set<Map> errors = new HashSet<>();
for (FieldError fieldError : list) {
errors.add(new HashMap<String, Object>() {{
put("className", bindException.getFieldType(fieldError.getField()).getName());
put("errorMsg", fieldError.getDefaultMessage());
put("name", fieldError.getField());
put("value", bindException.getFieldValue(fieldError.getField()));
}});
}
result.put("validation", errors);
}
return result;
}
} |
package com.fb.graph;
import java.util.ArrayList;
public class DFS<T> {
/**
* DFS can be used:
* (a) To find Connected Components - Change color of a picture floodfill
* (b) Maze problems
* DFS can be pre/post/in order for a Binary Tree
* (c) DirectedGraph GC Mark and Sweep, Code Flow
* visit all
*/
private final UnDirectedGraph<T> graph;
private final ArrayList<T> visitedNodes = new ArrayList<T>();
public DFS(UnDirectedGraph<T> graph){
this.graph = graph;
}
public void dfs(T node){
visitedNodes.add(node);
for(T leafNode :graph.getAdjacentNodes(node)){
if (!isVisited(leafNode)){
dfs(leafNode);
}
}
}
public boolean isVisited(T node){
return visitedNodes.contains(node);
}
public ArrayList<T> getVisitedNodes() {
return visitedNodes;
}
public static void main(String[] args) {
UnDirectedGraph<GraphNode> dg = new UnDirectedGraph<GraphNode>();
GraphNode zero = new GraphNode("0");GraphNode one = new GraphNode("1");GraphNode two = new GraphNode("2");GraphNode three = new GraphNode("3");GraphNode four = new GraphNode("4");
GraphNode five = new GraphNode("5");GraphNode six = new GraphNode("6");GraphNode seven = new GraphNode("7");GraphNode eight = new GraphNode("8");GraphNode nine = new GraphNode("9");
dg.addNode(zero);dg.addNode(one);dg.addNode(two);dg.addNode(three);dg.addNode(four);dg.addNode(five);dg.addNode(six);dg.addNode(seven);
dg.addEdge(zero, five);dg.addEdge(zero, one);dg.addEdge(zero, two);dg.addEdge(zero, six);
dg.addEdge(six, seven);
dg.addEdge(five,three);;dg.addEdge(four, five);
/*
* 0
* / / \ \
* 5 1 2 6
* / \ /
* 3 4 7
*/
DFS<GraphNode> dfs = new DFS<GraphNode>(dg);
dfs.dfs(zero);
System.out.println(dfs.getVisitedNodes());
}
}
|
package com.cloudogu.smeagol.wiki.domain;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.util.Objects;
/**
* Simple string value object.
*/
public class RepositoryName {
private final String value;
private RepositoryName(String value) {
this.value = value;
}
/**
* Returns the string representation of the repository name.
*
* @return string representation
*/
public String getValue() {
return value;
}
/**
* Creates a repository name from a string.
*
* @param value string representation of repository name
* @return repository name
*/
public static RepositoryName valueOf(String value) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(value), "repository name can not be null or empty");
return new RepositoryName(value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RepositoryName that = (RepositoryName) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
return value;
}
}
|
/**
* Created by alexanderhughes on 2/1/16.
*/
public class Cat { // Class for a schrodinger's cat.
public String name;
public int age;
public double weight;
public boolean isAlive;
public Cat(String name, int age, double weight, boolean isAlive) {
setName(name);
setAge(age);
setWeight(weight);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age >= 0) {
this.age = age;
}
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
if(weight >= 0) {
this.weight = weight;
}
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
}
|
package Methods_Classes_Objects;
public class student {
//method : a method is block of code which only run when it called
//different type of method creation
//first method
void add(){
// void: no return type
//add is the method name
}
//second method: constructor
student(){
// no return type, not even void
//student is the method name
}
//third method : static
static void sub(){
//static is a keyword
//sub is a method
}
//fourth method : final
final void mul(){
//final is a keyword
//sub is a method
}
}
|
package br.com.nozinho.dao.impl;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.TypedQuery;
import br.com.nozinho.dao.OrgaoEntidadeDAO;
import br.com.nozinho.ejb.dao.impl.GenericDAOImpl;
import br.com.nozinho.model.OrgaoEntidade;
@Stateless
public class OrgaoEntidadeDAOImpl extends GenericDAOImpl<OrgaoEntidade, Long> implements OrgaoEntidadeDAO{
@Override
public List<OrgaoEntidade> findByNameLike(String name) {
TypedQuery<OrgaoEntidade> query = getEntityManager().createNamedQuery("OrgaoEntidade.findByNameLike", OrgaoEntidade.class);
query.setParameter("nome", name + "%");
return query.getResultList();
}
}
|
package q1adt;
import java.util.Iterator;
/**
* FastBag
*
* An implementation of a Bag whose keys are known
* ahead of time and whose main operations (add, count,
* and remove) operate in logarithmic time.
*
* The keys are given to the constructor; they all initially
* have count 0. Behavior is undefined if add or remove is
* called using a key besides those given to the constructor.
*
* CSCI 345
* Test 2 Practice Problem 1.
*/
public class FastBag implements Bag<String> {
private int size = 0;
private String[] internal;
private int[] counts;
/**
* Constructor that takes an iterator that gives
* the keys in sorted order and the number of keys.
* Behavior is undefined if the number of items returned
* by the iterator differs from numKeys.
* @param keys An iterator that gives the potential keys
* in sorted order.
* @param numKeys The number of keys
*/
public FastBag(Iterator<String> keys, int numKeys) {
internal = new String[numKeys];
counts = new int[numKeys];
for(;keys.hasNext();){
internal[size++] = keys.next();
}
}
/**
* Add an item to the bag, increasing its count by 1.
* Behavior undefined if the given item is not one of the
* keys supplied to the constructor.
* @param item The item to add
*/
public void add(String item) {
int index = this.search(item, 0, size);
if(index == -1){
return;
}
counts[index]++;
}
/**
* How many times does this bag contain this item?
* Items supplied to the constructor but either have never been
* added or have been delete have count 0.
* Behavior is undefined for items not supplied to the
* constructor.
* @param item The item to check
* @return The count for the given item.
*/
public int count(String item) {
int index = this.search(item, 0, size);
if(index == -1){
return 0;
}
return counts[index];
}
/**
* Remove the given item, resetting its count to 0.
* Behavior is undefined for items not supplied to the
* constructor.
* @param The item to remove
*/
public void remove(String item) {
int index = this.search(item, 0, size);
if(index == -1){
return;
}
counts[index] = 0;
}
/**
* The number of items in the bag. This is the sum
* of the counts, not the number of unique items.
* @return The number of items.
*/
public int size() {
int total = 0;
for(int i = 0; i < counts.length; i++){
total += counts[i];
}
return total;
}
/**
* Is the set empty?
* @return True if the set is empty, false otherwise.
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Recursive calls
* @param item
* @return
*/
public int search(String item, int begin, int end){
if( end - begin == 1) { //0 , 1 , end
if(item.compareTo(internal[begin]) == 0){
return begin;
}
return -1;
}
if(end == begin){
return -1;
}
int mid = (end + begin) / 2;
if(item.compareTo(internal[mid]) < 0){
return search(item, begin, mid);
}else if(item.compareTo(internal[mid]) == 0){
return mid;
}else{
return search(item, mid+1, end);
}
}
/**
* Make an iterator over the items in this bag which will
* return each item the number times indicated by its count.
* @return An iterator over the bag
*/
public Iterator<String> iterator() {
return new Iterator<String>(){
int i = 0;
int count = counts[0];
int total = 0;
public boolean hasNext() {
return total < size();
}
public String next() {
total++;
if(count == 0){
while(counts[++i]==0);
String toReturn = internal[i];
count = counts[i]-1;
return toReturn;
}else{
count--;
return internal[i];
}
}
};
}
}
|
package orgvictoryaxon.photofeed.photolist.di;
import javax.inject.Singleton;
import dagger.Component;
import orgvictoryaxon.photofeed.PhotoFeedAppModule;
import orgvictoryaxon.photofeed.domain.di.DomainModule;
import orgvictoryaxon.photofeed.lib.di.LibsModule;
import orgvictoryaxon.photofeed.photolist.ui.PhotoListFragment;
/**
* Created by VictorYaxon.
*/
@Singleton
@Component(modules = {PhotoListModule.class, DomainModule.class, LibsModule.class, PhotoFeedAppModule.class})
public interface PhotoListComponent {
void inject(PhotoListFragment fragment);
}
|
package ru.itis.javalab.services;
import org.springframework.stereotype.Service;
import ru.itis.javalab.models.Role;
import ru.itis.javalab.repositories.RoleRepository;
import javax.annotation.PostConstruct;
import java.util.Optional;
/**
* created: 21-03-2021 - 22:46
* project: SemesterWork
*
* @author dinar
* @version v0.1
*/
@Service
public class RoleServiceImpl implements RoleService {
private final RoleRepository roleRepository;
public RoleServiceImpl(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
@PostConstruct
private void init() {
Optional<Role> role = roleRepository.findByRole(Role.Roles.USER);
if (role.isEmpty()) {
roleRepository.save(Role.builder().role(Role.Roles.USER).build());
}
role = roleRepository.findByRole(Role.Roles.ADMIN);
if (role.isEmpty()) {
roleRepository.save(Role.builder().role(Role.Roles.ADMIN).build());
}
}
}
|
package Manufacturing.Ingredient.ConcreteIngredient;
import Manufacturing.Ingredient.BaseIngredient;
/**
* 三文鱼罐头原材料
*
* @author 孟繁霖
* @date 2021/10/25 14:07
*/
public class Salmon extends BaseIngredient {
public Salmon() {
this.setName(
"三文鱼",
"三文魚",
"Salmon"
);
setCost(25.0);
}
}
|
package com.moon.config;
public interface IConfigChangeListener {
public void configChanged();
}
|
package net.thumbtack.asurovenko.tasks.task13;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Formatter {
public String format(Date date) {
return new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss").format(date);
}
}
|
package foo.dbgroup.RDFstruct;
import java.io.InputStream;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.rdf.model.AnonId;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.RDFVisitor;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.util.FileManager;
public class TestLoadingJena {
public static void main(String[] args) {
// create an empty model
Model model = ModelFactory.createDefaultModel();
// use the FileManager to find the input file
InputStream in = FileManager.get().open("adms");
if (in == null) {
throw new IllegalArgumentException(
"File: not found");
}
// read the RDF/XML file
model.read(in,null);
// write it to standard out
model.write(System.out);
// System.out.println(model.containsLiteral(new Resource, arg1, arg2)contains());
}
}
|
package com.tt.miniapp.msg.ad;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.AppbrandContext;
import com.tt.miniapphost.IActivityProxy;
import com.tt.miniapphost.MiniappHostBase;
import com.tt.option.ad.h;
import com.tt.option.e.e;
public class ApiCreateBannerAdCtrl extends BannerAdCtrl {
public ApiCreateBannerAdCtrl(String paramString, int paramInt, e parame) {
super(paramString, paramInt, parame);
}
public void act() {
final h adModel = new h(this.mArgs);
StringBuilder stringBuilder = new StringBuilder("createBannerAd:");
stringBuilder.append(h);
AppBrandLogger.d("tma_ApiCreateBannerAdCtrl", new Object[] { stringBuilder.toString() });
if (!isSupportGameBannerAd()) {
notifyErrorState(h.a, 1003, "feature is not supported in app");
callbackFail("feature is not supported in app");
return;
}
final MiniappHostBase activity = AppbrandContext.getInst().getCurrentActivity();
if (miniappHostBase != null) {
AppbrandContext.mainHandler.post(new Runnable() {
public void run() {
IActivityProxy iActivityProxy = activity.getActivityProxy();
if (iActivityProxy == null) {
ApiCreateBannerAdCtrl.this.callbackFail("activity proxy is null");
return;
}
if (iActivityProxy.onCreateBannerView(adModel)) {
ApiCreateBannerAdCtrl.this.callbackOk();
return;
}
ApiCreateBannerAdCtrl.this.callbackFail("can not create banner ad");
}
});
return;
}
callbackFail("activity is null");
}
public String getActionName() {
return "createBannerAd";
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\ad\ApiCreateBannerAdCtrl.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.tencent.mm.plugin.sns.ui;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.sns.model.af;
import com.tencent.mm.sdk.platformtools.bi;
class SnsTimeLineUI$37 implements OnClickListener {
final /* synthetic */ SnsTimeLineUI odw;
SnsTimeLineUI$37(SnsTimeLineUI snsTimeLineUI) {
this.odw = snsTimeLineUI;
}
public final void onClick(View view) {
Intent intent = new Intent();
intent.setClass(this.odw, SnsUserUI.class);
Intent e = af.bye().e(intent, SnsTimeLineUI.H(this.odw));
if (e == null) {
this.odw.finish();
return;
}
g.Ek();
int a = bi.a((Integer) g.Ei().DT().get(68388, null), 0);
g.Ek();
g.Ei().DT().set(68388, Integer.valueOf(a + 1));
this.odw.startActivity(e);
if ((e.getFlags() & 67108864) != 0) {
this.odw.finish();
}
}
}
|
package edu.nju.logic.impl;
import edu.nju.RuanHuApplication;
import edu.nju.data.dao.UserDAO;
import edu.nju.data.entity.User;
import edu.nju.logic.service.UserProfileService;
import org.junit.Assert;
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.annotation.Rollback;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Date;
/**
* Created by cuihao on 2016/7/13.
*/
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringApplicationConfiguration(classes = RuanHuApplication.class) // 指定我们SpringBoot工程的Application启动类
@WebAppConfiguration
@Rollback
@Transactional
public class UserProfileImplTest {
@Autowired
private UserProfileService userProfileService;
@Autowired
private UserDAO userDAO;
@Test
public void editProfile() throws Exception {
User user = userDAO.getUserByName("ch");
userProfileService.editProfile(user, "description","jiangsu","2015-01-01");
user = userDAO.getUserByName("ch");
Assert.assertTrue(user.getDescription().equals("description"));
Assert.assertTrue(user.getLocation().equals("jiangsu"));
Assert.assertTrue(user.getBirthDate().getTime()== Date.valueOf("2015-01-01").getTime());
}
} |
/*
* 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 view;
import entity.Comment;
import entity.Post;
import entity.RedditAccount;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import logic.CommentLogic;
import logic.LogicFactory;
import logic.PostLogic;
import logic.RedditAccountLogic;
/**
*
* @author Adriano Reckziegel
*/
@WebServlet( name = "CreateComment", urlPatterns = { "/CreateComment" })
public class CreateComment extends HttpServlet {
private String errorMessage = null;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
response.setContentType( "text/html;charset=UTF-8" );
try( PrintWriter out = response.getWriter() ) {
out.println( "<!DOCTYPE html>" );
out.println( "<html>" );
out.println( "<head>" );
out.println( "<title>Create Comment</title>" );
out.println( "</head>" );
out.println( "<body>" );
out.println( "<div style=\"text-align: center;\">" );
out.println( "<div style=\"display: inline-block; text-align: left;\">" );
out.println( "<form action=\"CreateComment\" method=\"post\">" );
out.println( "Reddit Account ID:<br>" );
out.printf( "<input type='text' name=\"%s\" value=\"\">", CommentLogic.REDDIT_ACCOUNT_ID );
out.println( "<br>" );
out.println( "Post ID:<br>" );
out.printf( "<input type='text' name=\"%s\" value=\"\">", CommentLogic.POST_ID );
out.println( "<br>" );
out.println( "Unique ID:<br>" );
out.printf( "<input type='text' name=\"%s\" value=\"\">", CommentLogic.UNIQUE_ID );
out.println( "<br>" );
out.println( "Text:<br>" );
out.printf( "<input type='text' name=\"%s\" value=\"\">", CommentLogic.TEXT );
out.println( "<br>" );
out.println( "Date:<br>" );
out.printf( "<input type=\"datetime-local\" name=\"%s\" min=\"2017-06-01 08:30:00\" max=\"2021-06-30 16:30:00\" pattern=\"[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\" required><br>", CommentLogic.CREATED );
out.println( "<br>" );
out.println( "Points:<br>" );
out.printf( "<input type='text' name=\"%s\" value=\"\"><br>", CommentLogic.POINTS );
out.println( "<br>" );
out.println( "Replys:<br>" );
out.printf( "<input type='text' name=\"%s\" value=\"\"><br>", CommentLogic.REPLYS );
out.println( "<br>" );
out.println( "Is Reply:<br>" );
out.printf( "<input type='text' name=\"%s\" value=\"\"><br>", CommentLogic.IS_REPLY );
out.println( "<br>" );
out.println( "<input type=\"submit\" name=\"view\" value=\"Add and View\">" );
out.println( "<input type=\"submit\" name=\"add\" value=\"Add\">" );
out.println( "</form>" );
if( errorMessage != null && !errorMessage.isEmpty() ){
out.println( "<p color=red>" );
out.println( "<font color=red size=4px>" );
out.println( errorMessage );
out.println( "</font>" );
out.println( "</p>" );
errorMessage = null;
}
out.println( "<pre>" );
out.println( "Submitted keys and values:" );
out.println( toStringMap( request.getParameterMap() ) );
out.println( "</pre>" );
out.println( "</div>" );
out.println( "</div>" );
out.println( "</body>" );
out.println( "</html>" );
}
}
private String toStringMap( Map<String, String[]> values ) {
StringBuilder builder = new StringBuilder();
values.forEach( ( k, v ) -> builder.append( "Key=" ).append( k )
.append( ", " )
.append( "Value/s=" ).append( Arrays.toString( v ) )
.append( System.lineSeparator() ) );
return builder.toString();
}
/**
* Handles the HTTP <code>GET</code> method.
*
* get method is called first when requesting a URL. since this servlet will create a host this method simple
* delivers the html code. creation will be done in doPost method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
log( "GET" );
processRequest( request, response );
}
static int connectionCount = 0;
/**
* Handles the HTTP <code>POST</code> method.
*
* this method will handle the creation of entity. as it is called by user submitting data through browser.
*
* @param request servlet request
* @param response servlet response
*
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
log( "POST" );
log( "POST: Connection=" + connectionCount );
CommentLogic cLogic = LogicFactory.getFor( "Comment" );
RedditAccountLogic raLogic = LogicFactory.getFor( "RedditAccount" );
PostLogic postLogic = LogicFactory.getFor( "Post" );
String uniqueId = request.getParameter( CommentLogic.UNIQUE_ID );
if( cLogic.getCommentWithUniqueId( uniqueId ) == null ){
try {
Comment comment = cLogic.createEntity( request.getParameterMap() );
RedditAccount ra = raLogic.getWithId(Integer.valueOf(request.getParameter(CommentLogic.REDDIT_ACCOUNT_ID)));
Post post = postLogic.getWithId(Integer.valueOf(request.getParameter(CommentLogic.POST_ID)));
// need to convert the date string generated from the input - from Rodrigo Tavares
Map<String, String[]> map = new HashMap<>(request.getParameterMap());
SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd" );
String dateStr = map.get(CommentLogic.CREATED)[0];
Date date = formatter.parse(dateStr);
map.put(
CommentLogic.CREATED,
new String[] { cLogic.convertDateToString(date)}
);
//create the two logics for post and reddit account
//get the entities from logic using getWithId
//set the entities on your comment object before adding comment to db
comment.setUniqueId(uniqueId);
comment.setRedditAccountId(ra);
comment.setPostId(post);
cLogic.add( comment );
} catch( Exception ex ) {
log("", ex);
errorMessage = ex.getMessage();
}
} else {
//if duplicate print the error message
errorMessage = "UniqueID: \"" + uniqueId + "\" already exists";
}
if( request.getParameter( "add" ) != null ){
//if add button is pressed return the same page
processRequest( request, response );
} else if( request.getParameter( "view" ) != null ){
//if view button is pressed redirect to the appropriate table
response.sendRedirect( "CommentTable" );
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Create a Comment Entity";
}
private static final boolean DEBUG = true;
@Override
public void log( String msg ) {
if( DEBUG ){
String message = String.format( "[%s] %s", getClass().getSimpleName(), msg );
getServletContext().log( message );
}
}
@Override
public void log( String msg, Throwable t ) {
String message = String.format( "[%s] %s", getClass().getSimpleName(), msg );
getServletContext().log( message, t );
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pack1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
*
* @author gaurav.sharma
*/
public class MyConnection {
public static Connection con;
public static PreparedStatement pst;
public MyConnection() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=sfsbatch9;selectMethod=cursor", "sa", "abc123");
pst = con.prepareStatement(" ");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
|
// Sun Certified Java Programmer
// Chapter 3, P229
// Assignments
class Tester229 {
public static void main(String[] args) {
Cat[][] myCats = {{new Cat("Fluffy"), new Cat("Zeus")},
{new Cat("Bilbo"), new Cat("Legolas"), new Cat("Bert")}};
}
}
|
/**
*
*/
package spring.mvc;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
/**
* @Title LogAspect
* @Description
*/
@Aspect
public class LogAspect {
@Pointcut("execution(* spring.AccountDao.addAccount(..))")
private void myPointcut(){}
/**
* 前置通知
*/
@Before(value = "myPointcut()", argNames = "userId")
public void before(long userId) {
System.out.println("前置通知...." + userId);
}
/**
* 后置通知 returnVal,切点方法执行后的返回值
*/
@AfterReturning(value = "myPointcut()", returning = "returnVal")
public void AfterReturning(Object returnVal) {
System.out.println("后置通知...." + returnVal);
}
/**
* 环绕通知
*
* @param joinPoint
* 可用于执行切点的类
* @return
* @throws Throwable
*/
@Around(value = "myPointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕通知前....");
Object obj = (Object) joinPoint.proceed();
System.out.println("环绕通知后....");
return obj;
}
/**
* 抛出通知
*
* @param e
*/
@AfterThrowing(value = "myPointcut()", throwing = "e")
public void afterThrowable(Throwable e) {
System.out.println("出现异常:msg=" + e.getMessage());
}
/**
* 无论什么情况下都会执行的方法
*/
@After(value = "myPointcut()")
public void after() {
System.out.println("最终通知....");
}
}
|
package com.marshalchen.ultimaterecyclerview.demo.loadmoredemo;
import android.graphics.Color;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.demo.R;
import com.marshalchen.ultimaterecyclerview.demo.rvComponents.sectionZeroAdapter;
import com.marshalchen.ultimaterecyclerview.demo.modules.SampleDataboxset;
import com.marshalchen.ultimaterecyclerview.ui.emptyview.emptyViewOnShownListener;
import java.util.ArrayList;
/**
* Created by hesk on 25/2/16.
*/
public class FinalEmptyViewDisplayActivity extends BasicFunctions implements emptyViewOnShownListener {
private sectionZeroAdapter simpleRecyclerViewAdapter = null;
private Handler time_count = new Handler();
private int time = 0;
@Override
protected void onLoadmore() {
time_count.postDelayed(new Runnable() {
@Override
public void run() {
SampleDataboxset.insertMoreWhole(simpleRecyclerViewAdapter, 5);
}
}, 1000);
}
@Override
protected void onFireRefresh() {
time_count.postDelayed(new Runnable() {
@Override
public void run() {
ultimateRecyclerView.setRefreshing(false);
}
}, 1000);
}
@Override
protected void enableEmptyViewPolicy() {
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER_AND_LOARMORE);
// ultimateRecyclerView.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_KEEP_HEADER);
ultimateRecyclerView.setEmptyView(R.layout.empty_view_v2, UltimateRecyclerView.EMPTY_CLEAR_ALL, this);
}
@Override
protected void doURV(UltimateRecyclerView urv) {
ultimateRecyclerView.setHasFixedSize(false);
simpleRecyclerViewAdapter = new sectionZeroAdapter(new ArrayList<String>());
configLinearLayoutManager(ultimateRecyclerView);
enableEmptyViewPolicy();
enableLoadMore();
ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#ff4fcccf"));
enableRefresh();
ultimateRecyclerView.setAdapter(simpleRecyclerViewAdapter);
}
@Override
protected void addButtonTrigger() {
SampleDataboxset.insertMoreWhole(simpleRecyclerViewAdapter, 3);
ultimateRecyclerView.reenableLoadmore();
}
@Override
protected void removeButtonTrigger() {
simpleRecyclerViewAdapter.removeAll();
ultimateRecyclerView.showEmptyView();
}
@Override
protected void toggleButtonTrigger() {
simpleRecyclerViewAdapter.removeAll();
ultimateRecyclerView.showEmptyView();
ultimateRecyclerView.disableLoadmore();
}
@Override
public void onEmptyViewShow(View mView) {
TextView tv = (TextView) mView.findViewById(R.id.exp_section_title);
if (tv != null) {
StringBuilder sb = new StringBuilder();
sb.append("Your pressed at \"");
sb.append(time);
sb.append("\" and that is not found.");
tv.setText(sb.toString());
}
time++;
}
}
|
package com.fibbery.cli.command;
import com.fibbery.cli.consts.CommandConsts;
public class QuitCommand implements ICommand{
@Override
public String getIdentifier() {
return CommandConsts.COMMAND_QUIT;
}
@Override
public void execute(String[] args) {
System.out.println("Good Bye !");
System.exit(-1);
}
@Override
public void printUsage() {
}
}
|
package com.example.warehouse.model;
import javax.persistence.*;
@Entity
@Table(name = "PARTS")
public class Part {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "PARTS_NAME")
private String partName;
@Column(name = "PARTS_REQUIRE")
private boolean require;
@Column(name = "PARTS_QUANTITY")
private int quantity;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPartName() {
return partName;
}
public void setPartName(String partName) {
this.partName = partName;
}
public boolean isRequire() {
return require;
}
public void setRequire(boolean require) {
this.require = require;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "Part{" +
"id=" + id +
", partName='" + partName + '\'' +
", require=" + require +
", quantity=" + quantity +
'}';
}
}
|
package com.stryksta.swtorcentral.models;
public class CompanionItem {
public String txtID;
public String txtName;
public String txtTitle;
public String txtCategory;
public String txtSubCategory;
public String txtDescription;
public String txtGender;
public String txtGiftsUnRomanced;
public String txtGiftsRomanced;
public String txtRace;
public String txtPath;
public CompanionItem(String txtID, String txtName, String txtTitle, String txtCategory, String txtSubCategory, String txtDescription, String txtGender, String txtGiftsUnRomanced, String txtGiftsRomanced, String txtRace, String txtPath) {
this.txtID = txtID;
this.txtName = txtName;
this.txtTitle = txtTitle;
this.txtCategory = txtCategory;
this.txtSubCategory = txtSubCategory;
this.txtDescription = txtDescription;
this.txtGender = txtGender;
this.txtGiftsUnRomanced = txtGiftsUnRomanced;
this.txtGiftsRomanced = txtGiftsRomanced;
this.txtRace = txtRace;
this.txtPath = txtPath;
}
public String getID() {
return txtID;
}
public void getID(String txtName){
this.txtID = txtID;
}
public String getName() {
return txtName;
}
public void setName(String txtName){
this.txtName = txtName;
}
public String getTitle() {
return txtTitle;
}
public void setTitle(String txtTitle){
this.txtTitle = txtTitle;
}
public String getCategory() {
return txtCategory;
}
public void setCategory(String txtCategory) {
this.txtCategory = txtCategory;
}
public String getSubCategory() {
return txtSubCategory;
}
public void setSubCategory(String txtSubCategory) {
this.txtSubCategory = txtSubCategory;
}
public String getDescription() {
return txtDescription;
}
public void setDescription(String txtDescription) {
this.txtDescription = txtDescription;
}
public String getGender() {
return txtGender;
}
public void setGender(String txtGender) {
this.txtGender = txtGender;
}
public String getGiftsUnRomanced() {
return txtGiftsUnRomanced;
}
public void setGiftsUnRomanced(String txtGiftsUnRomanced) {
this.txtGiftsUnRomanced = txtGiftsUnRomanced;
}
public String getGiftsRomanced() {
return txtGiftsRomanced;
}
public void setGiftsRomanced(String txtGiftsRomanced) {
this.txtGiftsRomanced = txtGiftsRomanced;
}
public String getRace() {
return txtRace;
}
public void setRace(String txtRace) {
this.txtRace = txtRace;
}
public String getPath() {
return txtPath;
}
public void setPath(String txtPath) {
this.txtPath = txtPath;
}
public String toString() {
return txtName;
}
}
|
package util;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Input {
Scanner scanner = new Scanner(System.in);
public String getPath() {
return scanner.next();
}
public String getLine() {
return scanner.next();
}
public int getChose() {
try {
return scanner.nextInt();
} catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
}
return 0;
}
public String getAnswer() {
return scanner.next();
}
}
|
package asus.ft.autoBrowsing;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
public class AutoBrowser_Thread extends Thread{
public int _runtime=1;
public int _duration1=1;
public int _duration2=1;
public int RunCount=1;
Context _Context;
Intent _intent;
int repeatTime=1;
public AutoBrowser_Thread(Context Context,Intent intent,int runtime,int duration1,int duration2)
{
this._runtime=runtime;
this._duration1=duration1;
this._duration2=duration2;
this._intent=intent;
this._Context= Context;
}
public void run() {
try {
Timer timer = new Timer(true);
long startTime = SystemClock.elapsedRealtime();
int tmp = 0;
// 若 duration1==duration2, 則定時執行
if (_duration1 == _duration2) {
tmp = _duration1 * 60;
} else {
int tmp_min = (int) (Math.random() * 100
% (_duration2 - _duration1) + _duration1);
tmp = (int) (Math.random() * 10 + 60 * tmp_min);
}
// 使用者輸入的秒數
repeatTime = repeatTime + tmp * 1000;
timer.schedule(AutoRun,tmp*1000,tmp*1000);
} catch (Exception e) {
Log.i("info","Run() error" + e.getMessage());
e.getMessage();
}
}
private TimerTask AutoRun = new TimerTask(){
@Override
public void run() {
// TODO Auto-generated method stub
if (RunCount<=_runtime){
Intent i = new Intent(_Context, BrowsingServices.class);
Bundle bb = new Bundle();
bb.putString("STR_CALLER", "");
i.putExtras(bb);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_Context.startService(i);
RunCount++;
}
}
};
}
|
package com.github.rmannibucau.cdi.scopes.internal.method;
import com.github.rmannibucau.cdi.scopes.api.method.MethodScopeExtension;
import com.github.rmannibucau.cdi.scopes.api.method.WrappingMethodScoped;
import com.github.rmannibucau.cdi.scopes.api.method.WithScope;
import org.apache.openejb.jee.WebApp;
import org.apache.openejb.junit.ApplicationComposer;
import org.apache.openejb.testing.Classes;
import org.apache.openejb.testing.Module;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ContextNotActiveException;
import javax.inject.Inject;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(ApplicationComposer.class)
public class WithScopeExtensionTest {
@Module
@Classes(innerClassesAsBean = true, cdi = true)
public WebApp app() {
return new WebApp();
}
@Inject
private ScopeUser user;
@Inject
private MethodScopeExtension extension;
@Inject
private Value value;
@Before
public void reset() {
Value.GENERATOR.set(0);
}
@Test
public void scopeIsOn() {
user.scopeWorks();
}
@Test
public void sameInstanceInSingleScope() {
user.singleInstance();
}
@Test
public void programmatic() {
extension.executeInScope(() -> assertEquals(1, value.getValue()));
}
@Test(expected = ContextNotActiveException.class)
public void notActive() {
value.getValue();
}
public static class ScopeUser {
@Inject
private Value value;
@WithScope
public void scopeWorks() {
assertTrue(value.getValue() > 0);
}
@WithScope
public void singleInstance() {
assertEquals(value.getValue(), value.getValue());
}
}
@WrappingMethodScoped
public static class Value {
private static final AtomicInteger GENERATOR = new AtomicInteger();
private int value;
@PostConstruct
private void init() {
value = GENERATOR.incrementAndGet();
}
public int getValue() {
return value;
}
}
}
|
package com.tantransh.workshopapp.requestlistener;
public interface GeneralRequestListener {
void getStateList();
void getMakeList();
}
|
package com.vilio.pcfs.dao;
import com.vilio.pcfs.pojo.LoginInfo;
import java.util.Map;
public interface LoginInfoDao {
//查询登录信息表
public LoginInfo selectLoginInfo(LoginInfo loginInfo);
//更新登录信息表
public int updateLoginInfo(LoginInfo loginInfo);
//插入登录信息表
public int insert(LoginInfo loginInfo);
//清空超过阈值的登录信息
public int deleteInvalidInfo(Map param);
//退出登录
public int deleteInvalidInfoById(Map param);
}
|
/*
* 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 pplassginment;
/**
*
* @author Dark_ni8
*/
public class girls
{
String name;
double att_level;
double m_budget;
double int_level;
boolean isCommitted;
int typ;
public girls(String n,double a,double m,double i,int t,boolean ic)
{
name=n;
att_level=a;
m_budget=m;
int_level=i;
isCommitted=ic;
typ=t;
}
public String retName()
{
return name;
}
public void setName(String n)
{
this.name=n;
}
public double retAtt_level()
{
return att_level;
}
public void setAtt_level(double a)
{
att_level=a;
}
public double retInt_level()
{
return int_level;
}
public void setInt_level(double i)
{
int_level=i;
}
public double retMaintainanceBudget()
{
return m_budget;
}
public void setMaintainanceBudget(double b)
{
m_budget=b;
}
public boolean isComm()
{
return isCommitted;
}
public void setComm(boolean ic)
{
isCommitted=ic;
}
public int retType()
{
return typ;
}
}
|
package org.opencompare.projetGroupe1;
import java.io.File;
import java.util.List;
import org.opencompare.api.java.Cell;
import org.opencompare.api.java.Feature;
import org.opencompare.api.java.PCM;
import org.opencompare.api.java.PCMContainer;
import org.opencompare.api.java.Product;
import org.opencompare.api.java.impl.PCMElementImpl;
public class Question8 {
/**
* Dans quels cas la procédure d’extraction est défectueuse?
*/
public static boolean fonction(String path)
{
File fichier = new File(path);
List<PCMContainer> pcmContainers = Code.getListPCMContainers(new File(path));
for ( PCMContainer pcmContainer : pcmContainers)
{
PCM pcm = pcmContainer.getPcm();
List<Feature> features = pcm.getConcreteFeatures();
List<Product> products = pcm.getProducts();
for( Product product : products)
{
for( Feature feature : features)
{
Cell cellule = product.findCell(feature);
if(cellule == null)
{
return false;
}
}
}
}
return true;
}
}
|
package com.codemine.talk2me;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONObject;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.ArrayList;
import static com.codemine.talk2me.MESSAGE.*;
public class ChatActivity extends AppCompatActivity {
ArrayList<ChattingInfo> chattingInfos = new ArrayList<>();
ListView chatList;
EditText inputMsgText;
Button inputVoiceButton;
Button sendMsgButton;
TextView backText;
TextView chattingWith;
String oppositeIp;
ImageButton jumpToVoiceImg;
Button changeModeButton;
ChatMode chatMode = ChatMode.TEXT;
boolean isAlive = true;
final String multiCastIp = "239.6.7.8";
boolean isMultiCast;
int textPort = 2345;
//audio
int frequency = 10000;
int channelConfiguration = AudioFormat.CHANNEL_IN_DEFAULT;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
int bufferSize = 160;
boolean isStop = false;
int voicePort = 2333;
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
frequency,
channelConfiguration,
audioEncoding,
bufferSize*2,
AudioTrack.MODE_STREAM
);
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
frequency, channelConfiguration,
audioEncoding, bufferSize);
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case NEW_MSG:
handler.removeMessages(NEW_MSG);
ChattingAdapter chattingAdapter = new ChattingAdapter(ChatActivity.this, R.layout.chatting_item, chattingInfos);
chatList.setAdapter(chattingAdapter);
chatList.setSelection(chattingInfos.size() - 1);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getSupportActionBar() != null)
getSupportActionBar().hide();
setContentView(R.layout.activity_chat);
chatList = (ListView) findViewById(R.id.chattingListView);
inputMsgText = (EditText) findViewById(R.id.inputMsgText);
inputVoiceButton = (Button) findViewById(R.id.inputVoiceButton);
sendMsgButton = (Button) findViewById(R.id.sendMsgButton);
backText = (TextView) findViewById(R.id.back_text);
chattingWith = (TextView) findViewById(R.id.chattingWith);
// jumpToVoiceText = (TextView) findViewById(R.id.jump_to_voice_text);
jumpToVoiceImg = (ImageButton) findViewById(R.id.jump_to_voice_img);
changeModeButton = (Button) findViewById(R.id.changeModButton);//改变模式的按钮
changeModeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(chatMode == ChatMode.VOICE) {
chatMode = ChatMode.TEXT;
inputVoiceButton.setVisibility(View.GONE);
inputMsgText.setVisibility(View.VISIBLE);
sendMsgButton.setVisibility(View.VISIBLE);
changeModeButton.setText("语音");
inputMsgText.setHint("请输入......");
}
else {
chatMode = ChatMode.VOICE;
changeModeButton.setText("文字");
inputVoiceButton.setVisibility(View.VISIBLE);
inputVoiceButton.setBackgroundResource(R.color.white);
inputMsgText.setVisibility(View.GONE);
sendMsgButton.setVisibility(View.GONE);
// inputMsgText.setEnabled(false);
// inputMsgText.setText("");
// inputMsgText.setHint("按住说话");
// inputMsgText.setTextColor(Color.parseColor("#EBEBEB"));
// changeModeButton.setText("文字");
}
}
});
inputVoiceButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
new Thread(new VoiceSender()).start();
inputVoiceButton.setBackgroundResource(R.color.deepGray);
break;
case MotionEvent.ACTION_UP:
stopSend();
inputVoiceButton.setBackgroundResource(R.color.white);
break;
default:
break;
}
return true;
}
});
chattingWith.setText(getIntent().getStringExtra("contactName"));
oppositeIp = getIntent().getStringExtra("contactName");
isMultiCast = oppositeIp.equals(multiCastIp);
//点击返回主界面
backText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isAlive = false;
audioRecord.release();
finish();
}
});
//点击跳转到语音通话界面
jumpToVoiceImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.putExtra("contactName", getIntent().getStringExtra("contactName"));
intent.putExtra("ipAddr", getIntent().getStringExtra("ipAddr"));
intent.setClass(ChatActivity.this, VoiceActivity.class);
startActivity(intent);
}
});
ChattingAdapter chattingAdapter = new ChattingAdapter(ChatActivity.this, R.layout.chatting_item, chattingInfos);
chatList.setAdapter(chattingAdapter);
chatList.setSelection(chattingInfos.size() - 1);
//输入信息
inputMsgText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(!inputMsgText.getText().toString().equals(""))
sendMsgButton.setBackgroundColor(Color.parseColor("#FFC125"));
else
sendMsgButton.setBackgroundColor(Color.parseColor("#EBEBEB"));
}
@Override
public void afterTextChanged(Editable editable) {
}
});
//点击发送消息
sendMsgButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!inputMsgText.getText().toString().equals("")) {
String msg = inputMsgText.getText().toString();
chattingInfos.add(new ChattingInfo(R.drawable.head, msg, MsgType.OWN, ""));
ChattingAdapter chattingAdapter = new ChattingAdapter(ChatActivity.this, R.layout.chatting_item, chattingInfos);
chatList.setAdapter(chattingAdapter);
chatList.setSelection(chattingInfos.size() - 1);
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("info", msg);
new Thread(new TextSender(jsonObject)).start();
}
catch (Exception e) {
e.printStackTrace();
}
}
inputMsgText.getText().clear();
}
});
//循环接收消息
new Thread(new TextReceiver(),"textReceiver").start();
new Thread(new VoiceReceiver(),"voiceReceiver").start();
}
private class TextReceiver implements Runnable {
@Override
public void run() {
try {
byte[] text_buffer = new byte[2<<5];
DatagramSocket datagramSocket;
InetAddress address = InetAddress.getByName(oppositeIp);
if(isMultiCast){
datagramSocket = new MulticastSocket(textPort);
((MulticastSocket)datagramSocket).joinGroup(address);
} else {
datagramSocket = new DatagramSocket(textPort);
}
DatagramPacket datagramPacket = new DatagramPacket(
text_buffer,
text_buffer.length,
address,
textPort);
while (isAlive) {
datagramSocket.receive(datagramPacket);
if(isMultiCast) {
if (datagramPacket.getAddress().
toString().substring(1).
equals(getLocalIp())) {
continue;
}
} else {
if (!datagramPacket.getAddress().
toString().substring(1).
equals(oppositeIp)) {
continue;
}
}
chattingInfos.add(new ChattingInfo(R.drawable.head,new String(text_buffer), MsgType.OTHER, ""));
MESSAGE.sendNewMessage(handler, NEW_MSG);
}
if(isMultiCast){
((MulticastSocket)datagramSocket).leaveGroup(address);
}
datagramSocket.close();
} catch (IOException e) {
e.printStackTrace();
new Thread(new TextReceiver(),"textReceiver").start();
}
}
}
private class TextSender implements Runnable{
JSONObject inputJson;
TextSender(JSONObject inputJson) {
this.inputJson = inputJson;
}
@Override
public void run() {
try {
byte[] text_buffer = new byte[2<<5];
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress address = InetAddress.getByName(oppositeIp);
DatagramPacket datagramPacket = new DatagramPacket(
text_buffer,
text_buffer.length,
address,
textPort);
int i = 0;
for(byte b: inputJson.getString("info").getBytes()){
text_buffer[i++] = b;
}
datagramSocket.send(datagramPacket);
datagramSocket.close();
}
catch (Exception e) {
e.printStackTrace();
new Thread(new TextSender(inputJson)).start();
}
}
}
private class VoiceReceiver implements Runnable{
@Override
public void run() {
try {
byte[] record_buffer = new byte[bufferSize];
DatagramSocket datagramSocket;
InetAddress address = InetAddress.getByName(oppositeIp);
if(isMultiCast){
datagramSocket = new MulticastSocket(voicePort);
((MulticastSocket)datagramSocket).joinGroup(address);
} else {
datagramSocket = new DatagramSocket(voicePort);
}
DatagramPacket datagramPacket = new DatagramPacket(
record_buffer,
record_buffer.length,
address,
voicePort);
while (isAlive) {
datagramSocket.receive(datagramPacket);
if(isMultiCast) {
if (datagramPacket.getAddress().
toString().substring(1).
equals(getLocalIp())) {
continue;
}
} else {
if (!datagramPacket.getAddress().
toString().substring(1).
equals(oppositeIp)) {
continue;
}
}
audioTrack.play();
audioTrack.write(record_buffer,0,bufferSize);
audioTrack.stop();
}
if(isMultiCast){
((MulticastSocket)datagramSocket).leaveGroup(address);
}
datagramSocket.close();
} catch (IOException e) {
e.printStackTrace();
new Thread(new VoiceReceiver(),"voiceReceiver").start();
}
}
}
private class VoiceSender implements Runnable{
@Override
public void run() {
try {
byte[] record_buffer = new byte[bufferSize];
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress address = InetAddress.getByName(oppositeIp);
DatagramPacket datagramPacket = new DatagramPacket(
record_buffer,
record_buffer.length,
address,
voicePort);
audioRecord.startRecording();
while(!isStop){
audioRecord.read(record_buffer, 0, bufferSize);
datagramSocket.send(datagramPacket);
}
audioRecord.stop();
isStop = false;
datagramSocket.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
private void stopSend(){
isStop = true;
}
@Override
public void onBackPressed() {
isAlive = false;
audioRecord.release();
finish();
}
private String getLocalIp() {
// WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
//判断wifi是否开启
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
return intToIp(ipAddress);
}
private String intToIp(int i) {
return (i & 0xFF ) + "." +
((i >> 8 ) & 0xFF) + "." +
((i >> 16 ) & 0xFF) + "." +
( i >> 24 & 0xFF) ;
}
}
enum ChatMode {
TEXT,
VOICE
} |
package oop1;
public class Score {
String studentName;
int kor;
int eng;
int math;
int total;
int average;
boolean isPassed;
}
|
package finggui;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;
/**
* The third panel of the GUI. It contains all log and table information.
*
* The class extends JPanel (as it is one big JPanel that will be directly
* added to the JFrame), and it is a BorderLayout.
*
* Inside this JPanel class resides three JPanels. The JPanel middlePanel is
* used to hold the other two JPanels. It is a BorderLayout.
*
* The first component added to the panel is a JLabel, logOrTableLabel,
* which is placed at middlePanel's BorderLayout North.
*
* The JPanel logOrTablePanel is responsible for lining up the two
* JRadioButtons, the JLabel, and the JComboBox that are associated with log
* and table information. It is a GridLayout. It is placed at middlePanel's
* BorderLayout South.
*
* The JPanel filePanel is responsible for lining up the JLabel, the
* JTextField, and the JButton associated with file path information. It is a
* FlowLayout. This is placed at middlePanel's BorderLayout South.
*
* @author Frank
* @date 8.8.2013
*/
public class ThirdPanel extends JPanel implements ActionListener{
private JPanel middlePanel;
private JPanel logOrTablePanel;
private JPanel filePanel;
private JLabel logOrTableLabel;
private ButtonGroup logOrTableButtonGroup;
public JRadioButton logRadioButton;
public JRadioButton tableRadioButton;
private JLabel formatLabel;
public List<String> formatList;
private DefaultComboBoxModel<String> boxModel;
public JComboBox<String> formatBox;
private JLabel filePathLabel;
public JTextField filePathField;
private JButton directoryButton;
private JFileChooser fileChooser;
/**
* Default constructor. Sets the layout for the panel, initializes other
* JPanels, adds them to the JPanel, then calls methods to initialize and
* organize the components properly.
*/
public ThirdPanel(){
setLayout(new BorderLayout());
setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
middlePanel = new JPanel(new BorderLayout());
logOrTablePanel = new JPanel(new GridLayout(2, 2));
filePanel = new JPanel(new GridLayout(1, 3));
this.add(middlePanel, BorderLayout.CENTER);
initTop();
initMiddle();
}
/**
* Initializes the north most component, the JLabel.
*/
public void initTop(){
logOrTableLabel = new JLabel("Log or Table");
logOrTableLabel.setHorizontalAlignment(JLabel.CENTER);
// Add component to the North of middlePanel
middlePanel.add(logOrTableLabel, BorderLayout.NORTH);
}
/**
* Initializes the second grouping of components: the two JRadioButtons,
* the JLabel, and the JComboBox.
*/
public void initLogOrTable(){
logOrTableButtonGroup = new ButtonGroup();
logRadioButton = new JRadioButton("Log");
logRadioButton.setHorizontalAlignment(JRadioButton.CENTER);
tableRadioButton = new JRadioButton("Table");
tableRadioButton.setHorizontalAlignment(JRadioButton.CENTER);
// Add JRadioButtons to ButtonGroup
logOrTableButtonGroup.add(logRadioButton);
logOrTableButtonGroup.add(tableRadioButton);
// Add action listeners to JRadioButtons
logRadioButton.addActionListener(this);
tableRadioButton.addActionListener(this);
formatLabel = new JLabel("Format: ");
formatLabel.setHorizontalAlignment(JLabel.CENTER);
// Holds all the format types
formatList = new ArrayList<String>();
// DefaultComboBoxModel is added so the JComboBox is able to be changed
formatBox = new JComboBox<String>();
boxModel = (DefaultComboBoxModel<String>) formatBox.getModel();
for (int i = 0; i < formatList.size(); i++){
formatBox.addItem(formatList.get(i));
}
// Add components to logOrTablePanel
logOrTablePanel.add(logRadioButton);
logOrTablePanel.add(tableRadioButton);
logOrTablePanel.add(formatLabel);
logOrTablePanel.add(formatBox);
}
/**
* Initializes the third grouping of components: the JLabel, the
* JTextField, and the JButton.
*/
public void initFile(){
filePathLabel = new JLabel("File Path: ");
filePathLabel.setHorizontalAlignment(JLabel.CENTER);
filePathField = new JTextField();
filePathField.setEditable(false);
directoryButton = new JButton("Select directory...");
fileChooser = new JFileChooser();
directoryButton.addActionListener(this);
// Add components to filePanel
filePanel.add(filePathLabel);
filePanel.add(filePathField);
filePanel.add(directoryButton);
}
/**
* Adds the two separate JPanels, logOrTablePanel and filePanel, to
* middlePanel.
*/
public void initMiddle(){
initLogOrTable();
initFile();
middlePanel.add(logOrTablePanel, BorderLayout.CENTER);
middlePanel.add(filePanel, BorderLayout.SOUTH);
}
/**
* Action listener.
*
* If logRadioButton is clicked, display proper options in formatBox.
*
* If tableRadioButton is clicked, display proper options in formatBox.
*
* If directoryButton is clicked, a directory chooser dialog is displayed,
* and the user can select a directory. This directory is then displayed
* in filePathField.
*
*/
public void actionPerformed(ActionEvent actionEvent) {
if(actionEvent.getSource() == logRadioButton){
eventLogRadioButton();
}
if(actionEvent.getSource() == tableRadioButton){
eventTableRadioButton();
}
if(actionEvent.getSource() == directoryButton){
eventDirectoryButton();
}
}
/**
* Handles all code when logRadioButton is selected.
*/
public void eventLogRadioButton(){
boxModel.removeAllElements();
formatList.clear();
formatList.add("text");
formatList.add("csv");
for (int i = 0; i < formatList.size(); i++){
formatBox.addItem(formatList.get(i));
}
}
public void eventTableRadioButton(){
boxModel.removeAllElements();
formatList.clear();
formatList.add("html");
formatList.add("stext");
formatList.add("xml");
formatList.add("json");
formatList.add("text");
formatList.add("csv");
for (int i = 0; i < formatList.size(); i++){
formatBox.addItem(formatList.get(i));
}
}
public void eventDirectoryButton(){
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.showOpenDialog(null);
String absPath = "";
try{
absPath = (fileChooser.getSelectedFile().getAbsolutePath());
}
catch(Exception ex){
}
filePathField.setText(absPath);
filePathField.setToolTipText(absPath);
}
} |
package com.springcore.spel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("demo")
public class Demo {
@Value("#{10+2}")
private int x;
@Value("#{2+3+4+5}")
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "Demo [x=" + x + ", y=" + y + "]";
}
}
|
import java.util.Arrays;
/**
* Created on 2020/3/21.
*
* @author ray
*/
public class MaxProfit3 {
public static int maxProfit(int[] prices) {
if (prices.length <= 1) {
return 0;
}
int profit = 0;
for (int i = 1; i <= prices.length; i++) {
int p;
if (i != prices.length) {
p = subProfit(Arrays.copyOfRange(prices, 0, i)) + subProfit(Arrays.copyOfRange(prices, i, prices.length));
} else {
p = subProfit(Arrays.copyOfRange(prices, 0, prices.length));
}
if (profit == 0 || profit < p) {
profit = p;
}
}
return profit;
}
public static int subProfit(int[] prices) {
if (prices.length <= 1) {
return 0;
}
int min = prices[0];
int proift = 0;
for (int i = 1; i < prices.length; i++) {
int price = prices[i];
int p = price - min;
if (p > 0 && p > proift) {
proift = p;
}
if (price < min) {
min = price;
}
}
return proift;
}
public static void main(String[] args) {
int[] p = {3,3,5,0,0,3,1,4};
System.out.println(maxProfit(p));
}
}
|
package 线程交互.PC2;
public class PC2 {
/*
企业级多线程实战二:
生产者与消费者问题:(2)两个生产者,两个个消费者,商品池子的大小为1。
这个例子主要阐述问题:多线程交互中的,防止虚假唤醒。
下面4个线程交互,两个进程要生产,其实还是要遵守商品池子的大小为1的要求,
应该是两个线程中的一个生产一个商品,然后要等消费之后才能再生产。
但是实际情况却不是这样的,会出现超过一个商品的情况,即商品池中商品生产的数量超过1
谁来背这个锅?我们加了synchronized的,每次都是一个进程进去操作的
起因是wait(),notifyAll()这个机制,然后是if这个问题
比如说如果两个生产者都wait(),然后我们notifyAll(),他们被唤醒,就继续往下运行了,然后count++执行了两次
*/
public static void main(String[] args) {
Product p = new Product();
new Thread(() -> {
for(int i=0;i<100;i++){
try {
p.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"Producer1").start();
new Thread(() -> {
for(int i=0;i<100;i++){
try {
p.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"Producer2").start();
new Thread(() -> {
for(int i=0;i<100;i++){
try {
p.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"Comsumer1").start();
new Thread(() -> {
for(int i=0;i<100;i++){
try {
p.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"Comsumer2").start();
}
}
|
package com.pine.template.db_server;
import com.pine.template.base.BaseSPKeyConstants;
/**
* Created by tanghongfeng on 2019/11/1.
*/
public interface DbSPKeyConstants extends BaseSPKeyConstants {
}
|
package com.sree.mapreduce.training.forums;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class TopTen {
public static class MapperClass extends
Mapper<LongWritable, Text, IntWritable, MapWritable> {
private final TreeMap<Integer, String> bodyLengthMap = new TreeMap<>();
IntWritable one = new IntWritable(1);
@Override
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
if (null != value) {
String bodyString = value.toString();
int length = bodyString.length();
bodyLengthMap.put(length, bodyString);
if (bodyLengthMap.size() > 10) {
bodyLengthMap.remove(bodyLengthMap.firstKey());
}
}
}
@Override
public void cleanup(Context context) throws IOException,
InterruptedException {
MapWritable mapWritable = new MapWritable();
for (Map.Entry<Integer, String> entry : bodyLengthMap.entrySet()) {
mapWritable.put(new IntWritable(entry.getKey()),
new Text(entry.getValue()));
}
context.write(one, mapWritable);
}
}
public static class ReducerClass extends
Reducer<IntWritable, MapWritable, IntWritable, Text> {
private final TreeMap<Integer, Text> bodyLengthMap = new TreeMap<>();
@Override
public void reduce(IntWritable key, Iterable<MapWritable> values,
Context context) {
for (MapWritable mapWritable : values) {
for (Entry<Writable, Writable> entry : mapWritable.entrySet()) {
Text mwValue = (Text) entry.getValue();
int reducerKey = ((IntWritable) entry.getKey()).get();
bodyLengthMap.put(new Integer(reducerKey), mwValue);
if (bodyLengthMap.size() > 10) {
bodyLengthMap.remove(bodyLengthMap.firstKey());
}
}
}
}
@Override
public void cleanup(Context context) throws IOException,
InterruptedException {
for (Integer mapKey : bodyLengthMap.keySet()) {
context.write(null, bodyLengthMap.get(mapKey));
}
}
}
public static void main(String[] args) throws IOException,
ClassNotFoundException, InterruptedException {
Configuration configuration = new Configuration();
Job job = new Job(configuration, "TopEnn");
job.setJarByClass(TopTen.class);
Path inputPath = new Path(
"/home/cloudera/datasets/forum_data/snippets.txt");
Path outputPath = new Path("/home/cloudera/datasets/forum_data/output");
org.apache.hadoop.mapreduce.lib.input.FileInputFormat.setInputPaths(
job, inputPath);
FileOutputFormat.setOutputPath(job, outputPath);
job.setMapperClass(MapperClass.class);
job.setReducerClass(ReducerClass.class);
job.setNumReduceTasks(1);
job.setInputFormatClass(TextInputFormat.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(MapWritable.class);
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(Text.class);
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
|
package com.yunhe.systemsetup.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunhe.systemsetup.dao.SystemLogMapper;
import com.yunhe.systemsetup.entity.SystemLog;
import com.yunhe.systemsetup.service.ISystemLogService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* <p>
* 系统日志表 服务实现类
* </p>
*
* @author 孔邹祥
* @since 2019-01-25
*/
@Service
public class SystemLogServiceImpl extends ServiceImpl<SystemLogMapper, SystemLog> implements ISystemLogService {
@Resource
SystemLogMapper systemLogMapper;
@Override
public IPage<SystemLog> selectAllSystemLog(Integer current, Integer size, SystemLog systemLog) {
Page<SystemLog> page = new Page<>(current, size);
return systemLogMapper.selectPage(page, new QueryWrapper<SystemLog>()
.orderByDesc("id")
);
}
@Override
public Integer deleteByIdSystemLog(Integer id) {
return systemLogMapper.delete(new QueryWrapper<SystemLog>().eq("id",id));
}
}
|
/*
HeroScribe
Copyright (C) 2002-2004 Flavio Chierichetti and Valerio Chierichetti
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 (not
later versions) as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.lightless.heroscribe.helper;
import org.lightless.heroscribe.Constants;
import org.lightless.heroscribe.gui.Gui;
import org.lightless.heroscribe.list.LObject;
import org.lightless.heroscribe.quest.*;
import java.util.Iterator;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.ImageObserver;
public class BoardPainter implements ImageObserver {
private Gui gui;
public Dimension boardSize, boardPixelSize, framePixelSize;
public float boxEdge;
public int adjacentBoardsOffset;
public BoardPainter(Gui gui) throws Exception {
this.gui = gui;
init();
}
public void init() {
boardSize =
new Dimension(
gui.getObjects().getBoard().width,
gui.getObjects().getBoard().height);
boardPixelSize =
new Dimension(getBoardIcon().getWidth(this),
getBoardIcon().getHeight(this));
boxEdge =
(getBoardIcon().getWidth(this) * 1.0f)
/ (gui.getObjects().getBoard().width + 2);
adjacentBoardsOffset =
Math.round(boxEdge * gui.getObjects().getBoard().adjacentBoardsOffset);
framePixelSize =
new Dimension(
boardPixelSize.width * gui.getQuest().getWidth() +
adjacentBoardsOffset * (gui.getQuest().getWidth() - 1),
boardPixelSize.height * gui.getQuest().getHeight() +
adjacentBoardsOffset * (gui.getQuest().getHeight() - 1));
}
private void drawBridge(int column, int row, boolean horizontal, int position, Graphics2D g2d) {
int x, y;
int width, height;
if ( horizontal ) {
x = getIntX(column, gui.getQuest().getBoard(column, row).getWidth() + 1);
y = getIntY(row, position);
width = getIntX(column + 1, 1) - x + 1;
height = getIntY(row, position + 1) - y + 1;
} else {
x = getIntX(column, position);
y = getIntY(row, gui.getQuest().getBoard(column, row).getHeight() + 1);
width = getIntX(column, position + 1) - x + 1;
height = getIntY(row + 1, 1) - y + 1;
}
g2d.setColor(Color.BLACK);
g2d.fillRect(x, y, width, height);
if (getRegion().equals("Europe"))
g2d.setColor(org.lightless.heroscribe.Constants.europeCorridorColor);
else if (getRegion().equals("USA"))
g2d.setColor(org.lightless.heroscribe.Constants.usaCorridorColor);
g2d.fillRect(x + 1, y + 1, width - 2, height - 2);
}
private void drawRectangle(int column, int row,
float left, float top,
float width, float height, Graphics2D g2d) {
g2d.fillRect(getIntX(column, left), getIntY(row, top),
(int) Math.ceil(width * boxEdge),
(int) Math.ceil(height * boxEdge));
}
private float getX(int column, float left) {
return column * (boardPixelSize.width + adjacentBoardsOffset) +
left * boxEdge;
}
private float getY(int row, float top) {
return row * (boardPixelSize.height + adjacentBoardsOffset) +
top * boxEdge;
}
private int getIntX(int column, float left) {
return (int) Math.floor(getX(column, left));
}
private int getIntY(int row, float top) {
return (int) Math.floor(getY(row, top));
}
public void paint(QObject floating, int column, int row, Graphics2D g2d) {
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, framePixelSize.width, framePixelSize.height);
for (int i = 0; i < gui.getQuest().getWidth(); i++)
for (int j = 0; j < gui.getQuest().getHeight(); j++) {
QBoard board = gui.getQuest().getBoard(i, j);
/* Corridors */
if (getRegion().equals("Europe"))
g2d.setColor(Constants.europeCorridorColor);
else if (getRegion().equals("USA"))
g2d.setColor(Constants.usaCorridorColor);
for (int left = 1; left <= board.getWidth(); left++)
for (int top = 1; top <= board.getHeight(); top++)
if (gui.getObjects().board.corridors[left][top])
drawRectangle(i, j, left, top, 1, 1, g2d);
/* Dark Areas */
if (getRegion().equals("Europe"))
g2d.setColor(Constants.europeDarkColor);
else if (getRegion().equals("USA"))
g2d.setColor(Constants.usaDarkColor);
for (int left = 1; left <= board.getWidth(); left++)
for (int top = 1; top <= board.getHeight(); top++)
if (board.isDark(left, top))
drawRectangle(i, j, left, top, 1, 1, g2d);
/* Board */
g2d.drawImage(getBoardIcon(), getIntX(i, 0), getIntY(j, 0), this);
}
/* Bridges */
for (int i = 0; i < gui.getQuest().getWidth(); i++)
for (int j = 0; j < gui.getQuest().getHeight(); j++) {
QBoard board = gui.getQuest().getBoard(i, j);
if ( i < gui.getQuest().getWidth() - 1 )
for (int top = 1 ; top <= board.getHeight() ; top++ )
if ( gui.getQuest().getHorizontalBridge(i, j, top) )
drawBridge(i, j, true, top, g2d);
if ( j < gui.getQuest().getHeight() - 1 )
for (int left = 1 ; left <= board.getWidth() ; left++ )
if ( gui.getQuest().getVerticalBridge(i, j, left) )
drawBridge(i, j, false, left, g2d);
}
for (int i = 0; i < gui.getQuest().getWidth(); i++)
for (int j = 0; j < gui.getQuest().getHeight(); j++) {
QBoard board = gui.getQuest().getBoard(i, j);
/* Objects */
Iterator iterator = board.iterator();
while (iterator.hasNext()) {
QObject obj = (QObject) iterator.next();
drawIcon(obj, i, j, g2d);
}
}
if (floating != null)
drawIcon(floating, column, row, g2d);
}
private void drawIcon(QObject piece, int column, int row, Graphics2D g2d) {
AffineTransform original = null;
float x, y, xoffset, yoffset;
int width, height;
LObject obj = gui.getObjects().getObject(piece.id);
if (!isWellPositioned(piece))
return;
if (piece.rotation % 2 == 0) {
width = obj.width;
height = obj.height;
} else {
width = obj.height;
height = obj.width;
}
if (obj.trap) {
if (getRegion().equals("Europe"))
g2d.setColor(Constants.europeTrapColor);
else if (getRegion().equals("USA"))
g2d.setColor(Constants.usaTrapColor);
drawRectangle(0, 0, piece.left, piece.top, width, height, g2d);
}
x = piece.left + width / 2.0f;
y = piece.top + height / 2.0f;
if (obj.door) {
if (piece.rotation % 2 == 0) {
if (piece.top == 0)
y -= gui.getObjects().getBoard().borderDoorsOffset;
else if (piece.top == boardSize.height)
y += gui.getObjects().getBoard().borderDoorsOffset;
} else {
if (piece.left == 0)
x -= gui.getObjects().getBoard().borderDoorsOffset;
else if (piece.left == boardSize.width)
x += gui.getObjects().getBoard().borderDoorsOffset;
}
}
xoffset = obj.getIcon(getRegion()).xoffset;
yoffset = obj.getIcon(getRegion()).yoffset;
switch (piece.rotation) {
case 0 :
x += xoffset;
y += yoffset;
break;
case 1 :
x += yoffset;
y -= xoffset;
break;
case 2 :
x -= xoffset;
y -= yoffset;
break;
case 3 :
x -= yoffset;
y += xoffset;
break;
}
x = getX(column, x);
y = getY(row, y);
if (piece.rotation != 0) {
AffineTransform rotated;
original = g2d.getTransform();
rotated = (AffineTransform) (original.clone());
rotated.rotate((-Math.PI / 2) * piece.rotation, x, y);
g2d.setTransform(rotated);
}
x -= getObjectIcon(obj.id).getWidth(this) / 2.0f;
y -= getObjectIcon(obj.id).getHeight(this) / 2.0f;
g2d.drawImage(getObjectIcon(obj.id), Math.round(x), Math.round(y), this);
if (piece.rotation != 0)
g2d.setTransform(original);
}
private Image getObjectIcon(String id) {
return gui.getObjects().getObject(id).getIcon(getRegion()).image;
}
private Image getBoardIcon() {
return gui.getObjects().getBoard().getIcon(getRegion()).image;
}
private String getRegion() {
return gui.getQuest().getRegion();
}
public boolean isWellPositioned(QObject piece) {
LObject obj = gui.getObjects().getObject(piece.id);
int width, height;
if (piece.rotation % 2 == 0) {
width = obj.width;
height = obj.height;
} else {
width = obj.height;
height = obj.width;
}
if (obj.door) {
if (piece.left < 0
|| piece.top < 0
|| piece.left + width - 1 > boardSize.width + 1
|| piece.top + height - 1 > boardSize.height + 1
|| (piece.rotation % 2 == 0
&& (piece.left == 0 || piece.left == boardSize.width + 1))
|| (piece.rotation % 2 == 1
&& (piece.top == 0 || piece.top == boardSize.height + 1)))
return false;
} else {
if (piece.left < 1
|| piece.top < 1
|| piece.left + width - 1 > boardSize.width
|| piece.top + height - 1 > boardSize.height)
return false;
}
return true;
}
public boolean imageUpdate(
Image img,
int infoflags,
int x,
int y,
int width,
int height) {
return false;
}
}
|
package com.gld.znaqm.mapper;
import com.gld.znaqm.model.User;
import tk.mybatis.mapper.common.Mapper;
public interface UserMapper extends Mapper<User> {
}
|
package com.zhouyi.business.controller;
import com.zhouyi.business.core.model.LedenCollectPCallrecords;
import com.zhouyi.business.core.model.Response;
import com.zhouyi.business.core.service.BaseService;
import com.zhouyi.business.core.service.LedenCollectPCallrecordsService;
import com.zhouyi.business.core.vo.LedenCollectPCallrecordsVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/api/callrecords")
@Api(hidden = true)
public class LedenCollectPCallrecordsController {
@Autowired
private BaseService<LedenCollectPCallrecords, LedenCollectPCallrecordsVo> baseService;
@Autowired
private LedenCollectPCallrecordsService ledenCollectPCallrecordsService;
@RequestMapping(value = "/get/{id}")
public Response getDataById(@PathVariable(value = "id") String id){
return baseService.findDataById(id);
}
@RequestMapping(value = "/getlist")
public Response getList(@RequestBody LedenCollectPCallrecordsVo ledenCollectPCallrecordsVo){
LedenCollectPCallrecordsVo ledenCollectPCallrecordsVo1 = ledenCollectPCallrecordsVo;
if (ledenCollectPCallrecordsVo == null){
ledenCollectPCallrecordsVo1 = new LedenCollectPCallrecordsVo();
}
return baseService.findDataList(ledenCollectPCallrecordsVo1);
}
@RequestMapping(value = "/save")
public Response saveData(@RequestBody LedenCollectPCallrecords ledenCollectPCallrecords){
return baseService.saveData(ledenCollectPCallrecords);
}
@RequestMapping(value = "/update")
public Response updateData(@RequestBody LedenCollectPCallrecords ledenCollectPCallrecords){
return baseService.updateData(ledenCollectPCallrecords);
}
@RequestMapping("/delete/{id}")
public Response deleteData(@PathVariable(value = "id")String id){
return baseService.deleteData(id);
}
@RequestMapping(value = "/select")
public Response selectDataById(@RequestBody LedenCollectPCallrecordsVo ledenCollectPCallrecordsVo){
return ledenCollectPCallrecordsService.selectDataById(ledenCollectPCallrecordsVo);
}
}
|
package cn.com.ykse.santa.repository.dao;
import cn.com.ykse.santa.repository.entity.RequirementDO;
import cn.com.ykse.santa.repository.pagination.Page;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
public interface RequirementDOMapper {
int deleteByPrimaryKey(Integer requirementId);
int insert(RequirementDO record);
int insertSelective(RequirementDO record);
RequirementDO selectByPrimaryKey(Integer requirementId);
int updateByPrimaryKeySelective(RequirementDO record);
int updateByPrimaryKey(RequirementDO record);
//................................................
List<RequirementDO> selectAllUnfinished(@Param("page") Page page);
int countAllUnfinished();
List<RequirementDO> searchByTitle(@Param("title") String title,@Param("page") Page page);
int countByTitle(@Param("title") String title);
List<RequirementDO> searchSelective(@Param("requirement") RequirementDO requirement, @Param("expectedDateStart") Date expectedDateStart, @Param("expectedDateEnd") Date expectedDateEnd, @Param("page") Page page);
int countSelective(@Param("requirement") RequirementDO requirement,@Param("expectedDateStart") Date expectedDateStart,@Param("expectedDateEnd") Date expectedDateEnd);
List<RequirementDO> selectRequirementsByStatus(@Param("status") String status,@Param("page") Page page);
int countRequirementByStatus(@Param("status") String status);
int updateBatchNewRequirement(@Param("idList") List<Integer> idList, @Param("pd") String pd);
List<RequirementDO> selectEnableRequirementsForHandling(@Param("self") String self,@Param("statusList") List<String> statusList);
List<RequirementDO> selectRequirementsForDemand(@Param("demandId") Integer demandId);
String selectStatusByPrimaryKey(Integer requirementId);
String selectCreatorByPrimaryKey(Integer requirementId);
int unableRequirement(Integer requirementId);
int updateStatusToDoingInBatch(@Param("idList") List<Integer> idList);
int updateStatusByPrimaryKey(@Param("requirementId") Integer requirementId,@Param("status") String status);
int updateStatusToDone(@Param("requirementId") Integer requirementId,@Param("reason") String reason);
} |
package pl.com.bartusiak.designpatterns.state;
import java.util.ArrayList;
import java.util.stream.Collectors;
class CombinationLock
{
private int [] combination;
private ArrayList<Integer> list;
public String status;
public CombinationLock(int[] combination)
{
this.combination = combination;
list = new ArrayList<>();
status="LOCKED";
}
public void enterDigit(int digit)
{
list.add(digit);
status = list.stream().map(el->""+el).collect(Collectors.joining());
if(list.size()==combination.length){
for (int i=0; i<combination.length; i++){
status="OPEN";
if(combination[i]!=list.get(i)){
status="ERROR";
break;
}
}
}
}
}
public class Exercise {
public static void main(String[] args) {
CombinationLock lock = new CombinationLock(new int[]{1,2,3,4});
System.out.println(lock.status);
lock.enterDigit(1);
System.out.println(lock.status);
lock.enterDigit(2);
System.out.println(lock.status);
lock.enterDigit(3);
System.out.println(lock.status);
lock.enterDigit(4);
System.out.println(lock.status);
}
}
|
package com.qq.taf.jce.dynamic;
import java.util.Comparator;
class StructField$1 implements Comparator<JceField> {
StructField$1() {
}
public int compare(JceField jceField, JceField jceField2) {
return jceField.getTag() - jceField2.getTag();
}
}
|
/**
* $id$
*/
package com.renren.api.connect.android.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Read the logcat log
*
* @author Shaofeng Wang (shaofeng.wang@renren-inc.com)
*/
public final class LogHelper {
private static final String LOG_TAG_REQUEST = "Renren-SDK-Request";
private static final String LOG_TAG_RESPONSE = "Renren-SDK-Response";
/**
* Get the log using the specified filter
*
* @param tag
* @return
*/
public synchronized String getLog() {
StringBuffer logger = new StringBuffer();
try {
Process process = Runtime.getRuntime().exec("logcat -v time + "
+ LOG_TAG_REQUEST + ":I "
+ LOG_TAG_RESPONSE + ":I *:S");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()), 1024);
Thread thread = new Thread(new LogFinalizer(process));
thread.start();
String line = bufferedReader.readLine();
while (line != null && line.length() != 0) {
logger.append(parseLog(line));
line = bufferedReader.readLine();
}
if(bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return logger.toString();
}
/**
* clear the log
*/
public synchronized void clear() {
try {
Runtime.getRuntime().exec("logcat -c + "
+ LOG_TAG_REQUEST + ":I "
+ LOG_TAG_RESPONSE + ":I *:S");
} catch (IOException e) {
}
}
/**
* 解析log为显示格式
* @param log
* @return
*/
private static String parseLog(String logStr) {
StringBuffer sb = new StringBuffer();
String requestTag = "I/" + LOG_TAG_REQUEST;
String responseTag = "I/" + LOG_TAG_RESPONSE;
if(logStr.contains(requestTag)) {
//请求log 格式形如:08-23 03:05:43.112 I/Renren-SDK-Request( 775):
//method=users.getInfo&Bundle[{v=1.0, uids=3××××××, ……
StringBuffer log = new StringBuffer(logStr);
int tagIndex = log.indexOf(requestTag);
//添加时间
sb.append(log.substring(0, tagIndex)).append("\r\n");
int methodIndex = log.indexOf("method");
int methodEnd = log.indexOf("&");
//添加method项
sb.append(log.substring(methodIndex, methodEnd)).append("\r\n").append("request:\r\n");
String bundleStr = "Bundle[{";
int paramIndex = log.indexOf(bundleStr, 0) + bundleStr.length();
//获取参数序列(不包括"[{"以及"}]")
String paramStr = log.substring(paramIndex, log.length() - 2);
//添加参数 key=value 对
String[] params = paramStr.split(",");
sb.append("{\r\n");
if(params != null) {
for(String str : params) {
sb.append("\t").append(str.trim()).append(";\r\n");
}
}
sb.append("}\r\n\r\n");
} else if(logStr.contains(responseTag)){
//响应log 格式形如:03:05:51.452 I/Renren-SDK-Response( 775):
// method=status.set&{"result":1}……
StringBuffer log = new StringBuffer(logStr);
int tagIndex = log.indexOf(responseTag);
//添加时间
sb.append(log.substring(0, tagIndex)).append("\r\n");
int methodIndex = log.indexOf("method");
int methodEnd = log.indexOf("&");
//添加method项
sb.append(log.substring(methodIndex, methodEnd)).append("\r\n").append("response:\r\n");
int paramIndex = methodEnd + 1;
//获取参数序列
String paramStr = log.substring(paramIndex, log.length());
//添加参数 key=value 对
paramStr.replace(",", ",\r\n");
sb.append(paramStr).append("\r\n\r\n");
} else {
return logStr;
}
return sb.toString();
}
/**
* Used to stop the log process after a specified time
*
* @author Shaofeng Wang (shaofeng.wang@renren-inc.com)
*/
private class LogFinalizer implements Runnable{
private Process process;
public LogFinalizer(Process process) {
this.process = process;
}
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
process.destroy();
}
}
}
|
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class EmpUpdate implements CRUD
{
static List<Emp_info> employee_list = new ArrayList<>();
private PreparedStatement p_stmt;
private static EmpUpdate emp_DBO;
public EmpUpdate(){
}
public static EmpUpdate getInstance(){
if(emp_DBO == null)
emp_DBO = new EmpUpdate();
return emp_DBO;
}
@Override
public List<Emp_info> readData(Connection con) throws CustomException {
public List<Emp_info> readData() throws CustomException,SQLException {
JDBCdemo jdbc_con = new JDBCdemo();
Connection con = jdbc_con.getConnection();
try{
String query = "Select * from emppayroll";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("Name");
String phone = rs.getString("phone_no");
String address = rs.getString("Address");
String department = rs.getString("Department");
Date start = rs.getDate("start");
char gender = rs.getString("gender").charAt(0);
double salary = rs.getDouble("salary");
Emp_info emp = new Emp_info(id,name,phone,address,department,gender,salary,start);
employee_list.add(emp);
this.employee_list.add(emp);
}
}catch(Exception e){
throw new CustomException("Read Process Unsuccessful");
}finally {
con.close();
}
return employee_list;
}
@Override
public void insertData() { }
@Override
public void updateData(Connection con, String column, String name, String value) throws CustomException {
public void updateData(String column, String name, String value) throws CustomException, SQLException {
JDBCdemo jdbc_con = new JDBCdemo();
Connection con = jdbc_con.getConnection();
try{
PreparedStatement stmt = con.prepareStatement("Update emppayroll set salary = ? where name = ?");
stmt.setDouble(1,Double.parseDouble(value));
stmt.setString(2,name);
stmt.executeUpdate();
p_stmt = con.prepareStatement("Update employee set salary = ? where name = ?");
p_stmt.setDouble(1,Double.parseDouble(value));
p_stmt.setString(2,name);
p_stmt.executeUpdate();
}catch(Exception e){
throw new CustomException("Read Process Unsuccessful");
}finally {
if(con != null)
con.close();
}
}
@Override
public void deleteData() { }
public ResultSet getEmployeeDataFromDB(String query) {
ResultSet rs = null;
Connection con = null;
try{
JDBCdemo jdbc_con = new JDBCdemo();
con = jdbc_con.getConnection();
Statement stmt = con.createStatement();
rs = stmt.executeQuery(query);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public Emp_info getPayrollDataByName(String name) throws SQLException {
JDBCdemo jdbc_con = new JDBCdemo();
Connection con = jdbc_con.getConnection();
p_stmt = con.prepareStatement("Select * from payroll where name = ?");
p_stmt.setString(1,name);
ResultSet rs = p_stmt.executeQuery();
Emp_info emp = null;
while(rs.next()){
int id = rs.getInt("id");
String phone = rs.getString("phone_no");
String address = rs.getString("Address");
String department = rs.getString("Department");
Date start = rs.getDate("start");
char gender = rs.getString("gender").charAt(0);
double salary = rs.getDouble("salary");
emp = new Emp_info(id,name,phone,address,department,gender,salary,start);
}
return emp;
}
public ResultSet retrieveEmployeesByDate(String startDate, String endDate){
String query = "Select * from emppayroll where start date between " + startDate + " and " + endDate;
ResultSet rs = this.getEmployeeDataFromDB(query);
return rs;
}
} |
import java.util.Scanner;
class prog23{
public static void main(String args[])
{
int arr[] = new int [] {10,20,30,40,50};
System.out.println("User Array : ");
for(int i=0; i<arr.length; i++)
{
System.out.println(arr[i]+ " ");
}
System.out.println("Reverse of Array : ");
for(int i = arr.length-1; i>=0; i--)
{
System.out.println(arr[i]+ " ");
}
}
} |
package fr.clivana.lemansnews.view;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.*;
import com.facebook.android.Facebook;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
//import com.markupartist.android.widget.PullToRefreshListView;
import fr.clivana.lemansnews.R;
import fr.clivana.lemansnews.controller.GalleryOneByOne;
import fr.clivana.lemansnews.controller.VuePrincipaleController;
import fr.clivana.lemansnews.utils.facebook.FacebookFunctions;
public class VuePrincipaleActivity extends Activity{
//Un lien sur le controlleur qui gère les évènements
VuePrincipaleController vuePrincipaleController;
//les attributs de classe pour la vue
TextView titreApplication;
TextView titreActualite;
TextView titreSuite;
TextView titreEvenement;
TextView derniereMaj;
//Lien de la gallerie en haut et au milieu
GalleryOneByOne galleryEvents;
//PullToRefreshListView pullToRefreshListView;
ListView listview;
//Les boutons de la vue Principale
Button boutonALaUne;
Button boutonNews;
Button boutonEvents;
Button boutonInfo;
Button boutonActualiser;
Button boutonFavoris;
CategoriesDialog dialog;
//Tableau de données
String[] items={"Facebook", "Mail", "SMS", "Google+"};
//lien sur l'api de google analytics
GoogleAnalyticsTracker tracker;
//Lien sur l'api de facebook
Facebook facebook;
//Une image
ImageView suivant;
ImageView precedent;
public final static String AUTH = "authentication";
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//désiarilisation de la vue dans l'activity
setContentView(R.layout.main);
//Appel de la méthode pour s'enregistrer sur google analytics
register();
//Apper de l'api de google analytics
tracker = GoogleAnalyticsTracker.getInstance();
tracker.startNewSession("UA-27914218-1",1, this);
tracker.setAnonymizeIp(true);
//page tracker via google analytics
tracker.trackPageView("/index");
//On récupère depuis le fichier main.xml la vue
galleryEvents = (GalleryOneByOne)findViewById(R.id.galleryEvents);
vuePrincipaleController = new VuePrincipaleController(this, galleryEvents);
titreApplication =(TextView)findViewById(R.id.textViewTitreApplication);
titreActualite = (TextView)findViewById(R.id.titreActualite);
titreSuite = (TextView)findViewById(R.id.titreActualiteSuite);
derniereMaj = (TextView)findViewById(R.id.textViewDateMAJ);
//pullToRefreshListView = (PullToRefreshListView)findViewById(R.id.pullToRefreshListView);
listview = (ListView)findViewById(R.id.pullToRefreshListView);
boutonALaUne = (Button)findViewById(R.id.buttonALaUne);
boutonNews = (Button)findViewById(R.id.buttonNews);
boutonEvents = (Button)findViewById(R.id.buttonEvents);
boutonInfo = (Button)findViewById(R.id.buttonInfo);
boutonActualiser = (Button)findViewById(R.id.buttonActualiser);
boutonFavoris = (Button)findViewById(R.id.buttonFavoris);
//désrialisation des boutons
//Un background dans la barre de titre
titreApplication.setBackgroundResource(R.drawable.titreapplication);
//modification de la police pour la vue principale
vuePrincipaleController.miseEnPageRomanLight(titreActualite);
vuePrincipaleController.miseEnPageRomanLight(titreSuite);
setDate();
initAdapters();
//bouton selection
boutonALaUne.setPressed(true);
boutonALaUne.setClickable(false);
//Ajout des listeners sur les boutons et envoie au controleur
boutonNews.setOnClickListener(vuePrincipaleController);
boutonActualiser.setOnClickListener(vuePrincipaleController);
boutonEvents.setOnClickListener(vuePrincipaleController);
boutonInfo.setOnClickListener(vuePrincipaleController);
boutonFavoris.setOnClickListener(vuePrincipaleController);
//Ajout des évenements sur la gallerie
galleryEvents.setOnItemClickListener(vuePrincipaleController);
listview.setOnItemClickListener(vuePrincipaleController);
//Ajout de l'événements du pull to refresh
//pullToRefreshListView.setOnRefreshListener(vuePrincipaleController);
}
public void onResume(){
super.onResume();
boutonALaUne.setPressed(true);
boutonALaUne.setClickable(false);
}
public void initAdapters(){
//Envoie de l'evenements issue de la gallerie de la vue principale
galleryEvents.setAdapter(vuePrincipaleController.initGalleryAdapter());
listview.setAdapter(vuePrincipaleController.initNewsAdapter());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//Initialisation du layout
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.optionmenu, menu);
return super.onCreateOptionsMenu(menu);
}
//méthode qui permet de gérer les options clic droit sur la vue principal
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.share:
tracker.trackEvent("Accueil", "option", "partage application", 1);
dialog=new CategoriesDialog(this, "Partager l'application", "", "", "Annuler", items, -1, 3);
dialog.addInfos("Application Le Mans News & Evénements", "https://market.android.com/details?id=fr.clivana.lemansnews", "logoLeMans");
dialog.getBuilder().show();
break;
case R.id.actualiseroption:
tracker.trackEvent("Accueil", "option", "actualisation", 1);
vuePrincipaleController.Actualisation();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
tracker.stopSession();
super.onDestroy();
}
public void setDate() {
derniereMaj.setText("Actualisé le : "+getSharedPreferences("prefs", 0).getString("date", ""));
}
//facebook retour de la requête envoyée a facebook
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==FacebookFunctions.FACEBOOK_REQUEST_CODE){
FacebookFunctions.handleLoginResult(resultCode, data);
}
}
public void register() {
Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
intent.putExtra("app",PendingIntent.getBroadcast(this, 0, new Intent(), 0));
intent.putExtra("sender", "clivanadev@gmail.com");
startService(intent);
}
public void showRegistrationId() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
String string = prefs.getString(AUTH, "n/a");
Toast.makeText(this, string, Toast.LENGTH_LONG).show();
Log.d("C2DM RegId", string);
}
//Méthode pour rafraichir le pulltoRefresh au niveau visuel
// public void refreshVisuActivity (){
//
// pullToRefreshListView.onRefreshComplete();
//
// }
}
|
/*
* 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 ui;
import domein.DomeinController;
import java.util.InputMismatchException;
import java.util.Scanner;
import resources.Taal;
/**
*
* @author anneliesdewolf
*/
public class UC2_Console {
Scanner input = new Scanner(System.in);
private final DomeinController dc;
public UC2_Console(DomeinController dc) {
this.dc = dc;
}
public void doeUC2(int taal) {
UC3_4_Console uc34 = new UC3_4_Console(dc);
int aantal = 0;
boolean vlag = true;
do {
try {
System.out.print(Taal.geefString("aantalSpelers"));
aantal = input.nextInt();
if (aantal > 4 || aantal < 2) {
throw new IllegalArgumentException("Foutief aantal!");
}
vlag = false;
} catch (IllegalArgumentException e) {
System.out.println(Taal.geefString("\u001B[31maantalErr\u001B[0m"));
} catch (InputMismatchException e) {
System.out.println(Taal.geefString("\u001B[31maantalSInt\u001B[0m"));
input.nextLine();
}
} while (vlag);
dc.maakNieuwSpel(taal, aantal);
dc.geefAantalSpelers(aantal);
boolean herhalen = true;
do {
try {
geefGegevensIn(aantal);
herhalen = false;
}catch (InputMismatchException e){
System.out.println(Taal.geefString("\u001B[31merrLeeftijd\u001B[0m"));
input.nextLine();
} catch (IllegalArgumentException e) {
System.out.println("\u001B[31m" + e.getMessage() + "\u001B[0m");
input.nextLine();
}
} while (herhalen);
String[] overzicht = dc.toonGegevensSpelers();
for (String lijn : overzicht) {
System.out.println(lijn);
}
System.out.printf("%n%s:%n%s%n%n", Taal.geefString("volgorde"), dc.bepaalBeurt());
uc34.DoeUC3_4(overzicht);
}
private void geefGegevensIn(int aantal) {
for (int i = 0; i < aantal; i++) {
System.out.println(Taal.geefString("spelerNr") + (i + 1));
System.out.print(Taal.geefString("naamSpeler"));
String naam = input.next();
System.out.print(Taal.geefString("geboortejaar"));
int geboortejaar = input.nextInt();
System.out.print(Taal.geefString("kleurSpeler"));
String kleur = input.next();
System.out.println();
//System.out.printf("%s%s %s%d %s%s%n", Taal.geefString("naamOverzicht"),naam, Taal.geefString("geboortejaarOverzicht"), geboortejaar, Taal.geefString("kleurOverzicht"), kleur);
dc.geefGegevensIn(i, naam, geboortejaar, kleur);
}
}
private void toonDoolhof(String[][][] spelbord) {
for (String[][] spelbord1 : spelbord) {
//rij binnen doolhof
for (int rijKaart = 0; rijKaart < 3; rijKaart++) {
for (String[] spelbord11 : spelbord1) {
//kaart binnen rij
System.out.print(spelbord11[rijKaart] + "\t");
}
System.out.println();
}
System.out.println();
}
}
private void toonVrijeGangkaart(String[] vrije) {
for (String vrije1 : vrije) {
System.out.print(vrije1 + "\n");
}
}
}
|
package com.coinhunter.utils.http;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
@Slf4j
public class HttpClientTest {
private HttpClient httpClient = new HttpClient();
@Test
public void getTest() {
//0 : 1 H:3 L :4 c:2 rate : 5
long startTime = System.currentTimeMillis();
//https://www.bithumb.com/resources/chart/XEM_xcoinTrade_10M.json?symbol=XEM&resolution=0.5&from=1527862876&to=1528726936&strTime=1528726876754
//https://www.bithumb.com/resources/chart/BTC_xcoinTrade_10M.json?symbol=BTC&resolution=0.5&from=1527862257&to=1528726317&strTime=1528726257216
String result = httpClient.get("https://api.bithumb.com/public/ticker/EOS");
log.info("result : {}", result);
long endTime = System.currentTimeMillis() - startTime;
log.info("endTime : {}", endTime);
}
}
|
/*
* 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 ejb.session.stateless;
import entity.AircraftConfiguration;
import entity.CabinClass;
import entity.CabinClassConfiguration;
import java.util.ArrayList;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author Administrator
*/
@Stateless
public class CabinClassSessionBean implements CabinClassSessionBeanRemote, CabinClassSessionBeanLocal {
@PersistenceContext(unitName = "FlightReservationSystem-ejbPU")
private EntityManager em;
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
@Override
public CabinClass createNewCabinClass (CabinClass newCabinClass, CabinClassConfiguration newCabinClassConfiguration) {
em.persist(newCabinClass);
em.persist(newCabinClassConfiguration);
newCabinClass.setCabinClassConfiguration(newCabinClassConfiguration);
em.flush();
return newCabinClass;
}
}
|
public class Demo{
public static void printLoop(int n){
for (int i=0; i<n; i++){
for (int j=1; j<=(n-i); j++){
System.out.print(i+1);
}
System.out.println();
}
}
public static String arrToString(int[] arr){
String ans="{";
if (arr.length==0){
return "{}";
}
for (int i=0; i<arr.length-1; i++){
ans+=arr[i] + ", ";
}
ans+=arr[arr.length-1]+"}";
return ans;
}
public static String arrayDeepToString(int[][]arr){
String ans="{";
for (int i=0; i<arr.length-1; i++){
ans+=(arrToString(arr[i]));
if (i!=arr.length-2){
ans+=", ";
}
}
ans+="}";
return ans;
}
public static int[][] create2DArray(int rows, int cols, int maxValue){
int[][] arr= new int[rows+1][cols];
for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
arr[i][j]=(int)((maxValue+1) * Math.random());
}
}
return arr;
}
public static int[][] create2DArrayRandomized(int rows, int cols, int maxValue){
int[][] arr= new int[rows+1][];
for (int i=0; i<arr.length; i++){
arr[i]=new int [(int)((cols+1) * Math.random())];
for (int j=0; j<arr[i].length; j++){
arr[i][j]=(int)((maxValue+1) * Math.random());
}
}
return arr;
}
public static void main(String[] args){
if (args.length!=0){
printLoop(Integer.parseInt(args[0]));
}else{
printLoop(5);
}
//tests
/*
int[] a = {1, 2, 3};
int[] b = {1, 2, 3, 4};
int[] c = {1, 2, 3, 4, 5};
int[] d = {1, 2, 3, 4, 5, 6};
int[] e = {1, 2, 3, 4, 5, 6, 7};
int[][] x = new int[a.length][b.length];
x[0]=a;
x[1]=b;
System.out.println(arrToString(a));
System.out.println(arrToString(b));
System.out.println(arrToString(c));
System.out.println(arrToString(d));
System.out.println(arrToString(e));
System.out.println(arrToString(x[1]));
System.out.println(arrayDeepToString(x));
System.out.println(arrayDeepToString(x).replace("}, ","},\n"));
System.out.println(arrayDeepToString(create2DArray(4, 11, 5)).replace("}, ","},\n"));
System.out.println(arrayDeepToString(create2DArrayRandomized(4, 5, 6)).replace("}, ","},\n"));
*/
}
}
|
package by.imag.app.classes;
public class TagItem {
private String tagName;
private String tagURL;
private int postCount;
public TagItem(String tagName, String tagURL, int postCount) {
this.tagName = tagName;
this.tagURL = tagURL;
this.postCount = postCount;
}
public String getTagName() {
return tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
public String getTagURL() {
return tagURL;
}
public void setTagURL(String tagURL) {
this.tagURL = tagURL;
}
public int getPostCount() {
return postCount;
}
public void setPostCount(int postCount) {
this.postCount = postCount;
}
}
|
package ms.ui;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import javafx.fxml.FXML;
import javafx.scene.layout.GridPane;
import ms.events.BlockEvent;
import ms.events.Difficulty;
import ms.events.GameOverEvent;
import ms.model.Block;
import ms.model.BoardInteractionFactory;
@Component
public class BoardController {
@FXML
private GridPane board;
private double blockSize;
private BoardUpdatingService boardService;
private BoardInteractionFactory interactFact;
private BlocksConfiguration config;
public BoardController(@Value("${spring.application.ui.blockSize}") double blockSize,
BoardInteractionFactory interactFact,
BlocksConfiguration config) {
this.blockSize = blockSize;
this.interactFact = interactFact;
this.config = config;
}
public void initialize() {
boardService = new BoardUpdatingService(board, blockSize);
}
public void setup(Difficulty difficulty) {
boardService.reset(difficulty,
config.getBlocks(
difficulty.getNumRows(),
difficulty.getNumCols(),
interactFact.getService(difficulty)));
}
@EventListener(condition="#event.isSafeReveal()")
public void onSafeReveal(BlockEvent event) {
Block block = event.getBlock();
boardService.remove(block.getRow(), block.getCol());
if (block.getVal() > 0) {
boardService.reveal(block.getRow(), block.getCol(), block.getVal());
}
}
@EventListener(condition="#event.isFlag()")
public void onFlag(BlockEvent event) {
Block block = event.getBlock();
boardService.flag(block.getRow(), block.getCol());
}
@EventListener(condition="#event.isUnFlag()")
public void onUnFlag(BlockEvent event) {
Block block = event.getBlock();
boardService.unFlag(block.getRow(), block.getCol());
}
@EventListener(condition="#event.isBadFlag()")
public void onBadFlag(BlockEvent event) {
Block block = event.getBlock();
boardService.remove(block.getRow(), block.getCol());
boardService.displayBadFlag(block.getRow(), block.getCol());
}
@EventListener(condition="#event.isBombChosen()")
public void onBombChosen(BlockEvent event) {
Block block = event.getBlock();
boardService.remove(block.getRow(), block.getCol());
boardService.displayBombChosen(block.getRow(), block.getCol());
}
@EventListener(condition="#event.isBombReveal()")
public void onBombReveal(BlockEvent event) {
Block block = event.getBlock();
boardService.remove(block.getRow(), block.getCol());
boardService.displayBomb(block.getRow(), block.getCol());
}
@EventListener(condition="event.isGameWon()")
public void onGameWon(GameOverEvent event) {
//TODO
}
@EventListener(condition="event.isGameLost()")
public void onGameLost(GameOverEvent event) {
//TODO
}
} |
package com.appium.pageObject.tests;
import com.appium.pageObject.pages.HomePage;
import com.appium.pageObject.pages.InputControlsPage;
import com.appium.pageObject.utils.BaseTest;
import org.junit.Assert;
import org.testng.annotations.Test;
/**
* Created by syamsasi on 07/02/17.
*/
public class EnterTextTest extends BaseTest{
HomePage homePage;
@Test
public void enterText() throws InterruptedException {
homePage = new HomePage(driver);
String inputString="Singapore Appium Meetup";
InputControlsPage inputControlsPage = homePage.clickMenu().clickInputControls().enterText(inputString);
Thread.sleep(2000);
Assert.assertEquals(inputControlsPage.getCurrentTextValue(),inputString);
}
}
|
package com.tiandi.logistics.shiro;
import com.tiandi.logistics.utils.JWTUtil;
import com.tiandi.logistics.utils.RedisUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
/**
* @author Yue Wu
* @version 1.0
* @since 2020/11/23 15:43
*/
@Component
public class CustomRealm extends AuthorizingRealm {
@Autowired
private RedisUtil redisUtil;
@Resource(name = "createThreadPool")
private ExecutorService chickPool;
/**
* 必须重写此方法,不然会报错
*/
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JWTToken;
}
/**
* 默认使用此方法进行用户名正确与否验证,错误抛出异常即可。
* <p>
* 使用Redis此处校验Redis缓存,如不存在则直接抛校验异常 存在则正常返回
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
String token = (String) authenticationToken.getCredentials();
// 解密获得username,用于和数据库进行对比
String username = JWTUtil.getUsername(token);
String tokenCache = (String) redisUtil.hasKeyReturn(username);
if (tokenCache == null) {
throw new AuthenticationException("token认证失败!");
} else {
if (token.equals(tokenCache)) {
return new SimpleAuthenticationInfo(token, token, "MyRealm");
} else {
throw new AuthenticationException("该账号在其他地点登陆!");
}
}
}
/**
* 只有当需要检测用户权限的时候才会调用此方法,例如checkRole,checkPermission之类的
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
@SuppressWarnings("unchecked")
Future future = chickPool.submit(new Callable() {
@Override
public Object call() throws Exception {
String token = principals.toString();
String username = JWTUtil.getUsername(token);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 获得该用户角色
String role = JWTUtil.getUserRole(token);
// 每个用户可以设置新的权限
String permission = JWTUtil.getUserPermission(token);
Set<String> roleSet = new HashSet<>();
Set<String> permissionSet = new HashSet<>();
roleSet.add(role);
permissionSet.add(permission);
// 设置该用户拥有的角色和权限
info.setRoles(roleSet);
info.setStringPermissions(permissionSet);
return info;
}
});
try {
return (AuthorizationInfo) future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
}
|
/*
* Copyright (C) 2021-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.test.e2e.acceptance.client;
import com.hedera.hashgraph.sdk.KeyList;
import com.hedera.hashgraph.sdk.PrivateKey;
import com.hedera.hashgraph.sdk.ScheduleCreateTransaction;
import com.hedera.hashgraph.sdk.ScheduleDeleteTransaction;
import com.hedera.hashgraph.sdk.ScheduleId;
import com.hedera.hashgraph.sdk.ScheduleSignTransaction;
import com.hedera.hashgraph.sdk.Transaction;
import com.hedera.mirror.test.e2e.acceptance.props.ExpandedAccountId;
import com.hedera.mirror.test.e2e.acceptance.response.NetworkTransactionResponse;
import jakarta.inject.Named;
import java.util.List;
import org.springframework.retry.support.RetryTemplate;
@Named
public class ScheduleClient extends AbstractNetworkClient {
public ScheduleClient(SDKClient sdkClient, RetryTemplate retryTemplate) {
super(sdkClient, retryTemplate);
}
public NetworkTransactionResponse createSchedule(
ExpandedAccountId payerAccountId, Transaction<?> transaction, KeyList signatureKeyList) {
var memo = getMemo("Create schedule");
ScheduleCreateTransaction scheduleCreateTransaction = new ScheduleCreateTransaction()
.setAdminKey(payerAccountId.getPublicKey())
.setPayerAccountId(payerAccountId.getAccountId())
.setScheduleMemo(memo)
.setScheduledTransaction(transaction)
.setTransactionMemo(memo);
if (signatureKeyList != null) {
scheduleCreateTransaction
.setNodeAccountIds(List.of(sdkClient.getRandomNodeAccountId()))
.freezeWith(client);
// add initial set of required signatures to ScheduleCreate transaction
signatureKeyList.forEach(k -> {
PrivateKey pk = (PrivateKey) k;
byte[] signature = pk.signTransaction(scheduleCreateTransaction);
scheduleCreateTransaction.addSignature(pk.getPublicKey(), signature);
});
}
var response = executeTransactionAndRetrieveReceipt(scheduleCreateTransaction);
var scheduleId = response.getReceipt().scheduleId;
log.info("Created new schedule {} with memo '{}' via {}", scheduleId, memo, response.getTransactionId());
return response;
}
public NetworkTransactionResponse signSchedule(ExpandedAccountId expandedAccountId, ScheduleId scheduleId) {
ScheduleSignTransaction scheduleSignTransaction =
new ScheduleSignTransaction().setScheduleId(scheduleId).setTransactionMemo(getMemo("Sign schedule"));
var keyList = KeyList.of(expandedAccountId.getPrivateKey());
var response = executeTransactionAndRetrieveReceipt(scheduleSignTransaction, keyList);
log.info("Signed schedule {} via {}", scheduleId, response.getTransactionId());
return response;
}
public NetworkTransactionResponse deleteSchedule(ScheduleId scheduleId) {
ScheduleDeleteTransaction scheduleDeleteTransaction = new ScheduleDeleteTransaction()
.setScheduleId(scheduleId)
.setTransactionMemo(getMemo("Delete schedule"));
var response = executeTransactionAndRetrieveReceipt(scheduleDeleteTransaction);
log.info("Deleted schedule {} via {}", scheduleId, response.getTransactionId());
return response;
}
}
|
package com.concordia.soen6441riskgame;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.Component;
import javax.swing.border.LineBorder;
public class Prueba extends JFrame {
private JPanel right;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Prueba frame = new Prueba();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Prueba() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 367, 217);
right = new JPanel();
right.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
setContentPane(right);
right.setLayout(null);
JLabel lblSetupPhase = new JLabel("WORLD DOMINATION VIEW");
lblSetupPhase.setBounds(111, 11, 205, 33);
right.add(lblSetupPhase);
JLabel lblMapCntrol = new JLabel("Map Control");
lblMapCntrol.setBounds(44, 55, 103, 33);
right.add(lblMapCntrol);
JLabel label = new JLabel("0");
label.setFont(new Font("Tahoma", Font.PLAIN, 17));
label.setBounds(202, 55, 50, 33);
right.add(label);
JLabel lblContinentsControlled = new JLabel("Continents Controlled");
lblContinentsControlled.setBounds(44, 76, 152, 33);
right.add(lblContinentsControlled);
JLabel lblArmyOwned = new JLabel("Army Owned");
lblArmyOwned.setAlignmentX(Component.RIGHT_ALIGNMENT);
lblArmyOwned.setBounds(44, 136, 115, 33);
right.add(lblArmyOwned);
JLabel label_4 = new JLabel("0");
label_4.setFont(new Font("Tahoma", Font.PLAIN, 17));
label_4.setBounds(202, 133, 50, 33);
right.add(label_4);
JTextArea textArea = new JTextArea();
textArea.setBounds(202, 87, 125, 46);
right.add(textArea);
}
}
|
package com.cognitive.newswizard.service.translator;
import com.cognitive.newswizard.api.vo.newsfeed.RawFeedEntryVO;
import com.cognitive.newswizard.service.entity.RawFeedEntryEntity;
public class RawFeedEntryTranslator {
public static RawFeedEntryEntity toEntity(final RawFeedEntryVO valueObject) {
return new RawFeedEntryEntity(
valueObject.getId(),
valueObject.getFeedEntryId(),
valueObject.getTitle(),
valueObject.getAddress(),
valueObject.getPublishedDateTime(),
valueObject.getContent(),
valueObject.getFeedSourceId(),
valueObject.getCompactContent());
}
public static RawFeedEntryVO toValueObject(final RawFeedEntryEntity entity) {
return new RawFeedEntryVO(
entity.getId(),
entity.getFeedEntryId(),
entity.getTitle(),
entity.getAddress(),
entity.getPublishedDateTime(),
entity.getContent(),
entity.getFeedSourceId(),
entity.getCompactContent());
}
}
|
package pl.edu.charzynm;
public enum SeparableVerbsPrefixes {
AB("ab"),
AN("an"),
AUF("auf"),
AUS("aus"),
AUSEINANDER("auseinander"),
BEI("bei"),
EIN("ein"),
EMPOR("empor"),
ENTGEGEN("entgegen"),
ENTLANG("entlang"),
ENTZWEI("entzwei"),
FERN("fern"),
FEST("fest"),
FORT("fort"),
FUR("für"),
GEGEN("gegen"),
GEGENUBER("gegenüber"),
HEIM("heim"),
HINTERHER("hinterher"),
HOCH("hoch"),
LOS("los"),
MIT("mit"),
NACH("nach"),
NEBEN("neben"),
NIEDER("nieder"),
VOR("vor"),
WEB("weg"),
WEITER("weiter"),
ZU("zu"),
ZURECHT("zurecht"),
ZURUCK("zurück"),
ZUSAMMEN("zusammen"),
DA("da"),
HIN("hin"),
HER("her");
private String value;
SeparableVerbsPrefixes(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
|
package pe.gob.trabajo.web.rest;
import pe.gob.trabajo.LiquidacionesApp;
import pe.gob.trabajo.domain.Tipcalconre;
import pe.gob.trabajo.repository.TipcalconreRepository;
import pe.gob.trabajo.repository.search.TipcalconreSearchRepository;
import pe.gob.trabajo.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the TipcalconreResource REST controller.
*
* @see TipcalconreResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LiquidacionesApp.class)
public class TipcalconreResourceIntTest {
private static final String DEFAULT_V_NOMTCAL = "AAAAAAAAAA";
private static final String UPDATED_V_NOMTCAL = "BBBBBBBBBB";
private static final Integer DEFAULT_N_USUAREG = 1;
private static final Integer UPDATED_N_USUAREG = 2;
private static final Instant DEFAULT_T_FECREG = Instant.ofEpochMilli(0L);
private static final Instant UPDATED_T_FECREG = Instant.now().truncatedTo(ChronoUnit.MILLIS);
private static final Boolean DEFAULT_N_FLGACTIVO = false;
private static final Boolean UPDATED_N_FLGACTIVO = true;
private static final Integer DEFAULT_N_SEDEREG = 1;
private static final Integer UPDATED_N_SEDEREG = 2;
private static final Integer DEFAULT_N_USUAUPD = 1;
private static final Integer UPDATED_N_USUAUPD = 2;
private static final Instant DEFAULT_T_FECUPD = Instant.ofEpochMilli(0L);
private static final Instant UPDATED_T_FECUPD = Instant.now().truncatedTo(ChronoUnit.MILLIS);
private static final Integer DEFAULT_N_SEDEUPD = 1;
private static final Integer UPDATED_N_SEDEUPD = 2;
@Autowired
private TipcalconreRepository tipcalconreRepository;
@Autowired
private TipcalconreSearchRepository tipcalconreSearchRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restTipcalconreMockMvc;
private Tipcalconre tipcalconre;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final TipcalconreResource tipcalconreResource = new TipcalconreResource(tipcalconreRepository, tipcalconreSearchRepository);
this.restTipcalconreMockMvc = MockMvcBuilders.standaloneSetup(tipcalconreResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Tipcalconre createEntity(EntityManager em) {
Tipcalconre tipcalconre = new Tipcalconre()
.vNomtcal(DEFAULT_V_NOMTCAL)
.nUsuareg(DEFAULT_N_USUAREG)
.tFecreg(DEFAULT_T_FECREG)
.nFlgactivo(DEFAULT_N_FLGACTIVO)
.nSedereg(DEFAULT_N_SEDEREG)
.nUsuaupd(DEFAULT_N_USUAUPD)
.tFecupd(DEFAULT_T_FECUPD)
.nSedeupd(DEFAULT_N_SEDEUPD);
return tipcalconre;
}
@Before
public void initTest() {
tipcalconreSearchRepository.deleteAll();
tipcalconre = createEntity(em);
}
@Test
@Transactional
public void createTipcalconre() throws Exception {
int databaseSizeBeforeCreate = tipcalconreRepository.findAll().size();
// Create the Tipcalconre
restTipcalconreMockMvc.perform(post("/api/tipcalconres")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipcalconre)))
.andExpect(status().isCreated());
// Validate the Tipcalconre in the database
List<Tipcalconre> tipcalconreList = tipcalconreRepository.findAll();
assertThat(tipcalconreList).hasSize(databaseSizeBeforeCreate + 1);
Tipcalconre testTipcalconre = tipcalconreList.get(tipcalconreList.size() - 1);
assertThat(testTipcalconre.getvNomtcal()).isEqualTo(DEFAULT_V_NOMTCAL);
assertThat(testTipcalconre.getnUsuareg()).isEqualTo(DEFAULT_N_USUAREG);
assertThat(testTipcalconre.gettFecreg()).isEqualTo(DEFAULT_T_FECREG);
assertThat(testTipcalconre.isnFlgactivo()).isEqualTo(DEFAULT_N_FLGACTIVO);
assertThat(testTipcalconre.getnSedereg()).isEqualTo(DEFAULT_N_SEDEREG);
assertThat(testTipcalconre.getnUsuaupd()).isEqualTo(DEFAULT_N_USUAUPD);
assertThat(testTipcalconre.gettFecupd()).isEqualTo(DEFAULT_T_FECUPD);
assertThat(testTipcalconre.getnSedeupd()).isEqualTo(DEFAULT_N_SEDEUPD);
// Validate the Tipcalconre in Elasticsearch
Tipcalconre tipcalconreEs = tipcalconreSearchRepository.findOne(testTipcalconre.getId());
assertThat(tipcalconreEs).isEqualToComparingFieldByField(testTipcalconre);
}
@Test
@Transactional
public void createTipcalconreWithExistingId() throws Exception {
int databaseSizeBeforeCreate = tipcalconreRepository.findAll().size();
// Create the Tipcalconre with an existing ID
tipcalconre.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restTipcalconreMockMvc.perform(post("/api/tipcalconres")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipcalconre)))
.andExpect(status().isBadRequest());
// Validate the Tipcalconre in the database
List<Tipcalconre> tipcalconreList = tipcalconreRepository.findAll();
assertThat(tipcalconreList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkvNomtcalIsRequired() throws Exception {
int databaseSizeBeforeTest = tipcalconreRepository.findAll().size();
// set the field null
tipcalconre.setvNomtcal(null);
// Create the Tipcalconre, which fails.
restTipcalconreMockMvc.perform(post("/api/tipcalconres")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipcalconre)))
.andExpect(status().isBadRequest());
List<Tipcalconre> tipcalconreList = tipcalconreRepository.findAll();
assertThat(tipcalconreList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checknUsuaregIsRequired() throws Exception {
int databaseSizeBeforeTest = tipcalconreRepository.findAll().size();
// set the field null
tipcalconre.setnUsuareg(null);
// Create the Tipcalconre, which fails.
restTipcalconreMockMvc.perform(post("/api/tipcalconres")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipcalconre)))
.andExpect(status().isBadRequest());
List<Tipcalconre> tipcalconreList = tipcalconreRepository.findAll();
assertThat(tipcalconreList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checktFecregIsRequired() throws Exception {
int databaseSizeBeforeTest = tipcalconreRepository.findAll().size();
// set the field null
tipcalconre.settFecreg(null);
// Create the Tipcalconre, which fails.
restTipcalconreMockMvc.perform(post("/api/tipcalconres")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipcalconre)))
.andExpect(status().isBadRequest());
List<Tipcalconre> tipcalconreList = tipcalconreRepository.findAll();
assertThat(tipcalconreList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checknFlgactivoIsRequired() throws Exception {
int databaseSizeBeforeTest = tipcalconreRepository.findAll().size();
// set the field null
tipcalconre.setnFlgactivo(null);
// Create the Tipcalconre, which fails.
restTipcalconreMockMvc.perform(post("/api/tipcalconres")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipcalconre)))
.andExpect(status().isBadRequest());
List<Tipcalconre> tipcalconreList = tipcalconreRepository.findAll();
assertThat(tipcalconreList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checknSederegIsRequired() throws Exception {
int databaseSizeBeforeTest = tipcalconreRepository.findAll().size();
// set the field null
tipcalconre.setnSedereg(null);
// Create the Tipcalconre, which fails.
restTipcalconreMockMvc.perform(post("/api/tipcalconres")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipcalconre)))
.andExpect(status().isBadRequest());
List<Tipcalconre> tipcalconreList = tipcalconreRepository.findAll();
assertThat(tipcalconreList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllTipcalconres() throws Exception {
// Initialize the database
tipcalconreRepository.saveAndFlush(tipcalconre);
// Get all the tipcalconreList
restTipcalconreMockMvc.perform(get("/api/tipcalconres?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(tipcalconre.getId().intValue())))
.andExpect(jsonPath("$.[*].vNomtcal").value(hasItem(DEFAULT_V_NOMTCAL.toString())))
.andExpect(jsonPath("$.[*].nUsuareg").value(hasItem(DEFAULT_N_USUAREG)))
.andExpect(jsonPath("$.[*].tFecreg").value(hasItem(DEFAULT_T_FECREG.toString())))
.andExpect(jsonPath("$.[*].nFlgactivo").value(hasItem(DEFAULT_N_FLGACTIVO.booleanValue())))
.andExpect(jsonPath("$.[*].nSedereg").value(hasItem(DEFAULT_N_SEDEREG)))
.andExpect(jsonPath("$.[*].nUsuaupd").value(hasItem(DEFAULT_N_USUAUPD)))
.andExpect(jsonPath("$.[*].tFecupd").value(hasItem(DEFAULT_T_FECUPD.toString())))
.andExpect(jsonPath("$.[*].nSedeupd").value(hasItem(DEFAULT_N_SEDEUPD)));
}
@Test
@Transactional
public void getTipcalconre() throws Exception {
// Initialize the database
tipcalconreRepository.saveAndFlush(tipcalconre);
// Get the tipcalconre
restTipcalconreMockMvc.perform(get("/api/tipcalconres/{id}", tipcalconre.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(tipcalconre.getId().intValue()))
.andExpect(jsonPath("$.vNomtcal").value(DEFAULT_V_NOMTCAL.toString()))
.andExpect(jsonPath("$.nUsuareg").value(DEFAULT_N_USUAREG))
.andExpect(jsonPath("$.tFecreg").value(DEFAULT_T_FECREG.toString()))
.andExpect(jsonPath("$.nFlgactivo").value(DEFAULT_N_FLGACTIVO.booleanValue()))
.andExpect(jsonPath("$.nSedereg").value(DEFAULT_N_SEDEREG))
.andExpect(jsonPath("$.nUsuaupd").value(DEFAULT_N_USUAUPD))
.andExpect(jsonPath("$.tFecupd").value(DEFAULT_T_FECUPD.toString()))
.andExpect(jsonPath("$.nSedeupd").value(DEFAULT_N_SEDEUPD));
}
@Test
@Transactional
public void getNonExistingTipcalconre() throws Exception {
// Get the tipcalconre
restTipcalconreMockMvc.perform(get("/api/tipcalconres/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateTipcalconre() throws Exception {
// Initialize the database
tipcalconreRepository.saveAndFlush(tipcalconre);
tipcalconreSearchRepository.save(tipcalconre);
int databaseSizeBeforeUpdate = tipcalconreRepository.findAll().size();
// Update the tipcalconre
Tipcalconre updatedTipcalconre = tipcalconreRepository.findOne(tipcalconre.getId());
updatedTipcalconre
.vNomtcal(UPDATED_V_NOMTCAL)
.nUsuareg(UPDATED_N_USUAREG)
.tFecreg(UPDATED_T_FECREG)
.nFlgactivo(UPDATED_N_FLGACTIVO)
.nSedereg(UPDATED_N_SEDEREG)
.nUsuaupd(UPDATED_N_USUAUPD)
.tFecupd(UPDATED_T_FECUPD)
.nSedeupd(UPDATED_N_SEDEUPD);
restTipcalconreMockMvc.perform(put("/api/tipcalconres")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedTipcalconre)))
.andExpect(status().isOk());
// Validate the Tipcalconre in the database
List<Tipcalconre> tipcalconreList = tipcalconreRepository.findAll();
assertThat(tipcalconreList).hasSize(databaseSizeBeforeUpdate);
Tipcalconre testTipcalconre = tipcalconreList.get(tipcalconreList.size() - 1);
assertThat(testTipcalconre.getvNomtcal()).isEqualTo(UPDATED_V_NOMTCAL);
assertThat(testTipcalconre.getnUsuareg()).isEqualTo(UPDATED_N_USUAREG);
assertThat(testTipcalconre.gettFecreg()).isEqualTo(UPDATED_T_FECREG);
assertThat(testTipcalconre.isnFlgactivo()).isEqualTo(UPDATED_N_FLGACTIVO);
assertThat(testTipcalconre.getnSedereg()).isEqualTo(UPDATED_N_SEDEREG);
assertThat(testTipcalconre.getnUsuaupd()).isEqualTo(UPDATED_N_USUAUPD);
assertThat(testTipcalconre.gettFecupd()).isEqualTo(UPDATED_T_FECUPD);
assertThat(testTipcalconre.getnSedeupd()).isEqualTo(UPDATED_N_SEDEUPD);
// Validate the Tipcalconre in Elasticsearch
Tipcalconre tipcalconreEs = tipcalconreSearchRepository.findOne(testTipcalconre.getId());
assertThat(tipcalconreEs).isEqualToComparingFieldByField(testTipcalconre);
}
@Test
@Transactional
public void updateNonExistingTipcalconre() throws Exception {
int databaseSizeBeforeUpdate = tipcalconreRepository.findAll().size();
// Create the Tipcalconre
// If the entity doesn't have an ID, it will be created instead of just being updated
restTipcalconreMockMvc.perform(put("/api/tipcalconres")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(tipcalconre)))
.andExpect(status().isCreated());
// Validate the Tipcalconre in the database
List<Tipcalconre> tipcalconreList = tipcalconreRepository.findAll();
assertThat(tipcalconreList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteTipcalconre() throws Exception {
// Initialize the database
tipcalconreRepository.saveAndFlush(tipcalconre);
tipcalconreSearchRepository.save(tipcalconre);
int databaseSizeBeforeDelete = tipcalconreRepository.findAll().size();
// Get the tipcalconre
restTipcalconreMockMvc.perform(delete("/api/tipcalconres/{id}", tipcalconre.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate Elasticsearch is empty
boolean tipcalconreExistsInEs = tipcalconreSearchRepository.exists(tipcalconre.getId());
assertThat(tipcalconreExistsInEs).isFalse();
// Validate the database is empty
List<Tipcalconre> tipcalconreList = tipcalconreRepository.findAll();
assertThat(tipcalconreList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void searchTipcalconre() throws Exception {
// Initialize the database
tipcalconreRepository.saveAndFlush(tipcalconre);
tipcalconreSearchRepository.save(tipcalconre);
// Search the tipcalconre
restTipcalconreMockMvc.perform(get("/api/_search/tipcalconres?query=id:" + tipcalconre.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(tipcalconre.getId().intValue())))
.andExpect(jsonPath("$.[*].vNomtcal").value(hasItem(DEFAULT_V_NOMTCAL.toString())))
.andExpect(jsonPath("$.[*].nUsuareg").value(hasItem(DEFAULT_N_USUAREG)))
.andExpect(jsonPath("$.[*].tFecreg").value(hasItem(DEFAULT_T_FECREG.toString())))
.andExpect(jsonPath("$.[*].nFlgactivo").value(hasItem(DEFAULT_N_FLGACTIVO.booleanValue())))
.andExpect(jsonPath("$.[*].nSedereg").value(hasItem(DEFAULT_N_SEDEREG)))
.andExpect(jsonPath("$.[*].nUsuaupd").value(hasItem(DEFAULT_N_USUAUPD)))
.andExpect(jsonPath("$.[*].tFecupd").value(hasItem(DEFAULT_T_FECUPD.toString())))
.andExpect(jsonPath("$.[*].nSedeupd").value(hasItem(DEFAULT_N_SEDEUPD)));
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Tipcalconre.class);
Tipcalconre tipcalconre1 = new Tipcalconre();
tipcalconre1.setId(1L);
Tipcalconre tipcalconre2 = new Tipcalconre();
tipcalconre2.setId(tipcalconre1.getId());
assertThat(tipcalconre1).isEqualTo(tipcalconre2);
tipcalconre2.setId(2L);
assertThat(tipcalconre1).isNotEqualTo(tipcalconre2);
tipcalconre1.setId(null);
assertThat(tipcalconre1).isNotEqualTo(tipcalconre2);
}
}
|
package CSArmyBot.commands;
import CSArmyBot.main;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
public class SelfAssignCommand extends Command {
public SelfAssignCommand() {
this.name = "notify";
this.category = main.NORMAL;
this.guildOnly = true;
this.arguments = "<Role>";
this.help = "Assign your self a specific role to recive updates W.I.P";
this.ownerCommand = true;
}
//TODO Make this better
@Override
protected void execute(CommandEvent event) {
if (event.getArgs().isEmpty()) {
event.replyError("You must supply a role!");
return;
}
String[] args = event.getArgs().split(" ");
args[0].toLowerCase();
switch (args[0]) {
case "pokedash": {
event.getGuild().getController().addRolesToMember(event.getMember(), event.getGuild().getRolesByName("pokedash", true).get(0)).queue();
break;
}
case "pokeverse": {
event.getGuild().getController().addRolesToMember(event.getMember(), event.getGuild().getRolesByName("pokeverse", true).get(0)).queue();
break;
}
case "pokelegends": {
event.getGuild().getController().addRolesToMember(event.getMember(), event.getGuild().getRolesByName("pokelegends", true).get(0)).queue();
break;
}
case "pokeclub": {
event.getGuild().getController().addRolesToMember(event.getMember(), event.getGuild().getRolesByName("pokeclub", true).get(0)).queue();
break;
}
default: {
event.replyError("We do not support this role!");
return;
}
}
event.replySuccess("Successfully added " + args[0] + " tag!");
}
}
|
package com.ibm.jikesbt;
/*
* Licensed Material - Property of IBM
* (C) Copyright IBM Corp. 1998, 2003
* All rights reserved
*/
import java.io.DataInputStream;
import java.io.IOException;
/**
The info of a class that is read until its name is known.
* @author IBM
**/
// Added class to allow replacement of stub classes by read classes.
public class BT_ClassInfoUntilName extends BT_Base {
public int minorVersion;
public int majorVersion;
public BT_ConstantPool pool;
public short flags;
public String className;
/**
Reads start of class from a class file until its name is known.
@param dis An input stream from which class is read.
@param file A java.io.File or a java.util.zip.ZipFile.
**/
public void readUntilName(DataInputStream dis, Object file, BT_Repository repo)
throws BT_ClassFileException, IOException {
int magicRead = dis.readInt();
if (magicRead != BT_Class.MAGIC)
throw new BT_ClassFileException(Messages.getString("JikesBT.bad_magic____not_a_Java_class_file_1"));
minorVersion = dis.readUnsignedShort();
majorVersion = dis.readUnsignedShort();
pool = repo.createConstantPool();
if (CHECK_USER && 1 != pool.size())
assertFailure(Messages.getString("JikesBT.The_constant_pool_should_be_empty_2"));
try {
pool.read(dis);
flags = dis.readShort();
className =
pool.getClassNameAt(dis.readUnsignedShort(), BT_ConstantPool.CLASS);
} catch(BT_ConstantPoolException e) {
throw new BT_ClassFileException(e);
} catch(BT_DescriptorException e) {
throw new BT_ClassFileException(e);
}
}
}
|
package com.jim.multipos.data.operations;
import com.jim.multipos.data.db.model.stock.Stock;
import java.util.List;
import io.reactivex.Observable;
/**
* Created by user on 17.08.17.
*/
public interface StockOperations {
Observable<Long> addStock(Stock stock);
Observable<Boolean> addStocks(List<Stock> stocks);
Observable<List<Stock>> getAllStocks();
Observable<Boolean> removeStock(Stock stock);
Observable<Boolean> removeAllStocks();
}
|
//
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
package com.wire.bots.sdk.assets;
import com.waz.model.Messages;
import java.util.UUID;
public class Ping implements IGeneric {
private final UUID messageId = UUID.randomUUID();
@Override
public Messages.GenericMessage createGenericMsg() {
Messages.Knock.Builder knock = Messages.Knock.newBuilder()
.setHotKnock(false);
return Messages.GenericMessage.newBuilder()
.setMessageId(getMessageId().toString())
.setKnock(knock)
.build();
}
@Override
public UUID getMessageId() {
return messageId;
}
}
|
package org.acme.kafka;
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@RegisterForReflection
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyRecord {
private String id;
// private String name;
private String payload;
// private String message;
private int myNumber;
}
|
package com.apprisingsoftware.xmasrogue.io;
import com.apprisingsoftware.util.ArrayUtil;
import com.apprisingsoftware.xmasrogue.util.Coord;
import java.awt.Color;
import java.util.Collection;
import java.util.Map;
public abstract class MenuScreen implements AsciiScreen {
protected final int width, height;
private final Map<Coord, Message> labels;
private boolean justCreated;
public MenuScreen(int width, int height, Map<Coord, Message> labels) {
this.width = width;
this.height = height;
this.labels = labels;
justCreated = true;
}
@Override public AsciiTile getTile(int x, int y) {
for (Map.Entry<Coord, Message> entry : labels.entrySet()) {
Coord loc = entry.getKey();
Message label = entry.getValue();
if (y == loc.y && x >= loc.x && x < loc.x + label.getText().length()) {
return new AsciiTile(label.getText().charAt(x - loc.x), label.getActiveColor(), getBackgroundColor(x, y));
}
}
return new AsciiTile(' ', Color.BLACK, getBackgroundColor(x, y));
}
protected abstract Color getBackgroundColor(int x, int y);
@Override public boolean isTransparent(int x, int y) {
return !inBounds(x, y);
}
@Override public Collection<Coord> getUpdatedTiles() {
if (justCreated) {
justCreated = false;
return ArrayUtil.cartesianProduct(width, height, (x, y) -> new Coord(x, y));
}
return getUpdatedBackgroundTiles();
}
public abstract Collection<Coord> getUpdatedBackgroundTiles();
@Override public int getWidth() {
return width;
}
@Override public int getHeight() {
return height;
}
}
|
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Client;
import model.ClientManager;
import model.Order;
import model.OrderManager;
import model.Pizza;
import model.PizzaManager;
import model.Printable;
public class Api extends HttpServlet{
private ClientManager clientMan = ClientManager.getInstance();
private PizzaManager pizzaMan = PizzaManager.getInstance();
private OrderManager orderMan = OrderManager.getInstance();
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String requestFormat = req.getHeader("Accept");
String format;
if( !requestFormat.contains("application/json") &&
!requestFormat.contains("application/xml")){
throw new InvalidHeaderException();
} else {
format = requestFormat.contains("application/json")? "json":"xml";
}
String baseUrl = req.getContextPath()+"/Api";
String reqUrl = req.getRequestURI();
PrintWriter out = resp.getWriter();
if( reqUrl.equals(baseUrl + "/pedidos") ){
Iterable<Order> orders = orderMan.getAll();
if(format.equals("xml")){
responseXml(orders, "pedidos", out);
} else {
responseJson(orders, out);
}
} else if( reqUrl.equals(baseUrl + "/clients") ){
Iterable<Client> clients = clientMan.getAll();
if(format.equals("xml")){
responseXml(clients, "clientes", out);
} else {
responseJson(clients, out);
}
} else if( reqUrl.equals(baseUrl + "/pizzas") ){
Iterable<Pizza> pizzas = pizzaMan.getAll();
if(format.equals("xml")){
responseXml(pizzas, "pizzas", out);
} else {
responseJson(pizzas, out);
}
} else {
throw new NotFoundException();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String requestFormat = req.getHeader("Accept");
String format;
if( !requestFormat.contains("application/json") &&
!requestFormat.contains("application/xml")){
throw new InvalidHeaderException();
} else {
format = requestFormat.contains("application/json")? "json":"xml";
}
String baseUrl = req.getContextPath()+"/Api";
String reqUrl = req.getRequestURI();
PrintWriter out = resp.getWriter();
String parts[] = reqUrl.split("/");
int len = parts.length;
String aux = "";
for (int i = 0 ; i < len - 1 ; ++i){
aux += parts[i] + "/";
}
Integer id;
if( aux.equals(baseUrl + "clientes/cliente/") ){
id = Integer.valueOf(req.getParameter("id"));
String name = req.getParameter("name");
String address = req.getParameter("address");
try {
id = Integer.valueOf(parts[len - 1]);
} catch( NumberFormatException e){
throw new IllegalArgumentException();
}
if(id == null || name == null || address == null){
throw new IllegalArgumentException();
}
Client client = clientMan.getClient(id);
client.setAddress(address);
client.setName(name);
List<Client> l = new ArrayList<Client>();
l.add(client);
if (format.equals("xml")){
responseXml(l, "clientes", out);
} else {
responseJson(l, out);
}
} else if( aux.equals(baseUrl + "/pedidos/pedido/") ){
Integer clientId, pizzaId;
try {
id = Integer.valueOf(parts[len - 1]);
clientId = Integer.valueOf(req.getParameter("client_id"));
pizzaId = Integer.valueOf(req.getParameter("pizza_id"));
} catch( NumberFormatException e){
throw new IllegalArgumentException();
}
try {
id = Integer.valueOf(parts[len - 1]);
} catch( NumberFormatException e){
throw new IllegalArgumentException();
}
if(id == null || clientId == null || pizzaId == null){
throw new IllegalArgumentException();
}
Order order = orderMan.getOrder(id);
Client client = clientMan.getClient(clientId);
Pizza pizza = pizzaMan.getPizza(pizzaId);
if (order == null || client == null || pizza == null){
throw new IllegalArgumentException();
}
order.setClient(client);
order.setPizza(pizza);
List<Order> l = new ArrayList<Order>();
l.add(order);
if(format.equals("xml")){
responseXml(l, "pedidos", out);
} else {
responseJson(l, out);
}
} else {
throw new NotFoundException();
}
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String requestFormat = req.getHeader("Accept");
String format;
if( !requestFormat.contains("application/json") &&
!requestFormat.contains("application/xml")){
throw new InvalidHeaderException();
} else {
format = requestFormat.contains("application/json")? "json":"xml";
}
String baseUrl = req.getContextPath()+"/Api";
String reqUrl = req.getRequestURI();
PrintWriter out = resp.getWriter();
if( reqUrl.equals(baseUrl + "/clientes/cliente") ){
String name = req.getParameter("name");
String address = req.getParameter("address");
if(name == null || address == null){
throw new IllegalArgumentException();
}
Client client = new Client(name,address);
List<Client> l = new ArrayList<Client>();
l.add(client);
clientMan.addClient(client);
if(format.equals("xml")){
responseXml(l, "clientes", out);
} else {
responseJson(l, out);
}
} else if( reqUrl.equals(baseUrl + "/pedidos/pedido") ){
Integer clientId, pizzaId, cant;
try {
clientId = Integer.valueOf(req.getParameter("client_id"));
pizzaId = Integer.valueOf(req.getParameter("pizza_id"));
cant = Integer.valueOf(req.getParameter("cant"));
} catch( NumberFormatException e){
throw new IllegalArgumentException();
}
Client client = clientMan.getClient(clientId);
Pizza pizza = pizzaMan.getPizza(pizzaId);
Order order = new Order(client, pizza, cant);
orderMan.addOrder(order);
List<Order> l = new ArrayList<Order>();
l.add(order);
if(format.equals("xml")){
responseXml(l, "pedidos", out);
} else {
responseJson(l, out);
}
} else {
throw new NotFoundException();
}
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String baseUrl = req.getContextPath()+"/Api";
String reqUrl = req.getRequestURI();
String parts[] = reqUrl.split("/");
int len = parts.length;
String aux = "";
for (int i = 0 ; i < len - 1 ; ++i){
aux += parts[i] + "/";
}
Integer id;
if( aux.equals(baseUrl + "clientes/cliente/") ){
try {
id = Integer.valueOf(parts[len - 1]);
} catch( NumberFormatException e){
throw new IllegalArgumentException();
}
if (id == null){
throw new IllegalArgumentException();
}
Client client = clientMan.getClient(id);
clientMan.deleteClient(client);
} else if( aux.equals(baseUrl + "/pedidos/pedido/") ){
try {
id = Integer.valueOf(parts[len - 1]);
} catch( NumberFormatException e){
throw new IllegalArgumentException();
}
if (id == null){
throw new IllegalArgumentException();
}
Order order = orderMan.getOrder(id);
orderMan.deleteOrder(order);
} else {
throw new NotFoundException();
}
}
private void responseXml(Iterable<? extends Printable> iterator, String root, PrintWriter out){
out.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.print("<"+root+">");
for(Printable each: iterator){
out.print(each.toXml());
}
out.print("</"+root+">");
}
private void responseJson(Iterable<? extends Printable> iterator, PrintWriter out){
out.print("[");
Iterator<? extends Printable> it = iterator.iterator();
if(it.hasNext()){
out.print(it.next().toJson());
}
while(it.hasNext()){
out.print(","+it.next().toJson());
}
out.print("]");
}
}
|
package com.fixit.ui.activities;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import com.fixit.controllers.ActivityController;
import com.fixit.app.R;
import com.fixit.ui.adapters.DeveloperSettingsAdapter;
/**
* Created by Kostyantin on 7/3/2017.
*/
public abstract class BaseDeveloperSettingsActivity extends BaseActivity<ActivityController> implements DeveloperSettingsAdapter.DeveloperSettingsChangedListener {
private LinearLayout mRoot;
private RecyclerView mRecyclerView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_recycler_list);
mRoot = (LinearLayout) findViewById(R.id.root);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setVisibility(View.VISIBLE);
notifySettingsChanged();
}
public void setToolbar(@LayoutRes int toolbarRes) {
Toolbar toolbar = (Toolbar) LayoutInflater.from(this).inflate(toolbarRes, mRoot, false);
mRoot.addView(toolbar, 0);
setToolbar(toolbar, true);
}
public abstract EditableConfiguration[] getEditableConfigurations();
public void notifySettingsChanged() {
DeveloperSettingsAdapter adapter = new DeveloperSettingsAdapter(getEditableConfigurations());
adapter.setSettingChangedListener(this);
mRecyclerView.setAdapter(adapter);
}
@Override
public ActivityController createController() {
return null;
}
public enum ConfigurationType {
STRING,
INT,
BOOLEAN;
public boolean isBoolean() {
return this == BOOLEAN;
}
public ConfigurationValue wrapValue(Object value) {
if(value == null) {
throw new IllegalArgumentException("value cannot be null");
}
if(isOfType(value)) {
switch (this) {
case STRING:
return new ConfigurationValue<>((String) value, this);
case BOOLEAN:
return new ConfigurationValue<>((Boolean) value, this);
case INT:
return new ConfigurationValue<>((Integer) value, this);
}
}
throw new IllegalArgumentException("value must be of type " + this);
}
public boolean isOfType(Object value) {
if(value != null) {
switch (this) {
case STRING:
return value instanceof String;
case BOOLEAN:
return value instanceof Boolean;
case INT:
return value instanceof Integer;
}
}
return false;
}
public int getInputType() {
switch (this) {
case INT:
return InputType.TYPE_CLASS_NUMBER;
default:
return InputType.TYPE_CLASS_TEXT;
}
}
}
public static class EditableConfiguration {
public final String key;
public final ConfigurationType type;
private ConfigurationValue value;
public EditableConfiguration(String key, ConfigurationType type) {
this.key = key;
this.type = type;
}
public void setValue(Object value) {
this.value = type.wrapValue(value);
}
public <T> ConfigurationValue<T> getValue() {
return value;
}
}
public static class ConfigurationValue<T> {
private final T value;
private final ConfigurationType type;
ConfigurationValue(T value, ConfigurationType type) {
this.value = value;
this.type = type;
}
public T get() {
return value;
}
public Boolean asBoolean() {
if (type != ConfigurationType.BOOLEAN) {
throw new IllegalStateException("Cannot return a Boolean, " + EditableConfiguration.class.getName() + " instance is of type " + type);
}
return (Boolean) value;
}
public Integer asInteger() {
if (type != ConfigurationType.INT) {
throw new IllegalStateException("Cannot return a Integer, " + EditableConfiguration.class.getName() + " instance is of type " + type);
}
return (Integer) value;
}
public String asString() {
if (type != ConfigurationType.STRING) {
throw new IllegalStateException("Cannot return a String, " + EditableConfiguration.class.getName() + " instance is of type " + type);
}
return (String) value;
}
}
}
|
package com.appdear.client;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.appdear.client.ContactOperateActivity.DialogListener;
import com.appdear.client.commctrls.BaseActivity;
import com.appdear.client.commctrls.InstalledBackupControler;
import com.appdear.client.commctrls.SharedPreferencesControl;
import com.appdear.client.exception.ApiException;
import com.appdear.client.model.SoftlistInfo;
import com.appdear.client.service.AppContext;
import com.appdear.client.service.api.ApiManager;
import com.appdear.client.service.api.ApiNormolResult;
import com.appdear.client.service.api.ApiSoftListResult;
import com.appdear.client.utility.ContactUtil;
import com.appdear.client.utility.ScreenManager;
import com.appdear.client.utility.ServiceUtils;
import com.appdear.client.utility.SmsUtil;
public class BeiFenActivity extends BaseActivity implements
OnClickListener {
public static final int RECOMMEND_UPDATE = 0;
public static final int DAREN_DETECT=1;
public static final int INSTALLED_BACKUP=2;
public static final int INSTALLED_RESTORE=3;
public static final int INSTALLED_FAIL=4;
private static final String BACK_INFO ="您是否需要备份?\n登录会员后备份 可支持在不同手机中还原。";
private static final String RESTORE_INFO ="您是否需要还原?\n如还原信息与本地没有发生变化,将不做还原处理。";
int xh_count = 0;
// 声明进度条对话框
ProgressDialog xh_pDialog;
TextView detectButton; // 检测button
TextView darenNumView; // 已安装多少应用
/*
* 初级达人:用户安装的软件为10个以下时 中级达人:用户安装软件为10-19时 高级达人:用户安装软件为20-39时
* 终极玩家:用户安装软件为40个及以上时
*/
TextView darenLevelView; // 等级 0 未检测 1 初级 2 中级 3 高级 4终极玩家
TextView darenWarnView; // 提示信息
ImageView darenImage;
// Button darenUpdateButton;
// GridView recommendListGrid; // 推荐应用
int darenInstalled;
int darenLevel;
/**
* 列表数据
*/
private ApiSoftListResult result;
private List<SoftlistInfo> listData = null;
private int page = 1;
/**
* 总页码
*/
protected int PAGE_TOTAL_SIZE = 1;
/**
* 每页显示10条
*/
protected int PAGE_SIZE = 8;
int recommendCount; // 推荐总数量
List<String> recommendIconUrls = new ArrayList<String>();
List<String> recommendNames = new ArrayList<String>();
// GetRecommendListRunnble myRunnable = null;
boolean isLoading = false;
boolean isFirst = true;
InstalledBackupControler installedControler=new InstalledBackupControler();
TextView tag1=null;
LinearLayout back,retore;
ImageButton btn_return;
private LinearLayout tab_ll_linear;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
installedControler.setActivity(this,myHandler);
setContentView(R.layout.beifen);
ScreenManager.getScreenManager().pushActivity(this);// 进栈
Intent intent=this.getIntent();
String tag=intent.getStringExtra("backup");
back=(LinearLayout) this.findViewById(R.id.beifen);
retore=(LinearLayout) this.findViewById(R.id.huanyuan);
tag1=(TextView)this.findViewById(R.id.tv_navigation);
if(tag==null||tag.equals("")){
retore.setVisibility(View.VISIBLE);
back.setVisibility(View.GONE);
tag1.setText("云还原");
}else if(tag.equals("true")){
back.setVisibility(View.VISIBLE);
retore.setVisibility(View.GONE);
tag1.setText("云备份");
}
}
@Override
public void init() {
// TODO Auto-generated method stub
Button Button01 = (Button) findViewById(com.appdear.client.R.id.Button01);
Button Button02 = (Button) findViewById(com.appdear.client.R.id.Button02);
Button01.setOnClickListener(this);
Button02.setOnClickListener(this);
Button btn_smsback = (Button) findViewById(R.id.btn_smsback);
Button btn_smsrestore = (Button) findViewById(R.id.btn_smsrestore);
btn_smsback.setOnClickListener(this);
btn_smsrestore.setOnClickListener(this);
installedControler.initView();
tab_ll_linear = (LinearLayout) findViewById(R.id.ll_navigation);
tab_ll_linear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
btn_return = (ImageButton) findViewById(R.id.btn_return);
btn_return.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
finish();
}
});
// myRunnable = new GetRecommendListRunnble();
// new Thread(myRunnable).start();
}
public void dialog_daren() {
if (xh_pDialog == null)
xh_pDialog = new ProgressDialog(this);
// 设置进度条风格,风格为圆形,旋转的
xh_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// 设置ProgressDialog 标题
// xh_pDialog.setTitle("提示");
// 设置ProgressDialog提示信息
xh_pDialog.setMessage("正在检测中请稍后");
// 设置ProgressDialog标题图标
// xh_pDialog.setIcon(R.drawable.icon);
// 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
xh_pDialog.setIndeterminate(false);
xh_pDialog.show();
// 设置ProgressDialog 是否可以按退回键取消
// xh_pDialog.setCancelable(true);
// 设置ProgressDialog 的一个Button
// xh_pDialog.setButton("确定", new Bt1DialogListener());
}
public void dialog() {
if (xh_pDialog == null)
xh_pDialog = new ProgressDialog(this);
// 设置进度条风格,风格为圆形,旋转的
xh_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// 设置ProgressDialog 标题
//xh_pDialog.setTitle("提示");
// 设置ProgressDialog提示信息
xh_pDialog.setMessage("操作中,请稍后.....");
// 设置ProgressDialog标题图标
// xh_pDialog.setIcon(R.drawable.icon);
// 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
xh_pDialog.setIndeterminate(false);
// 设置ProgressDialog 是否可以按退回键取消
xh_pDialog.setCancelable(true);
// 设置ProgressDialog 的一个Button
// xh_pDialog.setButton("确定", new Bt1DialogListener());
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.Button01:
createDialog(BACK_INFO,new DialogListener() {
@Override
public void postListener() {
backupContact();
}
});
break;
case R.id.Button02:
createDialog(RESTORE_INFO,new DialogListener() {
@Override
public void postListener() {
recoverContact();
}
});
break;
case R.id.installed_backup:
if (!AppContext.getInstance().isNetState) {
showMessageInfo("网络错误,不能进行该操作");
return;
}
createDialog(BACK_INFO,new DialogListener() {
@Override
public void postListener() {
installedControler.clickBackup();
}
});
break;
case R.id.installed_restore:
if (!AppContext.getInstance().isNetState) {
showMessageInfo("网络错误,不能进行该操作");
return;
}
createDialog(RESTORE_INFO,new DialogListener() {
@Override
public void postListener() {
installedControler.clickRestore();
}
});
break;
case R.id.btn_smsback:
createDialog(BACK_INFO,new DialogListener() {
@Override
public void postListener() {
sms_back();
}
});
break;
case R.id.btn_smsrestore:
createDialog(RESTORE_INFO,new DialogListener() {
@Override
public void postListener() {
sms_recover();
}
});
break;
default:
break;
}
}
private void recoverContact() {
dialog();
if (!AppContext.getInstance().isNetState) {
showMessageInfo("网络错误,不能进行该操作");
return;
}
// if (!ServiceUtils.checkLogin(BeiFenActivity.this, true)) {
// SoftwareMainDetilActivity.isClickFavorite = true;
// return;
// } else {
// 让ProgressDialog显示
xh_pDialog.show();
new Thread() {
@Override
public void run() {
try {
String userid = SharedPreferencesControl
.getInstance()
.getString(
"userid",
com.appdear.client.commctrls.Common.USERLOGIN_XML,
BeiFenActivity.this);
//String imei = ServiceUtils.getIMEI(BeiFenActivity.this);
ApiNormolResult apiSoftListResult = ApiManager
.recovercontact(userid);
String contact = apiSoftListResult.contact;
// contact = JsonUtil.uncompress(contact);
Log.i("gefy", "o===="+apiSoftListResult.isok);
if (apiSoftListResult.isok == 2) {
xh_pDialog.cancel();
showMessageInfo("云端没有任何备份数据,请先备份!");
}else {
JSONObject contactJson = new JSONObject(contact);
int i = ContactUtil.handlerContactAdd(
BeiFenActivity.this,
contactJson, 0);
xh_pDialog.cancel();
if (apiSoftListResult.isok == 1) {
if(i == 0){
showMessageInfo("本地没有变化,无需还原!");
return;
}
showMessageInfo("恭喜您!已成功还原记录" + i + "条");
} else
showMessageInfo("数据还原失败!");
}
} catch (Exception e) {
xh_pDialog.cancel();
showMessageInfo("数据还原失败!");
e.printStackTrace();
}
}
}.start();
}
// }
private void backupContact() {
dialog();
if (!AppContext.getInstance().isNetState) {
showMessageInfo("网络错误,不能进行该操作");
return;
}
/*if (!ServiceUtils.checkLogin(BeiFenActivity.this, true)) {
SoftwareMainDetilActivity.isClickFavorite = true;
return;
} else {*/
// 让ProgressDialog显示
xh_pDialog.show();
new Thread() {
@Override
public void run() {
try {
String userid = SharedPreferencesControl
.getInstance()
.getString(
"userid",
com.appdear.client.commctrls.Common.USERLOGIN_XML,
BeiFenActivity.this);
String imei = ServiceUtils.getIMEI(BeiFenActivity.this);
ApiNormolResult apiSoftListResult = ApiManager
.backupcontact(userid,
BeiFenActivity.this);
if(apiSoftListResult == null || apiSoftListResult.contactcount.equals("0")){
sleep(1000);
xh_pDialog.cancel();
showMessageInfo("手机中没有数据,无法备份!");
return;
}
xh_pDialog.cancel();
if (apiSoftListResult == null || apiSoftListResult.isok == 1)
showMessageInfo("已经成功备份!已备份数据条数" + apiSoftListResult.contactcount + "条");
else
showMessageInfo("备份数据失败!");
} catch (Exception e) {
xh_pDialog.cancel();
showMessageInfo("备份数据失败!");
e.printStackTrace();
}
}
}.start();
//}
}
// xhButton01的监听器类
class Bt1DialogListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int which) {
// 点击“确定”按钮取消对话框
dialog.cancel();
}
}
/**
* sms back
*/
private void sms_back(){
dialog();
if (!AppContext.getInstance().isNetState) {
showMessageInfo("网络错误,不能进行该操作");
return;
}
xh_pDialog.show();
new Thread() {
@Override
public void run() {
try {
String userid = SharedPreferencesControl
.getInstance()
.getString(
"userid",
com.appdear.client.commctrls.Common.USERLOGIN_XML,
BeiFenActivity.this);
//String imei = ServiceUtils.getIMEI(BeiFenActivity.this);
String imsi = ServiceUtils.getSimsi(BeiFenActivity.this);
ApiNormolResult smsResult = ApiManager
.backupsms(userid,imsi, BeiFenActivity.this);
if(smsResult == null || smsResult.contactcount.equals("0")){
sleep(1000);
xh_pDialog.cancel();
showMessageInfo("手机中没有数据,无法备份!");
return;
}
xh_pDialog.cancel();
if (smsResult == null || smsResult.isok == 1){
showMessageInfo("已经成功备份!已备份数据条数"
+ smsResult.contactcount + "条");
}
else{
showMessageInfo("备份数据失败!");
}
} catch (Exception e) {
xh_pDialog.cancel();
showMessageInfo("备份数据失败!");
e.printStackTrace();
}
}
}.start();
}
/**
* sms recover
*/
private void sms_recover(){
dialog();
if (!AppContext.getInstance().isNetState) {
showMessageInfo("网络错误,不能进行该操作");
return;
}xh_pDialog.show();
new Thread() {
@Override
public void run() {
try {
String userid = SharedPreferencesControl
.getInstance()
.getString(
"userid",
com.appdear.client.commctrls.Common.USERLOGIN_XML,
BeiFenActivity.this);
//String imei = ServiceUtils.getIMEI(BeiFenActivity.this);
String imsi = ServiceUtils.getSimsi(BeiFenActivity.this);
ApiNormolResult smsResult = ApiManager.recoversms(userid,imsi);
String sms = smsResult.sms;
//System.out.println("recorve"+sms);
// contact = JsonUtil.uncompress(contact);
Log.i("gefy", "o===="+smsResult.isok);
if (smsResult.isok == 2) {
xh_pDialog.cancel();
showMessageInfo("云端没有任何备份数据,请先备份!");
}else {
//JSONObject contactJson = new JSONObject(contact);
//int i = ContactUtil.handlerContactAdd(
int i = SmsUtil.smsRestroe(BeiFenActivity.this,sms);
xh_pDialog.cancel();
if(i==0){
showMessageInfo("本地没有变化,无需还原!");
}else{
showMessageInfo("恭喜您!已成功还原短信"+ i +"条");
}
//if (smsResult.isok == 1) {
// } else
// showMessageInfo("数据还原失败!");
}
} catch (Exception e) {
xh_pDialog.cancel();
showMessageInfo("数据还原失败!");
e.printStackTrace();
}
}
}.start();
}
public interface DialogListener{
void postListener();
//void negaListener();
}
private void createDialog(String message ,final DialogListener dialogListener){
AlertDialog.Builder builder = new Builder(BeiFenActivity.this);
builder.setMessage(message);//您确定要备份吗?
builder.setTitle("提示");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
dialogListener.postListener();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//dialogListener.negaListener();
}
});
builder.create().show();
}
public Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case INSTALLED_BACKUP: //安装列表备份
xh_pDialog.cancel();
installedControler.handleBackup();
break;
case INSTALLED_RESTORE: //安装列表备份
xh_pDialog.cancel();
installedControler.handleRestore();
break;
case INSTALLED_FAIL:
xh_pDialog.cancel();
break;
}
}
};
}
|
package controller;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.logging.Level;
import com.sun.javafx.logging.Logger;
import Threads.ThreadTime;
import Threads.ThreadTimeRematch;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import model.*;
import javafx.util.Callback;
public class PrincipalController implements Initializable{
@FXML
private Label principal;
@FXML
private ImageView gift;
@FXML
private ImageView hipodrome;
@FXML
private VBox scoreInicial;
@FXML
private VBox scoreFinal;
@FXML
private Label time;
@FXML
private Button ramdom;
@FXML
private Button addHorse;
@FXML
private Button addBet;
@FXML
private Button searchBet;
@FXML
private Button rematch;
private Dealer dealer;
private boolean tf = false;
private boolean tf1 = false;
public boolean isTf1() {
return tf1;
}
public void setTf1(boolean tf1) {
this.tf1 = tf1;
}
public <T extends Dialog<?>> void setCss(T dialog) {
DialogPane dialogPane = dialog.getDialogPane();
dialogPane.getStylesheets().add(getClass().getResource("/application/application.css").toExternalForm());
dialogPane.getStyleClass().add("dialog");
Stage stage = (Stage) dialogPane.getScene().getWindow();
stage.getIcons().add(new Image("file:med/Logo.png"));
}
public Dealer getDealer() {
return dealer;
}
public void setDealer(Dealer dealer) {
this.dealer = dealer;
}
public Label getTime() {
return time;
}
public void setTime(Label time) {
this.time = time;
}
public boolean isTf() {
return tf;
}
public void setTf(boolean tf) {
this.tf = tf;
}
@Override
public void initialize(URL location, ResourceBundle resources) {
dealer = new Dealer();
time.setText("00:00");
scoreInicial.setSpacing(3);
scoreInicial.setAlignment(Pos.CENTER);
scoreFinal.setSpacing(3);
scoreFinal.setAlignment(Pos.CENTER);
Image i = new Image("/controller/horseRun.gif",1400,300,false,false);
Image o = new Image("/controller/horseHipodromo.jpg",2400,820,true,true);
gift.setImage(i);
hipodrome.setImage(o);
Label m4 = new Label("ROW - HORSE NAME");
scoreInicial.getChildren().add(m4);
searchBet.setDisable(true);
rematch.setDisable(true);
addBet.setDisable(true);
}
public void addHorse(ActionEvent e) {
if(!scoreInicial.getChildren().isEmpty()) {
scoreInicial.getChildren().clear();
scoreFinal.getChildren().clear();
}
Dialog<Horse> dialog = new Dialog<>();
dialog.setTitle("");
dialog.setHeaderText("Please type the horseman's name and the horse's \n name in order to register the horse for the race");
dialog.setResizable(false);
Label label1 = new Label("Horseman's name: ");
Label label2 = new Label("Horse's name: ");
TextField text1 = new TextField();
TextField text2 = new TextField();
GridPane grid = new GridPane();
grid.add(label1, 1, 1);
grid.add(text1, 2, 1);
grid.add(label2, 1, 2);
grid.add(text2, 2, 2);
dialog.getDialogPane().setContent(grid);
ButtonType buttonTypeOk = new ButtonType("Accept", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().add(buttonTypeOk);
dialog.setResultConverter(new Callback<ButtonType, Horse>() {
@Override
public Horse call(ButtonType b) {
if (b == buttonTypeOk) {
if(!text1.getText().isEmpty() && !text2.getText().isEmpty()) {
Horse m2 = new Horse(text1.getText(), text2.getText());
return m2;
}else {
showAlert(4);
}
}
return null;
}
});
setCss(dialog);
Optional<Horse> m1 = dialog.showAndWait();
if(m1.isPresent()) {
if(dealer.getHorses().size() == 6) {
beginMethodTime();
dealer.getGamblers().clearNodes();
searchBet.setDisable(false);
addBet.setDisable(false);
}else if(dealer.getHorses().size() >= 10) {
showAlert(5);
}
if(dealer.getHorsesNames().size() < 10) {
dealer.getHorsesNames().add(m1.get().getHorseName());
dealer.addHorseQueue(m1.get());
}
Label m = new Label("ROW - HORSE NAME");
scoreInicial.getChildren().add(m);
int row =1;
for(int j = 0; j < dealer.getHorsesNames().size();j++) {
Label aux = new Label(row+" - "+dealer.getHorsesNames().get(j));
scoreInicial.getChildren().add(aux);
++row;
}
}else {
Label m4 = new Label("ROW - HORSE NAME");
scoreInicial.getChildren().add(m4);
int row =1;
for(int j = 0; j < dealer.getHorsesNames().size();j++) {
Label aux = new Label(row+" - "+dealer.getHorsesNames().get(j));
scoreInicial.getChildren().add(aux);
++row;
}
}
}
public void searchBet(ActionEvent e) {
Dialog<String> dialog = new Dialog<>();
dialog.setTitle("");
dialog.setHeaderText("Please type the ID linked to the bet:");
dialog.setResizable(false);
Label label1 = new Label("ID: ");
TextField text1 = new TextField();
GridPane grid = new GridPane();
grid.add(label1, 1, 1);
grid.add(text1, 2, 1);
dialog.getDialogPane().setContent(grid);
ButtonType buttonTypeOk = new ButtonType("Search", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().add(buttonTypeOk);
dialog.setResultConverter(new Callback<ButtonType, String>() {
@Override
public String call(ButtonType b) {
if (b == buttonTypeOk) {
try {
int mustBeNumber = Integer.parseInt(text1.getText());
if(!text1.getText().isEmpty() ) {
String theKey = text1.getText();
return theKey;
}else {
showAlert(2);
}
} catch (Exception e2) {
showAlert(1);
}
}
return null;
}
});
setCss(dialog);
Optional<String> m2 = dialog.showAndWait();
if(m2.isPresent()) {
User found = dealer.search4Gambler(m2.get());
if (found != null) {
Alert gameOver = new Alert(AlertType.INFORMATION);
gameOver.setTitle("Here is your bet");
String pos = "POSITION PENDING";
int posHorse = found.getMyWinnerHorse().getPosition();
String horseName = found.getMyWinnerHorse().getHorseName();
String row = "ROW"+found.getMyWinnerHorse().getRow()+" ";
if ( posHorse != -1) {
if (posHorse == 1) {
pos = "WINNER 1st PlACE";
} else {
pos = posHorse+" PLACE";
}
}
gameOver.setHeaderText(pos+" - "+row+horseName);
String space = " \n ";
gameOver.setContentText("ID: "+found.getId()+space+ "Name: "+found.getName()+space+ "Gamble : $"+found.getAmount());
gameOver.showAndWait();
//TODO
} else {
showAlert(3);
}
}
}
public void showAlert(int msg) {
Alert gameOver = new Alert(AlertType.INFORMATION);
gameOver.setTitle("ERROR");
switch (msg) {
case 1:
gameOver.setHeaderText("Please check the ID, it must be a number!");
break;
case 2:
gameOver.setHeaderText("Please check the ID, it is empty...");
break;
case 3:
gameOver.setTitle("We are very sorry...");
gameOver.setHeaderText("But we could not find any bet linked to your ID");
break;
case 4:
gameOver.setHeaderText("Information missing");
break;
case 5:
gameOver.setHeaderText("There can only be 10 horses per race!");
break;
case 6:
gameOver.setHeaderText("Please check the bet,some of the texts are empty...");
break;
case 7:
gameOver.setHeaderText("Please check the horse picked, because we cannot find it");
break;
default:
break;
}
gameOver.showAndWait();
}
public void rematch(ActionEvent e) {
ramdom.setDisable(true);
rematch.setDisable(true);
dealer.fillStack4Rematch();
dealer.getHorses().clearQueue();
dealer.getHorsesNames().clear();
dealer.setNumberOfHorses(0);
dealer.getGamblers().clearNodes();
scoreInicial.getChildren().clear();
scoreFinal.getChildren().clear();
addBet.setDisable(false);
searchBet.setDisable(false);
Label m = new Label("ROW - HORSE NAME");
scoreInicial.getChildren().add(m);
int row = 1;
for(int j = 0; j < dealer.getHorsesNamesRematch().size();j++) {
Label aux = new Label(row+" - "+ dealer.getHorsesNamesRematch().get(j));
scoreInicial.getChildren().add(aux);
++row;
}
beginMethodRematch();
dealer.getHorsesNamesRematch().clear();
}
public void addBet(ActionEvent e) {
Dialog<User> dialog = new Dialog<>();
dialog.setTitle("");
dialog.setHeaderText("Please type the bet:");
dialog.setResizable(false);
Label label1 = new Label("ID: ");
TextField text1 = new TextField();
Label label2 = new Label("Your Name: ");
TextField text2 = new TextField();
Label label3 = new Label("Horse name: ");
TextField text3 = new TextField();
Label label4 = new Label("Please type your bet: ");
TextField text4 = new TextField();
Label label5 = new Label("Please type the row:");
TextField text5 = new TextField();
GridPane grid = new GridPane();
grid.add(label1, 1, 1);
grid.add(text1, 2, 1);
grid.add(label2, 1, 2);
grid.add(text2,2,2);
grid.add(label3,1,3);
grid.add(text3,2,3);
grid.add(label5,1,4);
grid.add(text5, 2, 4);
grid.add(label4,1,5);
grid.add(text4,2,5);
dialog.getDialogPane().setContent(grid);
ButtonType buttonTypeOk = new ButtonType("Add", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().add(buttonTypeOk);
dialog.setResultConverter(new Callback<ButtonType, User>() {
@Override
public User call(ButtonType b) {
if (b == buttonTypeOk) {
try {
int mustBeNumber = Integer.parseInt(text1.getText());
double mustBeDouble = Double.parseDouble(text4.getText());
int rowPosition = Integer.parseInt(text5.getText());
if(!text1.getText().isEmpty() && !text2.getText().isEmpty() && !text3.getText().isEmpty() && !text4.getText().isEmpty() && !text5.getText().isEmpty()) {
dataStructures.Node<Horse> horse4Bet = dealer.findHorseWithRow(text3.getText() ,rowPosition); //dependency
Horse theHorse = null;
if (horse4Bet != null) {
theHorse = horse4Bet.getInfo();
}
User gambler = new User(mustBeNumber, text2.getText(), mustBeDouble, theHorse);
return gambler;
}else {
showAlert(6);
}
} catch (Exception e2) {
showAlert(1);
}
}
return null;
}
});
setCss(dialog);
Optional<User> gambler = dialog.showAndWait();
User finalGambler = gambler.get();
if (finalGambler.getMyWinnerHorse() != null) {
dealer.addGambler(finalGambler);
} else {
showAlert(7);
}
}
public void ramdomTest(ActionEvent e) {
addBet.setDisable(false);
searchBet.setDisable(false);
dealer.getGamblers().clearNodes();
scoreInicial.getChildren().clear();
scoreFinal.getChildren().clear();
ramdom.setDisable(true);
dealer.generateHorses();
beginMethodTime();
Label m = new Label("ROW - HORSE NAME");
scoreInicial.getChildren().add(m);
int row =1;
for(int j = 0; j < dealer.getHorsesNames().size();j++) {
Label aux = new Label(row+" - "+dealer.getHorsesNames().get(j));
scoreInicial.getChildren().add(aux);
++row;
}
}
private void beginMethodTime() {
ThreadTime t = new ThreadTime(this);
t.start();
}
private void beginMethodRematch(){
ThreadTimeRematch t = new ThreadTimeRematch(this);
t.start();
}
public void updateTime(String msj) {
time.setText(msj);
}
public void finishRace() {
dealer.setWinners(false);
Label m = new Label("PODIUM");
scoreFinal.getChildren().add(m);
Horse[] horsesSorted = dealer.sortByPosition(false);
int pos = 1;
for(int j = 1; j < horsesSorted.length;j++) {
Label aux = new Label(pos+". "+horsesSorted[j].getHorseName());
scoreFinal.getChildren().add(aux);
++pos;
}
dealer.getHorses().clearQueue();
dealer.getHorsesNames().clear();
dealer.setNumberOfHorses(0);
ramdom.setDisable(false);
rematch.setDisable(false);
addBet.setDisable(true);
}
public void finishRaceRematch() {
dealer.setWinners(true);
Label m = new Label("PODIUM");
scoreFinal.getChildren().add(m);
Horse[] horsesSorted = dealer.sortByPosition(true);
int pos = 1;
for(int j = 1; j < horsesSorted.length;j++) {
Label aux = new Label(pos+". "+horsesSorted[j].getHorseName());
scoreFinal.getChildren().add(aux);
++pos;
}
dealer.getHorsesRematch().clearStack();
dealer.getHorsesNamesRematch().clear();
dealer.setNumberOfHorses(0);
ramdom.setDisable(false);
rematch.setDisable(true);
addBet.setDisable(true);
}
} //end of class
|
package com.philippe.app.exception;
public class JobPausedException extends JobException {
public JobPausedException(String message) {
super(message);
}
}
|
package utility;
import exceptions.IncorrectValueException;
import exceptions.NullFieldException;
import exceptions.ValidationException;
public interface FieldCheckerHelp<T> {
T check(String str) throws NullFieldException, IncorrectValueException;
}
|
package ru.otus.adapter;
/*
* Created by VSkurikhin at autumn 2018.
*/
import ru.otus.dataset.DataSet;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
interface DataSetAdapter<T extends DataSet>
{
default Class<T> getTypeParameterClass()
{
Type[] types = getClass().getGenericInterfaces();
for (Type type: types) {
if (type.getTypeName().startsWith("ru.otus.adapter.DataSetAdapter")) {
ParameterizedType paramType = (ParameterizedType) type;
// some magic with reflection
//noinspection unchecked
return (Class<T>) paramType.getActualTypeArguments()[0];
}
}
// Backup way for XML Adapter. Need more testing.
Type type = getClass();
ParameterizedType paramType = (ParameterizedType) type;
//noinspection unchecked
return (Class<T>) paramType.getActualTypeArguments()[1];
}
default T unmarshalAdapter(String name) throws Exception
{
return unmarshalAdapter(name, getTypeParameterClass());
}
default T unmarshalAdapter(String name, Class<T> c)
throws IllegalAccessException, InstantiationException
{
T entity = c.newInstance();
entity.setName(name);
return entity;
}
default String marshalAdapter(T v)
{
return v == null ? null : v.getName();
}
default JsonObjectBuilder getJsonWithIdObjectBuilder(T v)
{
return Json.createObjectBuilder().add("id", v.getId());
}
default JsonObject marshalToJson(T v)
{
return Json.createObjectBuilder()
.add("id", v.getId())
.add("name", v.getName()).build();
}
default T unmarshalFromJson(JsonObject obj)
throws IllegalAccessException, InstantiationException
{
T entity = getTypeParameterClass().newInstance();
entity.setId(obj.getInt("id"));
entity.setName(obj.getString("name"));
return entity;
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
package prj.betfair.api.betting.operations;
import com.fasterxml.jackson.annotation.JsonProperty;
import prj.betfair.api.betting.datatypes.PlaceExecutionReport;
import prj.betfair.api.betting.datatypes.PlaceInstruction;
import prj.betfair.api.betting.exceptions.APINGException;
import prj.betfair.api.common.Executor;
import java.util.List;
/***
* Place new orders into market. LIMIT orders below the minimum bet size are allowed if there is an
* unmatched bet at the same price in the market. This operation is atomic in that all orders will
* be placed or none will be placed.
*/
public class PlaceOrdersOperation {
private final List<PlaceInstruction> instructions;
private final Executor executor;
private final String customerRef;
private final String customerStrategyRef;
private final String marketId;
private final Boolean async;
public PlaceOrdersOperation(Builder builder) {
this.instructions = builder.instructions;
this.executor = builder.executor;
this.customerRef = builder.customerRef;
this.customerStrategyRef = builder.customerStrategyRef;
this.marketId = builder.marketId;
this.async = builder.async;
}
/**
* @return marketId The market id these orders are to be placed on
*/
public String getMarketId() {
return this.marketId;
}
/**
* @return instructions
*/
public List<PlaceInstruction> getInstructions() {
return this.instructions;
}
/**
* @return customerRef Optional parameter allowing the client to pass a unique string (up to 32
* chars) that is used to de-dupe mistaken re-submissions.
*/
public String getCustomerRef() {
return this.customerRef;
}
/**
* @return customerStrategyRef An optional reference customers can use to specify which strategy has sent the order.
* The reference will be returned on order change messages through the stream API.
*/
public String getCustomerStrategyRef() {
return customerStrategyRef;
}
/**
* @return async An optional flag (not setting equates to false) which specifies if the orders should be placed
* asynchronously. Orders can be tracked via the Exchange Stream API or or the API-NG by providing a
* customerOrderRef for each place order. An order's status will be PENDING and no bet ID will be returned.
*/
public Boolean getAsync() {
return async;
}
public PlaceExecutionReport execute() throws APINGException {
return executor.execute(this);
}
public static class Builder {
private List<PlaceInstruction> instructions;
private String customerRef;
private String customerStrategyRef;
private String marketId;
private Boolean async;
private Executor executor;
/**
* @param instructions
* @param marketId : The market id these orders are to be placed on
*/
public Builder(@JsonProperty("instructions") List<PlaceInstruction> instructions,
@JsonProperty("marketId") String marketId) {
this.instructions = instructions;
this.marketId = marketId;
}
/**
* Use this function to set customerRef
*
* @param customerRef Optional parameter allowing the client to pass a unique string (up to 32
* chars) that is used to de-dupe mistaken re-submissions.
* @return Builder
*/
public Builder withCustomerRef(String customerRef) {
this.customerRef = customerRef;
return this;
}
/**
* Use this function to set customerStrategyRef
*
* @param customerStrategyRef An optional reference customers can use to specify which strategy has sent the order.
* The reference will be returned on order change messages through the stream API.
* @return Builder
*/
public Builder withCustomerStrategyRef(String customerStrategyRef) {
this.customerStrategyRef = customerStrategyRef;
return this;
}
/**
* Use this function to set async
*
* @param async An optional flag (not setting equates to false) which specifies if the orders should be placed
* asynchronously. Orders can be tracked via the Exchange Stream API or or the API-NG by providing a
* customerOrderRef for each place order. An order's status will be PENDING and no bet ID will be returned.
* @return Builder
*/
public Builder withAsync(Boolean async) {
this.async = async;
return this;
}
/**
* @param executor Executor for this operation
* @return Builder
*/
public Builder withExecutor(Executor executor) {
this.executor = executor;
return this;
}
public PlaceOrdersOperation build() {
return new PlaceOrdersOperation(this);
}
}
}
|
package com.workorder.ticket.service.convertor;
import com.workorder.ticket.persistence.dto.workorder.WorkOrderQueryDto;
import com.workorder.ticket.persistence.dto.workorder.WorkOrderWithCreatorDto;
import com.workorder.ticket.persistence.entity.User;
import com.workorder.ticket.persistence.entity.WorkOrder;
import com.workorder.ticket.service.bo.user.UserBaseBo;
import com.workorder.ticket.service.bo.workorder.WorkOrderBo;
import com.workorder.ticket.service.bo.workorder.WorkOrderEditBo;
import com.workorder.ticket.service.bo.workorder.WorkOrderQueryBo;
/**
* 工单对象转换器
*
* @author wzdong
* @Date 2019年3月6日
* @version 1.0
*/
public class WorkOrderServiceConvertor {
public static WorkOrder buildWorkOrder(WorkOrderEditBo editBo) {
WorkOrder wo = new WorkOrder();
wo.setId(editBo.getId());
wo.setTitle(editBo.getTitle());
wo.setType(editBo.getType());
wo.setDescription(editBo.getDescription());
wo.setComment(editBo.getComment());
wo.setContent(editBo.getContent());
return wo;
}
public static WorkOrderBo buildWorkOrderBo(
WorkOrderWithCreatorDto workOrder, User currentProcessor) {
WorkOrderBo bo = new WorkOrderBo();
bo.setId(workOrder.getId());
bo.setTitle(workOrder.getTitle());
bo.setType(workOrder.getType());
bo.setDescription(workOrder.getDescription());
bo.setStatus(workOrder.getStatus());
bo.setFlowEngineDefinitionId(workOrder.getFlowEngineDefinitionId());
bo.setFlowEngineInstanceId(workOrder.getFlowEngineInstanceId());
bo.setComment(workOrder.getComment());
bo.setCreateTime(workOrder.getCreateTime());
bo.setSubmitTime(workOrder.getSubmitTime());
bo.setContent(workOrder.getContent());
bo.setCreateUser(new UserBaseBo(workOrder.getCreateId(), workOrder
.getCreateUsername(), workOrder.getCreateRealName()));
if (currentProcessor != null) {
bo.setCurrentProcessor(new UserBaseBo(currentProcessor.getId(),
currentProcessor.getUsername(), currentProcessor
.getRealname()));
}
return bo;
}
public static WorkOrderQueryDto buildWorkOrderQueryDto(
WorkOrderQueryBo queryBo) {
WorkOrderQueryDto dto = new WorkOrderQueryDto();
dto.setStatus(queryBo.getStatus());
dto.setTitle(queryBo.getTitle());
dto.setCreator(queryBo.getCreator());
dto.setCreateRange(queryBo.getCreateRange());
dto.setSubmitRange(queryBo.getSubmitRange());
dto.setPageItem(queryBo.getPageItem());
return dto;
}
}
|
package com.wuyan.masteryi.mall.service;
import com.wuyan.masteryi.mall.entity.SingleCartItem;
import java.util.List;
import java.util.Map;
/**
* @Author: Zhao Shuqing
* @Date: 2021/7/6 16:40
* @Description:
*/
public interface CartItemService {
Map<String,Object> addCartItem(Integer userId, Integer goodsId, Integer goodsNum);
Map<String,Object> deleteCartItemById(Integer[] selectedCartItemId);
Map<String,Object> deleteAllCartItem(Integer userId);
Map<String,Object> changeGoodsNumById(Integer cartItemId, Integer newGoodsNum);
Map<String,Object> goodsNumSub1(Integer cartItemId);
Map<String,Object> goodsNumAdd1(Integer cartItemId);
Map<String,Object> showMyCart(Integer userId);
Map<String,Object> changeCartGoodId(int cartItemId,int goodsId);
}
|
package com.isslam.kidsquran.utils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.isslam.kidsquran.R;
import com.isslam.kidsquran.controllers.AudioListManager;
import com.isslam.kidsquran.controllers.SharedPreferencesManager;
import com.isslam.kidsquran.model.AudioClass;
public class Utils {
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
public static int getProgressPercentage(long currentDuration, long totalDuration){
Double percentage = (double) 0;
long currentSeconds = (int) (currentDuration / 1000);
long totalSeconds = (int) (totalDuration / 1000);
// calculating percentage
percentage =(((double)currentSeconds)/totalSeconds)*100;
// return percentage
return percentage.intValue();
}
public static boolean isConnectingToInternet(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
public static boolean isFileExist(String folderId, String verseName) {
String localPath = getLocalPath(folderId);
File file = new File(localPath, verseName);
if (file.exists()) {
return true;
}
return false;
}
public static boolean deleteFile(String folderId, String verseName) {
String localPath = getLocalPath(folderId);
File file = new File(localPath, verseName);
if (file.exists()) {
return file.delete();
}
return false;
}
public static String getLocalPath(String folderId) {
return Environment.getExternalStorageDirectory() + "/"+GlobalConfig.audioRootPath+"/"
+ folderId;
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); // match a number with optional
// '-' and decimal.
}
public static String getAudioMp3Name(int verseId) {
String versesId = verseId + "";
if (versesId.length() == 3)
versesId = versesId + ".mp3";
if (versesId.length() == 2)
versesId = "0" + versesId + ".mp3";
if (versesId.length() == 1)
versesId = "00" + versesId + ".mp3";
return versesId;
}
public static boolean deleteVerse(AudioClass audioClass) {
File currentDir = new File("/sdcard/"+GlobalConfig.audioRootPath+"/"
+ audioClass.getReciterId() + "/"
+ getAudioMp3Name(audioClass.getVerseId()));
if (currentDir.exists()) {
return currentDir.delete();
}
return false;
}
public static boolean ifSuraDownloaded(Context context,
AudioClass _audioClass) {
File dir = new File(Environment.getExternalStorageDirectory()
+ "/"+GlobalConfig.audioRootPath+"/" + _audioClass.getReciterId());
String versesId = getAudioMp3Name(_audioClass.getVerseId()) + "";
if (dir.exists()) {
File from = new File(dir, versesId);
if (from.exists())
return true;
}
return false;
}
public static void shareMp3(Context context, AudioClass audioClass) {
if (ifSuraDownloaded(context, audioClass)) {
String sharePath = Environment.getExternalStorageDirectory()
.getPath()
+ "/"+GlobalConfig.audioRootPath+"/"
+ audioClass.getReciterId()
+ "/"
+ getAudioMp3Name(audioClass.getVerseId());
Uri uri = Uri.parse(sharePath);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(share,
"Share Sound File"));
} else {
ShowNotDownloaded(context, audioClass);
}
}
public static void SharePath(Context context, AudioClass audioClass) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = context.getString(R.string.share_body)
+ "http://server11.mp3quran.net/shatri/001.mp3";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
context.getString(R.string.share_title));
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
context.startActivity(Intent.createChooser(sharingIntent,
context.getString(R.string.share_title)));
}
private static void ShowNotDownloaded(Context context, AudioClass audioClass) {
new AlertDialog.Builder(context)
.setTitle(
context.getResources().getString(R.string.share_title))
.setMessage(
context.getResources().getString(
R.string.share_condition))
.setPositiveButton(
context.getResources().getString(
R.string.app_exit_confirm),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).setIcon(android.R.drawable.ic_dialog_alert).show();
}
public static boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
if (files == null) {
return true;
}
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
public static int getDirectoryfilesCount(File path) {
int count=0;
if (path.exists()) {
File[] files = path.listFiles();
if (files == null) {
return -1;
}
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
//do nothing
} else {
count++;
}
}
}
Log.e("Files Count -->","Files Count -->"+count);
return count;
}
public static void updateLocal(Context context, String lang_local,
String lang_id) {
// SharedPreferences sharedPreferences = PreferenceManager
// .getDefaultSharedPreferences(context);
// String _local = sharedPreferences.getString("languages_preference",
// "ar");
// Log.e("_local", _local);
GlobalConfig.local = lang_local;
GlobalConfig.lang_id = lang_id;
Locale locale = new Locale(lang_local);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config,
context.getResources().getDisplayMetrics());
SharedPreferencesManager sharedPreferencesManager = SharedPreferencesManager
.getInstance(context);
sharedPreferencesManager.savePreferences(
SharedPreferencesManager._lang_id, lang_id);
sharedPreferencesManager.savePreferences(
SharedPreferencesManager._local, lang_local);
}
public static void unzip(File zipFile, File targetDirectory) throws IOException {
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(new FileInputStream(zipFile)));
try {
ZipEntry ze;
int count;
byte[] buffer = new byte[8192];
while ((ze = zis.getNextEntry()) != null) {
File file = new File(targetDirectory, ze.getName());
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Failed to ensure directory: " +
dir.getAbsolutePath());
if (ze.isDirectory())
continue;
FileOutputStream fout = new FileOutputStream(file);
try {
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
} finally {
fout.close();
}
/* if time should be restored as well
long time = ze.getTime();
if (time > 0)
file.setLastModified(time);
*/
}
} finally {
zis.close();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.