text stringlengths 10 2.72M |
|---|
/*자바의 모든 컴포넌트는 스스로 그림의 주체이자 즉 화자이자, 그림의 대상 즉 도화지가 된다*/
package app0512.graphic;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
public class LineTest extends JFrame{
//자바의 모든 컴포넌트는 부모 GUI객체로부터, paint메서드를 물려받아,
//자기 자신에게 알맞는 그림을 스스로 그린거다! 특히 그림 그리는 메서드인 paint 메서드에는
//붓만으로는 그릠을 그릴 수 없기 때문에 팔레트 역할을 수행하는 Graphics 객체가 인수로 넘어온다!
//특히, 시스템 즉 컴포넌트에 의한 그림이 아닌, 개발자가 주도하여 그림을 그리려면 paint 메서드를
//재정의 즉 오버라이드 하면 된다!!
@Override
public void paint(Graphics g) {
// System.out.println("print호출");
g.drawLine(100, 50, 250, 380);// 선 그리기
g.drawOval(100, 200, 100, 100);//원 그리기
g.drawRect(10, 250, 80, 80);//사각형 그리기
g.fillOval(30, 300, 90, 90);//채워진 원 그리기
//색상처리
g.setColor(Color.red);
g.fillRect(300, 200, 50, 100);//빨간색의 직사각형
//텍스트도 그려보자!
g.setFont(new Font("Verdana", Font.BOLD|Font.ITALIC, 50));
g.drawString("apple", 20, 400);
}
public LineTest() {
setSize(600, 500);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new LineTest();
}
}
|
package com.fullsail.e_davila_advancedviews;
public class IOUtils {
}
|
package com.repository;
import org.openqa.selenium.By;
public interface signInRepos {
By phone=By.className("/html/body/div[2]/div/div/div/div/div[2]/div/form/div[1]/input");
By passwordnumber=By.xpath("/html/body/div[2]/div/div/div/div/div[2]/div/form/div[2]/input");
By login=By.xpath("/html/body/div[2]/div/div/div/div/div[2]/div/form/div[3]/button");
}
|
package tw3b;
import java.util.Scanner;
class Rectangle{
int length, breadth, area;
Rectangle()
{
}
Rectangle(int l, int b)
{
length = l;
breadth = b;
}
void computeArea(int length, int breadth)
{
area = length * breadth;
System.out.println("Area of Rectangle :" + area);
}
}
public class TW3b {
public static void main(String[] args) {
int length, breadth;
Scanner in = new Scanner (System.in);
Rectangle r = new Rectangle();
System.out.println("Enter length and breadth:");
length = in.nextInt();
breadth = in.nextInt();
r.computeArea(length, breadth);
}
}
|
package com.techlab.frame;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class WelcomeFrame extends JFrame {
public WelcomeFrame() {
this.setVisible(true);
this.setTitle("sonam");
this.setSize(500, 500);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
this.add(panel);
}
}
|
package it.univaq.rtv.Model.FactoryMappa;
import it.univaq.rtv.Model.*;
import it.univaq.rtv.Utility.CittaDTO;
import it.univaq.rtv.Model.FactoryCitta.ICitta;
import com.lynden.gmapsfx.javascript.object.LatLong;
import it.univaq.rtv.Model.FactoryMezzo.Vagone;
import it.univaq.rtv.Utility.Utility;
import java.util.ArrayList;
import java.util.HashSet;
public abstract class AbstractMappa {
protected String nome;
protected ArrayList<Percorso> p=new ArrayList<Percorso>();
/**
* @return
*/
public String getNome() {
return this.nome;
}
/**
* @param p1
*/
public void addPercorso(Percorso p1){
this.p.add(p1);
}
/**
* @return
*/
public ArrayList<Percorso> dammiPercorsi() {
return this.p;
}
/**
* @param giocatores
*/
public void popolaMappa(ArrayList<Giocatore> giocatores) {
for(int i=0; i<giocatores.size();i++){
Giocatore g=giocatores.get(i);
FactorMezzo factory= new FactorMezzo();
Vagone v=(Vagone) factory.getMezzo("Vagone", g);
CartaPercorso c1=g.chiediCartaPercorso();
for(int j=0;j<this.p.size();j++){
Percorso p1=p.get(j);
p1.trovaPercorso(c1,factory,g);
}
}
}
/**
* @return
*/
public ArrayList<ICitta> getCitta(){
ArrayList<ICitta> c=new ArrayList<ICitta>();
for(int i=0; i<this.p.size();i++) {
Percorso percorso = p.get(i);
ICitta citta1=percorso.getCittaPartenza();
ICitta citta2=percorso.getCittaArrivo();
c.add(citta1);
c.add(citta2);
}
java.util.Set setta_citta=new HashSet(c);
ArrayList<ICitta> c1=new ArrayList<ICitta>(setta_citta);
return c1;
}
/**
* @param percorso
* @return
*/
public ArrayList<Percorso> getViciniPercorsoPartenza(Percorso percorso){
ArrayList<Percorso> percorsos=new ArrayList<>();
for (int a = 0; a < this.dammiPercorsi().size(); a++) {
Percorso per1 = this.dammiPercorsi().get(a);
if(percorso.getid()==per1.getid());
else if ( percorso.getCittaPartenza().getNome().equals(per1.getCittaPartenza().getNome())
||percorso.getCittaPartenza().getNome().equals(per1.getCittaArrivo().getNome())
){
percorsos.add(per1);
}
}
return percorsos;
}
/**
* @param percorso
* @return
*/
public ArrayList<Percorso> getViciniPercorsoArrivo(Percorso percorso){
ArrayList<Percorso> percorsos=new ArrayList<>();
for (int a = 0; a < this.dammiPercorsi().size(); a++) {
Percorso per1 = this.dammiPercorsi().get(a);
if(percorso.getid()==per1.getid());
else if ( percorso.getCittaArrivo().getNome().equals(per1.getCittaArrivo().getNome())
||percorso.getCittaArrivo().getNome().equals(per1.getCittaPartenza().getNome())
){
percorsos.add(per1);
}
}
return percorsos;
}
/**
* @param p
* @param c
* @return
*/
public ArrayList<Casella> getCaselleVicinePercorsi(ArrayList<Percorso> p, Casella c){
ArrayList<Casella> casellas= new ArrayList<>();
for(int i=0; i<p.size();i++)
casellas.add(p.get(i).getCasellaPerVicino(c));
return casellas;
}
/**
* @param c
* @return
*/
public Percorso getPercorsoByCasella(Casella c){
ArrayList<Percorso> percorsi = this.dammiPercorsi();
boolean esci=false;
int i;
ArrayList<Casella> caselle = new ArrayList<>();
for (i=0; i <percorsi.size();i++){
caselle= percorsi.get(i).getCaselle();
for(int j=0;j<caselle.size();j++) {
if (c.getId() ==caselle.get(j).getId()) {
esci=true;
break;}
}
if(esci==true) break;
}
return percorsi.get(i);
}
/**
* @param percorsi
* @return
*/
public ArrayList<Percorso> rimuoviDuplicati(ArrayList<Percorso> percorsi) {
ArrayList<Percorso> percorso_no_s = percorsi;
for (int i = 0; i < percorsi.size(); i++) {
Percorso percorso = percorsi.get(i);
for (int j = 0; j < percorsi.size(); j++) {
Percorso percorso1 = percorsi.get(j);
if (percorso.getid() != percorso1.getid()) {
if (Utility.equalsPartenza(percorso1,percorso)) {
percorso1.removeCasella(percorso1.getCasellaPartenza());
percorso_no_s.remove(percorso1);
percorso_no_s.add(percorso1);
} else if (Utility.equalsPartenzaArrivo(percorso1,percorso)) {
percorso1.removeCasella(percorso1.getCasellaPartenza());
percorso_no_s.remove(percorso1);
percorso_no_s.add(percorso1);
} else if (Utility.equalsArrivoPartenza(percorso1,percorso)) {
percorso1.removeCasella(percorso1.getCasellaArrivo());
percorso_no_s.remove(percorso1);
percorso_no_s.add(percorso1);
} else if (Utility.equalsArrivo(percorso1,percorso)) {
percorso1.removeCasella(percorso1.getCasellaArrivo());
percorso_no_s.remove(percorso1);
percorso_no_s.add(percorso1);
}
}
}
}
return percorso_no_s;
}
/**
* @return
*/
public LatLong calcolaCentro(){
ArrayList<ICitta> cittas=new ArrayList<ICitta>();
cittas=this.getCitta();
LatLong l=null;
double inizioLat=cittas.get(0).getCoordinate().getLatitude();
double inizioLong=cittas.get(0).getCoordinate().getLongitude();
double lat_min=inizioLat,lat_max=inizioLat,long_min=inizioLong, long_max=inizioLong, lat, longi;
for (int i=1; i<cittas.size();i++){
if(cittas.get(i).getCoordinate().getLatitude()>lat_max) lat_max=cittas.get(i).getCoordinate().getLatitude();
if(cittas.get(i).getCoordinate().getLatitude()<lat_min) lat_min=cittas.get(i).getCoordinate().getLatitude();
if(cittas.get(i).getCoordinate().getLongitude()>long_max) long_max=cittas.get(i).getCoordinate().getLongitude();
if(cittas.get(i).getCoordinate().getLongitude()<long_min) long_min=cittas.get(i).getCoordinate().getLongitude();
}
lat=(lat_max+lat_min)/2;
longi=(long_max+long_min)/2;
l=new LatLong(lat,longi);
return l;
}
/**
* @return
*/
public ArrayList<ICitta> creaMappa(){
ArrayList<ICitta> c1 = new ArrayList<ICitta>();
try{
CittaDTO[] cittaDTOS =Utility.getRestConnection(this.nome);
for(CittaDTO entry: cittaDTOS){
ICitta citta = FactorCitta.getCitta("Normale",entry.getNome());
citta.impostaCoordinate(new LatLong(entry.getLatitude(),entry.getLongitude()));
c1.add(citta);
}
}
catch (Exception e) {
System.out.println("Try Again");
}
finally {
return c1;
}
}
}
|
package shangguigu;
/**
* 线程死锁:即一个方法调用过程中,需要另一个资源的锁,而另一个资源锁需要本资源的锁,这样就造成双方
* 僵持不下的局面.
*/
public class Thread8 {
private Object o1= new Object();
private Object o2= new Object();
public void m1(){
synchronized (o1){
System.out.println("m1.....");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2){
System.out.println("m2.....");
}
}
}
public void m2(){
synchronized (o2){
System.out.println("m2.....");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1){
System.out.println("m1.....");
}
}
}
public static void main(String[] args) {
Thread8 thread8 = new Thread8();
new Thread(()->thread8.m1()).start();
new Thread(()->thread8.m2()).start();
}
}
|
package com.mx.profuturo.bolsa.model.service.candidates.dto;
import java.util.LinkedList;
public class SetScoreCandidateInDTO {
private Integer id;
private Integer calificacion;
private Integer idCandidato;
private int idCalificacion;
private LinkedList<Integer> subCalificacion;
public Integer getIdCandidato() {
return idCandidato;
}
public void setIdCandidato(Integer idCandidato) {
this.idCandidato = idCandidato;
}
public int getIdCalificacion() {
return idCalificacion;
}
public void setIdCalificacion(int idCalificacion) {
this.idCalificacion = idCalificacion;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCalificacion() {
return calificacion;
}
public void setCalificacion(Integer calificacion) {
this.calificacion = calificacion;
}
public LinkedList<Integer> getSubCalificacion() { return subCalificacion; }
public void setSubCalificacion(LinkedList<Integer> subCalificacion) { this.subCalificacion = subCalificacion; }
}
|
package lombok_test;
import lombok.AllArgsConstructor;
import lombok.Value;
/**
* Description:
*
* @author Baltan
* @date 2019-12-01 18:13
*/
@Value
@AllArgsConstructor
public class Computer {
private String brand;
private String model;
private float price;
}
|
import java.util.*;
import java.io.*;
public class UserInterface {
private static UserInterface userInterface;
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private static Warehouse warehouse;
enum Actions {
EXIT,
ADD_CLIENT,
EDIT_CLIENT,
ADD_SUPPLIER,
ADD_PRODUCTS,
EDIT_PRODUCTS,
SHOW_CLIENTS,
SHOW_SUPPLIERS,
SHOW_PRODUCTS,
DISPLAY_CART,
ADD_TO_CART,
EMPTY_CART,
PLACE_ORDER,
SHOW_ORDERS,
SHOW_INVOICES,
WAITLIST_ITEM,
SHOW_WAITLIST,
SHOW_BALANCE,
SHOW_OUTSTANDING,
SHOW_PRODUCTS_WAITLIST,
MAKE_PAYMENT,
SHOW_TRANSACTIONS,
EDIT_SHOPPING_CART,
SHOW_INVENTORY,
RECEIVE_SHIPMENT,
SAVE,
HELP,
}
private UserInterface() {
if (yesOrNo("Look for saved data and use it?")) {
retrieve();
} else {
warehouse = Warehouse.instance();
}
}
public static UserInterface instance() {
if (userInterface == null) {
return userInterface = new UserInterface();
} else {
return userInterface;
}
}
public void help() {
System.out.println("Enter a number between " + Actions.EXIT.ordinal() + " and " + Actions.HELP.ordinal() + " as explained below:");
System.out.println(Actions.EXIT.ordinal() + " to Exit\n");
System.out.println(Actions.ADD_CLIENT.ordinal() + " to add a client");
System.out.println(Actions.EDIT_CLIENT.ordinal() + " to edit a client");
System.out.println(Actions.ADD_SUPPLIER.ordinal() + " to add a supplier");
System.out.println(Actions.ADD_PRODUCTS.ordinal() + " to add products");
System.out.println(Actions.EDIT_PRODUCTS.ordinal() + " to edit products");
System.out.println(Actions.SHOW_CLIENTS.ordinal() + " to display all clients");
System.out.println(Actions.SHOW_SUPPLIERS.ordinal() + " to display all suppliers");
System.out.println(Actions.SHOW_PRODUCTS.ordinal() + " to display all products");
System.out.println(Actions.DISPLAY_CART.ordinal() + " to display all products in a client's shopping cart");
System.out.println(Actions.ADD_TO_CART.ordinal() + " to add products to a client's shopping cart");
System.out.println(Actions.EMPTY_CART.ordinal() + " to remove all products from a client's shopping cart");
System.out.println(Actions.PLACE_ORDER.ordinal() + " to place an order");
System.out.println(Actions.SHOW_ORDERS.ordinal() + " to display all orders");
System.out.println(Actions.SHOW_INVOICES.ordinal() + " to display all invoices");
System.out.println(Actions.WAITLIST_ITEM.ordinal() + " to add to the waitlist");
System.out.println(Actions.SHOW_WAITLIST.ordinal() + " to display the waitlist");
System.out.println(Actions.SHOW_BALANCE.ordinal() + " to display a client's balance");
System.out.println(Actions.MAKE_PAYMENT.ordinal() + " to add to a client's balance");
System.out.println(Actions.SHOW_TRANSACTIONS.ordinal() + " to display a list of a client's transactions");
System.out.println(Actions.SHOW_OUTSTANDING.ordinal() + " to display all oustanding balances");
System.out.println(Actions.SHOW_PRODUCTS_WAITLIST.ordinal() + " to display products, stock, and waitlist amt");
System.out.println(Actions.EDIT_SHOPPING_CART.ordinal() + " to edit the shopping cart");
System.out.println(Actions.SHOW_INVENTORY.ordinal() + " to view the warehouse's inventory");
System.out.println(Actions.RECEIVE_SHIPMENT.ordinal() + " to receive a shipment");
System.out.println(Actions.SAVE.ordinal() + " to save the current state of the warehouse");
System.out.println(Actions.HELP.ordinal() + " for help");
}
private void save() {
if (warehouse.save()) {
System.out.println(" The warehouse has been successfully saved in the file WarehouseData \n" );
} else {
System.out.println(" There has been an error in saving \n" );
}
}
private void retrieve() {
try {
Warehouse tempWarehouse = Warehouse.retrieve();
if (tempWarehouse != null) {
System.out.println(" The warehouse has been successfully retrieved from the file WarehouseData \n" );
warehouse = tempWarehouse;
} else {
System.out.println("File doesnt exist; creating new warehouse" );
warehouse = Warehouse.instance();
}
} catch(Exception cnfe) {
cnfe.printStackTrace();
}
}
public String getToken(String prompt) {
do {
try {
System.out.println(prompt);
String line = reader.readLine();
StringTokenizer tokenizer = new StringTokenizer(line,"\n\r\f");
if (tokenizer.hasMoreTokens()) {
return tokenizer.nextToken();
}
} catch (IOException ioe) {
System.exit(0);
}
} while (true);
}
private boolean yesOrNo(String prompt) {
String more = getToken(prompt + " (Y|y)[es] or anything else for no");
if (more.charAt(0) != 'y' && more.charAt(0) != 'Y') {
return false;
}
return true;
}
public int getInt(String prompt) {
do {
try {
String item = getToken(prompt);
Integer num = Integer.parseInt(item);
return num.intValue();
} catch (NumberFormatException nfe) {
System.out.println("Please input a number ");
}
} while (true);
}
public double getDouble(String prompt) {
do {
try {
String item = getToken(prompt);
Double num = Double.parseDouble(item);
return num.doubleValue();
} catch (NumberFormatException nfe) {
System.out.println("Please input a number ");
}
} while (true);
}
public Actions getCommand() {
do {
try {
int value = Integer.parseInt(getToken("Enter command:" + Actions.HELP.ordinal() + " for help"));
for ( Actions action : Actions.values() ) {
if ( value == action.ordinal() ) {
return action;
}
}
} catch (NumberFormatException nfe) {
System.out.println("Enter a number");
}
} while (true);
}
public void addClient() {
String firstName = getToken("Enter client's first name");
String lastName = getToken("Enter client's last name");
String address = getToken("Enter address");
Client result = warehouse.addClient(firstName, lastName, address);
if (result == null) {
System.out.println("Could not add member");
}
System.out.println(result);
}
public void waitlistItem() {
String clientId = getToken("Enter existing client id");
String productId = getToken("Enter exising product id");
int quantity = getInt("Enter quantity to waitlist");
boolean result = warehouse.waitlistItem(clientId, productId, quantity);
if ( result ) {
System.out.println("Successfully waitlisted items");
} else {
System.out.println("Could not waitlist item");
}
}
public void showWaitlist() {
Iterator<WaitItem> waitlist = warehouse.getWaitlist();
while (waitlist.hasNext()){
WaitItem item = waitlist.next();
System.out.println(item.toString());
}
}
public void addSupplier() {
String name = getToken("Enter supplier name");
Supplier result = warehouse.addSupplier(name);
if (result == null) {
System.out.println("Could not add member");
}
System.out.println(result);
}
public void addProducts() {
Product result;
do {
String name = getToken("Enter name");
int quantity = getInt("Enter quantity");
double salePrice = getDouble("Enter Sale Price");
double supplyPrice = getDouble("Enter Supply Price");
result = warehouse.addProduct(name, quantity, salePrice, supplyPrice);
if (result != null) {
System.out.println(result);
} else {
System.out.println("Product could not be added");
}
if (!yesOrNo("Add more products?")) {
break;
}
} while (true);
}
public void editClient() {
Client result;
String id = getToken("Enter client id to edit");
result = warehouse.getClientById(id);
if (result != null) {
System.out.println(result);
if (yesOrNo("Edit name?")) {
String fname = getToken("Enter new first name");
String lname = getToken("Enter new last name");
result.setFirstName(fname);
result.setLastName(lname);
}
if (yesOrNo("Edit Address?")) {
String address = getToken("Enter new address");
result.setAddress(address);
}
} else {
System.out.println("Could not find that client id");
}
}
public void editProducts() {
Product result;
do {
String id = getToken("Enter product id to edit");
result = warehouse.getProductById(id);
if (result != null) {
System.out.println(result);
if (yesOrNo("Edit name?")) {
String name = getToken("Enter new product name");
result.setName(name);
}
if (yesOrNo("Edit Sale Price")) {
double price = getDouble("Enter new sale price");
result.setSalePrice(price);
}
if (yesOrNo("Edit Supply Price")) {
double price = getDouble("Enter new supply price");
result.setSupplyPrice(price);
}
} else {
System.out.println("Could not find that product id");
}
if (!yesOrNo("Edit more products?")) {
break;
}
} while (true);
}
public void showClients() {
Iterator<Client> allClients = warehouse.getClients();
while (allClients.hasNext()){
Client client = allClients.next();
System.out.println(client.toString());
}
}
public void showSuppliers() {
Iterator<Supplier> allSuppliers = warehouse.getSuppliers();
while (allSuppliers.hasNext()){
Supplier supplier = allSuppliers.next();
System.out.println(supplier.toString());
}
}
public void showProducts() {
Iterator<Product> allProducts = warehouse.getProducts();
while (allProducts.hasNext()){
Product product = allProducts.next();
System.out.println(product.toString());
}
}
public void addToCart() {
Client client;
Product product;
String clientId = getToken("Enter client id to add to their shopping cart");
client = warehouse.getClientById(clientId);
if (client != null) {
System.out.println("Client found:");
System.out.println(client);
do {
String productId = getToken("Enter product id");
product = warehouse.getProductById(productId);
if(product != null) {
System.out.println("Product found:");
System.out.println(product);
int productQuantity = getInt("Enter enter quantity");
warehouse.addToCart(clientId, product, productQuantity);
} else {
System.out.println("Could not find that product id");
}
if (!yesOrNo("Add another product to the shopping cart?")) {
break;
}
} while (true);
} else {
System.out.println("Could not find that client id");
}
}
public void displayCart() {
Client client;
String clientId = getToken("Enter client id to view to their shopping cart");
client = warehouse.getClientById(clientId);
if (client != null) {
System.out.println("Client found:");
System.out.println(client);
System.out.println("Shopping Cart:");
warehouse.displayCart(clientId);
} else {
System.out.println("Could not find that client id");
}
}
public void emptyCart() {
Client client;
String clientId = getToken("Enter client id to empty to their shopping cart");
client = warehouse.getClientById(clientId);
if (client != null) {
System.out.println("Client found:");
System.out.println(client);
if(!yesOrNo("Are you sure you wish to empty the shopping cart?")) {
warehouse.emptyCart(clientId);
System.out.println("Shopping Cart has been emptied");
} else {
System.out.println("Canceled, shopping cart was not emptied");
}
} else {
System.out.println("Could not find that client id");
}
}
public void placeOrder() {
Client client;
String clientId = getToken("Enter client id to place an order");
client = warehouse.getClientById(clientId);
if (client != null) {
System.out.println("Client found:");
System.out.println(client);
//ensure the cart is not empty
Iterator<ShoppingCartItem> cartIterator = client.getShoppingCart().getShoppingCartProducts();
if (cartIterator.hasNext()) {
System.out.println("Shopping Cart Total: $" + client.getShoppingCart().getTotalPrice());
if(yesOrNo("Are you sure you wish to place an order?")) {
if(warehouse.placeOrder(clientId)) {
System.out.println("Order placed, total price charged to client's balance,");
System.out.println("invoice generated, and shopping cart has been emptied.");
} else {
System.out.println("Unable to place order");
}
} else {
System.out.println("Canceled, order was not placed");
}
} else {
System.out.println("Shopping cart is empty, unable to place order");
}
} else {
System.out.println("Could not find that client id");
}
}
public void showBalance() {
Client result;
String id = getToken("Enter client id to see balance");
result = warehouse.getClientById(id);
if (result != null) {
System.out.println("Current Balance: $" + result.getBalance());
} else {
System.out.println("Could not find that client id");
}
}
public void showOrders() {
Iterator<Order> allOrders = warehouse.getOrders();
while (allOrders.hasNext()){
Order order = allOrders.next();
System.out.println(order.toString());
}
}
public void showInvoices() {
Iterator<Invoice> allInvoices = warehouse.getInvoices();
while (allInvoices.hasNext()){
Invoice invoice = allInvoices.next();
System.out.println(invoice.toString());
}
}
public void processPayment() {
Client client;
String clientId = getToken("Enter client id to make a payment");
client = warehouse.getClientById(clientId);
if (client != null) {
Double paymentAmount = getDouble("Enter payment amount");
if(warehouse.makePayment(clientId, paymentAmount)) {
System.out.println("Payment Successful, new balance: " + client.getBalance());
}
} else {
System.out.println("Could not find that client id");
}
}
public void showOutstanding() {
Iterator<Client> allClients = warehouse.getClients();
while (allClients.hasNext()){
Client temp = allClients.next();
if (temp.getBalance() < 0){
System.out.println(temp.toString());
}
}
}
public void showProductsWaitlist() {
int amt = 0;
Iterator<Product> allProducts = warehouse.getProducts();
while(allProducts.hasNext()) {
Product tempProduct = allProducts.next();
Iterator<WaitItem> waitList = warehouse.getWaitlist();
while(waitList.hasNext()) {
WaitItem tempWaitItem = waitList.next();
if(tempProduct == tempWaitItem.getProduct()) {
amt += tempWaitItem.getQuantity();
}
}
System.out.println(tempProduct.toString() + " " + amt);
amt = 0;
}
}
public void showManufacturerAndPrice() {
Client client;
String clientId = getToken("Enter client id to make a payment");
client = warehouse.getClientById(clientId);
if (client != null) {
Double paymentAmount = getDouble("Enter payment amount");
if(warehouse.makePayment(clientId, paymentAmount)) {
System.out.println("Payment Successful, new balance: " + client.getBalance());
}
} else {
System.out.println("Could not find that client id");
}
}
public void showTransactions() {
Client client;
String clientId = getToken("Enter client id to see transactions");
client = warehouse.getClientById(clientId);
if (client != null) {
System.out.println("Transaction List: ");
Iterator<Transaction> transactions = warehouse.getTransactions(clientId);
while (transactions.hasNext()){
System.out.println(transactions.next().toString());
}
} else {
System.out.println("Could not find that client id");
}
}
public void editShoppingCart() {
String clientId = getToken("Enter client id to edit shopping cart");
Client client = warehouse.getClientById(clientId);
Boolean done = false;
if (client == null) {
System.out.println("Client does not exist");
return;
}
ShoppingCart cart = client.getShoppingCart();
while (!done) {
System.out.println("Shopping Cart:");
System.out.println(cart.toString());
String productId = getToken("Enter Product ID in cart to edit");
Iterator<ShoppingCartItem> cartIter = cart.getShoppingCartProducts();
// find the product in in the shopping cart
ShoppingCartItem item = null;
while ( cartIter.hasNext() ) {
ShoppingCartItem next = cartIter.next();
if (cartIter.next().getProduct().getId() == productId) {
item = next;
break;
}
}
if ( item == null ) {
done = !yesOrNo("That ID was not found in the shoping cart? Continue?");
} else {
int newQuantity = getInt("Enter the desired amount to put in your shopping cart.");
item.setQuantity(newQuantity);
done = !yesOrNo("Would you like to edit more items in your cart?");
}
}
}
public void showInventory() {
Iterator<InventoryItem> inventoryIterator = warehouse.getInventory();
while (inventoryIterator.hasNext()){
System.out.println(inventoryIterator.next().toString());
}
}
public void recieveShipment() {
Product p;
do {
String productId = getToken("Enter productId");
p = warehouse.getProductById(productId);
if(p != null) {
int quantity = getInt("Enter quantity");
//check for waitlisted orders
List<WaitItem> waitlistedOrders = warehouse.getWaitItemsByProductId(productId);
Iterator<WaitItem> waitlistedOrdersIterator = waitlistedOrders.iterator();
while(waitlistedOrdersIterator.hasNext()) {
WaitItem waitItem = waitlistedOrdersIterator.next();
System.out.println("Waitlisted Order found for provided product:");
System.out.println(waitItem.toString());
if(yesOrNo("Fill waitlisted order?")) {
quantity -= waitItem.getQuantity();
waitItem.setOrderFilled(true);
System.out.println("Order filled.");
} else {
System.out.println("Order was not filled.");
}
}
// add remaining product to inventory
warehouse.addToInventory(productId, quantity);
} else {
System.out.println("Product not found");
}
if (!yesOrNo("Receive another product?")) {
break;
}
} while(true);
}
public void process() {
Actions command;
help();
while ((command = getCommand()) != Actions.EXIT) {
switch (command) {
case ADD_CLIENT:
addClient();
break;
case EDIT_CLIENT:
editClient();
break;
case ADD_SUPPLIER:
addSupplier();
break;
case ADD_PRODUCTS:
addProducts();
break;
case EDIT_PRODUCTS:
editProducts();
break;
case SHOW_CLIENTS:
showClients();
break;
case SHOW_SUPPLIERS:
showSuppliers();
break;
case SHOW_PRODUCTS:
showProducts();
break;
case DISPLAY_CART:
displayCart();
break;
case ADD_TO_CART:
addToCart();
break;
case EMPTY_CART:
emptyCart();
break;
case PLACE_ORDER:
placeOrder();
break;
case SHOW_ORDERS:
showOrders();
break;
case SHOW_INVOICES:
showInvoices();
break;
case WAITLIST_ITEM:
waitlistItem();
break;
case SHOW_WAITLIST:
showWaitlist();
break;
case SHOW_BALANCE:
showBalance();
break;
case SHOW_OUTSTANDING:
showOutstanding();
break;
case SHOW_PRODUCTS_WAITLIST:
showProductsWaitlist();
break;
case MAKE_PAYMENT:
processPayment();
break;
case SHOW_TRANSACTIONS:
showTransactions();
break;
case SHOW_INVENTORY:
showInventory();
break;
case RECEIVE_SHIPMENT:
recieveShipment();
break;
case SAVE:
save();
break;
case EDIT_SHOPPING_CART:
editShoppingCart();
break;
case HELP:
help();
break;
}
}
}
public static void main(String[] s) {
UserInterface.instance().process();
}
}
|
package com.challenges.algo.leetcode;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class IntToRoman {
public String intToRoman(int num) {
Map<Integer, String> mapSet=new LinkedHashMap<>();
mapSet.put(1000, "M");
mapSet.put(900, "CM");
mapSet.put(500, "D");
mapSet.put(400, "CD");
mapSet.put(100, "C");
mapSet.put(90, "XC");
mapSet.put(50, "L");
mapSet.put(40, "XL");
mapSet.put(10, "X");
mapSet.put(9, "IX");
mapSet.put(5, "V");
mapSet.put(4, "IV");
mapSet.put(1, "I");
StringBuilder result=new StringBuilder();
Set< Map.Entry<Integer,String> > st = mapSet.entrySet();
for (Map.Entry<Integer,String> inside: st) {
while (num-inside.getKey()>=0) {
System.out.println(inside.getKey());
result.append(inside.getValue());
num=num-inside.getKey();
}
}
return result.toString();
}
}
|
package de.telekom.sea4.webserver.model;
import java.util.List;
import java.util.ArrayList;
public class Personen {
private List<Person> personen = new ArrayList<Person>();
// standard constructor
public Personen() { }
// constructor mit ArrayList
public Personen(List<Person> all) {
this.personen = all;
}
public List<Person> getPersonen() {
return personen;
}
public void setPersonen(List<Person> personen) {
this.personen = personen;
}
}
|
package ru.kappers.model.catalog;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import ru.kappers.model.mapping.TeamBridge;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.List;
/**
* JPA-сущность для команды
*/
@Slf4j
@Data
@Builder
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "team")
public class Team {
@Id
@Column(name = "team_id", nullable = false, insertable = false, updatable = false)
private Integer id;
/**
* название команды
*/
@Column(name = "name")
@Size(max = 255)
@NotBlank
private String name;
@Column(name = "code")
@Size(max = 8)
private String code;
@Column(name = "logo")
@Size(max = 512)
private String logo;
/**
* маппер для связи с сущностью CompetitorLeon
*/
@ToString.Exclude
@EqualsAndHashCode.Exclude
@JsonIgnore
@OneToMany(mappedBy = "rapidTeam")
private List<TeamBridge> teamBridge;
}
|
package com.paidaki.Greeklish;
public class Letters {
private Letters() {
}
public static final Letter ALPHA = new Letter("α", "a", "4", "@");
public static final Letter BETA = new Letter("β", "b", "v", "8");
public static final Letter GAMMA = new Letter("γ", "g");
public static final Letter DELTA = new Letter("δ", "d");
public static final Letter EPSILON = new Letter("ε", "e", "3");
public static final Letter ZETA = new Letter("ζ", "z", "7");
public static final Letter ETA = new Letter("η", "i", "h", "1", "!", "y", "u");
public static final Letter THETA = new Letter("θ", "th", "u", "8");
public static final Letter IOTA = new Letter("ι", "i", "h", "1", "!", "y", "u");
public static final Letter KAPPA = new Letter("κ", "k", "c", "ck");
public static final Letter LAMBDA = new Letter("λ", "l");
public static final Letter MU = new Letter("μ", "m");
public static final Letter NU = new Letter("ν", "n");
public static final Letter XI = new Letter("ξ", "x", "ks");
public static final Letter OMICRON = new Letter("ο", "o", "0", "w");
public static final Letter PI = new Letter("π", "p");
public static final Letter RHO = new Letter("ρ", "r");
public static final Letter SIGMA = new Letter("σ", "s", "$", "6");
public static final Letter TAU = new Letter("τ", "t", "7");
public static final Letter UPSILON = new Letter("υ", "i", "h", "1", "!", "y", "u");
public static final Letter PHI = new Letter("φ", "f");
public static final Letter CHI = new Letter("χ", "x", "h", "ch");
public static final Letter PSI = new Letter("ψ", "ps");
public static final Letter OMEGA = new Letter("ω", "o", "0", "w");
public static final Letter ALPHA_IOTA = new Letter("αι", "e", "3");
public static final Letter EPSILON_IOTA = new Letter("ει", "i", "h", "1", "!", "y", "u");
public static final Letter OMICRON_IOTA = new Letter("οι", "i", "h", "1", "!", "y", "u");
public static final Letter UPSILON_IOTA = new Letter("υι", "i", "h", "1", "!", "y", "u");
public static final Letter OMICRON_UPSILON = new Letter("ου", "u", "y");
public static final Letter GAMMA_KAPPA = new Letter("γκ", "g");
public static final Letter MU_PI = new Letter("μπ", "b", "mb", "8p", "8");
public static final Letter NU_TAU = new Letter("ντ", "d", "nd");
public static final Letter BETA_BETA = new Letter("ββ", "b", "v", "8");
public static final Letter KAPPA_KAPPA = new Letter("κκ", "k", "c");
public static final Letter LAMBDA_LAMBDA = new Letter("λλ", "l");
public static final Letter MU_MU = new Letter("μμ", "m");
public static final Letter NU_NU = new Letter("νν", "n");
public static final Letter PI_PI = new Letter("ππ", "p");
public static final Letter RHO_RHO = new Letter("ρρ", "r");
public static final Letter TAU_TAU = new Letter("ττ", "t");
public static Letter getLetter(String s) {
if (s.equalsIgnoreCase(Letters.ALPHA.getGreek())) {
return Letters.ALPHA;
} else if (s.equalsIgnoreCase(Letters.BETA.getGreek())) {
return Letters.BETA;
} else if (s.equalsIgnoreCase(Letters.GAMMA.getGreek())) {
return Letters.GAMMA;
} else if (s.equalsIgnoreCase(Letters.DELTA.getGreek())) {
return Letters.DELTA;
} else if (s.equalsIgnoreCase(Letters.EPSILON.getGreek())) {
return Letters.EPSILON;
} else if (s.equalsIgnoreCase(Letters.ZETA.getGreek())) {
return Letters.ZETA;
} else if (s.equalsIgnoreCase(Letters.ETA.getGreek())) {
return Letters.ETA;
} else if (s.equalsIgnoreCase(Letters.THETA.getGreek())) {
return Letters.THETA;
} else if (s.equalsIgnoreCase(Letters.IOTA.getGreek())) {
return Letters.IOTA;
} else if (s.equalsIgnoreCase(Letters.KAPPA.getGreek())) {
return Letters.KAPPA;
} else if (s.equalsIgnoreCase(Letters.LAMBDA.getGreek())) {
return Letters.LAMBDA;
} else if (s.equalsIgnoreCase(Letters.MU.getGreek())) {
return Letters.MU;
} else if (s.equalsIgnoreCase(Letters.NU.getGreek())) {
return Letters.NU;
} else if (s.equalsIgnoreCase(Letters.XI.getGreek())) {
return Letters.XI;
} else if (s.equalsIgnoreCase(Letters.OMICRON.getGreek())) {
return Letters.OMICRON;
} else if (s.equalsIgnoreCase(Letters.PI.getGreek())) {
return Letters.PI;
} else if (s.equalsIgnoreCase(Letters.RHO.getGreek())) {
return Letters.RHO;
} else if (s.equalsIgnoreCase(Letters.SIGMA.getGreek())) {
return Letters.SIGMA;
} else if (s.equalsIgnoreCase(Letters.TAU.getGreek())) {
return Letters.TAU;
} else if (s.equalsIgnoreCase(Letters.UPSILON.getGreek())) {
return Letters.UPSILON;
} else if (s.equalsIgnoreCase(Letters.PHI.getGreek())) {
return Letters.PHI;
} else if (s.equalsIgnoreCase(Letters.CHI.getGreek())) {
return Letters.CHI;
} else if (s.equalsIgnoreCase(Letters.PSI.getGreek())) {
return Letters.PSI;
} else if (s.equalsIgnoreCase(Letters.OMEGA.getGreek())) {
return Letters.OMEGA;
} else if (s.equalsIgnoreCase(Letters.ALPHA_IOTA.getGreek())) {
return Letters.ALPHA_IOTA;
} else if (s.equalsIgnoreCase(Letters.EPSILON_IOTA.getGreek())) {
return Letters.EPSILON_IOTA;
} else if (s.equalsIgnoreCase(Letters.OMICRON_IOTA.getGreek())) {
return Letters.OMICRON_IOTA;
} else if (s.equalsIgnoreCase(Letters.UPSILON_IOTA.getGreek())) {
return Letters.UPSILON_IOTA;
} else if (s.equalsIgnoreCase(Letters.OMICRON_UPSILON.getGreek())) {
return Letters.OMICRON_UPSILON;
} else if (s.equalsIgnoreCase(Letters.GAMMA_KAPPA.getGreek())) {
return Letters.GAMMA_KAPPA;
} else if (s.equalsIgnoreCase(Letters.MU_PI.getGreek())) {
return Letters.MU_PI;
} else if (s.equalsIgnoreCase(Letters.NU_TAU.getGreek())) {
return Letters.NU_TAU;
} else if (s.equalsIgnoreCase(Letters.BETA_BETA.getGreek())) {
return Letters.BETA_BETA;
} else if (s.equalsIgnoreCase(Letters.KAPPA_KAPPA.getGreek())) {
return Letters.KAPPA_KAPPA;
} else if (s.equalsIgnoreCase(Letters.LAMBDA_LAMBDA.getGreek())) {
return Letters.LAMBDA_LAMBDA;
} else if (s.equalsIgnoreCase(Letters.MU_MU.getGreek())) {
return Letters.MU_MU;
} else if (s.equalsIgnoreCase(Letters.NU_NU.getGreek())) {
return Letters.NU_NU;
} else if (s.equalsIgnoreCase(Letters.PI_PI.getGreek())) {
return Letters.PI_PI;
} else if (s.equalsIgnoreCase(Letters.RHO_RHO.getGreek())) {
return Letters.RHO_RHO;
} else if (s.equalsIgnoreCase(Letters.TAU_TAU.getGreek())) {
return Letters.TAU_TAU;
} else {
return null;
}
}
}
|
/*
* #%L
* Janus
* %%
* Copyright (C) 2014 KIXEYE, Inc
* %%
* 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.
* #L%
*/
package com.kixeye.janus.serverlist;
import com.kixeye.janus.ServerInstance;
import com.kixeye.janus.serverlist.ConstServerList;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class ConstServerListTest {
private static final String VIP = "kvpservice";
@Test
public void constHttpServerListTest() {
ConstServerList serverList = new ConstServerList(VIP,"http://localhost:8080","http://localhost:8180");
List<ServerInstance> servers = serverList.getListOfServers();
ServerInstance server = servers.get(0);
Assert.assertEquals(server.getId(), "localhost:8080");
Assert.assertEquals( server.getHost(), "localhost");
Assert.assertEquals( server.getPort(), 8080);
Assert.assertEquals( server.getWebsocketPort(), -1);
server = servers.get(1);
Assert.assertEquals( server.getId(), "localhost:8180");
Assert.assertEquals( server.getHost(), "localhost");
Assert.assertEquals( server.getPort(), 8180);
Assert.assertEquals( server.getWebsocketPort(), -1);
Assert.assertEquals( VIP, serverList.getServiceName() );
}
@Test
public void constWsServerListTest() {
ConstServerList serverList = new ConstServerList(VIP,"ws://localhost:8080","ws://localhost:8180");
List<ServerInstance> servers = serverList.getListOfServers();
ServerInstance server = servers.get(0);
Assert.assertEquals( server.getId(), "localhost:8080");
Assert.assertEquals( server.getHost(), "localhost");
Assert.assertEquals( server.getPort(), -1);
Assert.assertEquals( server.getWebsocketPort(), 8080);
server = servers.get(1);
Assert.assertEquals( server.getId(), "localhost:8180");
Assert.assertEquals( server.getHost(), "localhost");
Assert.assertEquals( server.getPort(), -1);
Assert.assertEquals( server.getWebsocketPort(), 8180);
Assert.assertEquals( VIP, serverList.getServiceName() );
}
}
|
/*
* 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 persistencia;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Ivana
*/
public class ConexaoJDBC {
/**
* Connect to the nomeBD database
*
* @return the Connection object
*/
public static synchronized Connection criaConexao() {
Connection conexao = null;
if( conexao == null){
try {
// Load the JDBC driver
String driverName = "org.postgresql.Driver"; // Postgresql driver
Class.forName(driverName);
// Create a connection to the database
// String url = "jdbc:postgresql://localhost:5432/sportsEvents"; // a JDBC url
String url = "jdbc:postgres://motty.db.elephantsql.com:5432/hmrzilbh"; // a JDBC url
String username = "hmrzilbh";
String password = "6P1apMiW1nZd13RQCZh-nfmZOFUpcsGZ";
conexao = DriverManager.getConnection(url, username, password);
System.out.println("Conexão obtida com sucesso!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException ex) {
Logger.getLogger(ConexaoJDBC.class.getName()).log(Level.SEVERE, null, ex);
}
}
return conexao;
}
}
|
package offer;
import java.util.Arrays;
/**
* @author kangkang lou
*/
public class LastRemaining {
public static int LastRemaining_Solution(int n, int m) {
boolean[] flag = new boolean[n];
int i = n - 1;
int start = 0;
int index = (start + m - 1) % n;
while (i > 0) {
index = (start + m - 1) % n;
if (!flag[index]) {
flag[index] = true;
} else {
while (flag[index]) {
m = m + 1;
index = m % n;
}
flag[index] = true;
}
start = index + 1;
i--;
if (i == 1) {
break;
}
}
System.out.println(Arrays.toString(flag));
return index;
}
public static void main(String[] args) {
System.out.println(LastRemaining_Solution(5, 3));
System.out.println(LastRemaining_Solution(5, 2));
}
}
|
package string.StringSub;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author kouguangyuan
* @date 2018/8/3 8:39
*/
public class Test1 {
public static void main(String[] args) {
String str = "abc<icon>def</icon>deftfh<icon>a</icon>";
String str1 = "(CERTIFICATION_TIME<=timestamp'2018-08-02 23:59:59')";
//Pattern p=Pattern.compile("<icon>(\\w+)</icon>");
Pattern p=Pattern.compile("\\((\\w+)<=");
Matcher m=p.matcher(str1);
while(m.find()){
System.out.println(m.group(1));
}
Pattern p1=Pattern.compile("<=timestamp'(.*)'\\)");
Matcher m1=p1.matcher(str1);
while(m1.find()){
System.out.println(m1.group(1));
}
}
}
|
package geeksforgeeks.mustdo.Sorting;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by joetomjob on 6/7/19.
*/
public class DutchNationalFlag {
public static int[] sort012(int[] s, int n){
int l=0, m = 0, h =n-1, temp = -1;
while ( m <= h ) {
switch (s[m]) {
case 0:
temp = s[l];
s[l] = s[m];
s[m] = temp;
m++;
l++;
break;
case 1:
m++;
break;
case 2:
temp = s[m];
s[m] = s[h];
s[h] = temp;
h--;
break;
}
}
return s;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int k = Integer.parseInt(br.readLine());
for (int i = 0; i < k; i++) {
int n = Integer.parseInt(br.readLine());
String s1 = br.readLine();
String[] s2 = s1.split("\\s");
int s3[] = new int[s2.length];
for (int j = 0; j < s2.length; j++) {
s3[j] = Integer.parseInt(s2[j]);
}
int[] res = sort012(s3, n);
for (int j = 0; j < n; j++) {
System.out.print(res[j]);
System.out.print(" ");
}
System.out.println();
}
}
}
|
import java.lang.reflect.Method;
import java.util.Date;
import models.Camp;
import models.Event;
import models.Staff;
import com.avaje.ebean.Ebean;
import play.Application;
import play.GlobalSettings;
import play.mvc.Action;
import play.mvc.Http.Request;
public class Global extends GlobalSettings {
public static boolean once = false;
@Override
public void onStart(Application arg0) {
if (!once) {
loadFixtures();
once = true;
}
super.onStart(arg0);
}
public void loadFixtures() {
try {
new Camp("Camp du Gabon", 0.2548821d, 12.52441d, "Gabon", "Gabon",
Camp.CampStatus.OPEN, 5).save();
new Event(
"Violences a Franceville",
Event.EventType.ALERT,
-1.63333,
13.583333,
"À Franceville, dans l’est du Gabon, les militaires et les bérets rouges – les agents des forces armées spéciales – ont investi le campus de l'université des sciences et techniques de Masuku (USTM) le samedi 29 novembre, à la suite de manifestations étudiantes. Outre les violences physiques et les arrestations, les étudiants ont subi un certain nombre d’humiliations de la part des forces de l’ordre.",
new Date(Date.UTC(2014, 11, 29, 0, 0, 0)), new Date(Date
.UTC(2014, 12, 15, 0, 0, 0))).save();
new Event(
"Se proteger des MST",
Event.EventType.PREVENTION,
-1.63333,
13.583333,
"Seul moyen de protection contre les infections sexuellement transmissibles, le préservatif se décline aussi au féminin. Découvrez tous les atouts de cet accessoire indispensable du safe sex.",
new Date(Date.UTC(2014, 11, 29, 0, 0, 0)), new Date(Date
.UTC(2014, 12, 15, 0, 0, 0))).save();
new Event(
"Diminution de la menace Ebola",
Event.EventType.NEWS,
-1.7662,
13.0297,
"On se felecite de la baisse du nombre d'infecte par l'ebola dans le sud du Gabon.",
new Date(Date.UTC(2014, 12, 5, 0, 0, 0))).save();
new Staff("admin", "admin", null, Staff.StaffRole.ADMINISTRATOR)
.save();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package codewars;
import java.util.Arrays;
/**
* Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
*
* For example:
*
* persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
* // and 4 has only one digit
*
* persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126,
* // 1*2*6 = 12, and finally 1*2 = 2
*
* persistence(4) == 0 // because 4 is already a one-digit number
*/
public class PersistentBugger {
public static int persistence(long n) {
int count = 0;
int result = (int) n;
do {
if (String.valueOf(result).toCharArray().length == 1) return count;
result = loop(String.valueOf(result).toCharArray());
count++;
} while (String.valueOf(result).toCharArray().length > 1);
return count;
}
public static int loop(char[] c) {
char[] chars = String.valueOf(c).toCharArray();
int result = Integer.parseInt(String.valueOf(chars[0]));
for (int i = 1; i < chars.length; i++) {
result *= Integer.parseInt(String.valueOf(chars[i]));
}
return result;
}
public static int persistence2(long n) {
if (n < 10) return 0;
final long newN = Arrays.stream(String.valueOf(n).split(""))
.mapToLong(Long::valueOf)
.reduce((acc, next) -> acc * next).getAsLong();
return persistence2(newN) + 1;
}
public static void main(String[] args) {
System.out.println(persistence2(999));
}
}
|
package com.salesianos.HerenciasManuel.services;
import com.salesianos.HerenciasManuel.model.Empleado;
import com.salesianos.HerenciasManuel.repositories.EmpleadoRepository;
import com.salesianos.HerenciasManuel.services.base.BaseService;
import org.springframework.stereotype.Service;
@Service
public class EmpleadoService extends BaseService<Empleado,Long, EmpleadoRepository> {
}
|
package com.codependent.mutualauth.web;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Destination implements Serializable {
private static final long serialVersionUID = 3505573878335711861L;
@JsonProperty("isdCountryCode")
private String countryCode;
@JsonProperty("phoneNumbers")
private List<String> phoneNumbers = new ArrayList();
public Destination() {
}
public String getCountryCode() {
return this.countryCode;
}
public List<String> getPhoneNumbers() {
return this.phoneNumbers;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public boolean equals(Object o) {
if(o == this) {
return true;
} else if(!(o instanceof Destination)) {
return false;
} else {
Destination other = (Destination)o;
if(!other.canEqual(this)) {
return false;
} else {
Object this$countryCode = this.getCountryCode();
Object other$countryCode = other.getCountryCode();
if(this$countryCode == null) {
if(other$countryCode != null) {
return false;
}
} else if(!this$countryCode.equals(other$countryCode)) {
return false;
}
Object this$phoneNumbers = this.getPhoneNumbers();
Object other$phoneNumbers = other.getPhoneNumbers();
if(this$phoneNumbers == null) {
if(other$phoneNumbers != null) {
return false;
}
} else if(!this$phoneNumbers.equals(other$phoneNumbers)) {
return false;
}
return true;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof Destination;
}
public int hashCode() {
int result = 1;
Object $countryCode = this.getCountryCode();
result = result * 59 + ($countryCode == null?43:$countryCode.hashCode());
Object $phoneNumbers = this.getPhoneNumbers();
result = result * 59 + ($phoneNumbers == null?43:$phoneNumbers.hashCode());
return result;
}
public String toString() {
return "Destination(countryCode=" + this.getCountryCode() + ", phoneNumbers=" + this.getPhoneNumbers() + ")";
}
}
|
package id.ac.ub.ptiik.papps.interfaces;
import id.ac.ub.ptiik.papps.base.User;
public interface LoginDialogFinishInterface {
public void onLoginFinished(User user);
}
|
/*
* 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 streaming.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import streaming.entity.Serie;
import streaming.service.GenreCrudService;
import streaming.service.SerieCrudService;
/**
*
* @author mvernier
*/
@Controller
public class SerieController {
@Autowired
private SerieCrudService serieService;
@Autowired
private GenreCrudService genreService;
@RequestMapping(value = "/series_list", method = RequestMethod.GET)
public String list(Model m) {
m.addAttribute("titre", "Liste des series :");
m.addAttribute("series", serieService.findAllByOrderByTitreAsc());
return "series_list.jsp";
}
@RequestMapping(value = "/serie_add", method = RequestMethod.GET)
public String add(Model m) {
m.addAttribute("titre", "Ajouter une série :");
m.addAttribute("serie", new Serie());
m.addAttribute("genres", genreService.findAllByOrderByNomAsc());
return "serie_add.jsp";
}
@RequestMapping(value = "/serie_add", method = RequestMethod.POST)
public String save(@ModelAttribute("serie") Serie serie) {
serieService.save(serie);
return "redirect:/series_list";
}
@RequestMapping(value = "/serie_edit/{id}", method = RequestMethod.GET)
public String edit(@PathVariable("id") long id, Model m) {
m.addAttribute("titre", "Modifier une série :");
m.addAttribute("serie", serieService.findOne(id));
m.addAttribute("genres", genreService.findAllByOrderByNomAsc());
return "serie_edit.jsp";
}
@RequestMapping(value = "/serie_edit", method = RequestMethod.POST)
public String update(@ModelAttribute("serie") Serie serie) {
serieService.save(serie);
return "redirect:/series_list";
}
@RequestMapping(value = "/serie_delete/{id}", method = RequestMethod.GET)
public String delete(@PathVariable("id") long id) {
serieService.delete(id);
return "redirect:/series_list";
}
}
|
/**
*
*/
package com.goodhealth.design.demo.DecorativePattern;
/**
* @author 24663
* @date 2018年10月27日
* @Description
*/
public class HatDecorator extends Decorator {
/**
* @param store
*/
public HatDecorator(IStore store) {
super(store);
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see CommandPattern.DecorativePattern.Decorator#exe()
* 在这里实现一个新的功能-卖帽子
*/
@Override
public void exe() {
// TODO Auto-generated method stub
System.out.println("店里卖帽子");
}
}
|
package com.qtplaf;
import com.qtplaf.library.app.Session;
import com.qtplaf.library.swing.OptionDialog;
import com.qtplaf.library.swing.core.JOptionDialog;
public class TestOptionFrame {
public static void main(String[] args) {
OptionDialog dlg = new OptionDialog(Session.UK);
dlg.addOption("Close");
dlg.setMessage("<html>Hello</html>");
dlg.showDialog();
}
}
|
package com.bowlong.third.redis;
import java.io.Serializable;
import java.util.Map;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;
import com.bowlong.Toolkit;
import com.bowlong.lang.StrEx;
import com.bowlong.sql.jdbc.BeanSupport;
import com.bowlong.util.MapEx;
/**
* jedis -- redis 的config与pool
*
* @author Canyon
*/
@SuppressWarnings("rawtypes")
public class JedisOrigin implements Serializable {
/*
* --------------------------------------------------------------------------
* --------------------------------- APPEND key value 追加一个值到key上
*
* AUTH password 验证服务器
*
* BGREWRITEAOF 异步重写追加文件
*
* BGSAVE 异步保存数据集到磁盘上
*
* BITCOUNT key [start] [end] 统计字符串指定起始位置的字节数
*
* BITOP operation destkey key [key ...] Perform bitwise operations between
* strings
*
* BLPOP key [key ...] timeout 删除,并获得该列表中的第一元素,或阻塞,直到有一个可用
*
* BRPOP key [key ...] timeout 删除,并获得该列表中的最后一个元素,或阻塞,直到有一个可用
*
* BRPOPLPUSH source destination timeout 弹出一个列表的值,将它推到另一个列表,并返回它;或阻塞,直到有一个可用
*
* CLIENT KILL ip:port 关闭客户端连接
*
* CLIENT LIST 获得客户端连接列表
*
* CLIENT GETNAME 获得当前连接名称
*
* CLIENT SETNAME connection-name 设置当前连接的名字
*
* CONFIG GET parameter 获取配置参数的值
*
* CONFIG SET parameter value 获取配置参数的值
*
* CONFIG RESETSTAT 复位再分配使用info命令报告的统计
*
* DBSIZE 返回当前数据库里面的keys数量
*
* DEBUG OBJECT key 获取一个key的debug信息
*
* DEBUG SEGFAULT 使服务器崩溃
*
* DECR key 整数原子减1
*
* DECRBY key decrement 原子减指定的整数
*
* DEL key [key ...] 删除一个key
*
* DISCARD 丢弃所有 MULTI 之后发的命令
*
* DUMP key 导出key的值
*
* ECHO message 回显输入的字符串
*
* EVAL script numkeys key [key ...] arg [arg ...] 在服务器端执行 LUA 脚本
*
* EVALSHA sha1 numkeys key [key ...] arg [arg ...] 在服务器端执行 LUA 脚本
*
* EXEC 执行所有 MULTI 之后发的命令
*
* EXISTS key 查询一个key是否存在
*
* EXPIRE key seconds 设置一个key的过期的秒数
*
* EXPIREAT key timestamp 设置一个UNIX时间戳的过期时间
*
* FLUSHALL 清空所有数据库
*
* FLUSHDB 清空当前的数据库
*
* GET key 获取key的值
*
* GETBIT key offset 返回位的值存储在关键的字符串值的偏移量。
*
* GETRANGE key start end 获取存储在key上的值的一个子字符串
*
* GETSET key value 设置一个key的value,并获取设置前的值
*
* HDEL key field [field ...] 删除一个或多个哈希域
*
* HEXISTS key field 判断给定域是否存在于哈希集中
*
* HGET key field 读取哈希域的的值
*
* HGETALL key 从哈希集中读取全部的域和值
*
* HINCRBY key field increment 将哈希集中指定域的值增加给定的数字
*
* HINCRBYFLOAT key field increment 将哈希集中指定域的值增加给定的浮点数
*
* HKEYS key 获取hash的所有字段
*
* HLEN key 获取hash里所有字段的数量
*
* HMGET key field [field ...] 获取hash里面指定字段的值
*
* HMSET key field value [field value ...] 设置hash字段值
*
* HSET key field value 设置hash里面一个字段的值
*
* HSETNX key field value 设置hash的一个字段,只有当这个字段不存在时有效
*
* HVALS key 获得hash的所有值
*
* INCR key 执行原子加1操作
*
* INCRBY key increment 执行原子增加一个整数
*
* INCRBYFLOAT key increment 执行原子增加一个浮点数
*
* INFO [section] 获得服务器的详细信息
*
* KEYS pattern 查找所有匹配给定的模式的键
*
* LASTSAVE 获得最后一次同步磁盘的时间
*
* LINDEX key index 获取一个元素,通过其索引列表
*
* LINSERT key BEFORE|AFTER pivot value 在列表中的另一个元素之前或之后插入一个元素
*
* LLEN key 获得队列(List)的长度
*
* LPOP key 从队列的左边出队一个元素
*
* LPUSH key value [value ...] 从队列的左边入队一个或多个元素
*
* LPUSHX key value 当队列存在时,从队到左边入队一个元素
*
* LRANGE key start stop 从列表中获取指定返回的元素
*
* LREM key count value 从列表中删除元素
*
* LSET key index value 设置队列里面一个元素的值
*
* LTRIM key start stop 修剪到指定范围内的清单
*
* MGET key [key ...] 获得所有key的值
*
* MIGRATE host port key destination-db timeout 原子性的将key从redis的一个实例移到另一个实例
*
* MONITOR 实时监控服务器
*
* MOVE key db 移动一个key到另一个数据库
*
* MSET key value [key value ...] 设置多个key value
*
* MSETNX key value [key value ...] 设置多个key value,仅当key存在时
*
* MULTI 标记一个事务块开始
*
* OBJECT subcommand [arguments [arguments ...]] 检查内部的再分配对象
*
* PERSIST key 移除key的过期时间
*
* PEXPIRE key milliseconds 设置一个key的过期的毫秒数
*
* PEXPIREAT key milliseconds-timestamp 设置一个带毫秒的UNIX时间戳的过期时间
*
* PING Ping 服务器
*
* PSETEX key milliseconds value Set the value and expiration in
* milliseconds of a key
*
* PSUBSCRIBE pattern [pattern ...] 听出版匹配给定模式的渠道的消息
*
* PTTL key 获取key的有效毫秒数
*
* PUBLISH channel message 发布一条消息到频道
*
* PUNSUBSCRIBE [pattern [pattern ...]] 停止发布到匹配给定模式的渠道的消息听
*
* QUIT 关闭连接,退出
*
* RANDOMKEY 返回一个随机的key
*
* RENAME key newkey 将一个key重命名
*
* RENAMENX key newkey 重命名一个key,新的key必须是不存在的key
*
* RESTORE key ttl serialized-value Create a key using the provided
* serialized value, previously obtained using DUMP.
*
* RPOP key 从队列的右边出队一个元素
*
* RPOPLPUSH source destination 删除列表中的最后一个元素,将其追加到另一个列表
*
* RPUSH key value [value ...] 从队列的右边入队一个元素
*
* RPUSHX key value 从队列的右边入队一个元素,仅队列存在时有效
*
* SADD key member [member ...] 添加一个或者多个元素到集合(set)里
*
* SAVE 同步数据到磁盘上
*
* SCARD key 获取集合里面的元素数量
*
* SCRIPT EXISTS script [script ...] Check existence of scripts in the
* script cache.
*
* SCRIPT FLUSH 删除服务器缓存中所有Lua脚本。
*
* SCRIPT KILL 杀死当前正在运行的 Lua 脚本。
*
* SCRIPT LOAD script 从服务器缓存中装载一个Lua脚本。
*
* SDIFF key [key ...] 获得队列不存在的元素
*
* SDIFFSTORE destination key [key ...] 获得队列不存在的元素,并存储在一个关键的结果集
*
* SELECT index 选择数据库
*
* SET key value 设置一个key的value值
*
* SETBIT key offset value Sets or clears the bit at offset in the string
* value stored at key
*
* SETEX key seconds value 设置key-value并设置过期时间(单位:秒)
*
* SETNX key value 设置的一个关键的价值,只有当该键不存在
*
* SETRANGE key offset value Overwrite part of a string at key starting at
* the specified offset
*
* SHUTDOWN [NOSAVE] [SAVE] 关闭服务
*
* SINTER key [key ...] 获得两个集合的交集
*
* SINTERSTORE destination key [key ...] 获得两个集合的交集,并存储在一个关键的结果集
*
* SISMEMBER key member 确定一个给定的值是一个集合的成员
*/
/**
* 标识
*/
private static final long serialVersionUID = 1L;
// ///////////////////// 类型 /////////////////////
static public final String PUBSUB_CHN_GEN = "GEN"; // General channel
static public final String PUBSUB_CHN_SET = "SET"; // object update
static public final String PUBSUB_CHN_LSET = "LSET"; // list update
static public final String PUBSUB_CHN_HSET = "HSET"; // map update
static public final String TYPE_UNKNOW = "unknow"; // (不能识别)
static public final String TYPE_NONE = "none"; // (key不存在)
static public final String TYPE_STRING = "string"; // (字符串)
static public final String TYPE_LIST = "list"; // (列表)
static public final String TYPE_SET = "set";// (集合)
static public final String TYPE_ZSET = "zset"; // (有序集)
static public final String TYPE_HASH = "hash"; // (哈希表)
static public final int N_UNKNOW = -1; // (不能识别)
static public final int N_NONE = 0; // (key不存在)
static public final int N_STRING = 1; // (字符串)
static public final int N_LIST = 2; // (列表)
static public final int N_SET = 3;// (集合)
static public final int N_ZSET = 4; // (有序集)
static public final int N_HASH = 5; // (哈希表)
static public final int ntype(final String type) {
switch (type) {
case TYPE_NONE:
return N_NONE;
case TYPE_STRING:
return N_STRING;
case TYPE_LIST:
return N_LIST;
case TYPE_SET:
return N_SET;
case TYPE_ZSET:
return N_ZSET;
case TYPE_HASH:
return N_HASH;
default:
return N_UNKNOW;
}
}
// 对象类型//none(key不存在),string(字符串),list(列表),set(集合),zset(有序集),hash(哈希表)
static public final String type(final JedisPool pool, final String key) {
final Jedis jedis = pool.getResource();
try {
return type(jedis, key);
} catch (Exception e) {
throw e;
} finally {
pool.returnResource(jedis);
}
}
static public final String type(final Jedis jedis, final String key) {
return jedis.type(key);
}
static public final String type(final String key) {
final JedisPool pool = getJedisPool();
return type(pool, key);
}
static public final boolean isType(final String key, final String type) {
String t = type(key);
if (t == null || t.isEmpty())
return false;
return t.equals(type);
}
static public final boolean isType(final String key, final int type) {
String t = type(key);
if (t == null || t.isEmpty())
return false;
return t.equals(stype(type));
}
static public final String stype(final int type) {
switch (type) {
case N_NONE:
return TYPE_NONE;
case N_STRING:
return TYPE_STRING;
case N_LIST:
return TYPE_LIST;
case N_SET:
return TYPE_SET;
case N_ZSET:
return TYPE_ZSET;
case N_HASH:
return TYPE_HASH;
default:
return TYPE_UNKNOW;
}
}
static public final byte[] key2(final byte[] key) {
return key;
}
static public final byte[] key2(final String key) {
return key.getBytes();
}
static public final byte[] val2(final byte[] val) {
return val;
}
static public final byte[] val2(final String val) {
return val.getBytes();
}
static public final byte[] val2(final Object val) {
if (val instanceof BeanSupport) {
BeanSupport tt = ((BeanSupport) val);
try {
return Toolkit.serialization(tt.toBasicMap());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
try {
return Toolkit.serialization(val);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// ///////////////////// 配置与池对象 /////////////////////
// redis参数配置
// {
// "REDIS":{
// "maxActiveUnlimite":-1,
// "maxIdleUnlimite":-1,
// "testOnBorrow":true,
// "testOnReturn":true,
// "testWhileIdle":true,
// "timeBetweenEvictionRunsMillis":60000,
// "minEvictableIdleTimeMillis":30000,
// "numTestsPerEvictionRun":3000,
// "maxActive":4000,
// "maxIdle":3000,
// "minIdle":10,
// "maxWait":10000,
// "timeOut":15000,
// "host":"127.0.0.1",
// "port":4011,
// "pwd":"1234567890!@#$%^&*()",
// "dbIndex":0,
// "defPort":6379
// }
// }
static public JedisPoolConfig config = null;
static public final JedisPoolConfig newConfig(final int maxActive,
final int maxIdle, final int minIdle, final int maxWait,
final boolean testOnBorrow, final boolean testOnReturn,
final boolean testWhileIdle,
final int timeBetweenEvictionRunsMillis,
final int numTestsPerEvictionRun,
final int minEvictableIdleTimeMillis) {
config = new JedisPoolConfig();
// 控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;如果赋值为-1,则表示不限制
config.setMaxTotal(maxActive);
// 控制一个pool最多有多少个状态为idle的jedis实例
config.setMaxIdle(maxIdle);
// 控制一个pool至少有多少个状态为idle的jedis实例
config.setMinIdle(minIdle);
// 表示当borrow一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException
config.setMaxWaitMillis(maxWait);
// 在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的
config.setTestOnBorrow(testOnBorrow);
// 在return给pool时,是否提前进行validate操作
config.setTestOnReturn(testOnReturn);
// 如果为true,表示有一个idle object evitor线程
// 对idle object进行扫描,如果validate失败,此object会被从pool中drop掉
// 这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义;
config.setTestWhileIdle(testWhileIdle);
// 表示idle object evitor两次扫描之间要sleep的毫秒数
config.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
// 表示idle object evitor每次扫描的最多的对象数
config.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
// 表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐
// 这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
config.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
return config;
}
static public final JedisPoolConfig newConfig(final int maxActive,
final int maxIdle, final int minIdle, final int maxWait) {
return newConfig(maxActive, maxIdle, minIdle, maxWait, true, true,
true, 60 * 1000, 3000, 30 * 1000);
}
static public final JedisPoolConfig newPoolConfig(final int maxActive,
final int maxIdle, final int minIdle, final int maxWait) {
config = new JedisPoolConfig();
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setMaxTotal(maxActive);
config.setMaxWaitMillis(maxWait);
config.setTestWhileIdle(true);
return config;
}
static public final JedisPoolConfig getJedisPoolConfig() {
if (config != null)
return config;
return newConfig(128, 64, 1, 4 * 1000);
}
// ///////////////////// 连接池 /////////////////////
static public JedisPool jedsPool = null;
static public final JedisPool getJedisPool(JedisPoolConfig config,
String host, int port, int timeOut, String password, int dbIndex) {
boolean isPwd = true;
if (StrEx.isEmpty(password)) {
password = null;
isPwd = false;
}
boolean isNotDef = dbIndex > 0;
if (isNotDef) {
return new JedisPool(config, host, port, timeOut, password, dbIndex);
}
if (isPwd) {
return new JedisPool(config, host, port, timeOut, password);
}
boolean isOut = timeOut > 0;
if (isOut) {
return new JedisPool(config, host, port, timeOut);
}
return new JedisPool(config, host, port);
}
static public final JedisPool getJedisPool(JedisPoolConfig config,
String host, int port) {
return getJedisPool(config, host, port, 0, null, 0);
}
static public final JedisPool getJedisPool(String host, int port,String pwd,int dbIndex) {
final JedisPoolConfig config = getJedisPoolConfig();
return getJedisPool(config, host, port, 10000, pwd, dbIndex);
}
static public final JedisPool getJedisPool(String host, int port) {
final JedisPoolConfig config = getJedisPoolConfig();
return getJedisPool(config, host, port);
}
static public final JedisPool getJedisPool(String host) {
JedisPoolConfig config = getJedisPoolConfig();
return getJedisPool(config, host, 6379);
}
static public final JedisPool setJedisPool(JedisPool pool) {
jedsPool = pool;
return jedsPool;
}
static public final JedisPool getJedisPool() {
if (jedsPool != null)
return jedsPool;
String host = "127.0.0.1";
jedsPool = getJedisPool(host);
return jedsPool;
}
static public final JedisPool resetJedisPool(Map redisConfig) {
if (MapEx.isEmpty(redisConfig)) {
return null;
}
// config 配置 参数
int maxActive = MapEx.getInt(redisConfig, "maxActive");
int maxIdle = MapEx.getInt(redisConfig, "maxIdle");
int minIdle = MapEx.getInt(redisConfig, "minIdle");
int maxWait = MapEx.getInt(redisConfig, "maxWait");
boolean testOnBorrow = MapEx.getBoolean(redisConfig, "testOnBorrow");
boolean testOnReturn = MapEx.getBoolean(redisConfig, "testOnReturn");
boolean testWhileIdle = MapEx.getBoolean(redisConfig, "testWhileIdle");
int timeBetweenEvictionRunsMillis = MapEx.getInt(redisConfig,
"timeBetweenEvictionRunsMillis");
int numTestsPerEvictionRun = MapEx.getInt(redisConfig,
"numTestsPerEvictionRun");
int minEvictableIdleTimeMillis = MapEx.getInt(redisConfig,
"minEvictableIdleTimeMillis");
config = newConfig(maxActive, maxIdle, minIdle, maxWait, testOnBorrow,
testOnReturn, testWhileIdle, timeBetweenEvictionRunsMillis,
numTestsPerEvictionRun, minEvictableIdleTimeMillis);
// jedis pool 参数
String host = MapEx.getString(redisConfig, "host");
int timeOut = MapEx.getInt(redisConfig, "timeOut");
int port = MapEx.getInt(redisConfig, "port");
String password = MapEx.getString(redisConfig, "pwd");
int dbIndex = MapEx.getInt(redisConfig, "dbIndex");
jedsPool = getJedisPool(config, host, port, timeOut, password, dbIndex);
return jedsPool;
}
/** 关闭数据 **/
static public final void closeJedisPool(JedisPool pool) {
if (pool != null)
pool.destroy();
}
// ///////////////////// jedis 对象 /////////////////////
static public final Jedis newJedis(final String host, final int port,
final int timeOut) {
if (timeOut > 0)
return new Jedis(host, port, timeOut);
return new Jedis(host, port);
}
static public final Jedis newJedis(final String host) {
return new Jedis(host);
}
/** 返回错误的redis **/
static public final void returnJedisWhenError(JedisPool pool, Jedis resource) {
if (pool == null || resource == null)
return;
try {
pool.returnBrokenResource(resource);
} catch (Exception e) {
}
}
static public final void returnJedisWhenError(Jedis resource) {
returnJedisWhenError(jedsPool, resource);
}
/** 返回 redis **/
static public final void returnJedis(JedisPool pool, Jedis resource) {
if (resource == null)
return;
try {
if (pool == null) {
resource.disconnect();
} else {
pool.returnResource(resource);
}
} catch (Exception e) {
}
}
static public final void returnJedis(Jedis resource) {
returnJedis(jedsPool, resource);
}
static public final Jedis getJedis(JedisPool pool) {
if (pool == null)
return null;
Jedis result = null;
int exceNum = 0;
while (result == null) {
try {
exceNum++;
result = pool.getResource();
} catch (Exception e) {
returnJedisWhenError(pool, result);
}
if (exceNum >= 100) {
exceNum = 0;
break;
}
}
return result;
}
static public final Jedis getJedis() {
return getJedis(jedsPool);
}
/** 选择数据库 默认是[0~15] **/
static public final Jedis selectDb(Jedis r, int index) {
if (r == null || index < 0)
return r;
r.select(index);
return r;
}
// ///////////////////// jedis的通道pipeline对象 /////////////////////
static public final Pipeline getPipeline(JedisPool pool) {
Jedis jedis = getJedis(pool);
if (jedis != null) {
return jedis.pipelined();
}
return null;
}
// /////////////////////
}
|
package kr.ac.sogang.gtasubway.search;
import java.util.ArrayList;
import kr.ac.sogang.gtasubway.R;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
public class ListViewAdapter extends BaseAdapter implements Filterable{
LayoutInflater inflater;
ArrayList<Station> mSearchListData;
ArrayList<Station> originalListData;
//this is a simple class that filtering the ArrayList of strings used in adapter
public class filter_here extends Filter{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ){
Result.values = originalListData;
Result.count = originalListData.size();
return Result;
}
ArrayList<Station> Filtered_Names = new ArrayList<Station>();
String filterString = constraint.toString().toLowerCase();
String filterableString;
for(int i = 0; i<originalListData.size(); i++){
filterableString = originalListData.get(i).mStation;
if(filterableString.toLowerCase().contains(filterString)){
Filtered_Names.add(originalListData.get(i));
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
@Override
protected void publishResults(CharSequence constraint,FilterResults results) {
// TODO Auto-generated method stub
mSearchListData = (ArrayList<Station>) results.values;
notifyDataSetChanged();
}
}
public ListViewAdapter(LayoutInflater inflater, ArrayList<Station> mSearchListData){
super();
this.inflater=inflater;
this.originalListData=this.mSearchListData=mSearchListData;
}
@Override
public int getCount() {
return mSearchListData.size();
}
@Override
public Object getItem(int position) {
return mSearchListData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View converView, ViewGroup parent) {
if(converView==null){
converView= inflater.inflate(R.layout.searchlistitem,null);
}
ImageView iv_icon=(ImageView)converView.findViewById(R.id.mIcon);
TextView tv_station=(TextView) converView.findViewById(R.id.mStation);
TextView tv_line1=(TextView) converView.findViewById(R.id.mLine1);
TextView tv_line2=(TextView) converView.findViewById(R.id.mLine2);
Station mData = mSearchListData.get(position);
tv_station.setText(mData.mStation);
tv_line1.setText(mData.mLine1);
tv_line2.setText(mData.mLine2);
return converView;
}
@Override
public Filter getFilter() {
// TODO Auto-generated method stub
return new filter_here();
//return filter;
}
}
|
import java.util.Stack;
/**
* 20. Valid Parentheses
* easy
* 可以写的更简短
*/
class Solution {
public int getVal(char c) {
switch (c) {
case '(':
return -1;
case '[':
return -2;
case '{':
return -3;
case ')':
return 1;
case ']':
return 2;
case '}':
return 3;
default:
return 0;
}
}
public boolean isValid(String s) {
if (s.isEmpty()) return true;
int len = s.length();
if (len % 2 == 1) return false;
char[] cs = s.toCharArray();
Stack<Integer> stack = new Stack<Integer>();
stack.push(getVal(cs[0]));
for (int i = 1; i < len; i++) {
int m = getVal(cs[i]);
if (m > 0) {
if (stack.isEmpty())
return false;
int t = stack.pop();
if (t + m != 0)
return false;
}
else {
stack.push(m);
}
}
if (stack.isEmpty())
return true;
return false;
}
public boolean isValidS(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.isValid("()[]{}"));
System.out.println(s.isValid("()[]}}"));
System.out.println(s.isValid("(((("));
}
} |
package pl.cwanix.opensun.authserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@SuppressWarnings("checkstyle:HideUtilityClassConstructor")
public class AuthServerApplication {
public static void main(final String[] args) {
SpringApplication.run(AuthServerApplication.class, args);
}
}
|
package capstone.abang.com.Car_Renter.Home;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.renderscript.Sampler;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.journeyapps.barcodescanner.ViewfinderView;
import com.vlk.multimager.utils.Utils;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import capstone.abang.com.Car_Renter.Car_Renter;
import capstone.abang.com.Models.CDFile;
import capstone.abang.com.Models.CarPhotos;
import capstone.abang.com.Models.CarSettings;
import capstone.abang.com.Models.HourlyRates;
import capstone.abang.com.Models.ReservationFile;
import capstone.abang.com.Models.SelfDriveRates;
import capstone.abang.com.Models.Services;
import capstone.abang.com.Models.StartPoint;
import capstone.abang.com.Models.Terms;
import capstone.abang.com.Models.UDFile;
import capstone.abang.com.Models.UHFile;
import capstone.abang.com.Models.WithDriverRates;
import capstone.abang.com.R;
import capstone.abang.com.Utils.PlaceAutocompleteAdapter;
import capstone.abang.com.Utils.ViewPagerAdapter;
public class CarBookingActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener{
//widgets
private Toolbar toolbar;
private TextView toolbar_title;
private ViewPager viewPager;
private LinearLayout sliderDotsPanel;
private ValueEventListener listener;
private TextView textViewCarName;
private TextView textViewPostedOn;
private TextView textViewContacts;
private TextView startDate;
private TextView endDate;
private TextView schedDate;
private TextView schedTime;
private AutoCompleteTextView editTextSearch;
private RadioButton roundTripBtn;
private RadioButton dropOffBtn;
private RadioButton pickupBtn;
private RadioButton deliverBtn;
private RadioGroup serviceMode;
private RadioGroup deliveryMode;
private LinearLayout serviceModeLayout;
private LinearLayout deliveryModeLayout;
private PlaceAutocompleteAdapter mPlaceAutocompleteAdapter;
private DatePickerDialog.OnDateSetListener startDateListener, endDateListener, resDateListner;
private TimePickerDialog.OnTimeSetListener resTimeListener;
private GoogleApiClient mGoogleApiClient;
private ProgressDialog progressDialog;
private Button requestButton;
private Spinner spinnerStartDestination;
private Spinner spinnerServices;
private LinearLayout dateHeaderLayout;
private LinearLayout scheduleDetail;
private LinearLayout scheduleHeader;
private LinearLayout layoutFromTo;
private LinearLayout layoutSpan;
private LinearLayout layoutTours;
private LinearLayout layoutTotal;
private LinearLayout layoutDelivery;
private LinearLayout layoutServiceMode;
private TextView textTotal;
private TextView textPrice;
private TextView textExcess;
private LinearLayout layoutRequirements;
private LinearLayout layoutOneWay;
private Spinner spinnerPackages;
private Spinner spinnerOneWay;
private Spinner spinnerOneWayEnd;
private TextView textfrom;
private TextView textto;
private Button viewTermsBtn;
private Button downloadTermsBtn;
private DownloadManager downloadManager;
private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
new LatLng(-40, -168), new LatLng(71, 136));
//Firebase
private DatabaseReference myRef;
private FirebaseDatabase firebaseDatabase;
//Variables
private Calendar[] days;
private List<Calendar> blockedDays = new ArrayList<>();
private String carCodeHolder;
private String ownerCodeHolder;
private String startDateHolder;
private String endDateHolder;
private CDFile carFile;
private String destination;
private String from;
private int dotscount;
private int hourOfDay;
private int minOfDay;
private int secOfDay;
private int numOfDays;
private ImageView[] dots;
private StringBuilder startPointBuilder;
private StringBuilder servicesBuilder;
private StringBuilder onewayDestinationsStart;
private StringBuilder onewayDestinationsEnd;
private String service;
private StringBuilder stringBuilder;
private int start_year, start_month, start_day, end_year, end_month, end_day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_car_booking);
firebaseDatabase = FirebaseDatabase.getInstance();
myRef = firebaseDatabase.getReference();
Calendar startDate1 = Calendar.getInstance();
start_year = startDate1.get(Calendar.YEAR);
start_month = startDate1.get(Calendar.MONTH);
start_day = startDate1.get(Calendar.DAY_OF_MONTH);
Calendar calendar = Calendar.getInstance();
hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
minOfDay = calendar.get(Calendar.MINUTE);
secOfDay = calendar.get(Calendar.SECOND);
Bundle b = getIntent().getExtras();
carCodeHolder = b.getString("carcode");
ownerCodeHolder = b.getString("ownercode");
startDateHolder = b.getString("startdate");
endDateHolder = b.getString("enddate");
if(startDateHolder != null && endDateHolder != null) {
startDate.setText(startDateHolder);
endDate.setText(endDateHolder);
}
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
castWidgets();
setPackages();
init();
retrieveData();
retriveAllReservations();
retrieveStartPoints();
retrieveServices();
retrieveOneWay();
days = blockedDays.toArray(new Calendar[blockedDays.size()]);
requestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
destination = editTextSearch.getText().toString();
from = (String) spinnerStartDestination.getSelectedItem();
service = (String) spinnerServices.getSelectedItem();
if(service.equalsIgnoreCase("Self Drive")) {
if(selfDriveValid()) {
book();
}
}
else if (service.equalsIgnoreCase("Out of Town")) {
if(withDriverValid()) {
book();
}
}
else if (service.equalsIgnoreCase("City Tour") || service.equalsIgnoreCase("Top Hills Tour")) {
if(hourlyValid()) {
book();
}
}
else if(service.equalsIgnoreCase("Drop-off") || service.equalsIgnoreCase("Pick-up")) {
if(hourlyValid()) {
book();
}
}
}
});
viewTermsBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(CarBookingActivity.this, ViewTermsActivity.class);
startActivity(intent);
}
});
downloadTermsBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performDownloadTerms();
}
});
}
private void performDownloadTerms() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Terms");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
if(snapshot.getValue(Terms.class).getTosStatus().equalsIgnoreCase("AC")) {
download(snapshot.getValue(Terms.class).getTosFilePath());
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void download(String path) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(path));
request.setTitle("Terms and Agreements Download");
request.setDescription("File is being downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String nameOfFile = URLUtil.guessFileName(path, null,
MimeTypeMap.getFileExtensionFromUrl(path));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOCUMENTS, nameOfFile);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
private boolean hourlyValid() {
boolean flag = true;
if(schedDate.getText().toString().equalsIgnoreCase("Start Date")) {
schedDate.setError("Please input date");
flag = false;
}
if(schedTime.getText().toString().equalsIgnoreCase("Time")) {
schedTime.setError("Please input time");
flag = false;
}
return flag;
}
private void setPackages() {
String[] packages = {"Three hours", "Eight hours", "Ten hours", "Twelve hours"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, packages);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPackages.setAdapter(adapter);
}
private boolean withDriverValid() {
boolean valid = true;
if(TextUtils.isEmpty(destination)) {
editTextSearch.setError("Please specify your destination");
valid = false;
}
if(schedDate.getText().toString().equalsIgnoreCase("Start Date")) {
schedDate.setError("Please specify date");
valid = false;
}
if(schedTime.getText().toString().equalsIgnoreCase("Time")) {
schedTime.setError("Please specify time");
valid = false;
}
if(serviceMode.getCheckedRadioButtonId() == -1) {
Toast.makeText(CarBookingActivity.this, "Please input necessary fields!", Toast.LENGTH_SHORT).show();
valid = false;
}
return valid;
}
private boolean selfDriveValid() {
boolean valid = true;
if(startDate.getText().toString().equalsIgnoreCase("Start Date")) {
startDate.setError("Please specify start date");
valid = false;
}
if(endDate.getText().toString().equalsIgnoreCase("End Date")) {
endDate.setError("Please specify end date");
valid = false;
}
if(deliveryMode.getCheckedRadioButtonId() == -1 ) {
Toast.makeText(CarBookingActivity.this, "Please input necessary fields!", Toast.LENGTH_SHORT).show();
valid = false;
}
return valid;
}
private void retrieveOneWay() {
onewayDestinationsStart = new StringBuilder();
onewayDestinationsEnd = new StringBuilder();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Rates").child("One Way");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
if(!onewayDestinationsStart.toString().contains(snapshot.getValue(WithDriverRates.class).getStartingPoint())
&& snapshot.getValue(WithDriverRates.class).getCategoryCode().equalsIgnoreCase(carFile.getCdcatcode())) {
onewayDestinationsStart.append(snapshot.getValue(WithDriverRates.class).getStartingPoint()).
append("/");
}
if(snapshot.getValue(WithDriverRates.class).getCategoryCode().equalsIgnoreCase(carFile.getCdcatcode())) {
onewayDestinationsEnd.append(snapshot.getValue(WithDriverRates.class).getEndPoint()).
append("/");
}
}
String[] holder = onewayDestinationsStart.toString().split("/");
String[] holder2 = onewayDestinationsEnd.toString().split("/");
setupOneWayDestinations(holder, holder2);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void retrieveStartPoints() {
startPointBuilder = new StringBuilder();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("StartPoint");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String[] aw;
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
startPointBuilder.append(snapshot.getValue(StartPoint.class).getStartPoint());
startPointBuilder.append("/");
}
String[] holder = startPointBuilder.toString().split("/");
setupStartingPoint(holder);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void retrieveServices() {
servicesBuilder = new StringBuilder();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Services");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
if(snapshot.getValue(Services.class).getServiceStatus().equalsIgnoreCase("AC")) {
servicesBuilder.append(snapshot.getValue(Services.class).getServiceName());
servicesBuilder.append("/");
}
}
String[] holder = servicesBuilder.toString().split("/");
setupServices(holder);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setupOneWayDestinations(String[] holder, String[] endPoints) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, holder);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOneWay.setAdapter(adapter);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, endPoints);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOneWayEnd.setAdapter(adapter1);
}
private void setupServices(String[] holder) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, holder);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerServices.setAdapter(adapter);
}
private void setupStartingPoint(String[] holder) {
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, holder);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerStartDestination.setAdapter(adapter);
}
private void book() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String renterCode = user.getUid();
String start = startDate.getText().toString();
String end = endDate.getText().toString();
String resDate = schedDate.getText().toString();
String resTime = schedTime.getText().toString();
float total = Float.parseFloat(textTotal.getText().toString());
String services;
String type = null;
String mode = null;
if(roundTripBtn.isChecked()) {
type = "Round Trip";
} else if(dropOffBtn.isChecked()) {
type = "Drop Off";
}
if(pickupBtn.isChecked()) {
mode = "Pick Up";
} else if(deliverBtn.isChecked()) {
mode = "Deliver";
}
service = (String) spinnerServices.getSelectedItem();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
String reservationID = databaseReference.push().getKey();
if(service.equalsIgnoreCase("Self Drive")) {
ReservationFile reservationFile = new ReservationFile(reservationID, start, end, null, service, null, mode, total, ownerCodeHolder, renterCode, "Pending", carCodeHolder, null, null, null, null, null, null, null, "Booking");
ReservationFile reservationFile2 = new ReservationFile(reservationID, start, end, null, service, null, mode, total, ownerCodeHolder, renterCode, "Pending", carCodeHolder, null, null, null, "Unseen", "0:00","Unseen", "0:00","Booking");
databaseReference.child("CDFile").child(carCodeHolder).child("reservations").child(reservationID).setValue(reservationFile);
databaseReference.child("ReservationFile").child(reservationID).setValue(reservationFile2);
}
else if(service.equalsIgnoreCase("Out of Town")) {
ReservationFile reservationFile = new ReservationFile(reservationID, null, null, destination, service, type, null, total, ownerCodeHolder, renterCode, "Pending", carCodeHolder, from, resDate, resTime, null, null, null, null,"Booking");
ReservationFile reservationFile3 = new ReservationFile(reservationID, null, null, destination, service, type, null, total, ownerCodeHolder, renterCode, "Pending", carCodeHolder, from, resDate, resTime, "Unseen", "0:00", "Unseen", "0:00","Booking");
databaseReference.child("CDFile").child(carCodeHolder).child("reservations").child(reservationID).setValue(reservationFile);
databaseReference.child("ReservationFile").child(reservationID).setValue(reservationFile3);
}
else if(service.equalsIgnoreCase("City Tour") || service.equalsIgnoreCase("Top Hills Tour")) {
String pack = (String) spinnerPackages.getSelectedItem();
String price = textPrice.getText().toString();
String excessrate = textExcess.getText().toString();
ReservationFile reservationFile = new ReservationFile(reservationID, ownerCodeHolder, renterCode, "Pending", carCodeHolder, resDate, resTime, null, null, null, null, price, pack, excessrate, service,"Booking");
ReservationFile reservationFile1 = new ReservationFile(reservationID, ownerCodeHolder, renterCode, "Pending", carCodeHolder, resDate, resTime, "Unseen", "0:00", "Unseen", "0:00", price, pack, excessrate, service,"Booking");
databaseReference.child("CDFile").child(carCodeHolder).child("reservations").child(reservationID).setValue(reservationFile);
databaseReference.child("ReservationFile").child(reservationID).setValue(reservationFile1);
}
else if(service.equalsIgnoreCase("Drop-off") || service.equalsIgnoreCase("Pick-up")) {
String from = (String) spinnerOneWay.getSelectedItem();
String to = (String) spinnerOneWayEnd.getSelectedItem();
if(service.equalsIgnoreCase("Drop-off")) {
ReservationFile reservationFile = new ReservationFile(reservationID, null, null, to, service, type, null, total, ownerCodeHolder, renterCode, "Pending", carCodeHolder, from, resDate, resTime, null, null, null, null, "Booking");
ReservationFile reservationFile3 = new ReservationFile(reservationID, null, null, to, service, type, null, total, ownerCodeHolder, renterCode, "Pending", carCodeHolder, from, resDate, resTime, "Unseen", "0:00", "Unseen", "0:00","Booking");
databaseReference.child("CDFile").child(carCodeHolder).child("reservations").child(reservationID).setValue(reservationFile);
databaseReference.child("ReservationFile").child(reservationID).setValue(reservationFile3);
}
else {
ReservationFile reservationFile = new ReservationFile(reservationID, null, null, from, service, type, null, total, ownerCodeHolder, renterCode, "Pending", carCodeHolder, to, resDate, resTime, null, null, null, null, "Booking");
ReservationFile reservationFile3 = new ReservationFile(reservationID, null, null, from, service, type, null, total, ownerCodeHolder, renterCode, "Pending", carCodeHolder, to, resDate, resTime, "Unseen", "0:00", "Unseen", "0:00","Booking");
databaseReference.child("CDFile").child(carCodeHolder).child("reservations").child(reservationID).setValue(reservationFile);
databaseReference.child("ReservationFile").child(reservationID).setValue(reservationFile3);
}
}
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
builder.setTitle("Book request")
.setMessage("Successfully requested" + "\n" + "Please wait for the owner's approval")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), Car_Renter.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
})
.setIcon(android.R.drawable.ic_dialog_info)
.setCancelable(false)
.show();
}
private void init() {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
schedTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TimePickerDialog dpd = TimePickerDialog.newInstance(resTimeListener,
hourOfDay,
minOfDay,
0,
false);
String currentDateString = DateFormat.getDateInstance(DateFormat.DEFAULT).format(c.getTime());
if(currentDateString.equalsIgnoreCase(schedDate.getText().toString())) {
dpd.setMinTime(hourOfDay, minOfDay, 0);
}
dpd.show(getFragmentManager(), "Time picker dialog");
}
});
resTimeListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
boolean isPM = (hourOfDay >= 12);
schedTime.setText(String.format("%02d:%02d %s", (hourOfDay == 12 || hourOfDay == 0) ? 12 : hourOfDay % 12, minute, isPM ? "PM" : "AM"));
}
};
schedDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog dpd = DatePickerDialog.newInstance(resDateListner,
start_year,
start_month,
start_day);
retriveAllReservations();
dpd.setMinDate(c);
days = blockedDays.toArray(new Calendar[blockedDays.size()]);
dpd.setDisabledDays(days);
dpd.show(getFragmentManager(), "Date picker dialog");
}
});
resDateListner = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, monthOfYear);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
start_year = year;
start_month = monthOfYear;
start_day = dayOfMonth;
String currentDateString = DateFormat.getDateInstance(DateFormat.DEFAULT).format(c.getTime());
schedDate.setText(currentDateString);
}
};
startDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog dpd = DatePickerDialog.newInstance(startDateListener,
start_year,
start_month,
start_day);
retriveAllReservations();
dpd.setMinDate(c);
days = blockedDays.toArray(new Calendar[blockedDays.size()]);
dpd.setDisabledDays(days);
dpd.show(getFragmentManager(), "Date picker dialog");
}
});
startDateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, monthOfYear);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
start_year = year;
start_month = monthOfYear;
start_day = dayOfMonth;
String currentDateString = DateFormat.getDateInstance(DateFormat.DEFAULT).format(c.getTime());
startDate.setText(currentDateString);
}
};
endDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final DatePickerDialog dpd = DatePickerDialog.newInstance(endDateListener,
start_year,
start_month,
start_day);
retriveAllReservations();
if(startDate.getText().toString().equalsIgnoreCase("Start Date")) {
Toast.makeText(CarBookingActivity.this, "Please specify start date!", Toast.LENGTH_SHORT).show();
} else {
days = blockedDays.toArray(new Calendar[blockedDays.size()]);
dpd.setMinDate(c);
dpd.setDisabledDays(days);
dpd.show(getFragmentManager(), "Date picker dialog");
}
}
});
endDateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, monthOfYear);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
end_year = year;
end_month = monthOfYear;
end_day = dayOfMonth;
String currentDateString = DateFormat.getDateInstance(DateFormat.DEFAULT).format(c.getTime());
String start = startDate.getText().toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
Date startDate = null;
Date enddDate = null;
try {
startDate = dateFormat.parse(start);
enddDate = dateFormat.parse(currentDateString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
String finalStartDate = timeFormat.format(startDate);
String finalEndDate = timeFormat.format(enddDate);
if(isValid(finalStartDate, finalEndDate)) {
endDate.setText(currentDateString);
getTotalDays(finalStartDate, finalEndDate);
calculateTotal();
} else {
Toast.makeText(CarBookingActivity.this, "Please enter valid range of dates!", Toast.LENGTH_SHORT).show();
}
}
};
serviceMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.RoundTrip) {
if(!editTextSearch.getText().toString().equalsIgnoreCase("")) {
calculateWithDriver("Round Trip");
}
}
else if(checkedId == R.id.DropOff) {
if(!editTextSearch.getText().toString().equalsIgnoreCase("")) {
calculateWithDriver("Drop Off");
}
}
}
});
spinnerPackages.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = parent.getItemAtPosition(position).toString();
if(selected.equalsIgnoreCase("Three hours")) {
setPrice("Three hours");
}
else if(selected.equalsIgnoreCase("Eight hours")) {
setPrice("Eight hours");
}
else if(selected.equalsIgnoreCase("Ten hours")) {
setPrice("Ten hours");
}
else if(selected.equalsIgnoreCase("Twelve hours")) {
setPrice("Twelve hours");
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerOneWay.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String From = parent.getItemAtPosition(position).toString();
String To = (String) spinnerOneWayEnd.getSelectedItem();
setOneWayTotal(From, To);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerOneWayEnd.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String To = parent.getItemAtPosition(position).toString();
String From = (String) spinnerOneWay.getSelectedItem();
setOneWayTotal(From, To);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerServices.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = parent.getItemAtPosition(position).toString();
if(selectedItem.equalsIgnoreCase("Self Drive")) {
// serviceModeLayout.setVisibility(View.GONE);
// deliveryModeLayout.setVisibility(View.VISIBLE);
spinnerStartDestination.setVisibility(View.GONE);
dateHeaderLayout.setVisibility(View.VISIBLE);
editTextSearch.setVisibility(View.GONE);
layoutSpan.setVisibility(View.VISIBLE);
startDate.setVisibility(View.VISIBLE);
layoutRequirements.setVisibility(View.VISIBLE);
endDate.setVisibility(View.VISIBLE);
scheduleHeader.setVisibility(View.GONE);
scheduleDetail.setVisibility(View.GONE);
layoutFromTo.setVisibility(View.GONE);
layoutTotal.setVisibility(View.VISIBLE);
layoutTours.setVisibility(View.GONE);
layoutServiceMode.setVisibility(View.GONE);
layoutDelivery.setVisibility(View.VISIBLE);
layoutOneWay.setVisibility(View.GONE);
}
else if(selectedItem.equalsIgnoreCase("Out of Town")) {
// serviceModeLayout.setVisibility(View.VISIBLE);
// deliveryModeLayout.setVisibility(View.GONE);
spinnerStartDestination.setVisibility(View.VISIBLE);
dateHeaderLayout.setVisibility(View.GONE);
editTextSearch.setVisibility(View.VISIBLE);
layoutSpan.setVisibility(View.GONE);
layoutRequirements.setVisibility(View.GONE);
startDate.setVisibility(View.GONE);
endDate.setVisibility(View.GONE);
scheduleHeader.setVisibility(View.VISIBLE);
scheduleDetail.setVisibility(View.VISIBLE);
layoutFromTo.setVisibility(View.VISIBLE);
layoutTotal.setVisibility(View.VISIBLE);
layoutTours.setVisibility(View.GONE);
layoutServiceMode.setVisibility(View.VISIBLE);
layoutDelivery.setVisibility(View.GONE);
layoutOneWay.setVisibility(View.GONE);
}
else if(selectedItem.equalsIgnoreCase("City Tour") || selectedItem.equalsIgnoreCase("Top Hills Tour")) {
// serviceModeLayout.setVisibility(View.GONE);
// deliveryModeLayout.setVisibility(View.GONE);
spinnerStartDestination.setVisibility(View.GONE);
dateHeaderLayout.setVisibility(View.GONE);
editTextSearch.setVisibility(View.GONE);
layoutSpan.setVisibility(View.GONE);
startDate.setVisibility(View.GONE);
layoutRequirements.setVisibility(View.GONE);
endDate.setVisibility(View.GONE);
scheduleHeader.setVisibility(View.VISIBLE);
scheduleDetail.setVisibility(View.VISIBLE);
layoutFromTo.setVisibility(View.GONE);
layoutTours.setVisibility(View.VISIBLE);
layoutTotal.setVisibility(View.GONE);
layoutDelivery.setVisibility(View.GONE);
layoutServiceMode.setVisibility(View.GONE);
layoutOneWay.setVisibility(View.GONE);
}
else if(selectedItem.equalsIgnoreCase("Drop-off") || selectedItem.equalsIgnoreCase("Pick-up")) {
if(selectedItem.equalsIgnoreCase("Drop-off")) {
textto.setText("* To");
textfrom.setText("* From");
}
else {
textfrom.setText("* To");
textto.setText("* From");
}
spinnerStartDestination.setVisibility(View.GONE);
layoutOneWay.setVisibility(View.VISIBLE);
dateHeaderLayout.setVisibility(View.GONE);
editTextSearch.setVisibility(View.GONE);
layoutSpan.setVisibility(View.GONE);
startDate.setVisibility(View.GONE);
layoutRequirements.setVisibility(View.GONE);
endDate.setVisibility(View.GONE);
scheduleHeader.setVisibility(View.VISIBLE);
scheduleDetail.setVisibility(View.VISIBLE);
layoutFromTo.setVisibility(View.GONE);
layoutTours.setVisibility(View.GONE);
layoutTotal.setVisibility(View.VISIBLE);
layoutDelivery.setVisibility(View.GONE);
layoutServiceMode.setVisibility(View.GONE);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
AutocompleteFilter autocompleteFilter = new AutocompleteFilter.Builder()
.setTypeFilter(Place.TYPE_COUNTRY)
.setCountry("PH")
.build();
mPlaceAutocompleteAdapter = new PlaceAutocompleteAdapter(this, mGoogleApiClient,
LAT_LNG_BOUNDS, autocompleteFilter);
editTextSearch.setAdapter(mPlaceAutocompleteAdapter);
editTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE
|| event.getAction() == KeyEvent.ACTION_DOWN
|| event.getAction() == KeyEvent.KEYCODE_ENTER) {
//execute method for searching
geoLocate();
}
return false;
}
});
}
private void setOneWayTotal(final String from, final String to) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Rates").child("One Way");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
WithDriverRates withDriverRates;
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
withDriverRates = snapshot.getValue((WithDriverRates.class));
if(withDriverRates.getStartingPoint().equalsIgnoreCase(from) && withDriverRates.getEndPoint().equalsIgnoreCase(to)
&& withDriverRates.getCategoryCode().equalsIgnoreCase(carFile.getCdcatcode())) {
textTotal.setText(withDriverRates.getPrice());
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setPrice(final String packageName) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Rates").child("Hourly");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String service = (String) spinnerServices.getSelectedItem();
String serviceHolder = service.replaceAll("\\s","");
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
HourlyRates hourlyRates = snapshot.getValue(HourlyRates.class);
if(hourlyRates.getServiceCode().equalsIgnoreCase(serviceHolder)
&& hourlyRates.getCategoryCode().equalsIgnoreCase(carFile.getCdcatcode())) {
textExcess.setText(hourlyRates.getPackageExcessHr());
if(packageName.equalsIgnoreCase("Three hours")) {
textPrice.setText(hourlyRates.getPackageThreeHrs());
}
else if(packageName.equalsIgnoreCase("Eight hours")) {
textPrice.setText(hourlyRates.getPackageEightHrs());
}
else if(packageName.equalsIgnoreCase("Ten hours")) {
textPrice.setText(hourlyRates.getPackageTenHrs());
}
else if(packageName.equalsIgnoreCase("Twelve hours")) {
textPrice.setText(hourlyRates.getPackageTwelveHrs());
}
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void calculateWithDriver(final String service) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Rates").child("Out of Town");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
WithDriverRates withDriverRates;
destination = editTextSearch.getText().toString();
from = (String) spinnerStartDestination.getSelectedItem();
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
withDriverRates = snapshot.getValue(WithDriverRates.class);
if(withDriverRates.getCategoryCode().equalsIgnoreCase(carFile.getCdcatcode())
&& destination.contains(withDriverRates.getEndPoint())
&& withDriverRates.getStartingPoint().equalsIgnoreCase(from)) {
double total = 0;
if(service.equalsIgnoreCase("Drop off")) {
total = Double.parseDouble(withDriverRates.getDropoffPrice());
}
else if(service.equalsIgnoreCase("Round Trip")) {
total = Double.parseDouble(withDriverRates.getRoundtripPrice());
}
textTotal.setText(String.valueOf(total));
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void calculateTotal() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Rates").child("Self Drive");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
SelfDriveRates selfDriveRates = new SelfDriveRates();
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
selfDriveRates = snapshot.getValue(SelfDriveRates.class);
if(carFile.getCDTransmission().equalsIgnoreCase("Automatic") && carFile.getCdcatcode().equalsIgnoreCase(selfDriveRates.getCategoryCode())) {
int weeks;
int months;
int daysRemaining;
double total = 0;
if(numOfDays >= 7) {
weeks = numOfDays / 7;
if(weeks >= 4) {
months = weeks / 4;
daysRemaining = numOfDays % 28;
if(daysRemaining >= 7) {
weeks = daysRemaining / 7;
daysRemaining = daysRemaining % 7;
if(weeks > 0) {
total = total + weeks * Double.parseDouble(selfDriveRates.getAutoWeeklyPrice());
}
if(daysRemaining > 0){
total = total + daysRemaining * Double.parseDouble(selfDriveRates.getAutoDailyPrice());
}
}
else {
total = total + daysRemaining * Double.parseDouble(selfDriveRates.getAutoDailyPrice());
}
total = total + months * Double.parseDouble(selfDriveRates.getAutoMonthlyPrice());
}
else {
daysRemaining = numOfDays % 7;
total = weeks * Double.parseDouble(selfDriveRates.getAutoWeeklyPrice());
total = total + daysRemaining * Double.parseDouble(selfDriveRates.getAutoDailyPrice());
}
}
else {
total = numOfDays * Double.parseDouble(selfDriveRates.getAutoDailyPrice());
}
double totalHolder = total;
textTotal.setText(String.valueOf(totalHolder));
}
else if(carFile.getCDTransmission().equalsIgnoreCase("Manual")) {
int weeks;
int months;
int daysRemaining;
double total = 0;
if(numOfDays >= 7) {
weeks = numOfDays / 7;
if(weeks >= 4) {
months = weeks / 4;
daysRemaining = numOfDays % 28;
if(daysRemaining >= 7) {
weeks = daysRemaining / 7;
daysRemaining = daysRemaining % 7;
if(weeks > 0) {
total = total + weeks * Double.parseDouble(selfDriveRates.getManualWeeklyPrice());
}
Toast.makeText(CarBookingActivity.this, "" + daysRemaining, Toast.LENGTH_SHORT).show();
if(daysRemaining > 0){
total = total + daysRemaining * Double.parseDouble(selfDriveRates.getManualDailyPrice());
}
}
else {
total = total + daysRemaining * Double.parseDouble(selfDriveRates.getManualDailyPrice());
}
total = total + months * Double.parseDouble(selfDriveRates.getManualMonthlyPrice());
}
else {
daysRemaining = numOfDays % 7;
total = weeks * Double.parseDouble(selfDriveRates.getManualWeeklyPrice());
total = total + daysRemaining * Double.parseDouble(selfDriveRates.getManualDailyPrice());
}
}
else {
total = numOfDays * Double.parseDouble(selfDriveRates.getManualDailyPrice());
}
double totalHolder = total;
textTotal.setText(String.valueOf(totalHolder));
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private boolean isValid(String start, String end) {
SimpleDateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
boolean b = false;
try {
b = dfDate.parse(start).before(dfDate.parse(end)) || dfDate.parse(start).equals(dfDate.parse(end));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
private void getTotalDays(String start, String end) {
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
int holder = 0;
Date date1 = null;
Date date2 = null;
try {
date1 = df1 .parse(start);
date2 = df1 .parse(end);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
while(!cal1.after(cal2))
{
Calendar dummmy = Calendar.getInstance();
dummmy.setTime(cal1.getTime());
holder = holder + 1;
if(dummmy.getTime().toString().equalsIgnoreCase(cal2.getTime().toString())) {
break;
}
cal1.add(Calendar.DATE, 1);
}
numOfDays = holder;
}
private void getDates(String start, String end) {
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = df1 .parse(start);
date2 = df1 .parse(end);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
blockedDays.add(cal1);
while(!cal1.after(cal2))
{
Calendar dummmy = Calendar.getInstance();
dummmy.setTime(cal1.getTime());
blockedDays.add(dummmy);
if(dummmy.getTime().toString().equalsIgnoreCase(cal2.getTime().toString())) {
break;
}
cal1.add(Calendar.DATE, 1);
}
}
private void retriveAllReservations() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query checkQuery = reference
.child("CDFile")
.child(carCodeHolder)
.child("reservations");
checkQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ReservationFile reservationFile = new ReservationFile();
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
if(!snapshot.getValue(ReservationFile.class).getResStatus().equalsIgnoreCase("Done")) {
reservationFile = snapshot.getValue(ReservationFile.class);
if(reservationFile.getResServiceType().equalsIgnoreCase("Self Drive")) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
Date startDate = null;
Date endDate = null;
try {
startDate = dateFormat.parse(reservationFile.getResDateStart());
endDate = dateFormat.parse(reservationFile.getResDateEnd());
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
String finalStartDate = timeFormat.format(startDate);
String finalEndDate = timeFormat.format(endDate);
getDates(finalStartDate, finalEndDate);
}
else {
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
Date startDate = null;
try {
startDate = dateFormat.parse(reservationFile.getResDateSchedule());
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
String finalStartDate = timeFormat.format(startDate);
getDatesVersionTwo(finalStartDate);
}
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getDatesVersionTwo(String date) {
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
try {
date1 = df1 .parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
blockedDays.add(cal1);
}
private void geoLocate() {
String searchString = editTextSearch.getText().toString();
Geocoder geocoder = new Geocoder(CarBookingActivity.this);
List<Address> list = new ArrayList<>();
try {
list = geocoder.getFromLocationName(searchString,1);
} catch (IOException e) {
Log.d("TAG", "geoLocate: IOException" + e.getMessage());
}
if(list.size() > 0) {
Address address = list.get(0);
}
}
private void retrieveData() {
listener = myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
setProfileWidgets(getUserSettings(dataSnapshot));
} catch (ParseException e) {
e.printStackTrace();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private CarSettings getUserSettings(DataSnapshot dataSnapshot) {
UDFile udFile = new UDFile();
UHFile uhFile = new UHFile();
CDFile cdFile = new CDFile();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
if(ds.getKey().equals("UDFile")) {
udFile = ds.child(ownerCodeHolder).getValue(UDFile.class);
}
if(ds.getKey().equals("UHFile")) {
uhFile = ds.child(ownerCodeHolder).getValue(UHFile.class);
}
if(ds.getKey().equals("CDFile")) {
cdFile = ds.child(carCodeHolder).getValue(CDFile.class);
}
}
return new CarSettings(udFile, uhFile, cdFile);
}
public void setProfileWidgets(CarSettings uSettings) throws ParseException {
myRef.removeEventListener(listener);
carFile = uSettings.getCdFile();
UDFile udFile = uSettings.getUdFile();
UHFile uhFile = uSettings.getUhFile();
CDFile cdFile = uSettings.getCdFile();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy kk:mm:ss");
String holder = new SimpleDateFormat("dd/MM/yyyy kk:mm:ss", Locale.getDefault()).format(new Date());
Date datePosted = simpleDateFormat.parse(cdFile.getCdpostedon());
Date currentDate = simpleDateFormat.parse(holder);
long different = currentDate.getTime() - datePosted.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapseDays = different / daysInMilli;
different = different % daysInMilli;
long elapseHourse = different / hoursInMilli;
different = different % hoursInMilli;
long elapseMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapseSeconds = different % secondsInMilli;
String date = null;
int w = 0;
if(elapseDays >= 1) {
if(elapseDays > 7) {
while (elapseDays >= 7) {
elapseDays = elapseDays - 7;
w++;
}
if(w < 1) {
date = w + " week ago";
} else {
date = w + " weeks ago";
}
}
else {
date = elapseDays + " days ago";
}
} else if(elapseHourse >= 1){
if(elapseHourse < 1) {
date = elapseHourse + " hour ago";
Toast.makeText(this, " " + elapseHourse, Toast.LENGTH_SHORT).show();
}
else {
date = elapseHourse + " hours ago";
}
} else if(elapseMinutes >= 1) {
if(elapseMinutes < 1) {
date = elapseMinutes + " minute ago";
} else {
date = elapseMinutes + " minutes ago";
}
} else {
if(elapseSeconds < 1) {
date = elapseSeconds + " second ago";
} else {
date = elapseSeconds + " seconds ago";
}
}
stringBuilder = new StringBuilder();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
ValueEventListener listener;
DatabaseReference databaseReference = firebaseDatabase.getReference();
Query query = databaseReference.child("CDFile").child(cdFile.getCDCode()).child("photos");
listener = query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 0;
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
stringBuilder.append(singleSnapshot.getValue(CarPhotos.class).getImageUrl());
stringBuilder.append(",");
i++;
}
if(!dataSnapshot.exists()) {
sliderDotsPanel.setVisibility(View.GONE);
}
String[] picUrls = stringBuilder.toString().split(",");
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getApplicationContext(), picUrls);
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int k = 0; k < dotscount; k++) {
dots[k] = new ImageView(getApplicationContext());
dots[k].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotsPanel.addView(dots[k], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
for(int i = 0; i < dotscount; i++) {
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//query.removeEventListener(listener);
textViewCarName.setText(cdFile.getCDMaker() + " " + cdFile.getCDModel() + " " + cdFile.getCdcaryear());
textViewPostedOn.setText(date);
Log.d("TAG", " " + udFile.getUDFullname());
textViewContacts.setText(udFile.getUDContact());
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
setResult(RESULT_CANCELED);
finish();
return true;
}
else {
return true;
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
private void castWidgets() {
toolbar = findViewById(R.id.toolbar);
toolbar_title = findViewById(R.id.toolbar_title);
viewPager = findViewById(R.id.viewpager);
sliderDotsPanel = findViewById(R.id.sliderdots);
textViewCarName = findViewById(R.id.textviewcarname);
textViewPostedOn = findViewById(R.id.textviewpostedon);
textViewContacts = findViewById(R.id.textviewcontact);
editTextSearch = findViewById(R.id.searchEditText);
roundTripBtn = findViewById(R.id.RoundTrip);
dropOffBtn = findViewById(R.id.DropOff);
serviceMode = findViewById(R.id.ServiceMode);
deliveryMode = findViewById(R.id.ServiceAdd);
pickupBtn = findViewById(R.id.PickUp);
deliverBtn = findViewById(R.id.Deliver);
endDate = findViewById(R.id.endDate);
startDate = findViewById(R.id.startDate);
spinnerStartDestination = findViewById(R.id.spinnerstartdestination);
spinnerServices = findViewById(R.id.spinnerservices);
dateHeaderLayout = findViewById(R.id.dateheaderlayout);
scheduleDetail = findViewById(R.id.scheduledetails);
scheduleHeader = findViewById(R.id.scheduleheader);
schedDate = findViewById(R.id.withDriverDate);
schedTime = findViewById(R.id.withDriverTime);
layoutFromTo = findViewById(R.id.layoutFromTo);
textTotal = findViewById(R.id.textTotal);
layoutSpan = findViewById(R.id.layoutSpan);
layoutTours = findViewById(R.id.layouttours);
layoutTotal = findViewById(R.id.layouttotal);
layoutDelivery = findViewById(R.id.layoutDelivery);
layoutServiceMode = findViewById(R.id.layoutServiceMode);
spinnerPackages = findViewById(R.id.spinnertours);
spinnerOneWay = findViewById(R.id.spinneroneway);
spinnerOneWayEnd = findViewById(R.id.spinneronewayend);
textPrice = findViewById(R.id.textPrice);
textExcess = findViewById(R.id.textExcess);
layoutRequirements = findViewById(R.id.SelfDriveRequirements);
layoutOneWay = findViewById(R.id.layoutOnewayServices);
textfrom = findViewById(R.id.textfromone);
textto = findViewById(R.id.textto);
viewTermsBtn = findViewById(R.id.viewTermsBtn);
downloadTermsBtn = findViewById(R.id.downloadTermsBtn);
setSupportActionBar(toolbar);
Utils.initToolBar(this, toolbar, true);
toolbar_title.setText("Hire a Car");
progressDialog = new ProgressDialog(this);
requestButton = findViewById(R.id.reservebtn);
}
}
|
package com.tt.miniapp.component.nativeview.game;
import android.content.Context;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.tt.miniapp.thread.ThreadUtil;
import com.tt.miniapphost.util.UIUtils;
import java.util.concurrent.atomic.AtomicInteger;
import org.json.JSONObject;
public class GameBannerManager {
private static GameBannerManager sManager;
public GameAbsoluteLayout mParentLayout;
private volatile AtomicInteger mViewIdCount;
private volatile SparseArray<View> mViewMap;
public GameBannerManager(GameAbsoluteLayout paramGameAbsoluteLayout) {
this.mParentLayout = paramGameAbsoluteLayout;
this.mViewMap = new SparseArray();
this.mViewIdCount = new AtomicInteger(0);
}
public static GameBannerManager get() {
return sManager;
}
public static void measureView(FrameLayout.LayoutParams paramLayoutParams, int paramInt, View paramView, OnMeasuredListener paramOnMeasuredListener) {
int i;
int j = paramLayoutParams.width;
if (paramLayoutParams.width < 0) {
i = Integer.MIN_VALUE;
} else {
i = 1073741824;
}
paramView.measure(View.MeasureSpec.makeMeasureSpec(j, i), View.MeasureSpec.makeMeasureSpec(1073741823, -2147483648));
paramOnMeasuredListener.onMeasured(paramInt, paramView);
}
public static void set(GameBannerManager paramGameBannerManager) {
sManager = paramGameBannerManager;
}
public static FrameLayout.LayoutParams style2Params(Context paramContext, JSONObject paramJSONObject) {
boolean bool1;
boolean bool2;
GameAbsoluteLayout.LayoutParams layoutParams = new GameAbsoluteLayout.LayoutParams(-2, -2, 0, 0);
if (paramJSONObject == null)
return layoutParams;
double d1 = UIUtils.dip2Px(paramContext, (float)paramJSONObject.optDouble("top", 0.0D));
double d2 = UIUtils.dip2Px(paramContext, (float)paramJSONObject.optDouble("left", 0.0D));
double d3 = UIUtils.dip2Px(paramContext, (float)paramJSONObject.optDouble("right", 0.0D));
double d4 = UIUtils.dip2Px(paramContext, (float)paramJSONObject.optDouble("bottom", 0.0D));
String str1 = paramJSONObject.optString("horizontalAlign", "left");
String str2 = paramJSONObject.optString("verticalAlign", "top");
if ("center".equalsIgnoreCase(str1)) {
bool1 = true;
} else if ("right".equalsIgnoreCase(str1)) {
bool1 = true;
} else {
bool1 = false;
}
if ("center".equalsIgnoreCase(str2)) {
bool2 = true;
} else if ("bottom".equalsIgnoreCase(str2)) {
bool2 = true;
} else {
bool2 = false;
}
int i = paramJSONObject.optInt("width", -2);
layoutParams.topMargin = (int)d1;
layoutParams.leftMargin = (int)d2;
layoutParams.rightMargin = (int)d3;
layoutParams.bottomMargin = (int)d4;
layoutParams.setGravity(bool1, bool2);
layoutParams.width = (int)UIUtils.dip2Px(paramContext, i);
return layoutParams;
}
public boolean add(int paramInt, View paramView, JSONObject paramJSONObject, OnMeasuredListener paramOnMeasuredListener) {
// Byte code:
// 0: aload_0
// 1: getfield mViewMap : Landroid/util/SparseArray;
// 4: iload_1
// 5: invokevirtual get : (I)Ljava/lang/Object;
// 8: ifnull -> 13
// 11: iconst_0
// 12: ireturn
// 13: aload_0
// 14: monitorenter
// 15: aload_0
// 16: getfield mViewMap : Landroid/util/SparseArray;
// 19: iload_1
// 20: aload_2
// 21: invokevirtual put : (ILjava/lang/Object;)V
// 24: aload_0
// 25: monitorexit
// 26: aload_2
// 27: bipush #8
// 29: invokevirtual setVisibility : (I)V
// 32: aload_0
// 33: getfield mParentLayout : Lcom/tt/miniapp/component/nativeview/game/GameAbsoluteLayout;
// 36: invokevirtual getContext : ()Landroid/content/Context;
// 39: aload_3
// 40: invokestatic style2Params : (Landroid/content/Context;Lorg/json/JSONObject;)Landroid/widget/FrameLayout$LayoutParams;
// 43: astore_3
// 44: aload_0
// 45: getfield mParentLayout : Lcom/tt/miniapp/component/nativeview/game/GameAbsoluteLayout;
// 48: aload_2
// 49: aload_3
// 50: invokevirtual addView : (Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V
// 53: aload #4
// 55: ifnull -> 66
// 58: aload_3
// 59: iload_1
// 60: aload_2
// 61: aload #4
// 63: invokestatic measureView : (Landroid/widget/FrameLayout$LayoutParams;ILandroid/view/View;Lcom/tt/miniapp/component/nativeview/game/GameBannerManager$OnMeasuredListener;)V
// 66: iconst_1
// 67: ireturn
// 68: astore_2
// 69: aload_0
// 70: monitorexit
// 71: aload_2
// 72: athrow
// Exception table:
// from to target type
// 15 26 68 finally
// 69 71 68 finally
}
public int generateBannerId() {
return this.mViewIdCount.addAndGet(1);
}
public boolean remove(int paramInt) {
// Byte code:
// 0: aload_0
// 1: monitorenter
// 2: aload_0
// 3: getfield mViewMap : Landroid/util/SparseArray;
// 6: iload_1
// 7: invokevirtual get : (I)Ljava/lang/Object;
// 10: checkcast android/view/View
// 13: astore_2
// 14: aload_2
// 15: ifnonnull -> 22
// 18: aload_0
// 19: monitorexit
// 20: iconst_0
// 21: ireturn
// 22: aload_0
// 23: getfield mViewMap : Landroid/util/SparseArray;
// 26: iload_1
// 27: invokevirtual remove : (I)V
// 30: new com/tt/miniapp/component/nativeview/game/GameBannerManager$1
// 33: dup
// 34: aload_0
// 35: aload_2
// 36: invokespecial <init> : (Lcom/tt/miniapp/component/nativeview/game/GameBannerManager;Landroid/view/View;)V
// 39: invokestatic runOnUIThread : (Ljava/lang/Runnable;)V
// 42: aload_0
// 43: monitorexit
// 44: iconst_1
// 45: ireturn
// 46: astore_2
// 47: aload_0
// 48: monitorexit
// 49: aload_2
// 50: athrow
// Exception table:
// from to target type
// 2 14 46 finally
// 22 42 46 finally
}
public boolean setVisible(int paramInt, final boolean shown) {
final View view = (View)this.mViewMap.get(paramInt);
if (view == null)
return false;
ThreadUtil.runOnUIThread(new Runnable() {
public void run() {
byte b;
View view = view;
if (shown) {
b = 0;
} else {
b = 4;
}
view.setVisibility(b);
}
});
return true;
}
public boolean update(final int id, final JSONObject style, final OnMeasuredListener listener) {
final View view = (View)this.mViewMap.get(id);
if (view == null)
return false;
ThreadUtil.runOnUIThread(new Runnable() {
public void run() {
FrameLayout.LayoutParams layoutParams = GameBannerManager.style2Params(GameBannerManager.this.mParentLayout.getContext(), style);
view.setLayoutParams((ViewGroup.LayoutParams)layoutParams);
GameBannerManager.OnMeasuredListener onMeasuredListener = listener;
if (onMeasuredListener == null)
return;
GameBannerManager.measureView(layoutParams, id, view, onMeasuredListener);
}
});
return true;
}
public static interface OnMeasuredListener {
void onMeasured(int param1Int, View param1View);
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\component\nativeview\game\GameBannerManager.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
/*
* 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 employeemgmt;
/**
* Create, Read, Update, Delete
* @author Benjamin Bowen
*
* This file was copy-pasted. Adding the getEmployee() method took under 1 minute.
* TOTAL TIME: 0H 01M
*/
public class CRUD {
// fields
private Database db = new Database();
// constructor
// methods
public Employee register(Employee e) {
Employee result = null;
result = db.register(e);
return result;
}
public Employee search(int id) {
Employee result = null;
result = db.search(id);
return result;
}
public int count() {
int result = 0;
result = db.count();
return result;
}
public Employee[] print() {
Employee[] result = null;
result = db.print();
return result;
}
public Employee getEmployee(int index) {
Employee result = null;
result = db.getEmployee(index);
return result;
}
}
|
package site.xulian.learning.utils;
public class Constant {
public final static Integer CODE_SUCCESS = 0;//成功
public final static Integer CODE_ERROR = 1;//失败
public static final String CACHE_KEY_30 = "cache_key_30";
public static final Integer PAGE_SIZE = 10;//一页显示10条
public static final Integer PAGE_NUM = 1;//从第一条开始
}
|
package org.campustalk.sql;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import org.campustalk.entity.CampusTalkBranch;
public class dbBranch extends DatabaseManager
{
public CampusTalkBranch getBranchById(int branchId)
{
CampusTalkBranch objBranch = new CampusTalkBranch();
try
{
this.open();
CallableStatement pst = CON.prepareCall("{ call getBranchById(?)}");
pst.setInt(1, branchId);
ResultSet rs = pst.executeQuery();
if (rs.next())
{
objBranch.setBranchId(rs.getInt("branchid"));
objBranch.setName(rs.getString("name"));
objBranch.setDuration(rs.getInt("duration"));
}
}
catch (ClassNotFoundException | SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return objBranch;
}
/**
* Admin Module ....
*/
public boolean AddBranch(String branchname, int duration)
{
boolean rtnTemp = false;
try
{
this.open();
CallableStatement csSql = CON
.prepareCall("{call insertBranch(?,?,?)}");
/**
* CREATE PROCEDURE `campustalk`.`insertRoles`( IN name VARCHAR(20),
* IN duration TEXT, IN status CHAR(2))
*/
csSql.setString(1, branchname);
csSql.setInt(2, duration);
csSql.registerOutParameter(3, Types.BOOLEAN);
csSql.executeUpdate();
rtnTemp = csSql.getBoolean(3);
csSql.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return rtnTemp;
}
public boolean EditBranch(int branchid, String branchname, int duration)
{
boolean rtnTemp = false;
try
{
this.open();
CallableStatement csSql = CON
.prepareCall("{call updateBranchByID(?,?,?,?)}");
csSql.setInt(1, branchid);
csSql.setString(2, branchname);
csSql.setInt(3, duration);
csSql.registerOutParameter(4, Types.BOOLEAN);
csSql.executeUpdate();
rtnTemp = csSql.getBoolean(4);
csSql.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return rtnTemp;
}
public void DeleteBranch(int branchid)
{
try
{
this.open();
CallableStatement csSql = CON.prepareCall("{call deleteBranch(?)}");
csSql.setInt(1, branchid);
csSql.executeQuery();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/*
* public ResultSet getBranchData() throws SQLException,
* ClassNotFoundException {
*
* this.open();
*
* CallableStatement csSql = CON.prepareCall("{call getBranchData()}");
* ResultSet rs = csSql.executeQuery(); return rs; }
*
* public CampusTalkBranch getBranchById(int branchId){ CampusTalkBranch
* objBranch= new CampusTalkBranch();
*
* try { this.open(); CallableStatement pst =
* CON.prepareCall("{ call getBranchById(?)}"); pst.setInt(1,branchId);
* ResultSet rs = pst.executeQuery(); if(rs.next()){
* objBranch.setBranchId(rs.getInt("branchid"));
* objBranch.setName(rs.getString("name"));
* objBranch.setDuration(rs.getInt("duration")); }
*
* } catch (ClassNotFoundException | SQLException e) { // TODO
* Auto-generated catch block e.printStackTrace(); }
*
*
* return objBranch;
*
*
* }
*/
public CampusTalkBranch objBranch[] = new CampusTalkBranch[10];
public CampusTalkBranch[] getBranchData()
{
ArrayList<CampusTalkBranch> branch = new ArrayList<>();
try
{
this.open();
CallableStatement csSql = CON.prepareCall("{call getAllBranch()}");
ResultSet rs = csSql.executeQuery();
CampusTalkBranch temp_branch;
while (rs.next())
{
temp_branch = new CampusTalkBranch();
temp_branch.setBranchId(rs.getInt("branchid"));
temp_branch.setName(rs.getString("name"));
temp_branch.setDuration(rs.getInt("duration"));
branch.add(temp_branch);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return branch.toArray(new CampusTalkBranch[branch.size()]);
/*
* while(rs.next()) { objBranch[i].setName(rs.getString("name")); i++; }
* return objBranch;
*/
}
/**
* End admin module
*/
}
|
//https://www.youtube.com/watch?v=GeltTz3Z1rw
//(inIndex - inStart) is the size of root's left subtree.
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return helper(0, 0, inorder.length - 1, preorder, inorder);
}
private TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) {
if (preStart > preorder.length || inStart > inEnd) return null;
TreeNode root = new TreeNode(preorder[preStart]);
int index = 0;
for (int i = inStart; i <= inEnd; i++) {
if (inorder[i] == root.val) {
index = i;
}
}
root.left = helper(preStart + 1, inStart, index - 1, preorder, inorder);
root.right = helper(preStart + 1 + index - inStart, index + 1, inEnd, preorder, inorder);
return root;
}
} |
package com.example.testimage;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
public class BackUI extends Activity {
private SoundPool soundPool;
private EditText et_advice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.back_layout);
soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
soundPool.load(this, R.raw.button34, 1);
et_advice = (EditText) findViewById(R.id.et_advice);
}
public void submit(View v) {
playAudio();
String str = et_advice.getText().toString();
if (!TextUtils.isEmpty(str)) {
MyToast.myTextSubmit(BackUI.this, "谢谢您提出的建议!", 0).show();
} else {
MyToast.myTextSubmit(BackUI.this, "您输入的内容为空!", 0).show();
}
}
public void playAudio() {
soundPool.play(1, 1, 1, 0, 0, 1);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
|
package com.gk.service.api;
import com.gk.dao.api.DaoCenter;
public interface ServiceCenter {
public void setInitData(Object data, DaoCenter daoCenter);
public void init();
public <T extends BaseService> T getService(Class<T> clazz);
}
|
package com.emse.spring.faircorp.api;
import com.emse.spring.faircorp.model.Building;
public class BuildingDto {
private Long id;
private Double outsideTemp;
public BuildingDto(){
}
public BuildingDto(Building building){
this.id = building.getId();
this.outsideTemp = building.getOutsideTemp();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Double getOutsideTemp() {
return outsideTemp;
}
public void setOutsideTemp(Double outsideTemp) {
this.outsideTemp = outsideTemp;
}
}
|
package tsubulko.entity;
import lombok.*;
import java.util.Date;
import java.util.LinkedList;
@Data
@EqualsAndHashCode
@ToString
public class Manager extends Employee {
private double bonus;
//private LinkedList<Project> projects;
public Manager(int id,Birth dateOfBirth, String name, String surname, Sex sex, String email, Adress adress, Position position, double salary, int experiense, Education education, double bonus) {
super(id,dateOfBirth, name, surname, sex, email, adress, position, salary, experiense, education);
this.bonus = bonus;
}
public Manager() {
}
}
|
package com.andy.springbootcasclient.mapper;
import com.andy.springbootcasclient.domain.Student;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
/**
* User: andy
* Date: 2019/7/31
* Time: 15:08
*/
@Repository
public interface StudentMapper {
@Select("select * from student where id =#{id}")
Student selectStudentById(String id);
}
|
import java.io.IOException;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class SearchResult {
private String searchText = "菜單 ";
private ArrayList<URLobj> legalURL = new ArrayList<>();
private String inputSearch = "";
public SearchResult(String inputSearch) {
this.inputSearch = inputSearch;
this.searchText += inputSearch;
}
public void setResultURL() {
try {
Document duckduckgo = Jsoup.connect("https://www.google.com/search?q=" + searchText)
.userAgent("Mozilla/5.0").get();
Elements searchResult = duckduckgo.getElementsByAttributeValue("class", "r");
for (Element ele : searchResult) {
String ele2 = ele.toString();
if (ele2.contains("http")) {
ele2 = ele2.substring(ele2.indexOf("http"), ele2.indexOf("&"));
legalURL.add(new URLobj(ele2, inputSearch));
}
}
//added
int i = 0;
Elements intros = duckduckgo.getElementsByAttributeValue("class", "st");
for (Element ele : intros) {
String intro = ele.toString();
// System.out.println(intro);
intro=intro.substring(intro.indexOf(">")+1, intro.indexOf("</span>"));
while(intro.contains("<br>")) {
int begin = intro.indexOf("<br>");
intro = intro.substring(0,begin)+intro.substring(begin+4);
}
legalURL.get(i).intro = intro;
i++;
}
//end of add
for (URLobj ele : legalURL) {
ele.countSum();
}
} catch (IOException e) {
e.printStackTrace();
}
sortResult();
}
public void sortResult() {
int n = legalURL.size();
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(legalURL, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
// Move current root to end
double temp = legalURL.get(0).sum;
legalURL.get(0).sum = legalURL.get(i).sum;
legalURL.get(i).sum = temp;
// call max heapify on the reduced heap
heapify(legalURL, i, 0);
}
}
void heapify(ArrayList<URLobj> arr, int n, int i) {
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr.get(l).sum < arr.get(largest).sum)
largest = l;
// If right child is larger than largest so far
if (r < n && arr.get(r).sum < arr.get(largest).sum)
largest = r;
// If largest is not root
if (largest != i) {
double swap = arr.get(i).sum;
arr.get(i).sum = arr.get(largest).sum;
arr.get(largest).sum = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
public ArrayList<URLobj> getArr(){
for(int i = 0;i<legalURL.size();i++) {
if(legalURL.get(i).title==null) {
legalURL.remove(i);
}
// if(legalURL.get(i).getURL()==null) {
// legalURL.remove(i);
// }
}
return legalURL;
}
public String retResult() {
String retVal = "";
for (URLobj ele : legalURL) {
retVal += (ele.title/* + ": " + ele.getURL()*/ + "\n");
// retVal += ( "<html><a href='"+ele.getURL()+"'>"+ele.title+"</a></html>");
}
return retVal;
}
}
|
import java.util.Scanner;
public class passengers {
public static void main(String [] args) {
loop();
}
//This function allows the user to input a string a then it will return that string.
public static String inputString(String text) {
Scanner scanner = new Scanner(System.in);
String textInput;
System.out.println(text);
textInput = scanner.nextLine();
return textInput;
}
//This method contains the loop that will ask the user for the number of passengers on the bus until the user enters "x".
public static void loop() {
int totalP = 0;
int totalB = 0;
boolean finished = true;
String userInput;
int userInt;
System.out.println("Enter 'x' when you wish to quit the program.\n");
while (finished == true) {
userInput = inputString("How many passengers were on the bus?");
if (userInput.toLowerCase().equals("x")) {
System.out.println("There were a total of " + totalP + " passengers on " + totalB + " buses.");
break;
} else {
userInt = Integer.parseInt(userInput);
totalP = totalP + userInt;
totalB = totalB + 1;
}
}
}
}
|
package com.tanmengen.en.tanmengenqi;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.widget.FrameLayout;
import com.tanmengen.en.tanmengenqi.fragments.Fragment1;
import com.tanmengen.en.tanmengenqi.fragments.Fragment2;
public class MainActivity extends AppCompatActivity {
private ViewPager mVp;
private TabLayout mTab;
private FragmentManager manager;
private FrameLayout mContain;
private Fragment1 fragment1;
private Fragment2 fragment2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
//找到控件对象
mTab = (TabLayout) findViewById(R.id.tab);
mTab.addTab(mTab.newTab().setText("首页").setIcon(R.drawable.tab1));
mTab.addTab(mTab.newTab().setText("网页").setIcon(R.drawable.tab2));
//创建Fragment对象
fragment1 = new Fragment1();
fragment2 = new Fragment2();
//frament管理器
manager = getSupportFragmentManager();
//开启事务
final FragmentTransaction transaction = manager.beginTransaction();
//添加事务 提交事务
transaction.add(R.id.contain, fragment1).add(R.id.contain, fragment2).hide(fragment2).commit();
mTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
FragmentTransaction transaction1 = manager.beginTransaction();
if (tab.getText().equals("首页")) {
transaction1.show(fragment1).hide(fragment2);
} else if (tab.getText().equals("网页")) {
transaction1.show(fragment2).hide(fragment1);
}
transaction1.commit();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mContain = (FrameLayout) findViewById(R.id.contain);
}
}
|
package com.graylin.csnews;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class NoteListActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_list);
ListView lv;
final ArrayList<String> FilesInFolder = GetFiles(Environment.getExternalStorageDirectory().getPath()+"/"+Environment.DIRECTORY_DOWNLOADS);
Collections.reverse(FilesInFolder);
lv = (ListView)findViewById(R.id.noteListView);
lv.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, FilesInFolder));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
if (MainActivity.isDebug) {
Log.e("gray", "MainActivity.java:onItemClick" + "Position : " + position + ", id : " + id);
Log.e("gray", "MainActivity.java:onItemClick" + "FilesInFolder : " + position + " = " + FilesInFolder.get(position));
}
PlayActivity.NoteFileName = FilesInFolder.get(position);
Intent intent = new Intent();
intent.setClass(NoteListActivity.this, NoteActivity.class);
startActivityForResult(intent, 0);
}
});
}
// get note file
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0){
return null;
} else {
int noteNumber = 0;
for (int i=0; i<files.length; i++){
if (files[i].getName().contains("cnnsNote")) {
MyFiles.add(files[i].getName());
noteNumber++;
}
}
if (noteNumber == 0) {
showAlertDialog("Information", "You don't have any note!!");
}
}
return MyFiles;
}
public void showAlertDialog(String title, String message) {
AlertDialog.Builder dialog = new AlertDialog.Builder(NoteListActivity.this);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (MainActivity.isDebug) {
Log.e("gray", "MainActivity.java: onActivityResult, requestCode: " + requestCode);
Log.e("gray", "MainActivity.java: onActivityResult, resultCode: " + resultCode);
}
switch (requestCode) {
case 0:
break;
}
}
@Override
public void onDestroy() {
if (MainActivity.isDebug) {
Log.e("gray", "MainActivity.java: onDestroy");
}
super.onDestroy();
}
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.note_list, menu);
// return true;
// }
}
|
package net.liuzd.spring.boot.v2.entity.enums;
import net.liuzd.spring.boot.v2.common.Enumerable;
@SuppressWarnings("rawtypes")
public enum UserStatusEnum implements Enumerable {
BAN(0, "禁止"), NORMAL(1, "正常"),;
UserStatusEnum(int value, String key) {
this.value = value;
this.key = key;
}
private int value;
private String key;
/**
* @param code
* @return
*/
public static UserStatusEnum get(Integer code) {
switch (code) {
case 0:
return BAN;
case 1:
return NORMAL;
default:
return BAN;
}
}
@Override
public String getKey() {
return this.key;
}
@Override
public int getValue() {
return this.value;
}
}
|
package com.cajr.demo.web;
import org.springframework.stereotype.Controller;
@Controller
public class ProductController {
}
|
package com.debugg3r.android.d3rworkout.view;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.debugg3r.android.d3rworkout.R;
import com.debugg3r.android.d3rworkout.WorkoutApplication;
import com.debugg3r.android.d3rworkout.presenter.MetronomePresenter;
import javax.inject.Inject;
public class MetronomeFragment extends Fragment {
private TextView mMetronomTextView;
@Inject
MetronomePresenter metronomePresenter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View fragment = inflater.inflate(R.layout.metronom_fragment, container, false);
WorkoutApplication.getComponent().inject(this);
mMetronomTextView = (TextView) fragment.findViewById(R.id.text_view_metronome);
Button buttonStartStop = (Button) fragment.findViewById(R.id.button_metronom_start_stop);
Button buttonPlus = (Button) fragment.findViewById(R.id.button_metronome_plus);
Button buttonMinus = (Button) fragment.findViewById(R.id.button_metronome_minus);
buttonStartStop.setOnClickListener((view) -> metronomePresenter.metronomSwitch(view));
buttonPlus.setOnClickListener((view) -> metronomePresenter.metronomRaise());
buttonMinus.setOnClickListener((view) -> metronomePresenter.metronomReduce());
return fragment;
}
@Override
public void onStart() {
super.onStart();
metronomePresenter.bind(mMetronomTextView);
}
@Override
public void onStop() {
super.onStop();
metronomePresenter.unbind();
}
}
|
package org.elasticsearch.index.analysis;
import java.io.Reader;
import org.apache.lucene.analysis.Tokenizer;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.assistedinject.Assisted;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.settings.IndexSettings;
import org.wltea.analyzer.dic.Dict;
import org.wltea.analyzer.dic.loader.FileDictLoader;
import org.wltea.analyzer.dic.loader.JdbcDictLoader;
import org.wltea.analyzer.lucene.IKTokenizer;
import org.wltea.analyzer.util.LogUtil;
/**
*
* @author linshouyi
*
*/
public class IKTokenizerFactory extends AbstractTokenizerFactory {
static {
FileDictLoader fdl = new FileDictLoader();
Dict.load(fdl);// 加载本地文件词库
JdbcDictLoader jdl = new JdbcDictLoader();
Dict.load(jdl);// 加载数据库词库
Dict.update(jdl);// 更新数据库词库
}
private boolean useSmart;
@Inject
public IKTokenizerFactory(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) {
super(index, indexSettings, name, settings);
String useSmart = settings.get("useSmart");
if ("true".equals(useSmart)) {
this.useSmart = true;
} else {
this.useSmart = false;
}
LogUtil.IK.info("==创建" + this + "," + useSmart);
}
/**
* 每次创建一个新实例
*/
@Override
public Tokenizer create(Reader reader) {
Tokenizer tokenizer = new IKTokenizer(reader, useSmart);
LogUtil.IK.info("==" + this + "创建:" + tokenizer + "," + useSmart);
return tokenizer;
}
}
|
package com.espendwise.manta.web.validator;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import com.espendwise.manta.util.Constants;
import com.espendwise.manta.util.FiscalCalendarUtility;
import com.espendwise.manta.util.Utility;
import com.espendwise.manta.util.arguments.Args;
import com.espendwise.manta.util.arguments.StringArgument;
import com.espendwise.manta.util.arguments.StringI18nArgument;
import com.espendwise.manta.util.validation.DateValidator;
import com.espendwise.manta.util.validation.IntegerValidator;
import com.espendwise.manta.util.validation.ValidationResult;
import com.espendwise.manta.util.validation.Validators;
import com.espendwise.manta.web.forms.AccountFiscalCalendarForm;
import com.espendwise.manta.web.forms.FiscalCalendarForm;
import com.espendwise.manta.web.resolver.DateErrorWebResolver;
import com.espendwise.manta.web.resolver.NumberErrorWebResolver;
import com.espendwise.manta.web.util.AppI18nUtil;
import com.espendwise.manta.web.util.WebError;
import com.espendwise.manta.web.util.WebErrors;
public class FiscalCalendarFormValidator extends AbstractFormValidator {
private static final Logger logger = Logger.getLogger(FiscalCalendarFormValidator.class);
@Override
public ValidationResult validate(Object obj) {
logger.info("validate()=> BEGIN");
WebErrors errors = new WebErrors();
ValidationResult vr;
AccountFiscalCalendarForm form = (AccountFiscalCalendarForm) obj;
FiscalCalendarForm calendar = form.getCalendarToEdit();
DateValidator dateValidator = Validators.getDateValidator(AppI18nUtil.getDatePattern());
vr = dateValidator.validate(getDateValue(calendar.getEffDate()), new DateErrorWebResolver("admin.account.fiscalCalendar.label.effDate"));
if (vr != null) {
errors.putErrors(vr.getResult());
}
Date effDate = dateValidator.getParsedDate();
Date expDate = null;
if (form.getIsServiceScheduleCalendar()) {
dateValidator = Validators.getDateValidator(AppI18nUtil.getDatePattern());
vr = dateValidator.validate(getDateValue(calendar.getExpDate()), new DateErrorWebResolver("admin.account.fiscalCalendar.label.expDate"));
if (vr != null) {
errors.putErrors(vr.getResult());
}
expDate = dateValidator.getParsedDate();
}
String fiscalYearInput = Utility.strNN(calendar.getFiscalYear()).equalsIgnoreCase(AppI18nUtil.getMessage("admin.account.fiscalCalendar.all"))
? String.valueOf(0)
: calendar.getFiscalYear();
IntegerValidator fiscalYearValidator = Validators.getIntegerValidator();
vr = fiscalYearValidator.validate(fiscalYearInput, new NumberErrorWebResolver("admin.account.fiscalCalendar.label.fiscalYear"));
if (vr != null) {
errors.putErrors(vr.getResult());
}
Integer fiscalYear = fiscalYearValidator.getParsedValue();
logger.info("validate()=> effDate: "+effDate+", expDate: "+expDate+", fiscalYear: "+fiscalYear);
if (fiscalYear != null && effDate != null) {
if (IsYearValid(fiscalYear)) {
if (Utility.isSet(calendar.getPeriods()) && fiscalYear >= 0) {
List<Integer> errorPeriods = checkPeriodFormat(form, effDate);
if (Utility.isSet(errorPeriods)) {
errors.putError(
new WebError(
"validation.web.error.wrongArrayPeriodFormat",
new StringI18nArgument("admin.account.fiscalCalendar.label.periodStartDate"),
new StringArgument( Utility.toCommaString(errorPeriods))
)
);
} else {
}
}
} else {
errors.putError(
new WebError(
"validation.web.error.wrongYearRange",
Args.i18nTyped(
"admin.account.fiscalCalendar.label.fiscalYear",
Constants.VALIDATION_FIELD_CRITERIA.MIN_YEAR,
Constants.VALIDATION_FIELD_CRITERIA.MAX_YEAR
)
)
);
}
}
logger.info("validate()=> END, errors.size: " + errors.size());
return new MessageValidationResult(errors.get());
}
private List<Integer> checkPeriodNotEmpty(AccountFiscalCalendarForm form) {
Set<Integer> errorPeriods = new HashSet<Integer>();
FiscalCalendarForm calendar = form.getCalendarToEdit();
logger.info("checkPeriodNotEmpty()=> calendar.getPeriods(): "+calendar.getPeriods());
for (int i = calendar.getPeriods().firstKey(); i < calendar.getPeriods().size(); i++) {
if (!Utility.isSet(calendar.getPeriods().get(i))) {
errorPeriods.add(i);
}
}
if (!calendar.getIsServiceScheduleCalendar() || form.isNew()) {
String lastMmddStr = calendar.getPeriods().get(calendar.getPeriods().lastKey());
if (calendar.getPeriods().size() > 1 && !Utility.isSet(lastMmddStr)) {
errorPeriods.add(calendar.getPeriods().lastKey());
}
}
return new ArrayList(errorPeriods);
}
private List<Integer> checkPeriodFormat(AccountFiscalCalendarForm form, Date effDate) {
Set<Integer> errorPeriods = new HashSet<Integer>();
FiscalCalendarForm calendar = form.getCalendarToEdit();
Integer year = FiscalCalendarUtility.getYearForDate(effDate);
logger.info("checkPeriodFormat()=> calendar.getPeriods().size(): "+calendar.getPeriods().size());
String prevMMDD = null;
for (int i = 13; i <= calendar.getPeriods().size(); i++) {
String mmDd = calendar.getPeriods().get(i);
if (Utility.isSet(mmDd)) {
if (i>13 && prevMMDD == null) {
errorPeriods.add(i - 1);
}
prevMMDD = mmDd;
}
}
if (Utility.isSet(errorPeriods)) {
return new ArrayList(errorPeriods);
}
Date prevDate = null;
for (int i = calendar.getPeriods().firstKey(); i < calendar.getPeriods().size(); i++) {
String mmddStr = calendar.getPeriods().get(i);
if (!Utility.isSet(mmddStr)) {
errorPeriods.add(i);
continue;
}
Date mmddDate = AppI18nUtil.parseMonthWithDay(mmddStr, year, true);
if (!Utility.isSet(mmddDate)) {
errorPeriods.add(i);
} else if (prevDate != null && mmddDate.after(prevDate)) {
year = year + 1;
}
prevDate = mmddDate;
}
if (!calendar.getIsServiceScheduleCalendar() || form.isNew()) {
String lastMmddStr = calendar.getPeriods().get(calendar.getPeriods().lastKey());
if (calendar.getPeriods().size() > 1 && !Utility.isSet(lastMmddStr)) {
errorPeriods.add(calendar.getPeriods().lastKey());
}
}
String lastMmddStr = calendar.getPeriods().get(calendar.getPeriods().lastKey());
if (Utility.isSet(lastMmddStr)) {
Date mmddDate = AppI18nUtil.parseMonthWithDay(lastMmddStr, year, true);
if (!Utility.isSet(mmddDate)) {
errorPeriods.add(calendar.getPeriods().lastKey());
}
}
return new ArrayList(errorPeriods);
}
private boolean IsYearValid(Integer year) {
return year == 0
|| !(year < Constants.VALIDATION_FIELD_CRITERIA.MIN_YEAR
|| year > Constants.VALIDATION_FIELD_CRITERIA.MAX_YEAR);
}
private String getDateValue(String date) {
return Utility.ignorePattern(
date,
AppI18nUtil.getDatePatternPrompt()
);
}
}
|
package com.UmidJavaUdemy;
// Create a class and demonstate proper encapsulation techniques
// the class will be called Printer
// It will simulate a real Computer Printer
// It should have fields for the toner Level, number of pages printed, and
// also whether its a duplex printer (capable of printing on both sides of the paper).
// Add methods to fill up the toner (up to a maximum of 100%), another method to
// simulate printing a page (which should increase the number of pages printed).
// Decide on the scope, whether to use constructors, and anything else you think is needed.
public class Printer {
private double tonerLevel;
private int numberOfPages;
private boolean isDuplex;
public Printer(double tonerLevel, boolean isDuplex) {
if (tonerLevel > 0 && tonerLevel < 100.0) {
this.tonerLevel = tonerLevel;
}
this.isDuplex = isDuplex;
this.numberOfPages = 0;
}
public double fillUpToner(double extraPowder) {
if (this.tonerLevel > 0 && this.tonerLevel <= 100.0) {
if (this.tonerLevel + extraPowder > 100) {
System.out.println("No filling is necessary");
return -1.0;
}
System.out.println("Printer loaded " + tonerLevel);
tonerLevel += extraPowder;
return tonerLevel;
} else return -1;
}
public int pagesPrinted(int print) {
int pagesToPrint = print;
if(this.isDuplex){
pagesToPrint = (print/2) + (print %2);
System.out.println("Printing double sided");
}
this.numberOfPages += pagesToPrint;
return pagesToPrint;
}
public double getTonerLevel() {
return this.tonerLevel;
}
public int getNumberOfPages() {
return numberOfPages;
}
public boolean isDuplex() {
return isDuplex;
}
}
|
package com.tencent.mm.plugin.sns.ui;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import com.tencent.mm.plugin.sns.g.b;
import com.tencent.mm.ui.base.MultiTouchImageView;
import com.tencent.mm.ui.tools.MMGestureGallery;
class SnsInfoFlip$4 implements OnItemSelectedListener {
final /* synthetic */ SnsInfoFlip nXg;
SnsInfoFlip$4(SnsInfoFlip snsInfoFlip) {
this.nXg = snsInfoFlip;
}
public final void onItemSelected(AdapterView<?> adapterView, View view, int i, long j) {
if (SnsInfoFlip.d(this.nXg) != null) {
if (SnsInfoFlip.e(this.nXg) && SnsInfoFlip.d(this.nXg).getCount() > 1) {
SnsInfoFlip.f(this.nXg).setVisibility(0);
SnsInfoFlip.f(this.nXg).setPage(i);
}
SnsInfoFlip.a(this.nXg, ((b) SnsInfoFlip.d(this.nXg).getItem(i)).caK, i, ((b) SnsInfoFlip.d(this.nXg).getItem(i)).nuP);
if (view instanceof MultiTouchImageView) {
((MultiTouchImageView) view).crm();
}
if ((SnsInfoFlip.g(this.nXg) instanceof MMGestureGallery) && (SnsInfoFlip.h(this.nXg) instanceof SnsBrowseUI)) {
((SnsBrowseUI) SnsInfoFlip.h(this.nXg)).bCZ();
}
}
}
public final void onNothingSelected(AdapterView<?> adapterView) {
}
}
|
package net.drs.myapp.resource;
import net.drs.myapp.config.UserPrincipal;
import net.drs.myapp.constants.ApplicationConstants;
import net.drs.myapp.model.User;
import java.util.TreeMap;
import javax.servlet.http.HttpSession;
import org.springframework.security.core.context.SecurityContextHolder;
import com.paytm.pg.merchant.CheckSumServiceHelper;
public abstract class GenericService {
private HttpSession session;
protected HttpSession getUserSession() {
return this.session ;
}
protected HttpSession setUserSession(HttpSession session) {
return this.session ;
}
protected void setValueInUserSession(HttpSession session ,String key, Object value) {
session.setAttribute(key, value);
}
protected Long getLoggedInUserId() {
UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return userPrincipal.getId();
}
protected String getLoggedInUserPassword() {
UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return userPrincipal.getPassword();
}
protected UserPrincipal getLoggedInUser() {
UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return userPrincipal;
}
protected String getLoggedInUserName() {
UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return userPrincipal.getUsername();
}
protected String getLoggedInUserRole() {
UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return "";
}
protected boolean validateCheckSum(TreeMap<String, String> parameters, String paytmChecksum) throws Exception {
parameters.remove("token");
return CheckSumServiceHelper.getCheckSumServiceHelper().verifycheckSum("ymYFiyrKDkr4QAHF",
parameters, paytmChecksum);
}
protected String getJWTfromsession() {
return (String) session.getAttribute("token");
}
protected void setJWTinsession(HttpSession session, String token) {
session.setAttribute("token",token);
this.session = session;
}
}
|
import java.io.*;
class test
{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String str;String str1="";
String[] words;
public test()
{
try{
str = buf.readLine();
words = str.split(" ");
for(String s : words)
{
str1 = str1+s;
}
System.out.print(str1);
}
catch(IOException e)
{
System.out.println("Please Enter Right Value!");
}
}
}
public class RemoveWhiteSpace
{
public static void main(String[] args)
{
test ob = new test();
}
} |
package com.quizcore.quizapp.model.entity;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.UUID;
@Entity
public class Options {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "id", updatable = false, nullable = false)
@Type(type="uuid-char")
public UUID id;
@Column
String optionText;
public Options() {
}
public Options(String text) {
this.optionText = text;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getText() {
return optionText;
}
public void setText(String text) {
this.optionText = text;
}
}
|
package com.smartwerkz.bytecode;
import static org.junit.Assert.assertEquals;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import org.junit.Test;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import com.smartwerkz.bytecode.controlflow.FrameExit;
import com.smartwerkz.bytecode.primitives.JavaObject;
import com.smartwerkz.bytecode.vm.ByteArrayResourceLoader;
import com.smartwerkz.bytecode.vm.Classpath;
import com.smartwerkz.bytecode.vm.HostVMResourceLoader;
import com.smartwerkz.bytecode.vm.VirtualMachine;
public class CharsetTest {
@Test
public void testDefaultCharset() throws Exception {
assertEquals("windows-1252", java.nio.charset.Charset.defaultCharset().name());
StringBuilder src = new StringBuilder();
src.append("public static String test() {");
src.append(" return java.nio.charset.Charset.defaultCharset().name();");
src.append("}");
VirtualMachine vm = new VirtualMachine();
vm.initSunJDK();
assertEquals("UTF-8", executeJavaCode(vm, src.toString()).asStringValue());
}
private JavaObject executeJavaCode(VirtualMachine vm, String methodBody) throws Exception {
ClassPool cp = new ClassPool(true);
CtClass cc = cp.makeClass("org.example.Test");
CtMethod method = CtNewMethod.make(methodBody, cc);
cc.addMethod(method);
byte[] b = cc.toBytecode();
Classpath classpath = new Classpath();
classpath.addLoader(new ByteArrayResourceLoader(b));
classpath.addLoader(new HostVMResourceLoader());
vm.setClasspath(classpath);
vm.start();
FrameExit result = vm.execute("org/example/Test", "test", new JavaObject[0]);
return result.getResult();
}
private JavaObject execute(int... opcodes) {
ClassWriter cw = new ClassWriter(0);
cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, "org/example/Foo", null, "java/lang/Object", null);
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V",
null, null);
// mv.visitMaxs(2, 2);
mv.visitCode();
for (int opcode : opcodes) {
mv.visitInsn(opcode);
}
mv.visitEnd();
cw.visitEnd();
byte[] b = cw.toByteArray();
VirtualMachine vm = new VirtualMachine();
Classpath classpath = new Classpath();
classpath.addLoader(new ByteArrayResourceLoader(b));
classpath.addLoader(new HostVMResourceLoader());
vm.setClasspath(classpath);
vm.start();
return vm.execute("org/example/Foo").getResult();
}
}
|
package chapter11.Exercise11_02;
public class Student extends Person {
private String status;
public final static int FRESHMAN = 1;
public final static int SOPHOMORE = 2;
public final static int JUNIOR = 3;
public final static int SENIOR = 4;
public Student(String name, String adress, String phoneNumber, String emailAdress, int status) {
super(name, adress, phoneNumber, emailAdress);
this.status = setStatus(status);
}
public String getStatus() {
return status;
}
public String setStatus(int status) {
switch (status) {
case FRESHMAN:
return "Freshman";
case SOPHOMORE:
return "Sophomore";
case JUNIOR:
return "Junior";
case SENIOR:
return "Senior";
default:
return "Invalid status";
}
}
@Override
public String toString() {
return super.toString()+"\nStatus: "+getStatus();
}
}
|
package am.main.spi;
import java.text.MessageFormat;
/**
* Created by ahmed.motair on 1/21/2018.
*/
public abstract class JMSQueues {
private static final String Q_FORMAT = "{0}_{1}_Q";
private static final String QCF_FORMAT = "{0}_{1}_QCF";
private String PREFIX;
private final String queueName;
private final String description;
public JMSQueues(String prefix, String queueName, String description){
this.PREFIX = prefix;
this.queueName = queueName;
this.description = description;
}
public String getQueueName() {
return MessageFormat.format(Q_FORMAT, PREFIX, queueName);
}
public String getConnectionFactory() {
return MessageFormat.format(QCF_FORMAT, PREFIX, queueName);
}
public String description() {
return this.description;
}
}
|
package listandqueue;
/**
* @Author: ZhiHao
* @Date: 2021/1/6
* @Version: 1.0
*/
public class Demo3 {
public static void main(String[] args) {
ArrayAroundQueue aroundQueue = new ArrayAroundQueue(5);
aroundQueue.addNum(1);
aroundQueue.addNum(2);
aroundQueue.addNum(3);
aroundQueue.addNum(4);
aroundQueue.showQueue();
System.out.println(aroundQueue.getNum());
System.out.println(aroundQueue.getNum());
aroundQueue.addNum(5);
aroundQueue.addNum(6);
aroundQueue.showQueue();
aroundQueue.getHead();
}
}
|
package Jdbc;
import java.sql.*;
public class DButil {
private static Connection conn=null;
private static PreparedStatement ps;
private static ResultSet rs=null;
public static void close()
{
try {
if(rs!=null)
{
rs.close();
}
if(ps!=null)
{
ps.close();
}
if(conn!=null)
{
conn.close();
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConn() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.55.214:1521:XE", "scott", "tiger");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void selectdept(String sql)
{
Connection con=getConn();
Statement stm=null;
ResultSet rs=null;
try {
stm=con.createStatement();
rs=stm.executeQuery(sql);
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+","+rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
if(stm!=null)
{
try {
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null)
{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
//
// public static void main(String[] args) {
// selectdept("select empno,ename,sal,dname from emp e,dept d where e.deptno=d.deptno and sal>3000");
// excute();
// }
}
|
class Solution {
public int distanceBetweenBusStops(int[] distance, int start, int destination) {
int simplePath = 0;
int roundPath = 0;
int len = distance.length;
int i = start;
while(i != destination)
{
simplePath += distance[i];
i = (i + 1) % len;
}
while (i != start)
{
roundPath += distance[i];
i = (i + 1) % len;
}
//System.out.print("simple" + simplePath + "round" + roundPath);
return simplePath > roundPath?roundPath:simplePath;
}
}
|
import dao.Dao;
import sourses.DaoDbConnectionSource;
import dao.DaoFactory;
import dao.DaoType;
import sourses.DaoJsonConnectionSource;
public class AccountDaoFactory implements DaoFactory<Account> {
@Override
public Dao<Account> getDao(DaoType type) {
Dao<Account> dao;
switch (type) {
case DATABASE:
dao = new DbAccountDao(new DaoDbConnectionSource());
break;
case JSON:
dao = new JsonAccountDao();
break;
default:
throw new UnsupportedOperationException("Don't find dao");
}
return dao;
}
}
|
package uy.edu.um.db;
import java.sql.SQLException;
import java.text.ParseException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringJDBCExampleMain {
public static void main(String[] args) throws ClassNotFoundException, SQLException, ParseException {
ApplicationContext ctx = new AnnotationConfigApplicationContext(JDBCExampleConfig.class);
JDBCExample example = ctx.getBean(JDBCExample.class);
example.printExamples();
System.exit(0);
}
}
|
package com.dahua.design.structural.flyweight;
public class FlyweightTest {
public static void main(String[] args) {
// 张三找服务员
AbstractWaitress waitress = ZuLiao.getWaitress("");
waitress.service();
System.out.println(waitress);
// 李四找服务员
AbstractWaitress waitress1 = ZuLiao.getWaitress("");
waitress1.service();
System.out.println(waitress1);
// 王五找服务员
AbstractWaitress waitress2 = ZuLiao.getWaitress("");
System.out.println(waitress2);
System.out.println("王五找不到服务员");
}
}
|
package com.flute.atp.resource.impl;
import com.flute.atp.application.ReportingApplicationService;
import com.flute.atp.domain.model.report.Reporting;
import com.flute.atp.resource.ReportingResource;
import com.flute.atp.share.req.CatReportReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ReportingResourceImpl implements ReportingResource {
@Autowired
private ReportingApplicationService reportingApplicationService;
@Override
public Reporting catReportOfFlow(CatReportReq req) {
String ruleGroupId = req.getRuleGroupId();
String flowId = req.getFlowId();
return reportingApplicationService.catReportOfFlow(ruleGroupId,flowId);
}
}
|
package company;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
public class Tools {
private String text="";
private String inverseText="";
private String texts[];
public Object Items[][];
int rows;
int column;
public Tools(String text){
this.setText(text);
}
public Tools(String[] texts){
this.texts=texts;
}
public Tools(String[][] Items){
this.Items=Items;
}
public Tools(int column){
this.column=column;
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}
/**
* @return the inverseText
*/
public String getInverseText() {
return inverseText;
}
/**
* @param inverseText the inverseText to set
*/
public void setInverseText(String inverseText) {
this.inverseText = inverseText;
}
public void printCharByChar(){
for(char c: getText().toCharArray()){
System.out.println(c);
}
}
public void printCharByCharInverse(){
StringBuilder sb=new StringBuilder(getText());
setInverseText(sb.reverse().toString());
for(char c: getInverseText().toCharArray()){
System.out.println(c);
}
}
public void printStringArray(){
for(String G:texts){
System.out.println(G);
}
}
public Object[] mergeTwoArray(Object arr1[],Object arr2[]){
int l1=arr1.length;
int l2=arr2.length;
Object result[]=new Object [l1+l2];
System.arraycopy(l1, 0, result, 0, l1);
System.arraycopy(l2, 0, result, l1, l2);
return result;
}
public void addNewRow(Object[] row){
Object temp[][]=Items;
int c=column;
Items=new Object[Items.length+1][c];
for(int x=0; x<temp.length;x++){
Items[x]=temp[x];
}
Items[Items.length-1]= row;
}
public void editRaw(int rowIndex,int columnIndex,Object newdata){
Items[rowIndex][columnIndex]=newdata;
}
public void MgsBOx(String Message){
JOptionPane.showMessageDialog(null, Message);
}
public static void createFolder(String folderName,String path){
File newFolder=new File(path+'/'+folderName);
newFolder.mkdir();
}
public static void openForm(JFrame form){
form.setLocationRelativeTo(null);
try {
Image img=ImageIO.read(Tools.class.getResource("iii.jpg"));
form.setIconImage(img);
form.getContentPane().setBackground(Color.white);
} catch (IOException ex) {
Logger.getLogger(Tools.class.getName()).log(Level.SEVERE, null, ex);
}
form.setVisible(true);
}
public static void clearText(Container form){
for(Component c: form.getComponents()){
if(c instanceof JTextField){
JTextField txt=(JTextField) c;
txt.setText("");
}else if(c instanceof Component){
clearText((Container) c);
}
}
}
public static void creatEmptyFile(String path,String fileName) throws IOException{
File newFile=new File(path+'/'+fileName+"txt");
newFile.createNewFile();
}
public static void createMultiEmptyFiles (String []files) throws IOException{
for(String str :files){
creatEmptyFile(str);
}
}
public static void creatEmptyFile(String fileName) throws IOException{
File newFile=new File(fileName+".txt");
newFile.createNewFile();
}
public static void writeDataIntoNewFile(String fileName,Object[] data) throws FileNotFoundException{
PrintWriter p=new PrintWriter(fileName);
for(Object o:data){
p.println(o);
}
p.close();
}
public static void writeDataIntoNewFiles(String []filesName,Object[][]data) throws FileNotFoundException{
for(int i=0;i<filesName.length;i++){
writeDataIntoNewFile(filesName[i],data[i]);
}
}
public static Object inputBox(String title){
Object myObj=JOptionPane.showInputDialog(title);
return myObj;
}
public static String digitsOfString(String text){
String sub="";
for(int i=0 ;i<text.length();i++){
if(Character.isDigit(text.charAt(i))){
sub+=text.charAt(i);
}
}
return sub;
}
public static void printScreen(String imageName) throws AWTException, IOException{
Robot r=new Robot();
Rectangle rect =new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage img =r.createScreenCapture(rect);
ImageIO.write(img, "jpg", new File(imageName+".jpg"));
}
public static void printScreen(String imageName,JFrame form) throws AWTException, IOException{
form.setState(1);
Robot r=new Robot();
Rectangle rect =new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage img =r.createScreenCapture(rect);
ImageIO.write(img, "jpg", new File(imageName+".jpg"));
form.setState(0);
}
public static void msgBox(String Message){
JOptionPane.showMessageDialog(null,Message);
}
public static boolean confirmMessage(String Message){
int MSG= JOptionPane.showConfirmDialog(null, Message);
if(MSG==JOptionPane.YES_OPTION){
return true;
}else{
return false;
}
}
public static void setReportHeader(JTable table){
table.getTableHeader().setBackground(new Color(0,0,100));
table.getTableHeader().setForeground(Color.white);
}
public static void printReport(JTable table ,String title){
try{
MessageFormat header =new MessageFormat(title+" Report");
MessageFormat footer =new MessageFormat("Page - {0}");
table.print(JTable.PrintMode.FIT_WIDTH,header,footer);
}catch(Exception e){
Tools.msgBox(e.getMessage());
}
}
}
|
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class OperatiiLogice {
public int checkHighestNumber(int first, int second) { //if-else if verifica2 conditii chiar daca nu exista si va da eroare, atunci pune un else general sau un return statement
if (first > second) {
return first;
} else {
return second;
}
}
public String checkFastText(String textFromUser) { //scriu doar in clasa operatii logice, adica "rezolvarea"
if (textFromUser.equals("FastTrack")) {
return "Learning text comparison";
} else {
return "Got to try some more"; //return pune val intr-o var, nu o printeaza, continutul e pus in Me
}
// Given a number, if it’s equal to or higher than 2 and equal to or lower than 8, print the number
} //main e apelarea
public int checkMiddleNumber(int numeroUno, int numeroDos, int numeroTres) {
if ((numeroUno >= numeroDos) && (numeroUno <= numeroTres)) {
System.out.println(numeroDos);
}
return numeroDos;
}
//Write a Java program to determine whether an input number is an even number
// Void - executa cod, nu returneaza nimic - ex. cand am un text cu care nu mai fac nimic dupa, pot pune return si nimic in void ca sa ies mai repede
public int checkNoFromUser(int noFromUser) {//scriu doar in clasa operatii logice, adica "rezolvarea"
if (noFromUser % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
return noFromUser;
}
//Given a number input, if it is higher than 8 OR equal to 6, print “The amount of snow this winter was(cm):” and the given number. Else print “The forecast snow is(cm):”
public void verifyWhether(int noUserSnow) {
if ((noUserSnow == 6) || (noUserSnow > 8)) {
System.out.println("The amount of snow this winter was " + noUserSnow + "cm");
} else {
System.out.println("The forecast snow is " + noUserSnow + "cm");
}
}
//Write Java program to allow the user to input his/her age. Then the program will show if the person is eligible to vote. A person who is eligible to vote must be older than or equal to 18 years old
public void enterAge(int ageVoting) {
if (ageVoting >= 18) {
System.out.println("You can vote.");
} else {
System.out.println("You cannot vote");
}
}
//If the user pressed number keys( from 0 to 9), the program will tell the number that is pressed, otherwise, program will show "Not allowed”. (use a switch case for this)
public void pressKey09(String whatKeyPress) {
switch (whatKeyPress) {
case "0":
System.out.println("0");
break;
case "1":
System.out.println("1");
break;
case "2":
System.out.println("2");
break;
case "3":
System.out.println("3");
break;
case "4":
System.out.println("4");
break;
case "5":
System.out.println("5");
break;
case "6":
System.out.println("6");
break;
case "7":
System.out.println("7");
break;
case "8":
System.out.println("8");
break;
case "9":
System.out.println("9");
break;
default:
System.out.println("Not allowed.");
}
}
// Find the greatest number from 3 given numbers
public void checkHighestNumber(int great1, int great2, int great3) {
if (great1 > great2 && great1 > great3)
System.out.println("Great1 is the greatest");
else if (great2 > great1 && great2 > great3)
System.out.println("Great2 is the greatest");
else if (great3 > great1 && great3 > great2)
System.out.println("Great3 is the greatest");
else {
System.out.println("Enter different no.");
}
}
//▸ Given a number input, if the number is greater than 3 but not equal to 4, print “The number is greater than 3 and not equal to 4”. Else if the number is equal to 4 print ”The number is equal to 4”. Else if the number is lower than 3 print “The number is lower than3”
public void checkFloatNo(float noFloat) {
if (noFloat > 3 && noFloat != 4)
System.out.println("The number is greater than 3 and not equal to 4");
else if (noFloat == 4)
System.out.println("The number is equal to 4");
else if (noFloat < 3)
System.out.println("The number is lower than 3");
}
//return - in afara metodei, cu void
// Given a text input and a number input, if the text is equal to “FastTrack” AND the
//number is equal to or lower than 3, print the text and the number. If the text is not
//“FastTrack” AND the number is equal to or higher than 4, print the number and the text,
//in this order.
//aici scriu ce face metoda, stiind ca are parametrul primit
public void printTxtNo(String txt, Integer nr) {
if (txt.equals("FastTrack") && nr <= 3)
System.out.println("FastTrack " + nr);
else if (txt != "FastTrack" && nr >= 4)
System.out.println(nr + txt);
}
public void printToHundred(int number) { //am facut om metoda din cea din main, return te scoate din met
for (int i = number; i <= 100; i++) {
System.out.println(i);
}
}
//Given a number, while the number is equal to or lower than 100, print the number;
public void printToHundredWhile(int number) { //aici o fac iar metoda
while (number <= 100) {
System.out.println(number);
number++; //fara incrementare e infinite l
}
}
//Write a java program to count backwards from a given number to a lower given number
public void countReverse(int elNumero) {
for (int i = elNumero; i >= 1; i--) {
System.out.println(i);
//fara incrementare e infinite loop
}
//Write a Java program by using two for loops to produce the output shown below:
//*******
//******
//*****
//****
//***
//**
//*
}
public void starExercise() {
for (int i = 7; i >= 1; i--) {
System.out.print("*");
}
}
//Write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., to 100. Also compute and display the average.
public void sumAndAverage() {
int xa = 100;
int sum = 0;
for (int i = 0; i <= xa; i++) {
sum = sum + i;
}
// to do
}
// Write a program to sum only the odd numbers from 1 to 100, and compute the average.
public void sum2OddNo() {
double iOdd = 0;
int sum2 = 0;
for (double nom = 1; nom <= 100; ++nom) {
sum2 += nom;
iOdd++;
}
System.out.println(sum2 / iOdd); //average
}
// Modify the program to sum from 111 to 8899, and compute the average. Introduce an int variable called count to count the numbers in the specified range.
public int sum3() { //as putea pune in parametru si sum ar fi egala cu parametrul
int number1 = 111;
int number2 = 8899;
int sum3 = 0;
for (int i = number1; i <= number2; i++) {
sum3 = sum3 + i;
}
return sum3;
}
public double avg() {
int number1 = 111;
int number2 = 8899;
int sum3 = 0;
int counter = 0;
for (int i = number1; i <= number2; i++) {
sum3 = sum3 + i;
counter++;
}
double avg = sum3 / (double) counter;
return avg;
}
//Write the program do display the first 20 Fibonacci numbers
public String fibonacciEx() {
int counting = 20, numerUn = 0, numerDo = 1;
String First20FibonacciNumbers = "";
for (int i = 1; i <= counting; i++) {
int sumOfPrevTwo = numerUn + numerDo;
numerUn = numerDo; // devin nr 2
numerDo = sumOfPrevTwo; //nr 2 devine suma
First20FibonacciNumbers = First20FibonacciNumbers + sumOfPrevTwo + ",";
}
return First20FibonacciNumbers;
}
//Fibbonci var 2
// Write a program to sum those numbers from 1 to 100 that is divisible by 7, and compute the average.
public double avgNoDiv7() {
double sum7 = 0;
double counter = 0;
for (int nuum = 1; nuum <= 100; nuum++) {
if (nuum % 7 == 0) {
sum7 = sum7 + nuum;
counter++;
}
}
return sum7 / counter;
}
// Modify DO WHILE loops 1. Given a number, while the number is equal to or lower than 100, print the number;
public void printToHundredDoWhile() {
int numbo = 100;
do {
System.out.println(numbo);
numbo--;
} while (numbo > 50);
}
// Modify DO WHILE loops 4. Write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., to 100. compute and display the average.
public int averageDoWhile() {
int i = 1;
int sumDow = 0;
do {
sumDow += i;
i++;
} while (i <= 100);
return sumDow / 100;
}
//Array exercises
//Array ex1. Def and write the values of array indeces so that value sof array start from 1 and count to 100, Print in console.
public int[] setArrayHundred() {
int[] myArray = new int[100];
for (int i = 1; i <= 100; i++) {
myArray[i - 1] = i; //
//System.out.println(myArray[i - 1]);
}
return myArray;
}
//Array ex2. Write Java program to calculate the average value of array elements.
public float getArrayAverage(int[] array) {
int sum = 0;
float average = 0f;
for (int i = 1; i <= array.length; i++) {
sum += array[i - 1];
}
System.out.println(sum);
average = sum / (float) array.length;
System.out.println(average);
return average;
}
// Array ex3 - Write a Java program to test if an array contains a specific value.
//with For Each
public boolean contains(int[] arr, int num) {
int[] miArray = {5, 2, 17, 13, 12, 19, 7, 3, 9, 15};
for (int x : arr) {
if (num == x) {
return true;
}
}
return false;
}
// Array Ex4. Write a Java program to find the index of an array element.
//a.Streams
// int[] numStreams = {13, 14, 15, 16, 17, 18, 19, 20, 21};
//public int ex4Array(int[] array) {
//int[] ex4Array = {3, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32};
// for (int p = 0; p < ex4Array.length; p++) {
// if (ex4Array[p] == 20) {
// System.out.println(p);
// break;
// }
// System.out.println(p);
// }
// return p
// Array Ex4. Write a Java program to find the index of an array element.
public int find(int[] array, int value) {
int[] arrayEx4 = {30, 31, 32, 33, 34, 35, 40, 42, 45, 50};
for (int i = 0; i < array.length; i++)
if (array[i] == value)
return i;
return value;
}
// Array Ex5. Write a Java program to remove a specific element from an array.
public int getRemoveElement(int[] elArray) {
// Remove the fourth element (index->3, value->14) of the array
int removeIndex = 1;
for (int i = removeIndex; i < elArray.length - 3; i++) {
elArray[i] = elArray[i + 3];
}
return elArray.length;
}
//Array Lists
//1. Given a list of numbers, check which one is the highest and print it
public int getHighestNumber(List<Integer> myList) {
int max = myList.get(0);
for (int i : myList) {
if (i > max) {
max = i;
}
}
return max;
}
//2. Given a list of numbers, determine all of the even numbers
public List evenNumbersFromList(List<Integer> myList) {
List<Integer> secondList = new ArrayList();
for (int i : myList) {
if (i % 2 == 0) {
secondList.add(i);
}
}
return secondList;
}
//3.Write a Java program to iterate through all elements in a loop starting at the specified position
public String[] arrBeverages() {
String[] arrBeverages = {"latte", "chai", "cappuccino", "espresso", "milkshake"};
for (int i = 0; i < arrBeverages.length; i++) {
//
if (i > 2) {
System.out.println("Sorted beverages from position 2 are: " + arrBeverages[i]); //nu pot pune System.out in Main din cauza [i]
}
}
return arrBeverages;
}
//4. Write a Java program to sort an array or a list
//a.Int Array with Array.sort
public int[] arrSortEx() {
int[] arrSort = {23, 1556, 57, 5000, 101, 325, 229, 5033};
Arrays.sort(arrSort);
for (int i = 0; i < arrSort.length; i++) {
System.out.println(arrSort[i]);
//return arrSort.length;
}
return arrSort;
}
Calculator calculator = new Calculator();
public void adunare2 () {
System.out.println(calculator.adunare(2, 3));
}
//ca sa chem o metoda dintr-o clasa in alta clasa, ii fac un obiect in clasa in care vreau (Calculator calculator...)
//2.ii fac o metoda (public...)
//3.o apelez (calculator.adunare
//4. introduc parametrii pe care deja i-am setat in metoda in clasa ei, (2, 3)
//5. daca metoda nu e cu void in clasa ei, va returna ceva (e un public int)
}
|
package SpritesheetRender;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Spritesheet {
private BufferedImage spritesheet;
public Spritesheet(String path) {
//try / catch gerado automaticamente
try {
/*ImageIO é uma classe nativa do java para manipulação, renderização, armazenamento e edição de
* imagens, também sendo o modo mais prático para capturar imagens dentro de variáveis
* (também podendo funcionar para arquivos no geral)*/
spritesheet = ImageIO.read(getClass().getResource(path));
//getClass() = Pega a classe em questão
//getResource() = pega na pasta res os arquivos com o nome indicado no path
/*Nesse caso estamos armazenando a imagem selecionada na variável path dentro da variável spritesheet*/
} catch (IOException e) {
e.printStackTrace();
}
}
public BufferedImage getSprite(int x, int y, int width, int height) {
return spritesheet.getSubimage(x, y, width, height);
//retorna a imagem que já estava no spritesheet, mas recortada no parâmetros desejados
//pegar imagem a partir desse x, com esse y, tendo isso de largura e isso de altura
}
}
|
package com.example.readdata.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.readdata.Activity.PlayMusicActivity;
import com.example.readdata.Model.BaiHat;
import com.example.readdata.R;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class FragmentBaiHat extends Fragment {
private View view;
private static ImageView img;
private static TextView name;
private static TextView singer;
private static TextView titlename;
private static TextView luotnghe;
private static BaiHat dataPlaymusic;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_baihat, container, false);
dataPlaymusic = PlayMusicActivity.dataBaiHat;
findView();
getData(dataPlaymusic);
return view;
}
private void findView(){
titlename = view.findViewById(R.id.titlename_baihat);
name = view.findViewById(R.id.name_baihat);
img = view.findViewById(R.id.image_baihat);
singer = view.findViewById(R.id.singer_baihat);
luotnghe = view.findViewById(R.id.luotnghe_baihat);
}
public static void getData(BaiHat baiHat){
titlename.setText(baiHat.getName());
name.setText(baiHat.getName());
Picasso.get()
.load(baiHat.getUrlimage())
.into(img);
singer.setText(baiHat.getTitle());
if (baiHat.getLuotnghe() != null) {
luotnghe.setText(baiHat.getLuotnghe() + " Lượt nghe");
}
}
}
|
package com.yida.design.factory.main;
import com.yida.design.factory.AbstractHumanFactory;
import com.yida.design.factory.extend.HumanFactory;
import com.yida.design.factory.extend.StaticHumanFactory;
import com.yida.design.factory.impl.BlackHuman;
import com.yida.design.factory.impl.WhiteHuman;
import com.yida.design.factory.impl.YellowHuman;
/**
*********************
* @author yangke
* @version 1.0
* @created 2018年4月20日 下午12:14:04
***********************
*/
public class NvWa {
public static void main(String[] args) {
AbstractHumanFactory yinYangLu = new HumanFactory();
WhiteHuman createHuman = StaticHumanFactory.createHuman(WhiteHuman.class);
createHuman.talk();
System.err.println("静态");
// 第一次造人火候不足,造了白人
WhiteHuman whiteHuman = yinYangLu.createHuman(WhiteHuman.class);
whiteHuman.getColor();
whiteHuman.talk();
BlackHuman blackHuman = yinYangLu.createHuman(BlackHuman.class);
blackHuman.getColor();
blackHuman.talk();
YellowHuman yellowHuman = yinYangLu.createHuman(YellowHuman.class);
yellowHuman.getColor();
yellowHuman.talk();
}
}
|
package ch.springcloud.lite.core.connector;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
@Data
public class LoadServerListeners {
public LoadServerListeners() {
super();
this.listeners = new ArrayList<>();
}
List<LoadServerListener> listeners;
public void addListener(LoadServerListener listener) {
this.listeners.add(listener);
}
}
|
/*
* 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 steganoapp.core;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import sun.misc.IOUtils;
/**
*
* @author calvin-pc
*/
public class FourPixelDiffrenceDeStegano implements DeStegano{
public int treshold = 6;
public int kl = 1; //Number of bit subsitution when 'smooth'
public int kh = 3; //Number of bit subsitution when 'rough'
public int msgSize;
private BufferedImage cover;
private Random numberGen;
@Override
public void setCoverObject(File cover) {
throw new UnsupportedOperationException();
}
@Override
public void setKey(String key) {
int hash=7;
for (int i=0; i < key.length(); i++) {
hash = hash*31+key.charAt(i) % 10000;
}
numberGen = new Random();
numberGen.setSeed(hash);
}
@Override
public void setMsgSize(int size) {
msgSize = size;
}
@Override
public void setStegoObject(File stegoObj) {
try {
this.cover = ImageIO.read(stegoObj);
} catch (IOException ex) {
Logger.getLogger(FourPixelDiffrenceStegano.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
@Override
public File deSteganoObject() {
int[] randomList; int rowSize, columnSize;
byte[][][] RGBDimension;
byte[] messageByte;
int messageByteOffset = 0, messageBitOffset = 0;
rowSize = (cover.getWidth())/2;
columnSize = (cover.getHeight())/2;
//Buat list random unik
randomList = new int [rowSize * columnSize];
for (int i = 0; i < columnSize; i++) {
for (int j = 0; j < rowSize; j++) {
randomList[i*rowSize + j] = i*rowSize + j;
}
}
for (int i = columnSize - 1; i >= 0; i--) {
for (int j = rowSize - 1; j >=0; j--) {
if (i == 0 && j == 0) continue;
int n = Math.abs(numberGen.nextInt()) % (i*rowSize + j);
int temp = randomList[i*rowSize + j];
randomList[i*rowSize + j] = randomList[n];
randomList[n] = temp;
}
}
RGBDimension = new byte[3][cover.getHeight()][cover.getWidth()];
for (int i = 0; i < cover.getHeight(); i++) {
for (int j = 0; j < cover.getWidth(); j++) {
int rgb = cover.getRGB(j, i);
for (int bitOffset = 0; bitOffset != 24; bitOffset += 8) {
byte value = (byte)((rgb >> bitOffset) % 256); //get spesific r/g/b value
RGBDimension[bitOffset/8][i][j] = value;
}
}
}
messageByte = new byte [msgSize];
for (int i = 0; i < randomList.length
&& messageByteOffset < messageByte.length; i++) { //until all message extracted
for (int dim = 0; dim < 3; dim++) {
int x = randomList[i] / rowSize * 2;
int y = randomList[i] % rowSize * 2;
int value1 = byteToUnsignedInt(RGBDimension[dim][x][y]);
int value2 = byteToUnsignedInt(RGBDimension[dim][x+1][y]);
int value3 = byteToUnsignedInt(RGBDimension[dim][x][y+1]);
int value4 = byteToUnsignedInt(RGBDimension[dim][x+1][y+1]);
int k = getK(value1, value2, value3, value4);
if (k == 0) continue; //Error block
//Step 3
int mask = 1;
for (int i1 = 1; i1 < k; i1++) mask = (mask << 1) + 1;
if (messageByteOffset < messageByte.length) { // still message to embeded
int pesan = value1 & mask;
if ((8 - messageBitOffset) >= k) {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan << (8-messageBitOffset-k)));
messageBitOffset += k;
}
else {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan >> (k- (8-messageBitOffset))));
messageByteOffset++;
if (messageByteOffset < messageByte.length) {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan << (8- (k- (8-messageBitOffset)))));
}
messageBitOffset = k- (8-messageBitOffset);
}
if (messageBitOffset == 8) {
messageBitOffset = 0;
messageByteOffset ++;
}
}
if (messageByteOffset < messageByte.length) { // still message to embeded
int pesan = value2 & mask;
if ((8 - messageBitOffset) >= k) {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan << (8-messageBitOffset-k)));
messageBitOffset += k;
}
else {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan >> (k- (8-messageBitOffset))));
messageByteOffset++;
if (messageByteOffset < messageByte.length) {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan << (8- (k- (8-messageBitOffset)))));
}
messageBitOffset = k- (8-messageBitOffset);
}
if (messageBitOffset == 8) {
messageBitOffset = 0;
messageByteOffset ++;
}
}
if (messageByteOffset < messageByte.length) { // still message to embeded
int pesan = value3 & mask;
if ((8 - messageBitOffset) >= k) {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan << (8-messageBitOffset-k)));
messageBitOffset += k;
}
else {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan >> (k- (8-messageBitOffset))));
messageByteOffset++;
if (messageByteOffset < messageByte.length) {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan << (8- (k- (8-messageBitOffset)))));
}
messageBitOffset = k- (8-messageBitOffset);
}
if (messageBitOffset == 8) {
messageBitOffset = 0;
messageByteOffset ++;
}
}
if (messageByteOffset < messageByte.length) { // still message to embeded
int pesan = value4 & mask;
if ((8 - messageBitOffset) >= k) {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan << (8-messageBitOffset-k)));
messageBitOffset += k;
}
else {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan >> (k- (8-messageBitOffset))));
messageByteOffset++;
if (messageByteOffset < messageByte.length) {
messageByte[messageByteOffset] = (byte)(byteToUnsignedInt(messageByte[messageByteOffset])
| (pesan << (8- (k- (8-messageBitOffset)))));
}
messageBitOffset = k- (8-messageBitOffset);
}
if (messageBitOffset == 8) {
messageBitOffset = 0;
messageByteOffset ++;
}
}
}
}
File stegoFile = new File("deStegoFile");//D:\\Kuliah\\image\\a.txt");
try {
stegoFile.delete();
FileOutputStream output = new FileOutputStream(stegoFile);
output.write(messageByte);
output.close();
} catch (IOException ex) {
System.out.println("Error on creating image file. " + ex);
}
return stegoFile;
}
double CalculateD (int y1, int y2, int y3, int y4) {
int ymin = Math.min(y4, Math.min(y3, Math.min(y1, y2)));
double d;
int sum = y1 + y2 + y3 + y4 - 4*ymin;
d = sum / 3;
return d;
}
//get the k-bit value for LSB subsitution, if 0 then no subsitution
int getK (int v1,int v2,int v3,int v4) {
double d = CalculateD(v1, v2, v3, v4);
if (d <= treshold) { // smooth block
int vmax = Math.max(v1, v2);
vmax = Math.max(v3, vmax);
vmax = Math.max(v4, vmax);
int vmin = Math.min(v1, v2);
vmin = Math.min(v3, vmin);
vmin = Math.min(v4, vmin);
if((vmax - vmin) > (2*treshold+2)) {// error block {
return 0;
}
else {
return kl;
}
} //edgy block
else {
return kh;
}
}
public int byteToUnsignedInt (byte n) {
int a = n & 0xFF;
return a;
}
}
|
package com.facebook.react.util;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableType;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JSStackTrace {
private static final Pattern mJsModuleIdPattern = Pattern.compile("(?:^|[/\\\\])(\\d+\\.js)$");
public static String format(String paramString, ReadableArray paramReadableArray) {
StringBuilder stringBuilder = new StringBuilder(paramString);
stringBuilder.append(", stack:\n");
for (int i = 0; i < paramReadableArray.size(); i++) {
ReadableMap readableMap = paramReadableArray.getMap(i);
stringBuilder.append(stackFrameToLineNumber(readableMap));
stringBuilder.append("@");
stringBuilder.append(stackFrameToModuleId(readableMap));
stringBuilder.append(stackFrameToLineNumber(readableMap));
if (readableMap.hasKey("column") && !readableMap.isNull("column") && readableMap.getType("column") == ReadableType.Number) {
stringBuilder.append(":");
stringBuilder.append(readableMap.getInt("column"));
}
stringBuilder.append("\n");
}
return stringBuilder.toString();
}
private static int stackFrameToLineNumber(ReadableMap paramReadableMap) {
if (paramReadableMap != null)
try {
if (paramReadableMap.hasKey("lineNumber") && paramReadableMap.getType("lineNumber") == ReadableType.String)
return paramReadableMap.getInt("lineNumber");
} finally {}
return 0;
}
private static String stackFrameToMethodName(ReadableMap paramReadableMap) {
if (paramReadableMap != null)
try {
if (paramReadableMap.hasKey("methodName") && paramReadableMap.getType("methodName") == ReadableType.Number)
return paramReadableMap.getString("methodName");
} finally {}
return "";
}
private static String stackFrameToModuleId(ReadableMap paramReadableMap) {
if (paramReadableMap.hasKey("file") && !paramReadableMap.isNull("file") && paramReadableMap.getType("file") == ReadableType.String) {
Matcher matcher = mJsModuleIdPattern.matcher(paramReadableMap.getString("file"));
if (matcher.find()) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(matcher.group(1));
stringBuilder.append(":");
return stringBuilder.toString();
}
}
return "";
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\reac\\util\JSStackTrace.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.squidtech.nodechan;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
*
* This class represents a single peer to which the client may send and receive
* posts and other data.
*
*/
public class Peer {
/** This peer's address information **/
private InetAddress addr;
/** The time this peer was last heard **/
private long lastHeard;
/** Whether or not we have resolved this peer's address **/
private boolean resolved;
public Peer(String ip) {
this.lastHeard = System.currentTimeMillis();
try {
this.addr = InetAddress.getByName(ip);
this.resolved = true;
} catch (UnknownHostException e) {
this.resolved = false;
}
}
/**
* We just heard from this peer, update their time
*/
public void heard() {
this.lastHeard = System.currentTimeMillis();
}
/**
* Return whether or not the address of this peer equals another address
*/
public boolean equalsAddress(InetAddress other) {
return this.addr.getHostAddress().equals(other.getHostAddress());
}
/*
* getters
*/
public InetAddress getAddress() {
return addr;
}
public long getLastHeard() {
return this.lastHeard;
}
public boolean isResolved() {
return this.resolved;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.util.models;
import de.hybris.platform.catalog.model.CatalogVersionModel;
import de.hybris.platform.cmsfacades.util.builder.ProductModelBuilder;
import de.hybris.platform.core.model.product.ProductModel;
import de.hybris.platform.product.daos.ProductDao;
import java.util.Locale;
public class ProductModelMother extends AbstractModelMother<ProductModel>
{
public static final String MOUSE = "mouse";
public static final String CAR = "car";
private ProductDao productDao;
public ProductModel createMouseProduct(final CatalogVersionModel catalogVersion)
{
return createDefaultProduct(MOUSE, catalogVersion);
}
public ProductModel createCarProduct(final CatalogVersionModel catalogVersion)
{
return createDefaultProduct(CAR, catalogVersion);
}
protected ProductModel createDefaultProduct(final String uid, final CatalogVersionModel catalogVersion)
{
return getFromCollectionOrSaveAndReturn(() -> getProductDao().findProductsByCode(uid),
() -> ProductModelBuilder.aModel() //
.withName(uid, Locale.ENGLISH) //
.withCatalogVersion(catalogVersion) //
.withCode(uid).build());
}
public ProductDao getProductDao()
{
return productDao;
}
public void setProductDao(final ProductDao productDao)
{
this.productDao = productDao;
}
}
|
package com.z3pipe.z3location.util;
import java.io.FileOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class GpsFileUtil {
private static ExecutorService executor;
private static ExecutorService getExecutor() {
if (executor == null) {
executor = Executors.newSingleThreadExecutor();
}
return executor;
}
/**
* 写到文件中
*
* @param filePath 文件路径
* @param data 写入的数据内容
* @param append 是否追加
*/
public static void writeBinaryStream(final String filePath, final String data, final boolean append) {
getExecutor().execute(new Runnable() {
@Override
public void run() {
FileOutputStream outStream = null;
try {
//获取输出流
outStream = new FileOutputStream(filePath, append);
outStream.write(data.getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outStream != null) {
outStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
}
|
package plp.functional3.declaration;
import java.util.ArrayList;
import java.util.List;
import plp.expressions1.util.Tipo;
import plp.expressions2.expression.Id;
import plp.expressions2.memory.AmbienteCompilacao;
import plp.expressions2.memory.VariavelJaDeclaradaException;
import plp.expressions2.memory.VariavelNaoDeclaradaException;
import plp.functional1.declaration.DeclaracaoFuncional;
import plp.functional1.util.TipoFuncao;
import plp.functional1.util.TipoPolimorfico;
import plp.functional3.expression.ValorFuncao;
public class DecFuncao implements DeclaracaoFuncional {
private ValorFuncao valorFuncao;
public DecFuncao(List<DecPadrao> listaDecPadroes) {
this.valorFuncao = new ValorFuncao(listaDecPadroes);
}
public DecFuncao(ValorFuncao valorFuncao) {
this.valorFuncao = valorFuncao;
}
public boolean checaTipo(AmbienteCompilacao ambiente)
throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException {
ambiente.incrementa();
// Adiciona os parametros da funcão como TipoPolimorfico
List<Tipo> params = new ArrayList<Tipo>(this.getAridade());
for ( int i = 0; i < this.getAridade(); i++ ) {
params.add(new TipoPolimorfico());
}
Tipo tipo = new TipoFuncao(params, new TipoPolimorfico());
// Mapeia a própria função no ambiente para permitir recursão.
ambiente.map(this.getId(), tipo);
// Checa o tipo do ValorFuncao da DecFuncao
boolean result = this.valorFuncao.checaTipo(ambiente);
ambiente.restaura();
return result;
}
public int getAridade() {
return this.valorFuncao.getAridade();
}
public ValorFuncao getExpressao() {
return this.valorFuncao;
}
public void setValorFuncao(ValorFuncao novoValorFuncao) {
this.valorFuncao = novoValorFuncao;
}
public List<DecPadrao> getDecPadroes() {
return this.valorFuncao.getDecPadroes();
}
public Id getId() {
return this.getDecPadroes().get(0).getIdFuncao();
}
public Tipo getTipo(AmbienteCompilacao amb) throws VariavelNaoDeclaradaException,
VariavelJaDeclaradaException {
amb.incrementa();
List<Tipo> params = new ArrayList<Tipo>(this.getAridade());
for ( int i = 0; i < this.getAridade(); i++ ) {
params.add(new TipoPolimorfico());
}
Tipo tipo = new TipoFuncao(params, new TipoPolimorfico());
amb.map(this.getId(), tipo);
// Retorna o tipo do ValorFuncao da DecFuncao
Tipo result = this.valorFuncao.getTipo(amb);
amb.restaura();
return result;
}
public DecFuncao clone() {
return new DecFuncao(this.valorFuncao.clone());
}
}
|
/*
* JFrameTest1.java
*
* Created on 2016年3月26日, 下午9:38
*/
package com.local.view;
import com.local.util.UIUtil;
/**
*
* @author xubo
*/
public class JFrameTest1 extends javax.swing.JFrame {
/** Creates new form JFrameTest1 */
public JFrameTest1() {
initComponents();
UIUtil.setCenter(this);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" 生成的代码 ">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenu4 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("\u5e10\u53f7");
jLabel2.setText("\u5bc6\u7801");
jButton1.setText("\u767b\u5f55");
jButton2.setText("\u91cd\u7f6e");
jMenuBar1.setToolTipText("qwe");
jMenu1.setText("\u6587\u4ef6");
jMenu1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu1ActionPerformed(evt);
}
});
jMenu2.setText("\u6d4b\u8bd5");
jMenu2.setToolTipText("");
jMenu4.setText("\u7b2c\u4e09\u5c42");
jMenuItem1.setText("\u83dc\u5355\u9879");
jMenu4.add(jMenuItem1);
jMenu2.add(jMenu4);
jMenu1.add(jMenu2);
jMenuBar1.add(jMenu1);
jMenu3.setText("\u9000\u51fa");
jMenuBar1.add(jMenu3);
setJMenuBar(jMenuBar1);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(40, 40, 40)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1)
.add(jLabel2))
.add(56, 56, 56)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 105, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 105, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(layout.createSequentialGroup()
.add(jButton1)
.add(47, 47, 47)
.add(jButton2)))
.addContainerGap(175, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(78, 78, 78)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel1)
.add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(56, 56, 56)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel2)
.add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(34, 34, 34)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jButton1)
.add(jButton2))
.addContainerGap(46, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu1ActionPerformed
// TODO 将在此处添加您的处理代码:
}//GEN-LAST:event_jMenu1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFrameTest1().setVisible(true);
}
});
}
// 变量声明 - 不进行修改//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// 变量声明结束//GEN-END:variables
}
|
package LightProcessing.common.tile;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import LightProcessing.common.block.*;
import LightProcessing.common.lib.*;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
public class TileEntityHarvester extends TileEntity {
private java.util.Random r = new java.util.Random();
private int chance;
@Override
public void updateEntity() {
chance = 2000;
if (this.worldObj.getBlockId(this.xCoord, this.yCoord + 1, this.zCoord) == IDRef.LIGHT_BLOCK_ID || this.worldObj.getBlockId(this.xCoord, this.yCoord + 1, this.zCoord) == IDRef.DARK_BLOCK_ID) {
chance /= 2;
}
if (r.nextInt(chance) == 0) {
BlockHarvester.Essence(this.worldObj, this.xCoord, this.yCoord, this.zCoord);
}
}
@SideOnly(Side.CLIENT)
public AxisAlignedBB getRenderBoundingBox() {
AxisAlignedBB bb = INFINITE_EXTENT_AABB;
bb = AxisAlignedBB.getAABBPool().getAABB(xCoord - 1, yCoord, zCoord - 1, xCoord + 2, yCoord + 2, zCoord + 2);
return bb;
}
public void Spawn(Float LightValue, boolean isAbove) {
ItemStack stack;
if (LightValue > 0.7F) {
stack = new ItemStack(LPItems.ItemLightBall, 1);
}
else {
stack = new ItemStack(LPItems.ItemDarkBall, 1);
}
EntityItem entityitem;
if(isAbove)
entityitem = new EntityItem(this.worldObj, this.xCoord + 0.5, this.yCoord + 1.0, this.zCoord + 0.5, stack);
else
entityitem = new EntityItem(this.worldObj, this.xCoord + 0.5, this.yCoord + 0.2, this.zCoord + 0.5, stack);
entityitem.motionX = 0;
entityitem.motionY = 0;
entityitem.motionZ = 0;
if (!this.worldObj.isRemote) {
if (!Methods.isPoweredIndirect(this.worldObj, this.xCoord, this.yCoord, this.zCoord)) {
this.worldObj.spawnEntityInWorld(entityitem);
}
}
}
}
|
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.miginfocom.swt.MigLayout;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolTip;
public class operUnos extends DEF implements FocusListener, VerifyListener,
KeyListener {
static String sTablica = "operateri";
static Label lblMess;
static Label lblIme;
static Label lblPrezime;
static Text txtIme;
static Text txtPrezime;
static Label lblUser;
static Label lblUserErr;
static Text txtUser;
static Label lblPass;
static Text txtPass;
static Text txtPass2;
static Label lblPassErr;
static Label lblHint;
static Text txtHint;
static Label sep;
static Label lblPrava;
static Scale slidePrava;
static Label lbldatumOD;
static Label lbldatumDO;
static DateTime dtpOD;
static DateTime dtpDO;
static String dtPoc;
static String dtKraj;
static Button cmdSpremi;
// static Button cmdOdustani;
// static FormLayout FL = new FormLayout ();
// static FormData data = new FormData ();
MigLayout layout = new MigLayout("", "15[]7[]", "20[]7[]7[]7[]7[]");
static Display display;
static Shell shell;
// String[] values;
// String[] labels;
static ToolTip tip;
public operUnos(Shell parent) {
dtPoc = getDateSQL();
dtKraj = getDateSQL();
// shell = new Shell(parent, SWT.APPLICATION_MODAL|SWT.DIALOG_TRIM );
shell = new Shell(parent, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
shell.setBounds(0, 0, 270, 470);
display = shell.getDisplay();
CenterScreen(shell, display);
shell.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
shell.setLayout(layout);
createWidgets();
createControlButtons();
// setLanguage(shell);
shell.open();
if (gBroj != 0) {
fillForm(gBroj);
} else {
shell.setText(getLabel("NewOper") + "?");
}
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
public static void main(String[] args) throws SQLException {
}
private void createControlButtons() {
sep = new Label(shell, SWT.SEPARATOR | SWT.SHADOW_IN | SWT.HORIZONTAL);
sep.setLayoutData("width 250px,wrap,span2");
cmdSpremi = new Button(shell, SWT.PUSH | SWT.WRAP);
cmdSpremi.setText(getLabel("Save"));
cmdSpremi.setLayoutData("width 240px,span 2,wrap");
cmdSpremi.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
switch (e.type) {
case SWT.Selection:
lblMess.setText("Spremanje u tijeku!\n Molimo pričekajte...");
if (checkFields() == true) {
Spremi(gBroj);
gBroj = 0;
shell.dispose();
} else {
// lblMess.setText("Nisu unešeni svi potrebni podaci!");
}
}
}
});
lblMess = new Label(shell, SWT.NONE);
lblMess.setLayoutData("width 240px,span2");
lblMess.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
lblMess.setForeground(display.getSystemColor(SWT.COLOR_RED));
lblMess.setAlignment(SWT.CENTER);
shell.setDefaultButton(cmdSpremi);
}
private void createWidgets() {
tip = new ToolTip(shell, SWT.BALLOON | SWT.ICON_INFORMATION);
lblIme = new Label(shell, SWT.NONE);
lblIme.setText(getLabel("Names"));
lblIme.setLayoutData("width 40px");
lblIme.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
txtIme = new Text(shell, SWT.SINGLE | SWT.BORDER);
txtIme.setLayoutData("width 150px,wrap");
txtIme.addFocusListener(this);
txtIme.addKeyListener(this);
txtIme.setTextLimit(25);
lblPrezime = new Label(shell, SWT.NONE);
lblPrezime.setText(getLabel("Surname"));
lblPrezime.setLayoutData("width 40px");
lblPrezime.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
txtPrezime = new Text(shell, SWT.SINGLE | SWT.BORDER);
txtPrezime.setLayoutData("width 150px,wrap");
txtPrezime.addFocusListener(this);
txtPrezime.addKeyListener(this);
txtPrezime.setTextLimit(25);
lblUser = new Label(shell, SWT.NONE);
lblUser.setText(getLabel("UserName"));
lblUser.setLayoutData("width 40px");
lblUser.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
txtUser = new Text(shell, SWT.SINGLE | SWT.BORDER);
txtUser.setLayoutData("width 100px,wrap");
txtUser.addFocusListener(this);
txtUser.addKeyListener(this);
txtUser.setTextLimit(10);
lblPass = new Label(shell, SWT.NONE);
lblPass.setText(getLabel("Password"));
lblPass.setLayoutData("width 40px");
lblPass.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
txtPass = new Text(shell, SWT.SINGLE | SWT.BORDER | SWT.PASSWORD);
txtPass.setLayoutData("width 70px,wrap");
// txtPass.setEchoChar('*');
txtPass.addFocusListener(this);
txtPass.addKeyListener(this);
txtPass.setTextLimit(50);
lblPass = new Label(shell, SWT.SINGLE);
lblPass.setText(getLabel("Password2"));
lblPass.setLayoutData("width 40px");
lblPass.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
txtPass2 = new Text(shell, SWT.SINGLE | SWT.BORDER | SWT.PASSWORD);
// txtPass2.setEchoChar('*');
txtPass2.setLayoutData("width 70px,wrap");
// txtPass2.addVerifyListener(this);
txtPass2.setTextLimit(50);
txtPass2.addKeyListener(this);
txtPass2.addFocusListener(this);
txtPass2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
String string = "";
if ((e.stateMask & SWT.SHIFT) != 0) {
if (e.keyCode == 112) {
// logger.logg("Prikaz passworda");
// System.out.println("pass to show: " +
// txtPass2.getText());
tip.setMessage("Password I : "
+ crypt.Decrypt(txtPass.getText())
+ "\nPassword II: "
+ crypt.Decrypt(txtPass2.getText()));
tip.setLocation(
(txtPass2.getBounds().x + shell.getBounds().x + 35),
(txtPass2.getBounds().y + shell.getBounds().y + 35));
tip.setVisible(true);
e.doit = false;
}
}
}
});
lblPass = new Label(shell, SWT.SINGLE);
lblPass.setText(getLabel("Rights"));
lblPass.setLayoutData("width 40px");
lblPass.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
slidePrava = new Scale(shell, SWT.HORIZONTAL);
slidePrava.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
slidePrava.setMinimum(0);
slidePrava.setMaximum(2);
slidePrava.setIncrement(1);
slidePrava.setPageIncrement(1);
slidePrava.setLayoutData("width 100,height 15px,wrap,span2");
slidePrava.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
String prava = "";
switch (slidePrava.getSelection()) {
case 0:
prava = getLabel("RIGHTS0");
break;
case 1:
prava = getLabel("RIGHTS1");
break;
case 2:
prava = getLabel("RIGHTS2");
break;
}
prava = getLabel("UserRights") + ": " + prava + " ("
+ slidePrava.getSelection() + ")";
lblPrava.setText(prava);
}
});
lblPrava = new Label(shell, SWT.SINGLE | SWT.CENTER);
lblPrava.setText("");
lblPrava.setForeground(display.getSystemColor(SWT.COLOR_BLUE));
lblPrava.setLayoutData("width 220px,span2,wrap");
lblPrava.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
if (login.getflgOper() == true) {
slidePrava.setSelection(2);
slidePrava.setEnabled(false);
lblPrava.setText(getLabel("UserRights") + ": "
+ getLabel("RIGHTS2"));
}
sep = new Label(shell, SWT.SEPARATOR | SWT.SHADOW_IN | SWT.HORIZONTAL);
sep.setLayoutData("width 250px,wrap,span2 ");
lbldatumOD = new Label(shell, SWT.NONE);
lbldatumOD.setText(getLabel("DateBeg"));
lbldatumOD.setLayoutData("width 40px");
lbldatumOD.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
dtpOD = new DateTime(shell, SWT.BORDER | SWT.DATE | SWT.DROP_DOWN);
dtpOD.setLayoutData("width 100px, wrap");
dtpOD.setDate(getToday().getYear(), getToday().getMonth(), DEF
.getToday().getDay());
dtpOD.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
switch (e.type) {
case SWT.Selection:
lblMess.setText("Početni dan odabran: " + dtpOD.getDay()
+ "." + dtpOD.getMonth() + "." + dtpOD.getYear());
dtPoc = dtpDO.getYear() + "-" + dtpDO.getMonth() + "-"
+ dtpDO.getDay();
break;
}
}
});
lbldatumOD = new Label(shell, SWT.NONE);
lbldatumOD.setText(getLabel("DateEnd"));
lbldatumOD.setLayoutData("width 40px");
lbldatumOD.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
dtpDO = new DateTime(shell, SWT.BORDER | SWT.DATE | SWT.DROP_DOWN);
dtpDO.setLayoutData("width 100px, wrap");
dtpDO.setDate(getToday().getYear(), getToday().getMonth(), DEF
.getToday().getDay());
dtpDO.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
switch (e.type) {
case SWT.Selection:
dtKraj = dtpDO.getYear() + "-" + dtpDO.getMonth() + "-"
+ dtpDO.getDay();
lblMess.setText("Krajnji dan odabran: " + dtpDO.getDay()
+ "." + dtpDO.getMonth() + "." + dtpDO.getYear());
break;
}
}
});
sep = new Label(shell, SWT.SEPARATOR | SWT.SHADOW_IN | SWT.HORIZONTAL);
sep.setLayoutData("width 250px,wrap,span2");
lblHint = new Label(shell, SWT.SINGLE);
lblHint.setText(getLabel("Hint"));
lblHint.setLayoutData("width 80px,height 50px");
lblHint.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
txtHint = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.WRAP
| SWT.V_SCROLL);
txtHint.setLayoutData("width 160px,height 60px,wrap");
txtHint.addKeyListener(this);
txtHint.setTextLimit(100);
}
private static void Spremi(int broj) {
if (broj != 0) {
// System.out.println();
// System.out.println("update operateri set ime='" +
// txtIme.getText()
// + "',prezime='" + txtPrezime.getText() + "',[user]='"
// + txtUser.getText() + "',pass='" + txtPass.getText()
// + "',vrijediOd='" + RSet.getSqlDate() + "',vrijediDo='"
// + RSet.getSqlDate() + "',prava="
// + slidePrava.getSelection() + " where ID= " + broj + "");
RSet.updateRS("update operateri set ime='" + txtIme.getText()
+ "',prezime='" + txtPrezime.getText() + "',korisnik='"
+ txtUser.getText() + "',lozinka='"
+ crypt.Encrypt(crypt.Decrypt((txtPass.getText())))
+ "',vrijediOd='" + dtPoc + "',vrijediDo='" + dtKraj
+ "',prava=" + slidePrava.getSelection() + ",hint='"
+ iNull(txtHint.getText()) + "' where ID= " + broj);
logger.logg("Ažurirane vrijednosti u tablici " + sTablica + " (ID="
+ broj + ")");
gBroj = 0;
} else {
// System.out.println("ime='" + txtIme.getText() + "',prezime='"
// + txtPrezime.getText() + "',[user]='" + txtUser.getText()
// + "',pass='" + txtPass.getText() + "',vrijediOd='" + dtPoc
// + "',vrijediDo='" + dtKraj + "'");
String col = "ime,prezime,korisnik,lozinka,vrijediOD,vrijediDO,prava,hint";
String val = "'" + txtIme.getText() + "','" + txtPrezime.getText()
+ "','" + txtUser.getText() + "','"
+ crypt.Encrypt(txtPass.getText()) + "','" + dtPoc + "','"
+ dtKraj + "'," + slidePrava.getSelection() + ",'"
+ iNull(txtHint.getText()) + "'";
RSet.addRS2(sTablica, col, val);
logger.logg("Unos novih vrijednosti u tablicu " + sTablica + " ("
+ txtIme.getText() + "," + txtPrezime.getText() + ")");
gBroj = 0;
}
}
private static void fillForm(int broj) {
ResultSet rs;
try {
rs = RSet.openRS("select * from " + sTablica + " where ID=" + broj);
while (rs.next()) {
shell.setText(getLabel("Edit") + ": " + rs.getString("Ime")
+ " " + rs.getString("Prezime"));
txtIme.setText(rs.getString("Ime"));
txtPrezime.setText(rs.getString("Prezime"));
txtUser.setText(rs.getString("Korisnik"));
txtPass.setText(rs.getString("Lozinka"));
txtPass2.setText(rs.getString("Lozinka"));
txtHint.setText(iNull(rs.getString("hint")));
// System.out.println("Slider: " + rs.getInt("prava"));
switch (rs.getInt("prava")) {
case 0:
lblPrava.setText(getLabel("UserRights") + ": "
+ getLabel("RIGHTS0"));
slidePrava.setSelection(0);
break;
case 1:
lblPrava.setText(getLabel("UserRights") + ": "
+ getLabel("RIGHTS1"));
slidePrava.setSelection(1);
break;
case 2:
lblPrava.setText(getLabel("UserRights") + ": "
+ getLabel("RIGHTS2"));
slidePrava.setSelection(2);
break;
}
// String date = "2000-11-01";
// SqlDate = java.sql.Date.valueOf(date);
// System.out.println("Datum: " + rs.getString("vrijediOD"));
}
RSet.closeRS();
txtIme.selectAll();
} catch (SQLException e) {
System.out.println("fillForm - greška RS!");
e.printStackTrace();
logger.loggErr("operUnos " + e.getMessage());
}
}
private static boolean checkPass() {
return txtPass.getText().equals(txtPass2.getText());
}
// ***************************************************************************************************//
// verifikacija teksta PRIMJER (ne koristi se)
@Override
public void verifyText(VerifyEvent event) {
// Assume we don't allow it
event.doit = false;
// Get the character typed
char myChar = event.character;
String text = ((Text) event.widget).getText();
// Allow '-' if first character
if (myChar == '-' && text.length() == 0)
event.doit = true;
// Allow 0-9
if (Character.isDigit(myChar))
event.doit = true;
// Allow backspace
if (myChar == '\b')
event.doit = true;
}
// ***************************************************************************************************//
@Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
Text t = (Text) e.widget;
t.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
t.selectAll();
}
@Override
public void focusLost(FocusEvent e) {
Text t = (Text) e.widget;
t.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
if (t.getText() == "") {
// System.out.println(e.toString());
lblMess.setText("Vrijednost mora biti unešena!");
} else {
lblMess.setText("");
}
if (e.getSource() == txtPass) {
} else if (e.getSource() == txtPass2) {
if (checkPass() == false) {
lblMess.setText("Passwordi nisu jednaki!");
} else {
lblMess.setText("");
}
}
}
@Override
public void keyPressed(KeyEvent e) {
String string = "";
Text t = (Text) e.widget;
// if ((e.stateMask & SWT.SHIFT) != 0) string += "SHIFT - keyCode = " +
// e.keyCode;
System.out.println(SWT.DOWN);
if (e.keyCode == 16777218) {// dolje
t.traverse(SWT.TRAVERSE_TAB_NEXT);
} else if (e.keyCode == 16777217) {// gore
t.traverse(SWT.TRAVERSE_TAB_PREVIOUS);
}
}
@Override
public void keyReleased(KeyEvent e) {
};
private boolean checkFields() {
int sum = 0;
// provjera unosa texta
if (txtIme.getText() == "") {
txtIme.setFocus();
} else {
sum += 1;
}
if (txtPrezime.getText() == "") {
txtPrezime.setFocus();
} else {
sum += 1;
}
if (txtUser.getText() == "") {
txtUser.setFocus();
} else {
sum += 1;
}
if (txtPass.getText() == "") {
txtPass.setFocus();
} else {
sum += 1;
}
if (txtPass2.getText() == "") {
txtPass2.setFocus();
} else {
sum += 1;
}
if (checkPass() == false) {
txtPass2.setFocus();
} else {
sum += 5;
}
// Provjera datuma (kao funkcija datuma)
Date dateOD = new Date(dtpOD.getYear(), dtpOD.getMonth(),
dtpOD.getDay());
Date dateDO = new Date(dtpDO.getYear(), dtpDO.getMonth(),
dtpDO.getDay());
if (dateOD.compareTo(dateDO) < 0) {
sum += 1;
} else if (dateOD.compareTo(dateDO) > 0) {
lblMess.setText("Početni datum veći od krajnjeg...");
} else {
sum += 1;
}
// System.out.println(sum);
return (sum == 11);
}
} |
package com.jx.sleep_dg.Bean;
import java.util.List;
/**
* Created by dingt on 2018/7/30.
*/
public class EveXinlvBean {
String type;
List<HeartRateBean> heartRateBeans;
public EveXinlvBean(String type, List<HeartRateBean> heartRateBeans) {
this.type = type;
this.heartRateBeans = heartRateBeans;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<HeartRateBean> getHeartRateBeans() {
return heartRateBeans;
}
public void setHeartRateBeans(List<HeartRateBean> heartRateBeans) {
this.heartRateBeans = heartRateBeans;
}
}
|
package com.anibal.educational.rest_service.comps.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.odhoman.api.utilities.db.DatabaseConnection;
public class DbUtil {
public final static String MASCARA_TIMESTAMP = "YYYY-MM-DD HH24:MI:SS.FF";
public final static String MIN_TIMESTAMP = "1900-01-01 00:00:00.0";
public final static String MAX_TIMESTAMP = "9999-12-31 00:00:00.0";
public DbUtil() {
}
/**
* Devuelve el proximo valor de la sequencias pasada como parametro.
*
* @param DatabaseConnection
* con la conexion a la db. seqName nombre de la secuencia
* @return Long nextval de la sequencia En caso de error devuelve SQLException para que sea manejada desde el metodo
* que invoca.
*/
public static Long getNewSequenceKey(DatabaseConnection db, String seqName) throws SQLException {
Long nKey = null;
String sql;
PreparedStatement ps = null;
ResultSet rs = null;
// Busca en la sequencia para SubObjetoReclamos el proximo valor.
// sql = " select nextval('" + seqName + "') as n_key";
sql = " select " + seqName + ".NEXTVAL as n_key from DUAL";
ps = db.prepare(sql);
rs = ps.executeQuery();
if (rs.next())
nKey = Long.valueOf(rs.getLong("n_key"));
rs.close();
ps.close();
return nKey;
}
/**
* Devuelve la descripcion correspondiente a los datos pasados como parametro.
*
* @param DatabaseConnection
* con la conexion a la db. tableName nombre de la tabla colKey columna clave colDes columna con la
* descripcion a recuperar valKey valor de la clave
* @return String descripcion recuperada En caso de error devuelve SQLException para que sea manejada desde el
* metodo que invoca.
*/
public static String getDescriptionByKey(DatabaseConnection db, String tableName, String colKey, String colDes,
Long valKey) throws SQLException {
String valDes = "";
String sql;
PreparedStatement ps = null;
ResultSet rs = null;
// sql
sql = " select " + colDes + " from " + tableName + " where " + colKey + " = " + valKey.toString();
ps = db.prepare(sql);
rs = ps.executeQuery();
if (rs.next())
valDes = rs.getString(colDes);
rs.close();
ps.close();
return valDes;
}
/**
* Devuelve la clausula WHERE para filtrar los registros habilitados
*
* @param campoHabilitado el campo que debe contener lo valores pasados por parametros
* @param params parametros que especifican cuales son los valores habilitados
* @param withWhere String de la clausula WHERE que se aplicara en la consulta a la tabla, si tiene
*/
public static String getClausulaWhereHabilitados(String campoHabilitado, String params) {
return getClausulaHabilitados(campoHabilitado, params, " where");
}
/**
* Devuelve la clausula del campo que tiene habilitado con sus valores
*
* @param campoHabilitado el campo que debe contener lo valores pasados por parametros
* @param params parametros que especifican cuales son los valores habilitados
* @param prefix String un prefijo que se aplicara en la consulta a la tabla, si tiene
*/
public static String getClausulaHabilitados(String campoHabilitado, String params, String prefix) {
String codigos = "";
String[] strCodesHabilitados = params.split(",");
for (int i=0; i < strCodesHabilitados.length; i++){
codigos += "'" + strCodesHabilitados[i] + "'";
if (i+1 < strCodesHabilitados.length)
codigos += ",";
}
if(prefix==null){
prefix="";
}
return prefix+" "+campoHabilitado+" IN (" + codigos + ") ";
}
public static byte[] incrementalByteCopy(InputStream inputStream) throws IOException {
byte[] chunk = new byte[4096]; //leo de a 4k
int cant = 1;
byte[] result = new byte[0]; //leo de a 4k
while ((cant=inputStream.read(chunk))>0) {
byte[] cadenaTem = new byte[result.length];
//salvo lo que lei hasta ahora en cadena tem
System.arraycopy(result , 0, cadenaTem , 0,
result .length);
//declaro cadenaTotal con el tama�o que tenia + el que acabo de leer
result = new byte[cadenaTem.length +cant];
//le vuelvo a copiar lo que tenia
System.arraycopy(cadenaTem, 0, result , 0,
cadenaTem.length);
// ahora le copio lo nuevo que lei
System.arraycopy(chunk , 0, result , cadenaTem.length,
cant);
}
inputStream.close();
return result;
}
}
|
package com.tencent.mm.pluginsdk.ui.websearch;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class WebSearchVoiceInputLayoutImpl$2 implements OnTouchListener {
final /* synthetic */ WebSearchVoiceInputLayoutImpl qUF;
WebSearchVoiceInputLayoutImpl$2(WebSearchVoiceInputLayoutImpl webSearchVoiceInputLayoutImpl) {
this.qUF = webSearchVoiceInputLayoutImpl;
}
public final boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case 0:
WebSearchVoiceInputLayoutImpl.a(this.qUF, false);
WebSearchVoiceInputLayoutImpl.a(this.qUF, bi.VG());
x.d("MicroMsg.WebSearchVoiceInputLayoutImpl", "btn onTouch ACTION_DOWN currentState %s longClickStartTime %s", new Object[]{Integer.valueOf(WebSearchVoiceInputLayoutImpl.c(this.qUF)), Long.valueOf(WebSearchVoiceInputLayoutImpl.d(this.qUF))});
WebSearchVoiceInputLayoutImpl.b(this.qUF).cdv();
this.qUF.R(false, false);
break;
case 1:
x.d("MicroMsg.WebSearchVoiceInputLayoutImpl", "btn onTouch ACTION_UP currentState %s longClickDown %s", new Object[]{Integer.valueOf(WebSearchVoiceInputLayoutImpl.e(this.qUF)), Boolean.valueOf(WebSearchVoiceInputLayoutImpl.f(this.qUF))});
if (!WebSearchVoiceInputLayoutImpl.f(this.qUF)) {
this.qUF.R(false, true);
break;
}
this.qUF.R(true, false);
WebSearchVoiceInputLayoutImpl.a(this.qUF, false);
WebSearchVoiceInputLayoutImpl.a(this.qUF, 0);
break;
}
return false;
}
}
|
package algorithms;
import java.io.*;
import java.util.*;
//очередь с приоритетами
class PriorQueue<T extends Comparable> {
//на основе обычного ссылочного массива
ArrayList<T> arr = new ArrayList<T>();
//добавляем в конец = O(1)
public void add(T obj) {
arr.add(obj);
}// add
//извлекаем наименьший элемент = O(N)
public T get() {
if (arr.size() == 0)
return null;
//ищем наименьший элемент
T prior = arr.get(0);
for (int i = 1; i < arr.size(); i++) {
if (arr.get(i).compareTo(prior) < 0) {
prior = arr.get(i);
}
}
//найденный элемент удаляем
arr.remove(prior);
return prior;
}// add
public int size() {
return arr.size();
}
} // PriorQueue
public class Huffman {
//вершина дерева - вверху (наименьший путь) популярные записи, внизу редкие
Node root;
//таблицы соответствия = буква - битовая карта
// [буква] = бинарный код
String codeTable_in[] = new String[256];
// [бинарный код] = буква
HashMap<String, Character> codeTable_out = new HashMap<String, Character>();
public Huffman(Node r) {
this.root = r;
}
//ветвь дерева
static class Node implements Comparable<Node> {
//буква
public Character ch;
//частота символа
public Integer freq;
//ветви ниже
public Node left;
public Node right;
public Node(Character c, Integer f) {
this.ch = c;
this.freq = f;
} // Node
public Node(Node l, Node r) {
//частота родителя = сумме частоты детей
this.freq = l.freq + r.freq;
this.left = l;
this.right = r;
} // Node
@Override
public int compareTo(Node h) {
return this.freq - h.freq;
} // compareTo
public void dump(Huffman parrent) {
if (this.left != null)
this.left.dump(parrent);
if (this.ch != null) {
String pout = this.ch + " (" + this.freq + ")";
if (parrent != null) {
pout = pout + " = " + parrent.codeTable_in[(char) this.ch];
}
System.out.println(pout);
}
if (this.right != null)
this.right.dump(parrent);
} // dump
} // node
//частота символов в файле
public static int[] getFreqFromFile(String file) throws IOException {
int[] freq = new int[256];
BufferedReader br = new BufferedReader(
new FileReader(file));
try {
String line = br.readLine();
while (line != null) {
for (char c : line.toCharArray()) {
//если это необходимые символы
if (c > 0 && c < 256) {
//увеличиваем счетчик кол-ва символов
freq[c]++;
}
}
line = br.readLine();
}
} finally {
br.close();
}
return freq;
} // getFreqFromFile
//создаем таблицу соответствия буква - сжатая битовая карта
public void makeCodeTable() {
//прямая карта
makeCodeTableIn(this.root, "");
//обратая карта
for (int i = 0; i < this.codeTable_in.length; i++) {
codeTable_out.put(this.codeTable_in[(char) i], (char) i);
}
} // makeCodeTableIn
protected void makeCodeTableIn(Node n, String code) {
if (n == null)
return;
if (n.ch != null) {
this.codeTable_in[(char) n.ch] = code;
}
//при переходе ниже левее увеличиваем битовую карту на 0 справа
this.makeCodeTableIn(n.left, code + "0");
//при перехода направо ниже увеличиваем битовую карту на 1 справа
this.makeCodeTableIn(n.right, code + "1");
} // makeCodeTableIn
//сжатие текста
public String compress(String txt) {
String result = new String();
//проходимся по каждому символу текста
for (int i = 0; i < txt.length(); i++) {
//если символ есть в таблице преобразования
if (txt.charAt(i) < 256 && this.codeTable_in[txt.charAt(i)] != null) {
result = result + this.codeTable_in[txt.charAt(i)];
} else {
//если нет, то просто вставляем символ
result = result + txt.charAt(i);
}
}
return result;
} // compress
//разжатие текста
public String decompress(String txt) {
String result = new String();
String buf = "";
//обходим каждый бит
for (int i = 0; i < txt.length(); i++) {
//накапливаем буфер битов
buf = buf + txt.charAt(i);
//если буфер есть в таблице соответствия
if (codeTable_out.containsKey(buf)) {
//берем из таблицы и сбрасываем буфер
result = result + codeTable_out.get(buf);
buf = "";
} else if (txt.charAt(i) >= 256 || this.codeTable_in[txt.charAt(i)] == null) {
// нет в таблице преобразования - выдаем как есть
result = result + txt.charAt(i);
buf = "";
}
}
result = result + buf;
return result;
} // compress
public void dump() {
this.root.dump(this);
} // dump
public static void main(String[] args) throws IOException {
int[] freq = getFreqFromFile("C:\\Users\\007\\Google Диск\\info\\blog-02-17-2017.xml");
PriorQueue<Node> pq = new PriorQueue();
for (int i = 0; i < freq.length; i++) {
if (freq[i] > 0) {
pq.add(new Node((char) i, freq[i]));
}
}
while (pq.size() > 1) {
Node l = pq.get();
Node r = pq.get();
pq.add(new Node(l, r));
}
Huffman h = new Huffman(pq.get());
h.makeCodeTable();
String test_string = "abcdeя f`d";
String compr_string = h.compress(test_string);
String decompr_string = h.decompress(compr_string);
System.out.println(test_string);
System.out.println(compr_string);
System.out.println(decompr_string);
// h.dump();
} // main
} // Huffman |
package fr.lteconsulting;
public class Personne
{
private String nom;
private int secu;
public Personne( String nom, int secu )
{
this.nom = nom;
this.secu = secu;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((nom == null) ? 0 : nom.hashCode());
result = prime * result + secu;
return result;
}
@Override
public boolean equals( Object obj )
{
if( this == obj )
return true;
if( obj == null )
return false;
if( getClass() != obj.getClass() )
return false;
Personne other = (Personne) obj;
if( nom == null )
{
if( other.nom != null )
return false;
}
else if( !nom.equals( other.nom ) )
return false;
if( secu != other.secu )
return false;
return true;
}
@Override
public String toString()
{
return "Personne [secu=" + secu + ", nom=" + nom + "]";
}
}
|
package com.invitation.api.request;
import lombok.Getter;
import lombok.Setter;
@Setter @Getter
public class PersonRequest {
private String name;
private String lastName;
private String phone;
}
|
package com.yingying.distributed.hw2;
import java.util.stream.IntStream;
public class Producer {
public static IntStream getData(int start, int end) {
return IntStream.rangeClosed(start, end)
.flatMap(n -> IntStream.generate(() -> n)
.parallel().limit(Config.repeat));
}
}
|
package com.ehootu.user.service.impl;
import com.ehootu.core.feature.orm.mybatis.Page;
import com.ehootu.core.generic.GenericDao;
import com.ehootu.core.generic.GenericServiceImpl;
import com.ehootu.user.dao.PoliceMapper;
import com.ehootu.user.dao.UserMapper;
import com.ehootu.user.model.Police;
import com.ehootu.user.model.PoliceExample;
import com.ehootu.user.model.User;
import com.ehootu.user.model.UserExample;
import com.ehootu.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 用户Service实现类
*
*
* @since 2014年7月5日 上午11:54:24
*/
@Service
public class UserServiceImpl extends GenericServiceImpl<User, String> implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private PoliceMapper policeMapper;
@Override
public GenericDao<User, String> getDao() {
return userMapper;
}
@Override
public User authentication(User personInfo) {
return null;
}
/**
* 微信服务号用户登录
*/
@Override
public User login(User user) {
UserExample example = new UserExample();
UserExample.Criteria criteria = example.createCriteria();
// criteria.andPhoneNumberEqualTo(user.getPhoneNumber());
criteria.andPhoneNumberEqualTo(user.getPhoneNumber());
criteria.andPasswordEqualTo(user.getPassword());
List<User> list = userMapper.selectByExample(example);
if (list.size() > 0) {
return list.get(0);
}
return null;
}
@Override
public User selectByUsername(String username) {
return null;
}
@Override
public Page<User> selectByExampleAndPage(Page<User> page, UserExample example) {
return null;
}
/**
* 查询用户
*/
@Override
public List<User> findUser(User user) {
UserExample example = new UserExample();
// user.getUserName() 为注册的电话号码
example.createCriteria().andPhoneNumberEqualTo(user.getPhoneNumber());
List<User> list = userMapper.selectByExample(example);
return list;
}
@Override
public User selectByExample(UserExample example) {
return null;
}
@Override
public Police policeLogin(Police police) {
PoliceExample example = new PoliceExample();
PoliceExample.Criteria criteria = example.createCriteria();
// criteria.andPhoneNumberEqualTo(user.getPhoneNumber());
criteria.andPoliceNumberEqualTo(police.getPoliceNumber());
criteria.andPolicePasswordEqualTo(police.getPolicePassword());
List<Police> list = policeMapper.selectByExample(example);
if (list.size() > 0) {
return list.get(0);
}
return null;
}
@Override
public String findPoliceNameById(String ids) {
StringBuffer stringBuffer = new StringBuffer();
if (StringUtils.isBlank(ids)){return null;}
String[] strIds = ids.split(",");
if (null != strIds || strIds.length != 0){
for (String id : strIds) {
String policeName = policeMapper.findPoliceNameById(id);
if (StringUtils.isBlank(ids)){continue;}
stringBuffer.append(policeName).append(",");
}
}
return stringBuffer.toString();
}
@Override
public void savePolice(Police police) {
policeMapper.insertSelective(police);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.apache.clerezza.dataset.security;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.PushbackReader;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.Permission;
/**
* Provides a utility method to instantiate a permission given its string
* representation as returned by <code>java security.Permission.toString</code>.
*
* @author reto
*/
public class PermissionParser {
final static Logger logger = LoggerFactory.getLogger(PermissionParser.class);
/**
* Parsers permissionDescription and instantiates the permission using
* the ClassLoader of this class.
*
* @param permissionDescription
* @return Permission
*/
public static Permission getPermission(String permissionDescription) {
return getPermission(permissionDescription, PermissionParser.class.getClassLoader());
}
/**
* Parsers permissionDescription and instantiates the permission using
* classLoader.
*
* @param permissionDescription
* @param classLoader
* @return Permission
*/
public static Permission getPermission(String permissionDescription, ClassLoader classLoader) {
PermissionInfo permissionInfo = parse(permissionDescription);
try {
Class clazz = classLoader.loadClass(permissionInfo.className);
Constructor<?> constructor = clazz.getConstructor(
String.class, String.class);
return (Permission) constructor.newInstance(
permissionInfo.name, permissionInfo.actions);
} catch (InstantiationException ie) {
logger.warn("{}", ie);
throw new RuntimeException(ie);
} catch (ClassNotFoundException cnfe) {
logger.warn("{}", cnfe);
throw new RuntimeException(cnfe);
} catch (NoSuchMethodException nsme) {
logger.warn("{}", nsme);
throw new RuntimeException(nsme);
} catch (InvocationTargetException ite) {
logger.warn("{}", ite);
throw new RuntimeException(ite);
} catch (IllegalAccessException iae) {
logger.warn("{}", iae);
throw new RuntimeException(iae);
}
}
private static PermissionInfo parse(String permissionDescription) {
StringReader reader = new StringReader(permissionDescription);
try {
return parse(reader);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private static PermissionInfo parse(StringReader reader) throws IOException {
PermissionInfo result = new PermissionInfo();
for (int ch = reader.read(); ch != -1; ch = reader.read()) {
if (ch == ' ') {
continue;
}
if (ch =='(') {
parseFromClassName(reader, result);
break;
} else {
throw new IllegalArgumentException("Permission description does not start with '('");
}
}
for (int ch = reader.read(); ch != -1; ch = reader.read()) {
if (ch != ' ') {
throw new IllegalArgumentException("Unparsable characters after closing ')'");
}
}
return result;
}
private static void parseFromClassName(StringReader StringReader, PermissionInfo result) throws IOException {
PushbackReader reader = new PushbackReader(StringReader, 1);
result.className = readSection(reader);
result.name = readSection(reader);
result.actions = readSection(reader);
byte closingBracketsCount = 0;
for (int ch = reader.read(); ch != -1; ch = reader.read()) {
if (ch == ' ') {
continue;
}
if (ch == ')') {
closingBracketsCount++;
if (closingBracketsCount > 1) {
throw new IllegalArgumentException("more than 1 closing bracket");
}
continue;
}
else {
throw new IllegalArgumentException("illegal character at this position: "+ch);
}
}
}
private static String readSection(PushbackReader reader) throws IOException {
for (int ch = reader.read(); ch != -1; ch = reader.read()) {
if (ch == ' ') {
continue;
} else {
reader.unread(ch);
return readSectionWithNoHeadingSpace(reader);
}
}
return null;
}
private static String readSectionWithNoHeadingSpace(PushbackReader reader) throws IOException {
StringBuilder sectionWriter = new StringBuilder();
for (int ch = reader.read(); ch != -1; ch = reader.read()) {
if (ch == '"') {
if (sectionWriter.length() > 0) {
throw new IllegalArgumentException("Quote at wrong position, characters before quote: "+sectionWriter.toString());
}
sectionWriter = null;
return readTillQuote(reader);
}
if (ch == ' ') {
return sectionWriter.toString();
}
if (ch == ')') {
reader.unread(ch);
return sectionWriter.toString();
}
sectionWriter.append((char)ch);
}
throw new IllegalArgumentException("missing closing bracket (')')");
}
private static String readTillQuote(PushbackReader reader) throws IOException {
StringBuilder sectionWriter = new StringBuilder();
for (int ch = reader.read(); ch != -1; ch = reader.read()) {
if (ch == '"') {
return sectionWriter.toString();
}
sectionWriter.append((char)ch);
}
throw new IllegalArgumentException("missing closing quote ('=')");
}
private static class PermissionInfo {
String className, name, actions;
}
}
|
package com.Collections_HashSet;
public class HashSetToTreeSet {
}
|
package com.tencent.mm.plugin.sns.model;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.q;
import com.tencent.mm.modelsfs.FileOp;
import com.tencent.mm.plugin.sns.g.d;
import com.tencent.mm.plugin.sns.g.e;
import com.tencent.mm.plugin.sns.g.f;
import com.tencent.mm.protocal.c.boh;
import com.tencent.mm.protocal.c.boi;
import com.tencent.mm.protocal.c.bon;
import com.tencent.mm.protocal.c.boy;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Vector;
public final class ad {
String cXR = "";
private d npq;
private List<Integer> npr = new Vector();
private Map<String, Integer> nps = new HashMap();
private List<Integer> npt = new Vector();
private Map<Integer, Integer> npu = new HashMap();
private String path;
public static boolean Mg(String str) {
if (str != null && str.startsWith("_AD_TAG_")) {
return true;
}
return false;
}
public ad(String str) {
this.path = str;
if (!bxR()) {
this.npq = new d();
}
this.npr.clear();
this.nps.clear();
}
public final synchronized void bxP() {
if (!af(this.npq.nuS)) {
if (!af(this.npq.nuT) && !af(this.npq.nuU) && !af(this.npq.nuV)) {
f fVar;
long j;
while (!this.npq.nuW.isEmpty()) {
fVar = (f) this.npq.nuW.getFirst();
if (bi.bG((long) fVar.nuZ) <= 21600) {
j = fVar.nvb;
g.Ek();
g.Eh().dpP.a(new r(j, 1), 0);
break;
}
this.npq.nuW.removeFirst();
}
while (!this.npq.nuX.isEmpty()) {
fVar = (f) this.npq.nuX.getFirst();
if (bi.bG((long) fVar.nuZ) <= 21600) {
j = fVar.nvb;
g.Ek();
g.Eh().dpP.a(new r(j, 5), 0);
break;
}
this.npq.nuX.removeFirst();
}
}
}
}
private static boolean af(LinkedList<e> linkedList) {
while (!linkedList.isEmpty()) {
e eVar = (e) linkedList.getFirst();
if (bi.bG((long) eVar.nuZ) > 21600) {
linkedList.removeFirst();
} else {
if (Mg(eVar.nuY)) {
g.Ek();
g.Eh().dpP.a(new k(eVar.nnO, eVar.nuY, eVar.nva), 0);
} else {
g.Ek();
g.Eh().dpP.a(new o(eVar.nnO, eVar.nuY), 0);
}
return true;
}
}
return false;
}
public final synchronized boolean eR(long j) {
boolean z;
Iterator it = this.npq.nuW.iterator();
while (it.hasNext()) {
if (((f) it.next()).nvb == j) {
z = false;
break;
}
}
z = true;
return z;
}
public final synchronized void eS(long j) {
f fVar = new f();
fVar.nvb = j;
fVar.nuZ = (int) bi.VE();
this.npq.nuW.add(fVar);
bxQ();
}
final synchronized void eT(long j) {
Object obj;
Iterator it = this.npq.nuW.iterator();
while (it.hasNext()) {
obj = (f) it.next();
if (obj.nvb == j) {
break;
}
}
obj = null;
if (obj != null) {
this.npq.nuW.remove(obj);
}
bxQ();
}
private static boolean a(LinkedList<bon> linkedList, String str, int i) {
if (bi.oW(str)) {
return true;
}
Iterator it = linkedList.iterator();
while (it.hasNext()) {
bon bon = (bon) it.next();
if (str.equals(bon.jSA) && i == bon.lOH) {
return true;
}
}
return false;
}
public final synchronized boy c(boy boy) {
if (bi.oW(this.cXR)) {
this.cXR = q.GF();
}
if (!(this.npq.nuS.size() == 0 && this.npq.nuT.size() == 0)) {
e eVar;
bon bon;
long j = boy.rlK;
Iterator it = this.npq.nuS.iterator();
while (it.hasNext()) {
eVar = (e) it.next();
bon a = a(eVar.nnO);
if (eVar.nnO.rlK == j && !a(boy.smL, a.jSA, a.lOH)) {
boy.smL.add(a);
boy.smJ++;
}
}
Iterator it2 = boy.smL.iterator();
while (it2.hasNext()) {
bon = (bon) it2.next();
if (bon.rdS.equals(this.cXR)) {
Object obj = null;
Iterator it3 = this.npq.nuX.iterator();
while (it3.hasNext()) {
Object obj2;
if (((f) it3.next()).nvb == j) {
boy.smL.remove(bon);
boy.smJ--;
obj2 = 1;
} else {
obj2 = obj;
}
obj = obj2;
}
if (obj != null) {
break;
}
}
}
it = this.npq.nuT.iterator();
while (it.hasNext()) {
eVar = (e) it.next();
if (eVar.nnO.rlK == j) {
bon = a(eVar.nnO);
if (!a(boy.smO, bon.jSA, bon.lOH)) {
boy.smO.add(bon);
boy.smM++;
}
}
}
}
return boy;
}
public static bon a(boi boi) {
boh boh = boi.smo;
boh boh2 = boi.smp;
bon bon = new bon();
bon.jSA = boh.jSA;
bon.lOH = boh.lOH;
bon.rTW = boh.sme;
bon.rdq = boh.rdq;
bon.hcE = boh.hcE;
bon.rdS = boh.seC;
bon.smh = boh.smh;
bon.smk = boh.smk;
bon.smm = boh.smm;
bon.smB = boh2.seC;
bon.smj = boh2.smj;
bon.smg = boh2.smg;
return bon;
}
public final boolean a(String str, boi boi) {
return a(str, boi, "");
}
public final synchronized boolean a(String str, boi boi, String str2) {
boolean z = true;
synchronized (this) {
e eVar = new e();
eVar.nuY = str;
eVar.nnO = boi;
eVar.nuZ = (int) bi.VE();
eVar.nva = str2;
switch (boi.smo.hcE) {
case 1:
this.npq.nuS.add(eVar);
if (eV(boi.rlK)) {
z = false;
break;
}
break;
case 2:
this.npq.nuT.add(eVar);
break;
case 3:
this.npq.nuU.add(eVar);
break;
case 5:
this.npq.nuV.add(eVar);
break;
case 7:
this.npq.nuS.add(eVar);
if (eV(boi.rlK)) {
z = false;
break;
}
break;
case 8:
this.npq.nuT.add(eVar);
break;
}
if (!bxQ()) {
x.e("MicroMsg.SnsAsyncQueueMgr", "error listToFile");
}
}
return z;
}
public final void d(long j, int i, String str) {
aj.byG();
e(j, i, str);
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private synchronized void e(long r2, int r4, java.lang.String r5) {
/*
r1 = this;
monitor-enter(r1);
switch(r4) {
case 1: goto L_0x0009;
case 2: goto L_0x0014;
case 3: goto L_0x002c;
case 4: goto L_0x0004;
case 5: goto L_0x0034;
case 6: goto L_0x0004;
case 7: goto L_0x001c;
case 8: goto L_0x0024;
default: goto L_0x0004;
};
L_0x0004:
r1.bxQ(); Catch:{ all -> 0x0011 }
monitor-exit(r1);
return;
L_0x0009:
r0 = r1.npq; Catch:{ all -> 0x0011 }
r0 = r0.nuS; Catch:{ all -> 0x0011 }
a(r2, r0, r5); Catch:{ all -> 0x0011 }
goto L_0x0004;
L_0x0011:
r0 = move-exception;
monitor-exit(r1);
throw r0;
L_0x0014:
r0 = r1.npq; Catch:{ all -> 0x0011 }
r0 = r0.nuT; Catch:{ all -> 0x0011 }
a(r2, r0, r5); Catch:{ all -> 0x0011 }
goto L_0x0004;
L_0x001c:
r0 = r1.npq; Catch:{ all -> 0x0011 }
r0 = r0.nuS; Catch:{ all -> 0x0011 }
a(r2, r0, r5); Catch:{ all -> 0x0011 }
goto L_0x0004;
L_0x0024:
r0 = r1.npq; Catch:{ all -> 0x0011 }
r0 = r0.nuT; Catch:{ all -> 0x0011 }
a(r2, r0, r5); Catch:{ all -> 0x0011 }
goto L_0x0004;
L_0x002c:
r0 = r1.npq; Catch:{ all -> 0x0011 }
r0 = r0.nuU; Catch:{ all -> 0x0011 }
a(r2, r0, r5); Catch:{ all -> 0x0011 }
goto L_0x0004;
L_0x0034:
r0 = r1.npq; Catch:{ all -> 0x0011 }
r0 = r0.nuV; Catch:{ all -> 0x0011 }
a(r2, r0, r5); Catch:{ all -> 0x0011 }
goto L_0x0004;
*/
throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.plugin.sns.model.ad.e(long, int, java.lang.String):void");
}
private static void a(long j, LinkedList<e> linkedList, String str) {
a(j, linkedList, str, false);
}
private static boolean a(long j, LinkedList<e> linkedList, String str, boolean z) {
Object obj;
Iterator it = linkedList.iterator();
while (it.hasNext()) {
obj = (e) it.next();
if (obj.nnO.rlK == j && (z || obj.nuY.equals(str))) {
break;
}
}
obj = null;
if (obj == null) {
return false;
}
linkedList.remove(obj);
return true;
}
public final synchronized boolean eU(long j) {
boolean z = true;
synchronized (this) {
f fVar = new f();
fVar.nvb = j;
fVar.nuZ = (int) bi.VE();
this.npq.nuX.add(fVar);
bxQ();
if (a(j, this.npq.nuS, "", true)) {
z = false;
}
}
return z;
}
final synchronized boolean eV(long j) {
boolean z;
Object obj;
Iterator it = this.npq.nuX.iterator();
while (it.hasNext()) {
obj = (f) it.next();
if (obj.nvb == j) {
break;
}
}
obj = null;
if (obj != null) {
this.npq.nuX.remove(obj);
z = true;
} else {
z = false;
}
bxQ();
return z;
}
private synchronized boolean bxQ() {
boolean z = false;
synchronized (this) {
try {
byte[] toByteArray = this.npq.toByteArray();
if (FileOp.b(this.path, toByteArray, toByteArray.length) == 0) {
z = true;
}
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.SnsAsyncQueueMgr", e, "listToFile failed: " + this.path, new Object[0]);
FileOp.deleteFile(this.path);
}
}
return z;
}
private synchronized boolean bxR() {
boolean z;
byte[] e = FileOp.e(this.path, 0, -1);
if (e == null) {
z = false;
} else {
try {
this.npq = (d) new d().aG(e);
z = true;
} catch (Throwable e2) {
x.printErrStackTrace("MicroMsg.SnsAsyncQueueMgr", e2, "", new Object[0]);
FileOp.deleteFile(this.path);
z = false;
}
}
return z;
}
public final synchronized boolean wq(int i) {
return this.npr.contains(Integer.valueOf(i));
}
public final synchronized boolean wr(int i) {
boolean z;
if (this.npr.contains(Integer.valueOf(i))) {
z = false;
} else {
this.npr.add(Integer.valueOf(i));
z = true;
}
return z;
}
public final synchronized boolean ws(int i) {
this.npr.remove(Integer.valueOf(i));
return true;
}
public final synchronized boolean isDownloading(String str) {
return this.nps.containsKey(str);
}
public final synchronized boolean Mh(String str) {
boolean z = false;
synchronized (this) {
if (!this.nps.containsKey(str)) {
this.nps.put(str, Integer.valueOf(0));
z = true;
}
}
return z;
}
public final synchronized boolean Mi(String str) {
this.nps.remove(str);
return true;
}
public final synchronized int bxS() {
return this.nps.size();
}
public final synchronized boolean wt(int i) {
boolean z;
if (this.npt.contains(Integer.valueOf(i))) {
z = false;
} else {
this.npt.add(Integer.valueOf(i));
z = true;
}
return z;
}
public final synchronized boolean wu(int i) {
this.npt.remove(Integer.valueOf(i));
this.npu.remove(Integer.valueOf(i));
return true;
}
public final synchronized boolean du(int i, int i2) {
this.npu.put(Integer.valueOf(i), Integer.valueOf(i2));
return true;
}
public final synchronized boolean wv(int i) {
this.npu.remove(Integer.valueOf(i));
return true;
}
public final synchronized int ww(int i) {
int intValue;
if (this.npu.containsKey(Integer.valueOf(i))) {
intValue = ((Integer) this.npu.get(Integer.valueOf(i))).intValue();
} else {
intValue = -1;
}
return intValue;
}
}
|
package com.redbean;
import org.neo4j.ogm.session.SessionFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableNeo4jRepositories(basePackages = "com.redbean.repository")
@EnableTransactionManagement
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
package prService;
import java.util.ArrayList;
import pr.pojos.Dog;
import pr.pojos.Owner;
import pr.pojos.Pairing;
import pr.pojos.Runner;
public class Database {
public static int dogId = 0;
public static int pairingId = 0;
public ArrayList <Owner> owners = new ArrayList<>();
public ArrayList <Runner> runners = new ArrayList<>();
public ArrayList <Pairing> pairings = new ArrayList<>();
public ArrayList <Dog> dogs = new ArrayList<>();
public Database() {
}
public void addOwner(Owner owner) {
owners.add(owner);
}
public void addRunner(Runner runner) {
runners.add(runner);
}
public void addPairing(Pairing pairing) {
pairings.add(pairing);
pairing.setPairingId(pairingId);
pairingId++;
}
public void addDog(Dog dog) {
dogs.add(dog);
dog.setDogId(dogId);
dogId++;
}
public Dog getDog(int index) {
return dogs.get(index);
}
public Owner getOwner(int index) {
return owners.get(index);
}
public Runner getRunner(int index) {
return runners.get(index);
}
public Pairing getPairing(int index) {
return pairings.get(index);
}
public void clearDatabase() {
pairings.clear();
runners.clear();
owners.clear();
}
}
|
package com.mcf.base.common.enums;
/**
* Title. <br>
* Description.
* <p>
* Copyright: Copyright (c) 2016年12月17日 下午2:24:18
* <p>
* Author: 10003/sunaiqiang saq691@126.com
* <p>
* Version: 1.0
* <p>
*/
public enum CooperateType {
COMPANY(0, "企业"), UNITY(1, "个体");
private final Integer index;
private final String value;
private CooperateType(Integer index, String value) {
this.index = index;
this.value = value;
}
public Integer getIndex() {
return index;
}
public Byte getOrdinal() {
return index.byteValue();
}
public String getValue() {
return value;
}
@Override
public String toString() {
return value;
}
}
|
/*
* created 29.08.2005 by sell
*
* $Id: DDLGeneratorExtension.java 678 2008-02-17 22:52:09Z cse $
*/
package com.byterefinery.rmbench.extension;
import org.eclipse.jface.wizard.IWizardPage;
import com.byterefinery.rmbench.external.IDDLFormatter;
import com.byterefinery.rmbench.external.IDDLGenerator;
import com.byterefinery.rmbench.external.IDDLGeneratorWizardFactory;
import com.byterefinery.rmbench.external.IDDLScript;
import com.byterefinery.rmbench.external.IDatabaseInfo;
/**
* representation of a DDLGenerator extension
*
* @author sell
*/
public class DDLGeneratorExtension extends NamedExtension {
private final IDDLGenerator.Factory generatorFactory;
private final IDDLGeneratorWizardFactory wizardCreator;
private final IDDLFormatter.Factory formatterFactory;
private final IDDLScript.Factory scriptFactory;
private final DatabaseExtension[] supportedDatabases;
private final DatabaseExtension nativeDatabase;
public DDLGeneratorExtension(
String namespace,
String id,
String name,
IDDLGenerator.Factory generatorFactory,
IDDLGeneratorWizardFactory wizardCreator,
IDDLFormatter.Factory formatterFactory,
IDDLScript.Factory scriptFactory,
DatabaseExtension nativeDatabase,
DatabaseExtension[] supportedDatabases) {
super(namespace, id, name);
this.generatorFactory = generatorFactory;
this.wizardCreator = wizardCreator;
this.formatterFactory = formatterFactory;
this.scriptFactory = scriptFactory;
this.supportedDatabases = supportedDatabases;
this.nativeDatabase = nativeDatabase;
}
public IDDLGenerator getDDLGenerator(IDatabaseInfo database) {
return generatorFactory.getGenerator(database);
}
/**
* @return a new wizard page, or <code>null</code> if a wizard page creator was
* not specified by this extension
*/
public IWizardPage createGeneratorWizardPage(IDDLGenerator generator) {
return wizardCreator != null ? wizardCreator.getWizardPage(generator) : null;
}
public IDDLFormatter createFormatter(IDDLGenerator generator) {
return formatterFactory.createFormatter(generator);
}
public IDDLScript createScript(IDDLGenerator generator) {
return scriptFactory.createScript(generator);
}
public DatabaseExtension[] getDatabaseExtensions() {
return supportedDatabases;
}
/**
* @param id a database extension id
* @return true if the given database is in the list of supported databases
*/
public boolean supportsDatabase(String id) {
for (int i = 0; i < supportedDatabases.length; i++) {
if(supportedDatabases[i].getId().equals(id))
return true;
}
return false;
}
/**
* @param id a database extension id
* @return true if the given database is the native database for this generator
*/
public boolean belongsToDatabase(String id) {
return nativeDatabase != null && nativeDatabase.getId().equals(id);
}
}
|
package com.espendwise.manta.util.trace;
import com.espendwise.manta.util.arguments.TypedArgument;
public class ApplicationIllegalAccessException extends ApplicationRuntimeException {
public ApplicationIllegalAccessException(ExceptionReason.SystemReason excReason, TypedArgument... args) {
super(new ApplicationExceptionCode<ExceptionReason.SystemReason>(excReason, args));
}
}
|
package application;
import static database.DB.bandlessMusicians;
import static database.DB.bands;
import band.Band;
import band.Musician;
import java.util.Collections;
import java.util.Locale;
import java.util.Scanner;
public class Commands {
private static Musician removedMember;
private Commands() {
}
private static void play() {
for (Band band : bands) {
removeMemberFromBand(band);
addNewMemberToBand(band);
addRemovedMemberToBandlessGroup();
}
}
private static void removeMemberFromBand(Band band) {
if (band.getMembers().size() <= 0) {
return;
}
removedMember = band.getRandomMember();
band.removeMember(removedMember);
Printer.printLeaving(removedMember, band);
}
private static void addNewMemberToBand(Band band) {
Collections.shuffle(bandlessMusicians);
for (Musician musician : bandlessMusicians) {
if (band.hasMembersWithSameInstrument(musician)) {
continue;
}
band.addMember(musician);
bandlessMusicians.remove(musician);
Printer.printJoining(musician, band);
break;
}
}
private static void addRemovedMemberToBandlessGroup() {
if (removedMember != null) {
bandlessMusicians.add(removedMember);
}
removedMember = null;
}
private static void list() {
printBandsDetails();
printBandlessDetails();
}
private static void printBandsDetails() {
for (Band band : bands) {
Printer.printBandDetails(band);
}
}
private static void printBandlessDetails() {
if (bandlessMusicians.size() > 0) {
Printer.printBandlessMusiciansDetails(bandlessMusicians);
}
}
private static void exit() {
System.exit(1);
}
public static void executeCommand() {
Scanner scanner = new Scanner(System.in);
String commandString = "";
do {
Printer.printStartingMessage();
System.out.print("$ ");
commandString = scanner.nextLine();
switch (CommandType.getTypeFromString(commandString.toUpperCase())) {
case PLAY-> play();
case LIST-> list();
case WRONG-> Printer.printWrongCommand();
}
}
while (!commandString.toLowerCase().equals("exit"));
}
}
|
package com.variado.pegue.textitlater;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by pegue on 7/14/2016.
*/
public class FragmentTextTab extends Fragment {
View rootView;
Locale locale;
Calendar calendar;
int day, month, year, notifyValue = 1, datePickerIdentifier = 1;
Switch switchNotify;
TextView textviewDate, textviewTime;
EditText edittextPhoneNumber, edittextMessage;
Button buttonSaveMessage;
String currentDate, dayOfWeek, currentTime;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_text_tab, container, false);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
Date date = new Date(year, month, day - 1);
Date time = new Date(calendar.getTime().toString());
locale = Resources.getSystem().getConfiguration().locale;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE", locale);
SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("hh:mm aa", locale);
dayOfWeek = simpleDateFormat.format(date);
currentDate = dayOfWeek + " " +
calendar.get(Calendar.DAY_OF_MONTH) + "/" +
calendar.get(Calendar.MONTH) +
"/" + calendar.get(Calendar.YEAR);
currentTime = simpleTimeFormat.format(time);
textviewDate = (TextView) rootView.findViewById(R.id.textview_new_message_date_send);
textviewTime = (TextView) rootView.findViewById(R.id.textview_new_message_time_send);
switchNotify = (Switch) rootView.findViewById(R.id.switch_notification);
edittextPhoneNumber = (EditText) rootView.findViewById(R.id.edittext_phone_number);
edittextMessage = (EditText) rootView.findViewById(R.id.edittext_message_body);
buttonSaveMessage = (Button) rootView.findViewById(R.id.button_save);
textviewDate.setText(currentDate);
textviewTime.setText(currentTime);
switchNotify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
notifyValue = 1;
else
notifyValue = 0;
}
});
buttonSaveMessage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (edittextPhoneNumber.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), R.string.toast_phone_number_empty, Toast.LENGTH_SHORT).show();
} else if (edittextMessage.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), R.string.toast_message_empty, Toast.LENGTH_SHORT).show();
} else {
DatabaseHandler databaseHandler = new DatabaseHandler(getActivity());
databaseHandler.addMessage(new TextMessage(
edittextPhoneNumber.getText().toString(),
edittextMessage.getText().toString(),
notifyValue,
currentDate,
textviewDate.getText().toString(),
textviewTime.getText().toString()));
edittextPhoneNumber.setText("");
edittextMessage.setText("");
Toast.makeText(getActivity(), R.string.toast_message_saved, Toast.LENGTH_SHORT).show();
}
}
});
textviewDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePickerFragment = new DatePickerFragment();
Bundle bundle = new Bundle();
bundle.putInt("identifier", datePickerIdentifier);
datePickerFragment.setArguments(bundle);
datePickerFragment.show(getFragmentManager(), "datePicker");
}
});
textviewTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment timePickerFragment = new TimePickerFragment();
Bundle bundle = new Bundle();
bundle.putInt("identifier", datePickerIdentifier);
timePickerFragment.setArguments(bundle);
timePickerFragment.show(getFragmentManager(), "timePicker");
}
});
return rootView;
}
}
|
package com.example.springboothibernate.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.example.springboothibernate.models.Course;
import com.example.springboothibernate.models.Student;
import com.example.springboothibernate.repositories.StudentCourseRepository;
import lombok.extern.log4j.Log4j2;
@Service
@Log4j2
public class StudentCourseService {
@Autowired
private StudentCourseRepository studentCourseRepository;
//Describes a transaction attribute on an individual method or on a class.
//At the class level, this annotation applies as a default to all methods ofthe declaring class and its subclasses.
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
public void processData() {
Course courseA = new Course("Course A");
List<Student> list1 = new ArrayList<Student>();
list1.add(new Student("Ravi", courseA));
list1.add(new Student("Gopi", courseA));
list1.add(new Student("Kamesh", courseA));
list1.add(new Student("Ravi", courseA));
Course courseB = new Course("Course B");
List<Student> list2 = new ArrayList<Student>();
list1.add(new Student("Roja", courseB));
list1.add(new Student("Sasi", courseB));
list1.add(new Student("Keerthi", courseB));
list1.add(new Student("Roja", courseB));
list1.add(new Student("Sasi", courseB));
courseA.setStudents(list1);
courseB.setStudents(list2);
studentCourseRepository.save(courseA);
studentCourseRepository.save(courseB);
//studentCourseRepository.findAll().forEach(data -> log.info(data));
}
//Annotation indicating that the result of invoking a method (or all methodsin a class) can be cached.
@Cacheable(value = "studentCourseCache")
public List<Course> findAll(){
return studentCourseRepository.findAll();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.