text
stringlengths 10
2.72M
|
|---|
package cn.sange.appserver.dao;
import cn.sange.appserver.pojo.Token;
import cn.sange.appserver.pojo.User;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @ program: Appserver
* @ description: 安全验证实体类数据访问层
* @ author: Sange
* @ create: 2018-09-06 19:55
**/
@Repository
public class TokenDaoImpl implements TokenDao{
@Autowired
private HibernateTemplate hibernateTemplate;
public Token istokenAvailable(String phone) {
List<Token> tokens = (List<Token>)this.hibernateTemplate.find("from Token where phone = ?", phone);
if (null != tokens){
return tokens.get(0);
}
return null;
}
public void saveOrUpdate(Token token) {
hibernateTemplate.saveOrUpdate(token);
}
}
|
package org.lfy.eureka.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* WebSecurityConfig
* 作用:解决Eureka添加Security权限验证导致服务无法注册到Eureka上
* 参考链接:https://blog.csdn.net/h11401140334/article/details/103260456
*
* @author lfy
* @date 2021/3/19
**/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//close csrf
http.csrf().disable();
//open auth
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
|
package com.inobu.mquestioner;
//import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;
//import java.util.List;
import java.util.Set;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
//import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "mQuestionair.db";
// tasks table name
private static final String TABLE_KK = "tb_kk";
private static final String TABLE_LAHAN = "tb_lahan";
private static final String TABLE_USER = "tb_user";
private static final String TABLE_DESA = "mst_desa";
private static final String TABLE_KEC = "mst_kecamatan";
private static final String TABLE_KAB = "mst_kabkot";
private static final String TABLE_PROV = "mst_prov";
private static final String TABLE_KOSONG = "mst_kosong";
private static final String TABLE_SETTING = "tb_setting";
public static final String KEY_SETURL = "setURL";
// posisi di id_desa
public static final String KEY_DESAPOS = "pos_desa";
public static final String KEY_KECPOS = "pos_kecamatan";
public static final String KEY_KABPOS = "pos_kabkot";
public static final String KEY_PROVPOS = "pos_prov";
// untuk table desa
public static final String KEY_KDESA = "kode_desa";
public static final String KEY_KKEC = "kode_kecamatan";
public static final String KEY_KKAB = "kode_kabupaten";
public static final String KEY_NDESA = "nama_desa";
// untuk table kecamatan
public static final String KEY_NKEC = "nama_kecamatan";
public static final String KEY_KKAB_KOTA = "kode_kabkot";
// untuk table kabupaten
private static final String KEY_NKAB_KOTA = "nama_kab_kot";
// private static final String KEY_PROVINSI = "nama_kab_kot";
// untuk table provinsi
private static final String KEY_KODEPROV = "kode_prov";
private static final String KEY_NPROV = "nama_provinsi";
// untuk table kk
// public static final String KEY_IDNARA = "id_nara";
public static final String KEY_IDKK = "id_kk";
public static final String KEY_ENUM = "enumID";
public static final String KEY_NARA = "narasumber";
private static final String KEY_DESA = "desa";
private static final String KEY_KEC = "kecamatan";
private static final String KEY_KAB = "kabupaten";
private static final String KEY_PROV = "provinsi";
public static final String KEY_KTP = "no_KTP";
private static final String KEY_HP = "no_HP";
public static final String KEY_NAMAKK = "nama_kk";
private static final String KEY_JMLKK = "jumlah_kk";
private static final String KEY_TMPLHR = "tempat_lhr";
private static final String KEY_TGLLHR = "tanggal_lhr";
private static final String KEY_PDDK = "pendidikan";
private static final String KEY_SUKU = "suku";
private static final String KEY_PKJUTAMA = "pekerjaan_utama ";
private static final String KEY_PKJLAIN = "pekerjaan_lain ";
private static final String KEY_AGTORG = "anggota_organisasi";
private static final String KEY_TGLINPUT = "tgl_input";
private static final String KEY_WKTINPUT = "waktu_input";
// private static final String KEY_DATE= "tgl_input";
// private static final String KEY_TIME= "waktu_input";
private static final String KEY_STATUS = "status";
private static final String KEY_CHECKON = "sent_on";
// untuk table lahan
public static final String KEY_IDLAHAN = "id_lahan";
public static final String KEY_SHAPEID = "shape_id";
public static final String KEY_STSLAHAN = "status_lahan";
private static final String KEY_LAMALAHAN = "lama_lahan";
private static final String KEY_LUASPROD = "luas_produksi";
private static final String KEY_LUASNPROD = "luas_nonproduksi";
private static final String KEY_THNTNMPROD = "tahun_tanam_prod";
private static final String KEY_THNTNMNPROD = "tahun_tanam_nonprod";
private static final String KEY_PRNPANEN = "pernah_panen";
private static final String KEY_SKLSPANEN = "siklus_panen";
private static final String KEY_BRTBUAHPANEN = "berat_buah_perpanen";
private static final String KEY_PRODPANEN = "prod_perpanen";
private static final String KEY_ASALBBTCHK = "asal_bibitchk";
private static final String KEY_ASALBBT = "asal_bibit";
private static final String KEY_JNSBBT = "jenis_bibit";
private static final String KEY_HIBRIDA = "hibrida";
private static final String KEY_ASALPPKCHK = "asal_pupukchk";
private static final String KEY_ASALPPK = "asal_pupuk";
private static final String KEY_JNSPPK = "jenis_pupuk";
private static final String KEY_GUNAPPKCHK = "penggunaan_pupukchk";
private static final String KEY_GUNAPPK = "penggunaan_pupuk";
private static final String KEY_CMPRPPK = "campur_pupuk";
private static final String KEY_BHNPPK = "bahan_pupuk";
private static final String KEY_TTPLHN = "tutupan_lahan";
private static final String KEY_LOKJUALCHK = "lokasi_jual_chk";
private static final String KEY_LOKJUAL = "lokasi_jual";
// private static final String KEY_STATUSLahan = "status";
// private static final String KEY_IDKOSONG = "id_kosong";
private static final String KEY_DESKRIPSI = "deskripsi";
private static final String KEY_USERNAME = "user";
private static final String KEY_PASSWORD = "password";
private static final String KEY_ENUMID = "enumID";
private static final String[] COLUMNS = { KEY_IDKK, KEY_NARA, KEY_DESA,
KEY_KEC, KEY_KAB, KEY_KTP, KEY_HP, KEY_NAMAKK, KEY_JMLKK,
KEY_TMPLHR, KEY_TGLLHR, KEY_PDDK, KEY_SUKU, KEY_PKJUTAMA,
KEY_PKJLAIN, KEY_AGTORG, KEY_TGLINPUT, KEY_WKTINPUT };
// private SQLiteDatabase dbase;
private int randomValue;
private static Random random = new Random();
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql_kk = "CREATE TABLE IF NOT EXISTS tb_kk ("
+ " id_kk INTEGER PRIMARY KEY AUTOINCREMENT,"
+ " enumID VARCHAR(50)," + " narasumber VARCHAR(50),"
+ " desa VARCHAR(50)," + " kecamatan VARCHAR(50),"
+ " kabupaten VARCHAR(50)," + " provinsi VARCHAR(50),"
+ " no_KTP VARCHAR(48)," + " no_HP VARCHAR(48),"
+ " nama_kk VARCHAR(50)," + " jumlah_kk INTEGER,"
+ " tempat_lhr VARCHAR(50)," + " tanggal_lhr VARCHAR(50),"
+ " pendidikan VARCHAR(50)," + " suku VARCHAR(50),"
+ " pekerjaan_utama VARCHAR(50),"
+ " pekerjaan_lain VARCHAR(50),"
+ " anggota_organisasi VARCHAR(50),"
+ " tgl_input TIMESTAMP DEFAULT CURRENT_TIMESTAMP,"
+ " status BOOLEAN DEFAULT 0," + " sent_on VARCHAR(50))";
db.execSQL(sql_kk);
String sql_lahan = "CREATE TABLE IF NOT EXISTS tb_lahan ("
+ " id_lahan INTEGER PRIMARY KEY AUTOINCREMENT,"
+ " id_kk INTEGER," + " enumID VARCHAR(50),"
+ " shape_id VARCHAR(50)," + " status_lahan VARCHAR(50),"
+ " lama_lahan VARCHAR(50)," + " luas_produksi DOUBLE,"
+ " luas_nonproduksi DOUBLE," + " tahun_tanam_prod VARCHAR(4),"
+ " tahun_tanam_nonprod VARCHAR(4)," + " pernah_panen BOOLEAN,"
+ " siklus_panen INTEGER," + " berat_buah_perpanen DOUBLE,"
+ " prod_perpanen DOUBLE," + " asal_bibitchk VARCHAR(50),"
+ " asal_bibit VARCHAR(50)," + " jenis_bibit VARCHAR(50),"
+ " hibrida VARCHAR(50)," + " asal_pupukchk VARCHAR(50),"
+ " asal_pupuk VARCHAR(50)," + " jenis_pupuk VARCHAR(50),"
+ " penggunaan_pupukchk TEXT," + " penggunaan_pupuk TEXT,"
+ " campur_pupuk BOOLEAN," + " bahan_pupuk VARCHAR(50),"
+ " tutupan_lahan VARCHAR(50),"
+ " lokasi_jual_chk VARCHAR(50)," + " lokasi_jual VARCHAR(50),"
+ " status BOOLEAN DEFAULT 0," + " sent_on VARCHAR(50))";
db.execSQL(sql_lahan);
String sql_user = "CREATE TABLE IF NOT EXISTS tb_user ("
+ " id_user INTEGER PRIMARY KEY AUTOINCREMENT,"
+ " user VARCHAR(50)," + " password VARCHAR(50),"
+ " enumID INTEGER)";
db.execSQL(sql_user);
String sql_desa = "CREATE TABLE IF NOT EXISTS mst_desa ("
+ " kode_kecamatan INTEGER ," + " kode_desa INTEGER,"
+ " nama_desa VARCHAR(200))";
db.execSQL(sql_desa);
String sql_kec = "CREATE TABLE IF NOT EXISTS mst_kecamatan ("
+ " kode_kabkot int(11)," + " kode_kecamatan int(11),"
+ " nama_kecamatan varchar(200))";
db.execSQL(sql_kec);
String sql_kab = "CREATE TABLE IF NOT EXISTS mst_kabkot ("
+ " kode_prov int(11)," + " kode_kabkot int(11),"
+ " nama_kab_kot varchar(200))";
db.execSQL(sql_kab);
String sql_prov = "CREATE TABLE IF NOT EXISTS mst_prov ("
+ " kode_prov int(11)," + " nama_provinsi varchar(200))";
db.execSQL(sql_prov);
String sql_kosong = "CREATE TABLE IF NOT EXISTS tb_kosong ("
+ " id_kosong int(11)," + " id_kk int(11),"
+ " shape_id VARCHAR(50)," + " deskripsi VARCHAR(250))";
db.execSQL(sql_kosong);
String sql_setting = "CREATE TABLE IF NOT EXISTS tb_setting ("
+ " id_set INTEGER PRIMARY KEY AUTOINCREMENT,"
+ " setURL varchar(200))";
db.execSQL(sql_setting);
// String sql_count = "CREATE TABLE IF NOT EXISTS tb_count (" +
// " id_count INTEGER PRIMARY KEY AUTOINCREMENT," +
// " name VARCHAR(50),"+
// " count int(11))";
// db.execSQL(sql_count);
}
public void deleteRow(int idKK) {
getWritableDatabase().delete("tb_kk", "id_kk=" + idKK, null);
}
public void deleteRowLahan(int idLahan) {
getWritableDatabase().delete("tb_lahan", "id_lahan=" + idLahan, null);
}
public void delete(String mst) {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(mst, null, null);
db.close();
}
public void insertURL() {
ContentValues val = new ContentValues();
val.put(KEY_SETURL, "http://smallholder.inobu.org/");
// val.put(KEY_SETURL, "http://158.69.130.3/");
getWritableDatabase().insert(TABLE_SETTING, null, val);
}
public void insertCount(String name) {
ContentValues val = new ContentValues();
val.put(KEY_USERNAME, name);
getWritableDatabase().insert(TABLE_USER, null, val);
}
public void insertUser(String username, String password, String enumid) {
ContentValues val = new ContentValues();
val.put(KEY_USERNAME, username);
val.put(KEY_PASSWORD, password);
val.put(KEY_ENUMID, enumid);
getWritableDatabase().insert(TABLE_USER, null, val);
}
public void updateURL(long id, String url) {
ContentValues val = new ContentValues();
val.put(KEY_SETURL, url);
getWritableDatabase().update(TABLE_SETTING, val, "id_set=" + id, null);
close();
}
public void updateDesa(long id, String desa, String kecamatan,
String kabupaten, String provinsi) {
ContentValues val = new ContentValues();
val.put(KEY_DESA, desa);
val.put(KEY_KEC, kecamatan);
val.put(KEY_KAB, kabupaten);
val.put(KEY_PROV, provinsi);
getWritableDatabase().update(TABLE_KK, val, "id_kk=" + id, null);
close();
}
public void insertDesa(String desa, String kecamatan, String kabupaten,
String provinsi) {
ContentValues val = new ContentValues();
val.put(KEY_DESA, desa);
val.put(KEY_KEC, kecamatan);
val.put(KEY_KAB, kabupaten);
val.put(KEY_PROV, provinsi);
getWritableDatabase().insert(TABLE_KK, null, val);
}
public void updateStatus(int id, String status, String checkon) {
ContentValues val = new ContentValues();
val.put(KEY_STATUS, status);
val.put(KEY_CHECKON, checkon);
getWritableDatabase().update(TABLE_KK, val, "id_kk=" + id, null);
close();
}
public void updateStatusLahan(String id, String status, String checkon) {
ContentValues val = new ContentValues();
val.put(KEY_STATUS, status);
val.put(KEY_CHECKON, checkon);
getWritableDatabase().update(TABLE_LAHAN, val,
"shape_id= '" + id + "'", null);
close();
}
public void insertNarasumber(String enumne, String narasumber, int KTP,
int HP, String namakk, String jmlkk, String tempatlhr,
String tanggallhr, String pendidikan, String suku,
String kerjaUtama, String kerjaLain, String AngOrg) {
ContentValues val = new ContentValues();
val.put(KEY_ENUM, enumne);
val.put(KEY_NARA, narasumber);
val.put(KEY_KTP, KTP);
val.put(KEY_HP, HP);
val.put(KEY_NAMAKK, namakk);
val.put(KEY_JMLKK, jmlkk);
val.put(KEY_TMPLHR, tempatlhr);
val.put(KEY_TGLLHR, tanggallhr);
val.put(KEY_PDDK, pendidikan);
val.put(KEY_SUKU, suku);
val.put(KEY_PKJUTAMA, kerjaUtama);
val.put(KEY_PKJLAIN, kerjaLain);
val.put(KEY_AGTORG, AngOrg);
getWritableDatabase().insert(TABLE_KK, null, val);
}
public void updateNarasumber(long id, String enumID, String narasumber,
String KTP, String HP, String namakk, int jmlkk, String tempatlhr,
String tanggallhr, String pendidikan, String suku,
String kerjaUtama, String kerjaLain, String AngOrg) {
ContentValues val = new ContentValues();
val.put(KEY_ENUM, enumID);
val.put(KEY_NARA, narasumber);
val.put(KEY_KTP, KTP);
val.put(KEY_HP, HP);
val.put(KEY_NAMAKK, namakk);
val.put(KEY_JMLKK, jmlkk);
val.put(KEY_TMPLHR, tempatlhr);
val.put(KEY_TGLLHR, tanggallhr);
val.put(KEY_PDDK, pendidikan);
val.put(KEY_SUKU, suku);
val.put(KEY_PKJUTAMA, kerjaUtama);
val.put(KEY_PKJLAIN, kerjaLain);
val.put(KEY_AGTORG, AngOrg);
getWritableDatabase().update(TABLE_KK, val, "id_kk=" + id, null);
close();
}
public void insertLahan(int idkk, String enumne, String shapeID,
String statusLahan, String lamaLahan, String luasProd,
String luasNonProd, String tahunTanamProd,
String tahunTanamNonProd, Boolean pernahPanen, String siklusPanen,
String beratPerPanen, String prodPerPanen, String tutupLahan,
String lokJualChk, String lokJual) {
ContentValues val = new ContentValues();
val.put(KEY_IDKK, idkk);
val.put(KEY_ENUM, enumne);
val.put(KEY_SHAPEID, shapeID);
val.put(KEY_STSLAHAN, statusLahan);
val.put(KEY_LAMALAHAN, lamaLahan);
val.put(KEY_LUASPROD, luasProd);
val.put(KEY_LUASNPROD, luasNonProd);
val.put(KEY_THNTNMPROD, tahunTanamProd);
val.put(KEY_THNTNMNPROD, tahunTanamNonProd);
val.put(KEY_PRNPANEN, pernahPanen);
val.put(KEY_SKLSPANEN, siklusPanen);
val.put(KEY_BRTBUAHPANEN, beratPerPanen);
val.put(KEY_PRODPANEN, prodPerPanen);
val.put(KEY_TTPLHN, tutupLahan);
val.put(KEY_LOKJUALCHK, lokJualChk);
val.put(KEY_LOKJUAL, lokJual);
val.put(KEY_STATUS, "0");
getWritableDatabase().insert(TABLE_LAHAN, null, val);
}
public void updateLahan(String shapeID, String statusLahan,
String lamaLahan, String luasProd, String luasNonProd,
String tahunTanamProd, String tahunTanamNonProd,
Boolean pernahPanen, String siklusPanen, String beratPerPanen,
String prodPerPanen, String tutupLahan, String lokJualChk,
String lokJual) {
ContentValues val = new ContentValues();
val.put(KEY_STSLAHAN, statusLahan);
val.put(KEY_LAMALAHAN, lamaLahan);
val.put(KEY_LUASPROD, luasProd);
val.put(KEY_LUASNPROD, luasNonProd);
val.put(KEY_THNTNMPROD, tahunTanamProd);
val.put(KEY_THNTNMNPROD, tahunTanamNonProd);
val.put(KEY_PRNPANEN, pernahPanen);
val.put(KEY_SKLSPANEN, siklusPanen);
val.put(KEY_BRTBUAHPANEN, beratPerPanen);
val.put(KEY_PRODPANEN, prodPerPanen);
val.put(KEY_TTPLHN, tutupLahan);
val.put(KEY_LOKJUALCHK, lokJualChk);
val.put(KEY_LOKJUAL, lokJual);
getWritableDatabase().update(TABLE_LAHAN, val,
"shape_id='" + shapeID + "'", null);
}
public void updateshapeid(int id_lahan, String shapeID) {
ContentValues val = new ContentValues();
val.put(KEY_SHAPEID, shapeID);
getWritableDatabase().update(TABLE_LAHAN, val,
"id_lahan ='" + id_lahan + "'", null);
}
public void updateBibit(String ShapeID, String asalBibitchk,
String asalBibit, String jenisBibit, String hibrida) {
ContentValues val = new ContentValues();
val.put(KEY_ASALBBT, asalBibit);
val.put(KEY_ASALBBTCHK, asalBibitchk);
val.put(KEY_JNSBBT, jenisBibit);
val.put(KEY_HIBRIDA, hibrida);
getWritableDatabase().update(TABLE_LAHAN, val, "shape_id=" + ShapeID,
null);
}
public void updatePupuk(String ShapeID, String asalPupukchk,
String asalPupuk, String jenisPupuk, String gunaPupukchk,
String gunaPupuk, boolean campurPupuk, String bahanPupuk) {
ContentValues val = new ContentValues();
val.put(KEY_ASALPPKCHK, asalPupukchk);
val.put(KEY_ASALPPK, asalPupuk);
val.put(KEY_JNSPPK, jenisPupuk);
val.put(KEY_GUNAPPKCHK, gunaPupukchk);
val.put(KEY_GUNAPPK, gunaPupuk);
val.put(KEY_CMPRPPK, campurPupuk);
val.put(KEY_BHNPPK, bahanPupuk);
getWritableDatabase().update(TABLE_LAHAN, val, "shape_id=" + ShapeID,
null);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_KK);
onCreate(db);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LAHAN);
onCreate(db);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
onCreate(db);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DESA);
onCreate(db);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_KEC);
onCreate(db);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_KAB);
onCreate(db);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PROV);
onCreate(db);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTING);
onCreate(db);
// db.execSQL("DROP TABLE IF EXISTS tb_count");
// onCreate(db);
}
public Cursor getAll() {
return (getReadableDatabase().rawQuery(
"SELECT * FROM tb_kk ORDER BY id_kk", null));
}
public Cursor getAllKK(int idKK) {
Log.d("idKK Response", idKK + "");
return (getReadableDatabase().rawQuery(
"SELECT * FROM tb_kk WHERE id_kk = '" + idKK + "'", null));
}
public Cursor getViewLahan(String idKK) {
Log.d("idKK Response", idKK + "");
return (getReadableDatabase().rawQuery(
"SELECT * FROM tb_lahan WHERE id_kk = '" + idKK
+ "' ORDER BY id_lahan", null));
}
public Cursor getAllLahan(String idKK) {
Log.d("idKK Response", idKK + "");
return (getReadableDatabase().rawQuery(
"SELECT * FROM tb_lahan WHERE id_kk = '" + idKK
+ "' and status = '0' ORDER BY id_lahan", null));
}
public Cursor getAlltoLahan(String idKK, int idLahan) {
// Log.d("idKK Response", idKK+"");
return (getReadableDatabase().rawQuery(
"SELECT * FROM tb_lahan WHERE id_kk = '" + idKK
+ "' and id_lahan=" + idLahan + " ORDER BY id_lahan",
null));
}
public Cursor getAllLahanKosong() {
return (getReadableDatabase()
.rawQuery(
"select * from tb_lahan where status_lahan is null and lama_lahan ='' and tahun_tanam_prod='0'",
null));
}
public Cursor getAlltoLhn(String idKK, String shapeid) {
Log.d("idKK Response", idKK + " " + shapeid);
return (getReadableDatabase().rawQuery(
"select * from tb_lahan where id_kk='" + idKK
+ "' and shape_id='" + shapeid + "' order by id_lahan",
null));
}
public Cursor getOneContact(long id) {
return (getReadableDatabase().query("tb_kk", null, "id_kk=" + id, null,
null, null, null));
}
public Cursor getLastdateKK() {
return (getReadableDatabase().rawQuery(
"select * from tb_kk where status = 0", null));
}
public Cursor getLastdateLahan() {
return (getReadableDatabase().rawQuery(
"select * from tb_lahan where status = 0", null));
}
// public Cursor getURL()
// {
// return (getReadableDatabase().query("tb_setting", null, "id_set= 1",
// null, null, null, null));
// }
public String getURL() {
String row = null;
try {
String selectQuery = "SELECT setURL FROM tb_setting where id_set=1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getString(0);
} catch (Throwable e) {
}
return row;
}
// public String setRandom() {
// String setrandom = null;
// myRandom = new Random();
//
// for(int i = 0; i < 10; i++){
// setrandom += String.valueOf(myRandom.nextInt()) + "\n";
// }
// return setrandom;
// }
public static int getRandom(int max, int min){
return random.nextInt(max - min + 1)+min;
}
public String getUser() {
String row = null;
try {
String selectQuery = "SELECT user FROM tb_user where id_user=1";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getString(0);
} catch (Throwable e) {
}
return row;
}
// public Cursor getOneDesa(String id)
// {
// return (getReadableDatabase().query("mst_desa", null, "kode_desa=" + id,
// null, null, null, null));
// }
//
// public Cursor getOneKec(String id)
// {
// return (getReadableDatabase().query("mst_kecamatan", null,
// "kode_kecamatan=" + id, null, null, null, null));
// }
//
// public Cursor getOneKab(String id)
// {
// return (getReadableDatabase().query("mst_kabupaten", null, "kode_kabkot="
// + id, null, null, null, null));
// }
//
// public Cursor getOneProv(String id)
// {
// return (getReadableDatabase().query("mst_prov", null, "kode_prov=" + id,
// null, null, null, null));
// }
public Contact readContact(int id) {
// get reference of the BookDB database
SQLiteDatabase db = this.getReadableDatabase();
// get book query
Cursor cursor = db.query(
TABLE_KK, // a. table
COLUMNS, " id_kk = ?", new String[] { String.valueOf(id) },
null, null, null, null);
// if results !=null, parse the first one
if (cursor != null)
cursor.moveToFirst();
Contact cont = new Contact();
cont.setID(Integer.parseInt(cursor.getString(0)));
cont.setName(cursor.getString(1));
cont.setName(cursor.getString(2));
return cont;
}
public int getid() {
int row = 0;
String selectQuery = "SELECT MAX(id_kk) FROM tb_kk";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
return row;
}
// public int getidLahan(int idkk)
// {
// int row=0;
// String selectQuery = "SELECT MAX(id_lahan) FROM tb_lahan where id_kk='"+
// idkk+"'";
// SQLiteDatabase db = this.getWritableDatabase();
// Cursor cursor = db.rawQuery(selectQuery, null);
// if (cursor != null) {
// cursor.moveToFirst();
// }
//
// row = cursor.getInt(0);
// return row;
// }
public int getidLahannya(int idkk) {
int row = 0;
try {
String selectQuery = "SELECT MAX(id_lahan) FROM tb_lahan where id_kk='"
+ idkk + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
public int getidLahan() {
int row = 0;
try {
String selectQuery = "SELECT MAX(id_lahan) FROM tb_lahan";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
public int getEnumID() {
int row = 0;
String selectQuery = "SELECT MAX(enumID) FROM tb_user";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
return row;
}
public int getShapeID(int idk) {
int row = 0;
try {
String selectQuery = "SELECT MAX(shape_id) FROM tb_lahan where id_kk="
+ idk;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
public Set<String> getAllDesa(String kec) {
Set<String> set = new HashSet<String>();
String selectQuery = null;
selectQuery = "select b.kode_desa, b.nama_desa from mst_kecamatan a"
+ " inner join mst_desa b on a.kode_kecamatan = b.kode_kecamatan"
+ " where nama_kecamatan like '%" + kec
+ "%' order by nama_desa asc";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return set;
}
public Set<String> getAllKec(String kab) {
Set<String> set = new HashSet<String>();
String selectQuery = "select b.kode_kecamatan, b.nama_kecamatan"
+ " from mst_kecamatan b"
+ " left join mst_kabkot c on b.kode_kabkot = c.kode_kabkot"
+ " where c.nama_kab_kot like '%" + kab
+ "%' order by nama_kecamatan asc";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return set;
}
public Set<String> getAllKab(String prov) {
Set<String> set = new HashSet<String>();
String selectQuery = "select b.kode_kabkot, b.nama_kab_kot"
+ " from mst_kabkot b"
+ " left join mst_prov c on b.kode_prov = c.kode_prov"
+ " where c.nama_provinsi like '%" + prov
+ "%' order by b.nama_kab_kot asc";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return set;
}
public Set<String> getAllProv() {
Set<String> set = new HashSet<String>();
String selectQuery = "select kode_prov, nama_provinsi from mst_prov order by nama_provinsi asc";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return set;
}
public int getDesaID(String ndesa) {
int row = 0;
try {
String selectQuery = "SELECT kode_desa FROM mst_desa WHERE nama_desa ='"
+ ndesa + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
public int getKecID(String idkec) {
int row = 0;
try {
String selectQuery = "SELECT kode_kecamatan FROM mst_kecamatan where nama_kecamatan ='"
+ idkec + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
public int getKabID(String idkab) {
int row = 0;
try {
String selectQuery = "SELECT kode_kabkot FROM mst_kabkot where nama_kab_kot='"
+ idkab + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
public int getProvID(String idProv) {
int row = 0;
try {
String selectQuery = "SELECT kode_prov FROM mst_prov where nama_provinsi ='"
+ idProv + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
public int countURL() {
int row = 0;
try {
String selectQuery = "SELECT COUNT(*) from tb_setting";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
public int countDesa() {
int row = 0;
try {
String selectQuery = "SELECT COUNT(*) from mst_desa";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
public int countKec() {
int row = 0;
try {
String selectQuery = "SELECT COUNT(*) from mst_kecamatan";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
public int countKab() {
int row = 0;
try {
String selectQuery = "SELECT COUNT(*) from mst_kab_kota";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
public int countProv() {
int row = 0;
try {
String selectQuery = "SELECT COUNT(*) from mst_prov";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getInt(0);
} catch (Throwable e) {
}
return row;
}
// public void InsertCount(String namec, int count)
// {
// ContentValues val = new ContentValues();
// val.put("name", namec);
// val.put("count", count);
//
// getWritableDatabase().insert("tb_count", null, val);
// }
public void createInsertDesa(int kodekecamatan, int kodedesa,
String namadesa) {
ContentValues val = new ContentValues();
val.put(KEY_KKEC, kodekecamatan);
val.put(KEY_KDESA, kodedesa);
val.put(KEY_NDESA, namadesa);
getWritableDatabase().insert(TABLE_DESA, null, val);
}
public void createInsertKec(int kodekabkot, int kodekecamatan,
String namakec) {
ContentValues val = new ContentValues();
val.put(KEY_KKAB_KOTA, kodekabkot);
val.put(KEY_KKEC, kodekecamatan);
val.put(KEY_NKEC, namakec);
getWritableDatabase().insert(TABLE_KEC, null, val);
}
public void createInsertProv(int kodeprov, String namaprov) {
ContentValues val = new ContentValues();
val.put(KEY_KODEPROV, kodeprov);
val.put(KEY_NPROV, namaprov);
getWritableDatabase().insert(TABLE_PROV, null, val);
}
public void createInsertKab(int kodeprov, int kodekabkot, String namakab) {
ContentValues val = new ContentValues();
val.put(KEY_KODEPROV, kodeprov);
val.put(KEY_KKAB_KOTA, kodekabkot);
val.put(KEY_NKAB_KOTA, namakab);
getWritableDatabase().insert(TABLE_KAB, null, val);
}
public void createInsertKosong(int idKK, String deskripsi) {
ContentValues val = new ContentValues();
val.put(KEY_IDKK, idKK);
val.put(KEY_DESKRIPSI, deskripsi);
getWritableDatabase().insert(TABLE_KOSONG, null, val);
}
public void createUpdateKosong(int idKK, String deskripsi) {
ContentValues val = new ContentValues();
val.put(KEY_DESKRIPSI, deskripsi);
getWritableDatabase().update(TABLE_KOSONG, val, "id_kk=" + idKK, null);
}
// dari tabel kk
public String getIdKK(Cursor c) {
return (c.getString(0));
}
// dari tabel kk
public String getEnumIDnara(Cursor c) {
return (c.getString(1));
}
public String getNama(Cursor c) {
return (c.getString(2));
}
public String getDesa(Cursor c) {
return (c.getString(3));
}
public String getKec(Cursor c) {
return (c.getString(4));
}
public String getKab(Cursor c) {
return (c.getString(5));
}
public String getProv(Cursor c) {
return (c.getString(6));
}
public String getKTP(Cursor c) {
return (c.getString(7));
}
public String getHP(Cursor c) {
return (c.getString(8));
}
public String getnamaKK(Cursor c) {
return (c.getString(9));
}
public String getJmlKK(Cursor c) {
return (c.getString(10));
}
public String getTempatLhr(Cursor c) {
return (c.getString(11));
}
public String gettanggalLhr(Cursor c) {
return (c.getString(12));
}
public String getpendidikan(Cursor c) {
return (c.getString(13));
}
public String getsuku(Cursor c) {
return (c.getString(14));
}
public String getpekerjaanutama(Cursor c) {
return (c.getString(15));
}
public String getpekerjaanlain(Cursor c) {
return (c.getString(16));
}
public String getagt_org(Cursor c) {
return (c.getString(17));
}
public String gettglinput(Cursor c) {
return (c.getString(18));
}
public String getStatus(Cursor c) {
return (c.getString(19));
}
// Declare Lahan
public String getidlahan(Cursor c) {
return (c.getString(0));
}
public String getidkklahan(Cursor c) {
return (c.getString(1));
}
public String getEnumID(Cursor c) {
return (c.getString(2));
}
public String getshape_ID(Cursor c) {
return (c.getString(3));
}
public String getstatus_lahan(Cursor c) {
return (c.getString(4));
}
public String getlama_lahan(Cursor c) {
return (c.getString(5));
}
public String getluas_prod(Cursor c) {
return (c.getString(6));
}
public String getluas_nonprod(Cursor c) {
return (c.getString(7));
}
public String gettahun_tanam(Cursor c) {
return (c.getString(8));
}
public String gettahun_tanamnon(Cursor c) {
return (c.getString(9));
}
public String getpernah_panen(Cursor c) {
return (c.getString(10));
}
public String getsiklus_panen(Cursor c) {
return (c.getString(11));
}
public String getberat_buah(Cursor c) {
return (c.getString(12));
}
public String getprod_perpanen(Cursor c) {
return (c.getString(13));
}
public String getasal_bibitchk(Cursor c) {
return (c.getString(14));
}
public String getasal_bibit(Cursor c) {
return (c.getString(15));
}
public String getjenis_bibit(Cursor c) {
return (c.getString(16));
}
public String gethibrida(Cursor c) {
return (c.getString(17));
}
public String getasal_pupukchk(Cursor c) {
return (c.getString(18));
}
public String getasal_pupuk(Cursor c) {
return (c.getString(19));
}
public String getjenis_pupuk(Cursor c) {
return (c.getString(20));
}
public String getpenggunaan_pupukchk(Cursor c) {
return (c.getString(21));
}
public String getpenggunaan_pupuk(Cursor c) {
return (c.getString(22));
}
public String getcampur_pupuk(Cursor c) {
return (c.getString(23));
}
public String getbahan_pupuk(Cursor c) {
return (c.getString(24));
}
public String gettutupan_lahan(Cursor c) {
return (c.getString(25));
}
public String getlokasi_jualchk(Cursor c) {
return (c.getString(26));
}
public String getlokasi_jual(Cursor c) {
return (c.getString(27));
}
public String getStatusKirim_lahan(Cursor c) {
return (c.getString(28));
}
// ------------------------
public String getOneDesa(String iddesa) {
String row = null;
try {
String selectQuery = "SELECT nama_desa FROM mst_desa WHERE kode_desa ='"
+ iddesa + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getString(0);
} catch (Throwable e) {
}
return row;
}
public String getOneKec(String idkec) {
String row = null;
try {
String selectQuery = "SELECT nama_kecamatan FROM mst_kecamatan WHERE kode_kecamatan ='"
+ idkec + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getString(0);
} catch (Throwable e) {
}
return row;
}
public String getOneKab(String idkab) {
String row = null;
try {
String selectQuery = "SELECT nama_kab_kot FROM mst_kabkot WHERE kode_kabkot ='"
+ idkab + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getString(0);
} catch (Throwable e) {
}
return row;
}
public String getOneProv(String idprov) {
String row = null;
try {
String selectQuery = "SELECT nama_provinsi FROM mst_prov WHERE kode_prov ='"
+ idprov + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getString(0);
} catch (Throwable e) {
}
return row;
}
public String getNarasumber(int id_kk) {
String row = null;
try {
String selectQuery = "select b.narasumber, a.id_lahan, a.shape_id, a.status_lahan from tb_lahan a left join tb_kk b on a.id_kk=b.id_kk where id_kk='"
+ id_kk + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
row = cursor.getString(0);
} catch (Throwable e) {
}
return row;
}
// public int getCount(String idcount)
// {
// Integer row=null;
// try{
// String selectQuery =
// "SELECT count FROM tb_count WHERE name ='"+idcount+"'";
//
// SQLiteDatabase db = this.getWritableDatabase();
// Cursor cursor = db.rawQuery(selectQuery, null);
// if (cursor != null) {
// cursor.moveToFirst();
// }
//
// row = cursor.getInt(0);
// }catch (Throwable e) {
//
// }
// return row;
// }
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
public int cekSentNarasumber() {
String countQuery = "SELECT * FROM tb_kk where status=0";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public int cekSentLahan() {
String countQuery = "SELECT * FROM tb_lahan where status=0";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public int getCountLahan(int idkk) {
String countQuery = "SELECT * FROM tb_lahan where id_kk=" + idkk
+ " and status=0";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public int getLahanKosong() {
String countQuery = "select * from tb_lahan where status_lahan is null and lama_lahan ='' and tahun_tanam_prod='0'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public void resetTables() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_USER, null, null);
db.close();
}
public int getstatusKK(String idkk) {
int status = 0;
try {
String selectQuery = "select status from tb_kk where id_kk='"
+ idkk + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
cursor.moveToFirst();
}
status = cursor.getInt(0);
} catch (Throwable e) {
}
return status;
}
public Cursor fetchAllCountries() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCursor = db.query(TABLE_KK, new String[] { KEY_IDKK,
KEY_NAMAKK, KEY_KTP }, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
|
public class LQueue {
private class Node {
Node next;
int value;
}
private Node head, tail;
public void enqueue(int value) {
Node node = new Node();
node.value = value;
if(tail == null) {
head = node;
tail = node;
} else {
tail.next = node;
tail = node;
}
}
public int dequeue() throws Exception {
if(head == null) {
throw new Exception("Empty!");
} else {
Node ret = head;
head = head.next;
if(head == null)
tail = null;
return ret.value;
}
}
public static void main(String[] args) throws Exception {
LQueue lq = new LQueue();
lq.enqueue(5);
lq.enqueue(3);
lq.enqueue(2);
lq.enqueue(4);
System.out.println(lq.dequeue());
System.out.println(lq.dequeue());
System.out.println(lq.dequeue());
System.out.println(lq.dequeue());
lq.enqueue(5);
lq.enqueue(3);
lq.enqueue(2);
lq.enqueue(4);
System.out.println(lq.dequeue());
System.out.println(lq.dequeue());
System.out.println(lq.dequeue());
System.out.println(lq.dequeue());
System.out.println(lq.dequeue());
}
}
|
package com.hcy.suzhoubusquery.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.hcy.suzhoubusquery.R;
import com.hcy.suzhoubusquery.utils.BaseBean;
import java.util.ArrayList;
/**
* Created by hcy on 2015/11/30.
*
* LineNumBaseAdapter
*
*/
public class LineNumBaseAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
private ArrayList<BaseBean> items;
public LineNumBaseAdapter(Context context, ArrayList<BaseBean> items) {
this.inflater = LayoutInflater.from(context);
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
BaseBean item = items.get(position);
if (null == item) {
return convertView;
}
Holder holder;
if (convertView == null) {
holder = new Holder();
convertView = inflater.inflate(R.layout.fragment_line_num_layout_item, null);
holder.lineNum = (TextView) convertView.findViewById(R.id.line_num);
holder.linNumToWhere = (TextView) convertView.findViewById(R.id.to_where);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.lineNum.setText(item.getStr("LName")+"");
holder.linNumToWhere.setText(item.getStr("LDirection")+"");
return convertView;
}
private class Holder {
TextView lineNum;
TextView linNumToWhere;
}
}
|
package com.bofsoft.laio.customerservice.dialog;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import com.bofsoft.laio.customerservice.R;
public class PromptDialog {
String title;
String content;
Context context;
OnClickListener onClickListener;
AlertDialog dialog;
public PromptDialog(Context context, String title, String content, OnClickListener onClickListener) {
this.title = title;
this.content = content;
this.context = context;
this.onClickListener = onClickListener;
try {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title).setMessage(content).setIcon(R.drawable.ic_launcher)
.setCancelable(false).setPositiveButton("知道了", onClickListener).create();
dialog = builder.create();
dialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isShowing() {
if (dialog != null) {
return dialog.isShowing();
} else {
return false;
}
}
public void close() {
if (dialog != null) {
dialog.dismiss();
}
}
}
|
//accept producet details calculate and print bill
import java.util.*;
class bulk_discount_on_qty
{
public static void main(String args[])
{
boolean b=true;
double mrp=0.0,qty=0.0,total=0.0,bdis=0.0,pay=0.0,vat=0.0,net=0.0,rate=0.0;
Scanner x=new Scanner(System.in);
System.out.print("Enter Producet code:-");
double pcode=x.nextDouble();
if(pcode>0)
{
System.out.print("Enter M.R.P of given Producet:-");
mrp=x.nextDouble();
if(mrp>0)
{
System.out.print("Enter Quataty of given Producet:-");
qty=x.nextDouble();
if(qty>0)
{
if(qty<=10)
if(qty<=50)
rate=20.0;
else
if(qty<=100)
rate=25.0;
else
rate=30.0;
}else{
b=false;
System.out.println("Invalied Quantety found !plz Enter agan" );
}
}else{
b=false;
System.out.println("Invalied MRP found !plz Enter agan" );
}
}else{
b=false;
System.out.println("Invalied Producet code found !plz Enter agan" );
}
if(b)
{
total=mrp*qty;
bdis=total*rate/100;
pay=total-bdis;
vat=pay*12/100;
net=pay+vat;
System.out.println("==========Bill DETAILS=============");
System.out.println("Producet code:: "+pcode);
System.out.println("M.R.P in Rs :: "+mrp);
System.out.println("Quantety Tokan:: "+qty);
System.out.println("----------------------------------------");
System.out.println("Total amount in Rs:: "+total);
System.out.println("BULK Discount Amount in Rs::"+bdis);
System.out.println("----------------------------------------");
System.out.println("Payble Amount in Rs:: "+pay);
System.out.println("12% Vat in Rs:: "+vat);
System.out.println("----------------------------------------");
System.out.println("NET bill Amount in Rs:: "+net);
}
}//close of main
}//close of class
|
package listTest;
import java.util.Stack;
public class Test1 {
public static void main(String[] args) {
String s = "12132431qda2312fsdfs121231weww";
Stack<String> ss = new Stack<>();
Stack<String> ss1 = new Stack<>();
for (int i = 0; i < s.length();i++){
String s3 = String.valueOf(s.charAt(i));
if (s3.matches("[a-z]")){
ss.push(s3);
}else {
ss1.push(s3);
}
}
for (String d:ss){
System.out.print(d);
}
System.out.println("--------------");
for (String e:ss1){
System.out.print(e);
}
}
}
|
package com.gnts.infog.InfoGlogin;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WebFunction {
public static WebDriver driver;
public static WebDriverWait wait;
static Logger log = Logger.getLogger(WebFunction.class);
static int targetDay = 0;
static int targetMonth = 0, targetYear = 0;
static int currenttDate = 0, currenttMonth = 0, currenttYear = 0;
static int jumMonthBy = 0;
static boolean increment = true;
// WEB_BROWSER_INVOKE_FUNCTION
public static TestStatus WEB_BROWSER_INVOKE(String BrowserName) {
TestStatus test = new TestStatus();
test.setStatus("PASS");
if (BrowserName == null || BrowserName == "") {
System.out.println("The browsername is blank");
test.setStatus("FAIL");
test.setErrormsg("Browsername is empty");
log.error("Browser name is empty");
} else {
try {
switch (BrowserName) {
case "firefox":
driver = new FirefoxDriver();
log.info("Firefox browser invoked");
test.setStatus("PASS");
break;
case "chrome":
System.setProperty("webdriver.chrome.driver",
"F:\\Selenium supported files\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
log.info("Chrome browser invoked");
test.setStatus("PASS");
break;
case "Internet explorer":
System.setProperty("webdriver.ie.driver",
"F:\\Selenium supported files\\IEDriverServer_x64_3.3.0\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
log.info("IE browser invoked");
test.setStatus("PASS");
break;
default:
log.error("Browser name is invalid");
test.setStatus("FAIL");
break;
}
} catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
}
}
return test;
}
// Web browser navigate function
// Give to URL data
public static TestStatus WEB_BROWSER_NAVIGATE(String UrlData) {
TestStatus test = new TestStatus();
test.setStatus("PASS");
if (UrlData == "") {
log.error("URL is rmpty");
test.setStatus("FAIL");
test.setErrormsg("URL is empty");
return test;
} else {
try {
wait = new WebDriverWait(driver, 50);
driver.get(UrlData);
test.setStatus("PASS");
test.setErrormsg("Open the infog home page");
log.info("Open the infog home page");
} catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
}
return test;
}
// WEB_VIEW_FULLSCREEN FUNCTION
public static TestStatus WEB_BROWSER_FULLSCREEN() {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
test.setStatus("PASS");
test.setErrormsg("View the full screen");
log.info("View the full screen");
} catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
return test;
}
return test;
}
// Click,Link function
// Pass parameter locator type and element(id,xpath,classname)
public static TestStatus WEB_ELEMENT_CLICK(String Locator, String path, String actualValue) throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
if (Locator == "" || path == "") {
test.setStatus("FAIL");
test.setErrormsg("Parameter is empty");
log.error("Parameter is empty");
return test;
} else {
try {
switch (Locator) {
case "xpath":
WebElement button = driver.findElement(By.xpath(path));
if (button.isDisplayed() || button.isEnabled()) {
String se = driver.findElement(By.xpath(path)).getText();
System.out.println(se);
test.setStatus("PASS");
test.setErrormsg(actualValue);
test.setElement(se);
driver.findElement(By.xpath(path)).click();
log.info("Element clicked");
break;
} else {
test.setStatus("FAIL");
test.setErrormsg("Element disable");
log.error("Element disable");
return test;
}
case "className":
WebElement button1 = driver.findElement(By.className(path));
if (button1.isDisplayed() || button1.isEnabled()) {
driver.findElement(By.className(path)).click();
String se = driver.findElement(By.className(path)).getText();
System.out.println(se);
test.setStatus("PASS");
test.setErrormsg("Element clicked");
log.info("Element clicked");
test.setElement(se);
break;
} else {
test.setStatus("FAIL");
test.setErrormsg("Element disable");
log.error("Element disable");
return test;
}
case "id":
WebElement button2 = driver.findElement(By.id(path));
if (button2.isDisplayed() || button2.isEnabled()) {
String se = button2.getText();
System.out.println(se);
test.setStatus("PASS");
test.setElement(se);
test.setErrormsg("Element clicked");
driver.findElement(By.id(path)).click();
log.info("Element clicked");
break;
} else {
test.setStatus("FAIL");
test.setErrormsg("Element disable");
log.error("Element disable");
return test;
}
}
} catch (NullPointerException e) {
// TODO: handle exception
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg("NULL POINTER EXCEPTION");
log.info("Null Pointer Exception");
return test;
} catch (NoSuchElementException e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg("NO SUCH ELEMENT EXCEPTION");
log.info("No such element exception");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.info(e.getMessage());
return test;
}
}
return test;
}
// Web_Edit_Type function
// Pass parameter locator type and Button location
// element(id,xpath,classname)
public static TestStatus WEB_EDIT_TYPE(String Locator, String path, String value, String actualValue) {
TestStatus test = new TestStatus();
test.setStatus("PASS");
if (Locator.isEmpty() || path.isEmpty() || value.isEmpty()) {
System.out.println("The parameter passed is blank");
test.setStatus("FAIL");
test.setErrormsg("PARAMETER IS EMPTY");
return test;
} else {
try {
switch (Locator) {
case "xpath":
WebElement button = driver.findElement(By.xpath(path));
if (button.isDisplayed() || button.isEnabled()) {
driver.findElement(By.xpath(path)).sendKeys(value);
log.info("Type in text field:"+ value);
test.setStatus("PASS");
return test;
} else {
test.setStatus("FAIL");
test.setErrormsg("TEXT FIELD DISABLED");
log.error("Text field disable");
return test;
}
case "className":
WebElement button1 = driver.findElement(By.className(path));
if (button1.isDisplayed() || button1.isEnabled()) {
driver.findElement(By.className(path)).sendKeys(value);
log.info("Type in text field:"+value);
test.setStatus("PASS");
break;
} else {
test.setStatus("FAIL");
test.setErrormsg("TEXT FIELD DISABLED");
log.error("Text field disable");
return test;
}
case "id":
String se = driver.findElement(By.id(path)).getText();
System.out.println(se);
WebElement button2 = driver.findElement(By.id(path));
if (button2.isDisplayed() || button2.isEnabled()) {
driver.findElement(By.id(path)).sendKeys(value);
log.info("Type in text field:"+value);
test.setStatus("PASS");
break;
} else {
test.setStatus("FAIL");
test.setErrormsg("TEXT FIELD DISABLED");
log.error("Text field disable");
return test;
}
}
} catch (NullPointerException e) {
// TODO: handle exception
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg("NullPointerException");
log.error("NullPointerException");
return test;
} catch (NoSuchElementException e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg("No Such element");
log.error("No Such element");
return test;
} catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
}
return test;
}
// Invoice name select Dropdown function
public static TestStatus INVOICE_NAME_SELECT(String Value) throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try {
WebElement ee = driver.findElement(By.id("invoiceTo"));
ee.click();
log.info("Click on invoice name dropdown");
List<WebElement> elements = ee.findElements(By.className("ui-select-choices-row-inner"));
for (WebElement element : elements) {
if (element.findElement(By.tagName("span")).getText().equals(Value)) {
element.click();
log.info("Select value from Invoice name dropdown ");
test.setStatus("PASS");
test.setErrormsg("VALUE IS MATCHED");
break;
} else {
System.out.println("VALUE NOT MATCHED");
test.setStatus("FAIL");
test.setErrormsg("VALUE NOT MATCHED");
log.error("Invoice name is not matched");
}
}
} catch (NullPointerException e) {
// TODO: handle exception
e.printStackTrace();
test.setStatus("FAIL");
log.error("Null pointer exception");
test.setErrormsg("NULL POINTER EXCEPTION");
return test;
} catch (NoSuchElementException e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error("No such element");
test.setErrormsg("NO SUCH ELEMENT EXCEPTION");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
return test;
}
return test;
}
// LOGIN_FUNCTION
public static TestStatus LOGIN_FUNCTION(String[] actualValue) throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(By.xpath(".//*[@id='signin-form']/div[3]/div/div/button")).submit();
log.info("Click on signIn button");
for (String errorMsg : actualValue) {
boolean alertMessage = driver.getPageSource().contains(errorMsg);
System.out.println(alertMessage);
if (alertMessage) {
test.setStatus("FAIL");
test.setErrormsg(errorMsg);
log.error(errorMsg);
return test;
}
}
test.setStatus("PASS");
test.setErrormsg("System provided Login Successfully");
log.info("Login Successfully");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
return test;
}
}
// Signup_function
public static TestStatus SIGNUP_FUNCTION(String[] actualValue) throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(By.id("btnSignup")).click();
log.info("click on create account button");
for (String errorMsg : actualValue) {
boolean alertMessage = driver.getPageSource().contains(errorMsg);
System.out.println(alertMessage);
if (alertMessage) {
test.setStatus("PASS");
test.setErrormsg(errorMsg);
log.error(errorMsg);
return test;
}
}
test.setStatus("PASS");
test.setErrormsg("System provide signup Successfully");
log.info("Create account successfully");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
return test;
}
}
// Invoice _Submit function
public static TestStatus INVOICE_SUBMIT(String[] actualValue) throws AWTException {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
String totalvalue = driver
.findElement(
By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div/div/form/div[4]/div[4]/div"))
.getText();
System.out.println(totalvalue);
test.setElement(totalvalue);
driver.findElement(
By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div/div/form/div[2]/div[1]/div[4]/button"))
.click();
log.info("Click on invoice submit button");
for (String errorMsg : actualValue) {
boolean alertMessage = driver.getPageSource().contains(errorMsg);
System.out.println(alertMessage);
if (alertMessage) {
test.setStatus("PASS");
test.setErrormsg(errorMsg);
log.info(errorMsg);
return test;
}
}
test.setStatus("PASS");
test.setErrormsg("Invoice created successfully");
log.info("Invoice created successfully");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
return test;
}
}
// threadsleep
// Browser action wait and action, depands upon time
public static TestStatus THREADSLEEP() throws InterruptedException {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try {
Thread.sleep(5000L);
test.setStatus("PASS");
log.info("Wait");
test.setErrormsg("WAIT");
return test;
} catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
}
//Signup industry,country,state and city dropdown select
public static TestStatus SIGNUP_DROPDOWN_SELECT(String id, String value) throws InterruptedException {
TestStatus test = new TestStatus();
test.setStatus("PASS");
if (id == "" || value == "") {
test.setStatus("FAIL");
log.error("Parameter is empty");
test.setErrormsg("PARAMETER IS EMPTY");
return test;
} else
try {
{
WebElement reg_area = driver.findElement(By.id(id));
reg_area.click();
log.info("click on dropdown");
WebElement chosenResult = reg_area.findElement(By.className("chosen-results"));
List<WebElement> dropDownChoices = chosenResult.findElements(By.className("active-result"));
boolean isFound = false;
for (WebElement webElement : dropDownChoices) {
System.out.println("Drop down value : " + webElement.getText());
String sValue = webElement.getText();
if (value.equals(sValue)) {
webElement.click();
log.info("System selected the value is"+webElement.getText());
isFound = true;
test.setStatus("PASS");
test.setErrormsg("System selected the value");
test.setElement(value);
System.out.println("Drop down value selected is : " + webElement.getText());
return test;
}
else {
test.setStatus("FAIL");
log.error("Value is not match");
System.out.println("value is not match" + sValue);
}
}
if (isFound) {
System.out.println("Testcase is pass");
} else {
System.out.println("Testcase is fail");
test.setStatus("FAIL");
test.setErrormsg("VALUE NOT MATCHED");
test.setElement(value);
return test;
}
}
}
catch (NullPointerException e) {
// TODO: handle exception
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg("NullPointerException");
return test;
} catch (NoSuchElementException e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg("No Such element");
return test;
} catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
return test;
}
return test;
}
//Select product from dropdown
public static TestStatus INVOICE_DROPDOWN(String path, String value) throws InterruptedException {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try {
WebElement se = driver.findElement(By.xpath(path));
se.click();
log.info("Dropdown select");
WebElement choicesList = se.findElement(By.className("ui-select-choices-group"));
List<WebElement> choices = se.findElements(By.className("ui-select-choices-row-inner"));
// List<WebElement> spans = driver.findElements(By.tagName("span"));
for (WebElement choice : choices) {
WebElement span = choice.findElement(By.tagName("span"));
String text = span.getText();
System.out.println(text);
if (text.equals(value)) {
choice.click();
log.info("Value is match"+value);
boolean alertMessage = driver.getPageSource().contains("Product already exist.");
System.out.println(alertMessage);
if (alertMessage) {
test.setStatus("FAIL");
log.error("Product already exist.");
test.setErrormsg("Product already exist.");
System.out.println("Product already exist.");
break;
}
System.out.println("Value is Match");
test.setStatus("PASS");
break;
}
else {
test.setStatus("FAIL");
log.error("Value not match");
System.out.println("Value not Match");
test.setErrormsg("Value not match");
}
}
System.out.println("LOOP END");
} catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
return test;
}
return test;
}
// web get cell data
public static TestStatus WEB_GET_CELL_DATA(String value, String actualvalue) {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try {
int Row_count = driver
.findElements(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div/div/div[2]/div/div[1]/table/tbody/tr/td[1]"))
.size();
System.out.println("Number Of Rows = " + Row_count);
log.info("Row count is"+Row_count);
int Col_count = driver
.findElements(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div/div/div[2]/div/div[1]/table/tbody/tr[1]/td"))
.size();
log.info("Row count is"+Col_count);
System.out.println("Number Of Columns = " + Col_count);
String first_part = "html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div/div/div[2]/div/div[1]/table/tbody/tr[";
String second_part = "]";
String third_part = "/td[";
String fourth_part = "]";
String fifth_part = "/td[4]/a";
for (int i = 1; i <= Row_count; i++) {
for (int j = 1; j <= Col_count; j++) {
String final_xpath = first_part + i + second_part + third_part + j + fourth_part;
System.out.println(final_xpath);
String Table_data = driver.findElement(By.xpath(final_xpath)).getText();
System.out.println(Table_data + " ");
if (Table_data.equals(value)) {
System.out.println("Value is Match:" + value);
WebElement actionCell = driver.findElement(By.xpath(first_part + i + second_part + fifth_part));
System.out.println(actionCell);
actionCell.click();
log.info("View the data");
test.setErrormsg("Success");
return test;
}
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
// Brands edit function
public static TestStatus EDIT_BRANDS() {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[6]/div/div/form/div[2]/input[2]"))
.clear();
log.info("Clear the brands name");
driver.findElement(By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[6]/div/div/form/div[2]/input[2]"))
.sendKeys("Fridge");
log.info("Edit the brands name");
WebElement ee = driver.findElement(By.id("baloonmodel"));
ee.click();
log.info("Select brands status dropdown");
List<WebElement> elements = ee.findElements(By.className("ui-select-choices-row-inner"));
for (WebElement element : elements) {
if (element.findElement(By.tagName("span")).getText().equals("InActive")) {
element.click();
test.setStatus("PASS");
log.info("Value is matched");
System.out.println("VALUE IS MATCHED");
test.setErrormsg("Value is matched");
break;
}
else{
test.setStatus("FAIL");
log.error("Value is not matched");
test.setErrormsg("Value is matched");
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
// brands_save_function
public static TestStatus BRANDS_SAVE(String[] actualValue) throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[6]/div/div/div/div/button")).click();
log.info("Click on brand save button");
for (String errorMsg : actualValue) {
boolean alertMessage = driver.getPageSource().contains(errorMsg);
System.out.println(alertMessage);
if (alertMessage) {
test.setStatus("PASS");
test.setStatus_message(errorMsg);
return test;
}
else{
test.setStatus("FAIL");
test.setErrormsg("Enter valid brand name");
return test;
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
// CATEGORY_SAVE_FUNCTION
public static TestStatus CATEGORY_SAVE(String[] actualValue) throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[6]/div/div/div/div/button")).click();
log.info("Click on category save button");
for (String errorMsg : actualValue) {
boolean alertMessage = driver.getPageSource().contains(errorMsg);
System.out.println(alertMessage);
if (alertMessage) {
test.setStatus("PASS");
test.setErrormsg(errorMsg);
log.info(errorMsg);
return test;
}
else{
test.setStatus("FAIL");
test.setErrormsg("Enter valid Category name");
log.info("Enter valid Category name");
return test;
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
// Category edit function
public static TestStatus EDIT_CATEGORY() {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[6]/div/div/form/div[2]/input[2]"))
.clear();
log.info("Text field is clear");
driver.findElement(By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[6]/div/div/form/div[2]/input[2]"))
.sendKeys("Fridge");
log.info("Type in text field");
WebElement ee = driver.findElement(By.id("baloonmodel"));
ee.click();
log.info("Category status select from dropdown");
List<WebElement> elements = ee.findElements(By.className("ui-select-choices-row-inner"));
for (WebElement element : elements) {
if (element.findElement(By.tagName("span")).getText().equals("InActive")) {
element.click();
test.setStatus("PASS");
System.out.println("VALUE IS MATCHED");
test.setErrormsg("Value is matched");
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
//Select UOM dropdown
public static TestStatus SELECT_UOM(String path, String value, String actualvalue) {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
WebElement ee = driver.findElement(By.xpath(path));
ee.click();
log.info("Click on UOM ");
List<WebElement> elements = ee.findElements(By.className("ui-select-choices-row-inner"));
for (WebElement element : elements) {
if (element.findElement(By.tagName("span")).getText().equals(value)) {
System.out.println(element);
element.click();
log.info("Selected uom is"+value);
test.setStatus("PASS");
System.out.println("VALUE IS MATCHED");
test.setErrormsg("Value is matched");
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
// product_save function
public static TestStatus PRODUCT_SAVE(String[] actualValue) throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div[2]/div/div/div/div/div/div/div[2]/div/div/div/div/div/button"))
.click();
log.info("click on product save button");
for (String errorMsg : actualValue) {
boolean alertMessage = driver.getPageSource().contains(errorMsg);
System.out.println(alertMessage);
if (alertMessage) {
test.setStatus("PASS");
test.setErrormsg(errorMsg);
log.info(errorMsg);
return test;
} else {
test.setStatus("FAIL");
test.setErrormsg("Mandatory field required");
log.error("Mandatory field required");
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
// View product
public static TestStatus VIEW_PRODUCT(String value, String actualvalue) {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try {
int Row_count = driver
.findElements(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div[2]/div/div/div/div/div/div/div[1]/div/div/div[1]/table/tbody/tr/td[1]"))
.size();
System.out.println("Number Of Rows = " + Row_count);
log.info("Product Number Of Rows = " + Row_count);
int Col_count = driver
.findElements(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div[2]/div/div/div/div/div/div/div[1]/div/div/div[1]/table/tbody/tr[1]/td"))
.size();
System.out.println("Number Of Columns = " + Col_count);
log.info("Product Number Of Rows = " + Col_count);
String first_part = "html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div[2]/div/div/div/div/div/div/div[1]/div/div/div[1]/table/tbody/tr[";
String second_part = "]";
String third_part = "/td[";
String fourth_part = "]";
String fifth_part = "/td[6]/a";
for (int i = 1; i <= Row_count; i++) {
for (int j = 1; j <= Col_count; j++) {
String final_xpath = first_part + i + second_part + third_part + j + fourth_part;
System.out.println(final_xpath);
String Table_data = driver.findElement(By.xpath(final_xpath)).getText();
System.out.println(Table_data + " ");
// Thread.sleep(500);
if (Table_data.equals(value)) {
System.out.println("Value is Match:" + value);
WebElement actionCell = driver.findElement(By.xpath(first_part + i + second_part + fifth_part));
System.out.println(actionCell);
actionCell.click();
log.info("View the product"+value);
test.setErrormsg("success");
return test;
}
}
}
} catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
return test;
}
return test;
}
// Product_update function
public static TestStatus PRODUCT_UPDATE(String[] actualValue) throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div[2]/div/div/div/div/div/div/div[3]/div/div/div/div/div/button"))
.click();
for (String errorMsg : actualValue) {
boolean alertMessage = driver.getPageSource().contains(errorMsg);
System.out.println(alertMessage);
if (alertMessage) {
test.setStatus("PASS");
test.setErrormsg(errorMsg);
log.info(errorMsg);
return test;
} else {
test.setStatus("FAIL");
test.setErrormsg("Mandatory field required");
log.error("Mandatory field required");
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
//Ledger groups select function
public static TestStatus LEDGER_CREATE_DROPDOWN(String path, String value, String actualvalue) {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
WebElement ee = driver.findElement(By.xpath(path));
ee.click();
log.info("Click on dropdown");
List<WebElement> elements = driver.findElements(By.className("ui-select-choices-row-inner"));
for (WebElement element : elements) {
if (element.findElement(By.tagName("span")).getText().equals(value)) {
System.out.println(element);
element.click();
test.setStatus("PASS");
log.info("Selected name is"+value);
System.out.println("VALUE IS MATCHED");
test.setErrormsg("Value is matched");
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
//Ledger save function
public static TestStatus LEDGER_ADD_SAVE(String[] actualValue) throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div[2]/div/div/div/div/div/div/div[2]/div/div/div/div/div/form/div[2]/button")).click();
log.info("Click on ledger save button");
for (String errorMsg : actualValue) {
boolean alertMessage = driver.getPageSource().contains(errorMsg);
System.out.println(alertMessage);
if (alertMessage) {
test.setStatus("PASS");
test.setErrormsg(errorMsg);
log.info(errorMsg);
return test;
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
//Ledger save function
public static TestStatus LEDGER_EDIT_SAVE(String[] actualValue) throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div[2]/div/div/div/div/div/div/div[3]/div/div/div/div/div/form/div[2]/button")).click();
log.info("Click on ledger save button");
for (String errorMsg : actualValue) {
boolean alertMessage = driver.getPageSource().contains(errorMsg);
System.out.println(alertMessage);
if (alertMessage) {
test.setStatus("PASS");
test.setErrormsg(errorMsg);
log.info(errorMsg);
return test;
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
//View ledger function
public static TestStatus VIEW_LEDGER(String value, String actualvalue) {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try {
int Row_count = driver
.findElements(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div[2]/div/div/div/div/div/div/div[1]/div/div/div[1]/table/tbody/tr/td[1]"))
.size();
System.out.println("Number Of Rows = " + Row_count);
int Col_count = driver
.findElements(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div[2]/div/div/div/div/div/div/div[1]/div/div/div[1]/table/tbody/tr[1]/td"))
.size();
System.out.println("Number Of Columns = " + Col_count);
String first_part = "html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div[2]/div/div/div/div/div/div/div[1]/div/div/div[1]/table/tbody/tr[";
String second_part = "]";
String third_part = "/td[";
String fourth_part = "]";
String fifth_part = "/td[5]/a";
for (int i = 1; i <= Row_count; i++) {
for (int j = 1; j <= Col_count; j++) {
String final_xpath = first_part + i + second_part + third_part + j + fourth_part;
System.out.println(final_xpath);
String Table_data = driver.findElement(By.xpath(final_xpath)).getText();
System.out.println(Table_data + " ");
// Thread.sleep(500);
if (Table_data.equals(value)) {
System.out.println("Value is Match:" + value);
WebElement actionCell = driver.findElement(By.xpath(first_part + i + second_part + fifth_part));
System.out.println(actionCell);
test.setStatus("PASS");
actionCell.click();
log.info("View the ledger:"+value);
test.setErrormsg("success");
return test;
}
}
}
} catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
return test;
}
return test;
}
// Give to date and Pick calendar
// Pass parameter set date, forward button xpath, reverse button xpath,
// dayofmonth xpath
public static TestStatus WEB_PICDATE(String fwdbutton, String revbutton, String dayofmonth, String value)
throws InterruptedException {
TestStatus test = new TestStatus();
test.setStatus("PASS");
if (fwdbutton.isEmpty() || revbutton.isEmpty() || dayofmonth.isEmpty()) {
// System.out.println("The parameter passed is blank");
test.setStatus("FAIL");
test.setErrormsg("PARAMETER IS EMPTY");
log.error("Parameter is empty");
return test;
} else {
try {
String dateToSet = value;
LocalDate currentDate = LocalDate.now();
LocalDate targetDate = LocalDate.parse(dateToSet, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
int dayofMonth = targetDate.getDayOfMonth();
currentDate = currentDate.with(TemporalAdjusters.firstDayOfMonth());
targetDate = targetDate.with(TemporalAdjusters.firstDayOfMonth());
if (targetDate.isAfter(currentDate))
{
// Forward condition
Period p = Period.between(currentDate, targetDate);
System.out.println("years : " + p.getYears());
System.out.println("MOnths: " + p.getMonths());
jumMonthBy = p.getYears() * 12 + p.getMonths();
}
else if (currentDate.isAfter(targetDate)) {
// Backward condition
Period p = Period.between(targetDate, currentDate);
System.out.println("years : " + p.getYears());
System.out.println(" Months: " + p.getMonths());
jumMonthBy = p.getYears() * 12 + p.getMonths();
increment = false;
} else {
jumMonthBy = 1;
}
// increment=true :Move to calendar Forward button (Based on
// jumpmonth)
for (int i = 0; i < jumMonthBy; i++) {
if (increment) {
driver.findElement(By.xpath(fwdbutton)).click();
}
// increment=false :Move to calendar back button (Based on
// jumpmonth)
else {
driver.findElement(By.xpath(revbutton)).click();
}
Thread.sleep(1000);
}
System.out.println(dayofMonth);
List<WebElement> allDates = driver.findElements(By.xpath(dayofmonth));
for (WebElement ele : allDates) {
String date = ele.getText();
if (!ele.getAttribute("class").equals("old day")
&& date.equalsIgnoreCase(dateToSet.split("-")[0].replaceFirst("^0", ""))) {
System.out.println(date);
ele.click();
test.setStatus("PASS");
test.setErrormsg("DATE SELECTED");
log.info("Date selected");
return test;
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
}
return test;
}
//Invoice delete function
public static TestStatus INVOICE_DELETE(String value, String actualvalue) {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try {
int Row_count = driver
.findElements(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div/div/form/div[4]/div[1]/table/tbody/tr/td[1]"))
.size();
System.out.println("Number Of Rows = " + Row_count);
log.info("Number Of Rows = " + Row_count);
int Col_count = driver
.findElements(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div/div/form/div[4]/div[1]/table/tbody/tr[1]/td"))
.size();
System.out.println("Number Of Columns = " + Col_count);
log.info("Number Of Colums = " + Col_count);
String first_part = "html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div/div/form/div[4]/div[1]/table/tbody/tr[";
String second_part = "]";
String third_part = "/td[";
String fourth_part = "]";
String fifth_part = "/td[7]/div/button";
for (int i = 1; i <= Row_count; i++) {
for (int j = 1; j <= Col_count; j++) {
String final_xpath = first_part + i + second_part + third_part + j + fourth_part;
System.out.println(final_xpath);
String Table_data = driver.findElement(By.xpath(final_xpath)).getText();
System.out.println(Table_data + " ");
if (Table_data.equals(value)) {
System.out.println("Value is Match:" + value);
WebElement actionCell = driver.findElement(By.xpath(first_part + i + second_part + fifth_part));
System.out.println(actionCell);
actionCell.click();
log.info("Invoice deleted row is"+value);
String totalvalue = driver
.findElement(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div/div/form/div[4]/div[4]/div"))
.getText();
System.out.println(totalvalue);
test.setStatus("PASS");
test.setErrormsg("success");
test.setElement(totalvalue);
log.info("Invoce totalvalue="+totalvalue);
return test;
}
}
}
} catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
//Add new product row
public static TestStatus AddNEW_PRODUCT_ROW() throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(
By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div/div/form/div[4]/div[2]/button")).click();
test.setStatus("PASS");
log.info("Added in new product row");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
}
return test;
}
//Invoice full screen mode
public static TestStatus INVOICE_FULLSCREENMODE() throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(
By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div/div/form/div[2]/div[1]/div[2]/a"))
.click();
log.info("View invoice fullscreen mode");
test.setStatus("PASS");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
}
return test;
}
//Invoice cancel
public static TestStatus INVOICE_CANCEL() {
// TODO Auto-generated method stub
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(
By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[1]/div/div/form/div[2]/div[1]/div[3]/a"))
.click();
test.setStatus("PASS");
log.info("Invoice cancelled");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
}
return test;
}
// View the invoice
public static TestStatus VIEW_INVOICE(String value) {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try {
int Row_count = driver
.findElements(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div[3]/div[2]/div[1]/table/tbody/tr/td[1]"))
.size();
System.out.println("Number Of Rows = " + Row_count);
log.info("Number Of Rows = " + Row_count);
int Col_count = driver
.findElements(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div[3]/div[2]/div[1]/table/tbody/tr[1]/td"))
.size();
System.out.println("Number Of Columns = " + Col_count);
log.info("Number Of Columns = " + Col_count);
String first_part = "html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div[3]/div[2]/div[1]/table/tbody/tr[";
String second_part = "]";
String third_part = "/td[";
String fourth_part = "]";
String fifth_part = "/td[8]/a";
for (int i = 1; i <= Row_count; i++) {
for (int j = 1; j <= Col_count; j++) {
String final_xpath = first_part + i + second_part + third_part + j + fourth_part;
System.out.println(final_xpath);
String Table_data = driver.findElement(By.xpath(final_xpath)).getText();
System.out.println(Table_data + " ");
if (Table_data.equals(value)) {
System.out.println("Value is Match:" + value);
WebElement actionCell = driver.findElement(By.xpath(first_part + i + second_part + fifth_part));
System.out.println(actionCell);
// WebElement actionCell =
// driver.findElement(By.cssSelector("a[class='btn
// btn-xs btn-success view-btn']"));
actionCell.click();
String totalvalue = driver
.findElement(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div/div[3]/div/div[2]/div/div[1]/div/div/div/div[1]/div/div[2]/table/tbody/tr[1]/td[2]"))
.getText();
System.out.println(totalvalue);
test.setStatus("PASS");
log.info("View the invoice"+value);
test.setErrormsg("success");
test.setElement(totalvalue);
return test;
}
}
}
} catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
test.setErrormsg(e.getMessage());
log.error(e.getMessage());
return test;
}
return test;
}
//Receipt name select
public static TestStatus RECIEPT_NAME_SELECT(String value) {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try {
WebElement ee = driver.findElement(By.id("receiptTo"));
ee.click();
log.info("Click on recieptname dropdown");
List<WebElement> elements = ee.findElements(By.className("ui-select-choices-row-inner"));
for (WebElement element : elements) {
if (element.findElement(By.tagName("span")).getText().equals(value)) {
element.click();
log.info("Receipt name selected:"+value);
test.setStatus("PASS");
test.setErrormsg("VALUE IS MATCHED");
System.out.println("VALUE IS MATCHED");
break;
} else {
System.out.println("VALUE NOT MATCHED");
test.setStatus("FAIL");
log.error("Value not matched:"+value);
test.setErrormsg("VALUE NOT MATCHED");
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.info(e.getMessage());
test.setErrormsg(e.getMessage());
return test;
}
return test;
}
//Select Reciept mode
public static TestStatus RECEIPT_MODE() {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try {
WebElement ee = driver.findElement(By.id("receiptMode"));
ee.click();
log.info("Click on receipt mode");
List<WebElement> elements = ee.findElements(By.className("ui-select-choices-row-inner"));
for (WebElement element : elements) {
if (element.findElement(By.tagName("span")).getText().equals("Cash In Hand")) {
element.click();
log.info("Receipt mode selected");
test.setStatus("PASS");
test.setErrormsg("VALUE IS MATCHED");
System.out.println("VALUE IS MATCHED");
break;
} else {
System.out.println("VALUE NOT MATCHED");
test.setStatus("FAIL");
log.error("Value not matched");
test.setErrormsg("VALUE NOT MATCHED");
}
}
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
return test;
}
return test;
}
// Receipt_Save function
public static TestStatus RECIEPT_SAVE(String[] actualValue) throws AWTException {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
String payment = driver
.findElement(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div[3]/form/div[2]/div[2]/div[2]/div[2]/div"))
.getText();
System.out.println(payment);
test.setElement(payment);
String balancevalue = driver
.findElement(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div[3]/form/div[2]/div[2]/div[1]/div/table/tbody/tr[1]/td[6]/p"))
.getText();
System.out.println(balancevalue);
log.info(balancevalue);
driver.findElement(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div[3]/form/div[1]/div[1]/div[3]/button"))
.click();
log.info("Click on receipt save button");
for (String errorMsg : actualValue) {
boolean alertMessage = driver.getPageSource().contains(errorMsg);
System.out.println(alertMessage);
if (alertMessage) {
test.setStatus("FAIL");
log.error(errorMsg);
test.setErrormsg(errorMsg);
return test;
}
}
test.setStatus("PASS");
test.setErrormsg("Reciept created successfully");
log.info("Reciept created successfully");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
}
return test;
}
//Receipt add row
public static TestStatus RECEIPT_ADDROW() throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(By
.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div[3]/form/div[2]/div[2]/div[1]/div/div/button"))
.click();
log.info("add receipt row");
test.setStatus("PASS");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
}
return test;
}
//Receipt fullscreen mode
public static TestStatus RECEIPT_FULLSCREENMODE() throws Exception {
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(
By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div[3]/form/div[1]/div[1]/div[2]/a"))
.click();
test.setStatus("PASS");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
}
return test;
}
//Receipt cancelled
public static TestStatus RECEIPT_CANCEL() {
// TODO Auto-generated method stub
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
driver.findElement(
By.xpath("html/body/div[4]/div[1]/div[2]/div[1]/div/div[2]/div/div[3]/form/div[1]/div[1]/div[4]/a"))
.click();
log.info("Click reciept cancel button");
test.setStatus("PASS");
return test;
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
}
return test;
}
//Page_up function
public static TestStatus PAGE_UP() {
// TODO Auto-generated method stub
TestStatus test = new TestStatus();
test.setStatus("PASS");
try{
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PAGE_UP);
robot.keyRelease(KeyEvent.VK_PAGE_UP);
test.setStatus("PASS");
log.info("Page up");
test.setStatus_message("System scroll pageup");
}
catch (Exception e) {
e.printStackTrace();
test.setStatus("FAIL");
log.error(e.getMessage());
test.setErrormsg(e.getMessage());
}
return test;
}
}
|
package com.mmc.design.pattern.factory.demo1;
import com.mmc.design.pattern.factory.Service;
/**
* @packageName:com.mmc.design.pattern.factory.demo1
* @desrciption:
* @author: gaowei
* @date: 2018-10-23 17:18
* @history: (version) author date desc
*/
public class ServiceImpl1 implements Service {
@Override
public void method1() {
System.out.println("serviceImpl1.mehtod1()");
}
@Override
public void method2() {
System.out.println("serviceImpl1.mehtod2()");
}
}
|
package cn.edu.nju.software.timemachine.action.user;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import cn.edu.nju.software.timemachine.action.BaseAction;
import cn.edu.nju.software.timemachine.entity.User;
import cn.edu.nju.software.timemachine.service.IUserService;
@Controller
@Scope("prototype")
public class LoginAction extends BaseAction{
private static final long serialVersionUID = 1L;
private User user;
private String json;
@Autowired
private IUserService<User> userService;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public IUserService<User> getUserService() {
return userService;
}
public void setUserService(IUserService<User> userService) {
this.userService = userService;
}
public String getJson() {
return json;
}
public void setJson(String json) {
this.json = json;
}
public void login() throws Exception{
JSONObject jsonObject = new JSONObject(json);
System.out.println(json);
String email = jsonObject.getString("loginName");
String password = jsonObject.getString("password");
User _user = userService.getUser(email, password);
if(_user != null){
session.put("id", _user.getId());
json = "{\"msg\":\"1\"}";
}else{
json = "{\"msg\":\"2\"}";
}
sendMsg(json);
}
}
|
package ariel.manndrops.game.model;
import java.util.Set;
public class GameModel {
private static GameModel gameModel;
private String name = "";
private int score = 0;
private int exercisesSolved = 0;
private int errors = 0;
private int lives = 3;
private GameModel(){
}
public static GameModel getInstance() {
if(gameModel == null){
gameModel = new GameModel();
}
return gameModel;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public int getExercisesSolved() {
return exercisesSolved;
}
public int getErrors() {
return errors;
}
public int getLives() {
return lives;
}
}
|
package test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import FourRowSolitaire.Card;
import FourRowSolitaire.CardStack;
import FourRowSolitaire.DealDeck;
import FourRowSolitaire.Deck;
import FourRowSolitaire.DiscardPile;
public class DiscardPileTest {
@Test
public void testAddStack() {
DiscardPile pile = new DiscardPile(3);
CardStack stack = new CardStack();
stack.push(new Card(Card.CLUBS_SUIT, 1, 1, 1));
stack.push(new Card(Card.DIAMONDS_SUIT, 2, 1, 1));
pile.addStack(stack);
assertEquals(2, pile.length());
}
@Test
public void testIsValidMove() {
DiscardPile pile = new DiscardPile(1);
Deck deck = new Deck(1);
Card cardOne = deck.getDeck().removeFirst();
CardStack stack = new CardStack();
DealDeck dealDeck = new DealDeck(pile, 1);
dealDeck.setDeck(deck.getDeck());
Card cardTwo = deck.getDeck().removeFirst();
assertFalse(pile.isValidMove(stack));
assertFalse(pile.isValidMove(cardOne));
assertTrue(pile.isValidMove(dealDeck.peek()));
}
}
|
package br.com.wasys.library.jackson;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Date;
import br.com.wasys.library.utils.DateUtils;
public class JsonDateSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator generator, SerializerProvider serializers) throws IOException, JsonProcessingException {
if (value == null) {
generator.writeNull();
}
else {
generator.writeString(DateUtils.format(value));
}
}
}
|
/*
* Lesson 4 Coding Activity Question 2
*
* Ask the user their name and age and print out how many years until
* they are 100. Note that age should be an integer, not a double.
*
* Sample run:
Hi there. What is your name?
Pascal
Hi Pascal. How old are you?
16
Pascal, you will be 100 in 84 years.
*/
import java.util.Scanner;
class Lesson_4_Activity_Two {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String name;
int age;
System.out.println("Hi there. What is your name?");
name = input.nextLine();
System.out.println(String.format("Hi %s. How old are you?", name));
age = input.nextInt();
if (age > 100 || age < 0)
{
input.close();
throw new RuntimeException("That's not how any of this works.");
}
System.out.println(String.format("%s, you will be 100 in %d years.", name, 100 - age));
input.close();
}
}
|
package com.neu.spring;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.neu.spring.pojo.StockEvent;
import com.neu.spring.pojo.UserAccount;
public class StockEventValidator implements Validator {
public boolean supports(Class aClass)
{
return aClass.equals(StockEvent.class);
}
public void validate(Object obj, Errors errors)
{
StockEvent stockEvent = (StockEvent) obj;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "stockId", "error.invalid.stockId", "stockId Required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "date", "error.invalid.date", "date Required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "eventDescription", "error.invalid.eventDescription", "eventDescription Required");
}
}
|
package com.onightperson.hearken.notify;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.onightperson.hearken.R;
/**
* Created by liubaozhu on 17/6/13.
*/
public class NotificationActivity extends Activity implements View.OnClickListener {
private static final String TAG = "NotificationActivity";
private Button mSendNormalNotiBtn;
private Button mSendCustomNotiBtn;
private Button mSendNormalNoti2Btn;
private Button mSendBigNotiBtn;
private Button mSendMutiBtnBtn;
private Button mSendNotifications;
private Button mStartListenerServiceBtn;
private Button mStartIntentServiceNotifyBtn;
private Button mStartReadPermBtn;
private Button mSendContinuousNotificationBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_layout);
initViews();
}
private void initViews() {
mSendNormalNotiBtn = (Button) findViewById(R.id.send_normal_notification);
mSendNormalNotiBtn.setOnClickListener(this);
mSendCustomNotiBtn = (Button) findViewById(R.id.send_custom_notification);
mSendCustomNotiBtn.setOnClickListener(this);
mSendNormalNoti2Btn = (Button) findViewById(R.id.send_normal_notification_2);
mSendNormalNoti2Btn.setOnClickListener(this);
mSendBigNotiBtn = (Button) findViewById(R.id.send_big_notification);
mSendBigNotiBtn.setOnClickListener(this);
mSendMutiBtnBtn = (Button) findViewById(R.id.send_muti_btn_notification);
mSendMutiBtnBtn.setOnClickListener(this);
mSendNotifications = (Button) findViewById(R.id.send_notifications);
mSendNotifications.setOnClickListener(this);
mStartListenerServiceBtn = (Button) findViewById(R.id.start_listener_service);
mStartListenerServiceBtn.setOnClickListener(this);
mStartIntentServiceNotifyBtn = (Button) findViewById(R.id.start_intent_service_notification);
mStartIntentServiceNotifyBtn.setOnClickListener(this);
mStartReadPermBtn = (Button) findViewById(R.id.start_read_perm_activity);
mStartReadPermBtn.setOnClickListener(this);
mSendContinuousNotificationBtn = (Button) findViewById(R.id.post_continuous_notifications);
mSendContinuousNotificationBtn.setOnClickListener(this);
// 查看版本
Log.i(TAG, "initViews: sdk_version: " + Build.VERSION.SDK_INT);
}
@Override
public void onClick(View v) {
if (v == mSendNormalNotiBtn) {
NotificationMgr.getInstance(this).sendAlarmNotification();
} else if (v == mSendCustomNotiBtn) {
NotificationMgr.getInstance(this).sendCustomNotification();
} else if (v == mSendNormalNoti2Btn) {
NotificationMgr.getInstance(this).sendNormalNotification();
} else if (v == mSendBigNotiBtn) {
NotificationMgr.getInstance(this).sendBigContentViewNotification();
} else if (v == mSendMutiBtnBtn) {
NotificationMgr.getInstance(this).sendMutiBtnNotification();
} else if (v == mStartListenerServiceBtn) {
Intent intent = new Intent(this, MyNotificationListenerService.class);
intent.setAction("com.zhuzi.start.service.action");
startService(intent);
} else if (v == mStartIntentServiceNotifyBtn) {
NotificationMgr.getInstance(this).sendStartServiceNotification();
} else if (v == mStartReadPermBtn) {
// Intent intent = new Intent(this, ParseNotificationActivity.class);
// startActivity(intent);
} else if (v == mSendNotifications) {
NotificationMgr.getInstance(this).sendNotificationsOneByOne();
Object test = null;
Log.i(TAG, "onClick: test: " + test);
} else if (v == mSendContinuousNotificationBtn) {
Log.i(TAG, "onClick: mSendContinuousNotificationBtn");
NotificationMgr.getInstance(this).sendContinuousNotifications();
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.fatecpg.quiz;
import java.util.ArrayList;
/**
*
* @author MohamadTarif
*/
public class DbConta {
private static ArrayList<Conta> contas;
public static ArrayList<Conta> getContas(){
if(contas==null){
contas = new ArrayList<>();
Conta c1 = new Conta();
c1.setUsuario("usuario12");
contas.add(c1);
}
return contas;
}
}
|
package problem;
import simulator.*;
import java.io.IOException;
import java.util.*;
public class MCTS {
private ProblemSpec ps;
private Helper helper;
private Map<Terrain, Object[]> terrain2spec;
public MCTS(ProblemSpec ps) {
this.ps = ps;
this.helper = new Helper();
this.terrain2spec = helper.getBestSpecification();
}
// Define 3 grame state: win, lose, running
public enum GameState {
WIN,
LOSE,
RUNNING
}
// Define the state node data structure of the Monte Carlo Search Tree,
// If all the action are deterministic, we would use a HashMap<Action, StateNode> to store all the actions and
// their corresponding next state. However, the action MOVE is indeterministic (may move -4..5 cells), which
// means that the action MOVE has more than one possible next states. It contradicts with HashMap since the
// key-value pair is one-to-one. (In this case, key(MOVE) corresponds to at most 12 values (possible next states).
// Therefore, We defined two kinds of nodes: ActionNode and StateNode.
// They appear in the Monte Carlo Search Tree in an interleaving manner. That is, the first level are all state nodes,
// then the second level are all action nodes, the third level are all state nodes...
//
// Each state node maintains a HashMap<Action, ActionNode> to store all the possible action and its corresponding action nodes.
// In this case, action MOVE only corresponds to a single ActionNode, all the possible outcomes are stored as the children of
// the state node.
//
// Each action node maintains a HashMap<StateTuple, StateNode> to store all the possible state tuples and its corresponding state nodes.
class StateNode {
private StateTuple stateTuple; // stores state and whether the state are recovered from Slip or Breakdown
private HashMap<Action, ActionNode> map; // store all the possible actions and their corresponding action nodes
private ActionNode parent; // which action lead to current state
// What is current timestep, it will be used in the Simulation (roll-out) phase of MCTS.
// Suppose MAXT=30 and current timestep is 20.
// During Simulation, if it doesn't win in (30-20=10) steps, the simulation fails.
// If we don't store current timestep, we don't how many steps are available in the Simulation phase.
private int timestep;
private int visit; // how many time this node has been visited
private int reward; // what is the reward of this node
public int getVisit() {
return visit;
}
public StateTuple getStateTuple() {
return stateTuple;
}
public HashMap<Action, ActionNode> getMap() {
return map;
}
public ActionNode getParent() {
return parent;
}
public int getTimestep() {
return timestep;
}
public StateNode(StateTuple stateTuple, ActionNode parent, int timestep) {
this.stateTuple = stateTuple;
this.map = new HashMap<>();
this.parent = parent;
this.visit = 0;
this.reward = 0;
this.timestep = timestep;
}
public double getRatio() {
return (double) reward / visit;
}
public void increaseVisit() {
this.visit++;
}
public void increaseReward(double result) {
this.reward += result;
}
public GameState getGameState() {
// Reached the goal
if (this.stateTuple.state.getPos() >= ps.getN()) {
return GameState.WIN;
} else if (this.timestep >= ps.getMaxT()) {
// Time out
return GameState.LOSE;
} else {
// Otherwise the game is still running
return GameState.RUNNING;
}
}
public int getReward() {
return reward;
}
}
class ActionNode {
private Action action;
private HashMap<StateTuple, StateNode> map;
private StateNode parent;
private double reward;
private int visit;
public Action getAction() {
return this.action;
}
public HashMap<StateTuple, StateNode> getMap() {
return map;
}
public StateNode getParent() {
return parent;
}
public double getReward() {
return reward;
}
public int getVisit() {
return visit;
}
public ActionNode(Action action, StateNode parent) {
this.action = action;
this.map = new HashMap<>();
this.parent = parent;
this.visit = 0;
}
public double getRatio() {
return reward / this.visit;
}
public void increaseReward(double result) {
this.reward += result;
}
public void increaseVisit() {
this.visit++;
}
@Override
public String toString() {
return "ActionNode{" +
"action=" + action +
", visit=" + visit +
", ratio=" + getRatio() +
'}';
}
}
class Helper {
// Given current state, return the fuel consumption by action MOVE,
// copied from support code
public int getFuelConsumption(State currentState) {
// get parameters of current state
Terrain terrain = ps.getEnvironmentMap()[currentState.getPos() - 1];
String car = currentState.getCarType();
TirePressure pressure = currentState.getTirePressure();
// get fuel consumption
int terrainIndex = ps.getTerrainIndex(terrain);
int carIndex = ps.getCarIndex(car);
int fuelConsumption = ps.getFuelUsage()[terrainIndex][carIndex];
if (pressure == TirePressure.FIFTY_PERCENT) {
fuelConsumption *= 3;
} else if (pressure == TirePressure.SEVENTY_FIVE_PERCENT) {
fuelConsumption *= 2;
}
return fuelConsumption;
}
// Given problemSpec and current state, return all possible actions in a set.
// For example, if the fuel is less than fuel consumption, action MOVE
// won't appear in possible actions.
// Problem: maybe too slow?
//
// : adding A7 and A8, the number of possible actions increased significantly,
// the probability of choosing the action MOVE is quite low.
//
// For example, suppose there are 25 possible actions, and MaxT=100.
//
// The (maximum) expectation of the number of MOVE chosen is 4.
// (if slip or breakdown occurs, we don't have 100 times to perform the action)
//
// If N>20, it is unlikely to reach the goal even every time we MOVE 5 cells.
public Set<Action> getAllPossibleActions(ProblemSpec ps, StateTuple stateTuple) {
State currentState = stateTuple.state;
Set<Action> actions = new HashSet<>();
// A1. Continue Moving
if (currentState.getFuel() > getFuelConsumption(currentState)) {
if (currentState.getFuel() >= getFuelConsumption(currentState)) {
actions.add(new Action(ActionType.MOVE));
}
}
if (ps.getLevel().getLevelNumber() <= 3) {
// A2. Change the car type
for (String carType : ps.getCarOrder()) {
if (!carType.equals(currentState.getCarType())) {
actions.add(new Action(ActionType.CHANGE_CAR, carType));
}
}
// A3. Change the driver
for (String driver : ps.getDriverOrder()) {
if (!driver.equals(currentState.getDriver())) {
actions.add(new Action(ActionType.CHANGE_DRIVER, driver));
}
}
// A4. Change the tire(s) of existing car
for (Tire tire : ps.getTireOrder()) {
if (!tire.equals(currentState.getTireModel())) {
actions.add(new Action(ActionType.CHANGE_TIRES, tire));
}
}
// Only support level 1
if (ps.getLevel().getLevelNumber() == 1) {
return actions;
}
// A5. Add fuel to existing car
actions.add(new Action(ActionType.ADD_FUEL, 10));
// A6. Change pressure to the tires
actions.add(new Action(ActionType.CHANGE_PRESSURE, TirePressure.FIFTY_PERCENT));
actions.add(new Action(ActionType.CHANGE_PRESSURE, TirePressure.SEVENTY_FIVE_PERCENT));
actions.add(new Action(ActionType.CHANGE_PRESSURE, TirePressure.ONE_HUNDRED_PERCENT));
actions.remove(new Action(ActionType.CHANGE_PRESSURE, currentState.getTirePressure()));
// Only support level 2 & 3
} else if (ps.getLevel().getLevelNumber() == 4) {
// level 4
// A7. Combination of options A2 and A3.
for (String carType : ps.getCarOrder()) {
for (String driverType : ps.getDriverOrder()) {
actions.add(new Action(ActionType.CHANGE_CAR_AND_DRIVER, carType, driverType));
}
}
actions.remove(new Action(ActionType.CHANGE_CAR_AND_DRIVER, currentState.getCarType(), currentState.getDriver()));
// A4. Change the tire(s) of existing car
for (Tire tire : ps.getTireOrder()) {
if (!tire.equals(currentState.getTireModel())) {
actions.add(new Action(ActionType.CHANGE_TIRES, tire));
}
}
// A5. Add fuel to existing car
actions.add(new Action(ActionType.ADD_FUEL, 10));
// A6. Change pressure to the tires
actions.add(new Action(ActionType.CHANGE_PRESSURE, TirePressure.FIFTY_PERCENT));
actions.add(new Action(ActionType.CHANGE_PRESSURE, TirePressure.SEVENTY_FIVE_PERCENT));
actions.add(new Action(ActionType.CHANGE_PRESSURE, TirePressure.ONE_HUNDRED_PERCENT));
actions.remove(new Action(ActionType.CHANGE_PRESSURE, currentState.getTirePressure()));
} else {
// level 5
// A7. Combination of options A2 and A3.
for (String carType : ps.getCarOrder()) {
for (String driverType : ps.getDriverOrder()) {
actions.add(new Action(ActionType.CHANGE_CAR_AND_DRIVER, carType, driverType));
}
}
actions.remove(new Action(ActionType.CHANGE_CAR_AND_DRIVER, currentState.getCarType(), currentState.getDriver()));
for (Tire tire : ps.getTireOrder()) {
actions.add(new Action(ActionType.CHANGE_TIRE_FUEL_PRESSURE, tire, 0, TirePressure.FIFTY_PERCENT));
actions.add(new Action(ActionType.CHANGE_TIRE_FUEL_PRESSURE, tire, 0, TirePressure.SEVENTY_FIVE_PERCENT));
actions.add(new Action(ActionType.CHANGE_TIRE_FUEL_PRESSURE, tire, 0, TirePressure.ONE_HUNDRED_PERCENT));
actions.add(new Action(ActionType.CHANGE_TIRE_FUEL_PRESSURE, tire, 10, TirePressure.FIFTY_PERCENT));
actions.add(new Action(ActionType.CHANGE_TIRE_FUEL_PRESSURE, tire, 10, TirePressure.SEVENTY_FIVE_PERCENT));
actions.add(new Action(ActionType.CHANGE_TIRE_FUEL_PRESSURE, tire, 10, TirePressure.ONE_HUNDRED_PERCENT));
}
actions.remove(new Action(ActionType.CHANGE_TIRE_FUEL_PRESSURE, currentState.getTireModel(), 0, currentState.getTirePressure()));
}
return actions;
}
public int getNumPossibleActions(StateTuple stateTuple) {
int rt;
int numCar = ps.getCT();
int numDriver = ps.getDT();
if (ps.getLevel().getLevelNumber() == 1) {
rt = 1 + numCar + numDriver + 4;
rt -= 3;
} else if (ps.getLevel().getLevelNumber() == 2 || ps.getLevel().getLevelNumber() == 3) {
rt = 1 + numCar + numDriver + 4 + 1 + 3;
rt -= 4;
} else if (ps.getLevel().getLevelNumber() == 4) {
rt = 1 + 4 + 1 + 3 + numCar * numDriver;
rt -= 3;
} else {
rt = 1 + numCar * numDriver + 4 * 3;
rt -= 2;
}
int consumption = getFuelConsumption(stateTuple.state);
if (stateTuple.state.getFuel() < consumption) {
rt--;
}
return rt;
}
// Given the ProblemSpec and current stateTuple, first generate all the possible actions set,
// then randomly pick one action (random policy in roll-out phase).
// Might have some problem:
// level 1: 1+2+2+4=9 N<=10 MaxT=30
// level 2: 1+3+2+4+1+3=14 N<=10 MaxT=30
// level 3: 1+3+2+4+1+3=14 N<=30 MaxT=90
// level 4: 1+0+0+4+1+3+25=34 N<=30 MaxT=90
// level 5: 1+0+0+0+0+0+25+12=38 N<=30 MaxT=90
public Action selectRandomAction(ProblemSpec ps, StateTuple stateTuple) {
Set<Action> actions = getAllPossibleActions(ps, stateTuple);
Random random = new Random();
int index = random.nextInt(actions.size());
Iterator<Action> iter = actions.iterator();
for (int i = 0; i < index; i++) {
iter.next();
}
return iter.next();
}
private Action balancedSelectRandomAction(ProblemSpec ps, StateTuple stateTuple) {
int fuel;
String car, driver;
Tire tire;
TirePressure pressure;
List<ActionType> validActionTypes = ps.getLevel().getAvailableActions();
List<TirePressure> validPressures = new LinkedList<>();
validPressures.add(TirePressure.FIFTY_PERCENT);
validPressures.add(TirePressure.SEVENTY_FIVE_PERCENT);
validPressures.add(TirePressure.ONE_HUNDRED_PERCENT);
int numActions = validActionTypes.size();
int CT = ps.getCT();
int DT = ps.getDT();
int TiT = ProblemSpec.NUM_TYRE_MODELS;
int PressureT = ProblemSpec.TIRE_PRESSURE_LEVELS;
ActionType actionType = validActionTypes.get(aRandomInt(0, numActions));
Action action = null;
boolean success = false;
while (!success) {
State currentState = stateTuple.state;
switch (actionType.getActionNo()) {
case 1:
int currentFuel = currentState.getFuel();
if (currentFuel > getFuelConsumption(currentState)) {
action = new Action(actionType);
success = true;
} else {
actionType = validActionTypes.get(aRandomInt(0, numActions));
}
break;
case 2:
car = ps.getCarOrder().get(aRandomInt(0, CT));
while (car.equals(currentState.getCarType())) {
car = ps.getCarOrder().get(aRandomInt(0, CT));
}
action = new Action(actionType, car);
success = true;
break;
case 3:
driver = ps.getDriverOrder().get(aRandomInt(0, DT));
while (driver.equals(currentState.getCarType())) {
driver = ps.getDriverOrder().get(aRandomInt(0, DT));
}
action = new Action(actionType, driver);
success = true;
break;
case 4:
tire = ps.getTireOrder().get(aRandomInt(0, TiT));
while (tire.equals(currentState.getTireModel())) {
tire = ps.getTireOrder().get(aRandomInt(0, TiT));
}
action = new Action(actionType, tire);
success = true;
break;
case 5:
fuel = 10;
action = new Action(actionType, fuel);
success = true;
break;
case 6:
pressure = validPressures.get(aRandomInt(0, PressureT));
while (pressure.equals(currentState.getTirePressure())) {
pressure = validPressures.get(aRandomInt(0, PressureT));
}
action = new Action(actionType, pressure);
success = true;
break;
case 7:
car = ps.getCarOrder().get(aRandomInt(0, CT));
driver = ps.getDriverOrder().get(aRandomInt(0, DT));
action = new Action(actionType, car, driver);
break;
default:
tire = ps.getTireOrder().get(aRandomInt(0, TiT));
fuel = aRandomInt(ProblemSpec.FUEL_MIN, ProblemSpec.FUEL_MAX);
pressure = validPressures.get(aRandomInt(0, PressureT));
action = new Action(actionType, tire, fuel, pressure);
}
}
return action;
}
private int aRandomInt(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min)) + min;
}
// instead of using 0/1 reward, I customized the reward function
// If reached the goal, the reward is 1, multiplied by MaxT/timesteps (the less timesteps, the larger reward)
// If didn't reach the goal but moved forward, scale the reward to 0-1 proportional to the moved distance
// (the more distance moved forward, the larger reward)
// If moved backward, the reward is 0
public double calculateReward(int start, int end, int timesteps) {
double reward;
// WIN
if (end == ps.getN()) {
reward = 1.0 * ((double) ps.getMaxT() / timesteps);
} else if (end > start) {
// Failed but move forward
reward = (double) (end - start) / (ps.getN() - start);
} else {
reward = 0;
}
return reward;
}
// Copied from support code
private double[] getMoveProbs(Terrain terrain, String car, String driver, Tire tire, TirePressure pressure) {
// get parameters of current state
int terrainIndex = ps.getTerrainIndex(terrain);
// calculate priors
double priorK = 1.0 / ProblemSpec.CAR_MOVE_RANGE;
double priorCar = 1.0 / ps.getCT();
double priorDriver = 1.0 / ps.getDT();
double priorTire = 1.0 / ProblemSpec.NUM_TYRE_MODELS;
double priorTerrain = 1.0 / ps.getNT();
double priorPressure = 1.0 / ProblemSpec.TIRE_PRESSURE_LEVELS;
// get probabilities of k given parameter
double[] pKGivenCar = ps.getCarMoveProbability().get(car);
double[] pKGivenDriver = ps.getDriverMoveProbability().get(driver);
double[] pKGivenTire = ps.getTireModelMoveProbability().get(tire);
double pSlipGivenTerrain = ps.getSlipProbability()[terrainIndex];
double[] pKGivenPressureTerrain = convertSlipProbs(pSlipGivenTerrain, pressure);
// use bayes rule to get probability of parameter given k
double[] pCarGivenK = bayesRule(pKGivenCar, priorCar, priorK);
double[] pDriverGivenK = bayesRule(pKGivenDriver, priorDriver, priorK);
double[] pTireGivenK = bayesRule(pKGivenTire, priorTire, priorK);
double[] pPressureTerrainGivenK = bayesRule(pKGivenPressureTerrain,
(priorTerrain * priorPressure), priorK);
// use conditional probability formula on assignment sheet to get what
// we want (but what is it that we want....)
double[] kProbs = new double[ProblemSpec.CAR_MOVE_RANGE];
double kProbsSum = 0;
double kProb;
for (int k = 0; k < ProblemSpec.CAR_MOVE_RANGE; k++) {
kProb = magicFormula(pCarGivenK[k], pDriverGivenK[k],
pTireGivenK[k], pPressureTerrainGivenK[k], priorK);
kProbsSum += kProb;
kProbs[k] = kProb;
}
// Normalize
for (int k = 0; k < ProblemSpec.CAR_MOVE_RANGE; k++) {
kProbs[k] /= kProbsSum;
}
return kProbs;
}
// Copied from support code
private double[] convertSlipProbs(double slipProb, TirePressure pressure) {
// Adjust slip probability based on tire pressure
if (pressure == TirePressure.SEVENTY_FIVE_PERCENT) {
slipProb *= 2;
} else if (pressure == TirePressure.ONE_HUNDRED_PERCENT) {
slipProb *= 3;
}
// Make sure new probability is not above max
if (slipProb > ProblemSpec.MAX_SLIP_PROBABILITY) {
slipProb = ProblemSpec.MAX_SLIP_PROBABILITY;
}
// for each terrain, all other action probabilities are uniform over
// remaining probability
double[] kProbs = new double[ProblemSpec.CAR_MOVE_RANGE];
double leftOver = 1 - slipProb;
double otherProb = leftOver / (ProblemSpec.CAR_MOVE_RANGE - 1);
for (int i = 0; i < ProblemSpec.CAR_MOVE_RANGE; i++) {
if (i == ps.getIndexOfMove(ProblemSpec.SLIP)) {
kProbs[i] = slipProb;
} else {
kProbs[i] = otherProb;
}
}
return kProbs;
}
// Copied from support code
private double[] bayesRule(double[] condProb, double priorA, double priorB) {
double[] swappedProb = new double[condProb.length];
for (int i = 0; i < condProb.length; i++) {
swappedProb[i] = (condProb[i] * priorA) / priorB;
}
return swappedProb;
}
// Copied from support code
private double magicFormula(double pA, double pB, double pC, double pD,
double priorE) {
return pA * pB * pC * pD * priorE;
}
// Given certain terrain, return the best specification in that terrain
// return a [car, driver, tire, tire]
public Object[] getBestSpecificationGivenTerrain(Terrain terrain) {
List<TirePressure> validPressures = new ArrayList<>();
validPressures.add(TirePressure.FIFTY_PERCENT);
validPressures.add(TirePressure.SEVENTY_FIVE_PERCENT);
validPressures.add(TirePressure.ONE_HUNDRED_PERCENT);
double bestExpect = -1.0;
Object[] rt = new Object[4];
// If we want to reach the goal in MaxT timesteps, each step we should move N/MaxT cells.
double unitTimeDistance = (double) ps.getN() / ps.getMaxT();
// move Distance: -4..5
double[] moveDistance = new double[12];
for (int i = 0; i < 10; i++) {
moveDistance[i] = ProblemSpec.CAR_MIN_MOVE + i;
}
// Slip and breakdown takes T timesteps to recover, in T timesteps we are expected move T*unitTimeDistance,
// but we didn't, so set the move distance to the negation of that distance
moveDistance[10] = -ps.getSlipRecoveryTime() * unitTimeDistance;
moveDistance[11] = -ps.getRepairTime() * unitTimeDistance;
System.out.println(terrain);
for (String car : ps.getCarOrder()) {
for (String driver : ps.getDriverOrder()) {
for (Tire tire : ps.getTireOrder()) {
for (TirePressure pressure : validPressures) {
double[] moveProbs = getMoveProbs(terrain, car, driver, tire, pressure);
double expect = 0.0;
for (int i = 0; i < ProblemSpec.CAR_MOVE_RANGE; i++) {
expect += moveProbs[i] * moveDistance[i];
}
System.out.print(car + " " + driver + " " + tire + " " + pressure + " " + expect + "\n");
if (expect > bestExpect) {
bestExpect = expect;
rt = new Object[]{car, driver, tire, pressure, expect};
}
}
}
}
}
System.out.println("======================================================");
return rt;
}
public Map<Terrain, Object[]> getBestSpecification() {
Map<Terrain, Object[]> map = new HashMap<>();
for (Terrain terrain : ps.terrainOrder) {
Object[] spec = getBestSpecificationGivenTerrain(terrain);
map.put(terrain, spec);
}
return map;
}
}
// In a state node with all the possible action performed (# of possible actions == # of children).
// Perform UCT to select the best node to visit.
public StateNode uct(StateNode current) throws Exception {
Action bestAction = null;
double bestScore = -1.0;
int N = current.getVisit();
// Iterate over all possible actions
for (Action action : current.getMap().keySet()) {
ActionNode actionNode = current.getMap().get(action);
double reward = actionNode.getReward();
int n_i = actionNode.getVisit();
// w_i/n_i + c * \sqrt{ln N_i / n_i}
// c is set to \sqrt{2} as recommended by the Wikipedia
double score = (reward / n_i) + Math.sqrt(2 * Math.log(N) / n_i);
if (score > bestScore) {
bestAction = action;
bestScore = score;
}
}
// Initialize mySimulator, set timestep and current state
MySimulator simulator = new MySimulator(ps);
simulator.reset();
simulator.setSteps(current.getTimestep());
simulator.setCurrentState(current.getStateTuple().state);
// mySimulator will return next stateTuple given current state and action
StateTuple nextStateTuple = simulator.myStep(bestAction);
StateNode nextNode = current.getMap().get(bestAction).getMap().get(nextStateTuple);
if (nextNode == null) {
throw new Exception("Null Pointer");
}
return nextNode;
}
// Selection phase of MCTS
// Travelling down the Monte Carlo Search Tree to select a node for the Exapnsion phase,
// or if a terminal node is returned, directly perform backpropagation.
// 1. current node is a terminal node (WIN or LOSE), return current node
// 2. current node has at least one UNVISITED action, return current node
// 3. current node has visited all the possible actions, using UCT to select the
// best node to select, move to the best node, keep running Selection until
// current node satisfies 1. or 2. Return that node.
public StateNode Selection(StateNode stateNode) throws Exception {
// actually we just need to stop when we reach a node whose number of children
// is less than number of possible action. (Terminal node has 0 children and
// it also satisfies the upper condition)
int numAllActions = helper.getNumPossibleActions(stateNode.stateTuple);
int numVisitedActions = stateNode.getMap().size();
boolean terminate = numVisitedActions < numAllActions;
StateNode node = stateNode;
while (!terminate) {
node = uct(node);
numAllActions = helper.getNumPossibleActions(node.stateTuple);
numVisitedActions = node.getMap().size();
terminate = numVisitedActions < numAllActions;
}
return node;
}
// Expansion phase of MCTS
// Given the stateNode with at least one UNVISITED action,
// select an UNVISITED action, add a child ActionNode,
// then add all the possible stateNode(s) as a child(ren) of stateNode.
// Return a list of all next stateNodes
public List<StateNode> Expansion(StateNode stateNode) {
// Store all the information of current state
int timesteps = stateNode.timestep;
State state = stateNode.stateTuple.state;
String carType = state.getCarType();
int consumption = helper.getFuelConsumption(state);
int fuel = state.getFuel();
TirePressure tirePressure = state.getTirePressure();
String driver = state.getDriver();
Tire tire = state.getTireModel();
State nextState;
StateTuple nextTuple;
StateNode nextNode;
Set<Action> availableActions = helper.getAllPossibleActions(ps, stateNode.stateTuple);
Set<Action> visitedActions = stateNode.getMap().keySet();
Action chosenAction = null;
for (Action action : availableActions) {
if (!visitedActions.contains(action)) {
chosenAction = action;
break;
}
}
assert chosenAction != null;
List<StateNode> nodes = new ArrayList<>();
// Action Node
ActionNode actionNode = new ActionNode(chosenAction, stateNode);
stateNode.getMap().put(chosenAction, actionNode);
if (chosenAction.getActionType() == ActionType.MOVE) {
// Consume fuel if level > 1
if (ps.getLevel().getLevelNumber() > 1) {
fuel -= consumption;
}
// MOVE -4 .. 5
for (int i = ProblemSpec.CAR_MIN_MOVE; i <= ProblemSpec.CAR_MAX_MOVE; i++) {
int pos = state.getPos() + i;
if (1 <= pos && pos <= ps.getN()) {
nextState = new State(pos, false, false, carType,
fuel, tirePressure, driver, tire);
nextTuple = new StateTuple(nextState, false, false);
nextNode = new StateNode(nextTuple, actionNode, timesteps + 1);
nodes.add(nextNode);
// Update Action Node's Map
actionNode.getMap().put(nextTuple, nextNode);
}
}
nextState = new State(state.getPos(), false, false, carType, fuel, tirePressure, driver, tire);
// MOVE Slip
nextTuple = new StateTuple(nextState, true, false);
nextNode = new StateNode(nextTuple, actionNode, timesteps + ps.getSlipRecoveryTime());
nodes.add(nextNode);
actionNode.getMap().put(nextTuple, nextNode);
// Move Breakdown
nextTuple = new StateTuple(nextState, false, true);
nextNode = new StateNode(nextTuple, actionNode, timesteps + ps.getRepairTime());
nodes.add(nextNode);
actionNode.getMap().put(nextTuple, nextNode);
} else {
MySimulator simulator = new MySimulator(ps);
simulator.reset();
simulator.setCurrentState(stateNode.stateTuple.state);
simulator.setSteps(stateNode.timestep);
nextTuple = simulator.myStep(chosenAction);
nextNode = new StateNode(nextTuple, actionNode, simulator.getSteps());
nodes.add(nextNode);
actionNode.getMap().put(nextTuple, nextNode);
}
return nodes;
}
// Simulation(roll-out) phase of MCTS
// initialize a simulator, and set simulator's timesteps and state
// use random policy to select action when roll-out
// return the reward
public double Simulation(StateNode stateNode) {
int start = stateNode.stateTuple.state.getPos();
MySimulator simulator = new MySimulator(ps);
simulator.reset();
simulator.setSteps(stateNode.getTimestep());
simulator.setCurrentState(stateNode.stateTuple.state);
StateTuple tuple = stateNode.stateTuple;
outer:
while (simulator.getSteps() < ps.getMaxT()) {
State state = tuple.state;
Terrain terrain = ps.getEnvironmentMap()[state.getPos() - 1];
// bestSpec = [car, driver, tire, tirePressure, expectedMoveDistance]
Object[] bestSpec = terrain2spec.get(terrain);
String bestCar = (String) bestSpec[0];
String bestDriver = (String) bestSpec[1];
Tire bestTire = (Tire) bestSpec[2];
TirePressure bestPressure = (TirePressure) bestSpec[3];
if (!state.getCarType().equals(bestCar)) {
Action action = new Action(ActionType.CHANGE_CAR, bestCar);
tuple = simulator.myStep(action);
if (simulator.getSteps() >= ps.getMaxT()) {
break;
}
}
if (!state.getDriver().equals(bestDriver)) {
Action action = new Action(ActionType.CHANGE_DRIVER, bestDriver);
tuple = simulator.myStep(action);
if (simulator.getSteps() >= ps.getMaxT()) {
break;
}
}
if (!state.getTireModel().equals(bestTire)) {
Action action = new Action(ActionType.CHANGE_TIRES, (Tire) bestSpec[2]);
tuple = simulator.myStep(action);
if (simulator.getSteps() >= ps.getMaxT()) {
break;
}
}
int consumption = helper.getFuelConsumption(tuple.state);
// Add fuel if not enough fuel
while (tuple.state.getFuel() < consumption) {
Action action = new Action(ActionType.ADD_FUEL, 10);
tuple = simulator.myStep(action);
if (simulator.getSteps() >= ps.getMaxT()) {
break outer;
}
}
Action action = new Action(ActionType.MOVE);
tuple = simulator.myStep(action);
if (tuple.state.getPos() == ps.getN()) {
break outer;
}
}
int end = tuple.state.getPos();
int timesteps = simulator.getSteps();
return helper.calculateReward(start, end, timesteps);
}
public double Simulation_level4(StateNode stateNode) {
int start = stateNode.stateTuple.state.getPos();
MySimulator simulator = new MySimulator(ps);
simulator.reset();
simulator.setSteps(stateNode.getTimestep());
simulator.setCurrentState(stateNode.stateTuple.state);
StateTuple tuple = stateNode.stateTuple;
outer:
while (simulator.getSteps() < ps.getMaxT()) {
State state = tuple.state;
Terrain terrain = ps.getEnvironmentMap()[state.getPos() - 1];
// bestSpec = [car, driver, tire, tirePressure, expectedMoveDistance]
Object[] bestSpec = terrain2spec.get(terrain);
String bestCar = (String) bestSpec[0];
String bestDriver = (String) bestSpec[1];
Tire bestTire = (Tire) bestSpec[2];
TirePressure bestPressure = (TirePressure) bestSpec[3];
if (!state.getCarType().equals(bestCar) || !state.getDriver().equals(bestDriver)) {
Action action = new Action(ActionType.CHANGE_CAR_AND_DRIVER, bestCar, bestDriver);
tuple = simulator.myStep(action);
if (simulator.getSteps() >= ps.getMaxT()) {
break;
}
}
if (!state.getTireModel().equals(bestTire)) {
Action action = new Action(ActionType.CHANGE_TIRES, (Tire) bestSpec[2]);
tuple = simulator.myStep(action);
if (simulator.getSteps() >= ps.getMaxT()) {
break;
}
}
int consumption = helper.getFuelConsumption(tuple.state);
// Add fuel if not enough fuel
while (tuple.state.getFuel() < consumption) {
Action action = new Action(ActionType.ADD_FUEL, 10);
tuple = simulator.myStep(action);
if (simulator.getSteps() >= ps.getMaxT()) {
break outer;
}
}
Action action = new Action(ActionType.MOVE);
tuple = simulator.myStep(action);
if (tuple.state.getPos() == ps.getN()) {
break outer;
}
}
int end = tuple.state.getPos();
int timesteps = simulator.getSteps();
return helper.calculateReward(start, end, timesteps);
}
public double Simulation_level5(StateNode stateNode) {
int start = stateNode.stateTuple.state.getPos();
MySimulator simulator = new MySimulator(ps);
simulator.reset();
simulator.setSteps(stateNode.getTimestep());
simulator.setCurrentState(stateNode.stateTuple.state);
StateTuple tuple = stateNode.stateTuple;
outer:
while (simulator.getSteps() < ps.getMaxT()) {
State state = tuple.state;
Terrain terrain = ps.getEnvironmentMap()[state.getPos() - 1];
// bestSpec = [car, driver, tire, tirePressure, expectedMoveDistance]
Object[] bestSpec = terrain2spec.get(terrain);
String bestCar = (String) bestSpec[0];
String bestDriver = (String) bestSpec[1];
Tire bestTire = (Tire) bestSpec[2];
TirePressure bestPressure = (TirePressure) bestSpec[3];
if (!state.getCarType().equals(bestCar) || !state.getDriver().equals(bestDriver)) {
Action action = new Action(ActionType.CHANGE_CAR_AND_DRIVER, bestCar, bestDriver);
tuple = simulator.myStep(action);
if (simulator.getSteps() >= ps.getMaxT()) {
break;
}
}
if (!state.getTireModel().equals(bestTire)) {
Action action = new Action(ActionType.CHANGE_TIRE_FUEL_PRESSURE, (Tire) bestSpec[2], 10, state.getTirePressure());
tuple = simulator.myStep(action);
if (simulator.getSteps() >= ps.getMaxT()) {
break;
}
}
int consumption = helper.getFuelConsumption(tuple.state);
// Add fuel if not enough fuel
while (tuple.state.getFuel() < consumption) {
Action action = new Action(ActionType.ADD_FUEL, 10);
tuple = simulator.myStep(action);
if (simulator.getSteps() >= ps.getMaxT()) {
break outer;
}
}
Action action = new Action(ActionType.MOVE);
tuple = simulator.myStep(action);
if (tuple.state.getPos() == ps.getN()) {
break outer;
}
}
int end = tuple.state.getPos();
int timesteps = simulator.getSteps();
return helper.calculateReward(start, end, timesteps);
}
// Backpropagation phase of MCTS
// Perform backpropagation from leaf to root
public void backPropagation(StateNode node, double result) {
StateNode cur = node;
while (cur.parent != null) {
cur.increaseVisit();
cur.increaseReward(result);
ActionNode parentAction = cur.getParent();
parentAction.increaseVisit();
parentAction.increaseReward(result);
cur = parentAction.getParent();
}
cur.increaseVisit();
cur.increaseReward(result);
}
// Perform a single simulation of MCTS
// return array of double containing {sum of rewards, # of nodes created in Expansion phase}
public double[] simulate(StateNode root) throws Exception {
StateNode selectedNode = Selection(root);
double rt = 0;
// If selected node is a terminal node, directly perform back propagation
if (selectedNode.getGameState() != GameState.RUNNING) {
int start = root.stateTuple.state.getPos();
int end = selectedNode.stateTuple.state.getPos();
int timesteps = selectedNode.getTimestep();
double result = helper.calculateReward(start, end, timesteps);
backPropagation(selectedNode, result);
rt += result;
return new double[]{rt, 1.0};
} else {
List<StateNode> nodes = Expansion(selectedNode);
for (StateNode node : nodes) {
double result;
if (ps.getLevel().getLevelNumber() == 4) {
result = Simulation_level4(node);
} else if (ps.getLevel().getLevelNumber() == 5) {
result = Simulation_level5(node);
} else {
result = Simulation(node);
}
backPropagation(node, result);
rt += result;
}
return new double[]{rt, nodes.size()};
}
}
public void solve(String outputPath) throws Exception {
State initState = State.getStartState(ps.getFirstCarType(), ps.getFirstDriver(), ps.getFirstTireModel());
StateNode root = new StateNode(new StateTuple(initState, false, false), null, 0); // initialization of timestep is 0
Simulator writer = new Simulator(ps, outputPath, true);
writer.reset();
StateTuple nextStateTuple = null;
int i = 0;
while (i < ps.getMaxT()) {
long start = System.currentTimeMillis();
double elapsed = (System.currentTimeMillis() - start) / 1000.0;
int count = 0;
int win = 0;
// Keep simulating for 15 sec
while (elapsed < 1) {
double[] vals = simulate(root);
count += vals[1];
win += vals[0] >= 1 ? 1 : 0;
elapsed = (System.currentTimeMillis() - start) / 1000.0;
}
System.out.println("Simulated " + count + " times.. " + win + " win..");
// Select the best Action
double ratio = -1.0;
Action bestAction = null;
for (Action action : root.getMap().keySet()) {
ActionNode actionNode = root.getMap().get(action);
if (actionNode.getRatio() > ratio) {
bestAction = action;
ratio = actionNode.getRatio();
}
}
System.out.println("The best action is : " + bestAction);
if (bestAction == null) {
bestAction = new Action(ActionType.MOVE);
}
nextStateTuple = writer.myStep(bestAction);
if (nextStateTuple != null) {
System.out.println(nextStateTuple);
System.out.println("==================");
}
root = root.getMap().get(bestAction).getMap().get(nextStateTuple);
root.parent = null;
i = root.getTimestep();
if (writer.isGoalState(nextStateTuple.state)) {
System.out.println("GOOOOOOAAAAAL!!");
break;
}
}
if (!writer.isGoalState(nextStateTuple.state)) {
System.out.println("Fail!!");
}
}
public static void main(String[] args) {
String inputPath = "examples/level_5/input_lvl5_2.txt";
String outputPath = "examples/level_5/output_lvl5_2.txt";
ProblemSpec ps;
try {
ps = new ProblemSpec(inputPath);
System.out.println(ps.terrainOrder);
MCTS treeSearch = new MCTS(ps);
treeSearch.solve(outputPath);
} catch (IOException e) {
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.zhicai.byteera.activity.myhome.widget;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.DatePicker;
import com.zhicai.byteera.R;
import com.zhicai.byteera.commonutil.UIUtils;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
/** Created by bing on 2015/5/8. */
public class SelectorBirthdayDialog extends AlertDialog {
private Context mContext;
private DatePicker mDatePicker;
public interface OnOkClickListener {
void onOk();
}
private OnOkClickListener okClickListener;
public void setOkClickListener(OnOkClickListener listener) {
this.okClickListener = listener;
}
public SelectorBirthdayDialog(Context context) {
super(context);
this.mContext = context;
}
public SelectorBirthdayDialog(Context context, int theme) {
super(context, theme);
this.mContext = context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_birthday_dialog);
WindowManager.LayoutParams attributes = this.getWindow().getAttributes();
attributes.width = UIUtils.dip2px(mContext, 300);
this.getWindow().setAttributes(attributes);
mDatePicker = (DatePicker) findViewById(R.id.date_picker);
findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
okClickListener.onOk();
dismiss();
}
});
findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
public String getYear() {
return String.valueOf(mDatePicker.getYear());
}
public String getMonth() {
return String.valueOf(mDatePicker.getMonth()) + 1;
}
public String getDay() {
return String.valueOf(mDatePicker.getDayOfMonth());
}
public String getDate() {
return String.valueOf(mDatePicker.getYear()) + "-" + String.valueOf(mDatePicker.getMonth() + 1) + "-" + String.valueOf(mDatePicker.getDayOfMonth());
}
public void setBirthday(String... date) {
if (date.length == 3) {
mDatePicker.init(Integer.parseInt(date[0]), Integer.parseInt(date[1]) - 1, Integer.parseInt(date[2]), new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
});
} else {
Date current = new Date();
long time = current.getTime();
Format format = new SimpleDateFormat("yyyy-MM-dd");
String format1 = format.format(time);
String[] split = format1.split("-");
mDatePicker.init(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]), new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
});
}
}
}
|
package com.github.jishida.gradle.shellscript;
import com.github.jishida.gradle.commons.util.Checker;
import com.github.jishida.gradle.shellscript.tasks.Msys2Setup;
import groovy.lang.Closure;
import org.gradle.api.Action;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.internal.ClosureBackedAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static com.github.jishida.gradle.commons.util.EnvironmentUtils.isWindows;
public class ShellScriptExtension {
private final Project project;
private ShellScriptInfo info;
private final Msys2Spec msys2;
private Object unixShell = ShellScriptStrings.DEFAULT_UNIX_SHELL;
private final List<String> shellArgs = new ArrayList<String>();
public ShellScriptExtension(final Project project) {
this.project = project;
msys2 = new Msys2Spec(project);
}
public Project getProject() {
return project;
}
public ShellScriptInfo getInfo() {
return info;
}
public Msys2Spec getMsys2() {
return msys2;
}
public void msys2(final Action<Msys2Spec> action) {
Checker.checkNull(action, "action");
action.execute(msys2);
}
public void msys2(final Closure closure) {
Checker.checkNull(closure, "closure");
msys2(new ClosureBackedAction<Msys2Spec>(closure));
}
public Object getUnixShell() {
return unixShell;
}
public void setUnixShell(final Object value) {
unixShell = value;
}
public Collection<String> getShellArgs() {
return shellArgs;
}
public void setShellArgs(final Collection<String> value) {
Checker.checkNull(value, "value");
shellArgs.clear();
shellArgs.addAll(value);
}
public void shellArgs(final Iterable<String> value) {
Checker.checkNull(value, "value");
for (String item : value) {
shellArgs.add(item);
}
}
public void shellArgs(final String... value) {
Collections.addAll(shellArgs, value);
}
ShellScriptInfo configure() {
if (info == null) {
info = new ShellScriptInfo(this);
if (isWindows()) {
final Task msys2Setup = project.getTasks().getByName(Msys2Setup.TASK_NAME);
if (!info.getMsys2().hasCache()) {
msys2Setup.dependsOn(info.getMsys2().getCache().getProject().getTasks().getByName(Msys2Setup.TASK_NAME));
}
}
}
return info;
}
}
|
package common.zhang.customer;
/**
* Created by zzw on 2017/3/15.
*/
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.HorizontalScrollView;
import android.widget.Scroller;
import java.lang.reflect.Field;
public class MHorizontalScrollView
extends HorizontalScrollView {
private static final String TAG = "CustomScrollView";
private int Scroll_height = 0;
private GestureDetector mGestureDetector;// = new GestureDetector(paramContext, new YScrollDetector());
protected Field scrollView_mScroller;
private int view_height = 0;
public MHorizontalScrollView(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
mGestureDetector= new GestureDetector(paramContext, new YScrollDetector());
setFadingEdgeLength(0);
}
public static Field getDeclaredField(Object paramObject, String paramString) {
paramObject = paramObject.getClass();
for (; ; ) {
if (paramObject == Object.class) {
return null;
}
try {
Field localField = ((Class) paramObject).getDeclaredField(paramString);
localField.setAccessible(true);
return localField;
} catch (Exception localException) {
paramObject = ((Class) paramObject).getSuperclass();
}
}
}
private void stopAnim() {
try {
if (this.scrollView_mScroller == null) {
this.scrollView_mScroller = getDeclaredField(this, "mScroller");
}
Object localObject = this.scrollView_mScroller.get(this);
if (localObject == null) {
return;
}
localObject.getClass().getMethod("abortAnimation", new Class[0]).invoke(localObject, new Object[0]);
return;
} catch (Exception localException) {
}
}
protected int computeVerticalScrollRange() {
this.Scroll_height = super.computeVerticalScrollRange();
return this.Scroll_height;
}
public boolean onInterceptTouchEvent(MotionEvent paramMotionEvent) {
if (paramMotionEvent.getAction() == 0) {
stopAnim();
}
boolean bool1 = super.onInterceptTouchEvent(paramMotionEvent);
boolean bool2 = this.mGestureDetector.onTouchEvent(paramMotionEvent);
return (bool1) && (bool2);
}
protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
super.onLayout(paramBoolean, paramInt1, paramInt2, paramInt3, paramInt4);
if (paramBoolean) {
this.view_height = (paramInt4 - paramInt2);
}
}
protected void onScrollChanged(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
int i = 0;
if (this.Scroll_height - this.view_height == paramInt2) {
i = 1;
}
if ((paramInt2 == 0) || (i != 0)) {
}
try {
if (this.scrollView_mScroller == null) {
this.scrollView_mScroller = getDeclaredField(this, "mScroller");
}
Object localObject = this.scrollView_mScroller.get(this);
if (localObject == null) {
return;
}
if (!(localObject instanceof Scroller)) {
return;
}
((Scroller) localObject).abortAnimation();
} catch (Exception localException) {
for (; ; ) {
Log.e("CustomScrollView", localException.getMessage());
}
}
super.onScrollChanged(paramInt1, paramInt2, paramInt3, paramInt4);
return;
}
public void requestChildFocus(View paramView1, View paramView2) {
if ((paramView2 != null) && ((paramView2 instanceof WebView))) {
return;
}
super.requestChildFocus(paramView1, paramView2);
}
class YScrollDetector
extends GestureDetector.SimpleOnGestureListener {
YScrollDetector() {
}
public boolean onScroll(MotionEvent paramMotionEvent1, MotionEvent paramMotionEvent2, float paramFloat1, float paramFloat2) {
return false;
}
}
}
|
package com.example.android.finalproject_yaocmengqid.MainContent;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android.finalproject_yaocmengqid.Expense;
import com.example.android.finalproject_yaocmengqid.People;
import com.example.android.finalproject_yaocmengqid.Plan;
import com.example.android.finalproject_yaocmengqid.R;
import com.example.android.finalproject_yaocmengqid.SideMenu.ProfileActivity;
import com.example.android.finalproject_yaocmengqid.Utils.CalculateAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Map;
public class CalculateActivity extends Activity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private ImageView photo;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
//private People user;
private ArrayList<Plan> results;
private String TAG = "CalculateActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculate);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
results = new ArrayList<>();
mRecyclerView.setHasFixedSize(true);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
photo = (ImageView) findViewById(R.id.calculate_photo);
DatabaseReference mDatabaseRef = FirebaseDatabase.getInstance().getReference("users").child(user.getUid());
mDatabaseRef.child("profilePhoto").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String url = dataSnapshot.getValue(String.class);
if (url != null) {
Picasso.with(CalculateActivity.this).load(Uri.parse(url))
.resize(photo.getWidth(), photo.getHeight())
.centerInside()
.into(photo);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
Intent intent = new Intent(CalculateActivity.this, LoginActivity.class);
startActivity(intent);
}
}
};
mAuth.addAuthStateListener(mAuthListener);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(CalculateActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new CalculateAdapter(results);
mRecyclerView.setAdapter(mAdapter);
FirebaseAuth mAuth = FirebaseAuth.getInstance();
mAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("people").child(user.getUid());
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Map<String, Object> collection = (Map<String, Object>)dataSnapshot.getValue();
ArrayList<People> members = new ArrayList<People>();
for (DataSnapshot child : dataSnapshot.getChildren())
members.add(child.getValue(People.class));
BigDecimal pay = new BigDecimal(members.get(0).getPay());
BigDecimal expense = new BigDecimal(members.get(0).getExpense());
BigDecimal delta = pay.subtract(expense);
int mark = delta.compareTo(BigDecimal.ZERO);
if (mark == 1) {
((TextView) findViewById(R.id.cal_pay_recv)).setText("You still need to receive");
((TextView) findViewById(R.id.calculate)).setText("$ " + delta.setScale(2).toString());
} else if (mark == -1) {
((TextView) findViewById(R.id.cal_pay_recv)).setText("You still need to pay");
((TextView) findViewById(R.id.calculate)).setText("$ " + delta.negate().setScale(2).toString());
}
for (int i = 1; i < members.size(); ++ i) {
pay = new BigDecimal(members.get(i).getPay());
expense = new BigDecimal(members.get(i).getExpense());
delta = pay.subtract(expense);
mark = delta.compareTo(BigDecimal.ZERO);
if (mark == 1) {
results.add(new Plan(members.get(0).getName(), delta.toString(), members.get(i).getName()));
} else if (mark == -1) {
results.add(new Plan(members.get(i).getName(), delta.negate().toString(), members.get(0).getName()));
}
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
finish();
}
}
});
}
public void share(View view){
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_SUBJECT, "Bill Summary");
intent.putExtra(Intent.EXTRA_TEXT, "You still need to pay");
if (intent.resolveActivity(getPackageManager())!=null) {
startActivity(intent);
}
}
}
|
package com.buttercell.vaxn.common;
/**
* Created by amush on 03-Mar-18.
*/
public class Common {
public static String patient_key="";
public static String guardian_key="";
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.socket.server.upgrade;
import java.net.URI;
import java.util.function.Supplier;
import reactor.core.publisher.Mono;
import reactor.netty5.http.server.HttpServerResponse;
import reactor.netty5.http.server.WebsocketServerSpec;
import org.springframework.core.io.buffer.Netty5DataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.reactive.socket.HandshakeInfo;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.adapter.ReactorNetty2WebSocketSession;
import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy;
import org.springframework.web.server.ServerWebExchange;
/**
* A WebSocket {@code RequestUpgradeStrategy} for Reactor Netty for Netty 5.
*
* <p>This class is based on {@link ReactorNettyRequestUpgradeStrategy}.
*
* @author Violeta Georgieva
* @since 6.0
*/
public class ReactorNetty2RequestUpgradeStrategy implements RequestUpgradeStrategy {
private final Supplier<WebsocketServerSpec.Builder> specBuilderSupplier;
/**
* Create an instances with a default {@link WebsocketServerSpec.Builder}.
* @since 5.2.6
*/
public ReactorNetty2RequestUpgradeStrategy() {
this(WebsocketServerSpec::builder);
}
/**
* Create an instance with a pre-configured {@link WebsocketServerSpec.Builder}
* to use for WebSocket upgrades.
* @since 5.2.6
*/
public ReactorNetty2RequestUpgradeStrategy(Supplier<WebsocketServerSpec.Builder> builderSupplier) {
Assert.notNull(builderSupplier, "WebsocketServerSpec.Builder is required");
this.specBuilderSupplier = builderSupplier;
}
/**
* Build an instance of {@code WebsocketServerSpec} that reflects the current
* configuration. This can be used to check the configured parameters except
* for sub-protocols which depend on the {@link WebSocketHandler} that is used
* for a given upgrade.
* @since 5.2.6
*/
public WebsocketServerSpec getWebsocketServerSpec() {
return buildSpec(null);
}
WebsocketServerSpec buildSpec(@Nullable String subProtocol) {
WebsocketServerSpec.Builder builder = this.specBuilderSupplier.get();
if (subProtocol != null) {
builder.protocols(subProtocol);
}
return builder.build();
}
@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler,
@Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) {
ServerHttpResponse response = exchange.getResponse();
HttpServerResponse reactorResponse = ServerHttpResponseDecorator.getNativeResponse(response);
HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
Netty5DataBufferFactory bufferFactory = (Netty5DataBufferFactory) response.bufferFactory();
URI uri = exchange.getRequest().getURI();
// Trigger WebFlux preCommit actions and upgrade
return response.setComplete()
.then(Mono.defer(() -> {
WebsocketServerSpec spec = buildSpec(subProtocol);
return reactorResponse.sendWebsocket((in, out) -> {
ReactorNetty2WebSocketSession session =
new ReactorNetty2WebSocketSession(
in, out, handshakeInfo, bufferFactory, spec.maxFramePayloadLength());
return handler.handle(session).checkpoint(uri + " [ReactorNetty2RequestUpgradeStrategy]");
}, spec);
}));
}
}
|
package com.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.test.base.Solution;
/**
* 正常的,dfs即可
* @author YLine
*
* 2018年12月18日 上午10:28:19
*/
public class SolutionA implements Solution
{
@Override
public List<Integer> spiralOrder(int[][] matrix)
{
List<Integer> result = new ArrayList<>();
int row = matrix.length;
if (row == 0)
{
return result;
}
int column = matrix[0].length;
dfs(matrix, 0, new Rect(row, column), result);
System.out.println(Arrays.toString(result.toArray()));
return result;
}
private void dfs(int[][] matrix, int oritation, Rect rect, List<Integer> result)
{
if (rect.isEnd())
{
return;
}
// 添加内容
rect.attach(matrix, oritation, result);
dfs(matrix, (oritation + 1) % 4, rect, result);
}
public static class Rect
{
private int left;
private int right;
private int top;
private int bottom;
public Rect(int row, int column)
{
this.left = 0;
this.top = 0;
this.right = column - 1;
this.bottom = row - 1;
}
public boolean isEnd()
{
return (left > right || top > bottom);
}
public void attach(int[][] matrix, int oritation, List<Integer> result)
{
if (oritation == 0) // 从左往右
{
for (int i = left; i <= right; i++)
{
result.add(matrix[top][i]);
}
top++;
}
else if (oritation == 1) // 从上往下
{
for (int i = top; i <= bottom; i++)
{
result.add(matrix[i][right]);
}
right--;
}
else if (oritation == 2) // 从右往左
{
for (int i = right; i >= left; i--)
{
result.add(matrix[bottom][i]);
}
bottom--;
}
else // 从下往上
{
for (int i = bottom; i >= top; i--)
{
result.add(matrix[i][left]);
}
left++;
}
}
}
}
|
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
Button minus;
Button plus;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
minus.findViewById(R.id.minus);
plus.findViewById(R.id.plus);
progressBar.findViewById(R.id.progressBar);
minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressBar.setProgress(progressBar.getProgress() - 10);
}
});
plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressBar.setProgress(progressBar.getProgress() + 10);
}
});
}
}
|
package com.tu.springsession;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
* @Auther: tuyongjian
* @Date: 2020/4/16 15:56
* @Description:
*/
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class SpringSessionApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSessionApplication.class,args);
}
}
|
package ibessonov.tm;
import java.util.List;
public class Sample {
interface BadList<T> extends List<List<? super BadList<? super T>>> {}
public static void main(String[] args) {
BadList<? super String> badList = null;
// List<? super BadList<? super String>> list = badList; // this will throw StackOverflowError in compiler
}
}
|
public class LinearSearch {
public static void main(String[] args) {
//dummy data for our method
char letter = 'a';
char[] letters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q',
'r','s','t','u','v','w','x','y','z'};
char[] lettersNull = null;
LinearSearch ls = new LinearSearch();
//calling methods
System.out.println(ls.findLetter(letter, lettersNull));
}
//write first method here
public int findLetter(char target, char[] data) {
//if the data we take as an input is null or uninitialized the we return -1
if(data == null) {
return -1;
}
//we return -1 if the data is not found in the array
int result = -1;
for(int i = 0; i < data.length; i++) {
//temporary holder for our data
char temp = data[i];
//testing current element against our target, if it matches we return the targets index
if(temp == target) {
return i;
}
}
return result;
}
}
|
/*
provides a simple method to start playing a one-player game
*/
import java.util.Scanner;
public class Play {
private Game game;
/**
* Constructor for the Play class to play a game of Battleship.
*/
public Play () {
game = new Game(false);
game.initializeGUI();
beginGame();
}
/**
* Runs the user input system for playing a game.
*/
public void beginGame () {
String target;
try {
Scanner in = new Scanner(System.in);
do {
System.out.println("Enter a cell (i.e. A1) to try to hit a ship, or type \"quit\" to end the game: ");
target = in.nextLine();
if (!target.equals("quit")) {
if (Config.isValidTarget(target)) {
int result = game.shootTarget(target);
switch (result) {
case 0:
System.out.println("Miss");
break;
case 3:
System.out.println("You win!");
break;
case 2:
System.out.println("You sunk a ship!");
break;
case 1:
System.out.println("Hit!");
break;
}
} else {
System.out.println("Invalid target cell");
}
}
System.out.println();
} while (!target.equalsIgnoreCase("quit"));
in.close();
} catch (Exception IOException) {
System.out.println("Input exception reported");
IOException.printStackTrace();
}
}
/**
* The entry point for the game mode.
* @param args
*/
public static void main(String[] args) {
new Play();
}
}
|
package com.sxb.controller;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.sxb.util.JsonUtils;
import com.sxb.util.Sign;
/**
* @description 后台工具和一些特定API接口管理 RestController
* @author <a href="mailto:ou8zz@sina.com">OLE</a>
* @date 2016/06/22
* @version 1.0
*/
@RestController
public class ApiController {
private Log log = LogFactory.getLog(ApiController.class);
/**
* JAVA获取微信签名方法 http://localhost/sxb//tools/reqjssdk?callback=callback&url=http://demo.com
* @param url 注意 URL 一定要动态获取,不能 hardcode
* 请求示例:GET请求后缀/tools/reqjssdk?callback=callback&url=http://demo.com
* @return 跨域请求callback
*/
@RequestMapping(method=RequestMethod.GET, value="/tools/reqjssdk")
public Object getSign(@RequestParam("callback") String callback, @RequestParam("url") String url) {
try {
Map<String, String> sign = Sign.getSign(null, null, url);
String json = JsonUtils.toJson(sign);
json = callback + "(" + json + ")"; // 跨域请求callback拼接
return json;
} catch(Exception e) {
log.error("getSign error", e);
}
return null;
}
}
|
package com.disco.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.disco.dao.utils.Closer;
import com.disco.dao.utils.Context;
import com.disco.model.Artist;
import com.disco.model.SacemRegistration;
public class SacemDaoImpl implements SacemDao {
private final String tableName = "sacemregistration";
private final String idColumnName = "reference";
@Override
public List<SacemRegistration> findAll() {
Connection conn;
Statement stmt = null;
ResultSet rs = null;
List<SacemRegistration> registrations = new ArrayList<>();
try {
conn = Context.getInstance().getConn();
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM " + tableName);
while(rs.next()) {
SacemRegistration p = new SacemRegistration(rs.getString(idColumnName), rs.getDate("date"));
registrations.add(p);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Closer.closeResultSet(rs);
Closer.closeStatement(stmt);
}
return registrations;
}
@Override
public SacemRegistration findByKey(String id) {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
SacemRegistration p = null;
try {
conn = Context.getInstance().getConn();
stmt = conn.prepareStatement("SELECT * FROM " + tableName + " where " + idColumnName + " LIKE ? ");
stmt.setString(1, id);
rs = stmt.executeQuery();
if(rs.next()) {
p = new SacemRegistration(rs.getString(this.idColumnName), rs.getDate("date"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
Closer.closeResultSet(rs);
Closer.closeStatement(stmt);
}
return p;
}
@Override
public void insert(SacemRegistration registration) {
Connection conn;
PreparedStatement stmt = null;
try {
conn = Context.getInstance().getConn();
stmt = conn.prepareStatement("INSERT INTO " + tableName + " (reference, date) VALUES (?, ?) ");
stmt.setString(1, registration.getReference());
stmt.setDate(2, new java.sql.Date(registration.getDate().getTime()));
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
Closer.closeStatement(stmt);
}
}
@Override
public void update(SacemRegistration registration) {
Connection conn;
PreparedStatement stmt = null;
try {
conn = Context.getInstance().getConn();
stmt = conn.prepareStatement("UPDATE " + tableName + " set " + idColumnName + " = ? WHERE " + idColumnName + " = ? ");
stmt.setString(1, registration.getReference());
stmt.setDate(2, new java.sql.Date(registration.getDate().getTime()));
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
Closer.closeStatement(stmt);
}
}
@Override
public void deleteByKey(String id) {
Connection conn;
PreparedStatement stmt = null;
try {
conn = Context.getInstance().getConn();
stmt = conn.prepareStatement("DELETE FROM " + tableName + " where " + idColumnName + "= ?");
stmt.setString(1, id);
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
Closer.closeStatement(stmt);
}
}
//select * from artist left join sacem on artist.sacem_id = sacem.reference where artist.bandName like 'Lamb of god'
@Override
public SacemRegistration getByArtist(Artist artist) {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
SacemRegistration p = null;
try {
conn = Context.getInstance().getConn();
stmt = conn.prepareStatement("SELECT * FROM " + tableName + " LEFT JOIN artist ON artist.sacem_id = sacem.reference WHERE artist.bandName LIKE ? ");
stmt.setString(1, artist.getBandName());
rs = stmt.executeQuery();
if(rs.next()) {
p = new SacemRegistration(rs.getString(this.idColumnName), rs.getDate("date"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
Closer.closeResultSet(rs);
Closer.closeStatement(stmt);
}
return p;
}
}
|
package com.imooc.handler;
import com.imooc.config.ProjectUrlConfig;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellerAuthorizeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
@ControllerAdvice
@Slf4j
public class SellerExceptionHandler {
@Autowired
private ProjectUrlConfig projectUrlConfig;
/**
* 拦截登陆异常
*/
@ExceptionHandler(SellerAuthorizeException.class)
public ModelAndView handlerAuthorizeException(){
//这里不能加Map《String, Object》是因为只能在Controller里才能加 这里没有页面链接设置@GetMapping
//这里应该跳到二维码扫描页面的 "redirect:".concat(projectUrl.getSell().concat("sell/wechat/qrAuthorize")) .....
log.warn("【进来了!】");
return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/sell/seller/login");
}
}
|
package cn.ztuo.bitrade.controller.aic;
import cn.ztuo.bitrade.dao.SysConfigDao;
import cn.ztuo.bitrade.entity.ExchangeOrderDirection;
import cn.ztuo.bitrade.service.RobotOrderService;
import cn.ztuo.bitrade.util.MessageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
@RestController
@Slf4j
@RequestMapping("robot")
public class RobotOrderController {
@Autowired
private RobotOrderService robotOrderService;
/**
* 获取历史总交易额,今日交易额,今日买单量,今日卖单量,以及机器人挂单记录
*/
@PostMapping("getRobotOrderPage")
public MessageResult getRobotOrderPage(Long memberId, Integer type, Integer pageNo, Integer pageSize) {
return robotOrderService.getRobotOrderPage(memberId, type, pageNo, pageSize);
}
/**
* 发布委托单
*/
@PostMapping("addOrder")
public MessageResult addOrder(BigDecimal price, BigDecimal amount, ExchangeOrderDirection exchangeOrderDirection) {
return robotOrderService.addOrder(price, amount, exchangeOrderDirection);
}
/**
* 查询机器人卖单延长时间
*/
@PostMapping("getRobotTime")
public MessageResult getRobotTime() {
return robotOrderService.getRobotTime();
}
@PostMapping("getBAmount")
public MessageResult getBAmount() {
return robotOrderService.getBAmount();
}
/**
* 修改机器人发布卖单延长时间
*/
@PostMapping("updateRobotTime")
public MessageResult updateRobotTime(String value) {
return robotOrderService.updateRobotTime(value);
}
@PostMapping("updateBAmount")
public MessageResult updateBAmount(String value) {
return robotOrderService.updateBAmount(value);
}
}
|
package daseel.game.trialsofjorah;
/*
* Class used to store positions in a 2d-space (might switch to float or double later)
*/
public class Vector {
private float x;
private float y;
public Vector(float x, float y) {
this.x = x;
this.y = y;
}
public Vector(Vector vector) {
this(vector.getX(), vector.getY());
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public void setX(float x) {
this.x = x;
}
public void setY(float y) {
this.y = y;
}
}
|
/*
* 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 exp8;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* @author ks834
*/
public class scroll extends Applet implements AdjustmentListener{
Scrollbar s1,s2,s3;
public void init(){
s1=new Scrollbar(Scrollbar.HORIZONTAL,0,50,0,255);
s2=new Scrollbar(Scrollbar.HORIZONTAL,0,50,0,255);
s3=new Scrollbar(Scrollbar.HORIZONTAL,0,50,0,255);
s1.addAdjustmentListener(this);
s2.addAdjustmentListener(this);
s3.addAdjustmentListener(this);
add(s1);
add(s2);
add(s3);
}
public void adjustmentValueChanged(AdjustmentEvent e){
repaint();
}
public void paint(Graphics g){
int x,y,z;
x=s1.getValue();
y=s2.getValue();
z=s3.getValue();
Color c=new Color(x,y,z);
setBackground(c);
}
}
|
package com.github.riyaz.bakingapp.di;
import com.github.riyaz.bakingapp.screens.ingredients.IngredientListActivity;
import com.github.riyaz.bakingapp.screens.ingredients.IngredientListActivityModule;
import com.github.riyaz.bakingapp.screens.recipes.RecipeListActivity;
import com.github.riyaz.bakingapp.screens.steps.StepActivityModule;
import com.github.riyaz.bakingapp.screens.steps.StepFragmentModule;
import com.github.riyaz.bakingapp.screens.steps.StepsActivity;
import com.github.riyaz.bakingapp.widget.WidgetConfigurationActivity;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
/**
* Dagger module to facilitate dagger in injecting Android platform managed classes
*
* @author Riyaz
*/
@Module public abstract class ActivityBuilderModule {
// [target]: RecipeListActivity
@ContributesAndroidInjector abstract RecipeListActivity bindRecipeListActivity();
// [target]: IngredientListActivity
@ContributesAndroidInjector(modules = { IngredientListActivityModule.class })
abstract IngredientListActivity bindIngredientListActivity();
// [target]: StepsActivity
@ContributesAndroidInjector(modules = { StepActivityModule.class, StepFragmentModule.class }) abstract StepsActivity bindStepsActivity();
// [target]: WidgetConfigurationActivity
@ContributesAndroidInjector abstract WidgetConfigurationActivity bindWidgetConfigurationActivity();
}
|
package com.rednovo.tools.sms;
import org.apache.commons.lang.StringUtils;
import com.rednovo.tools.web.HttpSender;
/**
* 神州短信工具类
*
* web登录入口 http://user.bjszrk.com/Frame/Index.aspx
*
* @author sg.z/2014年10月13日
*/
public class SzSMSUtil {
/**
* 接口地址
*/
private final static String SELSUM_URL = "http://api.bjszrk.com/sdk/SelSum.aspx";
/**
* 群发送短信地址
*/
private final static String BATCHSEND_URL = "http://api.bjszrk.com/sdk/BatchSend.aspx";
/**
* 用户名和密码
*/
private final static String CorpID = "SDK1981";
private final static String Pwd = "hongnuo123";
/**
* 获取余额
*
* @author sg.z
* @since 2014年10月13日下午6:23:42
*/
public static String getSelSum() {
StringBuffer sb = new StringBuffer();
sb.append("CorpID=" + CorpID);
sb.append("&Pwd=" + Pwd);
String result = HttpSender.urlRequest(SELSUM_URL, sb.toString());
if (StringUtils.isNotBlank(result)) {
int res = Integer.valueOf(result).intValue();
if (res >= 0) {
return result;
} else if (res == -1) {
return "账号未注册";
} else if (res == -2) {
return "其他错误";
} else if (res == -3) {
return "帐号或密码错误";
}
}
return "";
}
/**
* 批量发送短信
*
* @param mobiles 手机号码,多个号码‘,’号隔开,一次提交信息不能超过10000个手机号码 不能为空
* @param content 发送内容 不能为空
* @param sendTime 定时发送时间,固定14位长度字符串,比如:20060912152435 可以为空
* @return
* @author sg.z
* @since 2014年10月14日下午12:04:48
*/
public static String batchSend(String mobiles, String content, String sendTime) {
if (StringUtils.isBlank(content) || StringUtils.isBlank(mobiles)) {
return "发送号码和内容不能为空";
}
if (content.length() <= 3 || content.length() >= 250) {
return "发送内容需在3到250字之间";
}
if (StringUtils.isNotBlank(sendTime) && sendTime.length() != 14) {
return "定时发送时间不是有效的时间格式";
}
StringBuffer sb = new StringBuffer();
sb.append("CorpID=" + CorpID);
sb.append("&Pwd=" + Pwd);
sb.append("&Mobile=" + mobiles);
sb.append("&Content=" + content);
sb.append("&SendTime=" + sendTime);
String result = HttpSender.urlRequest(BATCHSEND_URL, sb.toString());
if (StringUtils.isNotBlank(result)) {
long res = Long.valueOf(result).longValue();
if (res > 0) {
return "发送成功";
} else if (res == -1) {
return "账号未注册";
} else if (res == -2) {
return "其他错误";
} else if (res == -3) {
return "帐号或密码错误";
} else if (res == -4) {
return "一次提交信息不能超过10000个手机号码,号码逗号隔开";
} else if (res == -5) {
return "余额不足,请先充值";
} else if (res == -6) {
return "定时发送时间不是有效的时间格式";
} else if (res == -8) {
return "发送内容需在3到250字之间";
} else if (res == -9) {
return "发送号码为空";
}
}
return "";
}
public static void main(String[] args) {
// System.out.println(getSelSum());
// System.out.println(batchSend("18201102770", "尊敬的客户您好,您的验证码是666666", ""));
System.out.println(batchSend("", "您的验证码是:111111。", ""));
}
}
|
package com.testFileUpload.util;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Mylog {
String value() default "";
}
|
package com.mmrath.sapp.web.rest.core;
import com.mmrath.sapp.domain.core.User;
import com.mmrath.sapp.service.core.UserService;
import com.mmrath.sapp.web.rest.rsql.RsqlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/api/core/users")
public class UserResource {
private final Logger logger = LoggerFactory.getLogger(UserResource.class);
private final UserService userService;
@Autowired
public UserResource(UserService userService) {
this.userService = userService;
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public User findById(@PathVariable("id") Long id) {
User user = userService.findUser(id);
return user;
}
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public Page<User> findAll(String query, Pageable pageRequest) {
logger.info("Page request:{}", pageRequest);
logger.info("User search criteria:{}", query);
return userService.findUsers(RsqlUtils.parse(query), pageRequest);
}
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public User create(@Valid @RequestBody User user) {
logger.debug("User to create:{}", user);
userService.createUser(user);
return user;
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ResponseBody
public User update(@PathVariable("id") Long id, @Valid @RequestBody User user) {
logger.debug("User to update:{}", user);
user = userService.updateUser(user);
return user;
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.OK)
public Long delete(@PathVariable("id") Long id) {
logger.debug("User to delete:{}", id);
return userService.deleteUser(id);
}
}
|
package cp.week17;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
*
* @author Fabrizio Montesi <fmontesi@imada.sdu.dk>
*/
public class ThreadsExercise14
{
/*
Modify Threads/cp/WalkExecutorFuture such that, instead of word occurrences,
it computes a map of type Map< Path, FileInfo >, which maps the Path of each file found in "data"
to an object of type FileInfo that contains:
- the size of the file;
- the number of lines contained in the file;
- the number of lines starting with the uppercase letter "L".
*/
public static void main(String[] args) {
Map< Path, FileInfo > infoForFiles = new HashMap<>();
ExecutorService executor = Executors.newWorkStealingPool();
try {
List< Future< FileInfoAndPath > > futures =
Files.walk( Paths.get( "data" ) )
.filter( Files::isRegularFile )
.map( filepath ->
executor.submit( () -> computeFileInfo( filepath ) )
)
.collect( Collectors.toList() );
for( Future< FileInfoAndPath > future : futures ) {
FileInfoAndPath result = future.get();
infoForFiles.put(result.filepath, result.fileInfo);
}
} catch( InterruptedException | ExecutionException | IOException e ) {
e.printStackTrace();
}
try {
executor.shutdown();
executor.awaitTermination( 1, TimeUnit.DAYS );
} catch( InterruptedException e ) {
e.printStackTrace();
}
infoForFiles.forEach( (key, value) -> System.out.println( key + ": " + value ) );
}
private static FileInfoAndPath computeFileInfo( Path textFile )
{
long numLines = 0;
long numLinesStartingWithL = 0;
long sizeOfFile = -1;
try {
sizeOfFile = Files.size(textFile);
for (String line : Files.readAllLines(textFile)) {
++numLines;
if (line.startsWith("L")) {
++numLinesStartingWithL;
}
}
} catch( IOException e ) {
e.printStackTrace();
}
return new FileInfoAndPath(new FileInfo(sizeOfFile, numLines, numLinesStartingWithL), textFile);
}
private static class FileInfoAndPath {
public final FileInfo fileInfo;
public final Path filepath;
public FileInfoAndPath(FileInfo fileInfo, Path filepath) {
this.fileInfo = fileInfo;
this.filepath = filepath;
}
}
private static class FileInfo {
// the size of the file;
public final long sizeOfFile;
// the number of lines contained in the file;
public final long numLines;
// the number of lines starting with the uppercase letter "L".
public final long numLinesStartingWithL;
public FileInfo(long sizeOfFile, long numLines, long numLinesStartingWithL) {
this.sizeOfFile = sizeOfFile;
this.numLines = numLines;
this.numLinesStartingWithL = numLinesStartingWithL;
}
@Override
public String toString() {
return String.format("(filesize:%d, numlines:%d, num_l_lines:%d)", sizeOfFile, numLines, numLinesStartingWithL);
}
}
}
|
/**
* Copyright 2016 Shyam Bhimani
*/
package day20_sortingArray;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.*;
public class BubbleSortExample {
/* public static int swap(a[i], a[i+1]){
int temp1 = 0;
int temp2 = 0;
int tempSwap;
temp1 = a[i];
temp2 = a[i+1];
if (a[i] < a[i+1]){
tempSwap = temp1;
temp1 = temp2;
temp2 = tempSwap;
}
return (temp1, temp2)
} */
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int numSwap = 0;
int a[] = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
for (int i = 0; i < n-1; i++){
for (int j = i+1; j <= n -1; j++){
if (a[i] > a[j]){
numSwap++;
}
}
}
Arrays.sort(a);
System.out.println("Array is sorted in " + numSwap + " swaps.");
System.out.println("First Element: " + a[0] );
System.out.println("Last Element: " + a[a.length-1] );
}
}
|
package com.lambda.iith.dashboard.LostFound;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import com.lambda.iith.dashboard.MainActivity;
import com.lambda.iith.dashboard.R;
import Adapters.ViewPagerAdapter;
public class Main2Activity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lostfound);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Toolbar toolbar = findViewById(R.id.toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
// toolbar.setNavigationOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// startActivity(new Intent(getApplicationContext(),MainActivity.class));
// }
// });
/*ImageView home=(ImageView) view.findViewById(R.id.back_id);
home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent homeIntent = new Intent(Main2Activity.this,MainActivity.class);
startActivity(homeIntent);
}
});*/
tabLayout = findViewById(R.id.tablayout_id);
// appBarLayout =(AppBarLayout) findViewById(R.id.appbarid);
viewPager = findViewById(R.id.viewpager_id);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// Adding fragments
adapter.AddFragment(new FragmentQuiz(), "LOST");
adapter.AddFragment(new FragmentExplore(), "FOUND");
// adapter setup
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
@Override
public boolean onSupportNavigateUp() {
Intent homeIntent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(homeIntent);
return true;
}
}
|
import com.sun.java.swing.plaf.windows.WindowsTabbedPaneUI;
import org.omg.CORBA.PRIVATE_MEMBER;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
private String IPAdress = "127.0.0.1";
private int port = 8081;
private PrintWriter out;
private BufferedReader in;
private Socket socket;
public Client () throws Exception {
//连接服务器
socket = new Socket(IPAdress,port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
//开启新县城
new ClientThread().start();
while (true){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
out.println(input);
if(input.equals("exit")){
out.close();
in.close();
socket.close();
System.exit(0);
}
}
}
private class ClientThread extends Thread{
public void run(){
String fromServerData;
try {
while (((fromServerData= in.readLine())!=null)) {
System.out.println(fromServerData);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
new Client();
}
}
|
package mx.redts.adendas.dao;
import java.util.List;
import mx.redts.adendas.exception.AdendaException;
import mx.redts.adendas.model.FeDetalle;
import mx.redts.adendas.model.FeDirFiscal;
import mx.redts.adendas.model.FeDirReceptor;
import mx.redts.adendas.model.FeEncabezado;
import mx.redts.adendas.model.FeExpedidoEn;
import mx.redts.adendas.model.FeLugarEntrega;
import mx.redts.adendas.model.FeSumario;
/**
*
* User DAO Interface
*
* @version 1.0.0
*
*/
public interface IAdendaDAO {
public List<FeDetalle> consultaDetalleByID(String id);
public FeDirFiscal consultaDirFiscalByID(String id);
public FeDirReceptor consultaDirReceptorByID(String id);
public FeEncabezado consultaEncabezadoByID(String id);
public FeExpedidoEn consultaExpedidaEnByID(String id);
public void consultaFactura();
public FeLugarEntrega consultaLugarEntregaByID(String id);
public FeSumario consultaSumarioByID(String id);
public boolean existeFacturaByID(String id);
public void guardaFactura();
public void saveFactura(FeEncabezado encabezado, FeDirReceptor receptor,
FeDirFiscal dirFiscal, FeExpedidoEn expedido, FeLugarEntrega lugar,
FeSumario sumario, List<FeDetalle> detalle) throws AdendaException;
}
|
package com.goldenasia.lottery.app;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.goldenasia.lottery.BuildConfig;
import com.goldenasia.lottery.R;
import com.goldenasia.lottery.base.Preferences;
import com.goldenasia.lottery.base.net.RestRequestManager;
import com.goldenasia.lottery.fragment.GoldenLoginFragment;
import com.goldenasia.lottery.util.WindowUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by Alashi on 2016/1/12.
*/
public class MainActivity extends AppCompatActivity
{
private static final int REQUEST_CODE = 1001;
/**
* 在cache与BuildConfig.VERSION_CODE版本不一致时,需要重新登录
*/
private static Boolean isSameVersion;
@BindView(R.id.count_down)
TextView countDown;
private CountDownTimer countDownTimer;
private int count = 3;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
WindowUtils.hideSystemUI(this);
countDown.setTextColor(ContextCompat.getColor(this, R.color.white));
countDownTimer = new CountDownTimer(4000, 1000)
{
@Override
public void onTick(long l)
{
countDown.setText("跳过" + count--);
}
@Override
public void onFinish()
{
skip();
}
};
countDownTimer.start();
PushAgent.getInstance(this).onAppStart();
}
private void skip()
{
if (!isInSameVersion())
{
GoldenAsiaApp.getUserCentre().logout();
RestRequestManager.cancelAll();
Preferences.saveInt(MainActivity.this, "app-version-code", BuildConfig.VERSION_CODE);
isSameVersion = true;
}
if (GoldenAsiaApp.getUserCentre().isLogin())
{
startActivityForResult(new Intent(MainActivity.this, ContainerActivity.class), REQUEST_CODE);
} else
{
FragmentLauncher.launchForResult(MainActivity.this, GoldenLoginFragment.class.getName(), null,
REQUEST_CODE);
}
}
@Override
protected void onResume()
{
super.onResume();
MobclickAgent.onResume(this);
}
@Override
protected void onPause()
{
super.onPause();
MobclickAgent.onPause(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
finish();
}
public boolean isInSameVersion()
{
if (isSameVersion == null)
{
isSameVersion = Preferences.getInt(this, "app-version-code", 0) == BuildConfig.VERSION_CODE;
}
return isSameVersion;
}
@OnClick(R.id.count_down)
public void onClick()
{
countDownTimer.cancel();
skip();
}
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neuro4j.studio.core;
import java.util.List;
import org.neuro4j.workflow.node.WorkflowNode;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Standard Node</b></em>'.
* <!-- end-user-doc -->
*
*
* @see org.neuro4j.studio.core.Neuro4jPackage#getStandardNode()
* @model
* @generated
*/
public interface StandardNode extends ActionNode {
public static final int X_OFFSET = 15;
public static final int Y_OFFSET = 17;
public int getType();
public void setType(int type);
public List<KeyValuePair> getProperties();
public void addProperty(String key, String value);
public void addConnection(WorkflowNode node);
public List getRepresentations();
} // StandardNode
|
package com.xmzj.common.Enums;
/**
* 菜单相关变量
* @author
*
*/
public enum PermissionPermission {
// type_sys_permission("0","-1","系统菜单功能类型"),
// type_sys_button("1","-1","系统按钮功能类型"),
// type_op_permission("2","-1","运营商菜单功能类型"),
// type_op_button("3",null,"运营商按钮功能类型"),
code_sysmanage("1000","-1","系统管理"),
code_rolemanage("1010","1000","角色管理"),
code_rolemanage_query("1011","1010","查询"),
code_rolemanage_add("1012","1010","新增"),
code_rolemanage_update("1013","1010","修改"),
code_rolemanage_del("1014","1010","删除"),
code_rolemanage_set("1015","1010","分配权限"),
code_sys_usermanage("1030","1000","用户管理"),
code_sys_usermanage_query("1031","1030","查询"),
code_sys_usermanage_add("1032","1030","新增"),
code_sys_usermanage_update("1033","1030","修改"),
code_sys_usermanage_del("1034","1030","删除"),
code_sys_usermanage_reset("1035","1030","修改密码"),
code_user_manage("10400","-1","用户管理"),
code_user_manage_rider("10410","10400","骑手管理(hub或餐馆)"),
code_user_manage_rider_query("10411","10410","查询"),
code_user_manage_rider_pass("10412","10410","审核通过"),
code_user_manage_rider_nopass("10413","10410","审核不通过"),
code_user_manage_rider_del("10414","10410","删除"),
code_user_manage_chef("10420","10400","厨师管理"),
code_user_manage_chef_query("10421","10420","查询"),
code_user_manage_chef_add("10422","10420","新增"),
code_user_manage_chef_edit("10423","10420","修改"),
code_user_manage_chef_del("10424","10420","删除"),
code_user_manage_chef_frozen("10425","10420","冻结/解冻"),
code_user_manage_riderlist("10430","10400","骑手列表(平台)"),
code_user_manage_riderlist_query("10431","10430","查询"),
code_user_manage_riderlist_pass("10432","10430","通过"),
code_user_manage_riderlist_nopass("10433","10430","未通过"),
code_user_manage_riderlist_fulltime("10434","10430","全/兼职"),
code_user_manage_riderlist_frozen("10435","10430","冻结/解冻"),
code_user_manage_riderlis_del("10436","10430","删除"),
code_team_manage_sys("10500","-1","团队管理"),
code_team_manage("10510","10500","团队管理"),
code_team_manage_query("10511","10510","查询"),
code_team_manage_add("10512","10510","新增"),
code_team_manage_edit("10513","10510","修改"),
code_team_manage_del("10514","10510","删除"),
code_team_manage_frozen("10515","10510","冻结/解冻"),
code_team_dishmenu("10520","10500","团队菜单管理"),
code_team_dishmenu_query("10521","10520","查询"),
code_team_dishmenu_add("10522","10520","新增"),
code_team_dishmenu_edit("10523","10520","修改"),
code_team_dishmenu_del("10524","10520","删除"),
code_discount_sys("10530","10500","折扣管理"),
code_discount_query("10531","10530","查询"),
code_discount_add("10532","10530","新增"),
code_discount_edit("10533","10530","修改"),
code_discount_del("10534","10530","删除"),
code_ad_manage("10600","-1","广告管理"),
code_ad_query("10601","10600","查询"),
code_ad_add("10602","10600","新增"),
code_ad_edit("10603","10600","修改"),
code_ad_del("10604","10600","删除"),
//订单
code_order_manage_sys("10700","-1","订单管理"),
code_order_manage("10710","10700","订单管理"),
code_order_query("10711","10710","查询"),
code_order_send("10712","10710","派单"),
code_order_del("10713","10710","删除"),
//餐厅
code_restaurant_manage_sys("10800","-1","餐厅管理"),
code_restaurant_join("10810","10800","加盟餐厅"),
code_restaurant_join_query("10811","10810","查询"),
code_restaurant_join_add("10812","10810","新增"),
code_restaurant_join_edit("10813","10810","修改"),
code_restaurant_join_del("10814","10810","删除"),
code_restaurant_join_frozen("10815","10810","冻结/解冻"),
code_restaurant_nomnom("10820","10800","nom-nom"),
code_restaurant_nomnom_query("10821","10820","查看"),
code_restaurant_nomnom_save("10822","10820","保存"),
code_restaurant_join_self("10830","10800","餐厅"),
code_restaurant_join_self_query("10831","10830","查看"),
code_restaurant_join_self_save("10832","10830","保存"),
//配送中心
code_dc_manage_sys("10900","-1","配送中心"),
code_dc("10910","10900","配送中心"),
code_dc_query("10911","10910","查询"),
code_dc_add("10912","10910","新增"),
code_dc_edit("10913","10910","修改"),
code_dc_del("10914","10910","删除"),
code_dc_frozen("10915","10910","冻结/解冻"),
//商品管理
code_goods_manage_sys("11000","-1","商品管理"),
code_dish("11100","11000","菜品管理"),
code_dish_query("11101","11100","查询"),
code_dish_add("11102","11100","新增"),
code_dish_edit("11103","11100","修改"),
code_dish_del("11104","11100","删除"),
code_dish_putaway("11105","11100","上/下架"),
code_dish_meterial("11106","11100","编辑食材"),
code_material("11200","11000","食材管理"),
code_material_query("11201","11200","查询"),
code_material_add("11202","11200","新增"),
code_material_edit("11203","11200","修改"),
code_material_del("11204","11200","删除"),
code_material_putaway("11205","11200","上/下架"),
code_dish_store("11300","11000","菜品库存"),
code_dish_store_query("11301","11300","查询"),
code_dish_store_add("11302","11300","新增"),
code_dish_store_edit("11303","11300","修改"),
code_dish_store_del("11304","11300","删除"),
code_material_store("11400","11000","食材库存"),
code_material_store_query("11401","11400","查询"),
code_material_store_add("11402","11400","新增"),
code_material_store_edit("11403","11400","修改"),
code_material_store_del("11404","11400","删除"),
//分类管理
code_tags_manage_sys("12000","-1","分类管理"),
code_dish_type("12100","12000","菜品分类"),
code_dish_type_query("12101","12100","查询"),
code_dish_type_add("12102","12100","新增"),
code_dish_type_edit("12103","12100","修改"),
code_dish_type_del("12104","12100","删除"),
code_material_type("12200","12000","食材分类"),
code_material_type_query("12201","12200","查询"),
code_material_type_add("12202","12200","新增"),
code_material_type_edit("12203","12200","修改"),
code_material_type_del("12204","12200","删除"),
code_restaurant_type("12300","12000","餐厅分类"),
code_restaurant_type_query("12301","12300","查询"),
code_restaurant_type_add("12302","12300","新增"),
code_restaurant_type_edit("12303","12300","修改"),
code_restaurant_type_del("12304","12300","删除"),
code_like_type("12400","12000","偏好分类"),
code_like_type_query("12401","12400","查询"),
code_like_type_add("12402","12400","新增"),
code_like_type_edit("12403","12400","修改"),
code_like_type_del("12404","12400","删除"),
code_member_sys("13000","-1","会员管理"),
code_member("13100","13000","会员管理"),
code_member_query("13101","13100","查询"),
code_member_frozen("13102","13100","冻结/解冻"),
code_member_giftcard("13200","13000","礼品卡"),
code_member_giftcard_query("13201","13200","查询"),
code_daliy_menu_sys("14000","-1","每日菜单"),
code_daliy_menu("14100","14000","每日菜单管理"),
code_daliy_menu_query("14101","14100","查询"),
code_daliy_menu_add("14102","14100","新增"),
code_daliy_menu_edit("14103","14100","编辑"),
code_daliy_menu_del("14104","14100","删除"),
code_message_sys("15000","-1","消息推送"),
code_message("15100","15000","消息推送"),
code_message_query("15101","15100","查询"),
code_message_add("15102","15100","新增"),
code_message_edit("15103","15100","编辑"),
code_message_del("15104","15100","删除"),
;
private String pkid;
private String parent;
private String desc;
private PermissionPermission(String value,String parent,String desc) {
this.pkid = value;
this.desc=desc;
this.parent=parent;
}
public String getDesc() {
return desc;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getPkid() {
return pkid;
}
public void setPkid(String pkid) {
this.pkid = pkid;
}
public void setDesc(String desc) {
this.desc = desc;
}
public static PermissionPermission setValue(String str) {
for (PermissionPermission e:PermissionPermission.values()) {
if(e.getPkid().equals(str)){
return e;
}
}
return null;
}
}
|
package dk.stfkbf;
import java.io.File;
public class DeleteChangedCase {
private String targetPath;
private String sourcePath;
private String gitRoot;
public String getTargetPath() {
return targetPath;
}
public void setTargetPath(String targetPath) {
this.targetPath = targetPath;
}
public String getSourcePath() {
return sourcePath;
}
public void setSourcePath(String sourcePath) {
this.sourcePath = sourcePath;
}
public String getGitRoot() {
return gitRoot;
}
public void setGitRoot(String gitRoot) {
this.gitRoot = gitRoot;
}
public static void main(String[] args){
DeleteChangedCase files = new DeleteChangedCase();
System.out.println("Checking for case changes");
files.setSourcePath(args[0]);
files.setTargetPath(args[1]);
files.setGitRoot(args[2]);
files.execute();
}
public void execute(){
try {
traverse(new File(this.getTargetPath()));
} catch (Exception e){
e.printStackTrace();
}
}
public void traverse(File file) throws Exception{
File targetDir = file;
File sourcePath = new File(this.getSourcePath());
File targetPath = new File(this.getTargetPath());
if (file.exists()){
for (String currentFile : targetDir.list()){
File targetFile = new File(targetDir, currentFile);
File sourceFile = new File(targetFile.getAbsolutePath().replace(targetPath.getAbsolutePath(), sourcePath.getAbsolutePath()));
if (!targetFile.getCanonicalFile().getName().equals(sourceFile.getCanonicalFile().getName())){
System.out.println("Casing changed: " + targetFile.getName() + " " + sourceFile.getName());
targetFile.delete();
}
if (targetFile.isDirectory()){
traverse(targetFile);
}
}
}
}
}
|
//Program to Check if a Given String is Palindrome
public class Palindrome {
public static boolean stringpalindome(String str) {
for(int i=0;i<str.length();i++) {
for(int j=str.length()-1;j>=0;j--) {
if(str.charAt(i)==str.charAt(j))
{
return true;
}
else {
return false;
}
} }
return false;
}
public static void main(String args[]) {
String str="abba";
System.out.println("the string is palindrome : "+stringpalindome(str));
}
}
|
package com.flower.api;
import com.alibaba.druid.pool.DruidDataSource;
import com.flower.common.utils.LoggerUtil;
import com.flower.core.dao.builder.ReVFS;
import com.flower.core.dao.interceptors.PagePluginInterceptor;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"com.flower.**.dao"}, sqlSessionFactoryRef = "druidSqlSessionFactory")
public class DruidDBConfig implements EnvironmentAware {
// static final String PACKAGE = "com.fengshang.common.dao.impl,com.fengshang.biz.information.dao.impl";
private String dbUrl;
private String username;
private String password;
private String typeAliasesPackage;
private String mapperLocations;
private RelaxedPropertyResolver propertyResolver;
@Override
public void setEnvironment(Environment env) {
this.propertyResolver = new RelaxedPropertyResolver(env);
this.dbUrl = propertyResolver.getProperty("spring.druid.datasource.url");
this.username = propertyResolver.getProperty("spring.druid.datasource.username");
this.password = propertyResolver.getProperty("spring.druid.datasource.password");
this.mapperLocations = propertyResolver.getProperty("mybatis.mapperLocations");
this.typeAliasesPackage = propertyResolver.getProperty("mybatis.typeAliasesPackage");
}
@Bean(name="druidDataSource") //声明其为Bean实例
@Primary //在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource(){
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName("com.mysql.jdbc.Driver");
//configuration
datasource.setInitialSize(5);
datasource.setMinIdle(5);
datasource.setMaxActive(20);
datasource.setMaxWait(60000);
datasource.setTimeBetweenEvictionRunsMillis(60000);
datasource.setMinEvictableIdleTimeMillis(300000);
datasource.setValidationQuery("SELECT 'x'");
datasource.setTestWhileIdle(true);
datasource.setTestOnBorrow(false);
datasource.setTestOnReturn(false);
datasource.setPoolPreparedStatements(false);
datasource.setMaxPoolPreparedStatementPerConnectionSize(20);
try {
datasource.setFilters("stat,wall,slf4j");
} catch (SQLException e) {
LoggerUtil.error(this.getClass(), e);
}
datasource.setConnectionProperties("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000");
return datasource;
}
@Bean(name = "druidTransactionManager")
@Primary
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean(name = "druidSqlSessionFactory")
// @Primary
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("druidDataSource") DataSource masterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(masterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(mapperLocations));
sessionFactory.setVfs(ReVFS.class);
VFS.addImplClass(ReVFS.class);
sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
PagePluginInterceptor pageHelper = new PagePluginInterceptor();
Properties props = new Properties();
props.setProperty("dialect", "mysql");
props.setProperty("pageSqlId", ".*istPage*");
pageHelper.setProperties(props);
// AutoMapperInterceptor mapperHelper = new AutoMapperInterceptor();
//
// ResultTypeInterceptor resultTypeInterceptor = new ResultTypeInterceptor();
// sessionFactory.setPlugins(new Interceptor[]{pageHelper, mapperHelper, resultTypeInterceptor});
// MybatisPlugin mybatisPlugin = new MybatisPlugin();
// sessionFactory.setPlugins(new Interceptor[]{mybatisPlugin, resultTypeInterceptor});
sessionFactory.setPlugins(new Interceptor[]{pageHelper});
return sessionFactory.getObject();
}
public String getDbUrl() {
return dbUrl;
}
public void setDbUrl(String dbUrl) {
this.dbUrl = dbUrl;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
package org.crazyit.cloud;
import java.io.IOException;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
public class Receive {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
String queueName = "hello";
//将consumer和channel绑定 ?
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body, "UTF-8");
System.out.println("接收到的消息:" + msg);
}
};
//消费指定queueName里的消息,是通过上面自定义的DefaultConsumer.handleDelivery方法消费
channel.basicConsume(queueName, consumer);
//如果不close的话,会一直定期去queue里取message
// channel.close();
// conn.close();
}
}
|
package com.mingrisoft;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.Timer;
public class AlarmClock {
private int delay;
private boolean flag;
public AlarmClock(int delay, boolean flag) {
this.delay = delay;
this.flag = flag;
}
public void start() {
class Printer implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
SimpleDateFormat format = new SimpleDateFormat("k:m:s");
String result = format.format(new Date());
System.out.println("当前的时间是:" + result);
if (flag) {
Toolkit.getDefaultToolkit().beep();
}
}
}
new Timer(delay, new Printer()).start();
}
}
|
package com.bcq.oklib.utils;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import java.util.ArrayList;
public class PermissionHelper {
public final static int REQUEST_CODE = 1000;
// group:android.permission-group.CONTACTS
// permission:android.permission.WRITE_CONTACTS
// permission:android.permission.GET_ACCOUNTS
// permission:android.permission.READ_CONTACTS
//
// group:android.permission-group.PHONE
// permission:android.permission.READ_CALL_LOG
// permission:android.permission.READ_PHONE_STATE
// permission:android.permission.CALL_PHONE
// permission:android.permission.WRITE_CALL_LOG
// permission:android.permission.USE_SIP
// permission:android.permission.PROCESS_OUTGOING_CALLS
// permission:com.android.voicemail.permission.ADD_VOICEMAIL
//
// group:android.permission-group.CALENDAR
// permission:android.permission.READ_CALENDAR
// permission:android.permission.WRITE_CALENDAR
//
// group:android.permission-group.CAMERA
// permission:android.permission.CAMERA
//
// group:android.permission-group.SENSORS
// permission:android.permission.BODY_SENSORS
//
// group:android.permission-group.LOCATION
// permission:android.permission.ACCESS_FINE_LOCATION
// permission:android.permission.ACCESS_COARSE_LOCATION
//
// group:android.permission-group.STORAGE
// permission:android.permission.READ_EXTERNAL_STORAGE
// permission:android.permission.WRITE_EXTERNAL_STORAGE
//
// group:android.permission-group.MICROPHONE
// permission:android.permission.RECORD_AUDIO
// group:android.permission-group.SMS
// permission:android.permission.READ_SMS
// permission:android.permission.RECEIVE_WAP_PUSH
// permission:android.permission.RECEIVE_MMS
// permission:android.permission.RECEIVE_SMS
// permission:android.permission.SEND_SMS
// permission:android.permission.READ_CELL_BROADCASTS
public final static String[] PERMISSIONS = new String[]{
Manifest.permission.READ_CALENDAR,//日历
Manifest.permission.WRITE_CALENDAR,
Manifest.permission.CAMERA,//相机
Manifest.permission.READ_CONTACTS,//联系人
Manifest.permission.WRITE_CONTACTS,
Manifest.permission.GET_ACCOUNTS,
Manifest.permission.LOCATION_HARDWARE,//定位
Manifest.permission.RECORD_AUDIO,//麦克相关
Manifest.permission.CALL_PHONE,//手机状态
Manifest.permission.READ_CALL_LOG,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.BODY_SENSORS, //传感器
Manifest.permission.READ_EXTERNAL_STORAGE, //存储权限
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_SMS,//短信
Manifest.permission.SEND_SMS,
};
public static void checkPermissions(Activity activity, String[] permissions) {
try {
if (Build.VERSION.SDK_INT >= 23) {
ArrayList<String> requestPerssions = new ArrayList<>();
int len = permissions.length;
for (String permission : permissions) {
if (PackageManager.PERMISSION_GRANTED != activity.checkSelfPermission(permission)) {
requestPerssions.add(permission);
}
}
int size = requestPerssions.size();
if (size > 0) {
activity.requestPermissions(requestPerssions.toArray(new String[size]), REQUEST_CODE);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void checkPermission(Activity activity, String permission, int requestCode) {
try {
if (Build.VERSION.SDK_INT >= 23) {
if (PackageManager.PERMISSION_GRANTED != activity.checkSelfPermission(permission)) {
activity.requestPermissions(new String[]{permission}, requestCode);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取拒绝权限
* @param context
* @param permissions
* @return
*/
public static String[] getDeniedPermissions(Context context, String[] permissions){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ArrayList<String> deniedPermissionList = new ArrayList<>();
for(String permission : permissions){
if(context.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED){
deniedPermissionList.add(permission);
}
}
int size = deniedPermissionList.size();
if(size > 0){
return deniedPermissionList.toArray(new String[size]);
}
}
return null;
}
}
|
package com.cn.ouyjs.controller;
import com.cn.ouyjs.service.TestService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author ouyjs
* @date 2019/8/14 20:26
*/
@RestController
@RequestMapping("/test")
public class TestController {
@Resource
private TestService testService;
@RequestMapping("/Consumer")
public String Consumer(String s){
System.out.println("传入的值为:" + s);
return testService.helloWorld(s);
}
}
|
package exam02.photo;
import java.util.ArrayList;
import java.util.List;
public class PhotoCollection {
List<Photo> photos = new ArrayList<>();
public void addPhoto(String... photoNames) {
for (String item : photoNames) {
photos.add(new Photo(item));
}
}
public void starPhoto(String photoName, Quality quality) {
boolean founded = false;
for (Photo item : photos) {
if (item.getName().equals(photoName)) {
item.setQuality(quality);
founded = true;
}
}
if (!founded) {
throw new PhotoNotFoundException(photoName + " is not found");
}
}
public int numberOfStars() {
int stars = 0;
for (Photo item : photos) {
stars += item.getQuality().getValue();
}
return stars;
}
public List<Photo> getPhotos() {
return new ArrayList<>(photos);
}
}
|
package ch.zuehlke.fullstack.hackathon.service;
import ch.zuehlke.fullstack.hackathon.model.Rating;
import ch.zuehlke.fullstack.hackathon.model.Skill;
import ch.zuehlke.fullstack.hackathon.service.http.InsightClient;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
public class SkillService {
private final InsightClient insightClient;
private final RatingService ratingService;
public SkillService(InsightClient insightClient,
RatingService ratingService) {
this.insightClient = insightClient;
this.ratingService = ratingService;
}
public List<Skill> getSkillsWithCalculatedPoints(String userId) {
HashMap<Long, Skill> skillMap = new HashMap<>();
List<Skill> insightSkills = insightClient.getSkills(userId);
insightSkills.forEach(skill -> skillMap.put(skill.getSkillId(), skill));
List<Rating> ratings = ratingService.getRatings(userId);
addPointsFromRatingToSkills(skillMap, ratings);
// add training: each training skill will be rated with +5
return new ArrayList<>(skillMap.values());
}
private void addPointsFromRatingToSkills(HashMap<Long, Skill> skillMap, List<Rating> ratings) {
for (Rating rating : ratings) {
Skill existingSkill = skillMap.get(rating.getSkillId());
if (existingSkill != null) {
existingSkill.addPoints(rating.getPoints());
skillMap.replace(rating.getSkillId(), existingSkill);
}
}
}
}
|
//designpatterns.adapter.PoliceLamp.java
package designpatterns.adapter;
//Ύ―΅Ζΐ࣬³δ΅±ΚΚΕδΥί
public class PoliceLamp {
public void alarmLamp() {
System.out.println("³ΚΟΦΎ―΅ΖΙΑΛΈ£‘");
}
}
|
package bean;
import java.util.Date;
/**
* 采购信息实体
* @author computer
*
*/
public class Procurement {
private int procurementId; // 采购编号
private int adminId; //管理员编号
private int costumeId; // 服装编号,采购时每件服装设为单价的0.7倍
private int supplierId; //供应商编号
private String color; //颜色
private String size; // 尺码
private int qualtity; //数量
private double total; //总金额
private Date createdTime; // 生成日期
public Procurement() {
super();
// TODO Auto-generated constructor stub
}
public Procurement(int procurementId, int adminId, int costumeId) {
super();
this.procurementId = procurementId;
this.adminId = adminId;
this.costumeId = costumeId;
}
public Procurement(int adminId, int costumeId, int supplierId, String color, String size, int qualtity) {
super();
this.adminId = adminId;
this.costumeId = costumeId;
this.supplierId = supplierId;
this.color = color;
this.size = size;
this.qualtity = qualtity;
}
public int getProcurementId() {
return procurementId;
}
public void setProcurementId(int procurementId) {
this.procurementId = procurementId;
}
public int getAdminId() {
return adminId;
}
public void setAdminId(int adminId) {
this.adminId = adminId;
}
public int getCostumeId() {
return costumeId;
}
public void setCostumeId(int costumeId) {
this.costumeId = costumeId;
}
public int getSupplierId() {
return supplierId;
}
public void setSupplierId(int supplierId) {
this.supplierId = supplierId;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public int getQualtity() {
return qualtity;
}
public void setQualtity(int qualtity) {
this.qualtity = qualtity;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
}
|
package ec.edu.upse.dao;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import ec.edu.upse.modelo.TblSgaMateria;
public class MateriaDao extends ClaseDao {
@SuppressWarnings("unchecked")
public List<TblSgaMateria> getMaterias() {
List<TblSgaMateria> retorno = new ArrayList<TblSgaMateria>();
Query query = getEntityManager().createNamedQuery("TblSgaMateria.findAll");
retorno = (List<TblSgaMateria>) query.getResultList();
return retorno;
}
}
|
package gameassignment2;
/**
* Enum representing the GameObject types in the Game.
* @author Sayid Akhundov
*/
public enum ID {
Player,Enemy,Coin,Block,Cherry,Bullet,Hud,Flag;
}
|
package com.symbio.supplier.domains;
import com.symbio.supplier.comparators.StartDateComparator;
import com.symbio.supplier.comparators.EndDateComparator;
import com.symbio.supplier.utils.DateUtils;
import com.symbio.supplier.exceptions.InvalidTimeWindowException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
public class Product
{
private final String name;
private final List<Material> materials;
public Product(String name, List<Material> materials)
{
this.name = name;
this.materials = materials;
}
public String calculateStartDate(CombinedMaterials combinedMaterials)
{
Collections.sort(combinedMaterials.getMaterialSupplyDetails(), new StartDateComparator());
return combinedMaterials.getMaterialSupplyDetails().get(0).getStartDate();
}
public String calculateEndDate(CombinedMaterials combinedMaterials)
{
Collections.sort(combinedMaterials.getMaterialSupplyDetails(), new EndDateComparator());
return combinedMaterials.getMaterialSupplyDetails().get(0).getEndDate();
}
public int calculateSupplyAmount(CombinedMaterials combinedMaterials)
{
checkValidTimeWindow(combinedMaterials);
List<Integer> amountList = new ArrayList<Integer>();
for (Material material : materials) {
for (MaterialSupplyDetail materialSupplyDetail : combinedMaterials.getMaterialSupplyDetails()) {
if (material.getMaterialCategory().hasContains(materialSupplyDetail)) {
amountList.add(materialSupplyDetail.getAmount() / material.getAmount());
}
}
}
Collections.sort(amountList);
return amountList.get(0);
}
private void checkValidTimeWindow(CombinedMaterials combinedMaterials)
{
Date startDate = DateUtils.strToDate(calculateStartDate(combinedMaterials));
Date endDate = DateUtils.strToDate(calculateEndDate(combinedMaterials));
if(startDate.after(endDate)){
throw new InvalidTimeWindowException();
}
}
public String getName()
{
return name;
}
public List<CombinedMaterials> getPossibleCombinationOfMaterials()
{
int total = 1;
for(int i = 0; i < materials.size(); i++){
total *= materials.get(i).getMaterialSupplyDetails().size();
}
CombinedMaterials[] result = new CombinedMaterials[total];
int current = 1;
int loopNumPerMaterialDetails;
int loopNumPerMaterialCategory;
for (int i = 0; i < materials.size(); i++){
List<MaterialSupplyDetail> currentMaterialSupplyDetails = materials.get(i).getMaterialSupplyDetails();
current = current * currentMaterialSupplyDetails.size();
int index = 0;
int currentSize = currentMaterialSupplyDetails.size();
loopNumPerMaterialDetails = total / current;
loopNumPerMaterialCategory = total / (loopNumPerMaterialDetails * currentSize);
int currentIndex = 0;
for (int j = 0; j < currentMaterialSupplyDetails.size(); j++){
for (int k = 0; k < loopNumPerMaterialCategory; k++){
if (currentIndex == currentMaterialSupplyDetails.size()){
currentIndex = 0;
}
for (int m = 0; m < loopNumPerMaterialDetails; m++){
if (result[index] == null){
result[index] = new CombinedMaterials(new ArrayList<MaterialSupplyDetail>());
}
result[index] = result[index].add(currentMaterialSupplyDetails.get(currentIndex));
index++;
}
currentIndex++;
}
}
}
return Arrays.asList(result);
}
}
|
package rpc;
public class Utils {
public static final String OPERATION_SESSION_READ = "read";
public static final String OPERATION_SESSION_WRITE = "write";
public static final String OPERATION_SESSION_CREATE_NEW ="create";
public static final String NOT_FOUND = "not found";
public static final int PROJECT1_PORT_NUMBER = 5300;
public static final int MAX_PACKET_LENGTH = 512;
public static final String SPLITTER = "_";
public static final String DOMAIN_NAME = ".cs2238.bigdata.systems";
//need to figure out where to get these information, may be from simpleDB
public static final int N = 3;
public static final int W = 3;
public static final int WQ = 3;
public static final int R = 1;
public static final String DATE_TIME_FORMAT = "EEE MMM dd HH:mm:ss z yyyy"; //"HH:mm:ss";
public static final String[] RESPONSE_FLAGS_READING = new String[]{"SUCCESS", "TIME_OUT", "WRONG_FOUND_VERSION", "NOT_FOUND"};
public static final String[] RESPONSE_FLAGS_WRITING = new String[] {"SUCCESS", "WRITING_FAILED","TIME_OUT"};
}
|
package com.software1605.androidtraining.adapotr;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.software1605.androidtraining.R;
import com.software1605.androidtraining.entity.Text;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class TextAdaport extends ArrayAdapter<Text> {
String IMG_URL_HTTP="http://wxscjy.free.ngrok.cc/";
private CircleImageView imageView;
private TextView title;
private TextView contennt;
private int resourcesId;
public TextAdaport(@NonNull Context context, int textViewResourceId, List<Text> objects) {
super(context,textViewResourceId,objects);
resourcesId = textViewResourceId;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Text text = getItem(position);
View view = LayoutInflater.from(getContext()).inflate(resourcesId,null);
imageView = view.findViewById(R.id.ivImage);
title = view.findViewById(R.id.tvTittle);
contennt = view.findViewById(R.id.tvContent);
//从网络获取远程图片数据
Glide.with(getContext()).load(IMG_URL_HTTP+text.getImgUrl()).into(imageView);
title.setText(text.getTitle());
contennt.setText(text.getContent());
return view;
}
}
|
package com.teamdev.business.impl;
import com.teamdev.business.ChatRoomService;
import com.teamdev.business.impl.dto.ChatRoomDTO;
import com.teamdev.business.impl.exception.AuthenticationException;
import com.teamdev.business.impl.exception.ChatRoomAlreadyExistsException;
import com.teamdev.business.impl.exception.ChatRoomNotFoundException;
import com.teamdev.business.impl.exception.UserNotFoundException;
import com.teamdev.business.impl.dto.ChatRoomId;
import com.teamdev.business.impl.dto.Token;
import com.teamdev.business.impl.dto.UserId;
import com.teamdev.persistence.ChatRoomRepository;
import com.teamdev.persistence.UserRepository;
import com.teamdev.persistence.dom.ChatRoom;
import com.teamdev.persistence.dom.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
@Service
public class ChatRoomServiceImpl implements ChatRoomService {
@Autowired
private ChatRoomRepository chatRoomRepository;
@Autowired
private UserRepository userRepository;
public ChatRoomServiceImpl() {
}
public ChatRoomDTO create(String chatRoomName) throws ChatRoomAlreadyExistsException {
if (chatRoomRepository.chatRoomCount() > 0 && chatRoomRepository.findByName(chatRoomName) != null) {
throw new ChatRoomAlreadyExistsException("ChatRoom with the same name already exists.");
}
ChatRoom chatRoom = new ChatRoom(chatRoomName);
chatRoomRepository.update(chatRoom);
return new ChatRoomDTO(chatRoom.getId(), chatRoom.getName(), 0, 0);
}
public void joinToChatRoom(Token token,
UserId userId,
ChatRoomId chatRoomId)
throws AuthenticationException, UserNotFoundException, ChatRoomNotFoundException {
ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId.id);
User user = userRepository.findById(userId.id);
if (user == null) {
throw new UserNotFoundException(String.format("User with this id [%d] not exists.", userId.id));
}
if (chatRoom == null) {
throw new ChatRoomNotFoundException(String.format("ChatRoom with this id [%d] not exists.", chatRoomId.id));
}
user.getChatRooms().add(chatRoom);
chatRoom.getUsers().add(user);
}
public void leaveChatRoom(Token token,
UserId userId,
ChatRoomId chatRoomId)
throws AuthenticationException, ChatRoomNotFoundException {
User user = userRepository.findById(userId.id);
if (user == null) {
return;
}
ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId.id);
if (chatRoom == null) {
throw new ChatRoomNotFoundException(String.format("ChatRoom with this id [%d] not exists.", chatRoomId.id));
}
user.getChatRooms().remove(chatRoom);
chatRoom.getUsers().remove(user);
}
@Override
public Collection<ChatRoomDTO> findAll() {
Collection<ChatRoom> chatRooms = chatRoomRepository.findAll();
Collection<ChatRoomDTO> chatRoomDTOs = new ArrayList<>();
for (ChatRoom chat : chatRooms) {
chatRoomDTOs.add(new ChatRoomDTO(chat.getId(), chat.getName(), chat.getUsers().size(), chat.getMessages().size()));
}
return chatRoomDTOs;
}
}
|
package datastructure;
public class CSLL {
private Node head;
private Node tail;
private int size;
public void insertAtStart(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
tail.next = head;
size++;
return;
}
newNode.next = head;
head = newNode;
tail.next = head;
size++;
}
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
tail.next = head;
size++;
return;
}
tail.next = newNode;
tail = newNode;
tail.next = head;
size++;
}
public void insertAt(int data, int index) throws Exception {
if (index > size) {
throw new Exception("Not Valid Index. Max index can be " + size);
}
if (index == 0) {
insertAtStart(data);
return;
} else if (index == size) {
insertAtEnd(data);
return;
}
Node newNode = new Node(data);
Node tempHead = head;
int i = 1;
while (i < index) {
tempHead = tempHead.next;
i++;
}
newNode.next = tempHead.next;
tempHead.next = newNode;
size++;
}
public void deleteAtStart() {
if (head == null) {
System.out.println("Cant delete. List is Empty");
return;
}
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
tail.next = head;
}
size--;
}
public void deleteAtEnd() {
if (head == null) {
System.out.println("Cant delete. List is Empty");
return;
}
if (head == tail) {
head = null;
tail = null;
}
Node tempHead = head;
int i = 1;
while (i < size - 1) {
tempHead = tempHead.next;
i++;
}
tempHead.next = null;
tail = tempHead;
tail.next = head;
size--;
}
public void deleteAt(int index) throws Exception {
if (index >= size) {
throw new Exception("Not Valid Index. Max index can be " + (size - 1));
}
if (index == 0) {
deleteAtStart();
return;
} else if (index == size - 1) {
deleteAtEnd();
return;
}
Node tempHead = head;
int i = 1;
while (i < index) {
tempHead = tempHead.next;
i++;
}
tempHead.next = tempHead.next.next;
size--;
}
public boolean search(int data) {
Node tempHead = head;
while (tempHead != null) {
if (tempHead.data == data)
return true;
if (tempHead == tail)
break;
tempHead = tempHead.next;
}
return false;
}
public void display() {
Node tempHead = head;
while (tempHead != null) {
System.out.print(tempHead.data + " --> ");
if (tempHead == tail)
break;
tempHead = tempHead.next;
}
System.out.println("NULL");
}
public int size() {
return size;
}
public static void main(String[] args) throws Exception {
CSLL list = new CSLL();
System.out.println("INSERTING");
list.insertAtStart(7);
list.insertAtStart(6);
list.display();
System.out.println("Found 10 : " + list.search(10));
System.out.println(list.size());
list.insertAtEnd(100);
list.insertAtEnd(101);
list.display();
System.out.println("Found 10 : " + list.search(10));
System.out.println(list.size());
list.insertAt(10, 2);
list.insertAt(11, 3);
list.display();
System.out.println("Found 10 : " + list.search(10));
System.out.println(list.size());
// list.insertAt(44, 40);
// *********************************************************
System.out.println("DELETING");
list.deleteAtStart();
list.display();
System.out.println("Found 101 : " + list.search(101));
System.out.println(list.size());
list.deleteAtEnd();
list.display();
System.out.println("Found 101 : " + list.search(101));
System.out.println(list.size());
list.deleteAt(2);
list.display();
System.out.println("Found 101 : " + list.search(101));
System.out.println(list.size());
list.deleteAt(40);
}
}
|
package com.pdd.pop.sdk.http.api.request;
import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty;
import com.pdd.pop.sdk.http.api.response.PddStockDepotPriorityUpdateResponse;
import com.pdd.pop.sdk.http.HttpMethod;
import com.pdd.pop.sdk.http.PopBaseHttpRequest;
import com.pdd.pop.sdk.common.util.JsonUtil;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class PddStockDepotPriorityUpdateRequest extends PopBaseHttpRequest<PddStockDepotPriorityUpdateResponse>{
/**
* 示例:[{"depot_id":1,"province_id":12,"city_id":34,"district_id":56,"priority":5}]
*/
@JsonProperty("priority_list")
private List<PriorityListItem> priorityList;
@Override
public String getVersion() {
return "V1";
}
@Override
public String getDataType() {
return "JSON";
}
@Override
public String getType() {
return "pdd.stock.depot.priority.update";
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
public Class<PddStockDepotPriorityUpdateResponse> getResponseClass() {
return PddStockDepotPriorityUpdateResponse.class;
}
@Override
public Map<String, String> getParamsMap() {
Map<String, String> paramsMap = new TreeMap<String, String>();
paramsMap.put("version", getVersion());
paramsMap.put("data_type", getDataType());
paramsMap.put("type", getType());
paramsMap.put("timestamp", getTimestamp().toString());
if(priorityList != null) {
paramsMap.put("priority_list", priorityList.toString());
}
return paramsMap;
}
public void setPriorityList(List<PriorityListItem> priorityList) {
this.priorityList = priorityList;
}
public static class PriorityListItem {
/**
* 优先级 范围是1 - 999
*/
@JsonProperty("priority")
private Integer priority;
/**
* 区id
*/
@JsonProperty("district_id")
private Integer districtId;
/**
* 市id
*/
@JsonProperty("city_id")
private Integer cityId;
/**
* 省id
*/
@JsonProperty("province_id")
private Integer provinceId;
/**
* 仓库id
*/
@JsonProperty("depot_id")
private Long depotId;
public void setPriority(Integer priority) {
this.priority = priority;
}
public void setDistrictId(Integer districtId) {
this.districtId = districtId;
}
public void setCityId(Integer cityId) {
this.cityId = cityId;
}
public void setProvinceId(Integer provinceId) {
this.provinceId = provinceId;
}
public void setDepotId(Long depotId) {
this.depotId = depotId;
}
@Override
public String toString() {
return JsonUtil.transferToJson(this);
}
}
}
|
package com.whoisericballard.gsenchants.enchants;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Arrow.PickupRule;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import com.whoisericballard.gsenchants.Enchantment;
import com.whoisericballard.gsenchants.EnchantmentType.Enchantments;
@SuppressWarnings("deprecation")
public class Impartial implements Listener {
// TODO Enchantments.CLOCKWORK (SWORD)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = false)
public void onUseInk(EntityDamageByEntityEvent event) {
if (!(event.getDamager() instanceof Player) || !(event.getEntity() instanceof LivingEntity))
return;
Player player = (Player) event.getDamager();
if (Enchantment.isEnchanted(player.getItemInHand(), player.getLocation()) && Enchantment.getEnchant(player.getItemInHand()).getType() == Enchantments.CLOCKWORK) {
Random r = new Random();
int amp = (ChatColor.stripColor(player.getItemInHand().getItemMeta().getLore().get(0))).split(" ")[1].replace("]", "").trim().length();
if (r.nextInt(100) <= (amp * 10))
for (Entity e : player.getNearbyEntities(2 * amp, 2 * amp, 2 * amp))
if (e instanceof LivingEntity && e.getUniqueId() != player.getUniqueId())
((LivingEntity) e).addPotionEffect(new PotionEffect(PotionEffectType.SLOW, (int) 20, amp));
}
}
// TODO Enchantments.GUARD (ARMOR)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = false)
public void onUseGuard(EntityDamageByEntityEvent event) {
if (!(event.getEntity() instanceof Player) || !(event.getDamager() instanceof LivingEntity))
return;
LivingEntity damager = (LivingEntity) event.getDamager();
Player player = (Player) event.getEntity();
for (ItemStack i : player.getInventory().getArmorContents())
if (Enchantment.isEnchanted(i, player.getLocation()) && Enchantment.getEnchant(i).getType() == Enchantments.GUARD) {
Random r = new Random();
int amp = (ChatColor.stripColor(i.getItemMeta().getLore().get(0))).split(" ")[1].replace("]", "").trim().length();
if (r.nextInt(100) <= 100 / amp) {
damager.damage(event.getDamage() * amp, player);
player.damage(event.getDamage() / 4, damager);
event.setCancelled(true);
}
break;
}
}
// TODO Enchantments.DAZZLE (BOW)
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = false)
public void onUseDazzle(EntityShootBowEvent event) {
if (!(event.getEntity() instanceof Player))
return;
Player player = (Player) event.getEntity();
if (Enchantment.isEnchanted(player.getItemInHand(), player.getLocation()) && Enchantment.getEnchant(player.getItemInHand()).getType() == Enchantments.DAZZLE) {
int amp = (ChatColor.stripColor(player.getItemInHand().getItemMeta().getLore().get(0))).split(" ")[1].replace("]", "").trim().length();
if (!player.getInventory().contains(new ItemStack(Material.GLOWSTONE, amp)))
return;
player.getInventory().remove(new ItemStack(Material.GLOWSTONE, amp));
Arrow arrow = player.getWorld().spawn(event.getProjectile().getLocation(), Arrow.class);
arrow.setPickupRule(PickupRule.DISALLOWED);
arrow.setShooter(player);
arrow.setBounce(false);
arrow.setCritical(true);
arrow.setGlowing(true);
arrow.setVelocity(event.getProjectile().getVelocity());
arrow.setCritical(true);
arrow.setGlowing(true);
}
}
}
|
package moe.tristan.easyfxml.api;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import javafx.stage.Stage;
import moe.tristan.easyfxml.util.Resources;
import moe.tristan.easyfxml.util.Stages;
import io.vavr.control.Try;
/**
* Represents a stylesheet a supplier of Path. What this means is that any protocol is acceptable. Whether it is local
* file-based or remote URI-based.
*
* @see Stages#setStylesheet(Stage, FxmlStylesheet)
*/
public interface FxmlStylesheet {
/**
* @return the CSS file that composes the stylesheet as a {@link Path}. See {@link
* Resources#getResourcePath(String)}
*/
Path getPath();
/**
* This method is a sample implementation that should work in almost all general cases.
* <p>
* An {@link java.io.IOException} can be thrown in very rare cases.
* <p>
* If you encounter them, post an issue with system details.
*
* @return the CSS file in external form (i.e. with the file:/, http:/...) protocol info before it.
*
* @see Resources#getResourceURL(String)
* @see URL#toExternalForm()
*/
default String getExternalForm() {
return Try.of(this::getPath)
.map(Path::toUri)
.mapTry(URI::toURL)
.map(URL::toExternalForm)
.get();
}
}
|
package beans;
public enum Bebida{
REFRIGERANTE(3.50),
AGUA(2.50),
SUCO(4.00),
SEM_BEBIDA(0);
public double valorBebida;
Bebida(double valor){
this.valorBebida = valor;
}
public double getValor() {
return this.valorBebida;
}
}
|
package by.gravity.cinema;
import by.gravity.cinema.acessLayout.TicketAccessLayoutImpl;
import by.gravity.cinema.ticketWindow.AbstractTicketWindow;
public class OctoberTicketWindow extends AbstractTicketWindow {
public static OctoberTicketWindow instance;
public static OctoberTicketWindow getInstance() {
if (instance == null) {
instance = new OctoberTicketWindow();
}
return instance;
}
OctoberTicketWindow() {
super(TicketAccessLayoutImpl.getInstance());
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.inbio.ara.eao.security;
import javax.ejb.Local;
import org.inbio.ara.eao.BaseLocalEAO;
import org.inbio.ara.persistence.taxonomy.UserNomenclaturalGroup;
/**
*
* @author esmata
*/
@Local
public interface UserNomenclaturalGroupEAOLocal extends BaseLocalEAO<UserNomenclaturalGroup,Long>{
public java.util.List<org.inbio.ara.persistence.taxonomy.UserNomenclaturalGroup> getNomenclaturalGroupList(java.lang.Long userId);
}
|
package lang;
import java.lang.Double;
import java.math.BigDecimal;
public class DoubleDemo {
public static void main(String[] args) {
//System.out.println(Long.MAX_VALUE);
//System.out.println(Double.MAX_VALUE);
//System.out.println(Integer.MAX_VALUE);
//System.out.println(Float.MAX_VALUE);
/*
System.out.println(Double.MAX_VALUE);
System.out.println(Double.MIN_VALUE);
System.out.println(Double.NaN);
System.out.println(Double.NEGATIVE_INFINITY);
System.out.println(Double.POSITIVE_INFINITY);
System.out.println();
*/
/*
Double a = new Double (1.2);
Double b = new Double ("3.4");
Double c = Double.valueOf ("5.6");
System.out.System.out.println(a);
System.out.System.out.println(b.toString ()); // System.out.System.out.printlnprint every things
System.out.println(c.toString ());
System.out.println();
System.out.println(b.compareTo (a));
System.out.println();
System.out.println(a.isInfinite ());
System.out.println(Double.isInfinite (123456789.9));
System.out.println(a.isNaN ());
System.out.println(Double.isNaN (123456789.9));
System.out.println();
System.out.println(Double.toString (12.34));
*/
//Long a = 20L;
//Long b = null;
//Double d = a / b;
//Long r = (Long) (a / b);
//Long r = Math.round((double)a / (double)b);
//System.out.println(a + b);
//System.out.println(Double.parseDouble("171"));
/*
System.out.println(Double.parseDouble(" 1 "));
System.out.println(Long.parseLong("1"));
System.out.println(Long.parseLong("1 "));
System.out.println(Long.parseLong(" 1"));
System.out.println(Long.parseLong(" 1 "));
*/
/*
int n = 00002342;
Long a = 00002342L;
System.out.println(n);
System.out.println(Long.parseLong("000002342"));
System.out.println(Long.valueOf("000002342"));
*/
/*
Long l = 0L;
Double d = 1 / l.doubleValue();
System.out.println(d);
System.out.println(Double.isNaN(d));
System.out.println(Double.isInfinite(d));
*/
/*
System.out.println(Long.parseLong("01001"));
String s = "1001.1+";
System.out.println(Double.parseDouble(s.substring(0, s.length() - 1)));
*/
/*
Long n = 0L;
Object[] a = new Object[2];
a[0] = "ABC";
a[1] = 0L;
System.out.println(n == 0L);
System.out.println(a[1] == 0L);
*/
/*
Double d = 100d;
BigDecimal a = new BigDecimal(0);
Double n = d + a.doubleValue();
d = 99.0000001 + 0.9999999;
System.out.println(d == 100d);
System.out.println(d.equals(100d));
System.out.println(d + 0 == 100d);
System.out.println(n == 100d);
*/
Double d = 18.618 + 4.6545;
BigDecimal bd1 = new BigDecimal(18.618);
BigDecimal bd2 = new BigDecimal(4.6545);
BigDecimal bd = bd1.add(bd2);
System.out.println(d);
System.out.println(d.equals(23.2725D));
System.out.println(d == 23.2725D);
System.out.println(d == 23.272499999999997);
System.out.println(bd1);
System.out.println(bd2);
System.out.println(bd);
}
}
|
import java.util.*;
public class Point {
/**
* @param args
*/
public LinkedList<Double> coord;
public GroupePoint groupe;
public Point(){
this.coord=new LinkedList<Double>();
}
// Methode permettant d'affecter un groupe a une point
public void grouper(LinkedList<GroupePoint> g, int paramSim, int puissance){
Distance sim= new Distance();
GroupePoint groupe = g.getFirst();
Double distanceMin=new Double(sim.distance(this, groupe.centre, paramSim, puissance));
for(GroupePoint p : g){
if(sim.distance(p.centre, this, paramSim, puissance) < distanceMin){
distanceMin=sim.distance(p.centre, this, paramSim, puissance);
groupe=p;
System.out.println("Le point en (" + this.coord.get(0) + "," + this.coord.get(1) + ") est attribué au " + groupe.nom );
}
}
this.groupe=groupe;
}
}
|
/*
* Copyright Andrei Goumilevski
* This file licensed under GPLv3 for non commercial projects
* GPLv3 text http://www.gnu.org/licenses/gpl-3.0.html
* For commercial usage please contact me
* gmlvsk2@gmail.com
*
*/
package net.kamradtfamily.mongorest;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class SimpleMongodbServer {
private static final Logger log = Logger.getLogger( SimpleMongodbServer.class.getName() );
// -------------------------------------------
public static void main(String[] args) throws Exception {
Config.init();
// server
Server server = new Server(Config.server_port);
//HandlerCollection handlers = new HandlerList();
AbstractHandler _handler;
ServletContextHandler context_handler = new ServletContextHandler( ServletContextHandler.NO_SESSIONS );
context_handler.setContextPath( "/" );
_handler = context_handler;
server.setHandler( _handler );
Map<String,HttpServlet> servlets = new HashMap<String,HttpServlet>();
servlets.put( "/database/*", new DatabasesServlet() );
servlets.put( "/collection/*", new CollectionsServlet() );
servlets.put( "/index/*", new IndexServlet() );
servlets.put( "/query/*", new QueryServlet() );
servlets.put( "/user/*", new AdminServlet() );
servlets.put( "/distinct/*", new DistinctServlet() );
servlets.put( "/err", new ErrorServlet() );
if( Config.gridfs )
servlets.put( "/gridfs/*", new GridfsServlet() );
//servlets.put( "/exc", new MyExceptionServlet() );
// servlets
for( String path:servlets.keySet() ){
context_handler.addServlet( new ServletHolder(servlets.get(path)), path );
}
context_handler.addServlet( DefaultServlet.class, "/*" );
// output filter
FilterHolder out_filter = new FilterHolder( new OutputFilter() );
context_handler.addFilter( out_filter, "/*", EnumSet.of(DispatcherType.REQUEST) );
// input filter
/*
FilterHolder input_filter = new FilterHolder( new InputFilter() );
context_handler.addFilter( input_filter, "/*", EnumSet.of(DispatcherType.REQUEST) );
*/
Runnable shutdown = new Runnable(){
@Override
public void run(){
log.info( "Shutting server" );
MongoDB.close();
}
};
Runtime.getRuntime().addShutdownHook( new Thread(shutdown) );
server.start();
server.join();
}
}
|
package com.foxshooter.bean;
import java.io.Serializable;
import java.util.Date;
public class Log implements Serializable {
private static final long serialVersionUID = 8606047481640044707L;
public String pid;
public String logId;
public String domainId;
public String personName;
public String personAreaId;
public String personAreaName;
public String personOrgId;
public String personOrgName;
public String personStatusId;
public String personStatus;
public String mainAcctId;
public String mainAcctName;
public String mainAcctStatusId;
public String mainAcctStatus;
public String subAcctId;
public String subAcctName;
public String subAcctStatus;
public String subAcctStatusId;
public String subAcctTypeId;
public String subAcctTypeName;
public String subAcctOrgId;
public String subAcctOrgName;
public String clientName;
public String clientIp;
public String clientMac;
public String clientCpuSerial;
public String clientAreaId;
public String clientAreaName;
public String clientIpSectionId;
public String clientIpSectionName;
public String serverIpSectionId;
public String serverIpSectionName;
public String serverIp;
public String auditTypeId;
public String auditTypeName;
public String auditLevelId;
public String auditLevelName;
public String operateTypeId;
public String operateTypeName;
public String operateContent;
public String operateResult;
public String operateTimeDate;
public String taskNo;
public String isWorkTime;
public String isWorkDay;
public String moduleId;
public String moduleName;
public String objTypeId;
public String objTypeName;
public String personDutyId;
public String personDutyName;
public String actionTypeId;
public String actionTypeName;
public String bankProof;
public String clientNetworkAddress;
public String bankApprove;
public String logSource;
public String isAuthorOthers;
public String ownMainAcctId;
public String ownMainAcctName;
public String ownPersonName;
public String bankflag;
public String bankIsneed;
public String bankIsopen;
public String bankSceneId;
public String bankSceneName;
public String isbinding;
public String fromProvincesId;
public String fromProvincesName;
public String toProvincesId;
public String toProvincesName;
public String goldApprMainAcctId;
public String goldApprPersonName;
public String bankApplyType;
public String bankLastCheckStatus;
public Date bankLastCheckTime;
public String bankLastCheckTimeDate;
public String bankFaiedCheckCount;
public String operateObjectType;
public String auditSubTypeId;
public String auditSubTypeName;
public String isLoginByfoura;
public String roundType;
public Date oriCreateTime;
public String oriCreateTimeDate;
public Date stdCreateTime;
public String stdCreateTimeDate;
public String level2OrgId;
public String level2OrgName;
public String oriFileName;
public String oriFileRownum;
public Date oriGatherTime;
public String oriGatherTimeDate;
public String recheckDataId;
public Date stdBeginTime;
public String stdBeginTimeDate;
public String appMaintainerId;
public String appMaintainer;
public String appImportLevel;
public String sectionIds;
public String sectionNames;
public Date operateTime;
public Date standardizeTime;
public Date indexTime;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getLogId() {
return logId;
}
public void setLogId(String logId) {
this.logId = logId;
}
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public String getPersonAreaId() {
return personAreaId;
}
public void setPersonAreaId(String personAreaId) {
this.personAreaId = personAreaId;
}
public String getPersonAreaName() {
return personAreaName;
}
public void setPersonAreaName(String personAreaName) {
this.personAreaName = personAreaName;
}
public String getPersonOrgId() {
return personOrgId;
}
public void setPersonOrgId(String personOrgId) {
this.personOrgId = personOrgId;
}
public String getPersonOrgName() {
return personOrgName;
}
public void setPersonOrgName(String personOrgName) {
this.personOrgName = personOrgName;
}
public String getPersonStatusId() {
return personStatusId;
}
public void setPersonStatusId(String personStatusId) {
this.personStatusId = personStatusId;
}
public String getPersonStatus() {
return personStatus;
}
public void setPersonStatus(String personStatus) {
this.personStatus = personStatus;
}
public String getMainAcctId() {
return mainAcctId;
}
public void setMainAcctId(String mainAcctId) {
this.mainAcctId = mainAcctId;
}
public String getMainAcctName() {
return mainAcctName;
}
public void setMainAcctName(String mainAcctName) {
this.mainAcctName = mainAcctName;
}
public String getMainAcctStatusId() {
return mainAcctStatusId;
}
public void setMainAcctStatusId(String mainAcctStatusId) {
this.mainAcctStatusId = mainAcctStatusId;
}
public String getMainAcctStatus() {
return mainAcctStatus;
}
public void setMainAcctStatus(String mainAcctStatus) {
this.mainAcctStatus = mainAcctStatus;
}
public String getSubAcctId() {
return subAcctId;
}
public void setSubAcctId(String subAcctId) {
this.subAcctId = subAcctId;
}
public String getSubAcctName() {
return subAcctName;
}
public void setSubAcctName(String subAcctName) {
this.subAcctName = subAcctName;
}
public String getSubAcctStatus() {
return subAcctStatus;
}
public void setSubAcctStatus(String subAcctStatus) {
this.subAcctStatus = subAcctStatus;
}
public String getSubAcctStatusId() {
return subAcctStatusId;
}
public void setSubAcctStatusId(String subAcctStatusId) {
this.subAcctStatusId = subAcctStatusId;
}
public String getSubAcctTypeId() {
return subAcctTypeId;
}
public void setSubAcctTypeId(String subAcctTypeId) {
this.subAcctTypeId = subAcctTypeId;
}
public String getSubAcctTypeName() {
return subAcctTypeName;
}
public void setSubAcctTypeName(String subAcctTypeName) {
this.subAcctTypeName = subAcctTypeName;
}
public String getSubAcctOrgId() {
return subAcctOrgId;
}
public void setSubAcctOrgId(String subAcctOrgId) {
this.subAcctOrgId = subAcctOrgId;
}
public String getSubAcctOrgName() {
return subAcctOrgName;
}
public void setSubAcctOrgName(String subAcctOrgName) {
this.subAcctOrgName = subAcctOrgName;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientIp() {
return clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public String getClientMac() {
return clientMac;
}
public void setClientMac(String clientMac) {
this.clientMac = clientMac;
}
public String getClientCpuSerial() {
return clientCpuSerial;
}
public void setClientCpuSerial(String clientCpuSerial) {
this.clientCpuSerial = clientCpuSerial;
}
public String getClientAreaId() {
return clientAreaId;
}
public void setClientAreaId(String clientAreaId) {
this.clientAreaId = clientAreaId;
}
public String getClientAreaName() {
return clientAreaName;
}
public void setClientAreaName(String clientAreaName) {
this.clientAreaName = clientAreaName;
}
public String getClientIpSectionId() {
return clientIpSectionId;
}
public void setClientIpSectionId(String clientIpSectionId) {
this.clientIpSectionId = clientIpSectionId;
}
public String getClientIpSectionName() {
return clientIpSectionName;
}
public void setClientIpSectionName(String clientIpSectionName) {
this.clientIpSectionName = clientIpSectionName;
}
public String getServerIpSectionId() {
return serverIpSectionId;
}
public void setServerIpSectionId(String serverIpSectionId) {
this.serverIpSectionId = serverIpSectionId;
}
public String getServerIpSectionName() {
return serverIpSectionName;
}
public void setServerIpSectionName(String serverIpSectionName) {
this.serverIpSectionName = serverIpSectionName;
}
public String getServerIp() {
return serverIp;
}
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}
public String getAuditTypeId() {
return auditTypeId;
}
public void setAuditTypeId(String auditTypeId) {
this.auditTypeId = auditTypeId;
}
public String getAuditTypeName() {
return auditTypeName;
}
public void setAuditTypeName(String auditTypeName) {
this.auditTypeName = auditTypeName;
}
public String getAuditLevelId() {
return auditLevelId;
}
public void setAuditLevelId(String auditLevelId) {
this.auditLevelId = auditLevelId;
}
public String getAuditLevelName() {
return auditLevelName;
}
public void setAuditLevelName(String auditLevelName) {
this.auditLevelName = auditLevelName;
}
public String getOperateTypeId() {
return operateTypeId;
}
public void setOperateTypeId(String operateTypeId) {
this.operateTypeId = operateTypeId;
}
public String getOperateTypeName() {
return operateTypeName;
}
public void setOperateTypeName(String operateTypeName) {
this.operateTypeName = operateTypeName;
}
public String getOperateContent() {
return operateContent;
}
public void setOperateContent(String operateContent) {
this.operateContent = operateContent;
}
public String getOperateResult() {
return operateResult;
}
public void setOperateResult(String operateResult) {
this.operateResult = operateResult;
}
public String getOperateTimeDate() {
return operateTimeDate;
}
public void setOperateTimeDate(String operateTimeDate) {
this.operateTimeDate = operateTimeDate;
}
public String getTaskNo() {
return taskNo;
}
public void setTaskNo(String taskNo) {
this.taskNo = taskNo;
}
public String getIsWorkTime() {
return isWorkTime;
}
public void setIsWorkTime(String isWorkTime) {
this.isWorkTime = isWorkTime;
}
public String getIsWorkDay() {
return isWorkDay;
}
public void setIsWorkDay(String isWorkDay) {
this.isWorkDay = isWorkDay;
}
public String getModuleId() {
return moduleId;
}
public void setModuleId(String moduleId) {
this.moduleId = moduleId;
}
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public String getObjTypeId() {
return objTypeId;
}
public void setObjTypeId(String objTypeId) {
this.objTypeId = objTypeId;
}
public String getObjTypeName() {
return objTypeName;
}
public void setObjTypeName(String objTypeName) {
this.objTypeName = objTypeName;
}
public String getPersonDutyId() {
return personDutyId;
}
public void setPersonDutyId(String personDutyId) {
this.personDutyId = personDutyId;
}
public String getPersonDutyName() {
return personDutyName;
}
public void setPersonDutyName(String personDutyName) {
this.personDutyName = personDutyName;
}
public String getActionTypeId() {
return actionTypeId;
}
public void setActionTypeId(String actionTypeId) {
this.actionTypeId = actionTypeId;
}
public String getActionTypeName() {
return actionTypeName;
}
public void setActionTypeName(String actionTypeName) {
this.actionTypeName = actionTypeName;
}
public String getBankProof() {
return bankProof;
}
public void setBankProof(String bankProof) {
this.bankProof = bankProof;
}
public String getClientNetworkAddress() {
return clientNetworkAddress;
}
public void setClientNetworkAddress(String clientNetworkAddress) {
this.clientNetworkAddress = clientNetworkAddress;
}
public String getBankApprove() {
return bankApprove;
}
public void setBankApprove(String bankApprove) {
this.bankApprove = bankApprove;
}
public String getLogSource() {
return logSource;
}
public void setLogSource(String logSource) {
this.logSource = logSource;
}
public String getIsAuthorOthers() {
return isAuthorOthers;
}
public void setIsAuthorOthers(String isAuthorOthers) {
this.isAuthorOthers = isAuthorOthers;
}
public String getOwnMainAcctId() {
return ownMainAcctId;
}
public void setOwnMainAcctId(String ownMainAcctId) {
this.ownMainAcctId = ownMainAcctId;
}
public String getOwnMainAcctName() {
return ownMainAcctName;
}
public void setOwnMainAcctName(String ownMainAcctName) {
this.ownMainAcctName = ownMainAcctName;
}
public String getOwnPersonName() {
return ownPersonName;
}
public void setOwnPersonName(String ownPersonName) {
this.ownPersonName = ownPersonName;
}
public String getBankflag() {
return bankflag;
}
public void setBankflag(String bankflag) {
this.bankflag = bankflag;
}
public String getBankIsneed() {
return bankIsneed;
}
public void setBankIsneed(String bankIsneed) {
this.bankIsneed = bankIsneed;
}
public String getBankIsopen() {
return bankIsopen;
}
public void setBankIsopen(String bankIsopen) {
this.bankIsopen = bankIsopen;
}
public String getBankSceneId() {
return bankSceneId;
}
public void setBankSceneId(String bankSceneId) {
this.bankSceneId = bankSceneId;
}
public String getBankSceneName() {
return bankSceneName;
}
public void setBankSceneName(String bankSceneName) {
this.bankSceneName = bankSceneName;
}
public String getIsbinding() {
return isbinding;
}
public void setIsbinding(String isbinding) {
this.isbinding = isbinding;
}
public String getFromProvincesId() {
return fromProvincesId;
}
public void setFromProvincesId(String fromProvincesId) {
this.fromProvincesId = fromProvincesId;
}
public String getFromProvincesName() {
return fromProvincesName;
}
public void setFromProvincesName(String fromProvincesName) {
this.fromProvincesName = fromProvincesName;
}
public String getToProvincesId() {
return toProvincesId;
}
public void setToProvincesId(String toProvincesId) {
this.toProvincesId = toProvincesId;
}
public String getToProvincesName() {
return toProvincesName;
}
public void setToProvincesName(String toProvincesName) {
this.toProvincesName = toProvincesName;
}
public String getGoldApprMainAcctId() {
return goldApprMainAcctId;
}
public void setGoldApprMainAcctId(String goldApprMainAcctId) {
this.goldApprMainAcctId = goldApprMainAcctId;
}
public String getGoldApprPersonName() {
return goldApprPersonName;
}
public void setGoldApprPersonName(String goldApprPersonName) {
this.goldApprPersonName = goldApprPersonName;
}
public String getBankApplyType() {
return bankApplyType;
}
public void setBankApplyType(String bankApplyType) {
this.bankApplyType = bankApplyType;
}
public String getBankLastCheckStatus() {
return bankLastCheckStatus;
}
public void setBankLastCheckStatus(String bankLastCheckStatus) {
this.bankLastCheckStatus = bankLastCheckStatus;
}
public Date getBankLastCheckTime() {
return bankLastCheckTime;
}
public void setBankLastCheckTime(Date bankLastCheckTime) {
this.bankLastCheckTime = bankLastCheckTime;
}
public String getBankLastCheckTimeDate() {
return bankLastCheckTimeDate;
}
public void setBankLastCheckTimeDate(String bankLastCheckTimeDate) {
this.bankLastCheckTimeDate = bankLastCheckTimeDate;
}
public String getBankFaiedCheckCount() {
return bankFaiedCheckCount;
}
public void setBankFaiedCheckCount(String bankFaiedCheckCount) {
this.bankFaiedCheckCount = bankFaiedCheckCount;
}
public String getOperateObjectType() {
return operateObjectType;
}
public void setOperateObjectType(String operateObjectType) {
this.operateObjectType = operateObjectType;
}
public String getAuditSubTypeId() {
return auditSubTypeId;
}
public void setAuditSubTypeId(String auditSubTypeId) {
this.auditSubTypeId = auditSubTypeId;
}
public String getAuditSubTypeName() {
return auditSubTypeName;
}
public void setAuditSubTypeName(String auditSubTypeName) {
this.auditSubTypeName = auditSubTypeName;
}
public String getIsLoginByfoura() {
return isLoginByfoura;
}
public void setIsLoginByfoura(String isLoginByfoura) {
this.isLoginByfoura = isLoginByfoura;
}
public String getRoundType() {
return roundType;
}
public void setRoundType(String roundType) {
this.roundType = roundType;
}
public Date getOriCreateTime() {
return oriCreateTime;
}
public void setOriCreateTime(Date oriCreateTime) {
this.oriCreateTime = oriCreateTime;
}
public String getOriCreateTimeDate() {
return oriCreateTimeDate;
}
public void setOriCreateTimeDate(String oriCreateTimeDate) {
this.oriCreateTimeDate = oriCreateTimeDate;
}
public Date getStdCreateTime() {
return stdCreateTime;
}
public void setStdCreateTime(Date stdCreateTime) {
this.stdCreateTime = stdCreateTime;
}
public String getStdCreateTimeDate() {
return stdCreateTimeDate;
}
public void setStdCreateTimeDate(String stdCreateTimeDate) {
this.stdCreateTimeDate = stdCreateTimeDate;
}
public String getLevel2OrgId() {
return level2OrgId;
}
public void setLevel2OrgId(String level2OrgId) {
this.level2OrgId = level2OrgId;
}
public String getLevel2OrgName() {
return level2OrgName;
}
public void setLevel2OrgName(String level2OrgName) {
this.level2OrgName = level2OrgName;
}
public String getOriFileName() {
return oriFileName;
}
public void setOriFileName(String oriFileName) {
this.oriFileName = oriFileName;
}
public String getOriFileRownum() {
return oriFileRownum;
}
public void setOriFileRownum(String oriFileRownum) {
this.oriFileRownum = oriFileRownum;
}
public Date getOriGatherTime() {
return oriGatherTime;
}
public void setOriGatherTime(Date oriGatherTime) {
this.oriGatherTime = oriGatherTime;
}
public String getOriGatherTimeDate() {
return oriGatherTimeDate;
}
public void setOriGatherTimeDate(String oriGatherTimeDate) {
this.oriGatherTimeDate = oriGatherTimeDate;
}
public String getRecheckDataId() {
return recheckDataId;
}
public void setRecheckDataId(String recheckDataId) {
this.recheckDataId = recheckDataId;
}
public Date getStdBeginTime() {
return stdBeginTime;
}
public void setStdBeginTime(Date stdBeginTime) {
this.stdBeginTime = stdBeginTime;
}
public String getStdBeginTimeDate() {
return stdBeginTimeDate;
}
public void setStdBeginTimeDate(String stdBeginTimeDate) {
this.stdBeginTimeDate = stdBeginTimeDate;
}
public String getAppMaintainerId() {
return appMaintainerId;
}
public void setAppMaintainerId(String appMaintainerId) {
this.appMaintainerId = appMaintainerId;
}
public String getAppMaintainer() {
return appMaintainer;
}
public void setAppMaintainer(String appMaintainer) {
this.appMaintainer = appMaintainer;
}
public String getAppImportLevel() {
return appImportLevel;
}
public void setAppImportLevel(String appImportLevel) {
this.appImportLevel = appImportLevel;
}
public String getSectionIds() {
return sectionIds;
}
public void setSectionIds(String sectionIds) {
this.sectionIds = sectionIds;
}
public String getSectionNames() {
return sectionNames;
}
public void setSectionNames(String sectionNames) {
this.sectionNames = sectionNames;
}
public Date getOperateTime() {
return operateTime;
}
public void setOperateTime(Date operateTime) {
this.operateTime = operateTime;
}
public Date getStandardizeTime() {
return standardizeTime;
}
public void setStandardizeTime(Date standardizeTime) {
this.standardizeTime = standardizeTime;
}
public Date getIndexTime() {
return indexTime;
}
public void setIndexTime(Date indexTime) {
this.indexTime = indexTime;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "Log [logId=" + logId + ", personName=" + personName + ", clientIp=" + clientIp + ", level2OrgId=" + level2OrgId + ", level2OrgName=" + level2OrgName + ", operateTime=" + operateTime + ", standardizeTime=" + standardizeTime + ", indexTime=" + indexTime + "]";
}
}
|
package com.madrapps.dagger.test;
import com.madrapps.dagger.models.Vehicle;
public class SuperCar implements Vehicle {
}
|
package com.example.BSD.tasks;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import com.example.BSD.MainActivity;
public class UserFunctions
{
private static String URL = "http://bsd.net76.net/db_verbinding/";
private static String login_tag = "login";
private static String register_tag = "register";
private static String getcursus_tag = "cursusrequest";
private static String inschrijf_tag = "inschrijven";
// constructor
public UserFunctions()
{
}
/**
* function make Login Request
* @param email
* @param password
* */
public JSONObject loginUser(Context context, String email, String password)
{
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = null;
try
{
json = new JSONParser(context, URL, params).execute().get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
return json;
}
/**
* function make Login Request
* @param name
* @param email
* @param password
* */
public JSONObject registerUser(Context context, String name, String email, String password)
{
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = null;
try
{
json = new JSONParser(context, URL, params).execute().get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
return json;
}
/**
* function make Login Request
* @param email
* */
public String getCursussenByEmail(Context context, String email)
{
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", getcursus_tag));
params.add(new BasicNameValuePair("email", email));
// getting JSON Object
JSONObject json = null;
try
{
json = new JSONParser(context, URL, params).execute().get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
String ingeschrevenCursussen = null;
if(json != null)
{
JSONArray jsonArr = null;
try
{
jsonArr = json.getJSONArray("cursussen");
}
catch (JSONException e)
{
e.printStackTrace();
}
JSONObject ingeschrevencursusObject = null;
try
{
ingeschrevencursusObject = jsonArr.getJSONObject(0);
}
catch (JSONException e1)
{
e1.printStackTrace();
}
try
{
ingeschrevenCursussen = ingeschrevencursusObject.getString("cursus_naam");
}
catch (JSONException e)
{
e.printStackTrace();
}
//Update ingeschreven cursus listview
MainActivity.updateIngeschrevenListView(ingeschrevenCursussen);
}
return ingeschrevenCursussen;
}
/**
* function make Login Request
* @param email
* */
public JSONObject cursusInschrijven(Context context, String email, String cursuslijst)
{
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", inschrijf_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("cursus", cursuslijst));
// getting JSON Object
JSONObject json = null;
try
{
json = new JSONParser(context, URL, params).execute().get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context)
{
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0)
{
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context)
{
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
|
/*
* MIT License
* <p>
* Copyright (c) 2017-2018 nuls.io
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package network.nerve.quotation;
import network.nerve.quotation.heterogeneouschain.BNBWalletApi;
import network.nerve.quotation.heterogeneouschain.ETHWalletApi;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* 合约报价测试
*
* @author: Loki
* @date: 2020/12/3
*/
public class ContractQuotaionTest {
//WETH-NVT:0x5A3De33Ae548aAe7abaA40Cc25A4edDFE4222b3B
//WBNB-NVT:0xeE31a8Bb1edb26D8de688e2a1Ca086E5C11f5978
public static final String ETH_UNI_V2_CONTRACT = "0x5a3de33ae548aae7abaa40cc25a4eddfe4222b3b";
public static final String ETH_NVT_TOKEN_CONTRACT = "0x7b6f71c8b123b38aa8099e0098bec7fbc35b8a13";
public static final String ETH_WETH_TOKEN_CONTRACT = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2";
public static final String BSC_CAKE_LP_CONTRACT = "0xee31a8bb1edb26d8de688e2a1ca086e5c11f5978";
public static final String BSC_NVT_TOKEN_CONTRACT = "0xf0e406c49c63abf358030a299c0e00118c4c6ba5";
public static final String BSC_WETH_TOKEN_CONTRACT = "0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c";
private ETHWalletApi ethWalletApi = new ETHWalletApi();
private BNBWalletApi bnbWalletApi = new BNBWalletApi();
@Before
public void before() {
// EthContext.rpcAddress = "https://ropsten.infura.io/v3/e51e9f10a4f647af81d5f083873f27a5";
ethWalletApi.init();
// BnbContext.rpcAddress = "https://data-seed-prebsc-1-s1.binance.org:8545/";
bnbWalletApi.init();
}
@Test
public void netEth() throws Exception {
// 计算ETH网络下 UNI_V2 的价格
// System.out.println(ethWalletApi.getContractTokenDecimals(ETH_UNI_V2_CONTRACT));
// System.out.println(ethWalletApi.getContractTokenDecimals(ETH_NVT_TOKEN_CONTRACT));
// System.out.println(ethWalletApi.getContractTokenDecimals(ETH_WETH_TOKEN_CONTRACT));
// 池子里ETH的数量
BigInteger wethBalance = ethWalletApi.getERC20Balance(ETH_UNI_V2_CONTRACT, ETH_WETH_TOKEN_CONTRACT);
System.out.println("wethBalance:" + wethBalance);
int wethDecimals = ethWalletApi.getContractTokenDecimals(ETH_WETH_TOKEN_CONTRACT);
System.out.println("wethDecimals:" + wethDecimals);
BigInteger wethTwice = wethBalance.multiply(new BigInteger("2"));
System.out.println("wethTwice:" + wethTwice);
BigDecimal wethCount = new BigDecimal(wethTwice).movePointLeft(wethDecimals);
System.out.println("wethCount:" + wethCount);
BigDecimal wethPrice = wethCount.multiply(new BigDecimal("600"));
System.out.println("wethPrice:" + wethPrice);
System.out.println();
BigInteger totalSupplyV2 = ethWalletApi.totalSupply(ETH_UNI_V2_CONTRACT);
System.out.println("totalSupplyV2:" + totalSupplyV2);
int v2Decimals = ethWalletApi.getContractTokenDecimals(ETH_UNI_V2_CONTRACT);
System.out.println("V2Decimals:" + v2Decimals);
BigDecimal v2Count = new BigDecimal(totalSupplyV2).movePointLeft(v2Decimals);
System.out.println("V2Count:" + v2Count);
BigDecimal uniV2Price = wethPrice.divide(v2Count, 4, RoundingMode.DOWN);
System.out.println("uniV2Price:" + uniV2Price);
}
@Test
public void netBsc() throws Exception {
// 计算ETH网络下 CAKE_LP 的价格 cakeLp
// 池子里ETH的数量
BigInteger wethBalance = bnbWalletApi.getERC20Balance(BSC_CAKE_LP_CONTRACT, BSC_WETH_TOKEN_CONTRACT);
System.out.println("wethBalance:" + wethBalance);
int wethDecimals = bnbWalletApi.getContractTokenDecimals(BSC_WETH_TOKEN_CONTRACT);
System.out.println("wethDecimals:" + wethDecimals);
BigInteger wethTwice = wethBalance.multiply(new BigInteger("2"));
System.out.println("wethTwice:" + wethTwice);
BigDecimal wethCount = new BigDecimal(wethTwice).movePointLeft(wethDecimals);
System.out.println("wethCount:" + wethCount);
BigDecimal wethPrice = wethCount.multiply(new BigDecimal("600"));
System.out.println("wethPrice:" + wethPrice);
System.out.println();
BigInteger totalSupplyCakeLp = bnbWalletApi.totalSupply(BSC_CAKE_LP_CONTRACT);
System.out.println("totalSupplyCakeLp:" + totalSupplyCakeLp);
int cakeLpDecimals = bnbWalletApi.getContractTokenDecimals(BSC_CAKE_LP_CONTRACT);
System.out.println("cakeLpDecimals:" + cakeLpDecimals);
BigDecimal cakeLpCount = new BigDecimal(totalSupplyCakeLp).movePointLeft(cakeLpDecimals);
System.out.println("cakeLpCount:" + cakeLpCount);
BigDecimal cakeLpPrice = wethPrice.divide(cakeLpCount, 4, RoundingMode.DOWN);
System.out.println("cakeLpPrice:" + cakeLpPrice);
}
}
|
package com.sprint.crm.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.sprint.crm.mapper.RolesMapper;
import com.sprint.crm.pojo.Modules;
import com.sprint.crm.pojo.Roles;
import com.sprint.crm.pojo.RolesPageBean;
import com.sprint.crm.pojo.User;
@Service
public class RolesServiceImpl implements RolesService {
@Resource
private RolesMapper rolesMapper;
@Override
public int insertSelective(Roles record) {
// TODO Auto-generated method stub
return rolesMapper.insertSelective(record);
}
@Override
public Roles selectByPrimaryKey(Integer roleId) {
// TODO Auto-generated method stub
return rolesMapper.selectByPrimaryKey(roleId);
}
@Override
public int updateByPrimaryKeySelective(Roles record) {
// TODO Auto-generated method stub
return rolesMapper.updateByPrimaryKeySelective(record);
}
@Override
public List<Roles> getPage(RolesPageBean rolesPageBean) {
// TODO Auto-generated method stub
return rolesMapper.getPage(rolesPageBean);
}
@Override
public int getSum(RolesPageBean rolesPageBean) {
// TODO Auto-generated method stub
return rolesMapper.getSum(rolesPageBean);
}
@Override
public List<User> getUserByRname(String rName) {
// TODO Auto-generated method stub
return rolesMapper.getUserByRname(rName);
}
@Override
public int getRIdByRname(String rName) {
// TODO Auto-generated method stub
return rolesMapper.getRIdByRname(rName);
}
@Override
public int addRole(Roles roles) {
// TODO Auto-generated method stub
return rolesMapper.addRole(roles);
}
@Override
public int updateRole(Roles roles) {
// TODO Auto-generated method stub
return rolesMapper.updateRole(roles);
}
@Override
public int dele(String roleId) {
// TODO Auto-generated method stub
return rolesMapper.dele(roleId);
}
@Override
public List<Modules> getUserByRole(Integer roleId) {
// TODO Auto-generated method stub
return rolesMapper.getUserByRole(roleId);
}
@Override
public int delAllRoles(int roleId) {
// TODO Auto-generated method stub
return rolesMapper.delAllRoles(roleId);
}
@Override
public int setRoles(int id, int ids) {
// TODO Auto-generated method stub
return rolesMapper.setRoles(id, ids);
}
}
|
package com.dassa.vo;
public class SearchUserVO {
private String searchType;
private String searchWord;
private String userType;
private String userType1;
private String userType2;
private String status;
private String endDate;
private String startDate;
private int startPage;
private int endPage;
public int getStartPage() {
return startPage;
}
public void setStartPage(int startPage) {
this.startPage = startPage;
}
public int getEndPage() {
return endPage;
}
public void setEndPage(int endPage) {
this.endPage = endPage;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public String getSearchWord() {
return searchWord;
}
public void setSearchWord(String searchWord) {
this.searchWord = searchWord;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getUserType1() {
return userType1;
}
public void setUserType1(String userType1) {
this.userType1 = userType1;
}
public String getUserType2() {
return userType2;
}
public void setUserType2(String userType2) {
this.userType2 = userType2;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public SearchUserVO(String searchType, String searchWord, String userType, String userType1, String userType2,
String status, String endDate, String startDate, int startPage, int endPage) {
super();
this.searchType = searchType;
this.searchWord = searchWord;
this.userType = userType;
this.userType1 = userType1;
this.userType2 = userType2;
this.status = status;
this.endDate = endDate;
this.startDate = startDate;
this.startPage = startPage;
this.endPage = endPage;
}
public SearchUserVO() {
super();
// TODO Auto-generated constructor stub
}
}
|
import javafx.scene.*;
public class Board {
public Cell[][] getBoard() {
return board;
}
/**
* The game board
*/
private Cell[][] board;
private final int SIZE = 8;
/**
* which player is playing 1 or 2
*/
private int currentPlayer;
/**
* initialize the game board for playing
*/
public Board() {
board = new Cell[SIZE][SIZE];
//place black pieces
board[0][0] = new Cell(new RookPiece("bR", "a8")); // place rook
board[0][1] = new Cell(new KnightPiece("bN", "b8")); // place knight
board[0][2] = new Cell(new BishopPiece("bB", "c8")); // place bishop
board[0][3] = new Cell(new QueenPiece("bQ", "d8")); // place queen
board[0][4] = new Cell(new KingPiece("bK", "e8")); // place king
board[0][5] = new Cell(new BishopPiece("bB", "f8")); // place bishop
board[0][6] = new Cell(new KnightPiece("bN", "g8")); // place knight
board[0][7] = new Cell(new RookPiece("bR", "h8")); // place rook
for (int i = 0; i < SIZE; i++) {
board[1][i] = new Cell(new PawnPiece("bp", (char) ('a' + i) + "7"));
}
//place white pieces
board[7][0] = new Cell(new RookPiece("wR", "a1"));
board[7][1] = new Cell(new KnightPiece("wN", "b1"));
board[7][2] = new Cell(new BishopPiece("wB", "c1"));
board[7][3] = new Cell(new QueenPiece("wQ", "d1"));
board[7][4] = new Cell(new KingPiece("wK", "e1"));
board[7][5] = new Cell(new BishopPiece("wB", "f1"));
board[7][6] = new Cell(new KnightPiece("wN", "g1"));
board[7][7] = new Cell(new RookPiece("wR", "h1"));
for (int i = 0; i < SIZE; i++) {
board[6][i] = new Cell(new PawnPiece("wp", (char) ('a' + i) + "2"));
}
currentPlayer = 1;
}
/**
* change player playing
*/
public void setCurrentPlayer(int currentPlayer) {
this.currentPlayer = currentPlayer;
}
/**
* return player playing
*/
public int getCurrentPlayer() {
return currentPlayer;
}
/**
* This method is called to move a piece from start point to end point
*
* return true if the move is valid, otherwise false
*/
public boolean move(String start, String end) {
if (start == null || end == null) {
return false;
}
if (start.length() != 2 || end.length() != 2) {
return false;
}
if (!isValidPos(start) || !isValidPos(end)) {
return false;
}
int colS = start.charAt(0) - 'a';
int rowS = '8' - start.charAt(1);
int colE = end.charAt(0) - 'a';
int rowE = '8' - end.charAt(1);
if (board[rowS][colS] == null) {
return false;
}
if (currentPlayer == 1 && !board[rowS][colS].getChessPiece().getType().startsWith("w")) {
return false;
}
if (currentPlayer == 2 && !board[rowS][colS].getChessPiece().getType().startsWith("b")) {
return false;
}
boolean validMove = board[rowS][colS].getChessPiece().isValidMove(end);
if (!validMove) {
return false;
}
if (!checkCollisionSameType(start, end)) {
return false;
}
if (!checkBetween(start, end)) {
return false;
}
if (!checkPawn(start, end)) {
return false;
}
board[rowE][colE] = board[rowS][colS];
board[rowE][colE].getChessPiece().setPosition(end);
board[rowS][colS] = null;
isCheck();
return true;
}
/**
* this method check if on move there is collision of same color <br>
* for example if we move black Rook from a7 to a6, and a6 has another black
* piece then this is not valid move
*
* return true if no collision of same color, otherwise return false
*/
private boolean checkCollisionSameType(String start, String end) {
int colS = start.charAt(0) - 'a';
int rowS = '8' - start.charAt(1);
int colE = end.charAt(0) - 'a';
int rowE = '8' - end.charAt(1);
//if the end location is empty (then no collision)
if (board[rowE][colE] == null) {
return true;
}
//otherwise the end location is not empty
//if start piece is black and end piece is black, then collision (return false)
if (board[rowE][colE].getChessPiece().getType().startsWith("b")
&& board[rowS][colS].getChessPiece().getType().startsWith("b")) {
return false;
}
//if start piece is white and end piece is white, then collision (return false)
if (board[rowE][colE].getChessPiece().getType().startsWith("w")
&& board[rowS][colS].getChessPiece().getType().startsWith("w")) {
return false;
}
return true;
}
/**
* This method check if there is any pieces between the start and end point
* for example if we move bishop from c1 to g4, check if any pieces in this
* path. <br>
* it won't be valid move if any pieces exist in move path
*
* return true if no pieces between the start and end location move,
* otherwise false
*/
private boolean checkBetween(String start, String end) {
int colS = start.charAt(0) - 'a';
int rowS = '8' - start.charAt(1);
int colE = end.charAt(0) - 'a';
int rowE = '8' - end.charAt(1);
ChessPiece piece = board[rowS][colS].getChessPiece();
String type = piece.getType().substring(1);
//check the Bishop and Queen Diagonal move cells
if (type.equals("B") || (type.equals("Q") && colS != colE)) {
if (colS < colE && rowS < rowE) {
for (int i = rowS + 1, j = colS + 1; i < rowE; i++, j++) { // if any cells not empty in path return false
if (board[i][j] != null) {
return false;
}
}
}
if (colS < colE && rowS > rowE) {
for (int i = rowS - 1, j = colS + 1; i > rowE; i--, j++) {
if (board[i][j] != null) {
return false;
}
}
}
if (colS > colE && rowS < rowE) {
for (int i = rowS + 1, j = colS - 1; i < rowE; i++, j--) {
if (board[i][j] != null) {
return false;
}
}
}
if (colS > colE && rowS > rowE) {
for (int i = rowS - 1, j = colS - 1; i > rowE; i--, j--) {
if (board[i][j] != null) {
return false;
}
}
}
}
//if Rook or Queen piece, check the vertical and horizontal moves
if (type.equals("R") || (type.equals("Q") && colS == colE)) {
if (colS == colE) {
if (rowS > rowE) {
for (int i = rowS - 1; i > rowE; i--) {
if (board[i][colE] != null) {
return false;
}
}
} else {
for (int i = rowS + 1; i < rowE; i++) {
if (board[i][colE] != null) {
return false;
}
}
}
} else if (rowS > rowE) {
for (int j = colS - 1; j > colE; j--) {
if (board[rowS][j] != null) {
return false;
}
}
} else {
for (int j = colS + 1; j < colE; j++) {
if (board[rowS][j] != null) {
return false;
}
}
}
}
return true;
}
/**
* This method checks the Pawn move, vertical or diagonal<br>
* vertical if no pieces on front of it, diagonal if enemy pieces on
* diagonalF
*
* return true if move vertical or diagonal correct, otherwise false
*/
private boolean checkPawn(String start, String end) {
int colS = start.charAt(0) - 'a';
int rowS = '8' - start.charAt(1);
int colE = end.charAt(0) - 'a';
int rowE = '8' - end.charAt(1);
if (!(board[rowS][colS].getChessPiece().getType().substring(1)).equals("p")) {
return true;
}
if (colS == colE) {
if (board[rowE][colE] != null) {
return false;
}
} else if (board[rowE][colE] == null) {
return false;
}
return true;
}
/**
* This method go over board to see if the white/black king is under attack
*/
private void isCheck() {
String whiteKingPos = "";
String blackKingPos = "";
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
if (board[row][col] != null) {
if (board[row][col].getChessPiece() instanceof KingPiece) {
if (board[row][col].getChessPiece().getType().equals("bK")) {
blackKingPos = board[row][col].getChessPiece().getPosition();
} else {
whiteKingPos = board[row][col].getChessPiece().getPosition();
}
}
}
}
}
//check if one king is not found, if a king not found, this mean it's killed. end game
if (whiteKingPos.isEmpty()) {
System.out.println("Black wins");
System.exit(0);
}
//check if black king is killed
if (blackKingPos.isEmpty()) {
System.out.println("White wins");
System.exit(0);
}
//
//go over the board and check for pieces that attack either kings
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
//if cell not empty
if (board[row][col] != null) {
ChessPiece piece = board[row][col].getChessPiece();
String piecePos = piece.getPosition();
//if white piece
if (piece.getType().startsWith("w")) {
if (piece.isValidMove(blackKingPos)) {
if (checkBetween(piecePos, blackKingPos) && checkPawn(piecePos, blackKingPos)) {
if (isCheckmate(whiteKingPos, blackKingPos)) {
System.out.println("Checkmate");
System.out.println(toString());
System.exit(0);
} else {
System.out.println("Check");
}
return;
}
}
}//if black piece, check if it can attack king
else if (piece.isValidMove(whiteKingPos)) {
if (checkBetween(piecePos, whiteKingPos) && checkPawn(piecePos, whiteKingPos)) {
if (isCheckmate(whiteKingPos, blackKingPos)) {
System.out.println("Checkmate");
System.out.println(toString());
System.exit(0);
} else {
System.out.println("Check");
}
return;
}
}
}
}
}
}
/**
* check if check mate for both whiteKing position and blackKing position
*/
private boolean isCheckmate(String whiteKingPos, String blackKingPos) {
boolean isCheckmate = false;
if (!whiteKingPos.isEmpty()) {
//check the white king valid moves
//get King location
char colW = whiteKingPos.charAt(0);
int rowW = whiteKingPos.charAt(1) - '0';
//specify the King 8 correct moves for this location
String pos[] = {
String.valueOf((char) (colW) + "" + (rowW + 1)),
String.valueOf((char) (colW + 1) + "" + (rowW + 1)),
String.valueOf((char) (colW - 1) + "" + (rowW + 1)),
String.valueOf((char) (colW) + "" + (rowW - 1)),
String.valueOf((char) (colW + 1) + "" + (rowW - 1)),
String.valueOf((char) (colW - 1) + "" + (rowW - 1)),
String.valueOf((char) (colW + 1) + "" + (rowW)),
String.valueOf((char) (colW - 1) + "" + (rowW))};
for (int j = 0; j < pos.length; j++) {
boolean isCheck = false;
int colS = whiteKingPos.charAt(0) - 'a';
int rowS = '8' - whiteKingPos.charAt(1);
if (isValidPos(pos[j]) && isEmptyLocation(pos[j]) && board[rowS][colS].getChessPiece().isValidMove(pos[j])) {
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
if (board[row][col] != null) {
ChessPiece piece = board[row][col].getChessPiece();
String piecePos = piece.getPosition();
if (piece.getType().startsWith("b")) {
if (piece.isValidMove(pos[j]) && checkBetween(piecePos, pos[j]) && checkPawn(piecePos, pos[j])) {
isCheck = true;
break;
}
}
}
}
if (isCheck) {
isCheckmate = true;
break;
}
}
if (!isCheck) {
isCheckmate = false;
break;
}
}
}
if (isCheckmate) {
return true;
}
}
//check the white king valid moves
//get King location
if (!blackKingPos.isEmpty()) {
char colB = blackKingPos.charAt(0);
int rowB = blackKingPos.charAt(1) - '0';
//specify the King 8 correct moves for this location
String posB[] = {
String.valueOf((char) (colB) + "" + (rowB + 1)),
String.valueOf((char) (colB + 1) + "" + (rowB + 1)),
String.valueOf((char) (colB - 1) + "" + (rowB + 1)),
String.valueOf((char) (colB) + "" + (rowB - 1)),
String.valueOf((char) (colB + 1) + "" + (rowB - 1)),
String.valueOf((char) (colB - 1) + "" + (rowB - 1)),
String.valueOf((char) (colB + 1) + "" + (rowB)),
String.valueOf((char) (colB - 1) + "" + (rowB))};
isCheckmate = false;
for (int j = 0; j < posB.length; j++) {
boolean isCheck = false;
//get king position
int colS = blackKingPos.charAt(0) - 'a';
//for possible positions, check if king can move to any to be safe
int rowS = '8' - blackKingPos.charAt(1);
if (isValidPos(posB[j]) && isEmptyLocation(posB[j]) && board[rowS][colS].getChessPiece().isValidMove(posB[j])) {
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
if (board[row][col] != null) {
ChessPiece piece = board[row][col].getChessPiece();
String piecePos = piece.getPosition();
if (piece.getType().startsWith("w")) {
if (piece.isValidMove(posB[j]) && checkBetween(piecePos, posB[j]) && checkPawn(piecePos, posB[j])) {
isCheck = true;
break;
}
}
}
}
if (isCheck) {
isCheckmate = true;
break;
}
}
if (!isCheck) {
return false;
}
}
}
}
return isCheckmate;
}
/**
* check if this position inside the board
*
* return true is pos inside the board, otherwise false
*/
private boolean isValidPos(String pos) {
if (pos.charAt(0) < 'a' || pos.charAt(0) > 'h') {
return false;
}
if (pos.charAt(1) < '1' || pos.charAt(1) > '8') {
return false;
}
return true;
}
/**
* check if board is empty at location pos
*
* return true if board empty at pos, otherwise false
*/
private boolean isEmptyLocation(String pos) {
int col = pos.charAt(0) - 'a';
int row = '8' - pos.charAt(1);
return board[row][col] == null;
}
/**
* Castle King/Rook and return true if valid castle
*
* return boolean
*/
public boolean castle(String pos) {
if (currentPlayer == 1) {
if (board[7][4] == null) // if king not in place
{
return false;
}
if (isCheckmate("e1", "")) // if check mate can't castle
{
return false;
}
if (pos.equals("g")) {
if (board[7][7] == null) // right rook not in place
{
return false;
}
if (board[7][6] != null || board[7][5] != null) {
return false;
}
return castleHelper(7, 4, 7, 7);
} else {
if (board[7][0] == null) // left rook not in place
{
return false;
}
if (board[7][1] != null || board[7][2] != null || board[7][3] != null) {
return false;
}
return castleHelper(7, 4, 7, 0);
}
} else {
if (board[0][4] == null) // king not in place
{
return false;
}
if (isCheckmate("", "e8")) // if check mate can't castle
{
return false;
}
if (pos.equals("g")) {
if (board[0][7] == null) // right rook not in place
{
return false;
}
if (board[0][6] != null || board[0][5] != null) {
return false;
}
return castleHelper(0, 4, 0, 7);
} else {
if (board[0][0] == null) // left rook not in place
{
return false;
}
if (board[0][1] != null || board[0][2] != null || board[0][3] != null) {
return false;
}
return castleHelper(0, 4, 0, 0);
}
}
}
/**
* Castle move helper method
*/
private boolean castleHelper(int kingR, int kingC, int rookR, int rookC) {
KingPiece king = (KingPiece) (board[kingR][kingC].getChessPiece());
RookPiece rook = (RookPiece) (board[rookR][rookC].getChessPiece());
//if either piece moved
if (king.hasMoved() || rook.hasMoved()) {
return false;
}
if (kingC > rookC) {
if (kingR == 0) {
board[kingR][2] = board[kingR][kingC];
board[kingR][2].getChessPiece().setPosition("c8");
board[rookR][3] = board[rookR][rookC];
board[rookR][3].getChessPiece().setPosition("d8");
} else {
board[kingR][2] = board[kingR][kingC];
board[kingR][2].getChessPiece().setPosition("c1");
board[rookR][3] = board[rookR][rookC];
board[rookR][3].getChessPiece().setPosition("d1");
}
} else {
if (kingR == 0) {
board[kingR][6] = board[kingR][kingC];
board[kingR][6].getChessPiece().setPosition("g8");
board[rookR][5] = board[rookR][rookC];
board[rookR][5].getChessPiece().setPosition("f8");
} else {
board[kingR][6] = board[kingR][kingC];
board[kingR][6].getChessPiece().setPosition("g1");
board[rookR][5] = board[rookR][rookC];
board[rookR][5].getChessPiece().setPosition("f1");
}
}
board[kingR][kingC] = null;
board[rookR][rookC] = null;
return true;
}
/**
* return String to represent the Game board
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("=============================================\n");
sb.append(" | a | b | c | d | e | f | g | h |\n");
sb.append("-- ---- ---- ---- ---- ---- ---- ---- ----\n");
for (int row = 0; row < SIZE; row++) {
sb.append(8 - row);
sb.append(" | ");
for (int col = 0; col < SIZE; col++) {
if (board[row][col] == null) {
sb.append(" | ");
} else {
sb.append(board[row][col] + " | ");
}
}
sb.append(8 - row + "\n");
sb.append("-- ---- ---- ---- ---- ---- ---- ---- ----\n");
}
sb.append(" | a | b | c | d | e | f | g | h |\n");
return sb.toString();
}
}
|
package Locacao;
public class ControleLocacao {
}
|
package com.example.hotel.controller.users.dto.in;
import io.swagger.annotations.ApiModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "UserCreate")
public class UserCreateDto {
private String login;
private String password;
private String email;
private String phone;
private String firstName;
private String secondName;
private String middleName;
}
|
package so.team.bukkitlejyon.cmdBlock.api;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import so.team.bukkitlejyon.BL;
import so.team.bukkitlejyon.cmdBlock.plugin.InputGuiPlayer;
public class InputListener
implements Listener
{
private Map<String, InputGuiPlayer> players = new HashMap<String, InputGuiPlayer>();
public InputGuiPlayer getPlayer(Player player)
{
String name = player.getName();
if (this.players.containsKey(name)) {
return (InputGuiPlayer)this.players.get(name);
}
InputGuiPlayer iplayer = new InputGuiPlayer(BL.instance, player);
this.players.put(name, iplayer);
return iplayer;
}
public void removePlayer(Player player)
{
this.players.remove(player.getName());
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e)
{
getPlayer(e.getPlayer());
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent e)
{
removePlayer(e.getPlayer());
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent e)
{
InputGuiPlayer player = getPlayer(e.getPlayer());
if (player.isCheckingMovement()) {
player.setCancelled();
}
}
}
|
/*
* Copyright 2017 Goldman Sachs.
* 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.gs.tablasco.verify;
import org.junit.Assert;
import org.junit.Test;
import java.sql.Timestamp;
public class CellFormatterTest
{
@Test
public void formatNumbers()
{
CellFormatter formatter = new CellFormatter(0.01, true);
Assert.assertEquals("1", formatter.format(1.0d));
Assert.assertEquals("1.1", formatter.format(1.10d));
Assert.assertEquals("1.11", formatter.format(1.11d));
Assert.assertEquals("1.11", formatter.format(1.111d));
Assert.assertEquals("1.12", formatter.format(1.116d));
Assert.assertEquals("-1.12", formatter.format(-1.116d));
Assert.assertEquals("-1,000.12", formatter.format(-1000.116d));
Assert.assertEquals("-1,000.12", formatter.format(-1000.116f));
Assert.assertEquals("1,000", formatter.format(1000));
Assert.assertEquals("-1,000", formatter.format((long) -1000));
Assert.assertEquals("NaN", formatter.format(Double.NaN));
Assert.assertEquals("NaN", formatter.format(Float.NaN));
Assert.assertEquals("0", formatter.format(-0.0d));
Assert.assertEquals("0", formatter.format(-0));
Assert.assertEquals("0", formatter.format(-0.0001));
}
@Test
public void formatNegativeZero()
{
CellFormatter formatter = new CellFormatter(0.0001, true);
Assert.assertEquals("0", formatter.format(-0.0d));
Assert.assertEquals("0", formatter.format(-0));
Assert.assertEquals("0", formatter.format(-0.00001));
Assert.assertEquals("-0.0001", formatter.format(-0.0001));
Assert.assertFalse(CellFormatter.isNegativeZero("-01"));
Assert.assertTrue(CellFormatter.isNegativeZero("-0.000000"));
}
@Test
public void formatDate()
{
CellFormatter formatter = new CellFormatter(0, false);
Assert.assertEquals("2009-02-13 23:31:30", formatter.format(Timestamp.valueOf("2009-02-13 23:31:30.0001")));
}
@Test
public void formatString()
{
CellFormatter formatter = new CellFormatter(0, false);
Assert.assertEquals("", formatter.format(""));
Assert.assertEquals("foo", formatter.format("foo"));
Assert.assertEquals("foo", formatter.format(" foo "));
Assert.assertEquals("foo bar", formatter.format("foo bar"));
Assert.assertEquals("foo bar", formatter.format("foo bar"));
Assert.assertEquals("foo bar", formatter.format("foo\nbar "));
Assert.assertEquals("foo bar", formatter.format(" foo\rbar"));
Assert.assertEquals("foo bar", formatter.format(" foo\r \nbar "));
Assert.assertEquals("foo", formatter.format("foo\r"));
Assert.assertEquals("foo", formatter.format("\n foo"));
Assert.assertEquals("", formatter.format("\n \r "));
Assert.assertEquals("", formatter.format(" \n \r"));
}
}
|
package com.dexvis.javafx.editors;
import java.util.List;
import org.controlsfx.control.PropertySheet.Item;
import org.controlsfx.property.editor.PropertyEditor;
import javafx.collections.FXCollections;
import javafx.scene.Node;
import javafx.scene.control.ChoiceBox;
public class ChoiceBoxEditor implements PropertyEditor<List<String>>
{
private List<String> value = null;
public ChoiceBoxEditor(Item item)
{
setValue((List<String>) item.getValue());
}
@Override
public Node getEditor()
{
return new ChoiceBox(FXCollections.observableList(getValue()));
}
@Override
public List<String> getValue()
{
return value;
}
@Override
public void setValue(List<String> value)
{
this.value = value;
}
}
|
package com.example.inventorymanagementsystem;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class Inventory extends AppCompatActivity {
private EditText editTextTextPersonName3;
private EditText editTextNumber2;
private EditText editTextNumber4;
private EditText editTextTextPersonName8;
private Button button11;
private Button button12;
private Button button13;
private Button button14;
myDBAdapter dbInventory;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory);
editTextTextPersonName3 = (EditText) findViewById(R.id.editTextTextPersonName3);
editTextNumber2 = (EditText) findViewById(R.id.editTextNumber2);
editTextNumber4 = (EditText) findViewById(R.id.editTextNumber4);
editTextTextPersonName8 = (EditText) findViewById(R.id.editTextTextPersonName8);
button11 = (Button) findViewById(R.id.button11);
button12 = (Button) findViewById(R.id.button12);
button13 = (Button) findViewById(R.id.button13);
button14 = (Button) findViewById(R.id.button14);
dbInventory = new myDBAdapter(this);
}
public void Add(View view){
String productName = editTextTextPersonName3.getText().toString();
String productQuality = editTextNumber2.getText().toString();
String productPrice = editTextNumber4.getText().toString();
String productDescription = editTextTextPersonName8.getText().toString();
if (productName.isEmpty()||productQuality.isEmpty()||productPrice.isEmpty()||productDescription.isEmpty())
{
Message.message(getApplicationContext(),"Please Enter Name, Quality, Price and Description...");
}
else
{
long id = dbInventory.insertData(productName,productQuality,productPrice,productDescription);
if (id<=0)
{
Message.message(getApplicationContext(),"Not Successful...");
editTextTextPersonName3.setText("");
editTextNumber2.setText("");
editTextNumber4.setText("");
editTextTextPersonName8.setText("");
}
else
{
Message.message(getApplicationContext()," Successful...");
editTextTextPersonName3.setText("");
editTextNumber2.setText("");
editTextNumber4.setText("");
editTextTextPersonName8.setText("");
}
}
}
public void View(View view){
String Products = dbInventory.viewProducts();
Message.message(this,Products);
}
public void Update(View view){
String productName2 = editTextTextPersonName3.getText().toString();
String productQuality2 = editTextNumber2.getText().toString();
String productPrice2 = editTextNumber4.getText().toString();
String productDescription2 = editTextTextPersonName8.getText().toString();
if (productName2.isEmpty()||productQuality2.isEmpty()||productPrice2.isEmpty()||productDescription2.isEmpty())
{
Message.message(getApplicationContext()," Enter Products");
}
else
{
int b = dbInventory.UpdateProducts(productName2,productQuality2,productPrice2,productDescription2);
if (b<=0)
{
Message.message(getApplicationContext(),"Not Successful...");
editTextTextPersonName3.setText("");
editTextNumber2.setText("");
editTextNumber4.setText("");
editTextTextPersonName8.setText("");
}
else
{
Message.message(getApplicationContext()," Updated...");
editTextTextPersonName3.setText("");
editTextNumber2.setText("");
editTextNumber4.setText("");
editTextTextPersonName8.setText("");
}
}
}
public void Delete(View view){
String delete = editTextTextPersonName3.getText().toString();
if (delete.isEmpty())
{
Message.message(getApplicationContext()," Enter Products");
}
else
{
int b = dbInventory.editTextTextPersonName3(delete);
if(b<=0)
{
Message.message(getApplicationContext()," Not Successful ...");
editTextTextPersonName3.setText("");
}
else
{
Message.message(getApplicationContext()," Deleted...");
editTextTextPersonName3.setText("");
}
}
}
}
|
package com.crmiguez.aixinainventory.service.movement;
import com.crmiguez.aixinainventory.entities.Movement;
import java.util.List;
import java.util.Optional;
public interface IMovementService {
public List<Movement> findAllMovements();
public Optional<Movement> findMovementById(Long movementId);
public List<Movement> findAllDowns();
public Movement addMovement(Movement Movement);
public Movement updateMovement(Movement movementDetails, Movement movement);
public void deleteMovement (Movement movement);
}
|
package com.gxjtkyy.standardcloud.api.domain.vo.request;
import com.gxjtkyy.standardcloud.common.domain.vo.PageRequestVO;
import com.gxjtkyy.standardcloud.common.domain.vo.RequestVO;
import com.gxjtkyy.standardcloud.common.validation.annotation.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* 根据关键字搜索文档
* @Package com.gxjtkyy.standardcloud.api.domain.vo.request
* @Author lizhenhua
* @Date 2018/6/30 11:36
*/
@Setter
@Getter
@ToString(callSuper = true)
public class KeySearchReq extends PageRequestVO{
/**关键字*/
@NotEmpty
private String key;
}
|
package TwoKindsCNC;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class PGV {
static int time;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//定义变量
int updowntime1=30;
int updowntime2=35;
int movetime=23;
int movetime2=41;
int movetime3=59;
int cleantime=30;
int worktime1 = 280;
int worktime2 = 500;
//创建little_car对象
Little_Car little_Car = new Little_Car(updowntime1, updowntime2, movetime,movetime2,movetime3,cleantime);
//创建cnc对象
CNC[] cnc = new CNC[8];
int[][] recordup = new int[8][400];
int[][] recorddown = new int[8][400];
String[][] recorduptime = new String[8][400];
String[][] recorddowntime = new String[8][400];
//为cnc初始化
cnc[0] = new CNC(1,worktime1, 1);
cnc[1] = new CNC(2,worktime2, 1);
cnc[2] = new CNC(3,worktime1, 2);
cnc[3] = new CNC(4,worktime2, 2);
cnc[4] = new CNC(5,worktime1, 3);
cnc[5] = new CNC(6,worktime2, 3);
cnc[6] = new CNC(7,worktime1, 4);
cnc[7] = new CNC(8,worktime2, 4);
int count = 0;
int product = 0;
int first1 = 0;
int first2 = 0;
int second1 = 0;
int second2 = 0;
int number1 = 0;
int number2 = 0;
int flag = 1;
//将cnc状态设置为-1,即空闲
for(int i = 0;i<8;i++) {
cnc[i].setState(-1);
}
for(time = 0;time<=8*60*60;time++) {
//判断cnc有无在繁忙中,若在繁忙中则为其计时器减一秒
for(int i = 0;i<8;i++) {
if(cnc[i].getState() == 0) {
cnc[i].onUpDown();
}else if(cnc[i].getState() == 2) {
cnc[i].onBusy();
}else if (cnc[i].getState() == 4) {
cnc[i].onDown();
}else if (cnc[i].getState() == 6) {
cnc[i].onFault();
}
}
//判断小车是否在繁忙中,若在繁忙中则为其计时器减一秒,且因为小车在繁忙中,整个系统做不了任何事情,故直接跳到下一秒
if(little_Car.isFree() == false && little_Car.state == 1) {
little_Car.onUpDown();
continue;
}else if(little_Car.isFree() == false && little_Car.state == 2) {
little_Car.onMove();
continue;
}else if(little_Car.isFree() == false && little_Car.state == 3) {
little_Car.onClean();
continue;
}
if(flag == 1) { //第一部分:为单数机器上料
//若小车位置和cnc[count]不一样,则让小车移动到cnc[count]位置上
if(little_Car.isFree() == true && little_Car.getPosition() != cnc[count].getPosition()) {
little_Car.move(cnc[count].getPosition());
continue;
}
//若cnc[count]处于空闲状态,且小车处于空闲状态,且小车位置和cnc[count]位置一样,则让小车为cnc[count]上下料
else if(cnc[count].getState() == -1 && little_Car.isFree() == true && little_Car.getPosition() == cnc[count].getPosition()) {
little_Car.updown(count);
if(count%2 == 0) {
recordup[count][number1++] = time;
cnc[count].toUpDown(updowntime1);
}else {
cnc[count].toUpDown(updowntime2);
}
if(count == 6) {
count = 0;
flag = 2;
}else {
count += 2;
}
continue;
}
}else if(flag == 2) { //第二部分:将单数机器上的已完成第一阶段的产品上下料到双数机器上
//若小车位置和cnc[count]不一样,则让小车移动到cnc[count]位置上
if(little_Car.isFree() == true && little_Car.getPosition() != cnc[count].getPosition()) {
little_Car.move(cnc[count].getPosition());
continue;
}
//若cnc[count]处于空闲或处于已完成生产但未下料状态,且小车处于空闲,且小车与cnc[count]位置相同,则让小车为cnc[count]上下料
else if((cnc[count].getState() == -1 || cnc[count].getState() == 3) && little_Car.isFree() == true && little_Car.getPosition() == cnc[count].getPosition()) {
little_Car.updown(count);
if(count%2 == 0) {
recorddown[count][first1++] = time;
recordup[count][number1++] = time;
cnc[count].toUpDown(updowntime1);
}else {
recordup[count][second1++] = time;
cnc[count].toUpDown(updowntime2);
}
if(count == 7) {
count = 1;
flag = 3;
}else {
count++;
}
continue;
}
}else if(flag == 3) { //第三部分:等待双数机器完成加工,然后上下料,然后清洗
if(cnc[count].getState() == 6) {
if(count == 7) {
count = 1;
}else {
count += 2;
}
}
//若小车位置和cnc[count]不一样,则让小车移动到cnc[count]位置上
if(little_Car.isFree() == true && little_Car.getPosition() != cnc[count].getPosition()) {
little_Car.move(cnc[count].getPosition());
continue;
}
//若cnc[count]处于空闲或处于已完成生产但未下料状态,且小车处于空闲,且小车与cnc[count]位置相同,则让小车为cnc[count]上下料
else if(cnc[count].getState() == 3 && little_Car.isFree() == true && little_Car.getPosition() == cnc[count].getPosition()) {
little_Car.updown(count);
if(count%2 == 0) {
cnc[count].toDown(updowntime1);
}else {
recorddown[count][product] = time;
cnc[count].toDown(updowntime2);
}
continue;
}
//若cnc[count]生产过一个产品,且未被清洗过,且小车正处于空闲状态,则让小车清洗物料
else if (cnc[count].product.state == 1 && little_Car.isFree() == true) {
little_Car.clean();
cnc[count].product.state = 0;
count--;
flag = 4;
product++;
continue;
}
}else if (flag == 4) { //第四部分:为双数机器上下料
if(cnc[count].getState() == 6) {
if (count %2 == 0) {
if(count == 7) {
count = 0;
}else {
count++;
}
}else {
if (count == 6) {
count = 0;
}else {
count++;
}
}
flag = 3;
}
//若小车位置和cnc[count]不一样,则让小车移动到cnc[count]位置上
if(little_Car.isFree() == true && little_Car.getPosition() != cnc[count].getPosition()) {
little_Car.move(cnc[count].getPosition());
continue;
}
//若小车位置和cnc[count]一样,且cnc[count]处于已完成生产且未被下料,或者处于已被下料且未被上料的状态,且小车处于空闲,则让小车为cnc[count]上下料
else if((cnc[count].getState() == 3 || cnc[count].getState() == 5) && little_Car.isFree() == true && little_Car.getPosition() == cnc[count].getPosition()) {
little_Car.updown(count);
if(count%2 == 0) {
recorddown[count][first1++] = time;
recordup[count][number1++] = time;
cnc[count].toUpDown(updowntime1);
}else {
recordup[count][second1++] = time;
cnc[count].toUpDown(updowntime2);
}
if(count %2 == 0) {
if (count == 7) {
count = 0;
}else {
count++;
}
}else {
if (count == 7) {
count = 1;
}else {
count += 2;
}
flag = 3;
}
continue;
}
}
}
//将记录的时间格式从秒转化为时分秒
count = 0;
for(int i = 0;i<product;i++) {
recorduptime[count][i] = secToTime(recordup[count][i]);
recorddowntime[count][i] = secToTime(recorddown[count][i]);
recorduptime[count+1][i] = secToTime(recordup[count+1][i]);
recorddowntime[count+1][i] = secToTime(recorddown[count+1][i]);
//System.out.println(recorduptime[count][i] + " " +recorddowntime[count][i]);
if(count == 6) {
count = 0;
}else {
count += 2;
}
}
//创建HSSFWorkbook对象
HSSFWorkbook wb = new HSSFWorkbook();
//创建HSSFSheet对象
HSSFSheet sheet = wb.createSheet("sheet0");
//创建HSSFRow对象
HSSFRow row = sheet.createRow(0);
//创建HSSFCell对象
HSSFCell cell=row.createCell(0);
count = 0;
for(int i = 0;i<product;i++) {
row = sheet.createRow(i);
cell = row.createCell(0);
cell.setCellValue(i+1);
cell = row.createCell(1);
cell.setCellValue(count + 1);
cell = row.createCell(2);
cell.setCellValue(recorduptime[count][i]);
cell = row.createCell(3);
cell.setCellValue(recorddowntime[count][i]);
cell = row.createCell(4);
cell.setCellValue(count + 2);
cell = row.createCell(5);
cell.setCellValue(recorduptime[count+1][i]);
cell = row.createCell(6);
cell.setCellValue(recorddowntime[count+1][i]);
if(count == 6) {
count = 0;
}else {
count += 2;
}
}
//输出Excel文件
FileOutputStream output=new FileOutputStream("d:\\workbook.xls");
wb.write(output);
output.flush();
System.out.println(product);
}
//时间格式秒转时分秒函数
public static String secToTime(int time) {
String timeStr = null;
int hour = 0;
int minute = 0;
int second = 0;
if (time <= 0)
return "00:00:00";
else {
minute = time / 60;
hour = minute / 60;
if (hour > 99)
return "99:59:59";
minute = minute % 60;
second = time - hour * 3600 - minute * 60;
timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
}
return timeStr;
}
public static String unitFormat(int i) {
String retStr = null;
if (i >= 0 && i < 10)
retStr = "0" + Integer.toString(i);
else
retStr = "" + i;
return retStr;
}
public int getTime() {
return PGV.time;
}
}
|
package com.example.vehiclehirebookingsystem.http;
import com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.RequiredArgsConstructor;
import lombok.Value;
/**
* The response object for the request to get cost of hire.
*/
@RequiredArgsConstructor
@JsonNaming(SnakeCaseStrategy.class)
@Value
public class GetCostOfHireResponse {
long cost;
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.core;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.lang.Nullable;
/**
* Helper class that efficiently creates multiple {@link CallableStatementCreator}
* objects with different parameters based on an SQL statement and a single
* set of parameter declarations.
*
* @author Rod Johnson
* @author Thomas Risberg
* @author Juergen Hoeller
*/
public class CallableStatementCreatorFactory {
/** The SQL call string, which won't change when the parameters change. */
private final String callString;
/** List of SqlParameter objects. May not be {@code null}. */
private final List<SqlParameter> declaredParameters;
private int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
private boolean updatableResults = false;
/**
* Create a new factory. Will need to add parameters via the
* {@link #addParameter} method or have no parameters.
* @param callString the SQL call string
*/
public CallableStatementCreatorFactory(String callString) {
this.callString = callString;
this.declaredParameters = new ArrayList<>();
}
/**
* Create a new factory with the given SQL and the given parameters.
* @param callString the SQL call string
* @param declaredParameters list of {@link SqlParameter} objects
*/
public CallableStatementCreatorFactory(String callString, List<SqlParameter> declaredParameters) {
this.callString = callString;
this.declaredParameters = declaredParameters;
}
/**
* Return the SQL call string.
* @since 5.1.3
*/
public final String getCallString() {
return this.callString;
}
/**
* Add a new declared parameter.
* <p>Order of parameter addition is significant.
* @param param the parameter to add to the list of declared parameters
*/
public void addParameter(SqlParameter param) {
this.declaredParameters.add(param);
}
/**
* Set whether to use prepared statements that return a specific type of ResultSet.
* specific type of ResultSet.
* @param resultSetType the ResultSet type
* @see java.sql.ResultSet#TYPE_FORWARD_ONLY
* @see java.sql.ResultSet#TYPE_SCROLL_INSENSITIVE
* @see java.sql.ResultSet#TYPE_SCROLL_SENSITIVE
*/
public void setResultSetType(int resultSetType) {
this.resultSetType = resultSetType;
}
/**
* Set whether to use prepared statements capable of returning updatable ResultSets.
*/
public void setUpdatableResults(boolean updatableResults) {
this.updatableResults = updatableResults;
}
/**
* Return a new CallableStatementCreator instance given these parameters.
* @param params list of parameters (may be {@code null})
*/
public CallableStatementCreator newCallableStatementCreator(@Nullable Map<String, ?> params) {
return new CallableStatementCreatorImpl(params != null ? params : new HashMap<>());
}
/**
* Return a new CallableStatementCreator instance given this parameter mapper.
* @param inParamMapper the ParameterMapper implementation that will return a Map of parameters
*/
public CallableStatementCreator newCallableStatementCreator(ParameterMapper inParamMapper) {
return new CallableStatementCreatorImpl(inParamMapper);
}
/**
* CallableStatementCreator implementation returned by this class.
*/
private class CallableStatementCreatorImpl implements CallableStatementCreator, SqlProvider, ParameterDisposer {
@Nullable
private ParameterMapper inParameterMapper;
@Nullable
private Map<String, ?> inParameters;
/**
* Create a new CallableStatementCreatorImpl.
* @param inParamMapper the ParameterMapper implementation for mapping input parameters
*/
public CallableStatementCreatorImpl(ParameterMapper inParamMapper) {
this.inParameterMapper = inParamMapper;
}
/**
* Create a new CallableStatementCreatorImpl.
* @param inParams list of SqlParameter objects
*/
public CallableStatementCreatorImpl(Map<String, ?> inParams) {
this.inParameters = inParams;
}
@Override
public CallableStatement createCallableStatement(Connection con) throws SQLException {
// If we were given a ParameterMapper, we must let the mapper do its thing to create the Map.
if (this.inParameterMapper != null) {
this.inParameters = this.inParameterMapper.createMap(con);
}
else {
if (this.inParameters == null) {
throw new InvalidDataAccessApiUsageException(
"A ParameterMapper or a Map of parameters must be provided");
}
}
CallableStatement cs = null;
if (resultSetType == ResultSet.TYPE_FORWARD_ONLY && !updatableResults) {
cs = con.prepareCall(callString);
}
else {
cs = con.prepareCall(callString, resultSetType,
updatableResults ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY);
}
int sqlColIndx = 1;
for (SqlParameter declaredParam : declaredParameters) {
if (!declaredParam.isResultsParameter()) {
// So, it's a call parameter - part of the call string.
// Get the value - it may still be null.
Object inValue = this.inParameters.get(declaredParam.getName());
if (declaredParam instanceof ResultSetSupportingSqlParameter) {
// It's an output parameter: SqlReturnResultSet parameters already excluded.
// It need not (but may be) supplied by the caller.
if (declaredParam instanceof SqlOutParameter) {
if (declaredParam.getTypeName() != null) {
cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType(), declaredParam.getTypeName());
}
else {
if (declaredParam.getScale() != null) {
cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType(), declaredParam.getScale());
}
else {
cs.registerOutParameter(sqlColIndx, declaredParam.getSqlType());
}
}
if (declaredParam.isInputValueProvided()) {
StatementCreatorUtils.setParameterValue(cs, sqlColIndx, declaredParam, inValue);
}
}
}
else {
// It's an input parameter; must be supplied by the caller.
if (!this.inParameters.containsKey(declaredParam.getName())) {
throw new InvalidDataAccessApiUsageException(
"Required input parameter '" + declaredParam.getName() + "' is missing");
}
StatementCreatorUtils.setParameterValue(cs, sqlColIndx, declaredParam, inValue);
}
sqlColIndx++;
}
}
return cs;
}
@Override
public String getSql() {
return callString;
}
@Override
public void cleanupParameters() {
if (this.inParameters != null) {
StatementCreatorUtils.cleanupParameters(this.inParameters.values());
}
}
@Override
public String toString() {
return "CallableStatementCreator: sql=[" + callString + "]; parameters=" + this.inParameters;
}
}
}
|
package sample.GAControllers;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import sample.AlgorithmControllers.AlgorithmView;
import sample.AlgorithmControllers.TSPGene;
import sample.AlgorithmControllers.TSPUtils;
import static sample.GAControllers.GeneticAlgorithmController.WIDTH;
public class GeneticAlgorithmView extends AlgorithmView {
public Canvas canvas;
public final TSPPopulation population;
private double Bshort, Ashort;
private static int check = 0;
public GeneticAlgorithmView(){
this.population = new TSPPopulation(TSPUtils.cities, 50);
this.canvas = new Canvas(WIDTH,GeneticAlgorithmController.HEIGHT);
this.getChildren().addAll(canvas);
}
public void draw(Label label){
GraphicsContext gc = this.canvas.getGraphicsContext2D();
Timeline t1 = new Timeline();
t1.setCycleCount(Animation.INDEFINITE);
t1.setAutoReverse(true);
t1.getKeyFrames().add(new KeyFrame(Duration.millis(50), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
if ( check % 50 == 0){
Bshort = getShortestPath();
}
check++;
update();
Ashort = getShortestPath();
gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
drawXY(gc);
label.setText("Shortest Path: " + String.format("%.2f", getShortestPath()));
if(Ashort == Bshort){
drawBest(gc, Color.GREEN);
}else {
drawBest(gc, Color.BLACK);
}
}
}));
t1.play();
}
public void update() {
this.population.update();
}
public double getShortestPath(){
return this.population.getAlpha().getDistance();
}
public String totalCities(){
final java.util.List<TSPGene> chromosome = this.population.getAlpha().getChromosome();
return ("Total Of cities: " + chromosome.size());
}
public void drawBest(javafx.scene.canvas.GraphicsContext gc, Color color) {
final java.util.List<TSPGene> chromosome = this.population.getAlpha().getChromosome();
for(int i = 0; i < chromosome.size() - 1; i++) {
TSPGene gene = chromosome.get(i);
TSPGene neighbor = chromosome.get(i + 1);
if(color == Color.GREEN){
gc.setLineWidth(3);
}
gc.setStroke(color);
gc.strokeLine(gene.getX(), gene.getY(), neighbor.getX(), neighbor.getY());
}
gc.setFill(Color.RED);
for(final TSPGene gene : chromosome) {
gc.fillOval(gene.getX() - 5, gene.getY() - 5, 10, 10);
gc.fillText(String.valueOf(gene.getKey()), gene.getX() -10, gene.getY() -10);
}
}
}
|
package DataStore_fileSYS;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Path;
import java.nio.file.Paths;
public class DataSerializer implements Serializable{
/**
*
*/
private static final long serialVersionUID = -7257227592581261544L;
public DataSerializer(String u, String p, String nm) {
Path p5 = Paths.get(System.getProperty("user.home"),"_mars_Local_REPO", u+nm); //user created
File fi=new File(p5.toUri()+u+p+".ser"); //the user object data is stored here
try(FileOutputStream fout=new FileOutputStream(fi)) {
ObjectOutputStream out =new ObjectOutputStream(fout);
out.writeBytes(nm);
out.writeBytes(p);
out.writeBytes(u);
out.close();
fi.setLastModified(serialVersionUID);
fi.setReadOnly();
System.out.println("new user sucessfully serialized");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
/** TableEntry.java
*
* Author: Greg Choice c9311718@uon.edu.au
*
* Created:
* Updated: 27/09/2018
*
* Description:
* Symbol table record class for the CD18 compiler
*
*/
public class TableEntry
{
private String symbolName;
private String symbolType;
private String symbolValue;
private Token token;
private int line;
private int col;
private int register;
private int offset;
public TableEntry(Token tkn)
{
token = tkn;
symbolName = token.getLexeme();
line = token.getLineNum();
col = token.getColNum();
}
public TableEntry(String parentName, TableEntry entry)
{
symbolName = parentName + "." + entry.symbolName;
symbolType = entry.symbolType;
symbolValue = entry.symbolValue;
token = entry.token;
line = entry.line;
col = entry.col;
}
public TableEntry(TableEntry entry)
{
symbolName = entry.symbolName;
symbolType = entry.symbolType;
symbolValue = entry.symbolValue;
token = entry.token;
line = entry.line;
col = entry.col;
}
public void setRegister(int reg)
{
register = reg;
}
public int getRegister()
{
return register;
}
public void setOffset(int oSet)
{
offset = oSet;
}
public int getOffset()
{
return offset;
}
public void setValue(String value)
{
symbolValue = value;
}
public String getValue()
{
return symbolValue;
}
public void setToken(Token tkn)
{
token = tkn;
}
public Token getToken()
{
return token;
}
public String getName()
{
return symbolName;
}
public String getType()
{
return symbolType;
}
public void setName(String name)
{
symbolName = name;
}
public void setType(String type)
{
symbolType = type;
}
public int getLine()
{
return line;
}
public int getCol()
{
return col;
}
public Token.TID getTokenID()
{
return token.getTokenID();
}
@Override
public boolean equals(Object object)
{
if(object instanceof TableEntry)
{
TableEntry other = (TableEntry)object;
return symbolName.equals(other.getName());
}
return false;
}
}
|
package com.bupsolutions.polaritydetection;
import com.martiansoftware.jsap.*;
public class ArgumentsHandler {
public static final String TEST_LONG = "test";
public static final char TEST_SHORT = 't';
public static final String HELP_LONG = "help";
public static final char HELP_SHORT = 'h';
private JSAP jsap;
private JSAPResult result;
public ArgumentsHandler(String[] args) throws JSAPException {
defineArgs();
result = parseArgs(args);
}
private void defineArgs() throws JSAPException {
this.jsap = new JSAP();
Switch flag;
flag = new Switch(TEST_LONG);
flag.setLongFlag(TEST_LONG);
flag.setShortFlag(TEST_SHORT);
flag.setDefault("false");
flag.setHelp("Show accuracy measured by holdout validation.");
jsap.registerParameter(flag);
flag = new Switch(HELP_LONG);
flag.setLongFlag(HELP_LONG);
flag.setShortFlag(HELP_SHORT);
flag.setDefault("false");
flag.setHelp("Print this help message.");
jsap.registerParameter(flag);
}
public JSAPResult parseArgs(String[] args) throws JSAPException {
defineArgs();
if (args == null) {
args = new String[0];
}
JSAPResult arguments = jsap.parse(args);
if (arguments.getBoolean(HELP_LONG)) {
printHelp();
System.exit(0);
}
if (!arguments.success()) {
// print out specific error messages describing the problems
java.util.Iterator<?> errs = arguments.getErrorMessageIterator();
while (errs.hasNext()) {
System.err.println("Error: " + errs.next());
}
printHelp();
System.exit(-1);
}
return arguments;
}
private void printHelp() {
printUsage();
System.err.println("Options:");
System.err.println();
System.err.println(jsap.getHelp());
}
private void printUsage() {
System.err.println("Usage:");
System.err.println("./polarityDetection [OPTIONS]");
System.err.println();
}
public boolean holdout() {
return result.getBoolean(TEST_LONG);
}
}
|
package com.metoo.foundation.dao;
import org.springframework.stereotype.Repository;
import com.metoo.core.base.GenericDAO;
import com.metoo.foundation.domain.FreeGoods;
@Repository("freeGoodsDAO")
public class FreeGoodsDAO extends GenericDAO<FreeGoods> {
}
|
package com.toda.consultant.fragment;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.toda.consultant.HouseInfoActivity;
import com.toda.consultant.R;
import com.toda.consultant.SecondHouseTypeActivity;
import com.toda.consultant.adapter.HouseListAdapter;
import com.toda.consultant.bean.SecondHouseListBean;
import com.toda.consultant.model.RequestParams;
import com.toda.consultant.model.ResultData;
import com.toda.consultant.statics.Task;
import com.toda.consultant.util.DeviceUtils;
import com.toda.consultant.util.HandlerRequestErr;
import com.toda.consultant.util.IConfig;
import com.toda.consultant.view.CommonListView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
/**
* 二手房源
*/
public class SecondHouseListFragment extends BaseFragment implements AdapterView.OnItemClickListener, CommonListView.OnRefreshListener {
@BindView(R.id.lv_list)
CommonListView lvList;
private HouseListAdapter adapter;
List<SecondHouseListBean.ListBean> mList = new ArrayList<>();
public SecondHouseListFragment() {
// Required empty public constructor
}
public static SecondHouseListFragment newInstance() {
SecondHouseListFragment fragment = new SecondHouseListFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_second_list, container, false);
ButterKnife.bind(this, view);
initView(view);
lvList.refresh(false);
return view;
}
/***
* 二手房源列表
*/
private void getHouseList(int pageNum) {
RequestParams params = new RequestParams(IConfig.URL_SECOND_HOUSE_LIST);
params.add("pageNum", pageNum + "");
params.add("numPerPage", pageSize + "");
startRequest(Task.SECOND_HOUSE_LIST, params, SecondHouseListBean.class, false);
}
@Override
public void onRefresh(Call call, int tag, ResultData data) {
super.onRefresh(call, tag, data);
switch (tag) {
case Task.SECOND_HOUSE_LIST:
if (HandlerRequestErr.handlerListViewErr(getContext(), lvList, data)) {
SecondHouseListBean bean = (SecondHouseListBean) data.getData();
List<SecondHouseListBean.ListBean> list = bean.getList();
lvList.notifyDataSetChanged(list);
}
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void initView(View view) {
lvList.getListView().setDivider(new ColorDrawable(getContext().getResources().getColor(R.color.line_color)));
lvList.getListView().setDividerHeight(DeviceUtils.dip2px(getContext(), 1));
lvList.setListener(this);
lvList.setList(mList);
adapter = new HouseListAdapter(getContext(), mList);
lvList.getListView().setOnItemClickListener(this);
lvList.setAdapter(adapter);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SecondHouseListBean.ListBean bean = mList.get(position - lvList.getListView().getHeaderViewsCount());
Bundle bundle = new Bundle();
bundle.putString(KEY_HOUSE_ID, bean.getSecondHousePersonalId() + "");
if (bean.getIsChecked() == 1) { //已核验
goPage(SecondHouseTypeActivity.class, bundle);
} else { //待核验
goPage(HouseInfoActivity.class, bundle);
}
}
@Override
public void onPullDownToRefresh(int currentPage) {
getHouseList(currentPage);
}
@Override
public void onPullUpToRefresh(int currentPage) {
getHouseList(currentPage);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.