text stringlengths 10 2.72M |
|---|
import java.util.*;
public class Hangover
{
public static void main(String [] args)
{
double[] m = new double[277];
m[0] = .5;
int k =1;
while(m[k-1] <5.2)
m[k++] = m[k-1] +(1.0/(k+2));
double c;
Scanner sc = new Scanner(System.in);
c=Double.parseDouble(sc.next());
while(c>0)
{
if(c==0.00)
break;
int i = 0;
while(c>m[i++]);
System.out.println(i+" card(s)\n");
c=Double.parseDouble(sc.next());
}
}
} |
/**
*/
package iotwearable.model.iotw;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>CDS</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link iotwearable.model.iotw.CDS#getPinGND <em>Pin GND</em>}</li>
* <li>{@link iotwearable.model.iotw.CDS#getPinVcc <em>Pin Vcc</em>}</li>
* <li>{@link iotwearable.model.iotw.CDS#getPinD0 <em>Pin D0</em>}</li>
* </ul>
*
* @see iotwearable.model.iotw.IotwPackage#getCDS()
* @model
* @generated
*/
public interface CDS extends InputDevice {
/**
* Returns the value of the '<em><b>Pin GND</b></em>' attribute.
* The default value is <code>"GND,IO"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Pin GND</em>' attribute.
* @see #setPinGND(Pin)
* @see iotwearable.model.iotw.IotwPackage#getCDS_PinGND()
* @model default="GND,IO" dataType="iotwearable.model.iotw.Pin"
* @generated
*/
Pin getPinGND();
/**
* Sets the value of the '{@link iotwearable.model.iotw.CDS#getPinGND <em>Pin GND</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Pin GND</em>' attribute.
* @see #getPinGND()
* @generated
*/
void setPinGND(Pin value);
/**
* Returns the value of the '<em><b>Pin Vcc</b></em>' attribute.
* The default value is <code>"Vcc,IO"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Pin Vcc</em>' attribute.
* @see #setPinVcc(Pin)
* @see iotwearable.model.iotw.IotwPackage#getCDS_PinVcc()
* @model default="Vcc,IO" dataType="iotwearable.model.iotw.Pin"
* @generated
*/
Pin getPinVcc();
/**
* Sets the value of the '{@link iotwearable.model.iotw.CDS#getPinVcc <em>Pin Vcc</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Pin Vcc</em>' attribute.
* @see #getPinVcc()
* @generated
*/
void setPinVcc(Pin value);
/**
* Returns the value of the '<em><b>Pin D0</b></em>' attribute.
* The default value is <code>"D0,IO"</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Pin D0</em>' attribute.
* @see #setPinD0(Pin)
* @see iotwearable.model.iotw.IotwPackage#getCDS_PinD0()
* @model default="D0,IO" dataType="iotwearable.model.iotw.Pin"
* @generated
*/
Pin getPinD0();
/**
* Sets the value of the '{@link iotwearable.model.iotw.CDS#getPinD0 <em>Pin D0</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Pin D0</em>' attribute.
* @see #getPinD0()
* @generated
*/
void setPinD0(Pin value);
} // CDS
|
package people;
import rooms.Room;
import java.util.Scanner;
public class Person
{
private String firstName;
private String[] inventory;
private int scaredMeter;
private String costume;
public int[] location = new int[2];
public Person(String firstName, int[] location)
{
this.firstName = firstName;
this.location = location;
}
public String getFirstName()
{
return firstName;
}
public int[] getLocation()
{
return location;
}
public void setRoom (Room room) {
this.location[0] = room.getX();
this.location[1] = room.getY();
//System.out.println("");
}
public String print() {
return "x";
}
public void printRoom()
{
System.out.println("");
System.out.println("");
System.out.println("[ ]");
System.out.println("[ ]");
System.out.println("This is the current room you're in.");
}
public String chooseMove()
{
Scanner in = new Scanner(System.in);
String statement = "";
statement = in.nextLine();
return statement;
}
/*
public String[] setRoom(Person p)
{
return this.location = p.location;
}
*/
}
|
package javaprg04;
import java.util.Scanner;
public class Power1 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int b,p;
System.out.println("Enter base no:");
b=s.nextInt();
System.out.println("Enter power of the no:");
p=s.nextInt();
s.close();
long r = 1;
for (;p!=0;p--)
{
r =r* b;
}
System.out.println("Answer = " + r);
}
}
|
package de.scads.gradoop_service.server.helper.clustering;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.operators.MapOperator;
import org.codehaus.jettison.json.JSONObject;
import org.gradoop.common.model.impl.pojo.Edge;
import org.gradoop.famer.clustering.clustering;
import org.gradoop.famer.clustering.parallelClusteringGraph2Graph.Center;
import org.gradoop.famer.clustering.parallelClusteringGraph2Graph.ConnectedComponents;
import org.gradoop.famer.clustering.parallelClusteringGraph2Graph.CorrelationClustering;
import org.gradoop.famer.clustering.parallelClusteringGraph2Graph.MergeCenter;
import org.gradoop.famer.clustering.parallelClusteringGraph2Graph.Star;
import org.gradoop.flink.model.api.epgm.LogicalGraph;
/**
* Contains method(s) to be used for clustering a logical graph
*/
public class ClusteringHelper {
/**
* Performs clustering of a logical graph
*
* @param inputGraph - graph to be clustered
* @param clusteringConfig - clustering configuration
* @return returns clustered graph
*/
public static LogicalGraph runClustering(LogicalGraph inputGraph, String clusteringConfig) throws Exception {
LogicalGraph clusteredGraph = null;
JSONObject clusteringConfigObject = new JSONObject(clusteringConfig);
String clusteringMethod = clusteringConfigObject.getString("clusteringMethod");
String edgeAttribute = clusteringConfigObject.getString("edgeAttribute");
// we preserve existing value if no edge attribute was input by user
if(!edgeAttribute.equals("")) {
inputGraph = performPreprocessing(inputGraph, edgeAttribute);
}
boolean isEdgeBidirection = false;
clustering.ClusteringOutputType clusteringOutputType = clustering.ClusteringOutputType.GraphCollection;
switch (clusteringMethod) {
case "CONCON":
clusteredGraph = inputGraph.callForGraph(new ConnectedComponents());
break;
case "CORRELATION_CLUSTERING":
clusteredGraph = inputGraph.callForGraph(new CorrelationClustering(isEdgeBidirection, clusteringOutputType));
break;
case "CENTER":
clusteredGraph = inputGraph.callForGraph(new Center(1, isEdgeBidirection, clusteringOutputType));
break;
case "MERGE_CENTER":
clusteredGraph = inputGraph.callForGraph(new MergeCenter(1, 0.0, isEdgeBidirection, clusteringOutputType));
break;
case "STAR1":
clusteredGraph = inputGraph.callForGraph(new Star(1, 1, isEdgeBidirection, clusteringOutputType));
break;
case "STAR2":
clusteredGraph = inputGraph.callForGraph(new Star(1, 2, isEdgeBidirection, clusteringOutputType));
break;
}
return clusteredGraph;
}
/**
* Performs input graph preprocessing: renames edge attribute containing similarities, that was chosen for clustering, into "value"-
* This is required in famer-clustering
*
* @param inputGraph - name of the input graph
* @param edgeAttribute - name of the currently existing attribute
* @return preprocessed input graph
*/
private static LogicalGraph performPreprocessing(LogicalGraph inputGraph, String edgeAttribute) {
@SuppressWarnings("serial")
MapOperator<Edge, Edge> graphEdgesTmp = inputGraph.getEdges().map(new MapFunction<Edge, Edge>() {
@Override
public Edge map(Edge input) throws Exception {
input.setProperty("value", input.getPropertyValue(edgeAttribute).getDouble());
input.removeProperty("similarity");
return input;
}
});
return inputGraph.getConfig().getLogicalGraphFactory().fromDataSets(inputGraph.getVertices(), graphEdgesTmp);
}
} |
package com.trump.auction.account.api.impl;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.cf.common.utils.ServiceResult;
import com.google.common.collect.Lists;
import com.trump.auction.account.api.AccountInfoStubService;
import com.trump.auction.account.constant.RedisConstant;
import com.trump.auction.account.dto.AccountDto;
import com.trump.auction.account.dto.PointsExchangePresentDto;
import com.trump.auction.account.service.AccountInfoService;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.JedisCluster;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* Created by wangyichao on 2017-12-19 下午 06:33.
*/
@Slf4j
@Service(version = "1.0.0")
public class AccountInfoStubServiceImpl implements AccountInfoStubService {
private AccountInfoService accountInfoService;
private JedisCluster jedisCluster;
AccountInfoStubServiceImpl(AccountInfoService accountInfoService, JedisCluster jedisCluster) {
this.accountInfoService = accountInfoService;
this.jedisCluster = jedisCluster;
}
@Override
public AccountDto getAccountInfo(Integer userId) {
return accountInfoService.getAccountInfo(userId);
}
@Override
public int getAuctionCoinByUserId(Integer userId, Integer type) {
return accountInfoService.getAuctionCoinByUserId(userId, type);
}
/**
* 创建充值订单
*/
@Override
public ServiceResult createAccountRechargeOrder(Integer userId, String userName, String userPhone, BigDecimal money, Integer transactionType, String outTradeNo) {
return accountInfoService.createAccountRechargeOrder(userId, userName, userPhone, money, transactionType, outTradeNo);
}
@Override
public ServiceResult rechargeUserAccount(boolean success, String outTradeNo, String resultJson) {
try {
return accountInfoService.rechargeUserAccount(success, outTradeNo, resultJson);
} catch (Exception e) {
log.error("充值拍币失败:{}", e);
return new ServiceResult(ServiceResult.FAILED, e.getMessage());
}
}
@Override
public List<PointsExchangePresentDto> getPointsExchangeList() {
List<PointsExchangePresentDto> list = Lists.newArrayList();
Map<String, String> map = jedisCluster.hgetAll(RedisConstant.EXCHANGE_POINTS);
for (String key : map.keySet()) {
String value = map.get(key);
JSONObject json = JSONObject.parseObject(value);
int presentCoin = json.getInteger("presentCoin");
int points = json.getInteger("points");
String type = json.getString("type");
String title = "¥" + presentCoin + type;
PointsExchangePresentDto p = new PointsExchangePresentDto(presentCoin, points * 100, title, type);
list.add(p);
}
return list;
}
/**
* 获取每天积分兑换赠币次数限制
*/
@Override
public String getPointsExchangeTimesLimit() {
Map<String, String> map = jedisCluster.hgetAll(RedisConstant.EXCHANGE_POINTS_EXCHANGE_LIMIT);
if(null == map) {
return "一";
}
String str = map.get(RedisConstant.EXCHANGE_POINTS_EXCHANGE_LIMIT);
if(StringUtils.isEmpty(str)) {
return "一";
}
return str.split(",")[0];
}
@Override
public ServiceResult exchangePoints(Integer userId, Integer presentCoin) {
try {
return accountInfoService.exchangePoints(userId, presentCoin);
} catch (Exception e) {
log.error("兑换失败:{}", e);
return new ServiceResult(ServiceResult.FAILED, "兑换失败");
}
}
@Override
public ServiceResult signGainPoints(Integer userId, String userPhone, Integer transactionCoin) {
try {
return accountInfoService.signGainPoints(userId, userPhone, transactionCoin);
} catch (Exception e) {
log.error("操作失败:{}", e);
return new ServiceResult(ServiceResult.FAILED, "操作失败");
}
}
@Override
public ServiceResult initUserAccount(Integer userId, String userPhone, String userName, Integer accountType) {
return accountInfoService.initUserAccount(userId, userPhone, userName, accountType);
}
/**
* 使用赠币或者拍币支付
*/
@Override
public ServiceResult paymentWithCoin(Integer userId, String userPhone, String productName, Integer coin, String orderId, String orderSerial, String productImage) {
try {
return accountInfoService.paymentWithCoin(userId, userPhone, productName, coin, orderId, orderSerial, productImage);
} catch (Exception e) {
log.error("paymentWithCoin 使用赠币或者拍币支付:{} \n {}", e.getMessage(), e);
return new ServiceResult(ServiceResult.FAILED, "出价失败");
}
}
/**
* 差价购买,扣除开心币操作
*/
@Override
public ServiceResult reduceBuyCoin(Integer userId, String userPhone, BigDecimal transactionCoin, String orderNo, Integer type) {
try {
return accountInfoService.reduceBuyCoin(userId, userPhone, transactionCoin, orderNo, type);
} catch (Exception e) {
log.error("扣除开心币失败:{}", e);
return new ServiceResult(ServiceResult.FAILED, "扣除开心币失败");
}
}
/**
* 返币操作
*/
@Override
public ServiceResult backCoinOperation(String orderNo, Integer transactionCoin, Integer accountType, Integer productId, String productName, String productImage, Integer coinType, String userPhone, Integer userId) {
try {
return accountInfoService.backCoinOperation(orderNo, transactionCoin, accountType, productId, productName, productImage, coinType, userPhone, userId);
} catch (Exception e){
log.error("返币失败:orderNo:{}<br>{}", orderNo, e);
return new ServiceResult(ServiceResult.FAILED, "操作失败");
}
}
@Override
public ServiceResult returnBuyCoin() {
try {
return accountInfoService.returnBuyCoin();
} catch (Exception e) {
log.error("首充返币操作失败:{}",e);
return new ServiceResult(ServiceResult.FAILED, "操作失败");
}
}
/**
* 拍卖-大转盘积分消耗
*/
@Override
public ServiceResult lotteryCostPoints(Integer userId, Integer transactionPoints) {
try {
return accountInfoService.lotteryCostPoints(userId, transactionPoints);
} catch (Exception e){
log.error("大转盘积分扣除失败:{}", e);
return new ServiceResult(ServiceResult.FAILED, "大转盘积分扣除失败");
}
}
/**
* 大转盘中奖-操作账户
*/
@Override
public ServiceResult lotteryPrizeUserAccount(Integer userId, Integer accountType, Integer transactionAmount, Integer productId, String productName, String productImage, Integer coinType, String userPhone) {
try {
return accountInfoService.lotteryPrizeUserAccount(userId, accountType, transactionAmount, productId, productName, productImage, coinType, userPhone);
} catch (Exception e) {
log.error("大转盘积分抽奖-写入奖品时出错:{}", e);
return new ServiceResult(ServiceResult.FAILED, "大转盘积分抽奖,写入奖品时出错");
}
}
@Override
public ServiceResult backCoinByShareAuctionOrder(Integer userId, Integer coinNum, Integer accountType) {
try {
return accountInfoService.backCoinByShareAuctionOrder(userId, coinNum, accountType);
} catch(Exception e) {
log.error("晒单返币失败:{}", e);
return new ServiceResult(ServiceResult.FAILED, "晒单返币失败");
}
}
@Override
public ServiceResult backShareCoin(Integer userId, Integer coinNum, Integer accountType) {
try {
return accountInfoService.backShareCoin(userId, coinNum, accountType);
} catch(Exception e) {
log.error("分享返币失败:{}", e);
return new ServiceResult(ServiceResult.FAILED, "分享返币失败");
}
}
}
|
package mx.redts.adendas.managebean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIOutput;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import mx.redts.adendas.dto.UsuarioDTO;
import mx.redts.adendas.model.Role;
import mx.redts.adendas.model.User;
import mx.redts.adendas.service.IUserService;
import mx.redts.adendas.util.Common;
import org.primefaces.event.CellEditEvent;
import org.primefaces.event.RowEditEvent;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
/**
*
* User Managed Bean
*
* @author Andres Cabrera
* @since 25 Mar 2012
* @version 1.0.0
*
*/
@ManagedBean(name = "userMB")
@ViewScoped
public class UserManagedBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final String SUCCESS = Messages
.getString("UserManagedBean.0"); //$NON-NLS-1$
private static final String ERROR = Messages.getString("UserManagedBean.1"); //$NON-NLS-1$
// Spring User Service is injected...
@ManagedProperty(value = "#{UserService}")
IUserService userService;
List<UsuarioDTO> userList;
private int id;
private String name;
private String surname;
private String mname;
private String username;
private String rol;
// private UsuarioDTO userSel;
// private UsuarioDTO userSelected;
private Integer editHabilitado;
private Integer editBloqueado;
private String password1;
private String password2;
/**
* Add User
*
* @return String - Response Message
*/
public String addUser() {
if (Messages.getString("UserManagedBean.2").equals(getRol()) || getRol() == null) { //$NON-NLS-1$
FacesMessage message = new FacesMessage(
FacesMessage.SEVERITY_ERROR,
Messages.getString("UserManagedBean.3"), null); //$NON-NLS-1$
FacesContext.getCurrentInstance().addMessage(null, message);
return ERROR;
} else {
User u = getUserService().loadUserByUsername(getUsername());
System.out.println(Messages.getString("UserManagedBean.4") + u); //$NON-NLS-1$
if (u == null) {
try {
User user = new User();
// user.setId(getId());
user.setNombre(getName());
user.setApellidoPaterno(getSurname());
user.setApellidoMaterno(getMname());
user.setAccountNonExpired(false);
user.setAccountNonLocked(false);
user.setCredentialsNonExpired(false);
user.setEnabled(true);
user.setUsername(getUsername());
user.setPassword(Common.md5Crypt(getUsername()));
// List<Role> rol = new ArrayList<Role>();
// // Role or = new Role();
// // or.setRoleId(getRol());
//
// System.out.println("#############> ROL : " + getRol());
// rol.add(getRol());
// user.setAuthorities(rol);
// rol.
getUserService().addUser(user);
Role rol = new Role();
rol.setUsername(user.getUsername());
rol.setAuthority(getRol());
getUserService().addRole(rol);
FacesMessage message = new FacesMessage(
FacesMessage.SEVERITY_INFO,
Messages.getString("UserManagedBean.5"), null); //$NON-NLS-1$
FacesContext.getCurrentInstance().addMessage(null, message);
setName(Messages.getString("UserManagedBean.6")); //$NON-NLS-1$
setSurname(Messages.getString("UserManagedBean.7")); //$NON-NLS-1$
setMname(Messages.getString("UserManagedBean.8")); //$NON-NLS-1$
setUsername(Messages.getString("UserManagedBean.9")); //$NON-NLS-1$
setRol(Messages.getString("UserManagedBean.10")); //$NON-NLS-1$
return SUCCESS;
} catch (DataAccessException e) {
e.printStackTrace();
}
} else {
FacesMessage message = new FacesMessage(
FacesMessage.SEVERITY_ERROR,
Messages.getString("UserManagedBean.11"), null); //$NON-NLS-1$
FacesContext.getCurrentInstance().addMessage(null, message);
return ERROR;
}
}
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN,
Messages.getString("UserManagedBean.12"), null); //$NON-NLS-1$
FacesContext.getCurrentInstance().addMessage(null, message);
return ERROR;
}
public String altausuarioview() {
return Messages.getString("UserManagedBean.13"); //$NON-NLS-1$
}
public void cambiaPassword() {
FacesMessage msg = null;
if (!this.getPassword1().equals(this.getPassword2())) {
msg = new FacesMessage(
FacesMessage.SEVERITY_ERROR,
Messages.getString("UserManagedBean.14"), Messages.getString("UserManagedBean.15")); //$NON-NLS-1$ //$NON-NLS-2$
} else {
userService.updadePassword(this.getUserlogged(),
this.getPassword1());
msg = new FacesMessage(
Messages.getString("UserManagedBean.16"), Messages.getString("UserManagedBean.17")); //$NON-NLS-1$ //$NON-NLS-2$
}
FacesContext.getCurrentInstance().addMessage(null, msg);
}
// public boolean getLocked(){
// return (userSelected != null?userSelected.isBloqueado():null);
// }
public Integer getEnabled() {
return editHabilitado;
}
/**
* Get User Id
*
* @return int - User Id
*/
public int getId() {
return id;
}
public Integer getLocked() {
return editBloqueado;
}
public String getMname() {
return mname;
}
/**
* Get User Name
*
* @return String - User Name
*/
public String getName() {
return name;
}
public List<Boolean> getOptions() {
List<Boolean> x = new ArrayList<Boolean>();
x.add(true);
x.add(false);
return x;
}
public String getPassword1() {
return password1;
}
public String getPassword2() {
return password2;
}
public String getRol() {
return rol;
}
public String getRolelogged() {
String rol = Messages.getString("UserManagedBean.18"); //$NON-NLS-1$
for (GrantedAuthority ga : SecurityContextHolder.getContext()
.getAuthentication().getAuthorities()) {
rol = ga.getAuthority();
}
return rol;
}
public List<Role> getRoles() {
return userService.getRoles();
}
/**
* Get User Surname
*
* @return String - User Surname
*/
public String getSurname() {
return surname;
}
/**
* Get User List
*
* @return List - User List
*/
public List<UsuarioDTO> getUserList() {
userList = new ArrayList<UsuarioDTO>();
userList.addAll(getUserService().getUsers());
return userList;
}
public String getUserlogged() {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
public String getUsername() {
return username;
}
/**
* Get User Service
*
* @return IUserService - User Service
*/
public IUserService getUserService() {
return userService;
}
public List<UsuarioDTO> getUsuarios() {
return userService.getUsers();
}
public void onLockChange(AjaxBehaviorEvent event) {
System.out
.println(Messages.getString("UserManagedBean.19") + ((UIOutput) event.getSource()).getValue()); //$NON-NLS-1$
}
// public void selUsrBlocked() {
//
// userSel.setBloqueado(!userSel.isBloqueado());
// userService.updateUser(userSel);
// FacesContext.getCurrentInstance().addMessage(
// null,
// new FacesMessage(
// "Usuario "
// + (userSel.isBloqueado() ? "Bloqueado"
// : "Desbloqueado")));
// }
// public void selUsrEnabled() {
// // String summary = value2 ? "Checked" : "Unchecked";
// userSel.setHabilitado(!userSel.isHabilitado());
// userService.updateUser(userSel);
//
// FacesContext.getCurrentInstance().addMessage(
// null,
// new FacesMessage("Usuario "
// + (userSel.isHabilitado() ? "Habilidado"
// : "Deshabilitado")));
// }
// public void setSelectedUser(UsuarioDTO usrsel) {
// System.out.println("###########################> Usuaro Seleccionado ;"
// + usrsel);
// userSel = usrsel;
// }
// public void onRowEdit(UsuarioDTO event) {
// System.out.println("###########################> EDITANDO USUARIO");
// userSel = event;
// //userService.updateUser(userSel);
//
// FacesMessage msg = new FacesMessage("Editando Usuario : ",
// userSel.getUsuario());
// FacesContext.getCurrentInstance().addMessage(null, msg);
// }
//
// // public void onCompleteRowEdit(RowEditEvent event) {
// // System.out.println("###########################> EDITANDO USUARIO");
// // userSel = ((UsuarioDTO) event.getObject());
// // FacesMessage msg = new FacesMessage("User Edited",
// userSel.getUsuario());
// // FacesContext.getCurrentInstance().addMessage(null, msg);
// // }
//
// public void onRowCancel(RowEditEvent event) {
// System.out.println("###########################> CANCELANDO EDICION");
// userSel = ((UsuarioDTO) event.getObject());
// FacesMessage msg = new FacesMessage("Edit Cancelled",
// userSel.getUsuario());
// FacesContext.getCurrentInstance().addMessage(null, msg);
// }
//
//
public void onRowCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage(
Messages.getString("UserManagedBean.20") + ((UsuarioDTO) event.getObject()).getUsuario() + Messages.getString("UserManagedBean.21"), Messages.getString("UserManagedBean.22")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onRowEdit(CellEditEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
UsuarioDTO entity = context.getApplication().evaluateExpressionGet(
context,
Messages.getString("UserManagedBean.23"), UsuarioDTO.class); //$NON-NLS-1$
if (editBloqueado != null && editBloqueado == 1)
entity.setBloqueado(true);
if (editBloqueado != null && editBloqueado == 2)
entity.setBloqueado(false);
if (editHabilitado != null && editHabilitado == 1)
entity.setHabilitado(true);
if (editHabilitado != null && editHabilitado == 2)
entity.setHabilitado(false);
userService.updateUser(entity);
FacesMessage msg = new FacesMessage(
Messages.getString("UserManagedBean.24") + entity.getUsuario() + Messages.getString("UserManagedBean.25"), Messages.getString("UserManagedBean.26")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
FacesContext.getCurrentInstance().addMessage(null, msg);
editBloqueado = null;
editHabilitado = null;
}
// public void onCellEdit(CellEditEvent event) {
// Object oldValue = event.getOldValue();
// Object newValue = event.getNewValue();
//
// if (newValue != null && !newValue.equals(oldValue)) {
// FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO,
// "Cell Changed", "Old: " + oldValue + ", New:" + newValue);
// FacesContext.getCurrentInstance().addMessage(null, msg);
// }
// }
// public void rowEditorForItem(UsuarioDTO item) {
// System.out.print("$$$$$$$$ > Usuario ; " + item.getNombre());
// userSelected = item;
// }
// public void setEnabled(boolean value){
// userSelected.setHabilitado(value);
// }
// public void setLocked(boolean value){
// userSelected.setBloqueado(value);
// }
/**
* Reset Fields
*
*/
public void reset() {
this.setId(0);
this.setName(Messages.getString("UserManagedBean.27")); //$NON-NLS-1$
this.setSurname(Messages.getString("UserManagedBean.28")); //$NON-NLS-1$
}
public void setEnabled(Integer x) {
editHabilitado = x;
System.out.println(Messages.getString("UserManagedBean.29") + x); //$NON-NLS-1$
}
/**
* Set User Id
*
* @param int - User Id
*/
public void setId(int id) {
this.id = id;
}
public void setLocked(Integer x) {
editBloqueado = x;
System.out.println(Messages.getString("UserManagedBean.30") + x); //$NON-NLS-1$
}
public void setMname(String mname) {
this.mname = mname;
}
/**
* Set User Name
*
* @param String
* - User Name
*/
public void setName(String name) {
this.name = name;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public void setRol(String rol) {
this.rol = rol;
}
/**
* Set User Surname
*
* @param String
* - User Surname
*/
public void setSurname(String surname) {
this.surname = surname;
}
/**
* Set User List
*
* @param List
* - User List
*/
public void setUserList(List<UsuarioDTO> userList) {
this.userList = userList;
}
public void setUsername(String username) {
this.username = username;
}
/**
* Set User Service
*
* @param IUserService
* - User Service
*/
public void setUserService(IUserService userService) {
this.userService = userService;
}
} |
package com.miyatu.tianshixiaobai.entity;
public class LimitedTimeSpikeEntity {
private int photo;
private String serviceName;
private int currentPrice;
private int originalPrice;
private int soldNumber;
private String time;
private String state;
private int isSelected; //是否被选中,0被选中,1未被选中
public int getIsSelected() {
return isSelected;
}
public void setIsSelected(int isSelected) {
this.isSelected = isSelected;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getPhoto() {
return photo;
}
public void setPhoto(int photo) {
this.photo = photo;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public int getCurrentPrice() {
return currentPrice;
}
public void setCurrentPrice(int currentPrice) {
this.currentPrice = currentPrice;
}
public int getOriginalPrice() {
return originalPrice;
}
public void setOriginalPrice(int originalPrice) {
this.originalPrice = originalPrice;
}
public int getSoldNumber() {
return soldNumber;
}
public void setSoldNumber(int soldNumber) {
this.soldNumber = soldNumber;
}
}
|
package com.revature.superhuman;
import java.sql.SQLException;
import java.util.List;
import com.revature.dao.SuperhumanDAO;
import com.revature.dao.SuperhumanDAOPostgres;
import com.revature.pojo.Superhuman;
public class SuperhumanService {
private static SuperhumanDAO superDAO;
public SuperhumanService() throws SQLException {
super();
superDAO = new SuperhumanDAOPostgres();
}
public void setSuperDAO(SuperhumanDAO superDAO) {
this.superDAO = superDAO;
}
public List<Superhuman> getSuperhumans() throws SQLException {
List<Superhuman> supers = null;
try {
supers = superDAO.getSuperhumans("superhuman_id");
} catch (SQLException e) {
throw e;
}
return supers;
}
public List<Superhuman> getSuperhumans(String sortBy) throws SQLException {
List<Superhuman> supers = null;
try {
supers = superDAO.getSuperhumans(sanitizeSortBy(sortBy));
} catch (SQLException e) {
throw e;
}
return supers;
}
public void addSuperhuman(Superhuman superhuman) throws SQLException {
try {
superDAO.addSuperhuman(superhuman);
} catch (SQLException e) {
throw e;
}
}
public void updateSuperhuman(Superhuman superhuman) throws SQLException {
try {
superDAO.updateSuperhuman(superhuman);
} catch (SQLException e) {
throw e;
}
}
public void deleteSuperhuman(Integer id) throws SQLException {
try {
superDAO.removeSuperhuman(id);
} catch (SQLException e) {
throw e;
}
}
public String sanitizeSortBy(String sortBy) {
if (sortBy == null) {
return "superhuman_id";
} else if (sortBy.equals("superhuman_name") || sortBy.equals("alien") || sortBy.equals("alignment_id")) {
return sortBy;
} else {
return "superhuman_id";
}
}
}
|
package com.gaoshin.amazon;
import java.util.Calendar;
import java.util.TimeZone;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import common.util.reflection.ReflectionUtil;
@Entity
@Table(name = "aws_item")
public class ItemEntity {
@Id
@Column(length = 31)
private String asin;
@Column(length = 255)
private String title;
@Column
private boolean loaded = false;
@Column(name = "LAST_UPDATE")
@Temporal(TemporalType.TIMESTAMP)
private Calendar lastUpdate = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
public ItemEntity() {
}
public ItemEntity(Object bean) {
copyFrom(bean);
}
public void copyFrom(Object bean) {
ReflectionUtil.copyPrimeProperties(this, bean);
}
public AwsItem getBean() {
try {
AwsItem bean = new AwsItem();
ReflectionUtil.copyPrimeProperties(bean, this);
return bean;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void setAsin(String asin) {
this.asin = asin;
}
public String getAsin() {
return asin;
}
public void setLoaded(boolean loaded) {
this.loaded = loaded;
}
public boolean isLoaded() {
return loaded;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setLastUpdate(Calendar lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Calendar getLastUpdate() {
return lastUpdate;
}
}
|
package com.leyton.flow.gateway;
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
@MessagingGateway(
name = "microserviceOneGateway")
public interface MicroserviceOneGateway {
@Gateway(
requestChannel = "httpRequestChannel")
void request(String message);
}
|
package com.sirma.itt.javacourse.collections.task4.LRUcache;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import org.apache.log4j.Logger;
/**
* LRU implementation class.
*
* @param <K>
* the key value for the objects.
* @param <V>
* the Object type value that is to be stored in the cache.
* @author simeon
*/
public class LRUTailCache<K, V> {
private final Logger log = Logger.getLogger(LRUTailCache.class);
private final Map<K, V> cache;
private final Queue<K> queue;
private final int maxElementts;
/**
* Constructor for LRUTailCache class.
*
* @param maxElementts
* the maximum number of elements allowed in the cache
*/
public LRUTailCache(int maxElementts) {
this.maxElementts = maxElementts;
cache = new HashMap<K, V>(maxElementts);
queue = new LinkedList<K>();
}
/**
* Adds an element to the cache. First we check if the element is in the cache if it it is we
* hit it, otherwise we check the size of the cache if its full or not, if the cache is not full
* we directly input the element in it. When the cache is full we use the queue to get the last
* visited element and replace it with the new element and also we place the new element in the
* queue.
*
* @param key
* the key for the object that is to placed in the map.
* @param value
* the value of the object.
* @return true if the object was added to the cache, false otherwise.
*/
public boolean addElement(K key, V value) {
if (cache.containsKey(key)) {
hitElement(key);
log.info("Hit");
return false;
} else if (maxElementts > cache.size()) {
insertElement(key, value);
log.info("Miss");
return true;
} else {
removeElementByKey(queue.peek());
insertElement(key, value);
log.info("Miss");
return true;
}
}
/**
* Inserts element in the cache and the queue.
*
* @param key
* the key to the object;
* @param value
* the value of the object;
*/
private void insertElement(K key, V value) {
cache.put(key, value);
queue.add(key);
}
/**
* Retrieves an element of the cache by specific key if there is no object to be found it
* returns null.
*
* @param key
* the key of the object.
* @return the object which is associated with the key, if there is no object with the specific
* key or @return null.
*/
public V getElement(K key) {
if (cache.containsKey(key)) {
hitElement(key);
}
return cache.get(key);
}
/**
* Removes an element from the cache by its key, if there is no key that matches returns false.
*
* @param key
* the key to the object we want to remove.
* @return true if the object was removed otherwise returns false.
*/
public boolean removeElementByKey(K key) {
if (cache.containsKey(key)) {
cache.remove(key);
queue.remove(key);
return true;
}
return false;
}
/**
* Hits the queue that an object was used.
*
* @param key
* the key of the object.
*/
private void hitElement(K key) {
queue.remove(key);
queue.add(key);
}
/**
* Returns a collection of all the elements in the cache.
*
* @return a collection of all the elements in the cache.
*/
public Collection<V> getAllElements() {
return cache.values();
}
}
|
package com.example.apprunner;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.apprunner.User.menu5_uplode_stat.Activity.UplodeStatistics;
import java.util.List;
public class RegEventAdapterUser extends RecyclerView.Adapter<RegEventAdapterUser.Holder> {
List<ResultQuery> eventList;
Context context;
public RegEventAdapterUser (Context context,List<ResultQuery> eventList) {
this.context = context;
this.eventList = eventList;
}
@NonNull
@Override
public RegEventAdapterUser.Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recyclerview__user,parent,false);
return new RegEventAdapterUser.Holder(view);
}
@Override
public void onBindViewHolder(@NonNull RegEventAdapterUser.Holder holder, int position) {
final Intent intent = ((Activity) context).getIntent();
final String type = intent.getExtras().getString("type");
final String first_name = intent.getExtras().getString("first_name");
final String last_name = intent.getExtras().getString("last_name");
final int id_user = intent.getExtras().getInt("id_user");
final ResultQuery event = eventList.get(position);
holder.FName1.setText(event.getFirst_name());
holder.card_view1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, UplodeStatistics.class);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return eventList.size();
}
public class Holder extends RecyclerView.ViewHolder {
TextView FName1;
CardView card_view1;
public Holder(@NonNull View itemView) {
super(itemView);
FName1 = (TextView)itemView.findViewById(R.id.FName1);
card_view1 = itemView.findViewById(R.id.card_view1);
}
}
}
|
package com.zzping.fix.mapper;
import java.util.List;
import com.zzping.fix.entity.FixCampus;
import com.zzping.fix.entity.FixCampusCriteria;
import com.zzping.fix.model.FixCampusModel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestParam;
@Mapper
public interface FixCampusMapper {
long countByExample(FixCampusCriteria example);
int deleteByExample(FixCampusCriteria example);
int deleteByPrimaryKey(String campusId);
int insert(FixCampus record);
int insertSelective(FixCampus record);
List<FixCampus> selectByExample(FixCampusCriteria example);
FixCampus selectByPrimaryKey(String campusId);
int updateByExampleSelective(@Param("record") FixCampus record, @Param("example") FixCampusCriteria example);
int updateByExample(@Param("record") FixCampus record, @Param("example") FixCampusCriteria example);
int updateByPrimaryKeySelective(FixCampus record);
int updateByPrimaryKey(FixCampus record);
List<FixCampusModel> searchByCampusPlace(@Param("searchKey") String searchKey);
List<FixCampusModel> searchCampusPlaceByCampus(@Param("campus") String campus);
} |
package kr.co.people_gram.app;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class YouType_Complate_Activity extends AppCompatActivity {
private String people_uid, people_email, people_username, data1, data2, data3, data4, data5, data6, data7, data8, data9, data10, gubun1, gubun2;
private String speed, control;
private String youtype;
private ImageView mytype_activity_typeImg;
private TextView mytype_tv;
private ImageView people_popup_btn1;
private ProgressDialog dialog;
private PeopleData pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_you_type__complate_);
mytype_activity_typeImg = (ImageView) findViewById(R.id.mytype_activity_typeImg);
mytype_tv = (TextView) findViewById(R.id.mytype_tv);
people_popup_btn1 = (ImageView) findViewById(R.id.people_popup_btn1);
PeopleData pd = new PeopleData();
Intent intent = getIntent();
if(intent != null) {
people_uid = intent.getStringExtra("people_uid");
people_email = intent.getStringExtra("people_email");
people_username = intent.getStringExtra("people_username");
data1 = intent.getStringExtra("data1");
data2 = intent.getStringExtra("data2");
data3 = intent.getStringExtra("data3");
data4 = intent.getStringExtra("data4");
data5 = intent.getStringExtra("data5");
data6 = intent.getStringExtra("data6");
data7 = intent.getStringExtra("data7");
data8 = intent.getStringExtra("data8");
data9 = intent.getStringExtra("data9");
data10 = intent.getStringExtra("data10");
gubun1 = intent.getStringExtra("gubun1");
gubun2 = intent.getStringExtra("gubun2");
float speed = Float.parseFloat(intent.getStringExtra("speed"));
float control = Float.parseFloat(intent.getStringExtra("control"));
youtype = intent.getStringExtra("youtype");
pd.set_people_uid(people_uid);
pd.set_people_username(people_username);
pd.set_people_type(youtype);
pd.set_people_gubun1(gubun1);
pd.set_people_gubun2(gubun2);
pd.set_people_speed((int) speed);
pd.set_people_control((int) control);
/*
if(people_email.equals("미가입")) {
people_popup_btn1.setImageResource(R.drawable.people_popup_btn1_style);
} else {
people_popup_btn1.setImageResource(R.drawable.people_popup_btn1_reretype_style);
}
*/
if(speed > 0 && control > 0) {
if(speed <= 5 && control <= 1){
if(speed <= 1 && control <= 1){
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>" + people_username + "</font>님의 진단 결과<br><b>꼼꼼하기도 하면서 때론 완벽을 추구하는 <b color='#ff8a55'>강한 추진력과 모험심 있는 스타일</b>로 진단되었습니다."));
}else{
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b>사람과의 관계와 소통을 중요시하며 <b color='#ff8a55'>때론 추진력과 도전을 좋아하는 스타일</b></b><br>로 진단되었습니다."));
}
}else if(speed <= 1 && control <= 5){
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b>꼼꼼하면서 <b color='#ff8a55'>밀어부치기도 도전을 좋아하기도 하는 스타일</b></b><br>로 진단되었습니다."));
}else{
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b color='#ff8a55'>새로운 도전과 모험, 강한 추진력을 가진 스타일</b>로 진단되었습니다."));
}
}
if(speed > 0 && control < 0) {
if(speed <= 5 && control >= -1){
if(speed <= 1 && control >= -1){
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b>가끔 밀어부치기도 하고 그러나 상대방을 배려하는 이해심도 가진<b color='#aa64f8'>소통의 달인</b></b><br>으로 진단되었습니다."));
}else{
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b>사람을 끄는 힘을 가진<b color='#aa64f8'>관계 형성이 좋은 스타일</b></b><br>로 진단되었습니다."));
}
}else if(speed <= 1 && control >= -5){
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b>상대에 대한 이해심이 높고 믿을 수 있는 <b color='#aa64f8'>소통하고 싶은 스타일</b></b><br>로 진단되었습니다."));
}else{
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b color='#aa64f8'>인간관계가 중요하고 큰 문제가 없으며 상대의 마음을 진심으로 대하는 스타일</b>로 진단되었습니다."));
}
}
if(speed < 0 && control > 0) {
if(speed >= -5 && control <= 1){
if(speed >= -1 && control <= 1){
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b>도전정신을 가진 이해심 깊은<b color='#37afec'>완벽주의자</b></b><br>로 진단되었습니다."));
}else{
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b>속 깊이 잘 챙기는<b color='#37afec'>꼼꼼주의자</b></b><br>로 진단되었습니다."));
}
}else if(speed >= -1 && control <= 5){
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b>새로운 것을 마다하지 않고 끝까지 완벽하게 꼼꼼히 이루는 스타일<br>로 진단되었습니다."));
}else{
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b color='#37afec'>꼼꼼한 완벽주의자</b>로 진단되었습니다."));
}
}
if(speed < 0 && control < 0) {
if(speed >= -5 && control >= -1){
if(speed >= -1 && control >= -1){
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b>사람과의 관계에서 이해심이 높지만 그래도 나름 계산하여 마음을 보이는 스타일</b><br>로 진단되었습니다."));
}else{
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b>꼼꼼히 상대를 알아보고 끝까지 믿어주는 스타일</b><br>로 진단되었습니다."));
}
}else if(speed >= -1 && control >= -5){
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b>상대를 이해하며 좋은 인간관계를 끝까지 유지하는 스타일</b><br>로 진단되었습니다."));
}else{
mytype_tv.setText(Html.fromHtml("<font color='#ccc'>"+people_username+"</font>님의 진단 결과<br><b color='#52d935'>상대방에 대한 배려심 좋고 신뢰성 있는 스타일</b>로 진단되었습니다."));
}
}
switch (youtype)
{
case "I":
mytype_activity_typeImg.setImageResource(R.drawable.mytype_i);
break;
case "D":
mytype_activity_typeImg.setImageResource(R.drawable.mytype_d);
break;
case "E":
mytype_activity_typeImg.setImageResource(R.drawable.mytype_e);
break;
case "A":
mytype_activity_typeImg.setImageResource(R.drawable.mytype_a);
break;
}
}
}
public void peopleView_btn(View v) {
Log.d("people_gram", "타입=" + youtype.toString());
Intent intent = new Intent(YouType_Complate_Activity.this, SubPeopleListSelect_Activity.class);
intent.putExtra("people_uid", people_uid);
intent.putExtra("people_username", people_username);
//intent.putExtra("people_mood", people_mood);
//intent.putExtra("people_type", people_type);
//finish();
startActivity(intent);
overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
}
public void mytype_re_btn(View v)
{
Intent intent = new Intent(YouType_Complate_Activity.this, YouType_Actvity_step1.class);
intent.putExtra("people_uid", people_uid);
intent.putExtra("people_email", people_email);
intent.putExtra("people_username", people_username);
startActivity(intent);
overridePendingTransition(R.anim.end_enter, R.anim.end_exit);
closeView();
}
public void mytype_view_btn(View v)
{
//mytype_view_btn
Intent intent = new Intent(YouType_Complate_Activity.this, YouType_Activity.class);
intent.putExtra("youtype", youtype);
startActivity(intent);
overridePendingTransition(R.anim.slide_up_info, R.anim.slide_down_info);
}
/*public void sendBtn(View v) {
if(people_email.equals("미가입")) {
Intent intent = new Intent(YouType_Complate_Activity.this, KakaoLoginActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
} else {
RequestParams params = new RequestParams();
params.put("uid", SharedPreferenceUtil.getSharedPreference(YouType_Complate_Activity.this, "uid"));
params.put("people_uid", people_uid);
params.put("people_username", SharedPreferenceUtil.getSharedPreference(YouType_Complate_Activity.this, "username"));
HttpClient.post("/user/peoplePushSend", params, new AsyncHttpResponseHandler() {
public void onStart() {
//Log.d("people_gram", "시작");
dialog = ProgressDialog.show(YouType_Complate_Activity.this, "", "데이터 수신중");
}
public void onFinish() {
dialog.dismiss();
}
@Override
public void onSuccess(String response) {
//Log.d("people_gram", response);
}
});
}
}*/
public void start_btn(View v) {
finish();
}
public void closeView()
{
super.finish();
}
public void prevBtn(View v) {
finish();
}
public void closeBtn(View v) {
finish();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
finish();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
public void finish()
{
super.finish();
overridePendingTransition(R.anim.slide_close_down_info, R.anim.slide_clode_up_info);
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables.records;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record4;
import org.jooq.Row4;
import org.jooq.impl.UpdatableRecordImpl;
import schema.tables.StudentPendingnamechange;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class StudentPendingnamechangeRecord extends UpdatableRecordImpl<StudentPendingnamechangeRecord> implements Record4<Integer, String, String, Integer> {
private static final long serialVersionUID = -1642589273;
/**
* Setter for <code>bitnami_edx.student_pendingnamechange.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>bitnami_edx.student_pendingnamechange.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>bitnami_edx.student_pendingnamechange.new_name</code>.
*/
public void setNewName(String value) {
set(1, value);
}
/**
* Getter for <code>bitnami_edx.student_pendingnamechange.new_name</code>.
*/
public String getNewName() {
return (String) get(1);
}
/**
* Setter for <code>bitnami_edx.student_pendingnamechange.rationale</code>.
*/
public void setRationale(String value) {
set(2, value);
}
/**
* Getter for <code>bitnami_edx.student_pendingnamechange.rationale</code>.
*/
public String getRationale() {
return (String) get(2);
}
/**
* Setter for <code>bitnami_edx.student_pendingnamechange.user_id</code>.
*/
public void setUserId(Integer value) {
set(3, value);
}
/**
* Getter for <code>bitnami_edx.student_pendingnamechange.user_id</code>.
*/
public Integer getUserId() {
return (Integer) get(3);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record4 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row4<Integer, String, String, Integer> valuesRow() {
return (Row4) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return StudentPendingnamechange.STUDENT_PENDINGNAMECHANGE.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field2() {
return StudentPendingnamechange.STUDENT_PENDINGNAMECHANGE.NEW_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field3() {
return StudentPendingnamechange.STUDENT_PENDINGNAMECHANGE.RATIONALE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field4() {
return StudentPendingnamechange.STUDENT_PENDINGNAMECHANGE.USER_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public String value2() {
return getNewName();
}
/**
* {@inheritDoc}
*/
@Override
public String value3() {
return getRationale();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value4() {
return getUserId();
}
/**
* {@inheritDoc}
*/
@Override
public StudentPendingnamechangeRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public StudentPendingnamechangeRecord value2(String value) {
setNewName(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public StudentPendingnamechangeRecord value3(String value) {
setRationale(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public StudentPendingnamechangeRecord value4(Integer value) {
setUserId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public StudentPendingnamechangeRecord values(Integer value1, String value2, String value3, Integer value4) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached StudentPendingnamechangeRecord
*/
public StudentPendingnamechangeRecord() {
super(StudentPendingnamechange.STUDENT_PENDINGNAMECHANGE);
}
/**
* Create a detached, initialised StudentPendingnamechangeRecord
*/
public StudentPendingnamechangeRecord(Integer id, String newName, String rationale, Integer userId) {
super(StudentPendingnamechange.STUDENT_PENDINGNAMECHANGE);
set(0, id);
set(1, newName);
set(2, rationale);
set(3, userId);
}
}
|
package kr.co.magiclms.domain;
public class Login {
private String memberID;
private String pass;
private int studentNo;
private int professorNo;
public String getMemberID() {
return memberID;
}
public void setMemberID(String memberID) {
this.memberID = memberID;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public int getStudentNo() {
return studentNo;
}
public void setStudentNo(int studentNo) {
this.studentNo = studentNo;
}
public int getProfessorNo() {
return professorNo;
}
public void setProfessorNo(int professorNo) {
this.professorNo = professorNo;
}
}
|
package com.gxtc.huchuan.ui.deal.liuliang.publicAccount.UserAnalyse;
/**
* Created by Steven on 17/2/27.
*/
public class UserRisePresenter implements UserContract.RisePresenter{
@Override
public void start() {
}
@Override
public void destroy() {
}
}
|
package images;
public class TwoColorImage extends BaseImage {
private TwoDFunc func;
private RGB zero,one;
public TwoColorImage(int width, int height, RGB zero, RGB one, TwoDFunc func) {
super(width, height);
this.zero = zero;
this.one = one;
this.func = func;
// TODO Auto-generated constructor stub
}
@Override
public RGB get(int x, int y) {
return RGB.mix(one, zero, func.f((double )x /width, (double )y/height) );
}
}
|
package com.zhaoyan.ladderball.domain.match.http;
import com.zhaoyan.ladderball.domain.common.http.Response;
/**
* 分配比赛给记录员
*/
public class MatchAsignResponse extends Response{
}
|
package DP;
/*
343. Integer Break
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
dp[i] = max(dp[j]*dp[i-j])
*/
public class IntegerBreak {
public int integerBreak(int n) {
int[] dp = new int[n+1];
for(int i = 2; i < n+1; i++) {
for(int j = 1; j < i+1; j++) {
dp[i] = Math.max(dp[i], Math.max(dp[i-j]*j, (i-j)*j));
}
}
return dp[n];
}
}
|
package com.yifengcom.yfpos.service;
import android.os.Parcel;
import android.os.Parcelable;
public class WorkKey implements Parcelable {
// TDK
private byte tdkIndex = 0x00;
private byte[] tdk;
private byte[] tdkCheckValue;
// MAK
private byte makIndex = 0x00;
private byte[] mak;
private byte[] makCheckValue;
// PIK
private byte pikIndex = 0x00;
private byte[] pik;
private byte[] pikCheckValue;
public WorkKey(){
}
public WorkKey(Parcel in) {
tdkIndex = in.readByte();
tdk = in.createByteArray();
tdkCheckValue = in.createByteArray();
makIndex = in.readByte();
mak = in.createByteArray();
makCheckValue = in.createByteArray();
pikIndex = in.readByte();
pik = in.createByteArray();
pikCheckValue = in.createByteArray();
}
/**
* 编码数据
*/
public byte[] encode() {
byte[] body = new byte[68];
// TDK索引
body[2] = tdkIndex;
body[3] = tdk == null ? 0x00 : (byte) 0x10;
if (tdk != null) {
System.arraycopy(tdk, 0, body, 4, tdk.length < 16 ? tdk.length : 16);
}
if (tdk != null && tdkCheckValue != null) {
System.arraycopy(tdkCheckValue, 0, body, 20,
tdkCheckValue.length < 4 ? tdkCheckValue.length : 4);
}
// MAK
body[24] = makIndex;
body[25] = mak == null ? 0x00 : (byte) 0x10;
if (mak != null) {
System.arraycopy(mak, 0, body, 26, mak.length < 16 ? mak.length
: 16);
}
if (mak != null && makCheckValue != null) {
System.arraycopy(makCheckValue, 0, body, 42,
makCheckValue.length < 4 ? makCheckValue.length : 4);
}
// PIK
body[46] = pikIndex;
body[47] = pik == null ? 0x00 : (byte) 0x10;
if (pik != null) {
System.arraycopy(pik, 0, body, 48, pik.length < 16 ? pik.length
: 16);
}
if (pik != null && pikCheckValue != null) {
System.arraycopy(pikCheckValue, 0, body, 64,
pikCheckValue.length < 4 ? pikCheckValue.length : 4);
}
// 组包
return body;
}
public byte getTdkIndex() {
return tdkIndex;
}
public void setTdkIndex(byte tdkIndex) {
this.tdkIndex = tdkIndex;
}
public byte[] getTdk() {
return tdk;
}
public void setTdk(byte[] tdk) {
this.tdk = tdk;
}
public byte[] getTdkCheckValue() {
return tdkCheckValue;
}
public void setTdkCheckValue(byte[] tdkCheckValue) {
this.tdkCheckValue = tdkCheckValue;
}
public byte getMakIndex() {
return makIndex;
}
public void setMakIndex(byte makIndex) {
this.makIndex = makIndex;
}
public byte[] getMak() {
return mak;
}
public void setMak(byte[] mak) {
this.mak = mak;
}
public byte[] getMakCheckValue() {
return makCheckValue;
}
public void setMakCheckValue(byte[] makCheckValue) {
this.makCheckValue = makCheckValue;
}
public byte getPikIndex() {
return pikIndex;
}
public void setPikIndex(byte pikIndex) {
this.pikIndex = pikIndex;
}
public byte[] getPik() {
return pik;
}
public void setPik(byte[] pik) {
this.pik = pik;
}
public byte[] getPikCheckValue() {
return pikCheckValue;
}
public void setPikCheckValue(byte[] pikCheckValue) {
this.pikCheckValue = pikCheckValue;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeByte(tdkIndex);
dest.writeByteArray(tdk);
dest.writeByteArray(tdkCheckValue);
dest.writeByte(makIndex);
dest.writeByteArray(mak);
dest.writeByteArray(makCheckValue);
dest.writeByte(pikIndex);
dest.writeByteArray(pik);
dest.writeByteArray(pikCheckValue);
}
/**
* 实例化静态内部对象CREATOR实现接口Parcelable.Creator public static
* final一个都不能少,内部对象CREATOR的名称也不能改变,必须全部大写
*/
public static final Parcelable.Creator<WorkKey> CREATOR = new Creator<WorkKey>() {
// 将Parcel对象反序列化为HarlanInfo
@Override
public WorkKey createFromParcel(Parcel source) {
WorkKey workKey = new WorkKey(source);
return workKey;
}
@Override
public WorkKey[] newArray(int size) {
return new WorkKey[size];
}
};
}
|
package engine;
/**
* Comparator pela data do Post
*
*/
import java.util.Comparator;
import java.time.LocalDate;
public class ComparatorPostScore implements Comparator<Post>{
public int compare(Post p1, Post p2){
int s1, s2;
s1 = p1.getPostScore();
s2 = p2.getPostScore();
if(s1 == s2) return 1;
if(s1>s2) return -1;
else return 1;
}
} |
import java.util.Map;
/**
* No-repeat Substring (hard)
* Given a string, find the length of the longest substring which has no repeating characters.
*
* 解决问题:
* 从数组中查询一个连续子串
*
* 窗口限制条件:
* 无重复字符
*
* 如何满足条件:
* 窗口右移一位,如果重复,则移动windowStart移除重复项
* windowStart = Math.max(preSameCharIdnex+1, windowStart)
* 如果 windowStart=preSameCharIdnex+1, 下面的场景存在bug
*
* |start
* a b c c b;
* |end (windowStart = Math.max(preSameCharIdnex+1, windowStart))
*/
class NoRepeatSubstring {
public static int findLength(String str) {
int windowStart = 0;
int winowEnd = 0;
int maxLength = 0;
Map<Character, Integer>map = new HashMap<>(); //char --> index of char
for (winowEnd = 0; winowEnd < str.length(); winowEnd++) {
char rightChar = str.charAt(winowEnd);
// 处理left,使其满足 窗口中无重复字符;
int preSameCharIdnex = map.getOrDefault(rightChar, -1);
if (preSameCharIdnex != -1){
windowStart = Math.max(preSameCharIdnex+1, windowStart);
map.remove(rightChar);
}
map.put(rightChar, winowEnd);
maxLength = Math.max(maxLength, winowEnd-windowStart+1);
}
return maxLength;
}
} |
package com.gxtc.huchuan.ui.live.hostpage.newhostpage;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.huchuan.MyApplication;
import com.gxtc.huchuan.bean.ChatInfosBean;
import com.gxtc.huchuan.http.ApiCallBack;
import java.util.List;
/**
* Created by zzg on 2017/12/18.
*/
public class ClassAndSerisePresenter implements LiveAndSeriseContract.Presenter {
private ClassAndSeriseResposery data;
private LiveAndSeriseContract.View view;
public ClassAndSerisePresenter(LiveAndSeriseContract.View view) {
this.view = view;
data = new ClassAndSeriseResposery();
this.view.setPresenter(this);
}
@Override
public void start() {}
@Override
public void getData(String chatRoomId, String token, String start) {
data.getData(chatRoomId, token, start, new ApiCallBack<List<ChatInfosBean>>() {
@Override
public void onSuccess(List<ChatInfosBean> data) {
if (view == null) return;
if(data == null || data.size() == 0){
view.showEmpty();
return;
}
view.showDatat(data);
}
@Override
public void onError(String errorCode, String message) {
ToastUtil.showShort(MyApplication.getInstance(),message);
}
});
}
@Override
public void destroy() {
data.destroy();
}
}
|
package com.tpg.brks.ms.expenses.service.converters;
import com.tpg.brks.ms.expenses.domain.Expense;
import com.tpg.brks.ms.expenses.persistence.entities.ExpenseEntity;
import com.tpg.brks.ms.expenses.utils.DateFormatting;
import org.modelmapper.Converter;
import org.modelmapper.TypeMap;
import java.util.Date;
public class ExpenseConverter extends DomainConverter implements ExpenseConverting, DateFormatting {
public ExpenseConverter() {
TypeMap<ExpenseEntity, Expense> typeMap = modelMapper.createTypeMap(ExpenseEntity.class, Expense.class);
typeMap.addMappings(mapper -> mapper.map(src -> toDdMmYyyyFormat(src.getDateEntered()), Expense::setDateEntered));
Converter<Date, String> dateToString =
ctx -> ctx.getSource() == null ? null : toDdMmYyyyFormat(ctx.getSource());
typeMap.addMappings(mapper -> mapper.using(dateToString).map(ExpenseEntity::getExpenseDate, Expense::setExpenseDate));
typeMap.addMappings(mapper -> mapper.using(dateToString).map(ExpenseEntity::getDateEntered, Expense::setDateEntered));
}
@Override
public Expense convert(ExpenseEntity expenseEntity) {
return modelMapper.map(expenseEntity, Expense.class);
}
}
|
package com.soft1841.timer;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class DrawCircleThread implements Runnable {
private JFrame jFrame;
public void setjFrame(JFrame jFrame) {
this.jFrame = jFrame;
}
@Override
public void run() {
TimerTask task = new TimerTask() {
@Override
public void run() {
int x = 800;
int y = 600;
int i = 0;
Random random = new Random();
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Graphics g = jFrame.getGraphics();
//设置线条的粗细
Graphics2D g2d = (Graphics2D)g;
Stroke stroke = new BasicStroke(8.0f);
g2d.setStroke(stroke);
g.setColor(getRandomColor());//给画笔设置随机数颜色
i = random.nextInt(20);
g.drawOval(x/2 - (i + 1) * 10,y/2 - (i + 1) * 10,10 + 20 * i,10+20 * i);
}
}
private Color getRandomColor() {
Color color=new Color((int)(Math.random()*256), (int)(Math.random()*256), (int)(Math.random()*256));
return color;
}
};
Timer timer = new Timer();
timer.schedule(task,1000,500);
}
}
|
package com.oodles.mapping;
public class URLMapping
{
public static final String ACCOUNTS_API_V1 ="/v1";
//USER
public static final String ADD_USER = ACCOUNTS_API_V1 +"/add_user";
public static final String GET_USER = ACCOUNTS_API_V1 +"/get_user";
public static final String UPDATE_USER=ACCOUNTS_API_V1+"/update_user";
public static final String EDIT_USER_PROFILE=ACCOUNTS_API_V1+"/edit_user";;
//EXCHANGE
public static final String ADD_EXCHANGE=ACCOUNTS_API_V1+"/add_exchange";
public static final String GET_EXCHANGE=ACCOUNTS_API_V1+"/get_exchange";
//MARKET
public static final String SAVE_MARKET=ACCOUNTS_API_V1+"/add_market";
public static final String GET_MARKET=ACCOUNTS_API_V1+"/get_market";
//ROLE
public static final String ADD_ROLE=ACCOUNTS_API_V1+"/add_role";
//ACTIVITY
public static final String ASSIGN_ACTIVITIES = ACCOUNTS_API_V1+"/assign_activity";
public static final String ADD_ACTIVITY=ACCOUNTS_API_V1+"/add_activity";
} |
/* Ara - capture species and specimen data
*
* Copyright (C) 2009 INBio (Instituto Nacional de Biodiversidad)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.inbio.ara.eao.reports.impl;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.inbio.ara.eao.reports.DwcSnapshotEAOJDBCLocal;
/**
*
* @author esmata
*/
@Stateless
public class DwcSnapshotEAOJDBCImpl implements DwcSnapshotEAOJDBCLocal {
/**
* Metodo que exporta el contenido de la tabla dwc_snapshot en un archivo
* destino
* @param file = archivo destino
* @return
*/
public boolean writeDwcSnapshotToFile(File f, String dataSource, String dbSchema){
try{
//Obtener la conexion JDBC del proyecto
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(dataSource);
Connection connection = ds.getConnection();
//Obtener los datos del snapshot
String query = "SELECT '\"'||COALESCE(globaluniqueidentifier,'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(datelastmodified,'YYYY-MM-DD HH24:MI:SS'),'')||'\"' || ','"+
"|| '\"'||COALESCE(institutioncode,'')||'\"' || ','"+
"|| '\"'||COALESCE(collectioncode,'')||'\"' || ','"+
"|| '\"'||COALESCE(catalognumber,'')||'\"' || ','"+
"|| '\"'||COALESCE(scientificname,'')||'\"' || ','"+
"|| '\"'||COALESCE(basisofrecord,'')||'\"' || ','"+
"|| '\"'||COALESCE(informationwithheld,'')||'\"' || ','"+
"|| '\"'||COALESCE(phylum,'')||'\"' || ','"+
"|| '\"'||COALESCE(highertaxon,'')||'\"' || ','"+
"|| '\"'||COALESCE(kingdom,'')||'\"' || ','"+
"|| '\"'||COALESCE(class,'')||'\"' || ','"+
"|| '\"'||COALESCE(orders,'')||'\"' || ','"+
"|| '\"'||COALESCE(family,'')||'\"' || ','"+
"|| '\"'||COALESCE(genus,'')||'\"' || ','"+
"|| '\"'||COALESCE(specificepithet,'')||'\"' || ','"+
"|| '\"'||COALESCE(infraspecificepithet,'')||'\"' || ','"+
"|| '\"'||COALESCE(infraspecificrank,'')||'\"' || ','"+
"|| '\"'||COALESCE(authoryearofscientificname,'')||'\"' || ','"+
"|| '\"'||COALESCE(nomenclaturalcode,'')||'\"' || ','"+
"|| '\"'||COALESCE(identificationqualifier,'')||'\"' || ','"+
"|| '\"'||COALESCE(collectingmethod,'')||'\"' || ','"+
"|| '\"'||COALESCE(validdistributionflag,'')||'\"' || ','"+
"|| '\"'||COALESCE(collector,'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(earliestdatecollected,'YYYY-MM-DD'),'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(latestdatecollected,'YYYY-MM-DD'),'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(dayofyear,'00000000000000'),'')||'\"' || ','"+
"|| '\"'||COALESCE(highergeography,'')||'\"' || ','"+
"|| '\"'||COALESCE(continent,'')||'\"' || ','"+
"|| '\"'||COALESCE(waterbody,'')||'\"' || ','"+
"|| '\"'||COALESCE(islandgroup,'')||'\"' || ','"+
"|| '\"'||COALESCE(island,'')||'\"' || ','"+
"|| '\"'||COALESCE(country,'')||'\"' || ','"+
"|| '\"'||COALESCE(stateprovince,'')||'\"' || ','"+
"|| '\"'||COALESCE(county,'')||'\"' || ','"+
"|| '\"'||TRANSLATE(COALESCE(locality,''),'\r\n', ' ')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(minimumelevationinmeters,'999999999.999999'),'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(maximumelevationinmeters,'999999999.999999'),'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(minimumdepthinmeters,'999999999.999999'),'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(maximumdepthinmeters,'999999999.999999'),'')||'\"' || ','"+
"|| '\"'||COALESCE(sex,'')||'\"' || ','"+
"|| '\"'||COALESCE(lifestage,'')||'\"' || ','"+
"|| '\"'||COALESCE(remarks,'')||'\"' || ','"+
"|| '\"'||COALESCE(attributes,'')||'\"' || ','"+
"|| '\"'||COALESCE(imageurl,'')||'\"' || ','"+
"|| '\"'||COALESCE(relatedinformation,'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(catalognumbernumeric,'00000000000000'),'')||'\"' || ','"+
"|| '\"'||COALESCE(identifiedby,'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(dateidentified,'YYYY-MM-DD'),'')||'\"' || ','"+
"|| '\"'||COALESCE(collectornumber,'')||'\"' || ','"+
"|| '\"'||COALESCE(fieldnumber,'')||'\"' || ','"+
"|| '\"'||COALESCE(fieldnotes,'')||'\"' || ','"+
"|| '\"'||COALESCE(verbatimcollectingdate,'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(verbatimelevation,'999999999.999999'),'')||'\"' || ','"+
"|| '\"'||COALESCE(preparations,'')||'\"' || ','"+
"|| '\"'||COALESCE(othercatalognumbers,'')||'\"' || ','"+
"|| '\"'||COALESCE(disposition,'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(individualcount,'00000000000000'),'')||'\"' || ','"+
"|| '\"'||COALESCE(decimallatitude,'')||'\"' || ','"+
"|| '\"'||COALESCE(decimallongitude,'')||'\"' || ','"+
"|| '\"'||COALESCE(geodeticdatum,'')||'\"' || ','"+
"|| '\"'||COALESCE(coordinateuncertaintyinmeters,'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(pointradiusspatialfit,'00000000000000'),'')||'\"' || ','"+
"|| '\"'||COALESCE(verbatimcoordinates,'')||'\"' || ','"+
"|| '\"'||COALESCE(verbatimlatitude,'')||'\"' || ','"+
"|| '\"'||COALESCE(verbatimlongitude,'')||'\"' || ','"+
"|| '\"'||COALESCE(verbatimcoordinatesystem,'')||'\"' || ','"+
"|| '\"'||COALESCE(georeferenceprotocol,'')||'\"' || ','"+
"|| '\"'||COALESCE(georeferencesources,'')||'\"' || ','"+
"|| '\"'||COALESCE(georeferenceverificationstatus,'')||'\"' || ','"+
"|| '\"'||COALESCE(georeferenceremarks,'')||'\"' || ','"+
"|| '\"'||COALESCE(footprintwkt,'')||'\"' || ','"+
"|| '\"'||COALESCE(to_char(footprintspatialfit,'00000000000000'),'')||'\"' || ',' "+
"|| '\"'||COALESCE(typestatus,'')||'\"'"+
"AS aux "+
"FROM "+dbSchema+".dwc_snapshot;";
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
//Imprimir los datos en el archivo
BufferedWriter out = new BufferedWriter(new FileWriter(f));
while (rs.next()) {
out.write(rs.getString("aux")+"\n");
}
out.close();
//Cerrar el resultset y el statement
rs.close();
st.close();
//Resultado
return true;
}
catch(Exception e){
e.printStackTrace();
return false;}
}
}
|
package com.db.server;
import com.db.persistence.wsSoap.ObjectCrudSvcRemote;
import com.db.persistence.wsSoap.QuerySvcRemote;
import com.db.persistence.wsSoap.SessionsSvcRemote;
import com.plugins_manager.Plugins;
import org.apache.log4j.Logger;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
//import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.scheduling.annotation.EnableScheduling;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.xml.ws.Endpoint;
import static com.db.server.SpringProfiles.*;
@Import({
DroneDBServerAppConfig.class,
DroneWeb.class,
Plugins.class,
SecurityConfig.class
})
@ComponentScan({
"com.events",
"com.db.persistence.wsRest.internal",
"com.db.persistence",
"com.db.server",
"com.db.aspects"
})
@PropertySource(value = "classpath:application.properties")
@SpringBootApplication
@EnableScheduling
public class DroneServer extends SpringBootServletInitializer
{
private final static Logger LOGGER = Logger.getLogger(DroneServer.class);
public static ApplicationContext context ;//= new AnnotationConfigApplicationContext(DroneDBServerAppConfig.class);
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
System.out.println("Start Server with profiles");
loadProfile();
return application.sources(DroneServer.class);
}
@Bean
protected ServletContextListener listener() {
return new ServletContextListener() {
@Override
public void contextInitialized(ServletContextEvent sce) {
LOGGER.info("ServletContext initialized - TALMA");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
LOGGER.info("ServletContext destroyed - TALMA");
}
};
}
public static void main(String[] args) throws Exception {
System.out.println("Start Server with profiles");
loadProfile();
SpringApplication.run(DroneServer.class, args);
}
public static void loadProfile() {
addSpringProfile(Hibernate);
// addSpringProfile(EclipseLink);
// addSpringProfile(Postgres);
addSpringProfile(H2);
}
public static void addSpringProfile(String profile) {
String prop = System.getProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME);
if (prop == null)
prop = profile;
else
prop += "," + profile;
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, prop);
}
// public void run(String[] args) {
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
String logPath = "Logs";
String confPath = "ServerCore/addon/conf/";
if (args != null && args.length == 2) {
logPath = args[0];
confPath = args[1];
}
else {
System.err.println("MISSING PARAMETERS");
}
// Debugs
System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
// External Settings
System.setProperty("LOGS.DIR", logPath);
System.setProperty("CONF.DIR", confPath);
context = ctx;
LOGGER.debug("Details: " + logPath + " " + confPath);
LOGGER.debug("Server is up and running!");
System.err.println("Server is up and running!");
};
}
private void go() {
// System.setProperty("javax.xml.bind.JAXBContext", "com.sun.xml.internal.bind.v2.ContextFactory");
ObjectCrudSvcRemote objectCrudSvcRemote = context.getBean(ObjectCrudSvcRemote.class);
QuerySvcRemote querySvcRemote = context.getBean(QuerySvcRemote.class);
// MissionCrudSvcRemote missionCrudSvcRemote = DroneDBServerAppConfig.context.getBean(MissionCrudSvcRemote.class);
SessionsSvcRemote sessionsSvcRemote = context.getBean(SessionsSvcRemote.class);
// PerimeterCrudSvcRemote perimeterCrudSvcRemote = DroneDBServerAppConfig.context.getBean(PerimeterCrudSvcRemote.class);
String ip = context.getBean("serverIp", String.class);
String port = context.getBean("serverPort", String.class);
String format = "http://%s:%s/wsSoap/%s";
String url;
url = String.format(format, ip, port, ObjectCrudSvcRemote.class.getSimpleName());
LOGGER.debug("Sign " + ObjectCrudSvcRemote.class.getSimpleName() + " " + url);
Endpoint.publish(url, objectCrudSvcRemote);
// url = String.format(format, ip, port, QuerySvcRemote.class.getSimpleName());
// LOGGER.debug("Sign " + QuerySvcRemote.class.getSimpleName() + " " + url);
//// endpoint = Endpoint.create(querySvcRemote);
//// endpoint.publish(String.format(format, ip, port, QuerySvcRemote.class.getSimpleName()));
// Endpoint.publish(url, querySvcRemote);
//
// url = String.format(format, ip, port, MissionCrudSvcRemote.class.getSimpleName());
// LOGGER.debug("Sign " + MissionCrudSvcRemote.class.getSimpleName() + " " + url);
// Endpoint.publish(url, missionCrudSvcRemote);
//
// url = String.format(format, ip, port, SessionsSvcRemote.class.getSimpleName());
// LOGGER.debug("Sign " + SessionsSvcRemote.class.getSimpleName() + " " + url);
// Endpoint.publish(url, sessionsSvcRemote);
//
// url = String.format(format, ip, port, PerimeterCrudSvcRemote.class.getSimpleName());
// LOGGER.debug("Sign " + PerimeterCrudSvcRemote.class.getSimpleName() + " " + url);
// Endpoint.publish(url, perimeterCrudSvcRemote);
LOGGER.debug("Up and running!");
}
} |
package com.zxt.compplatform.acegi.util;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.security.ConfigAttributeDefinition;
import org.springframework.security.ConfigAttributeEditor;
import org.springframework.security.intercept.web.DefaultFilterInvocationDefinitionSource;
import org.springframework.security.intercept.web.FilterInvocationDefinitionSource;
import org.springframework.security.intercept.web.RequestKey;
import org.springframework.security.util.AntUrlPathMatcher;
import org.springframework.security.util.UrlMatcher;
/**
*
* 系统资源管理类
* @author 007
*
*/
public class JdbcFilterInvocationDefinitionSourceFactoryBean
extends JdbcDaoSupport implements FactoryBean {
private String resourceQuery;
public boolean isSingleton() {
return true;
}
public Class getObjectType() {
return FilterInvocationDefinitionSource.class;
}
public Object getObject() {
return new DefaultFilterInvocationDefinitionSource(this
.getUrlMatcher(), this.buildRequestMap());
}
/**
* 根据数据源和查询语句,查询资源列表
* @return
*/
protected List findResources() {
ResourceMapping resourceMapping = new ResourceMapping(getDataSource(),
resourceQuery);
return resourceMapping.execute();
}
/**
* 构建请求集合
* @return
*/
protected LinkedHashMap buildRequestMap() {
LinkedHashMap requestMap = null;
requestMap = new LinkedHashMap();
ConfigAttributeEditor editor = new ConfigAttributeEditor();
List resourceList = this.findResources();
//for (Resource resource : resourceList) {
// }
for (int i=0;i< resourceList.size();i++) {
Resource resource =(Resource)resourceList.get(i);
RequestKey key = new RequestKey(resource.getUrl(), null);
editor.setAsText(resource.getRole());
requestMap.put(key,
(ConfigAttributeDefinition) editor.getValue());
}
return requestMap;
}
/**
* 定义新的URLMatcher实体
* @return
*/
protected UrlMatcher getUrlMatcher() {
return new AntUrlPathMatcher();
}
public void setResourceQuery(String resourceQuery) {
this.resourceQuery = resourceQuery;
}
/**
* 资源实体
* @author 007
*/
private class Resource {
private String url;
private String role;
public Resource(String url, String role) {
this.url = url;
this.role = role;
}
public String getUrl() {
return url;
}
public String getRole() {
return role;
}
}
/**
* 资源映射
* @author 007
*/
private class ResourceMapping extends MappingSqlQuery {
protected ResourceMapping(DataSource dataSource,
String resourceQuery) {
super(dataSource, resourceQuery);
compile();
}
/* (non-Javadoc)
* @see org.springframework.jdbc.object.MappingSqlQuery#mapRow(java.sql.ResultSet, int)
*/
protected Object mapRow(ResultSet rs, int rownum)
throws SQLException {
String url = rs.getString(1);
String role = rs.getString(2);
Resource resource = new Resource(url, role);
return resource;
}
}
} |
package ru.aplana.autotests.definitions;
/**
* Created by User on 23.04.2015.
*/
public class ElementDefinition {
private String parent;
private String name;
private String aliases;
private String type;
private String customType;
private String target;
private String description;
private String loaded;
public String getLoaded() {
if (loaded == null){
return "";
}
return loaded;
}
public void setLoaded(String loaded) {
this.loaded = loaded;
}
public String getItems() {
return items;
}
public void setItems(String items) {
this.items = items;
}
private String items;
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAliases() {
return aliases;
}
public void setAliases(String aliases) {
this.aliases = aliases;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCustomType() {
return customType;
}
public void setCustomType(String customType) {
this.customType = customType;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return String.format("%s [%s]", getAliases(), getType());
}
}
|
package com.demo.bluemine.mapper;
import org.springframework.stereotype.Repository;
@Repository("com.demo.bluemine.mapper.RootMapper")
public interface RootMapper {
//test
public String test();
}
|
package com.techboon.web.rest.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
/**
* Utility class for HTTP headers creation.
*/
public final class HeaderUtil {
private static final Logger log = LoggerFactory.getLogger(HeaderUtil.class);
private static final String APPLICATION_NAME = "techboonApp";
private HeaderUtil() {
}
public static HttpHeaders createAlert(String message, String param) {
HttpHeaders headers = new HttpHeaders();
headers.add("X-techboonApp-alert", message);
headers.add("X-techboonApp-params", param);
return headers;
}
public static HttpHeaders createEntityCreationAlert(String entityName, String param) {
return createAlert(APPLICATION_NAME + "." + entityName + ".created", param);
}
public static HttpHeaders createEntityUpdateAlert(String entityName, String param) {
return createAlert(APPLICATION_NAME + "." + entityName + ".updated", param);
}
public static HttpHeaders createEntityDeletionAlert(String entityName, String param) {
return createAlert(APPLICATION_NAME + "." + entityName + ".deleted", param);
}
public static HttpHeaders createEntityShareAlert(String entityName, String param) {
return createAlert(APPLICATION_NAME + "." + entityName + ".shared", param);
}
public static HttpHeaders createEntityUploadedAlert(String entityName, String param) {
return createAlert(APPLICATION_NAME + "." + entityName + ".uploaded", param);
}
public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) {
log.error("Entity processing failed, {}", defaultMessage);
HttpHeaders headers = new HttpHeaders();
headers.add("X-techboonApp-error", "error." + errorKey);
headers.add("X-techboonApp-params", entityName);
return headers;
}
}
|
package com.example.moviedb.reponsitory;
import com.example.moviedb.api.WebService;
import io.reactivex.Observable;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class Repository {
private WebService service;
public Repository() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.themoviedb.org/3/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(WebService.class);
}
public Observable getNowPlaying() {
return service.getNowPlaying("4b6dbb466a7dcc286e614fe5d5845299");
}
public Observable getPopular(){
return service.getPopular("4b6dbb466a7dcc286e614fe5d5845299");
}
public Observable getTopRated(){
return service.getTopRated("4b6dbb466a7dcc286e614fe5d5845299");
}
public Observable getUpcoming(){
return service.getUpComing("4b6dbb466a7dcc286e614fe5d5845299");
}
public Observable getVideo(int movie_id){
return service.getVideo(movie_id,"4b6dbb466a7dcc286e614fe5d5845299");
}
public Observable getDetail(int movie_id){
return service.getMovieDetail(movie_id,"4b6dbb466a7dcc286e614fe5d5845299");
}
public Observable getSimilar(int movie_id){
return service.getSimilarVideo(movie_id,"4b6dbb466a7dcc286e614fe5d5845299");
}
}
|
package com.lenovohit.ssm.app.community.model;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import com.lenovohit.core.model.BaseIdModel;
import com.lenovohit.ssm.app.elh.base.model.Doctor;
@Entity
@Table(name = "CONSULT_RECORD")
public class ConsultRecord extends BaseIdModel {
private static final long serialVersionUID = 2785667409688656841L;
private String department;
private String deptName;
private String hospital;
private String hosName;
private Doctor doctor;
private String consultType;
private String consultTopic;
private String consultDetail;
private String status;
private String comm;
private String stopFlag;
private String createTime;
private String createOper;
private String updateTime;
private String updateOper;
private String createOperId;
private String updateOperId;
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getHospital() {
return hospital;
}
public void setHospital(String hospital) {
this.hospital = hospital;
}
public String getHosName() {
return hosName;
}
public void setHosName(String hosName) {
this.hosName = hosName;
}
@ManyToOne
@JoinColumn(name = "doctor", nullable = true)
@NotFound(action=NotFoundAction.IGNORE)
public Doctor getDoctor() {
return doctor;
}
public void setDoctor(Doctor doctor) {
this.doctor = doctor;
}
public String getConsultType() {
return consultType;
}
public void setConsultType(String consultType) {
this.consultType = consultType;
}
public String getConsultTopic() {
return consultTopic;
}
public void setConsultTopic(String consultTopic) {
this.consultTopic = consultTopic;
}
public String getConsultDetail() {
return consultDetail;
}
public void setConsultDetail(String consultDetail) {
this.consultDetail = consultDetail;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getComm() {
return comm;
}
public void setComm(String comm) {
this.comm = comm;
}
public String getStopFlag() {
return stopFlag;
}
public void setStopFlag(String stopFlag) {
this.stopFlag = stopFlag;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getCreateOper() {
return createOper;
}
public void setCreateOper(String createOper) {
this.createOper = createOper;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public String getUpdateOper() {
return updateOper;
}
public void setUpdateOper(String updateOper) {
this.updateOper = updateOper;
}
public String getCreateOperId() {
return createOperId;
}
public void setCreateOperId(String createOperId) {
this.createOperId = createOperId;
}
public String getUpdateOperId() {
return updateOperId;
}
public void setUpdateOperId(String updateOperId) {
this.updateOperId = updateOperId;
}
}
|
package br.com.transactions.filter;
public class JPAFilterBeanFactory {
public JPAFilter getInstance() {
return new JPADefaultFilter();
}
}
|
package model.DAO;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.DBConnection.DBConnection;
import model.object.Language;
import model.object.Type;
public class TypeDAO {
public static List<Type> getListType() {
String query = "select * from Type ";
try {
PreparedStatement preparedStatement = DBConnection.connect(query);
List<Type> list = new ArrayList<Type>();
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Type type = new Type();
type.setId(resultSet.getInt("id"));
type.setType(resultSet.getString("type"));
list.add(type);
}
return list;
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static Boolean insertTypeBook(Type type) {
String query = "insert into Type (type) values(?)";
try {
PreparedStatement preparedStatement = DBConnection.connect(query);
preparedStatement.setString(1, type.getType());
return 1 == preparedStatement.executeUpdate();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
return false;
}
}
}
|
package io.breen.socrates.test;
import io.breen.socrates.criteria.Criteria;
import io.breen.socrates.file.File;
import io.breen.socrates.submission.Submission;
import io.breen.socrates.submission.SubmittedFile;
import javax.swing.text.Document;
/**
* An interface implemented by any test whose running can be automated. Any test that implements
* this interface can be scheduled for execution without any user interaction. This means that
* Automatable tests can be skipped at the UI level when it is presenting tests for a user to pass
* or fail.
*/
public interface Automatable<T extends File> {
/**
* For automatable tests, this method is called to determine whether the test should pass or
* fail.
*
* @param parent The File instance created from the criteria file, representing the assignment's
* requirements
* @param target A SubmittedFile object representing the actual submission on the file system,
* or null if the file could not be found
* @param submission The Submission object containing the target
* @param criteria The Criteria object that specifies the parent file (may be used to obtain
* resources loaded from a criteria package)
* @param transcript A Document object to which the "transcript" of a test should be written
* (detailed information showing what test is being run)
*
* @return Whether this test should pass (i.e. whether the target file is "correct")
*
* @throws CannotBeAutomatedException If, while running the test automatically, it becomes
* impossible to determine whether the test should pass automatically
* @throws AutomationFailureException If, while running the test automatically, a fatal error
* occurs
*/
boolean shouldPass(T parent, SubmittedFile target, Submission submission, Criteria criteria,
Document transcript, Document notes)
throws CannotBeAutomatedException, AutomationFailureException;
}
|
package com.cbs.edu.eshop.service;
import com.cbs.edu.eshop.dto.request.UserCreationRequestDto;
import com.cbs.edu.eshop.entity.Role;
import com.cbs.edu.eshop.entity.User;
import com.cbs.edu.eshop.repository.IRoleRepository;
import com.cbs.edu.eshop.repository.IUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class UserService {
private final IUserRepository userRepository;
private final IRoleRepository roleRepository;
@Autowired
public UserService(IUserRepository userRepository, IRoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
public User get(Integer id) {
return userRepository.get(id);
}
@Transactional
public User create(UserCreationRequestDto userDto) {
Role role;
if (!userDto.getUsername().contains("admin")) {
role = new Role("USER");
} else {
role = new Role("ADMIN");
}
Role savedRole = roleRepository.create(role);
User user = new User(
userDto.getFirstName(),
userDto.getLastName(),
userDto.getUsername(),
userDto.getEmail(),
userDto.getPassword()
);
user.setRole(savedRole);
return userRepository.create(user);
}
public User update(User user) {
return userRepository.update(user);
}
public void delete(Integer id) {
userRepository.delete(id);
}
public List<User> getAll() {
return userRepository.getAll();
}
public User getByUsername(String username) {
return userRepository.getByUsername(username);
}
}
|
package paketmalimslovima;
import java.util.Scanner;
//a) Napisati program koji ce sabrati brojeve od 1 do 5. Program treba da ispise zbir.
//b) Napisati program koji ce sabrati sve brojeve od 1 do n (n uneti preko konzole). Program treba da ispise zbir.
//c) Napisati program sabrati sve brojeve od k do n (k i n uneti preko konzole). Program treba da ispise zbir
public class Zadatak_2_13082019 {
public static void main(String[] args) {
Scanner ulaz = new Scanner(System.in);
int a, b, pocetak = 0, zbir = 0;
System.out.println("Odaberite program koji zelite da odredi: ");
System.out.println(" a) zbir brojeva od 1 do 5");
System.out.println(" b) zbir brojeva od 1 do broja koji Vi upisete");
System.out.println(" c) zbir brojeva u rasponu koji vi odredite");
String prekidac = ulaz.next();
switch(prekidac) {
case "a": {
a = 1;
b = 5;
while(a <= b) {
zbir += a++;
}
System.out.println("Zbir brojeva od 1 do 5 iznosi: " + zbir);
}break;
case "b": {
a = 1;
System.out.println("Unesite broj do kojeg zelite da sabiramo: ");
b = ulaz.nextInt();
while(a <= b) {
zbir += a++;
}
System.out.println("Zbir brojeva od 1 do " + b + " iznosi: " + zbir);
}break;
case "c": {
System.out.println("Unesite broj OD kojeg zelite da sabiramo: ");
a = ulaz.nextInt();
System.out.println("Unesite broj DO kojeg zelite da sabiramo: ");
b = ulaz.nextInt();
while(a >= b) {
System.out.println("Drugi broj mora biti veci od prvog. Ukucajte ga ponovo:");
b = ulaz.nextInt();
}
pocetak = a;
while(a <= b) {
zbir += a++;
}
System.out.println("Zbir brojeva od " + pocetak + " do " + b + " iznosi: " + zbir);
}break;
default: System.out.println("Pogresan unos.");
}
}
}
|
/**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.forms;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.explorer.client.app.ui.ExampleContainer;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.container.BoxLayoutContainer.BoxLayoutData;
import com.sencha.gxt.widget.core.client.container.HBoxLayoutContainer;
import com.sencha.gxt.widget.core.client.container.HBoxLayoutContainer.HBoxLayoutAlign;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.form.FieldLabel;
import com.sencha.gxt.widget.core.client.form.FormPanel.LabelAlign;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.toolbar.LabelToolItem;
@Detail(
name = "FieldLabel",
category = "Forms",
icon = "formsexample",
preferredHeight = FieldLabelExample.PREFERRED_HEIGHT,
preferredWidth = FieldLabelExample.PREFERRED_WIDTH)
public class FieldLabelExample implements IsWidget, EntryPoint {
protected static final int PREFERRED_HEIGHT = -1;
protected static final int PREFERRED_WIDTH = 500;
private ContentPanel panel;
@Override
public Widget asWidget() {
if (panel == null) {
TextField field1 = new TextField();
TextField field2 = new TextField();
TextField field3 = new TextField();
TextField field4 = new TextField();
TextField field5 = new TextField();
TextField field6 = new TextField();
// Example of the field label
FieldLabel fieldLabel1 = new FieldLabel(field1, "Field 1");
FieldLabel fieldLabel2 = new FieldLabel(field2, "Field 2");
FieldLabel fieldLabel3 = new FieldLabel(field3, "Field 3");
fieldLabel1.setLabelAlign(LabelAlign.LEFT);
fieldLabel1.setLabelPad(5);
fieldLabel1.setLabelSeparator(":");
fieldLabel1.setLabelWidth(100);
fieldLabel1.setLabelWordWrap(false);
// Write your own custom field label
Widget customFieldLabel1 = createMyOwnFieldLabel(field4, "Field 4");
Widget customFieldLabel2 = createMyOwnFieldLabel(field5, "Field 5");
Widget customFieldLabel3 = createMyOwnFieldLabel(field6, "Field 6");
VerticalLayoutContainer vbox = new VerticalLayoutContainer();
vbox.add(new LabelToolItem("FieldLabels"), new VerticalLayoutData(1, -1, new Margins(20, 20, 5, 20)));
vbox.add(fieldLabel1, new VerticalLayoutData(1, -1, new Margins(20)));
vbox.add(fieldLabel2, new VerticalLayoutData(1, -1, new Margins(20)));
vbox.add(fieldLabel3, new VerticalLayoutData(1, -1, new Margins(20)));
vbox.add(new LabelToolItem("Custom FieldLabels"), new VerticalLayoutData(1, -1, new Margins(40, 20, 5, 20)));
vbox.add(customFieldLabel1, new VerticalLayoutData(1, -1, new Margins(20)));
vbox.add(customFieldLabel2, new VerticalLayoutData(1, -1, new Margins(20)));
vbox.add(customFieldLabel3, new VerticalLayoutData(1, -1, new Margins(20)));
panel = new ContentPanel();
panel.setHeading("Example of the FieldLabel");
panel.add(vbox);
}
return panel;
}
private Widget createMyOwnFieldLabel(Widget widget, String label) {
LabelToolItem labelToolItem = new LabelToolItem(label + ":");
BoxLayoutData flex = new BoxLayoutData();
flex.setFlex(1);
HBoxLayoutContainer row = new HBoxLayoutContainer(HBoxLayoutAlign.MIDDLE);
row.setEnableOverflow(false);
row.add(labelToolItem);
row.add(widget, flex);
return row;
}
@Override
public void onModuleLoad() {
new ExampleContainer(this).setPreferredHeight(PREFERRED_HEIGHT).setPreferredWidth(PREFERRED_WIDTH).doStandalone();
}
}
|
package com.zantong.mobilecttx.user.bean;
import java.util.List;
/**
* Created by zhengyingbing on 16/6/1.
* 消息类别返回实体对象
*/
public class MessageBean {
private List<Meg> messageDetailList;
public void setMessageDetailList(List<Meg> messageDetailList) {
this.messageDetailList = messageDetailList;
}
public List<Meg> getMessageDetailList() {
return messageDetailList;
}
}
|
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
sc.nextLine();
String[] path = new String[n];
String[] name = new String[n];
for (int i = 0; i < n; i++) {
path[i] = sc.next();
name[i] = sc.next();
}
for (int i = 0; i < m; i++) {
String in = sc.next();
boolean matched = false;
for (int j = 0; !matched && j < n; j++) {
if (match(in, path[j])) {
matched = true;
System.out.print(name[j]);
printInfo(in, path[j]);
}
}
if (!matched) {
System.out.println("404");
}
}
}
public static boolean match(String inS, String pathS) {
int inLen = inS.length();
int pathLen = pathS.length();
int i = 0, p = 0;
char[] in = inS.toCharArray();
char[] path = pathS.toCharArray();
while (i < inLen && p < pathLen) {
if (in[i] == path[p]) {
i++;
p++;
} else {
if (path[p++] != '<') {
return false;
}
if (path[p] == 'i') {
boolean flag = false;
while (i < inLen && Character.isDigit(in[i])) {
if (in[i] != '0') {
flag = true;
}
i++;
}
if (!flag) {
return false;
}
p += 4;
} else if (path[p] == 's') {
boolean flag = false;
while (i < inLen && in[i] != '/') {
flag = true;
i++;
}
if (!flag) {
return false;
}
p += 4;
} else if (path[p] == 'p') {
return true;
}
}
}
return p == pathLen && i == inLen;
}
public static void printInfo(String inS, String pathS) {
int inLen = inS.length();
int pathLen = pathS.length();
int i = 0, p = 0;
char[] in = inS.toCharArray();
char[] path = pathS.toCharArray();
while (i < inLen && p < pathLen) {
if (in[i] == path[p]) {
i++;
p++;
} else {
if (path[p++] == '<') {
System.out.print(" ");
}
if (path[p] == 'i') {
StringBuilder num = new StringBuilder();
while (i < inLen && Character.isDigit(in[i])) {
num.append(in[i++]);
}
System.out.print(Integer.parseInt(num.toString()));
p += 4;
} else if (path[p] == 's') {
while (i < inLen && in[i] != '/') {
System.out.print(in[i++]);
}
p += 4;
} else if (path[p] == 'p') {
while (i < inLen) {
System.out.print(in[i++]);
}
}
}
}
System.out.println();
}
} |
package com.atguigu.exer2;
/*
冒泡排序 : 必须会手写
*/
public class BubbleSort {
public static void main(String[] args) {
int[] numbers = {10,2,89,39,16};
//外层循环控制比较几轮
for (int i = 0; i < numbers.length - 1; i++) {
//内层循环控制每轮的次数
for (int j = 0; j < numbers.length - i - 1; j++) {
//比较
if(numbers[j] > numbers[j + 1]){
//交换数据
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
//遍历数组
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
|
package test.java.cardprefixlist;
import org.junit.Test;
import test.java.cardprefixlist.exceptions.CrossingRangeException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import static org.junit.Assert.*;
public class RangeTest {
@Test
public void testGetFromPointLocation_Range() throws Exception {
Range range = new Range(10, 100, "test");
assertSame(PointLocation.BEFORE, range.getFromPointLocation(5));
assertSame(PointLocation.BEFORE, range.getFromPointLocation(9));
assertSame(PointLocation.AT_START, range.getFromPointLocation(10));
assertSame(PointLocation.INSIDE, range.getFromPointLocation(11));
assertSame(PointLocation.INSIDE, range.getFromPointLocation(50));
assertSame(PointLocation.INSIDE, range.getFromPointLocation(99));
assertSame(PointLocation.AT_END, range.getFromPointLocation(100));
assertSame(PointLocation.AFTER, range.getFromPointLocation(101));
assertSame(PointLocation.AFTER, range.getFromPointLocation(200));
}
@Test
public void testGetFromPointLocation_Point() throws Exception {
Range range = new Range(50, 50, "test");
assertSame(PointLocation.BEFORE, range.getFromPointLocation(5));
assertSame(PointLocation.BEFORE, range.getFromPointLocation(49));
assertSame(PointLocation.AT_START, range.getFromPointLocation(50));
assertSame(PointLocation.AFTER, range.getFromPointLocation(51));
assertSame(PointLocation.AFTER, range.getFromPointLocation(200));
}
@Test
public void testGetToPointLocation_Range() throws Exception {
Range range = new Range(10, 100, "test");
assertSame(PointLocation.BEFORE, range.getToPointLocation(5));
assertSame(PointLocation.BEFORE, range.getToPointLocation(9));
assertSame(PointLocation.AT_START, range.getToPointLocation(10));
assertSame(PointLocation.INSIDE, range.getToPointLocation(11));
assertSame(PointLocation.INSIDE, range.getToPointLocation(50));
assertSame(PointLocation.INSIDE, range.getToPointLocation(99));
assertSame(PointLocation.AT_END, range.getToPointLocation(100));
assertSame(PointLocation.AFTER, range.getToPointLocation(101));
assertSame(PointLocation.AFTER, range.getToPointLocation(200));
}
@Test
public void testGetToPointLocation_Point() throws Exception {
Range range = new Range(50, 50, "test");
assertSame(PointLocation.BEFORE, range.getToPointLocation(5));
assertSame(PointLocation.BEFORE, range.getToPointLocation(49));
assertSame(PointLocation.AT_END, range.getToPointLocation(50));
assertSame(PointLocation.AFTER, range.getToPointLocation(51));
assertSame(PointLocation.AFTER, range.getToPointLocation(200));
}
@Test
public void testMerge_Range_Range_BEFORE_BEFORE() throws Exception {
test(new Range(10, 20, "old"), true,
new Range(1, 5, "new"), true,
PointLocation.BEFORE, PointLocation.BEFORE, true,
new Range(10, 20, "old"),
new Range(1, 5, "new"),
new Range(1, 5, "new"));
}
@Test
public void testMerge_Range_Point_BEFORE_BEFORE() throws Exception {
test(new Range(10, 20, "old"), true,
new Range(5, 5, "new"), false,
PointLocation.BEFORE, PointLocation.BEFORE, true,
new Range(10, 20, "old"),
new Range(5, 5, "new"),
new Range(5, 5, "new"));
}
@Test
public void testMerge_Point_Range_BEFORE_BEFORE() throws Exception {
test(new Range(10, 10, "old"), false,
new Range(1, 5, "new"), true,
PointLocation.BEFORE, PointLocation.BEFORE, true,
new Range(10, 10, "old"),
new Range(1, 5, "new"),
new Range(1, 5, "new"));
}
@Test
public void testMerge_Point_Point_BEFORE_BEFORE() throws Exception {
test(new Range(15, 15, "old"), false,
new Range(1, 1, "new"), false,
PointLocation.BEFORE, PointLocation.BEFORE, true,
new Range(15, 15, "old"),
new Range(1, 1, "new"),
new Range(1, 1, "new"));
}
@Test(expected = CrossingRangeException.class)
public void testMerge_Range_Range_BEFORE_AT_START() throws Exception {
test(new Range(10, 20, "old"), true,
new Range(1, 10, "new"), true,
PointLocation.BEFORE, PointLocation.AT_START, true,
new Range(0, 0, ""),
new Range(0, 0, ""),
new Range(0, 0, ""));
}
@Test(expected = CrossingRangeException.class)
public void testMerge_Range_Range_BEFORE_INSIDE() throws Exception {
test(new Range(10, 20, "old"), true,
new Range(1, 15, "new"), true,
PointLocation.BEFORE, PointLocation.INSIDE, true,
new Range(0, 0, ""),
new Range(0, 0, ""),
new Range(0, 0, ""));
}
@Test
public void testMerge_Range_Range_BEFORE_AT_END() throws Exception {
test(new Range(10, 20, "old"), true,
new Range(1, 20, "new"), true,
PointLocation.BEFORE, PointLocation.AT_END, true,
new Range(10, 20, "old"),
new Range(1, 9, "new"),
new Range(1, 9, "new"));
}
@Test
public void testMerge_Point_Range_BEFORE_AT_END() throws Exception {
test(new Range(20, 20, "old"), false,
new Range(1, 20, "new"), true,
PointLocation.BEFORE, PointLocation.AT_END, true,
new Range(20, 20, "old"),
new Range(1, 19, "new"),
new Range(1, 19, "new"));
}
@Test
public void testMerge_Range_Range_BEFORE_AFTER() throws Exception {
test(new Range(10, 20, "old"), true,
new Range(1, 30, "new"), true,
PointLocation.BEFORE, PointLocation.AFTER, false,
new Range(10, 20, "old"),
new Range(21, 30, "new"),
new Range(1, 9, "new"));
}
@Test
public void testMerge_Point_Range_BEFORE_AFTER() throws Exception {
test(new Range(20, 20, "old"), false,
new Range(1, 30, "new"), true,
PointLocation.BEFORE, PointLocation.AFTER, false,
new Range(20, 20, "old"),
new Range(21, 30, "new"),
new Range(1, 19, "new"));
}
@Test
public void testMerge_Range_Point_AT_START_AT_START() throws Exception {
test(new Range(10, 20, "old"), true,
new Range(10, 10, "new"), false,
PointLocation.AT_START, PointLocation.AT_START, true,
new Range(11, 20, "old"),
new Range(10, 10, "new"),
new Range(10, 10, "new"),
new Range(11, 20, "old"));
}
@Test
public void testMerge_Range_Range_AT_START_INSIDE() throws Exception {
test(new Range(10, 20, "old"), true,
new Range(10, 15, "new"), true,
PointLocation.AT_START, PointLocation.INSIDE, true,
new Range(16, 20, "old"),
new Range(10, 15, "new"),
new Range(10, 15, "new"),
new Range(16, 20, "old"));
}
@Test
public void testMerge_Range_Range_AT_START_AT_END() throws Exception {
test(new Range(10, 20, "old"), true,
new Range(10, 20, "new"), true,
PointLocation.AT_START, PointLocation.AT_END, true,
new Range(10, 20, "old"),
new Range(10, 20, "new"));
}
@Test
public void testMerge_Point_Point_AT_START_AT_END() throws Exception {
test(new Range(10, 10, "old"), false,
new Range(10, 10, "new"), false,
PointLocation.AT_START, PointLocation.AT_END, true,
new Range(10, 10, "old"),
new Range(10, 10, "new"));
}
@Test
public void testMerge_Range_Range_AT_START_AFTER() throws Exception {
test(new Range(10, 20, "old"), true,
new Range(10, 30, "new"), true,
PointLocation.AT_START, PointLocation.AFTER, false,
new Range(10, 20, "old"),
new Range(21, 30, "new"));
}
@Test
public void testMerge_Point_Range_AT_START_AFTER() throws Exception {
test(new Range(10, 10, "old"), false,
new Range(10, 30, "new"), true,
PointLocation.AT_START, PointLocation.AFTER, false,
new Range(10, 10, "old"),
new Range(11, 30, "new"));
}
@Test
public void testMerge_Range_Range_INSIDE_INSIDE() throws Exception {
test(new Range(10, 30, "old"), true,
new Range(11, 29, "new"), true,
PointLocation.INSIDE, PointLocation.INSIDE, true,
new Range(10, 10, "old"),
new Range(11, 29, "new"),
new Range(10, 10, "old"),
new Range(11, 29, "new"),
new Range(30, 30, "old"));
}
@Test
public void testMerge_Range_Point_INSIDE_INSIDE() throws Exception {
test(new Range(10, 30, "old"), true,
new Range(20, 20, "new"), false,
PointLocation.INSIDE, PointLocation.INSIDE, true,
new Range(10, 19, "old"),
new Range(20, 20, "new"),
new Range(10, 19, "old"),
new Range(20, 20, "new"),
new Range(21, 30, "old"));
}
@Test
public void testMerge_Range_Range_INSIDE_AT_END() throws Exception {
test(new Range(10, 30, "old"), true,
new Range(11, 30, "new"), true,
PointLocation.INSIDE, PointLocation.AT_END, true,
new Range(10, 10, "old"),
new Range(11, 30, "new"),
new Range(10, 10, "old"),
new Range(11, 30, "new"));
}
@Test(expected = CrossingRangeException.class)
public void testMerge_Range_Range_INSIDE_AFTER() throws Exception {
test(new Range(10, 20, "old"), true,
new Range(15, 25, "new"), true,
PointLocation.INSIDE, PointLocation.AFTER, true,
new Range(0, 0, ""),
new Range(0, 0, ""),
new Range(0, 0, ""));
}
@Test
public void testMerge_Range_Point_AT_END_AT_END() throws Exception {
test(new Range(10, 30, "old"), true,
new Range(30, 30, "new"), false,
PointLocation.AT_END, PointLocation.AT_END, true,
new Range(10, 29, "old"),
new Range(30, 30, "new"),
new Range(10, 29, "old"),
new Range(30, 30, "new"));
}
@Test(expected = CrossingRangeException.class)
public void testMerge_Range_Range_AT_END_AFTER() throws Exception {
test(new Range(10, 30, "old"), true,
new Range(30, 35, "new"), true,
PointLocation.AT_END, PointLocation.AFTER, true,
new Range(0, 0, ""),
new Range(0, 0, ""),
new Range(0, 0, ""));
}
@Test
public void testMerge_Range_Range_AFTER_AFTER() throws Exception {
test(new Range(10, 30, "old"), true,
new Range(35, 40, "new"), true,
PointLocation.AFTER, PointLocation.AFTER, false,
new Range(10, 30, "old"),
new Range(35, 40, "new"));
}
private void test(Range oldRange, boolean oldRangeIsRange,
Range newRange, boolean newRangeIsRange,
PointLocation expectedStartLocation, PointLocation expectedEndLocation, boolean expectedResult,
Range expectedOldRange,
Range expectedNewRange,
Range... expectedUpdates) throws Exception {
assertTrue(oldRange.getPrefixFrom() <= oldRange.getPrefixTo());
assertTrue(newRange.getPrefixFrom() <= newRange.getPrefixTo());
assertEquals(oldRangeIsRange, oldRange.getPrefixFrom() < oldRange.getPrefixTo());
assertEquals(newRangeIsRange, newRange.getPrefixFrom() < newRange.getPrefixTo());
assertEquals(expectedStartLocation, oldRange.getFromPointLocation(newRange.getPrefixFrom()));
assertEquals(expectedEndLocation, oldRange.getToPointLocation(newRange.getPrefixTo()));
List<Range> updates = new ArrayList<>();
assertEquals(expectedResult, oldRange.merge(newRange, updates));
assertEquals(expectedOldRange, oldRange);
assertEquals(expectedNewRange, newRange);
// order doesn't matter
assertEquals(new HashSet<Range>(Arrays.asList(expectedUpdates)), new HashSet<Range>(updates));
}
@Test
public void testAssertNotCrossing() throws Exception {
// range & range
checkAssertNotCrossing(true, new Range(10, 20, "t1"), new Range(9, 15, "t2"));
checkAssertNotCrossing(true, new Range(10, 20, "t1"), new Range(9, 10, "t2"));
checkAssertNotCrossing(false, new Range(10, 20, "t1"), new Range(10, 15, "t2"));
checkAssertNotCrossing(false, new Range(10, 20, "t1"), new Range(11, 15, "t2"));
checkAssertNotCrossing(false, new Range(10, 20, "t1"), new Range(10, 20, "t2"));
checkAssertNotCrossing(false, new Range(10, 20, "t1"), new Range(15, 20, "t2"));
checkAssertNotCrossing(true, new Range(10, 20, "t1"), new Range(15, 21, "t2"));
checkAssertNotCrossing(true, new Range(10, 20, "t1"), new Range(20, 21, "t2"));
checkAssertNotCrossing(false, new Range(10, 20, "t1"), new Range(21, 22, "t2"));
checkAssertNotCrossing(false, new Range(10, 20, "t1"), new Range(1, 22, "t2"));
// point & range
checkAssertNotCrossing(false, new Range(20, 20, "t1"), new Range(1, 19, "t2"));
checkAssertNotCrossing(false, new Range(20, 20, "t1"), new Range(1, 20, "t2"));
checkAssertNotCrossing(false, new Range(20, 20, "t1"), new Range(1, 21, "t2"));
checkAssertNotCrossing(false, new Range(20, 20, "t1"), new Range(20, 22, "t2"));
checkAssertNotCrossing(false, new Range(20, 20, "t1"), new Range(21, 22, "t2"));
// range & point
checkAssertNotCrossing(false, new Range(15, 20, "t1"), new Range(14, 14, "t2"));
checkAssertNotCrossing(false, new Range(15, 20, "t1"), new Range(15, 15, "t2"));
checkAssertNotCrossing(false, new Range(15, 20, "t1"), new Range(16, 16, "t2"));
checkAssertNotCrossing(false, new Range(15, 20, "t1"), new Range(17, 17, "t2"));
checkAssertNotCrossing(false, new Range(15, 20, "t1"), new Range(19, 19, "t2"));
checkAssertNotCrossing(false, new Range(15, 20, "t1"), new Range(20, 20, "t2"));
checkAssertNotCrossing(false, new Range(15, 20, "t1"), new Range(21, 21, "t2"));
// point & point
checkAssertNotCrossing(false, new Range(20, 20, "t1"), new Range(14, 14, "t2"));
checkAssertNotCrossing(false, new Range(20, 20, "t1"), new Range(18, 18, "t2"));
checkAssertNotCrossing(false, new Range(20, 20, "t1"), new Range(19, 19, "t2"));
checkAssertNotCrossing(false, new Range(20, 20, "t1"), new Range(20, 20, "t2"));
checkAssertNotCrossing(false, new Range(20, 20, "t1"), new Range(21, 21, "t2"));
checkAssertNotCrossing(false, new Range(20, 20, "t1"), new Range(22, 22, "t2"));
}
private void checkAssertNotCrossing(boolean shouldFail, Range r1, Range r2) throws Exception {
try {
r1.assertNotCrossing(r2);
if (shouldFail) {
fail();
}
} catch (CrossingRangeException ex) {
if (!shouldFail) {
fail();
}
}
}
} |
package com.seven.contract.manage.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.seven.contract.manage.common.PageResult;
import com.seven.contract.manage.dao.MessageDao;
import com.seven.contract.manage.model.Message;
import com.seven.contract.manage.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
@Transactional(rollbackFor = Exception.class)
public class MessageServiceImpl implements MessageService {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private MessageDao messageDao;
@Override
public void addMessage(Message message) {
message.setReadFlag("N");
message.setAddTime(new Date());
messageDao.insert(message);
}
@Override
public void updateMessage(Message message){
messageDao.update(message);
}
@Override
public void deleteById(long id) {
messageDao.deleteById(id);
}
@Override
public Message selectOneById(long id) {
Message message = messageDao.selectOne(id);
return message;
}
@Override
public PageResult<Message> getListByPage(Map<String, Object> params, int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<Message> dataList = messageDao.selectList(params);
Page page=(Page) dataList;
PageResult pageResult=new PageResult();
pageResult.setRecords(page.getTotal());
pageResult.setRows(dataList);
pageResult.setPage(page.getPageNum());
pageResult.setTotal(page.getPages());
return pageResult;
}
@Override
public List<Message> getList(Map<String, Object> params) {
return messageDao.selectList(params);
}
}
|
package Controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class mycontroller {
@RequestMapping(value="/aform.html", method=RequestMethod.GET)
public ModelAndView show(){
ModelAndView mobj = new ModelAndView("admissionform");
return mobj;
}
@RequestMapping(value="/submitform.html",method=RequestMethod.POST)
public ModelAndView storeform(@RequestParam("sid") int id,@RequestParam("sname") String name){//@RequestParam is used to get form parameter
//in above line, sid and sname variable should be same as textbox name in the form(form in admissionform.jsp) by which request is sent.
ModelAndView mvobj = new ModelAndView("submitresponse");
mvobj.addObject("rid", id);
mvobj.addObject("rname", name);
return mvobj;
}
}
|
package com.mqld.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import com.mqld.constant.Constant;
import com.mqld.dao.QueueDao;
import com.mqld.model.Page;
import com.mqld.model.QueueItem;
import com.mqld.model.QueueProcess;
import com.mqld.model.TeachersPerfQueryConditionDTO;
import com.mqld.util.JdbcUtil;
import com.mqld.util.StringUtils;
@Repository
public class QueueDaoImpl implements QueueDao {
@Autowired
JdbcTemplate JdbcTemplate;
private static final String GET_TEACHER_STATUS="SELECT u.ID AS teacherID, u.name AS teacherName,t.startWorkTime,t.endWorkTime,IFNULL(t.onWork,false) AS teacherOnWork,t.style AS teacherStyle,t.maxStudentNum,t.contactInfo AS teacherContactInfo,IFNULL(cnt.count,0) AS currentQueueNum ,IFNULL(tcnt.count,0) AS totalQueueNum FROM teacher t,user u LEFT JOIN (SELECT b.ID, COUNT(*) AS count FROM queue q RIGHT JOIN user b ON b.ID=q.teacherID Where status=? AND DATE_FORMAT(q.createTime,'%Y-%m-%d')>=? GROUP BY b.ID) cnt ON u.ID=cnt.ID LEFT JOIN (SELECT b.ID, COUNT(*) AS count FROM queue q LEFT JOIN user b ON b.ID=q.teacherID WHERE DATE_FORMAT(q.createTime,'%Y-%m-%d')>=? GROUP BY b.ID) tcnt ON u.ID=tcnt.ID WHERE u.authority=? AND t.userID=u.ID LIMIT ?,?";
private static final String GET_STUDENT_STATUS="SELECT q.ID,q.pictureNum,q.studentPath,q.studentComment,u.name AS studentName FROM queue q, user u,teacher t WHERE t.userID=q.teacherID AND u.ID=q.studentID AND q.teacherID=? AND q.status=? AND DATE_FORMAT(q.createTime,'%Y-%m-%d')>=? ORDER BY q.createTime LIMIT ?,?";
private static final String GET_CURRENT_STUDENT_STATUS="SELECT q.pictureNum,q.studentPath,q.studentComment,u.name AS teacherName ,t.maxStudentNum ,a.rownum AS currentQueueNum FROM (SELECT @rownum:=@rownum+1 AS rownum, qu.teacherID,qu.studentID, qu.ID FROM (SELECT @rownum:=0) r, (SELECT * FROM queue WHERE teacherID=(SELECT teacherID from queue WHERE studentID=? AND DATE_FORMAT(createTime,'%Y-%m-%d')=?) AND DATE_FORMAT(createTime,'%Y-%m-%d')=? AND status=? ORDER BY createTime)qu )a ,queue q,user u, teacher t WHERE u.ID=q.teacherID AND t.userID=q.teacherID AND a.ID=q.ID AND a.teacherID=q.teacherID AND q.studentID=?";
private static final String GET_TEACHER_QUEUE_PROCESS="SELECT IFNULL(t.onWork,false) AS onWork,t.maxStudentNum,IFNULL(cnt.count,0) AS totalQueueNum FROM teacher t LEFT JOIN (SELECT t.userID, COUNT(*) AS count FROM queue q RIGHT JOIN teacher t ON t.userID=q.teacherID Where DATE_FORMAT(q.createTime,'%Y-%m-%d')>=? GROUP BY t.userID) cnt ON t.userID=cnt.userID WHERE t.userID=?";
private static final String GET_QUEUE_INFO="SELECT q.ID,DATE_FORMAT(q.createTime,'%Y-%m-%d %H:%i') AS createTime,q.status,q.pictureNum,q.studentPath,q.studentComment,q.teacherPath,q.teacherComment,u.name AS teacherName FROM queue q, user u WHERE u.ID=q.teacherID AND q.studentID=? ORDER BY q.createTime LIMIT ?,?";
private static final String ADD_QUEUE="INSERT INTO queue(createTime,status,teacherID,studentID,pictureNum,studentPath,studentComment) VALUES(NOW(),?,?,?,?,?,?)";
private static final String RESOLVE_QUEUE="UPDATE queue SET status=?,teacherPath=?,teacherComment=? WHERE ID=?";
private static final String DELETE_QUEUE="DELETE FROM queue where studentID=? AND status=?";
private static final String IS_QUEUE_EXIST="SELECT ID FROM queue where studentID=? AND status='排队中' AND DATE_FORMAT(createTime,'%Y-%m-%d')>=?";
private static final String GET_TEACHER_COUNT="SELECT IFNULL(COUNT(*),0) FROM teacher";
private static final String GET_STUDENT_COUNT="SELECT IFNULL(COUNT(*),0) FROM queue WHERE status='排队中' AND teacherID=? AND DATE_FORMAT(createTime,'%Y-%m-%d')>=?";
private static final String ADD_EVALUATION="INSERT INTO performance(queueID,profLevel,attitude,perfComment) VALUES(?,?,?,?)";
private static final String EVALUATE_QUEUE="UPDATE queue SET status=? WHERE ID=?";
private static final String GET_PERFORMANCE="SELECT q.ID,u.name,q.studentPath,q.studentComment,q.teacherPath,q.teacherComment,p.profLevel,p.attitude,p.perfComment FROM user u,queue q,performance p WHERE u.ID=q.studentID AND p.queueID=q.ID AND q.teacherID=? LIMIT ?,?";
private static final String GET_TEACHERS_PERFORMANCE_FIELDS_PART="SELECT q.createTime,u.name AS studentName,us.name AS teacherName,us.ID ,q.studentPath,q.studentComment,q.teacherPath,q.teacherComment,p.profLevel,p.attitude,p.perfComment ";
private static final String GET_TEACHERS_PERFORMANCE_CONDITION_PART="FROM queue q LEFT JOIN user u ON u.ID=q.studentID LEFT JOIN user us ON us.ID=q.teacherID LEFT JOIN performance p ON q.ID=p.queueID WHERE q.status='已评价' ";
private static final String GET_TEACHER_PERFORMANCE_COUNT=" SELECT COUNT(*) FROM performance p ,queue q WHERE q.ID=p.queueID and q.teacherID=?";
private static final String GET_COUNT_PART="SELECT COUNT(*) ";
private static final Logger logger=Logger.getLogger(QueueDaoImpl.class);
@Override
public boolean queue(QueueItem queue) {
int l=queue.getStudentComment().length();
logger.debug("Begin to ADD_QUEUE");
int count=JdbcTemplate.update(ADD_QUEUE,Constant.STATUS_PENDING,queue.getTeacherID(),queue.getStudentID(),queue.getPictureNum(),queue.getStudentPath(),queue.getStudentComment());
logger.debug("complete to ADD_QUEUE..."+count);
return count>0;
}
@Override
public boolean resolveQueue(QueueItem queue) {
logger.debug("Begin to RESOLVE_QUEUE");
int count=JdbcTemplate.update(RESOLVE_QUEUE,Constant.STATUS_RESOLVE,queue.getTeacherPath(),queue.getTeacherComment(),queue.getID());
logger.debug("complete to RESOLVE_QUEUE..."+count);
return count>0;
}
@Override
public boolean cancelQueue(String id) {
logger.debug("Begin to DELETE_QUEUE");
int count=JdbcTemplate.update(DELETE_QUEUE,id,Constant.STATUS_PENDING);
logger.debug("complete to DELETE_QUEUE..."+count);
return count>0;
}
@Override
public Page<QueueItem> getTeacherStatus(Page<QueueItem> page) {
RowMapper<QueueItem> rowMapper=new BeanPropertyRowMapper<QueueItem>(QueueItem.class);
logger.debug("Begin to GET_TEACHER_STATUS");
List<QueueItem> queues=null;
queues = JdbcTemplate.query(GET_TEACHER_STATUS, rowMapper,Constant.STATUS_PENDING,StringUtils.getCurrDate(),StringUtils.getCurrDate(),Constant.TEACHER,page.getStartNum(),page.getPageSize());
logger.debug("complete to GET_TEACHER_STATUS...");
page.setRecords(queues);
return page;
}
@Override
public Page<QueueItem> getStudentStatus(String teacherID,Page<QueueItem> page) {
RowMapper<QueueItem> rowMapper=new BeanPropertyRowMapper<QueueItem>(QueueItem.class);
logger.debug("Begin to GET_STUDENT_STATUS");
List<QueueItem> queues= JdbcTemplate.query(GET_STUDENT_STATUS, rowMapper,teacherID,Constant.STATUS_PENDING,StringUtils.getCurrDate(),page.getStartNum(),page.getPageSize());
logger.debug("complete to GET_STUDENT_STATUS...");
page.setRecords(queues);
return page;
}
@Override
public boolean isQueued(String studentID) {
logger.debug("Begin to IS_QUEUE_EXIST");
Integer queueId;
try {
queueId = JdbcTemplate.queryForObject(IS_QUEUE_EXIST, Integer.class,studentID,StringUtils.getCurrDate());
} catch (EmptyResultDataAccessException e) {
return false;
}
logger.debug("complete to IS_QUEUE_EXIST...");
return queueId!=null;
}
@Override
public int getTeacherCount() {
logger.debug("Begin to GET_TEACHER_COUNT");
int count = JdbcTemplate.queryForObject(GET_TEACHER_COUNT, Integer.class);
logger.debug("complete to GET_TEACHER_COUNT...");
return count;
}
@Override
public int getStudentCount(String teacherID) {
logger.debug("Begin to GET_STUDENT_COUNT");
int count = JdbcTemplate.queryForObject(GET_STUDENT_COUNT, Integer.class,teacherID,StringUtils.getCurrDate());
logger.debug("complete to GET_STUDENT_COUNT...");
return count;
}
@Override
public QueueItem getStudentCurrentStatus(String id) {
RowMapper<QueueItem> rowMapper=new BeanPropertyRowMapper<QueueItem>(QueueItem.class);
logger.debug("Begin to GET_CURRENT_STUDENT_STATUS");
QueueItem queueItem=null;
try {
queueItem = JdbcTemplate.queryForObject(GET_CURRENT_STUDENT_STATUS, rowMapper,id,StringUtils.getCurrDate(),StringUtils.getCurrDate(),Constant.STATUS_PENDING,id);
} catch (DataAccessException e) {
logger.debug("no result when GET_CURRENT_STUDENT_STATUS...");
return null;
}
logger.debug("complete to GET_CURRENT_STUDENT_STATUS...");
return queueItem;
}
@Override
public Page<QueueItem> getQueueInfo(String id,Page<QueueItem> page) {
RowMapper<QueueItem> rowMapper=new BeanPropertyRowMapper<QueueItem>(QueueItem.class);
logger.debug("Begin to GET_QUEUE_INFO");
List<QueueItem> queues= JdbcTemplate.query(GET_QUEUE_INFO, rowMapper,id,page.getStartNum(),page.getPageSize());
logger.debug("complete to GET_QUEUE_INFO...");
page.setRecords(queues);
return page;
}
@Override
public QueueProcess getTeacherQueueProcess(String teacherID) {
RowMapper<QueueProcess> rowMapper=new BeanPropertyRowMapper<QueueProcess>(QueueProcess.class);
logger.debug("Begin to GET_TEACHER_QUEUE_PROCESS");
QueueProcess process = JdbcTemplate.queryForObject(GET_TEACHER_QUEUE_PROCESS, rowMapper,StringUtils.getCurrDate(),teacherID);
logger.debug("complete to GET_TEACHER_QUEUE_PROCESS...");
return process;
}
@Override
public boolean addEvaluation(QueueItem queue) {
logger.debug("Begin to ADD_EVALUATION");
int count=JdbcTemplate.update(ADD_EVALUATION,queue.getID(),queue.getProfLevel(),queue.getAttitude(),queue.getPerfComment());
logger.debug("complete to ADD_EVALUATION..."+count);
if (count>0) {
count=JdbcTemplate.update(EVALUATE_QUEUE,Constant.STATUS_EVALUATED,queue.getID());
}
return count>0;
}
@Override
public Page<QueueItem> getTeacherPerf(String ID,Page<QueueItem> page) {
RowMapper<QueueItem> rowMapper=new BeanPropertyRowMapper<QueueItem>(QueueItem.class);
logger.debug("Begin to GET_PERFORMANCE");
List<QueueItem> queues= JdbcTemplate.query(GET_PERFORMANCE, rowMapper,ID,page.getStartNum(),page.getPageSize());
logger.debug("complete to GET_PERFORMANCE...");
page.setRecords(queues);
return page;
}
@Override
public Page<QueueItem> getTeachersPerf(TeachersPerfQueryConditionDTO condition,Page<QueueItem> page) {
condition.setPagination(true);
DataSource dataSource=JdbcTemplate.getDataSource();
Connection conn=null;
PreparedStatement stmt=null;
ResultSet rs=null;
try {
conn=dataSource.getConnection();
condition.setPagination(true);
System.out.println(getTeachersPerfStatement(condition));
stmt=conn.prepareStatement(getTeachersPerfStatement(condition));
logger.debug("Begin to GET_PERFORMANCE_COUNT");
int i=0;
setStmtProp(condition, stmt, i);
rs=stmt.executeQuery();
if (rs.next()) {
int count=rs.getInt(1);
page.setTotalRecord(count);
}
stmt.close();
rs.close();
logger.debug("complete to GET_PERFORMANCE_COUNT...");
logger.debug("Begin to GET_PERFORMANCE");
condition.setPagination(false);
System.out.println(getTeachersPerfStatement(condition));
stmt=conn.prepareStatement(getTeachersPerfStatement(condition));
int j=0;
j=setStmtProp(condition, stmt, j);
stmt.setInt(++j, page.getStartNum());
System.out.println("stmt.setInt("+j+","+page.getStartNum()+");");
stmt.setInt(++j, page.getPageSize());
System.out.println("stmt.setInt("+j+","+page.getPageSize()+");");
rs=stmt.executeQuery();
List<QueueItem> queues=new ArrayList<QueueItem>();
while (rs.next()) {
QueueItem qItem=new QueueItem();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
qItem.setCreateTime(sdf.format(rs.getDate("createTime")));
qItem.setTeacherID(rs.getString("ID"));
qItem.setStudentName(rs.getString("studentName"));
qItem.setTeacherName(rs.getString("teacherName"));
qItem.setStudentPath(rs.getString("studentPath"));
qItem.setStudentComment(rs.getString("studentComment"));
qItem.setTeacherPath(rs.getString("teacherPath"));
qItem.setTeacherComment(rs.getString("teacherComment"));
qItem.setProfLevel(rs.getString("profLevel"));
qItem.setAttitude(rs.getString("attitude"));
qItem.setPerfComment(rs.getString("perfComment"));
queues.add(qItem);
}
page.setRecords(queues);
logger.debug("complete to GET_PERFORMANCE...");
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtil.release(rs, stmt, conn);
}
return page;
}
private int setStmtProp(TeachersPerfQueryConditionDTO condition, PreparedStatement stmt, int i)
throws SQLException {
if (null != condition.getID()) {
stmt.setString(++i, condition.getID());
System.out.println("stmt.setString("+i+","+condition.getID()+");");
}
if (!"".equals(condition.getStartCreateTime())&&!"".equals(condition.getEndCreateTime())&&null != condition.getStartCreateTime() && null != condition.getEndCreateTime()) {
stmt.setString(++i, condition.getStartCreateTime());
System.out.println("stmt.setString("+i+","+condition.getStartCreateTime()+");");
stmt.setString(++i, condition.getEndCreateTime());
System.out.println("stmt.setString("+i+","+condition.getEndCreateTime()+");");
}
if (null != condition.getLowTotalScore() && null != condition.getHighTotalScore()) {
stmt.setInt(++i, condition.getLowTotalScore());
System.out.println("stmt.setString("+i+","+condition.getLowTotalScore()+");");
stmt.setInt(++i, condition.getHighTotalScore());
System.out.println("stmt.setString("+i+","+condition.getHighTotalScore()+");");
}
return i;
}
@Override
public int getTeacherPerfCount(String ID) {
logger.debug("Begin to GET_TEACHER_PERFORMANCE_COUNT");
int count = JdbcTemplate.queryForObject(GET_TEACHER_PERFORMANCE_COUNT, Integer.class,ID);
logger.debug("complete to GET_TEACHER_PERFORMANCE_COUNT...");
return count;
}
private String getTeachersPerfStatement(TeachersPerfQueryConditionDTO condition) {
StringBuilder sb;
if (condition.isPagination()) {
sb = new StringBuilder(GET_COUNT_PART);
} else {
sb = new StringBuilder(GET_TEACHERS_PERFORMANCE_FIELDS_PART);
}
sb.append(GET_TEACHERS_PERFORMANCE_CONDITION_PART);
if (null != condition.getID()) {
sb.append("and us.ID=? ");
}
if (!"".equals(condition.getStartCreateTime())&&!"".equals(condition.getEndCreateTime())&&null != condition.getStartCreateTime() && null != condition.getEndCreateTime()) {
sb.append("and q.createTime>=? and q.createTime<=? ");
}
if (null != condition.getLowTotalScore() && null != condition.getHighTotalScore()) {
sb.append("and (p.attitude+p.profLevel)>=? and (p.attitude+p.profLevel)<=? ");
}
sb.append("ORDER BY (p.attitude+p.profLevel) ");
if (condition.isScoreAsc()) {
sb.append("Asc ");
} else {
sb.append("Desc ");
}
if (!condition.isPagination()) {
sb.append(",q.createTime Desc LIMIT ?,?");
}
String sqlStatement=sb.toString();
return sqlStatement;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.alexander.mainstuff.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* @author user
*/
@Entity
public class SecondLanguage {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private long id_first;
private String word;
private int points_knowledge;
private int points_transcription;
private String forms;
public SecondLanguage(){
}
public SecondLanguage(long id, long id_first, String word, int points_knowledge, int points_transcription, String forms) {
this.id = id;
this.id_first = id_first;
this.word = word;
this.points_knowledge = points_knowledge;
this.points_transcription = points_transcription;
this.forms = forms;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getId_first() {
return id_first;
}
public void setId_first(long id_first) {
this.id_first = id_first;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public int getPoints_knowledge() {
return points_knowledge;
}
public void setPoints_knowledge(int points_knowledge) {
this.points_knowledge = points_knowledge;
}
public int getPoints_transcription() {
return points_transcription;
}
public void setPoints_transcription(int points_transcription) {
this.points_transcription = points_transcription;
}
public String getForms() {
return forms;
}
public void setForms(String forms) {
this.forms = forms;
}
@Override
public String toString() {
return "SecondLanguage{" + "id=" + id + ", id_first=" + id_first + ", word=" + word + ", points_knowledge=" + points_knowledge + ", points_transcription=" + points_transcription + ", forms=" + forms + '}';
}
}
|
/*
* Created by Angel Leon (@gubatron), Alden Torres (aldenml)
* Copyright (c) 2011-2014, FrostWire(R). All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.frostwire.gui.library;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.limewire.concurrent.ExecutorsHelper;
import org.limewire.util.FileUtils;
import org.limewire.util.FilenameUtils;
import org.limewire.util.StringUtils;
import com.frostwire.alexandria.IcyInputStream;
import com.frostwire.alexandria.IcyInputStream.Track;
import com.frostwire.alexandria.InternetRadioStation;
import com.frostwire.alexandria.Playlist;
import com.frostwire.alexandria.PlaylistItem;
import com.frostwire.alexandria.db.LibraryDatabase;
import com.frostwire.gui.bittorrent.TorrentUtil;
import com.frostwire.gui.library.LibraryPlaylistsTableTransferable.Item;
import com.frostwire.gui.library.tags.TagsData;
import com.frostwire.gui.library.tags.TagsReader;
import com.frostwire.gui.player.MediaPlayer;
import com.frostwire.gui.theme.ThemeMediator;
import com.frostwire.uxstats.UXAction;
import com.frostwire.uxstats.UXStats;
import com.limegroup.gnutella.gui.GUIMediator;
import com.limegroup.gnutella.gui.I18n;
/**
* @author gubatron
* @author aldenml
*
*/
public class LibraryUtils {
public static final Icon FILE_UNSHARED_ICON;
public static final Icon FILE_SHARING_ICON;
public static final Icon FILE_SHARED_ICON;
static {
FILE_UNSHARED_ICON = GUIMediator.getThemeImage("file_unshared");
FILE_SHARING_ICON = GUIMediator.getThemeImage("file_sharing");
FILE_SHARED_ICON = GUIMediator.getThemeImage("file_shared");
}
private static final Log LOG = LogFactory.getLog(LibraryUtils.class);
private static final ExecutorService executor;
static {
executor = ExecutorsHelper.newProcessingQueue("LibraryUtils-Executor");
}
private static void addPlaylistItem(Playlist playlist, File file, boolean starred) {
addPlaylistItem(playlist, file, starred, -1);
}
private static void addPlaylistItem(Playlist playlist, File file, boolean starred, int index) {
try {
LibraryMediator.instance().getLibrarySearch().pushStatus(I18n.tr("Importing") + " " + file.getName());
TagsData mt = new TagsReader(file).parse();
PlaylistItem item = playlist.newItem(file.getAbsolutePath(), file.getName(), file.length(), FileUtils.getFileExtension(file), mt.getTitle(), mt.getDuration(), mt.getArtist(), mt.getAlbum(), "",// TODO: cover art path
mt.getBitrate(), mt.getComment(), mt.getGenre(), mt.getTrack(), mt.getYear(), starred);
List<PlaylistItem> items = playlist.getItems();
if (index != -1 && index < items.size()) {
// insert item
items.add(index, item);
// update all sort indexes from insertion point onwards
for (int i = index; i < items.size(); i++) {
PlaylistItem cur_item = items.get(i);
cur_item.setSortIndex(i + 1); //set index 1-based
cur_item.save();
}
} else {
items.add(item);
item.setSortIndex(items.size()); // set sort index to 1-based size
item.save();
}
if (isPlaylistSelected(playlist)) {
// refresh UI
LibraryMediator.instance().getLibraryPlaylists().refreshSelection();
}
} finally {
LibraryMediator.instance().getLibrarySearch().revertStatus();
}
}
public static String getSecondsInDDHHMMSS(int s) {
if (s < 0) {
s = 0;
}
StringBuilder result = new StringBuilder();
String DD = "";
String HH = "";
String MM = "";
String SS = "";
//math
int days = s / 86400;
int r = s % 86400;
int hours = r / 3600;
r = s % 3600;
int minutes = r / 60;
int seconds = r % 60;
//padding
DD = String.valueOf(days);
HH = (hours < 10) ? "0" + hours : String.valueOf(hours);
MM = (minutes < 10) ? "0" + minutes : String.valueOf(minutes);
SS = (seconds < 10) ? "0" + seconds : String.valueOf(seconds);
//lazy formatting
if (days > 0) {
result.append(DD);
result.append(" day");
if (days > 1) {
result.append("s");
}
return result.toString();
}
if (hours > 0) {
result.append(HH);
result.append(":");
}
result.append(MM);
result.append(":");
result.append(SS);
return result.toString();
}
public static void createNewPlaylist(final List<? extends AbstractLibraryTableDataLine<?>> lines) {
String playlistName = (String) ThemeMediator.showInputDialog(GUIMediator.getAppFrame(), I18n.tr("Playlist name"), I18n.tr("Playlist name"), JOptionPane.PLAIN_MESSAGE, null, null, suggestPlaylistName(lines));
if (playlistName != null && playlistName.length() > 0) {
final Playlist playlist = LibraryMediator.getLibrary().newPlaylist(playlistName, playlistName);
playlist.save();
LibraryMediator.instance().getLibraryPlaylists().addPlaylist(playlist);
LibraryMediator.instance().getLibraryPlaylists().markBeginImport(playlist);
Thread t = new Thread(new Runnable() {
public void run() {
addToPlaylist(playlist, lines);
playlist.save();
asyncAddToPlaylistFinalizer(playlist);
}
}, "createNewPlaylist");
t.setDaemon(true);
t.start();
UXStats.instance().log(UXAction.LIBRARY_PLAYLIST_CREATED);
}
}
public static void createNewPlaylist(File[] files) {
createNewPlaylist(files, false);
}
public static void createNewPlaylist(final File[] files, final boolean starred) {
final StringBuilder plBuilder = new StringBuilder();
// GUIMediator.safeInvokeAndWait(new Runnable() {
//
// @Override
// public void run() {
String input = (String) ThemeMediator.showInputDialog(GUIMediator.getAppFrame(), I18n.tr("Playlist name"), I18n.tr("Playlist name"), JOptionPane.PLAIN_MESSAGE, null, null, suggestPlaylistName(files));
if (!StringUtils.isNullOrEmpty(input, true)) {
plBuilder.append(input);
}
// }
// });
String playlistName = plBuilder.toString();
if (playlistName != null && playlistName.length() > 0) {
GUIMediator.instance().setWindow(GUIMediator.Tabs.LIBRARY);
final Playlist playlist = LibraryMediator.getLibrary().newPlaylist(playlistName, playlistName);
playlist.save();
GUIMediator.safeInvokeLater(new Runnable() {
@Override
public void run() {
LibraryMediator.instance().getLibraryPlaylists().addPlaylist(playlist);
LibraryMediator.instance().getLibraryPlaylists().markBeginImport(playlist);
}
});
Thread t = new Thread(new Runnable() {
public void run() {
try {
Set<File> ignore = TorrentUtil.getIgnorableFiles();
addToPlaylist(playlist, files, starred, ignore);
playlist.save();
} finally {
asyncAddToPlaylistFinalizer(playlist);
}
}
}, "createNewPlaylist");
t.setDaemon(true);
t.start();
UXStats.instance().log(UXAction.LIBRARY_PLAYLIST_CREATED);
}
}
public static void createNewPlaylist(final PlaylistItem[] playlistItems) {
createNewPlaylist(playlistItems, false);
}
public static void createNewPlaylist(final PlaylistItem[] playlistItems, boolean starred) {
if (starred) {
createStarredPlaylist(playlistItems);
} else {
String playlistName = (String) ThemeMediator.showInputDialog(GUIMediator.getAppFrame(), I18n.tr("Playlist name"), I18n.tr("Playlist name"), JOptionPane.PLAIN_MESSAGE, null, null, suggestPlaylistName(playlistItems));
if (playlistName != null && playlistName.length() > 0) {
final Playlist playlist = LibraryMediator.getLibrary().newPlaylist(playlistName, playlistName);
Thread t = new Thread(new Runnable() {
public void run() {
try {
playlist.save();
addToPlaylist(playlist, playlistItems);
playlist.save();
GUIMediator.safeInvokeLater(new Runnable() {
public void run() {
LibraryMediator.instance().getLibraryPlaylists().addPlaylist(playlist);
}
});
} finally {
asyncAddToPlaylistFinalizer(playlist);
}
}
}, "createNewPlaylist");
t.setDaemon(true);
t.start();
}
}
UXStats.instance().log(UXAction.LIBRARY_PLAYLIST_CREATED);
}
private static void createStarredPlaylist(final PlaylistItem[] playlistItems) {
Thread t = new Thread(new Runnable() {
public void run() {
Playlist playlist = LibraryMediator.getLibrary().getStarredPlaylist();
addToPlaylist(playlist, playlistItems, true, -1);
GUIMediator.safeInvokeLater(new Runnable() {
public void run() {
DirectoryHolder dh = LibraryMediator.instance().getLibraryExplorer().getSelectedDirectoryHolder();
if (dh instanceof StarredDirectoryHolder) {
LibraryMediator.instance().getLibraryExplorer().refreshSelection();
} else {
LibraryMediator.instance().getLibraryExplorer().selectStarred();
}
}
});
}
}, "createNewPlaylist");
t.setDaemon(true);
t.start();
}
public static void createNewPlaylist(File m3uFile) {
createNewPlaylist(m3uFile, false);
}
public static void createNewPlaylist(File m3uFile, boolean starred) {
try {
List<File> files = M3UPlaylist.load(m3uFile.getAbsolutePath());
createNewPlaylist(files.toArray(new File[0]), starred);
UXStats.instance().log(UXAction.LIBRARY_PLAYLIST_CREATED);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void asyncAddToPlaylist(final Playlist playlist, final List<? extends AbstractLibraryTableDataLine<?>> lines) {
LibraryMediator.instance().getLibraryPlaylists().markBeginImport(playlist);
Thread t = new Thread(new Runnable() {
public void run() {
try {
addToPlaylist(playlist, lines);
} finally {
asyncAddToPlaylistFinalizer(playlist);
}
}
}, "asyncAddToPlaylist");
t.setDaemon(true);
t.start();
}
public static void asyncAddToPlaylist(Playlist playlist, File[] files) {
asyncAddToPlaylist(playlist, files, -1);
}
public static void asyncAddToPlaylist(final Playlist playlist, final File[] files, final int index) {
LibraryMediator.instance().getLibraryPlaylists().markBeginImport(playlist);
Thread t = new Thread(new Runnable() {
public void run() {
try {
Set<File> ignore = TorrentUtil.getIgnorableFiles();
addToPlaylist(playlist, files, false, index, ignore);
playlist.save();
} finally {
asyncAddToPlaylistFinalizer(playlist);
}
}
}, "asyncAddToPlaylist");
t.setDaemon(true);
t.start();
}
private static void asyncAddToPlaylistFinalizer(final Playlist playlist) {
GUIMediator.safeInvokeLater(new Runnable() {
public void run() {
LibraryMediator.instance().getLibraryPlaylists().markEndImport(playlist);
LibraryMediator.instance().getLibraryPlaylists().refreshSelection();
LibraryMediator.instance().getLibraryPlaylists().selectPlaylist(playlist);
}
});
}
public static void asyncAddToPlaylist(Playlist playlist, PlaylistItem[] playlistItems) {
asyncAddToPlaylist(playlist, playlistItems, -1);
}
public static void asyncAddToPlaylist(final Playlist playlist, final PlaylistItem[] playlistItems, final int index) {
Thread t = new Thread(new Runnable() {
public void run() {
addToPlaylist(playlist, playlistItems, index);
playlist.save();
GUIMediator.safeInvokeLater(new Runnable() {
public void run() {
LibraryMediator.instance().getLibraryPlaylists().refreshSelection();
}
});
}
}, "asyncAddToPlaylist");
t.setDaemon(true);
t.start();
}
public static void asyncAddToPlaylist(Playlist playlist, File m3uFile) {
asyncAddToPlaylist(playlist, m3uFile, -1);
}
public static void asyncAddToPlaylist(Playlist playlist, File m3uFile, int index) {
try {
List<File> files = M3UPlaylist.load(m3uFile.getAbsolutePath());
asyncAddToPlaylist(playlist, files.toArray(new File[0]), index);
} catch (Exception e) {
e.printStackTrace();
}
}
public static List<LibraryPlaylistsTableTransferable.Item> convertToItems(List<PlaylistItem> playlistItems) {
List<LibraryPlaylistsTableTransferable.Item> items = new ArrayList<LibraryPlaylistsTableTransferable.Item>(playlistItems.size());
for (PlaylistItem playlistItem : playlistItems) {
Item item = new LibraryPlaylistsTableTransferable.Item();
item.id = playlistItem.getId();
item.filePath = playlistItem.getFilePath();
item.fileName = playlistItem.getFileName();
item.fileSize = playlistItem.getFileSize();
item.fileExtension = playlistItem.getFileExtension();
item.trackTitle = playlistItem.getTrackTitle();
item.trackDurationInSecs = playlistItem.getTrackDurationInSecs();
item.trackArtist = playlistItem.getTrackArtist();
item.trackAlbum = playlistItem.getTrackAlbum();
item.coverArtPath = playlistItem.getCoverArtPath();
item.trackBitrate = playlistItem.getTrackBitrate();
item.trackComment = playlistItem.getTrackComment();
item.trackGenre = playlistItem.getTrackGenre();
item.trackNumber = playlistItem.getTrackNumber();
item.trackYear = playlistItem.getTrackYear();
item.starred = playlistItem.isStarred();
items.add(item);
}
return items;
}
public static PlaylistItem[] convertToPlaylistItems(LibraryPlaylistsTableTransferable.Item[] items) {
List<PlaylistItem> playlistItems = new ArrayList<PlaylistItem>(items.length);
for (LibraryPlaylistsTableTransferable.Item item : items) {
PlaylistItem playlistItem = new PlaylistItem(null, item.id, item.filePath, item.fileName, item.fileSize, item.fileExtension, item.trackTitle, item.trackDurationInSecs, item.trackArtist, item.trackAlbum, item.coverArtPath, item.trackBitrate, item.trackComment, item.trackGenre,
item.trackNumber, item.trackYear, item.starred);
playlistItems.add(playlistItem);
}
return playlistItems.toArray(new PlaylistItem[0]);
}
public static PlaylistItem[] convertToPlaylistItems(LibraryPlaylistsTableTransferable.PlaylistItemContainer itemContainer) {
List<PlaylistItem> playlistItems = new ArrayList<PlaylistItem>(itemContainer.items.size());
for (LibraryPlaylistsTableTransferable.Item item : itemContainer.items) {
PlaylistItem playlistItem = new PlaylistItem(null, item.id, item.filePath, item.fileName, item.fileSize, item.fileExtension, item.trackTitle, item.trackDurationInSecs, item.trackArtist, item.trackAlbum, item.coverArtPath, item.trackBitrate, item.trackComment, item.trackGenre,
item.trackNumber, item.trackYear, item.starred);
playlistItems.add(playlistItem);
}
return playlistItems.toArray(new PlaylistItem[0]);
}
public static File[] convertToFiles(PlaylistItem[] items) {
List<File> files = new ArrayList<File>(items.length);
for (PlaylistItem item : items) {
files.add(new File(item.getFilePath()));
}
return files.toArray(new File[0]);
}
private static void addToPlaylist(Playlist playlist, List<? extends AbstractLibraryTableDataLine<?>> lines) {
for (int i = 0; i < lines.size() && !playlist.isDeleted(); i++) {
AbstractLibraryTableDataLine<?> line = lines.get(i);
if (MediaPlayer.isPlayableFile(line.getFile())) {
LibraryUtils.addPlaylistItem(playlist, line.getFile(), false);
}
}
}
private static int addToPlaylist(Playlist playlist, File[] files, boolean starred, Set<File> ignore) {
return addToPlaylist(playlist, files, starred, -1, ignore);
}
private static int addToPlaylist(Playlist playlist, File[] files, boolean starred, int index, Set<File> ignore) {
int count = 0;
for (int i = 0; i < files.length && !playlist.isDeleted(); i++) {
if (MediaPlayer.isPlayableFile(files[i]) && !ignore.contains(files[i])) {
LibraryUtils.addPlaylistItem(playlist, files[i], starred, index + count);
count++;
} else if (files[i].isDirectory()) {
count += addToPlaylist(playlist, files[i].listFiles(), starred, index + count, ignore);
}
}
return count;
}
private static void addToPlaylist(Playlist playlist, PlaylistItem[] playlistItems) {
addToPlaylist(playlist, playlistItems, false, -1);
}
private static void addToPlaylist(Playlist playlist, PlaylistItem[] playlistItems, int index) {
addToPlaylist(playlist, playlistItems, false, index);
}
private static void addToPlaylist(Playlist playlist, PlaylistItem[] playlistItems, boolean starred, int index) {
List<PlaylistItem> items = playlist.getItems();
if (index != -1 && index <= items.size()) {
List<Integer> toRemove = new ArrayList<Integer>(playlistItems.length);
for (int i = 0; i < playlistItems.length && !playlist.isDeleted(); i++) {
toRemove.add(playlistItems[i].getId());
playlistItems[i].setId(LibraryDatabase.OBJECT_NOT_SAVED_ID);
playlistItems[i].setPlaylist(playlist);
items.add(index + i, playlistItems[i]);
if (starred) {
playlistItems[i].setStarred(starred);
playlistItems[i].save();
}
}
for (int i = 0; i < toRemove.size() && !playlist.isDeleted(); i++) {
int id = toRemove.get(i);
for (int j = 0; j < items.size() && !playlist.isDeleted(); j++) {
if (items.get(j).getId() == id) {
items.remove(j);
break;
}
}
}
// reupdate sort indexes now that the ordering in the list is correct
items = playlist.getItems();
for (int i = 0; i < items.size(); i++) {
PlaylistItem item = items.get(i);
item.setSortIndex(i + 1); // set index 1-based
item.save();
}
} else {
for (int i = 0; i < playlistItems.length && !playlist.isDeleted(); i++) {
playlistItems[i].setPlaylist(playlist);
items.add(playlistItems[i]);
playlistItems[i].setSortIndex(items.size()); // set sort index to be at the end (1-based)
if (starred) {
playlistItems[i].setStarred(starred);
}
playlistItems[i].save();
}
}
}
public static String getPlaylistDurationInDDHHMMSS(Playlist playlist) {
List<PlaylistItem> items = playlist.getItems();
float totalSecs = 0;
for (PlaylistItem item : items) {
totalSecs += item.getTrackDurationInSecs();
}
return getSecondsInDDHHMMSS((int) totalSecs);
}
public static boolean directoryContainsAudio(File directory, int depth) {
Set<File> ignore = TorrentUtil.getIgnorableFiles();
return directoryContainsExtension(directory, depth, ignore, MediaPlayer.getPlayableExtensions());
}
public static boolean directoryContainsAudio(File directory) {
Set<File> ignore = TorrentUtil.getIgnorableFiles();
return directoryContainsExtension(directory, 4, ignore, MediaPlayer.getPlayableExtensions());
}
public static boolean directoryContainsExtension(File directory, int depth, String extensionWithoutDot) {
Set<File> ignore = TorrentUtil.getIgnorableFiles();
return directoryContainsExtension(directory, depth, ignore, extensionWithoutDot);
}
public static boolean directoryContainsExtension(File directory, String... extensionWithoutDot) {
Set<File> ignore = TorrentUtil.getIgnorableFiles();
return directoryContainsExtension(directory, 4, ignore, extensionWithoutDot);
}
private static boolean directoryContainsExtension(File directory, int depth, Set<File> ignore, String... extensionWithoutDot) {
try {
if (directory == null || !directory.isDirectory()) {
return false;
}
for (File childFile : directory.listFiles()) {
if (!childFile.isDirectory()) {
if (FilenameUtils.hasExtension(childFile.getAbsolutePath(), extensionWithoutDot) && !ignore.contains(childFile)) {
return true;
}
} else {
if (depth > 0) {
if (directoryContainsExtension(childFile, depth - 1, ignore, extensionWithoutDot)) {
return true;
}
}
}
}
} catch (NullPointerException e) {
// NPE reported in bug manager, ignore until refactor
}
return false;
}
private static String suggestPlaylistName(File[] mediaFiles) {
HistoHashMap<String> artistNames = new HistoHashMap<String>();
HistoHashMap<String> artistsAlbums = new HistoHashMap<String>();
HistoHashMap<String> albumNames = new HistoHashMap<String>();
HistoHashMap<String> genres = new HistoHashMap<String>();
for (File mf : mediaFiles) {
if (MediaPlayer.isPlayableFile(mf)) {
TagsData mt = new TagsReader(mf).parse();
artistNames.update(mt.getArtist());
artistsAlbums.update(mt.getArtist() + " - " + mt.getAlbum());
albumNames.update(mt.getAlbum());
genres.update("(" + mt.getGenre() + ")");
}
}
Entry<String, Integer>[] histogramArtistNames = artistNames.histogram();
Entry<String, Integer>[] histogramArtistsAlbums = artistsAlbums.histogram();
Entry<String, Integer>[] histogramAlbumNames = albumNames.histogram();
Entry<String, Integer>[] histogramGenres = genres.histogram();
String topArtistName = histogramArtistNames[histogramArtistNames.length-1].getKey();
int topArtistNameCount = histogramArtistNames[histogramArtistNames.length-1].getValue();
String topArtistAlbum = histogramArtistsAlbums[histogramArtistsAlbums.length-1].getKey();
int topArtistAlbumCount = histogramArtistsAlbums[histogramArtistsAlbums.length-1].getValue();
String topAlbumName = histogramAlbumNames[histogramAlbumNames.length-1].getKey();
int topAlbumNameCount = histogramAlbumNames[histogramAlbumNames.length-1].getValue();
String topGenre = histogramGenres[histogramGenres.length-1].getKey();
String suggestedPlaylistName = topArtistName;
if (topArtistAlbumCount >= topArtistNameCount) {
suggestedPlaylistName = topArtistAlbum;
} else if (topAlbumNameCount >= topArtistNameCount) {
suggestedPlaylistName = topAlbumName;
if (topArtistNameCount > 3) {
suggestedPlaylistName = topArtistName + " - " + suggestedPlaylistName;
}
}
if (!topGenre.equals("()")) {
suggestedPlaylistName = suggestedPlaylistName + " " + topGenre;
}
return suggestedPlaylistName;
}
private static String suggestPlaylistName(List<? extends AbstractLibraryTableDataLine<?>> lines) {
File[] files = new File[lines.size()];
for (int i = 0; i < lines.size(); i++) {
files[i] = lines.get(i).getFile();
}
return suggestPlaylistName(files);
}
private static String suggestPlaylistName(PlaylistItem[] playlistItems) {
File[] files = new File[playlistItems.length];
for (int i = 0; i < files.length; i++) {
files[i] = new File(playlistItems[i].getFilePath());
}
return suggestPlaylistName(files);
}
public static void cleanup(Playlist playlist) {
if (playlist == null) {
return;
}
try {
for (PlaylistItem item : playlist.getItems()) {
if (!new File(item.getFilePath()).exists()) {
item.delete();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void refreshID3Tags(Playlist playlist) {
refreshID3Tags(playlist, playlist.getItems());
}
public static void refreshID3Tags(final Playlist playlist, final List<PlaylistItem> items) {
executor.execute(new Runnable() {
public void run() {
for (PlaylistItem item : items) {
try {
LibraryMediator.instance().getLibrarySearch().pushStatus(I18n.tr("Refreshing") + " " + item.getTrackAlbum() + " - " + item.getTrackTitle());
File file = new File(item.getFilePath());
if (file.exists()) {
TagsData mt = new TagsReader(file).parse();
LibraryMediator.getLibrary().updatePlaylistItemProperties(item.getFilePath(), mt.getTitle(), mt.getArtist(), mt.getAlbum(), mt.getComment(), mt.getGenre(), mt.getTrack(), mt.getYear());
}
} catch (Exception e) {
// ignore, skip
} finally {
LibraryMediator.instance().getLibrarySearch().revertStatus();
}
}
GUIMediator.safeInvokeLater(new Runnable() {
public void run() {
if (playlist != null) {
if (playlist.getId() == LibraryDatabase.STARRED_PLAYLIST_ID) {
DirectoryHolder dh = LibraryMediator.instance().getLibraryExplorer().getSelectedDirectoryHolder();
if (dh instanceof StarredDirectoryHolder) {
LibraryMediator.instance().getLibraryExplorer().refreshSelection();
}
} else {
Playlist selectedPlaylist = LibraryMediator.instance().getLibraryPlaylists().getSelectedPlaylist();
if (selectedPlaylist != null && selectedPlaylist.equals(playlist)) {
LibraryMediator.instance().getLibraryPlaylists().refreshSelection();
}
}
}
}
});
}
});
}
private static boolean isPlaylistSelected(Playlist playlist) {
Playlist selectedPlaylist = LibraryMediator.instance().getLibraryPlaylists().getSelectedPlaylist();
return selectedPlaylist != null && selectedPlaylist.equals(playlist);
}
public static boolean isRefreshKeyEvent(KeyEvent e) {
int keyCode = e.getKeyCode();
boolean ctrlCmdDown = e.isControlDown() || e.isAltGraphDown() || e.isMetaDown();
return keyCode == KeyEvent.VK_F5 || (ctrlCmdDown && keyCode == KeyEvent.VK_R);
}
public static void asyncAddRadioStation(final String url) {
Thread t = new Thread(new Runnable() {
public void run() {
addRadioStation(url);
}
}, "ImportRadioStation");
t.setDaemon(true);
t.start();
}
public static void addRadioStation(final String url) {
try {
LibraryMediator.instance().getLibrarySearch().pushStatus(I18n.tr("Importing from") + " " + url);
final InternetRadioStation item = processInternetRadioStationUrl(url);
item.save();
GUIMediator.safeInvokeLater(new Runnable() {
@Override
public void run() {
LibraryInternetRadioTableMediator.instance().addUnsorted(item);
LibraryMediator.instance().getLibraryExplorer().selectRadio();
LibraryInternetRadioTableMediator.instance().selectItemAt(0);
}
});
} catch (Throwable e) {
LOG.error("Error adding radio station", e);
GUIMediator.safeInvokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(GUIMediator.getAppFrame(), I18n.tr("Error importing Radio Station from") + " " + url, I18n.tr("Error"), JOptionPane.ERROR_MESSAGE);
}
});
} finally {
LibraryMediator.instance().getLibrarySearch().revertStatus();
}
}
private static InternetRadioStation processInternetRadioStationUrl(String urlStr) throws Exception {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(10000);
conn.setRequestProperty("User-Agent", "Java");
InputStream is = conn.getInputStream();
BufferedReader d = null;
if (conn.getContentEncoding() != null) {
d = new BufferedReader(new InputStreamReader(is, conn.getContentEncoding()));
} else {
d = new BufferedReader(new InputStreamReader(is, "UTF-8"));
}
String pls = "";
String[] props = null;
String strLine;
int numLine = 0;
while ((strLine = d.readLine()) != null) {
pls += strLine + "\n";
if (strLine.startsWith("File1=")) {
String streamUrl = strLine.split("=")[1];
props = processStreamUrl(streamUrl);
} else if (strLine.startsWith("icy-name:")) {
pls = "";
props = processStreamUrl(urlStr);
break;
}
numLine++;
if (numLine > 10) {
if (props == null) { // not a valid pls
break;
}
}
}
is.close();
if (props != null && props[0] != null) {
return LibraryMediator.getLibrary().newInternetRadioStation(props[0], props[0], props[1], props[2], props[3], props[4], props[5], pls, false);
} else {
return null;
}
}
private static String[] processStreamUrl(String streamUrl) throws Exception {
Track t = new Track();
IcyInputStream.create(streamUrl, t);
String name = clean(t.name);
String genre = clean(t.genre);
String website = clean(t.url);
String type = "";
String br = t.bitrate != null ? t.bitrate.trim() + " kbps" : "";
String contentType = t.contentType;
if (contentType.equals("audio/aacp")) {
type = "AAC+";
} else if (contentType.equals("audio/mpeg")) {
type = "MP3";
} else if (contentType.equals("audio/aac")) {
type = "AAC";
}
return new String[] { name, streamUrl, br, type, website, genre };
}
private static String clean(String str) {
return str.trim().replace("\"", "\\\"");
}
public static void movePlaylistItemsToIndex(Playlist playlist, int[] selectedIndexes, int index) {
List<PlaylistItem> items = playlist.getItems();
int targetIndex = index;
// first, order items in list correctly
for (int i = 0; i < selectedIndexes.length; i++) {
int sourceIndex = selectedIndexes[i];
if (sourceIndex != targetIndex) {
items.add(targetIndex, items.get(sourceIndex));
items.remove(sourceIndex < targetIndex ? sourceIndex : sourceIndex + 1);
// adjust remaining selected indexes if insertion point is greater than their location
for (int j = i + 1; j < selectedIndexes.length; j++) {
if (targetIndex > selectedIndexes[j]) {
selectedIndexes[j]--;
}
}
// update insertion point
if (sourceIndex > targetIndex) {
targetIndex++;
}
}
}
// second, generate new indexes based list order
for (int i = 0; i < items.size(); i++) {
PlaylistItem item = items.get(i);
item.setSortIndex(i + 1); // set index (1-based)
item.save();
}
// initiate UI refresh
GUIMediator.safeInvokeLater(new Runnable() {
public void run() {
LibraryMediator.instance().getLibraryPlaylists().refreshSelection();
}
});
}
}
|
package com.darg.NLPOperations.sentimentalAnalysis.test;
import static org.junit.Assert.*;
import org.junit.Test;
import java.util.ArrayList;
import org.junit.BeforeClass;
import com.darg.NLPOperations.dictionary.SentiWordNetDictionary;
import com.darg.NLPOperations.dictionary.WordNetDictionary;
import com.darg.NLPOperations.dictionary.model.SentiWordNet;
import com.darg.NLPOperations.dictionary.model.WordNet;
import com.darg.NLPOperations.pos.model.TaggedWord;
import com.darg.NLPOperations.pos.util.POSTagEnglish;
import com.darg.NLPOperations.sentimentalAnalysis.AverageScoreSentimentAnalyzer;
import com.darg.NLPOperations.sentimentalAnalysis.model.SentimentScore;
public class SentimentalAnalysisTest
{
public static SentiWordNetDictionary dict = SentiWordNetDictionary.getInstance("/home/erhan/Desktop/TEST-FOR-THESIS/sentiwordnet/SentiWordNet_3.0.0_20130122.txt",
SentiWordNet.VERSION_30, true);
private static String path = "/home/erhan/Desktop/TEST-FOR-THESIS/WordNet-3.0/dict";
private static WordNetDictionary dict2 = WordNetDictionary.getInstance(path , WordNet.VERSION_30);
/*----------------------------------------------------------------------------------*/
//
/*----------------------------------------------------------------------------------*/
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
if(!dict.loadDictionary())
{
fail("cannot load the sentiwordnet library");
}
if(!dict2.loadDictionary())
{
fail("cannot load the wordnet library");
}
System.out.println("adjectives: " + dict.getAdjectiveCount());
System.out.println("nouns: " + dict.getNounCount());
System.out.println("adverbs: " + dict.getAdverbCount());
System.out.println("verbs: " + dict.getVerbCount());
System.out.println("total words: " + dict.getWordCount());
}
@Test
public void documentBasedAnalysisTest()
{
ArrayList<TaggedWord> list = new ArrayList<TaggedWord>();
list.add(new TaggedWord("i" , POSTagEnglish.NN, "NN"));
list.add(new TaggedWord("was" , POSTagEnglish.VB, "VB"));
list.add(new TaggedWord("unable" , POSTagEnglish.JJR, "JJR"));
list.add(new TaggedWord("to" , POSTagEnglish.TO, "TO"));
list.add(new TaggedWord("test" , POSTagEnglish.VBD, "VBD"));
list.add(new TaggedWord("the" , POSTagEnglish.IN, "IN"));
list.add(new TaggedWord("code" , POSTagEnglish.NN, "NN"));
list.add(new TaggedWord("." , POSTagEnglish.DOT, "."));
AverageScoreSentimentAnalyzer analyzer = new AverageScoreSentimentAnalyzer(dict2, dict);
SentimentScore score = analyzer.documentBasedAnalysis(list, false);
if(score != null)
{
assertEquals(4 , score.getWordsFound());
assertEquals(8 , score.getWordCount());
System.out.println("pos=" + score.getPositiveProb());
System.out.println("neg=" + score.getNegativeProb());
System.out.println("obj=" + score.getObjectiveProb());
System.out.println("found=" + score.getWordsFound());
System.out.println("count=" + score.getWordCount());
fail("control manually");
}
else
{
fail("cannot calculate the score");
}
}
}
|
import DataStorageLayer.DAOAccount;
import DataStorageLayer.DatabaseConnection;
import org.junit.jupiter.api.Test;
import java.sql.ResultSet;
import java.sql.SQLException;
import static DataStorageLayer.DAOAccount.ACCOUNT_ID;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class DAO_Account_Test {
private static ResultSet resultSet;
@Test
void getLatestAccount() {
int DAOaccountid = 0;
DatabaseConnection.connect();
try {
resultSet = DatabaseConnection.getStatementResult(DAOAccount.getMostRecentAccount());
if (resultSet.next()) {
DAOaccountid = resultSet.getInt(ACCOUNT_ID);
}
} catch (SQLException e) {
}
assertTrue(isExecuted(), "The Method failed to pull the data");
}
private static boolean isExecuted() {
if (resultSet == null){
return false;
} else return true;
}
}
|
package com.mercadolibre.bootcampmelifrescos.exceptions.api;
import org.springframework.http.HttpStatus;
public class NotFoundApiException extends ApiException {
private final static String CODE = "NOT_FOUND";
private final static Integer STATUS_CODE = HttpStatus.NOT_FOUND.value();
public NotFoundApiException() {
super(CODE, CODE, STATUS_CODE);
}
public NotFoundApiException(String description) {
super(CODE, description, STATUS_CODE);
}
} |
package com.android.albumslist;
import com.android.albumslist.adapter.AlbumsAdapter;
import com.android.albumslist.api.Api;
import com.android.albumslist.api.Client;
import com.android.albumslist.model.Album;
import com.android.albumslist.view.AlbumsListActivity;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.util.ActivityController;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Callback;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
@Config(constants = BuildConfig.class, sdk = 21,
manifest = "app/src/main/AndroidManifest.xml")
@RunWith(RobolectricGradleTestRunner.class)
public class AlbumsListCallTest {
private AlbumsListActivity mainActivity;
@Mock
private Api mockRetrofitApiImpl;
@Captor
private ArgumentCaptor<Callback<List<Album>>> callbackArgumentCaptor;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ActivityController<AlbumsListActivity> controller = Robolectric.buildActivity(AlbumsListActivity.class);
mainActivity = controller.get();
// Then we need to swap the retrofit api impl. with a mock one
//Client.setApi(mockRetrofitApiImpl);
controller.create();
}
@Test
public void shouldFillAdapter() throws Exception {
Mockito.verify(mockRetrofitApiImpl)
.getAlbums();
int objectsQuantity = 10;
List<Album> list = new ArrayList<Album>();
for(int i = 0; i < objectsQuantity; ++i) {
list.add(new Album());
}
//callbackArgumentCaptor.getValue().success(list, null);
// AlbumsAdapter yourAdapter = mainActivity.getAdapter(); // Obtain adapter
// Simple test check if adapter has as many items as put into response
//assertThat(yourAdapter.getItemCount(), equalTo(objectsQuantity));
}
}
|
package com.mobile.mobilehardware.simcard;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import com.mobile.mobilehardware.exceptions.MobException;
import org.json.JSONException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author 谷闹年
* @date 2018/1/4
*/
public class MobCardUtils {
private static final String TAG = MobCardUtils.class.getSimpleName();
/**
* mobile info
*
* @param context
* @return
*/
@SuppressLint("HardwareIds")
public static void mobGetCardInfo(Context context, SimCardBean simCardBean) {
TelephonyManager telephonyManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));
if (telephonyManager == null) {
return;
}
boolean sim1Ready = telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY;
boolean sim2Ready = false;
try {
sim1Ready = getSIMStateBySlot(telephonyManager, "getSimStateGemini", 0);
sim2Ready = getSIMStateBySlot(telephonyManager, "getSimStateGemini", 1);
} catch (MobException e) {
try {
sim1Ready = getSIMStateBySlot(telephonyManager, "getSimState", 0);
sim2Ready = getSIMStateBySlot(telephonyManager, "getSimState", 1);
} catch (MobException e1) {
Log.i(TAG, e1.toString());
}
}
simCardBean.setSim1Ready(sim1Ready + "");
simCardBean.setSim2Ready(sim2Ready + "");
simCardBean.setIsTwoCard((sim1Ready && sim2Ready) + "");
String sim1Imei = null;
String sim2Imei = null;
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
try {
sim1Imei = getSIMOperator(telephonyManager, "getDeviceIdGemini", 0);
sim2Imei = getSIMOperator(telephonyManager, "getDeviceIdGemini", 1);
} catch (MobException e) {
try {
sim1Imei = getSIMOperator(telephonyManager, "getDeviceId", 0);
sim2Imei = getSIMOperator(telephonyManager, "getDeviceId", 1);
} catch (MobException e1) {
Log.i(TAG, e1.toString());
}
}
}
if(!TextUtils.isEmpty(sim1Imei)){
simCardBean.setSim1Imei(MidInfo.isNumeric(sim1Imei)?sim1Imei:null);
}
if(!TextUtils.isEmpty(sim2Imei)){
simCardBean.setSim2Imei(MidInfo.isNumeric(sim2Imei)?sim2Imei:null);
}
}
/**
* 判断卡是否已经准备好
*
* @param predictedMethodName
* @param slotID
* @return
*/
private static boolean getSIMStateBySlot(TelephonyManager telephony, String predictedMethodName, int slotID) throws MobException {
boolean isReady = false;
try {
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimStateGemini = telephonyClass.getMethod(predictedMethodName, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotID;
Object ob_phone = getSimStateGemini.invoke(telephony, obParameter);
if (ob_phone != null) {
int simState = Integer.parseInt(ob_phone.toString());
if (simState == TelephonyManager.SIM_STATE_READY) {
isReady = true;
}
}
} catch (Exception e) {
throw new MobException(predictedMethodName);
}
return isReady;
}
/**
* 获取哪张卡开启的运营商
*
* @param context con
* @return int
*/
private static int getDefaultDataSub(Context context) {
int num = -1;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
SubscriptionManager sm = SubscriptionManager.from(context);
try {
Method getSubId = sm.getClass().getDeclaredMethod("getDefaultDataSubscriptionId");
if (getSubId != null) {
try {
num = (int) getSubId.invoke(sm);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
} catch (NoSuchMethodException e) {
try {
@SuppressLint("PrivateApi") Method getSubId = sm.getClass().getDeclaredMethod("getDefaultDataSubId");
if (getSubId != null) {
try {
num = (int) getSubId.invoke(sm);
} catch (IllegalAccessException | InvocationTargetException e1) {
e1.printStackTrace();
}
}
} catch (NoSuchMethodException e1) {
/**
* 新加一个方案,此方案也是用于拿到获取的运营商,跟getDefaultDataSubscriptionId平级
*/
try {
Method slot = sm.getClass().getMethod("getDefaultDataSubscriptionInfo");
try {
SubscriptionInfo subscriptionInfo = (SubscriptionInfo) slot.invoke(sm);
num = subscriptionInfo.getSimSlotIndex();
} catch (IllegalAccessException | InvocationTargetException e2) {
e2.printStackTrace();
}
} catch (NoSuchMethodException e3) {
e3.printStackTrace();
}
}
}
}
return num;
}
/**
* 获取卡的imei信息
*/
private static String getSIMOperator(TelephonyManager telephony, String predictedMethodName, int slotID) throws MobException {
String imei = "$unknown";
try {
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimStateGemini = telephonyClass.getMethod(predictedMethodName, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotID;
Object phone = getSimStateGemini.invoke(telephony, obParameter);
if (phone != null) {
imei = phone.toString();
}
} catch (Exception e) {
throw new MobException(predictedMethodName);
}
return imei;
}
}
|
package de.julianpadawan.timelog.insight;
import de.julianpadawan.timelog.model.Goal;
import de.julianpadawan.timelog.model.LogEntry;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
public final class WeekStreakCalculator extends DurationAccumulatingStreakCalculator {
static final String PATTERN = "[1-9]\\d*w";
public WeekStreakCalculator(Goal goal) {
super(goal);
}
@Override
protected int getDayInterval(Goal goal) {
return Integer.parseInt(goal.getInterval().substring(0, goal.getInterval().length() - 1)) * 7;
}
@Override
protected LocalDate toFirstOfInterval(LocalDateTime dateTime) {
return LogEntry.getDate(dateTime).with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
}
@Override
protected String formatStreakDays(long streakDurationDays) {
if (streakDurationDays == -1) return "0w";
return streakDurationDays / 7 + 1 + "w";
}
}
|
package edu.westga.gradeunt;
public interface GradeCategorySummary extends Summarizable {
/**
* Specifies the format of data returned by a GradeSummary. Effectively the same information as the
* corresponding GradeItem, except:
* <ol>
* <li>description is the name of the test if the corresponding GradeItem's description is empty</li>
* <li>adds an additional field indicating if the test passed or not</li>
* </ol>
*
* @author lewisb
*
*/
interface Item {
/**
* See {@link GradeItem#points()}
* @return
*/
double points();
/**
* See {@link GradeItem#description()}. Will be set to the name of the test if the GradeItem's description
* is empty.
*
* @return
*/
String description();
/**
* Whether or not the test corresponding to this item passed.
*
* @return true if the test passed; false otherwise
*/
boolean passed();
}
/**
* Gets the category name
*
* @return the category's name
*/
String getName();
/**
* Graded items within this category.
*
* @return all graded items within this category
*/
Item[] getItems();
} |
package be.openclinic.statistics;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.ScreenHelper;
import be.mxs.common.util.system.StatFunctions;
import be.openclinic.common.KeyValue;
import be.openclinic.statistics.DepartmentIncome.Income;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.admin.Service;
/**
* User: Frank Verbeke
* Date: 9-aug-2007
* Time: 9:41:51
*/
public class DatacenterHospitalStats {
private Date begin;
private Date end;
private Hashtable encounters = new Hashtable();
private Hashtable diagnoses = new Hashtable();
private HashSet diagnosisencounter = new HashSet();
private Hashtable statvalues = new Hashtable();
private Hashtable departmentIncomes = new Hashtable();
private Hashtable totalDepartmentIncomes;
private Hashtable insurarAdmissions = new Hashtable();
private Hashtable insurarVisits = new Hashtable();
private Hashtable departmentLevels= new Hashtable();
Hashtable admissiondiagnosisfrequencies;
Hashtable visitdiagnosisfrequencies;
Hashtable deliveryincomes;
public Hashtable getInsurarAdmissions() {
return insurarAdmissions;
}
public void setInsurarAdmissions(Hashtable insurarAdmissions) {
this.insurarAdmissions = insurarAdmissions;
}
public Hashtable getInsurarVisits() {
return insurarVisits;
}
public void setInsurarVisits(Hashtable insurarVisits) {
this.insurarVisits = insurarVisits;
}
public Hashtable getTotalDepartmentIncomes() {
return totalDepartmentIncomes;
}
public Hashtable getTotalCostcenterIncomes(){
Hashtable csi = new Hashtable();
Hashtable allServices = MedwanQuery.getInstance().services;
Enumeration e = totalDepartmentIncomes.keys();
String id;
Service service;
String key;
while(e.hasMoreElements()){
id = (String)e.nextElement();
service = (Service)allServices.get(id);
key = (service==null || service.costcenter==null?"?":service.costcenter);
if(csi.get(key)==null){
csi.put(key, totalDepartmentIncomes.get(id));
}
else {
csi.put(key,new Double(((Double)csi.get(key)).doubleValue()+((Double)totalDepartmentIncomes.get(id)).doubleValue()));
}
}
return csi;
}
public void setTotalDepartmentIncomes(Hashtable totalDepartmentIncomes) {
this.totalDepartmentIncomes = totalDepartmentIncomes;
}
public Hashtable getDeliveryincomes() {
return deliveryincomes;
}
public void setDeliveryincomes(Hashtable deliveryincomes) {
this.deliveryincomes = deliveryincomes;
}
public Hashtable getDepartmentIncomes() {
return departmentIncomes;
}
public Hashtable getAdmissiondiagnosisfrequencies() {
return admissiondiagnosisfrequencies;
}
public void setAdmissiondiagnosisfrequencies(
Hashtable admissiondiagnosisfrequencies) {
this.admissiondiagnosisfrequencies = admissiondiagnosisfrequencies;
}
public Hashtable getVisitdiagnosisfrequencies() {
return visitdiagnosisfrequencies;
}
public void setVisitdiagnosisfrequencies(Hashtable visitdiagnosisfrequencies) {
this.visitdiagnosisfrequencies = visitdiagnosisfrequencies;
}
public void setDepartmentIncomes(Hashtable departmentIncomes) {
this.departmentIncomes = departmentIncomes;
}
private static DatacenterHospitalStats instance;
public static DatacenterHospitalStats getInstance() {
if(instance==null)
instance = new DatacenterHospitalStats();
return instance;
}
public static DatacenterHospitalStats getInstance(String begin, String end)throws Exception{
if(instance==null)
instance = new DatacenterHospitalStats(begin,end);
return instance;
}
public Hashtable getEncounters() {
return encounters;
}
public void setEncounters(Hashtable encounters) {
this.encounters = encounters;
}
public Date getBegin() {
return begin;
}
public void setBegin(Date begin) {
this.begin = begin;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public DatacenterHospitalStats(){
//void
}
public DatacenterHospitalStats(String begin, String end) throws Exception {
this.begin = ScreenHelper.parseDate(begin);
this.end = ScreenHelper.parseDate(end);
}
public DatacenterHospitalStats(Date begin, Date end) {
this.begin = begin;
this.end = end;
}
public static double getOverheadCosts() {
double cost = -1;
String sQuery = MedwanQuery.getInstance().getConfigString("query.statistics.hospital.overheadcosts");
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try {
PreparedStatement ps = oc_conn.prepareStatement(sQuery);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
cost = rs.getDouble("cost");
}
rs.close();
ps.close();
}
catch (Exception e) {
e.printStackTrace();
}
try {
oc_conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return cost;
}
public static int getBedCapacity() {
int capacity = -1;
String sQuery = "select count(*) total from OC_BEDS a,ServicesAddressView b where a.OC_BED_SERVICEUID=b.serviceid";
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try {
PreparedStatement ps = oc_conn.prepareStatement(sQuery);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
capacity = rs.getInt("total");
}
rs.close();
ps.close();
}
catch (Exception e) {
e.printStackTrace();
}
try {
oc_conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return capacity;
}
public ServiceStats getServiceStats() {
return new ServiceStats("", begin, end);
}
public void loadEncounters(String codetype) {
String serverid=MedwanQuery.getInstance().getConfigString("serverId")+".";
String sql="select OC_ENCOUNTER_SERVERID,OC_ENCOUNTER_OBJECTID,OC_ENCOUNTER_PATIENTUID,OC_ENCOUNTER_BEGINDATE,OC_ENCOUNTER_ENDDATE,"+
" OC_ENCOUNTER_OUTCOME,OC_ENCOUNTER_TYPE,OC_ENCOUNTER_SERVICEUID,OC_DIAGNOSIS_CODE,OC_DIAGNOSIS_GRAVITY,OC_DIAGNOSIS_CERTAINTY"+
" from"+
" UPDATESTATS2"+
" where"+
" OC_ENCOUNTER_ENDDATE>=? and"+
" OC_ENCOUNTER_BEGINDATE<=? and"+
" (OC_DIAGNOSIS_CODETYPE=? OR OC_DIAGNOSIS_CODETYPE IS NULL)"+
" ORDER BY OC_ENCOUNTER_BEGINDATE,OC_ENCOUNTER_SERVERID,OC_ENCOUNTER_OBJECTID";
try {
PreparedStatement ps = MedwanQuery.getInstance().getStatsConnection().prepareStatement(sql);
ps.setTimestamp(1, new java.sql.Timestamp(begin.getTime()));
ps.setTimestamp(2, new java.sql.Timestamp(end.getTime()));
ps.setString(3, codetype);
ResultSet rs = ps.executeQuery();
String encounterUid, patientUid, outcome, type, service, diagnosis;
Hashtable lastadmissions = new Hashtable();
Hashtable lastvisits = new Hashtable();
int readmissions6m = 0, readmissions12m = 0, readmissionPeriod = 0;
int revisit6m = 0, revisit12m = 0, revisitPeriod = 0;
long duration6m = 182 * 24 * 60;
duration6m *= 60000;
long duration12m = 365 * 24 * 60;
duration12m *= 60000;
long duration1w = 7 * 24 * 60;
duration1w *= 60000;
long duration1d = 24 * 60 * 60000;
long q = (end.getTime() - begin.getTime()) % duration1w;
double lastweekcorrection=q!=0?duration1w/(q):1;
Date beginDate, endDate;
Encounter encounter;
boolean begincorrected,endcorrected;
double gravity=1,certainty=1;
double MAX_GRAVITY=MedwanQuery.getInstance().getConfigInt("maxgravity",1),MAX_CERTAINTY=MedwanQuery.getInstance().getConfigInt("maxcertainty",1);
HashSet tpa,tpv,am;
Hashtable dvp,admissiondiagnosispatientfrequencies,visitdiagnosispatientfrequencies,admissiondiagnosisdeaths;
Vector admissionDurations;
int totalweeks,totaldays,ta,tv,tda,tan,week,daystart,dayend;
int [] dailyAdmittedPatients,dailyVisitedPatients,weeklyAdmissions,weeklyVisits,weeklyDeaths;
double[] weeklyIncome;
Enumeration e,e2,e3;
Object key;
String code;
Hashtable t10pfcca;
String serviceid,prestationcode,prestationfamily,encountertype,encounteruid,debetuid,insurarname;
Integer corrector;
double amount;
double totalIncome=0;
Hashtable t10ada,t10adar,t10pfccv,h,correctors;
while (rs.next()) {
begincorrected=false;
endcorrected=false;
encounterUid = rs.getInt("OC_ENCOUNTER_SERVERID") + "." + rs.getInt("OC_ENCOUNTER_OBJECTID");
patientUid = rs.getString("OC_ENCOUNTER_PATIENTUID");
outcome = rs.getString("OC_ENCOUNTER_OUTCOME");
type = rs.getString("OC_ENCOUNTER_TYPE");
service = rs.getString("OC_ENCOUNTER_SERVICEUID");
diagnosis = rs.getString("OC_DIAGNOSIS_CODE");
gravity = rs.getInt("OC_DIAGNOSIS_GRAVITY");
certainty=rs.getInt("OC_DIAGNOSIS_CERTAINTY");
if(diagnosis==null){
diagnosis="?";
gravity=1;
certainty=1;
}
beginDate = rs.getDate("OC_ENCOUNTER_BEGINDATE");
if (beginDate.before(begin)) {
beginDate = begin;
begincorrected=true;
}
endDate = rs.getDate("OC_ENCOUNTER_ENDDATE");
if (endDate == null || endDate.after(end)) {
endDate = end;
endcorrected=true;
}
encounter = (Encounter) encounters.get(encounterUid);
if (encounter == null) {
if (type.equalsIgnoreCase("admission")) {
if (lastadmissions.get(patientUid) != null) {
readmissionPeriod++;
if (beginDate.getTime() - ((Date) lastadmissions.get(patientUid)).getTime() < duration6m) {
readmissions6m++;
}
if (beginDate.getTime() - ((Date) lastadmissions.get(patientUid)).getTime() < duration12m) {
readmissions12m++;
}
}
} else if (type.equalsIgnoreCase("visit")) {
if (lastvisits.get(patientUid) != null) {
revisitPeriod++;
if (beginDate.getTime() - ((Date) lastvisits.get(patientUid)).getTime() < duration6m) {
revisit6m++;
}
if (beginDate.getTime() - ((Date) lastvisits.get(patientUid)).getTime() < duration12m) {
revisit12m++;
}
}
}
encounter = new Encounter(encounterUid, patientUid, beginDate, endDate, outcome, type, service);
}
encounter.addDiagnosis(diagnosis, gravity/MAX_GRAVITY, certainty/MAX_CERTAINTY);
if(!diagnosisencounter.contains(encounterUid+"."+diagnosis)){
diagnosisencounter.add(encounterUid+"."+diagnosis);
if(diagnoses.get(diagnosis)==null){
diagnoses.put(diagnosis,new Double(1));
}
else {
diagnoses.put(diagnosis, new Double(((Double)diagnoses.get(diagnosis)).doubleValue()+1));
}
}
encounter.setBegincorrected(begincorrected);
encounter.setEndcorrected(endcorrected);
encounters.put(encounterUid, encounter);
if (type.equalsIgnoreCase("admission")) {
lastadmissions.put(patientUid, beginDate);
} else if (type.equalsIgnoreCase("visit")) {
lastvisits.put(patientUid, beginDate);
}
}
rs.close();
ps.close();
//Now perform calculations
//First declare a bunch of variables
statvalues = new Hashtable();
tpa = new HashSet();
tpv = new HashSet();
am = new HashSet();
dvp = new Hashtable();
admissiondiagnosisfrequencies = new Hashtable();
admissiondiagnosispatientfrequencies = new Hashtable();
visitdiagnosisfrequencies = new Hashtable();
visitdiagnosispatientfrequencies = new Hashtable();
admissiondiagnosisdeaths = new Hashtable();
admissionDurations = new Vector();
totalweeks = Math.round((end.getTime() - begin.getTime()) / duration1w) + 1;
totaldays = Math.round((end.getTime() - begin.getTime()) / duration1d) + 1;
dailyAdmittedPatients = new int[totaldays];
dailyVisitedPatients = new int[totaldays];
weeklyAdmissions = new int[totalweeks];
weeklyVisits = new int[totalweeks];
weeklyDeaths = new int[totalweeks];
weeklyIncome = new double[totalweeks];
ta = 0;
tv = 0;
tda = 0;
tan=0;
//Then loop through all encounters
e = encounters.elements();
while (e.hasMoreElements()) {
encounter = (Encounter) e.nextElement();
week = Math.round((encounter.getBegin().getTime() - begin.getTime()) / duration1w);
daystart = Math.round((encounter.getBegin().getTime() - begin.getTime()) / duration1d);
dayend = Math.round((encounter.getEnd().getTime() - begin.getTime()) / duration1d);
if (encounter.isType("admission")) {
if(!encounter.isBegincorrected()){
weeklyAdmissions[week]++;
tan++;
}
for (int n = daystart; n < dayend + 1; n++) {
dailyAdmittedPatients[n]++;
}
tda += encounter.getDurationInDays();
admissionDurations.add(new Integer(encounter.getDurationInDays()));
ta++;
tpa.add(encounter.patientUid);
e2 = encounter.diagnoses.keys();
while (e2.hasMoreElements()) {
code = (String) e2.nextElement();
if (admissiondiagnosisfrequencies.get(code) == null) {
admissiondiagnosisfrequencies.put(code, new Integer(1));
} else {
admissiondiagnosisfrequencies.put(code, new Integer(((Integer) admissiondiagnosisfrequencies.get(code)).intValue() + 1));
}
if (admissiondiagnosispatientfrequencies.get(code) == null) {
admissiondiagnosispatientfrequencies.put(code, new HashSet());
}
((HashSet) admissiondiagnosispatientfrequencies.get(code)).add(encounter.getPatientUid());
if (encounter.isOutcome("dead")) {
if (admissiondiagnosisdeaths.get(code) == null) {
admissiondiagnosisdeaths.put(code, new HashSet());
}
((HashSet) admissiondiagnosisdeaths.get(code)).add(encounter.getPatientUid());
}
}
} else if (encounter.isType("visit")) {
if (dvp.get(daystart + "") == null) {
dvp.put(daystart + "", new HashSet());
}
((HashSet) dvp.get(daystart + "")).add(encounter.patientUid);
if(!encounter.isBegincorrected()){
weeklyVisits[week]++;
}
tv++;
tpv.add(encounter.patientUid);
e2 = encounter.diagnoses.keys();
while (e2.hasMoreElements()) {
code = (String) e2.nextElement();
if (visitdiagnosisfrequencies.get(code) == null) {
visitdiagnosisfrequencies.put(code, new Integer(1));
} else {
visitdiagnosisfrequencies.put(code, new Integer(((Integer) visitdiagnosisfrequencies.get(code)).intValue() + 1));
}
if (visitdiagnosispatientfrequencies.get(code) == null) {
visitdiagnosispatientfrequencies.put(code, new HashSet());
}
((HashSet) visitdiagnosispatientfrequencies.get(code)).add(encounter.getPatientUid());
}
}
if (encounter.isOutcome("dead")) {
am.add(encounter.getPatientUid());
if(!encounter.isBegincorrected()){
weeklyDeaths[week]++;
}
}
}
for (int n = 0; n < totaldays; n++) {
dailyVisitedPatients[n] = dvp.get(n + "") != null ? ((HashSet) dvp.get(n + "")).size() : 0;
}
//Search for quartile values
statvalues.put("MDA", StatFunctions.getMedian(admissionDurations));
//Export variables to statvalues array
statvalues.put("TPA", new Integer(tpa.size()));
statvalues.put("TA", new Integer(ta));
statvalues.put("TAN", new Integer(tan));
statvalues.put("TDA", new Integer(tda));
statvalues.put("TPV", new Integer(tpv.size()));
statvalues.put("TV", new Integer(tv));
statvalues.put("RA6", new Integer(readmissions6m));
statvalues.put("RA12", new Integer(readmissions12m));
statvalues.put("RAP", new Integer(readmissionPeriod));
statvalues.put("RV6", new Integer(revisit6m));
statvalues.put("RV12", new Integer(revisit12m));
statvalues.put("RVP", new Integer(revisitPeriod));
statvalues.put("AM", new Integer(am.size()));
statvalues.put("WA", weeklyAdmissions);
statvalues.put("WV", weeklyVisits);
statvalues.put("DAP", dailyAdmittedPatients);
statvalues.put("DVP", dailyVisitedPatients);
statvalues.put("WD", weeklyDeaths);
statvalues.put("T10FCCA", StatFunctions.getTop(admissiondiagnosisfrequencies, MedwanQuery.getInstance().getConfigInt("topxadmissiondiagnosisfrequencies",10)));
t10pfcca = new Hashtable();
e3 = admissiondiagnosispatientfrequencies.keys();
while (e3.hasMoreElements()) {
key = e3.nextElement();
t10pfcca.put(key, new Integer(((HashSet) admissiondiagnosispatientfrequencies.get(key)).size()));
}
t10ada = new Hashtable();
t10adar = new Hashtable();
e3 = admissiondiagnosisdeaths.keys();
while (e3.hasMoreElements()) {
key = e3.nextElement();
t10ada.put(key, new Integer(((HashSet) admissiondiagnosisdeaths.get(key)).size()));
t10adar.put(key, new Double(100 * (double) ((HashSet) admissiondiagnosisdeaths.get(key)).size() / (double) ((HashSet) admissiondiagnosispatientfrequencies.get(key)).size()));
}
statvalues.put("T10ADA", StatFunctions.getTop(t10ada, 10));
statvalues.put("T10ADAR", StatFunctions.getTop(t10adar, 10));
statvalues.put("T10PFCCA", StatFunctions.getTop(t10pfcca, 10));
statvalues.put("T10FCCV", StatFunctions.getTop(visitdiagnosisfrequencies, 10));
t10pfccv = new Hashtable();
e3 = visitdiagnosispatientfrequencies.keys();
while (e3.hasMoreElements()) {
key = e3.nextElement();
t10pfccv.put(key, new Integer(((HashSet) visitdiagnosispatientfrequencies.get(key)).size()));
}
statvalues.put("T10PFCCV", StatFunctions.getTop(t10pfccv, 10));
//Health econometrics
h = new Hashtable();
//First get list of distributioncorrectors
correctors = new Hashtable();
sql="SELECT OC_DEBETOBJECTID,OC_ENCOUNTERUID,count(*) as total"+
" from UPDATESTATS4"+
" where"+
" OC_BEGINDATE <=? and"+
" OC_ENDDATE >=?"+
" group by OC_DEBETOBJECTID,OC_ENCOUNTERUID having count(*)>1";
ps = MedwanQuery.getInstance().getStatsConnection().prepareStatement(sql);
ps.setDate(1,new java.sql.Date(end.getTime()));
ps.setDate(2,new java.sql.Date(begin.getTime()));
rs=ps.executeQuery();
while(rs.next()){
correctors.put(rs.getInt("OC_DEBETOBJECTID")+"."+rs.getString("OC_ENCOUNTERUID"),new Integer(rs.getInt("total")));
}
rs.close();
ps.close();
sql="select OC_INSURAR,OC_DEBETOBJECTID,OC_PRESTATIONREFTYPE,OC_PRESTATIONCODE,OC_SERVICEUID,OC_ENCOUNTERTYPE,OC_ENCOUNTERUID,OC_AMOUNT"+
" from UPDATESTATS4"+
" where"+
" OC_BEGINDATE <=? and"+
" OC_ENDDATE >=?";
ps = MedwanQuery.getInstance().getStatsConnection().prepareStatement(sql);
ps.setDate(1,new java.sql.Date(end.getTime()));
ps.setDate(2,new java.sql.Date(begin.getTime()));
rs=ps.executeQuery();
while (rs.next()){
insurarname=rs.getString("OC_INSURAR");
if(insurarname==null || insurarname.trim().length()==0){
insurarname="?";
}
debetuid=rs.getInt("OC_DEBETOBJECTID")+"";
serviceid=rs.getString("OC_SERVICEUID");
encountertype=rs.getString("OC_ENCOUNTERTYPE");
prestationcode=rs.getString("OC_PRESTATIONCODE");
prestationfamily=rs.getString("OC_PRESTATIONREFTYPE");
encounteruid=rs.getString("OC_ENCOUNTERUID");
amount=rs.getDouble("OC_AMOUNT");
corrector=(Integer)correctors.get(debetuid+"."+encounteruid);
if(corrector!=null){
amount/=corrector.intValue();
}
totalIncome+=amount;
if(departmentIncomes.get(serviceid)==null){
departmentIncomes.put(serviceid, new DepartmentIncome());
}
((DepartmentIncome)departmentIncomes.get(serviceid)).putIncome(prestationcode, prestationfamily, amount,encountertype);
if(encounters.get(encounteruid)!=null){
encounter=(Encounter)encounters.get(encounteruid);
if(!encounter.begincorrected){
if(encountertype.equalsIgnoreCase("admission")){
if(insurarAdmissions.get(insurarname)==null){
insurarAdmissions.put(insurarname, new HashSet());
}
((HashSet)insurarAdmissions.get(insurarname)).add(encounteruid);
}
else if(encountertype.equalsIgnoreCase("visit")){
if(insurarVisits.get(insurarname)==null){
insurarVisits.put(insurarname, new HashSet());
}
((HashSet)insurarVisits.get(insurarname)).add(encounteruid);
}
}
encounter.addDelivery(prestationcode, amount);
encounter.addFamily(prestationfamily, amount);
week = Math.round((encounter.getBegin().getTime() - begin.getTime()) / duration1w);
if(!encounter.isBegincorrected()){
weeklyIncome[week]+=amount;
}
}
else {
}
}
rs.close();
ps.close();
statvalues.put("TI",new Double(totalIncome));
statvalues.put("WI", weeklyIncome);
Hashtable familyincomes = new Hashtable();
deliveryincomes = new Hashtable();
Enumeration di = departmentIncomes.keys();
totalDepartmentIncomes=new Hashtable();
while (di.hasMoreElements()){
String departmentCode= (String)di.nextElement();
DepartmentIncome departmentIncome = (DepartmentIncome)departmentIncomes.get(departmentCode);
Hashtable del = departmentIncome.getDeliveries();
Hashtable fam = departmentIncome.getFamilies();
totalDepartmentIncomes.put(departmentCode,new Double(departmentIncome.getTotalIncome()));
Enumeration dfi=fam.keys();
while (dfi.hasMoreElements()){
key=(String)dfi.nextElement();
if(familyincomes.get(key)==null){
familyincomes.put(key,fam.get(key));
}
else {
familyincomes.put(key,new Double(((Double)familyincomes.get(key)).doubleValue()+((Double)fam.get(key)).doubleValue()));
}
}
dfi=del.keys();
while (dfi.hasMoreElements()){
key=(String)dfi.nextElement();
if(deliveryincomes.get(key)==null){
deliveryincomes.put(key,del.get(key));
}
else {
deliveryincomes.put(key,new Double(((Double)deliveryincomes.get(key)).doubleValue()+((Double)del.get(key)).doubleValue()));
}
}
}
statvalues.put("IDF", StatFunctions.getTop(familyincomes, familyincomes.size()));
statvalues.put("T10IDD", StatFunctions.getTop(deliveryincomes, 10));
statvalues.put("T10IDS", StatFunctions.getTop(totalDepartmentIncomes, 10));
Hashtable admissionDiagnosisCosts = new Hashtable(),visitDiagnosisCosts = new Hashtable();
e=encounters.elements();
Hashtable d;
Encounter enc;
Enumeration dc;
while(e.hasMoreElements()){
enc = (Encounter)e.nextElement();
if(enc.isType("admission")){
d=enc.getDiagnosisCosts();
dc=d.keys();
while (dc.hasMoreElements()){
key=(String)dc.nextElement();
if(!Double.isNaN(((Double)d.get(key)).doubleValue())){
if(admissionDiagnosisCosts.get(key)==null){
admissionDiagnosisCosts.put(key,d.get(key));
}
else {
admissionDiagnosisCosts.put(key,new Double(((Double)admissionDiagnosisCosts.get(key)).doubleValue()+((Double)d.get(key)).doubleValue()));
}
}
}
}
else if(enc.isType("visit")){
d=enc.getDiagnosisCosts();
dc=d.keys();
while (dc.hasMoreElements()){
key=(String)dc.nextElement();
if(!Double.isNaN(((Double)d.get(key)).doubleValue())){
if(visitDiagnosisCosts.get(key)==null){
visitDiagnosisCosts.put(key,d.get(key));
}
else {
visitDiagnosisCosts.put(key,new Double(((Double)visitDiagnosisCosts.get(key)).doubleValue()+((Double)d.get(key)).doubleValue()));
}
}
}
}
}
KeyValue[] T10DRA=StatFunctions.getTop(admissionDiagnosisCosts,10);
KeyValue[] T10DRV=StatFunctions.getTop(visitDiagnosisCosts,10);
statvalues.put("T10DRA", T10DRA);
statvalues.put("T10DRV", T10DRV);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public KeyValue[] getInsuranceCases(String encounterType){
Hashtable insurars = new Hashtable();
if(encounterType.equalsIgnoreCase("admission")){
insurars=insurarAdmissions;
}
else if(encounterType.equalsIgnoreCase("visit")){
insurars=insurarVisits;
}
KeyValue[] kv = new KeyValue[insurars.size()];
Enumeration e = insurars.keys();
String insurar;
Hashtable result = new Hashtable();
while(e.hasMoreElements()){
insurar = (String)e.nextElement();
result.put(insurar,Integer.valueOf(((HashSet)insurars.get(insurar)).size()));
}
return StatFunctions.getTop(result,result.size());
}
public static KeyValue[] getInsuranceCases(Date begin, Date end, String encounterType){
Hashtable cases = new Hashtable();
try{
String sql = "select count(oc_encounteruid) total, oc_insurar"+
" from updatestats3"+
" where"+
" a.oc_encountertype=? and"+
" a.oc_date >= ? and"+
" a.oc_date <= ?) q"+
" group by oc_insurar";
PreparedStatement ps = MedwanQuery.getInstance().getStatsConnection().prepareStatement(sql);
ps.setString(1, encounterType);
ps.setTimestamp(2, new java.sql.Timestamp(begin.getTime()));
ps.setTimestamp(3, new java.sql.Timestamp(end.getTime()));
ResultSet rs = ps.executeQuery();
String insurarname;
while(rs.next()){
insurarname=rs.getString("oc_insurar");
cases.put(insurarname==null?"?":insurarname, new Integer(rs.getInt("total")));
}
rs.close();
ps.close();
}
catch(Exception e){
e.printStackTrace();
}
return StatFunctions.getTop(cases, cases.size());
}
public static KeyValue[] getInsuranceCasesBasic(Date begin, Date end, String encounterType){
Hashtable cases = new Hashtable();
try{
String sql = "select count(oc_encounteruid) total, oc_insurar"+
" from updatestats3"+
" where"+
" a.oc_encountertype=? and"+
" a.oc_date >= ? and"+
" a.oc_date <= ?"+
" group by oc_insurar";
PreparedStatement ps = MedwanQuery.getInstance().getStatsConnection().prepareStatement(sql);
ps.setString(1, encounterType);
ps.setTimestamp(2, new java.sql.Timestamp(begin.getTime()));
ps.setTimestamp(3, new java.sql.Timestamp(end.getTime()));
ResultSet rs = ps.executeQuery();
String insurarname;
while(rs.next()){
insurarname=rs.getString("oc_insurar");
cases.put(insurarname==null?"?":insurarname, new Integer(rs.getInt("total")));
}
rs.close();
ps.close();
}
catch(Exception e){
e.printStackTrace();
}
return StatFunctions.getTop(cases, cases.size());
}
public double getTI() {
return ((Double) statvalues.get("TI")).doubleValue();
}
public int getTPA() {
return ((Integer) statvalues.get("TPA")).intValue();
}
public int getTPV() {
return ((Integer) statvalues.get("TPV")).intValue();
}
public int getTA() {
return ((Integer) statvalues.get("TA")).intValue();
}
public int getTAN() {
return ((Integer) statvalues.get("TAN")).intValue();
}
public int getTDA() {
return ((Integer) statvalues.get("TDA")).intValue();
}
public int getTV() {
return ((Integer) statvalues.get("TV")).intValue();
}
public int getMDA() {
return ((Integer) statvalues.get("MDA")).intValue();
}
public int getRA6() {
return ((Integer) statvalues.get("RA6")).intValue();
}
public int getRA12() {
return ((Integer) statvalues.get("RA12")).intValue();
}
public int getRAP() {
return ((Integer) statvalues.get("RAP")).intValue();
}
public int getRV6() {
return ((Integer) statvalues.get("RV6")).intValue();
}
public int getRV12() {
return ((Integer) statvalues.get("RV12")).intValue();
}
public int getRVP() {
return ((Integer) statvalues.get("RVP")).intValue();
}
public int getAM() {
return ((Integer) statvalues.get("AM")).intValue();
}
public int[] getWA() {
return (int[]) statvalues.get("WA");
}
public BaseChart getWAChart() {
return new BaseChart("weekly.admissions", "week", "number.of.admissions", getWA());
}
public int[] getWV() {
return (int[]) statvalues.get("WV");
}
public double[] getWI() {
return (double[]) statvalues.get("WI");
}
public BaseChart getWVChart() {
return new BaseChart("weekly.visits", "week", "number.of.visits", getWV());
}
public BaseChart getWIChart() {
return new BaseChart("weekly.income", "week", "amount", getWI());
}
public int[] getDAP() {
return (int[]) statvalues.get("DAP");
}
public BaseChart getDAPChart() {
return new BaseChart("daily.admitted.patients", "day", "number.of.patients", getDAP());
}
public int[] getDVP() {
return (int[]) statvalues.get("DVP");
}
public BaseChart getDVPChart() {
return new BaseChart("daily.visited.patients", "day", "number.of.patients", getDVP());
}
public int[] getWD() {
return (int[]) statvalues.get("WD");
}
public BaseChart getWDChart() {
return new BaseChart("weekly.deaths", "week", "number.of.deaths", getWD());
}
public KeyValue[] getT10FCCA() {
return (KeyValue[]) statvalues.get("T10FCCA");
}
public PieChart getT10FCCAChart() {
return new PieChart("top10.most.frequent.KPGS.number.of.admissions", getT10FCCA());
}
public KeyValue[] getT10PFCCA() {
return (KeyValue[]) statvalues.get("T10PFCCA");
}
public PieChart getT10PFCCAChart() {
return new PieChart("admission.top10.most.frequent.KPGS.number.of.patients", getT10PFCCA());
}
public KeyValue[] getT10ADA() {
return (KeyValue[]) statvalues.get("T10ADA");
}
public PieChart getT10ADAChart() {
return new PieChart("admission.top10.most.mortal.KPGS.number.of.deaths", getT10ADA());
}
public KeyValue[] getT10ADAR() {
return (KeyValue[]) statvalues.get("T10ADAR");
}
public PieChart getT10ADARChart() {
return new PieChart("admission.top10.most.mortal.KPGS.incode.number.of.deaths", getT10ADAR());
}
public KeyValue[] getT10FCCV() {
return (KeyValue[]) statvalues.get("T10FCCV");
}
public PieChart getT10FVVCChart() {
return new PieChart("visit.top10.most.frequent.KPGS.number.of.visits", getT10FCCV());
}
public KeyValue[] getT10PFCCV() {
return (KeyValue[]) statvalues.get("T10PFCCV");
}
public PieChart getT10PFVVCChart() {
return new PieChart("visit.top10.most.frequent.KPGS.incode.number.patients", getT10PFCCV());
}
public KeyValue[] getACP(String code){
Hashtable comorbidityCodes = new Hashtable();
double diagnosiscount=((Double)diagnoses.get(code)).doubleValue();
Enumeration e = encounters.elements();
Encounter encounter;
Enumeration diagnoses;
Diagnosis diagnosis;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code)){
diagnoses = encounter.getDiagnoses().elements();
while(diagnoses.hasMoreElements()){
diagnosis = (Diagnosis)diagnoses.nextElement();
if(!code.equalsIgnoreCase(diagnosis.getCode())){
if(comorbidityCodes.get(diagnosis.getCode())==null){
comorbidityCodes.put(diagnosis.getCode(),new Double((double)100/diagnosiscount));
}
else {
comorbidityCodes.put(diagnosis.getCode(),new Double(((Double)comorbidityCodes.get(diagnosis.getCode())).doubleValue()+(double)100/diagnosiscount));
}
}
}
}
}
return StatFunctions.getTop(comorbidityCodes, 10);
}
public ColumnChart getACPChart(String code){
return new ColumnChart("admission.comorbidity.profile","kpgs.code","% cases",getACP(code));
}
public double getACPI(String code){
double index=0;
int counter=0;
Enumeration e = encounters.elements();
Encounter encounter;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code)){
counter++;
index+=encounter.getAbsoluteMorbidityIndex();
}
}
return index/counter;
}
public KeyValue[] getACPW(String code){
Hashtable comorbidityCodes = new Hashtable();
double diagnosiscount=((Double)diagnoses.get(code)).doubleValue();
Enumeration e = encounters.elements();
Encounter encounter;
Diagnosis thisDiagnosis;
double thisweight;
Enumeration diagnoses;
Diagnosis diagnosis;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code)){
thisDiagnosis = encounter.getDiagnosis(code);
thisweight = thisDiagnosis.getCertainty()*thisDiagnosis.getGravity();
diagnoses = encounter.getDiagnoses().elements();
while(diagnoses.hasMoreElements()){
diagnosis = (Diagnosis)diagnoses.nextElement();
if(!code.equalsIgnoreCase(diagnosis.getCode())){
if(comorbidityCodes.get(diagnosis.getCode())==null){
comorbidityCodes.put(diagnosis.getCode(),new Double((double)100*diagnosis.getCertainty()*diagnosis.getGravity()/(thisweight*diagnosiscount)));
}
else {
comorbidityCodes.put(diagnosis.getCode(),new Double(((Double)comorbidityCodes.get(diagnosis.getCode())).doubleValue()+(double)100*diagnosis.getCertainty()*diagnosis.getGravity()/(thisweight*diagnosiscount)));
}
}
}
}
}
return StatFunctions.getTop(comorbidityCodes, 10);
}
public ColumnChart getACPWChart(String code){
return new ColumnChart("admission.weighed.comorbidity.profile","kpgs.code","% weighed cases",getACPW(code));
}
public double getACPIW(String code){
double index=0;
int counter=0;
Enumeration e = encounters.elements();
Encounter encounter;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code)){
counter++;
index+=encounter.getWeighedComorbidityIndex(code);
}
}
return index/counter;
}
public KeyValue[] getACMP(String code){
Hashtable comorbidityCodes = new Hashtable();
double diagnosiscount=getDeadAdmissionDiagnosisCount(code);
Enumeration e = encounters.elements();
Encounter encounter;
Enumeration diagnoses;
Diagnosis diagnosis;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code) && encounter.isOutcome("dead")){
diagnoses = encounter.getDiagnoses().elements();
while(diagnoses.hasMoreElements()){
diagnosis = (Diagnosis)diagnoses.nextElement();
if(!code.equalsIgnoreCase(diagnosis.getCode())){
if(comorbidityCodes.get(diagnosis.getCode())==null){
comorbidityCodes.put(diagnosis.getCode(),new Double((double)100/diagnosiscount));
}
else {
comorbidityCodes.put(diagnosis.getCode(),new Double(((Double)comorbidityCodes.get(diagnosis.getCode())).doubleValue()+(double)100/diagnosiscount));
}
}
}
}
}
return StatFunctions.getTop(comorbidityCodes, 10);
}
public ColumnChart getACMPChart(String code){
return new ColumnChart("admission.comortality.profile","kpgs.code","% cases",getACMP(code));
}
public double getACMPI(String code){
double index=0;
int counter=0;
Enumeration e = encounters.elements();
Encounter encounter;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code) && encounter.isOutcome("dead")){
counter++;
index+=encounter.getAbsoluteMorbidityIndex();
}
}
return index/counter;
}
public int getDeadAdmissionDiagnosisCount(String code){
int count=0;
Enumeration e = encounters.elements();
Encounter encounter;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code) && encounter.isOutcome("dead")){
count++;
}
}
return count;
}
public int getAdmissionDiagnosisCount(String code){
int count=0;
Enumeration e = encounters.elements();
Encounter encounter;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code)){
count++;
}
}
return count;
}
public int getAdmissionWithDeliveriesDiagnosisCount(String code){
int count=0;
Enumeration e = encounters.elements();
Encounter encounter;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code) && encounter.deliveries.size()>0){
count++;
}
}
return count;
}
public int getVisitWithDeliveriesDiagnosisCount(String code){
int count=0;
Enumeration e = encounters.elements();
Encounter encounter;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code) && encounter.deliveries.size()>0){
count++;
}
}
return count;
}
public int getDeadVisitDiagnosisCount(String code){
int count=0;
Enumeration e = encounters.elements();
Encounter encounter;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("visit") && encounter.hasDiagnosis(code) && encounter.isOutcome("dead")){
count++;
}
}
return count;
}
public int getVisitDiagnosisCount(String code){
int count=0;
Enumeration e = encounters.elements();
Encounter encounter;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("visit") && encounter.hasDiagnosis(code)){
count++;
}
}
return count;
}
public KeyValue[] getACMPW(String code){
Hashtable comorbidityCodes = new Hashtable();
double diagnosiscount=getDeadAdmissionDiagnosisCount(code);
Enumeration e = encounters.elements();
Encounter encounter;
Diagnosis thisDiagnosis;
double thisweight;
Enumeration diagnoses;
Diagnosis diagnosis;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code) && encounter.isOutcome("dead")){
thisDiagnosis = encounter.getDiagnosis(code);
thisweight = thisDiagnosis.getCertainty()*thisDiagnosis.getGravity();
diagnoses = encounter.getDiagnoses().elements();
while(diagnoses.hasMoreElements()){
diagnosis = (Diagnosis)diagnoses.nextElement();
if(!code.equalsIgnoreCase(diagnosis.getCode())){
if(comorbidityCodes.get(diagnosis.getCode())==null){
comorbidityCodes.put(diagnosis.getCode(),new Double((double)100*diagnosis.getWeight()/(thisweight*diagnosiscount)));
}
else {
comorbidityCodes.put(diagnosis.getCode(),new Double(((Double)comorbidityCodes.get(diagnosis.getCode())).doubleValue()+(double)100*diagnosis.getWeight()/(thisweight*diagnosiscount)));
}
}
}
}
}
return StatFunctions.getTop(comorbidityCodes, 10);
}
public ColumnChart getACMPWChart(String code){
return new ColumnChart("admission.weighed.comortality.profile","kpgs.code","% weighed cases",getACMPW(code));
}
public double getACMPIW(String code){
double index=0;
int counter=0;
Enumeration e = encounters.elements();
Encounter encounter;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis(code) && encounter.isOutcome("dead")){
counter++;
index+=encounter.getWeighedComorbidityIndex(code);
}
}
return index/counter;
}
public KeyValue[] getIDF() {
return (KeyValue[]) statvalues.get("IDF");
}
public PieChart getIDFChart() {
return new PieChart("income.distribution.per.family", getIDF());
}
public KeyValue[] getT10IDD() {
return (KeyValue[]) statvalues.get("T10IDD");
}
public PieChart getT10IDDChart() {
return new PieChart("top10.income.distribution.per.delivery", getT10IDD());
}
public KeyValue[] getT10IDS() {
return (KeyValue[]) statvalues.get("T10IDS");
}
public PieChart getT10IDSChart() {
return new PieChart("top10.income.distribution.per.department", getT10IDS());
}
public KeyValue[] getIDFSA(String serviceid){
DepartmentIncome departmentIncome = (DepartmentIncome)departmentIncomes.get(serviceid);
Hashtable fam=departmentIncome.getFamilies("admission");
return StatFunctions.getTop(fam, fam.size());
}
public KeyValue[] getIDFSA(String serviceid, int level){
DepartmentIncome departmentIncome = (DepartmentIncome)getDepartments(level).get(serviceid);
Hashtable fam=departmentIncome.getFamilies("admission");
return StatFunctions.getTop(fam, fam.size());
}
public PieChart getIDFSAChart(String serviceid) {
return new PieChart("income.distribution.per.family.per.department.admissions", getIDFSA(serviceid));
}
public PieChart getIDFSAChart(String serviceid, int level) {
return new PieChart("income.distribution.per.family.per.department.admissions", getIDFSA(serviceid,level));
}
public KeyValue[] getT10IDDSA(String serviceid){
DepartmentIncome departmentIncome = (DepartmentIncome)departmentIncomes.get(serviceid);
Hashtable del = departmentIncome.getDeliveries("admission");
return StatFunctions.getTop(del,10);
}
public KeyValue[] getT10IDDSA(String serviceid, int level){
DepartmentIncome departmentIncome = (DepartmentIncome)getDepartments(level).get(serviceid);
Hashtable del = departmentIncome.getDeliveries("admission");
return StatFunctions.getTop(del,10);
}
public PieChart getT10IDDSAChart(String serviceid) {
return new PieChart("income.distribution.per.family.per.department.admissions", getT10IDDSA(serviceid));
}
public PieChart getT10IDDSAChart(String serviceid, int level) {
return new PieChart("income.distribution.per.family.per.department.admissions", getT10IDDSA(serviceid, level));
}
public KeyValue[] getIDFSV(String serviceid){
DepartmentIncome departmentIncome = (DepartmentIncome)departmentIncomes.get(serviceid);
Hashtable fam=departmentIncome.getFamilies("visit");
return StatFunctions.getTop(fam, fam.size());
}
public KeyValue[] getIDFSV(String serviceid, int level){
DepartmentIncome departmentIncome = (DepartmentIncome)getDepartments(level).get(serviceid);
Hashtable fam=departmentIncome.getFamilies("visit");
return StatFunctions.getTop(fam, fam.size());
}
public PieChart getIDFSVChart(String serviceid) {
return new PieChart("income.distribution.per.family.per.department.admissions", getIDFSA(serviceid));
}
public PieChart getIDFSVChart(String serviceid, int level) {
return new PieChart("income.distribution.per.family.per.department.admissions", getIDFSA(serviceid, level));
}
public KeyValue[] getT10IDDSV(String serviceid){
DepartmentIncome departmentIncome = (DepartmentIncome)departmentIncomes.get(serviceid);
Hashtable del = departmentIncome.getDeliveries("visit");
return StatFunctions.getTop(del,10);
}
public KeyValue[] getT10IDDSV(String serviceid, int level){
DepartmentIncome departmentIncome = (DepartmentIncome)getDepartments(level).get(serviceid);
Hashtable del = departmentIncome.getDeliveries("visit");
return StatFunctions.getTop(del,10);
}
public PieChart getT10IDDSVChart(String serviceid) {
return new PieChart("income.distribution.per.family.per.department.admissions", getT10IDDSA(serviceid));
}
public PieChart getT10IDDSVChart(String serviceid, int level) {
return new PieChart("income.distribution.per.family.per.department.admissions", getT10IDDSA(serviceid, level));
}
public PieChart getT10DRAChart() {
return new PieChart("top10.income.distribution.per.kpgs.code.admissions", getT10DRA());
}
public PieChart getT10DRVChart() {
return new PieChart("top10.income.distribution.per.kpgs.code.visits", getT10DRV());
}
public PieChart getT10DRADChart(String code) {
return new PieChart("income.distribution.per.clinical.condition.admissions", getT10DRAD(code));
}
public PieChart getT10DRVDChart(String code) {
return new PieChart("income.distribution.per.clinical.condition.visits", getT10DRVD(code));
}
public KeyValue[] getDRARedistributed(){
return getDRCRedistributed("admission",0);
}
public KeyValue[] getT10DRARedistributed(){
return getDRCRedistributed("admission",10);
}
public KeyValue[] getDRA(){
return getDRC("admission",0);
}
public KeyValue[] getT10DRA(){
return getDRC("admission",10);
}
public KeyValue[] getDRV(){
return getDRC("visit",0);
}
public KeyValue[] getT10DRV(){
return getDRC("visit",10);
}
public KeyValue[] getT10DRVRedistributed(){
return getDRCRedistributed("visit",10);
}
public KeyValue[] getDRVRedistributed(){
return getDRCRedistributed("visit",0);
}
public KeyValue[] getDRAD(String code){
return getDRCD(code,"admission",0);
}
public KeyValue[] getT10DRAD(String code){
return getDRCD(code,"admission",10);
}
public KeyValue[] getDRVD(String code){
return getDRCD(code,"visit",0);
}
public KeyValue[] getT10DRVD(String code){
return getDRCD(code,"visit",10);
}
public KeyValue[] getT10DRADRedistributed(String code){
return getDRCDRedistributed(code, "admission",10);
}
public KeyValue[] getT10DRVDRedistributed(String code){
return getDRCDRedistributed(code, "visit",10);
}
public KeyValue[] getDRC(String contactType,int count){
Hashtable consumingDiagnoses = new Hashtable();
Enumeration e = encounters.elements();
Encounter encounter;
Enumeration dia,d;
String code,key;
Hashtable deliveries;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType(contactType)){
dia = encounter.getDiagnoses().keys();
while(dia.hasMoreElements()){
code=(String)dia.nextElement();
deliveries = encounter.getDiagnosisDeliveries(code);
d = deliveries.keys();
while(d.hasMoreElements()){
key = (String)d.nextElement();
if(consumingDiagnoses.get(code)==null){
consumingDiagnoses.put(code,deliveries.get(key));
}
else {
consumingDiagnoses.put(code, new Double(((Double)consumingDiagnoses.get(code)).doubleValue()+((Double)deliveries.get(key)).doubleValue()));
}
}
}
}
}
return StatFunctions.getTop(consumingDiagnoses, count>0?count:consumingDiagnoses.size());
}
public KeyValue[] getDRCRedistributed(String contactType,int count){
Hashtable consumingDiagnoses = new Hashtable();
Enumeration e = encounters.elements();
Encounter encounter;
Enumeration dia,d;
String code,key;
Hashtable deliveries;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType(contactType)){
dia = encounter.getDiagnoses().keys();
while(dia.hasMoreElements()){
code=(String)dia.nextElement();
deliveries = encounter.getDiagnosisDeliveries(code);
d = deliveries.keys();
while(d.hasMoreElements()){
key = (String)d.nextElement();
if(consumingDiagnoses.get(code)==null){
consumingDiagnoses.put(code,deliveries.get(key));
}
else {
consumingDiagnoses.put(code, new Double(((Double)consumingDiagnoses.get(code)).doubleValue()+((Double)deliveries.get(key)).doubleValue()));
}
}
}
}
}
double unknownDiagnosisAmount=((Double)consumingDiagnoses.get("?")).doubleValue();
double totalIncomeRemaining = getTI()-unknownDiagnosisAmount;
e = consumingDiagnoses.keys();
while(e.hasMoreElements()){
key = (String)e.nextElement();
consumingDiagnoses.put(key,new Double(((Double)consumingDiagnoses.get(key)).doubleValue()+((Double)consumingDiagnoses.get(key)).doubleValue()*unknownDiagnosisAmount/totalIncomeRemaining));
}
consumingDiagnoses.remove("?");
return StatFunctions.getTop(consumingDiagnoses, count>0?count:consumingDiagnoses.size());
}
public KeyValue[] getDRCD(String code,String contactType,int count){
Hashtable diagnosisDeliveries = new Hashtable();
Enumeration e = encounters.elements();
Encounter encounter;
Hashtable deliveries;
Enumeration d;
String key;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType(contactType) && encounter.hasDiagnosis(code)){
deliveries = encounter.getDiagnosisDeliveries(code);
d = deliveries.keys();
while(d.hasMoreElements()){
key = (String)d.nextElement();
if(diagnosisDeliveries.get(key)==null){
diagnosisDeliveries.put(key,deliveries.get(key));
}
else {
diagnosisDeliveries.put(key, new Double(((Double)diagnosisDeliveries.get(key)).doubleValue()+((Double)deliveries.get(key)).doubleValue()));
}
}
}
}
return StatFunctions.getTop(diagnosisDeliveries, count>0?count:diagnosisDeliveries.size());
}
public KeyValue[] getDRCDRedistributed(String code,String contactType,int count){
Hashtable diagnosisDeliveries = new Hashtable();
Enumeration e = encounters.elements();
Encounter encounter;
Hashtable deliveries;
Enumeration d;
String key;
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType(contactType) && encounter.hasDiagnosis(code)){
deliveries = encounter.getDiagnosisDeliveries(code);
d = deliveries.keys();
while(d.hasMoreElements()){
key = (String)d.nextElement();
if(diagnosisDeliveries.get(key)==null){
diagnosisDeliveries.put(key,deliveries.get(key));
}
else {
diagnosisDeliveries.put(key, new Double(((Double)diagnosisDeliveries.get(key)).doubleValue()+((Double)deliveries.get(key)).doubleValue()));
}
}
}
}
Hashtable consumingDiagnoses = new Hashtable();
double unknownDiagnosisAmount=0;
e = encounters.elements();
while(e.hasMoreElements()){
encounter = (Encounter)e.nextElement();
if(encounter.isType("admission") && encounter.hasDiagnosis("?")){
deliveries = encounter.getDiagnosisDeliveries("?");
d = deliveries.keys();
while(d.hasMoreElements()){
key = (String)d.nextElement();
unknownDiagnosisAmount+=((Double)deliveries.get(key)).doubleValue();
}
}
}
double totalIncomeRemaining = getTI()-unknownDiagnosisAmount;
e = consumingDiagnoses.keys();
while(e.hasMoreElements()){
key = (String)e.nextElement();
consumingDiagnoses.put(key,new Double(((Double)consumingDiagnoses.get(key)).doubleValue()+((Double)consumingDiagnoses.get(key)).doubleValue()*unknownDiagnosisAmount/totalIncomeRemaining));
}
consumingDiagnoses.remove("?");
return StatFunctions.getTop(diagnosisDeliveries, count>0?count:diagnosisDeliveries.size());
}
public String[] getIncomeDepartments(){
SortedSet deps = new TreeSet();
Enumeration e = departmentIncomes.keys();
String key;
DepartmentIncome departmentIncome;
while(e.hasMoreElements()){
key = (String)e.nextElement();
departmentIncome = (DepartmentIncome)departmentIncomes.get(key);
if(departmentIncome.getTotalIncome()>0){
deps.add(key);
}
}
String[] d = new String[deps.size()];
Iterator i=deps.iterator();
int counter=0;
while(i.hasNext()){
d[counter]=(String)i.next();
counter++;
}
return d;
}
public String[] getIncomeDepartments(int level){
SortedSet deps = new TreeSet();
Hashtable departmentIncomes=getDepartments(level);
Enumeration e = departmentIncomes.keys();
String key;
DepartmentIncome departmentIncome;
while(e.hasMoreElements()){
key = (String)e.nextElement();
departmentIncome = (DepartmentIncome)departmentIncomes.get(key);
if(departmentIncome.getTotalIncome()>0){
deps.add(key);
}
}
String[] d = new String[deps.size()];
Iterator i=deps.iterator();
int counter=0;
while(i.hasNext()){
d[counter]=(String)i.next();
counter++;
}
return d;
}
public String[] getIncomeDepartments(String encounterType){
SortedSet deps = new TreeSet();
Enumeration e = departmentIncomes.keys();
String key;
DepartmentIncome departmentIncome;
while(e.hasMoreElements()){
key = (String)e.nextElement();
departmentIncome = (DepartmentIncome)departmentIncomes.get(key);
if(departmentIncome.getEncounterTypeIncome(encounterType)>0){
deps.add(key);
}
}
String[] d = new String[deps.size()];
Iterator i=deps.iterator();
int counter=0;
while(i.hasNext()){
d[counter]=(String)i.next();
counter++;
}
return d;
}
public String[] getIncomeDepartments(String encounterType, int level){
SortedSet deps = new TreeSet();
Hashtable departmentIncomes=getDepartments(level);
Enumeration e = departmentIncomes.keys();
String key;
DepartmentIncome departmentIncome;
while(e.hasMoreElements()){
key = (String)e.nextElement();
departmentIncome = (DepartmentIncome)departmentIncomes.get(key);
if(departmentIncome.getEncounterTypeIncome(encounterType)>0){
deps.add(key);
}
}
String[] d = new String[deps.size()];
Iterator i=deps.iterator();
int counter=0;
while(i.hasNext()){
d[counter]=(String)i.next();
counter++;
}
return d;
}
public String[] getIncomeCostcenters(String encounterType, int level){
SortedSet deps = new TreeSet();
Hashtable departmentIncomes=getCostcenters(level);
Enumeration e = departmentIncomes.keys();
String key;
DepartmentIncome departmentIncome;
while(e.hasMoreElements()){
key = (String)e.nextElement();
departmentIncome = (DepartmentIncome)departmentIncomes.get(key);
if(departmentIncome.getEncounterTypeIncome(encounterType)>0){
deps.add(key);
}
}
String[] d = new String[deps.size()];
Iterator i=deps.iterator();
int counter=0;
while(i.hasNext()){
d[counter]=(String)i.next();
counter++;
}
return d;
}
public Hashtable getDepartments(int level){
if (departmentLevels.get(level+"")!=null){
return (Hashtable)departmentLevels.get(level+"");
}
Hashtable dps = new Hashtable();
Enumeration e = departmentIncomes.keys();
String key,levelkey;
DepartmentIncome departmentIncome,dep;
Income income;
Iterator i;
while (e.hasMoreElements()){
key = (String)e.nextElement();
departmentIncome = (DepartmentIncome)departmentIncomes.get(key);
levelkey="";
if(key.split("\\.").length<level){
levelkey=key;
}
else {
for(int n=0;n<level;n++){
if(n>0){
levelkey+=".";
}
levelkey+=key.split("\\.")[n];
}
}
dep = (DepartmentIncome)dps.get(levelkey);
if(dep==null){
dep=new DepartmentIncome();
dps.put(levelkey,dep);
}
i = departmentIncome.getIncomes().iterator();
while (i.hasNext()){
income = (Income)i.next();
dep.putIncome(income.deliveryCode, income.familyCode, income.amount, income.encounterType);
}
}
departmentLevels.put(level+"", dps);
return dps;
}
public double getTotalCost(String type){
double total=0;
Enumeration enumeration = encounters.elements();
while(enumeration.hasMoreElements()){
Encounter encounter = (Encounter)enumeration.nextElement();
if(encounter.isType(type)){
total+=encounter.getTotalCost();
}
}
return total;
}
public Hashtable getCostcenters(int level){
Hashtable dps = new Hashtable();
Enumeration e = departmentIncomes.keys();
String key,levelkey;
DepartmentIncome departmentIncome,dep;
Service service;
Iterator i;
Income income;
while (e.hasMoreElements()){
key = (String)e.nextElement();
departmentIncome = (DepartmentIncome)departmentIncomes.get(key);
service = Service.getService(key);
levelkey=(service!=null && service.costcenter!=null?service.costcenter:"?");
dep = (DepartmentIncome)dps.get(levelkey);
if(dep==null){
dep=new DepartmentIncome();
dps.put(levelkey,dep);
}
i = departmentIncome.getIncomes().iterator();
while (i.hasNext()){
income = (Income)i.next();
dep.putIncome(income.deliveryCode, income.familyCode, income.amount, income.encounterType);
}
}
return dps;
}
}
|
package com.nit.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.detect.db.ConnectionFactory;
public class PersistantAction extends HttpServlet {
private static final long serialVersionUID = 1L;
RequestDispatcher rd;
Connection con;
int count;
PreparedStatement ps;
String to;
public PersistantAction() {
con = ConnectionFactory.getConnection();
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
doPost(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("hi10");
HttpSession session=request.getSession();
PrintWriter pw = response.getWriter();
response.setContentType("text/html");
Statement statement = null;
try {
statement = con.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
ResultSet resultset = null;
try {
resultset = statement.executeQuery("select count(*) from inbox where toaddress='"+ to + "' and msgtype='T'");
} catch (SQLException e) {
e.printStackTrace();
}
try {
count = resultset.getRow();
System.out.println("hi2");
} catch (SQLException e) {
e.printStackTrace();
}
if (count > 5) {
rd=request.getRequestDispatcher("./P1.jsp");
}
}
}
|
/*
* Written by Erhan Sezerer
* Contact <erhansezerer@iyte.edu.tr> for comments and bug reports
*
* Copyright (C) 2014 Erhan Sezerer
*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.darg.RConnector;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.Rengine;
import com.darg.NLPOperations.sentimentalAnalysis.model.SentimentScoreType;
import com.darg.RConnector.model.RException;
import com.darg.fileOperations.utils.FileUtils;
/**singleton class, since the connection to R cannot be multiplied. Only one connection can exist.
*
* @author erhan sezerer
*
*/
public class REngineConnector
{
private Rengine rengine;
private static boolean instanceExist = false;
//constructor
private REngineConnector()
{
}
/**returns the singleton object REngineConnector if it is not created before, returns null if it is the second call to the function.
*
*
* @author erhan sezerer
*
* @return
*/
public static REngineConnector getInstance()
{
REngineConnector retVal;
if(!instanceExist)
{
retVal = new REngineConnector();
}
else
{
retVal = null;
}
return retVal;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////// INITIALIZATION FUNCTIONS /////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**creates the R connection that belongs to the newly created R.
*
* @author erhan sezerer
*
* @param args - cmd arguments
* @return boolean - false if something went wrong during initialization
*/
public boolean createConnection(String args[])
{
boolean retVal = true;
try
{
// just making sure we have the right version of everything
if (!Rengine.versionCheck())
{
throw new RException("** Version mismatch - Java files don't match library version.");
}
System.err.println("Creating Rengine (with arguments)");
// 1) we pass the arguments from the command line
// 2) we won't use the main loop at first, we'll start it later
// (that's the "false" as second argument)
// 3) the callbacks are implemented by the TextConsole class above
rengine = new Rengine(args, false, new TextConsole());
System.err.println("Rengine created, waiting for R");
// the engine creates R is a new thread, so we should wait until it's ready
if (!rengine.waitForR()) {
throw new RException("Cannot load R");
}
}
catch(RException e)
{
e.printStackTrace();
retVal = false;
}
return retVal;
}
/** Sets the environment and initializes the graphs needed for average score sentimental analysis, from the list of scores.
* Files should only contain scores separated with "\n"
*
* WARNING: Do not use it without calling createConnection() first
*
* @author erhan sezerer
*
* @param posDataPath - path to a list of positive scores of all words.
* @param negDataPath - path to a list of negative scores of all words.
* @param objDataPath - path to a list of objective scores of all words.
*
* @return boolean - true if the operation is successful
*/
public boolean setEnvForSental(final String posDataPath, final String negDataPath, final String objDataPath)
{
boolean retVal = true;
try
{
//temporary variables
String tempString;
String[] rawScores;
double[] scoreList;
//add the necessary library
rengine.eval("require(zoo)");
//for objective scores
/////////////////////////////////////////////////////////////////////////////
//read the scores list
tempString = FileUtils.readFile(objDataPath);
if(tempString == null)
{
throw new Exception("Cannot read the contents of: " + objDataPath);
}
//parse it to a double array
rawScores = tempString.split("\n");
scoreList = new double[rawScores.length];
for (int i=0; i<rawScores.length; i++)
{
scoreList[i] = Double.parseDouble(rawScores[i]);
}
//send it to R
rengine.assign("X", scoreList);
rengine.eval("OBJ <- density(X)", true);
rengine.eval("cdfOBJ <- cumsum(OBJ$y * diff(OBJ$x[1:2]))");
rengine.eval("cdfOBJ <- cdfOBJ / max(cdfOBJ)");
//for positive scores
/////////////////////////////////////////////////////////////////////////////
//read the scores list
tempString = FileUtils.readFile(posDataPath);
if(tempString == null)
{
throw new Exception("Cannot read the contents of: " + posDataPath);
}
//parse it to a double array
rawScores = tempString.split("\n");
scoreList = new double[rawScores.length];
for (int i=0; i<rawScores.length; i++)
{
scoreList[i] = Double.parseDouble(rawScores[i]);
}
//send it to R
rengine.assign("X", scoreList);
rengine.eval("POS <- density(X)", true);
rengine.eval("cdfPOS <- cumsum(POS$y * diff(POS$x[1:2]))");
rengine.eval("cdfPOS <- cdfPOS / max(cdfPOS)");
//for negative scores
/////////////////////////////////////////////////////////////////////////////
//read the scores list
tempString = FileUtils.readFile(negDataPath);
if(tempString == null)
{
throw new Exception("Cannot read the contents of: " + negDataPath);
}
//parse it to a double array
rawScores = tempString.split("\n");
scoreList = new double[rawScores.length];
for (int i=0; i<rawScores.length; i++)
{
scoreList[i] = Double.parseDouble(rawScores[i]);
}
//send it to R
rengine.assign("X", scoreList);
rengine.eval("NEG <- density(X)", true);
rengine.eval("cdfNEG <- cumsum(NEG$y * diff(NEG$x[1:2]))");
rengine.eval("cdfNEG <- cdfNEG / max(cdfNEG)");
}
catch(Exception e)
{
e.printStackTrace();
retVal = false;
}
return retVal;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////// SCORING FUNCTIONS /////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**evaluates the score of word. Gives the probability of that word having that score.
*
* WARNING: do not use this function without calling setEnvForSental() first.
*
* @author erhan sezerer
*
* @param wordScore
* @param SentimentScoreType - type(pos, neg, obj) of score that is searched
*
* @return double - score of the word in given type, -1 if there is an error
*/
public double evaluateScore(final double wordScore, final SentimentScoreType type)
{
double score = -1;
REXP rexp;
try
{
//calculate the probability from the appropriate graph(graoh of pos scores, graph of neg scores, etc.)
switch(type)
{
case POS: rengine.eval("avgPosition <- " + (512* (wordScore/1) ));
rexp = rengine.eval("cdfPOS[avgPosition]", true);
break;
case NEG: rengine.eval("avgPosition <- " + (512* (wordScore/1) ));
rexp = rengine.eval("cdfNEG[avgPosition]", true);
break;
case OBJ: rengine.eval("avgPosition <- " + (512* (wordScore/1) ));
rexp = rengine.eval("cdfOBJ[avgPosition]", true);
break;
default: throw new Exception("unknown score type\n");
}
//get the area under the graph
score = rexp.asDouble();
}
catch(Exception e)
{
e.printStackTrace();
score = -1;
}
return score;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////// OTHER FUNCTIONS /////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void closeConnection()
{
rengine.end();
}
}
|
package de.refugium.meta.extraUtils.utilities;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import de.refugium.meta.extraUtils.Main;
public class BookShelfHandler extends Utilities {
private Main main;
private HashMap<String, Inventory> bookInvs;
public BookShelfHandler(Main main) {
super(main, "Bookshelf");
this.main = main;
bookInvs = new HashMap<String, Inventory>();
fillHashMap();
}
private void fillHashMap() {
new File(main.getConfigManager().getSrcFolder() + File.separator + "Bookshelfs").mkdirs();
for (File f : new File(main.getConfigManager().getSrcFolder() + File.separator + "Bookshelfs").listFiles()) {
if (f.toString().endsWith(".bookshelf")) {
Location loc = stringToLoc(f.toString().replaceAll(".bookshelf", ""));
Inventory inv = createInventory(loc);
YamlConfiguration c = YamlConfiguration.loadConfiguration(f);
for (int i = 0; i < 9 * 3; i++) {
inv.addItem(c.getItemStack(i + "") == null ? new ItemStack(Material.AIR) : c.getItemStack(i + ""));
}
}
}
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
return false;
}
@Override
public void addDefault() {
setDefault("Bookshelf.InventoryTitle", "&5Bookshelf");
}
@Override
public void onDisable() {
for (String key : bookInvs.keySet()) {
Inventory inv = bookInvs.get(key);
main.getConfigManager().createConfig(key + ".bookshelf", "Bookshelfs");
YamlConfiguration c = YamlConfiguration.loadConfiguration(main.getConfigManager().getConfig(key + ".bookshelf"));
ItemStack[] contents = inv.getContents();
for (int i = 0; i < 9 * 3; i++) {
c.set(i + "", contents[i] == null ? new ItemStack(Material.AIR) : contents[i]);
}
try {
c.save(main.getConfigManager().getConfig(key + ".bookshelf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@EventHandler
public void clickBookShelf(PlayerInteractEvent e) {
if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
if (e.getClickedBlock().getType().equals(Material.BOOKSHELF)) {
Location loc = e.getClickedBlock().getLocation();
if (bookInvs.containsKey(locToString(loc))) {
e.getPlayer().openInventory(bookInvs.get(locToString(loc)));
} else {
e.getPlayer().openInventory(createInventory(loc));
}
}
}
}
private Inventory createInventory(Location loc) {
Inventory inv = Bukkit.createInventory(null, 3 * 9, main.getConfig().getString("Bookshelf.InventoryTitle").replaceAll("&", ChatColor.COLOR_CHAR + ""));
bookInvs.put(locToString(loc), inv);
return inv;
}
private String locToString(Location loc) {
return new StringBuilder().append(loc.getWorld().getName()).append("#").append(loc.getBlockX()).append("#").append(loc.getBlockY()).append("#").append(loc.getBlockZ()).toString();
}
private Location stringToLoc(String s) {
String[] args = s.split("#");
return new Location(Bukkit.getWorld(args[0]) == null ? Bukkit.getWorlds().get(0) : Bukkit.getWorld(args[0]), Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3]));
}
@EventHandler
public void InventoryInteract(InventoryClickEvent e) {
if (!(e.getAction().equals(InventoryAction.NOTHING) || e.getAction().equals(InventoryAction.UNKNOWN))) {
if (e.getInventory().getTitle().equalsIgnoreCase(main.getConfig().getString("Bookshelf.InventoryTitle").replaceAll("&", ChatColor.COLOR_CHAR + ""))) {
switch (e.getCurrentItem().getType()) {
case BOOK:
case MAP:
case ENCHANTED_BOOK:
case PAPER:
return;
default:
e.setCancelled(true);
return;
}
}
}
}
}
|
/*
* 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 Filme.dao;
import Filme.model.Filme;
import cliente.dao.DataBaseConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
/**
*
* @author Kimbelly
*/
public class FilmeDAO {
public boolean inserirFilme(Filme filme) {
Connection connection = DataBaseConnection.getConexao();
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("INSERT INTO Filme (nome, id_filme )VALUES(?,?)");
statement.setString(1, filme.getNome());
statement.setInt(2, filme.getId());
statement.executeUpdate();
return true;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Não foi possível cadastrar: " + ex);
return false;
}
finally{
DataBaseConnection.fecharConexao(connection, statement);
}
}
public int buscarIdFilme() throws SQLException{
boolean result = false;
int idFilme = 0;
Connection connection = DataBaseConnection.getConexao();
PreparedStatement statement = null;
ResultSet rs = null;
try{
statement = connection.prepareStatement("SELECT max(id_filme) id_filme FROM Filme");
rs = statement.executeQuery();
rs.next();
idFilme = rs.getInt("id_filme");
}catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao buscar Id: " + ex);
}
finally{
DataBaseConnection.fecharConexao(connection, statement);
}
return idFilme;
}
public boolean editarFilme(Filme filme) {
Connection connection = DataBaseConnection.getConexao();
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("UPDATE Filme set nome = ? ,id = ? where id_filme = ?");
statement.setString(1, filme.getNome());
statement.setInt(2, filme.getId());
statement.executeUpdate();
return true;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Não foi possível editar filme: " + ex);
return false;
}
finally{
DataBaseConnection.fecharConexao(connection, statement);
}
}
public boolean removerFilme(int id_filme) {
Connection connection = DataBaseConnection.getConexao();
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("DELETE from Filme WHERE id_filme = ?");
statement.setInt(1, id_filme);
statement.executeUpdate();
return true;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao deletar Filme " + ex);
}
finally{
DataBaseConnection.fecharConexao(connection, statement);
}
return false;
}
public ArrayList<Filme> listaFilmes() {
ArrayList<Filme> listaFilmes = new ArrayList<Filme>();
Connection connection = DataBaseConnection.getConexao();
PreparedStatement statement = null;
ResultSet rs = null;
try {
statement = connection.prepareStatement("Select * from Filme");
rs = statement.executeQuery();
while (rs.next()){
Filme filme = new Filme();
filme.setId(rs.getInt("id"));
filme.setNome(rs.getString("nome"));
listaFilmes.add(filme);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao buscar filmes: " + ex);
}
finally{
DataBaseConnection.fecharConexao(connection, statement, rs);
}
return listaFilmes;
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.junit4.statements;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.runners.model.Statement;
import org.springframework.test.annotation.TestAnnotationUtils;
/**
* {@code SpringRepeat} is a custom JUnit {@link Statement} which adds support
* for Spring's {@link org.springframework.test.annotation.Repeat @Repeat}
* annotation by repeating the test the specified number of times.
*
* @author Sam Brannen
* @since 3.0
* @see #evaluate()
*/
public class SpringRepeat extends Statement {
protected static final Log logger = LogFactory.getLog(SpringRepeat.class);
private final Statement next;
private final Method testMethod;
private final int repeat;
/**
* Construct a new {@code SpringRepeat} statement for the supplied
* {@code testMethod}, retrieving the configured repeat count from the
* {@code @Repeat} annotation on the supplied method.
* @param next the next {@code Statement} in the execution chain
* @param testMethod the current test method
* @see TestAnnotationUtils#getRepeatCount(Method)
*/
public SpringRepeat(Statement next, Method testMethod) {
this(next, testMethod, TestAnnotationUtils.getRepeatCount(testMethod));
}
/**
* Construct a new {@code SpringRepeat} statement for the supplied
* {@code testMethod} and {@code repeat} count.
* @param next the next {@code Statement} in the execution chain
* @param testMethod the current test method
* @param repeat the configured repeat count for the current test method
*/
public SpringRepeat(Statement next, Method testMethod, int repeat) {
this.next = next;
this.testMethod = testMethod;
this.repeat = Math.max(1, repeat);
}
/**
* Evaluate the next {@link Statement statement} in the execution chain
* repeatedly, using the specified repeat count.
*/
@Override
public void evaluate() throws Throwable {
for (int i = 0; i < this.repeat; i++) {
if (this.repeat > 1 && logger.isTraceEnabled()) {
logger.trace(String.format("Repetition %d of test %s#%s()", (i + 1),
this.testMethod.getDeclaringClass().getSimpleName(), this.testMethod.getName()));
}
this.next.evaluate();
}
}
}
|
package com.example.hahademo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mr5.icarus.Callback;
import com.github.mr5.icarus.Icarus;
import com.github.mr5.icarus.TextViewToolbar;
import com.github.mr5.icarus.button.TextViewButton;
import com.github.mr5.icarus.entity.Options;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MainActivity extends AppCompatActivity {
WebView webView;
Button button;
Icarus icarus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.wb);
button = (Button) findViewById(R.id.btn);
final TextViewToolbar toolbar = new TextViewToolbar();
Options options = new Options();
options.setPlaceholder("请输入歌词");
icarus = new Icarus(toolbar, options, webView);
TextView tv = (TextView) findViewById(R.id.tv);
TextViewButton tb = new TextViewButton(tv, icarus);
tb.setName(com.github.mr5.icarus.button.Button.NAME_ALIGN_CENTER);
toolbar.addButton(tb);
TextView tv1 = (TextView) findViewById(R.id.tv2);
TextViewButton tb1 = new TextViewButton(tv1, icarus);
tb1.setName(com.github.mr5.icarus.button.Button.NAME_BOLD);
toolbar.addButton(tb1);
icarus.loadCSS("file:///android_asset/editor.css");
icarus.loadJs("file:///android_asset/test.js");
icarus.render();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
icarus.getContent(new Callback() {
public void run(String params) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
Gson gson = new Gson();
LrcHtmlBean lrcHtml = gson.fromJson(params, new TypeToken<LrcHtmlBean>() {
}.getType());
intent.putExtra("html",lrcHtml.getContent());
startActivity(intent);
Log.i("MainActivity",params);
Toast.makeText(MainActivity.this, "获取的" + params, Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
|
package network.nerve.dex.util;
import io.nuls.base.basic.AddressTool;
import io.nuls.base.data.CoinData;
import io.nuls.base.data.CoinFrom;
import io.nuls.base.data.CoinTo;
import io.nuls.base.data.NulsHash;
import io.nuls.core.crypto.HexUtil;
import io.nuls.core.exception.NulsRuntimeException;
import io.nuls.core.rockdb.service.RocksDBService;
import network.nerve.dex.context.DexConstant;
import network.nerve.dex.context.DexContext;
import network.nerve.dex.context.DexErrorCode;
import network.nerve.dex.model.po.CoinTradingPo;
import network.nerve.dex.model.po.TradingOrderPo;
import network.nerve.dex.model.txData.CoinTrading;
import network.nerve.dex.model.txData.TradingOrder;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
/**
* dex模块,通用工具类
*/
public class DexUtil {
public static void createTable(String name) {
if (!RocksDBService.existTable(name)) {
try {
RocksDBService.createTable(name);
} catch (Exception e) {
LoggerUtil.dexLog.error(e);
throw new NulsRuntimeException(DexErrorCode.SYS_UNKOWN_EXCEPTION);
}
}
}
/**
* 通过币对id信息生成key
*
* @param chainId1
* @param assetId1
* @param chainId2
* @param assetId2
* @return
*/
public static String toCoinTradingKey(int chainId1, int assetId1, int chainId2, int assetId2) {
return chainId1 + "-" + assetId1 + "-" + chainId2 + "-" + assetId2;
}
/**
* 获取base开头的币对id
*
* @param po
* @return
*/
public static String getCoinTradingKey1(CoinTradingPo po) {
return po.getBaseAssetChainId() + "-" + po.getBaseAssetId() + "-" + po.getQuoteAssetChainId() + "-" + po.getQuoteAssetId();
}
public static String getCoinKey(String address, int assetChainId, int assetId) {
return address + "-" + assetChainId + "-" + assetId;
}
public static String getCoinKey(String address, int assetChainId, int assetId, int locked) {
return address + "-" + assetChainId + "-" + assetId + "-" + locked;
}
public static String getOrderNonceKey(byte[] nonce, byte[] address, int assetChainId, int assetId) {
return HexUtil.encode(nonce) + "-" + AddressTool.getStringAddressByBytes(address) + "-" + assetChainId + "-" + assetId;
}
public static byte[] getNonceByHash(NulsHash hash) {
byte[] out = new byte[8];
byte[] in = hash.getBytes();
int copyEnd = in.length;
System.arraycopy(in, (copyEnd - 8), out, 0, 8);
return out;
}
/**
* 生成成交交易的coinData
*
* @return
*/
public static Map<String, Object> createDealTxCoinData(CoinTradingPo tradingPo, BigInteger price,
TradingOrderPo buyOrder, TradingOrderPo sellOrder) {
CoinData coinData = new CoinData();
addCoinFrom(tradingPo, buyOrder, sellOrder, coinData);
return addCoinTo(tradingPo, price, buyOrder, sellOrder, coinData);
}
/**
* 生成成交交易的from ,解锁用户锁定挂单剩余数量的币
* from的第一条数据强制为买单的解锁信息,第二条为卖单的解锁信息
*
* @param tradingPo
* @param buyOrder
* @param sellOrder
*/
public static void addCoinFrom(CoinTradingPo tradingPo, TradingOrderPo buyOrder, TradingOrderPo sellOrder, CoinData coinData) {
//添加买单from
CoinFrom from1 = new CoinFrom();
from1.setAssetsChainId(tradingPo.getQuoteAssetChainId());
from1.setAssetsId(tradingPo.getQuoteAssetId());
from1.setAddress(buyOrder.getAddress());
from1.setNonce(buyOrder.getNonce());
from1.setAmount(buyOrder.getLeftQuoteAmount());
from1.setLocked(DexConstant.ASSET_LOCK_TYPE);
coinData.addFrom(from1);
//添加卖单from
CoinFrom from2 = new CoinFrom();
from2.setAssetsChainId(tradingPo.getBaseAssetChainId());
from2.setAssetsId(tradingPo.getBaseAssetId());
from2.setAddress(sellOrder.getAddress());
from2.setNonce(sellOrder.getNonce());
from2.setAmount(sellOrder.getLeftAmount());
from2.setLocked(DexConstant.ASSET_LOCK_TYPE);
coinData.addFrom(from2);
}
/**
* 根据成交量,生成成交交易的to
* 生成to的顺序也是强制的,详细顺序见DexService.createDealTx
*
* @param tradingPo
* @param buyOrder
* @param sellOrder
*/
private static Map<String, Object> addCoinTo(CoinTradingPo tradingPo, BigInteger priceBigInteger,
TradingOrderPo buyOrder, TradingOrderPo sellOrder, CoinData coinData) {
BigDecimal price = new BigDecimal(priceBigInteger).movePointLeft(tradingPo.getQuoteDecimal());
if (buyOrder.getLeftAmount().compareTo(sellOrder.getLeftAmount()) == 0) {
//如果两边所剩交易币种余数量刚好相等
return processWithEqual(coinData, tradingPo, price, buyOrder, sellOrder);
} else if (buyOrder.getLeftAmount().compareTo(sellOrder.getLeftAmount()) < 0) {
//如果买单剩余交易币种数量少于卖单剩余数量
return processBuyLess(coinData, tradingPo, price, buyOrder, sellOrder);
} else {
//如果买单剩余交易币种数量大于卖单剩余数量,需要按照卖单实际剩余数量计算,可以兑换多少基础币种
return processSellLess(coinData, tradingPo, price, buyOrder, sellOrder);
}
}
private static Map<String, Object> processWithEqual(CoinData coinData, CoinTradingPo tradingPo, BigDecimal price,
TradingOrderPo buyOrder, TradingOrderPo sellOrder) {
Map<String, Object> map = new HashMap<>();
//首先用卖单的交易币种剩余数量 * 单价 ,计算得到可以兑换到的计价币种总量
BigDecimal amount = new BigDecimal(sellOrder.getLeftAmount()).movePointLeft(tradingPo.getBaseDecimal());
amount = amount.multiply(price).movePointRight(tradingPo.getQuoteDecimal()).setScale(0, RoundingMode.DOWN);
BigInteger quoteAmount = amount.toBigInteger(); //最终可以兑换到的计价币种总量
addDealCoinTo(map, coinData, tradingPo, quoteAmount, buyOrder, sellOrder.getLeftAmount(), sellOrder);
//交易完全成交后,也许买单会有剩余未花费的币,这时需要将剩余币退还给买单用户
returnBuyLeftAmountCoinTo(coinData, tradingPo, buyOrder, buyOrder.getLeftQuoteAmount().subtract(quoteAmount));
map.put("isBuyOver", true);
map.put("isSellOver", true);
map.put("quoteAmount", quoteAmount);
map.put("baseAmount", sellOrder.getLeftAmount());
map.put("coinData", coinData);
return map;
}
private static Map<String, Object> processBuyLess(CoinData coinData, CoinTradingPo tradingPo, BigDecimal price,
TradingOrderPo buyOrder, TradingOrderPo sellOrder) {
Map<String, Object> map = new HashMap<>();
//如果买单剩余交易币种数量少于卖单剩余数量,那么卖单需要支付的数量就是买单剩余数量
//再用最终成交价格计算出买单应该支付多少计价货币给卖家
BigDecimal amount = new BigDecimal(buyOrder.getLeftAmount()).movePointLeft(tradingPo.getBaseDecimal());
amount = amount.multiply(price).movePointRight(tradingPo.getQuoteDecimal()).setScale(0, RoundingMode.DOWN);
BigInteger quoteAmount = amount.toBigInteger(); //最终可以兑换到的计价币种总量
addDealCoinTo(map, coinData, tradingPo, quoteAmount, buyOrder, buyOrder.getLeftAmount(), sellOrder);
//交易完全成交后,也许买单会有剩余未花费的币,这时需要将剩余币退还给买单用户
returnBuyLeftAmountCoinTo(coinData, tradingPo, buyOrder, buyOrder.getLeftQuoteAmount().subtract(quoteAmount));
//检查卖单剩余币是否支持继续交易,支持则继续锁定,不支持则退还给卖家
boolean isSellOver = addSellLeftAmountCoinTo(coinData, tradingPo, sellOrder, sellOrder.getLeftAmount().subtract(buyOrder.getLeftAmount()));
map.put("isBuyOver", true);
map.put("isSellOver", isSellOver);
map.put("quoteAmount", quoteAmount);
map.put("baseAmount", buyOrder.getLeftAmount());
map.put("coinData", coinData);
return map;
}
private static Map<String, Object> processSellLess(CoinData coinData, CoinTradingPo tradingPo, BigDecimal price,
TradingOrderPo buyOrder, TradingOrderPo sellOrder) {
Map<String, Object> map = new HashMap<>();
//如果买单剩余数量大于卖单剩余数量,则需要按照卖单剩余交易币种数量计算买单应该支付多少计价币
BigDecimal amount = new BigDecimal(sellOrder.getLeftAmount()).movePointLeft(tradingPo.getBaseDecimal());
amount = amount.multiply(price).movePointRight(tradingPo.getQuoteDecimal()).setScale(0, RoundingMode.DOWN);
BigInteger quoteAmount = amount.toBigInteger(); //最终可以兑换到的计价币种总量
addDealCoinTo(map, coinData, tradingPo, quoteAmount, buyOrder, sellOrder.getLeftAmount(), sellOrder);
//检查买单剩余币是否支持继续交易,支持则继续锁定,不支持则退还给买家
boolean isBuyOver = addBuyLeftAmountCoinTo(coinData, tradingPo, buyOrder, buyOrder.getLeftAmount().subtract(sellOrder.getLeftAmount()), buyOrder.getLeftQuoteAmount().subtract(quoteAmount));
map.put("isBuyOver", isBuyOver);
map.put("isSellOver", true);
map.put("quoteAmount", quoteAmount);
map.put("baseAmount", sellOrder.getLeftAmount());
map.put("coinData", coinData);
return map;
}
/**
* 添加成交交易必然生成的4条to记录
* 买单成交to
* 卖单成交to
* 买单手续费to
* 卖单手续费to
*/
private static void addDealCoinTo(Map<String, Object> map, CoinData coinData, CoinTradingPo tradingPo,
BigInteger quoteAmount, TradingOrderPo buyOrder,
BigInteger baseAmount, TradingOrderPo sellOrder) {
//1.首先计算买卖双方各自需要支付的系统手续费,默认系统手续费为 2/10000
//若计算出手续费小于资产最小支持位数时,默认收取资产最小单位为手续费
//卖方需要支付的系统手续费
BigDecimal sellSysFee = new BigDecimal(quoteAmount).multiply(DexContext.sysFeeScaleDecimal).divide(DexConstant.PROP, 0, RoundingMode.HALF_DOWN);
if (sellSysFee.compareTo(BigDecimal.ONE) < 0) {
sellSysFee = BigDecimal.ONE;
}
//买方需要支付的系统手续费
BigDecimal buySysFee = new BigDecimal(baseAmount).multiply(DexContext.sysFeeScaleDecimal).divide(DexConstant.PROP, 0, RoundingMode.HALF_DOWN);
if (buySysFee.compareTo(BigDecimal.ONE) < 0) {
buySysFee = BigDecimal.ONE;
}
//2.若委托单上有设置运营节点收取手续费地址,也需要计算
//卖方需要支付的节点手续费
BigDecimal sellNodeFee = BigDecimal.ZERO;
if (sellOrder.getFeeAddress() != null && sellOrder.getFeeAddress().length > 0 && sellOrder.getFeeScale() > 0) {
sellNodeFee = new BigDecimal(quoteAmount).multiply(new BigDecimal(sellOrder.getFeeScale())).divide(DexConstant.PROP, 0, RoundingMode.HALF_DOWN);
if (sellNodeFee.compareTo(BigDecimal.ONE) < 0) {
sellNodeFee = BigDecimal.ONE;
}
}
//买方需要支付的节点手续费
BigDecimal buyNodeFee = BigDecimal.ZERO;
if (buyOrder.getFeeAddress() != null && buyOrder.getFeeAddress().length > 0 && buyOrder.getFeeScale() > 0) {
buyNodeFee = new BigDecimal(baseAmount).multiply(new BigDecimal(buyOrder.getFeeScale())).divide(DexConstant.PROP, 0, RoundingMode.HALF_DOWN);
if (buyNodeFee.compareTo(BigDecimal.ONE) < 0) {
buyNodeFee = BigDecimal.ONE;
}
}
BigInteger sellFee = sellSysFee.add(sellNodeFee).toBigInteger();
BigInteger buyFee = buySysFee.add(buyNodeFee).toBigInteger();
//生成交易的to,将成交后的币转到对方的账户上
//对方实际收到的数量,是减去了手续费之后的
CoinTo to1, to2, to3, to4, to5 = null, to6 = null;
//卖方收到计价币种
to1 = new CoinTo(sellOrder.getAddress(), tradingPo.getQuoteAssetChainId(), tradingPo.getQuoteAssetId(), quoteAmount.subtract(sellFee));
//买方收到交易币种
to2 = new CoinTo(buyOrder.getAddress(), tradingPo.getBaseAssetChainId(), tradingPo.getBaseAssetId(), baseAmount.subtract(buyFee));
//支付手续费
//卖方支付系统手续费
to3 = new CoinTo(DexContext.sysFeeAddress, tradingPo.getQuoteAssetChainId(), tradingPo.getQuoteAssetId(), sellSysFee.toBigInteger());
//买方支付系统手续费
to4 = new CoinTo(DexContext.sysFeeAddress, tradingPo.getBaseAssetChainId(), tradingPo.getBaseAssetId(), buySysFee.toBigInteger());
//卖方支付节点手续费
if (sellNodeFee.compareTo(BigDecimal.ZERO) > 0) {
if (Arrays.equals(DexContext.sysFeeAddress, sellOrder.getFeeAddress())) {
//如果系统收取手续费地址和节点手续费地址配置一致,则直接合并
to3.setAmount(to3.getAmount().add(sellNodeFee.toBigInteger()));
} else if (Arrays.equals(sellOrder.getAddress(), sellOrder.getFeeAddress())) {
//如果卖单地址和节点手续费地址配置一致,则直接合并
to1.setAmount(to1.getAmount().add(sellNodeFee.toBigInteger()));
} else {
to5 = new CoinTo(sellOrder.getFeeAddress(), tradingPo.getQuoteAssetChainId(), tradingPo.getQuoteAssetId(), sellNodeFee.toBigInteger());
}
}
//买方支付节点手续费
if (buyNodeFee.compareTo(BigDecimal.ZERO) > 0) {
if (Arrays.equals(DexContext.sysFeeAddress, buyOrder.getFeeAddress())) {
//如果系统收取手续费地址和节点手续费地址配置一致,则直接合并
to4.setAmount(to4.getAmount().add(buyNodeFee.toBigInteger()));
} else if (Arrays.equals(buyOrder.getAddress(), buyOrder.getFeeAddress())) {
//如果买单地址和节点手续费地址配置一致,则直接合并
to2.setAmount(to2.getAmount().add(buyNodeFee.toBigInteger()));
} else {
to6 = new CoinTo(buyOrder.getFeeAddress(), tradingPo.getBaseAssetChainId(), tradingPo.getBaseAssetId(), buyNodeFee.toBigInteger());
}
}
coinData.addTo(to1);
coinData.addTo(to2);
coinData.addTo(to3);
coinData.addTo(to4);
if (to5 != null) {
coinData.addTo(to5);
}
if (to6 != null) {
coinData.addTo(to6);
}
map.put("sellFee", sellFee);
map.put("buyFee", buyFee);
}
/**
* 交易完全成交后,将买单剩余基础币数量退还给买单用户
*
* @param coinData
* @param tradingPo
* @param buyOrder
* @param leftAmount
* @return
*/
private static void returnBuyLeftAmountCoinTo(CoinData coinData, CoinTradingPo tradingPo, TradingOrderPo buyOrder, BigInteger leftAmount) {
if (leftAmount.compareTo(BigInteger.ZERO) == 0) {
return;
}
CoinTo to = new CoinTo(buyOrder.getAddress(), tradingPo.getQuoteAssetChainId(), tradingPo.getQuoteAssetId(), leftAmount);
to.setLockTime(0);
CoinTo to0 = coinData.getTo().get(0);
//存在一种极端情况,就是买家和卖家是同一个账户,这时就将剩余金额加在一起
if (to0.getAssetsChainId() == to.getAssetsChainId() && to0.getAssetsId() == to.getAssetsId() && Arrays.equals(to0.getAddress(), to.getAddress())) {
to0.setAmount(to0.getAmount().add(to.getAmount()));
} else {
coinData.addTo(to);
}
}
private static boolean addBuyLeftAmountCoinTo(CoinData coinData, CoinTradingPo tradingPo, TradingOrderPo buyOrder, BigInteger leftAmount, BigInteger leftQuoteAmount) {
//如果剩余买单未成交的币已经小于一定数量时(最小成交额的1/10),
//或者剩余币数量已经无法购买到兑换币的最小单位则退还给用户,否则继续锁定
boolean buyOver = false;
if (leftAmount.compareTo(tradingPo.getMinBaseAmount().divide(BigInteger.TEN)) <= 0 || leftAmount.compareTo(BigInteger.TEN) <= 0) {
buyOver = true;
}
if (!buyOver) {
BigDecimal price = new BigDecimal(buyOrder.getPrice()).movePointLeft(tradingPo.getQuoteDecimal());
BigDecimal sellDecimal = new BigDecimal(leftAmount);
sellDecimal = sellDecimal.movePointLeft(tradingPo.getBaseDecimal());
sellDecimal = sellDecimal.multiply(price).movePointRight(tradingPo.getQuoteDecimal()); //总量 * 单价 = 总兑换数量
sellDecimal = sellDecimal.setScale(0, RoundingMode.DOWN);
//如果一个都不能兑换,则视为挂单已完全成交
//这里比较的时候为10,是因为包含手续费需要支付3-8个最小单位
if (sellDecimal.compareTo(BigDecimal.TEN) <= 0) {
buyOver = true;
}
}
CoinTo to = new CoinTo(buyOrder.getAddress(), tradingPo.getQuoteAssetChainId(), tradingPo.getQuoteAssetId(), leftQuoteAmount);
if (buyOver) {
CoinTo to0 = coinData.getTo().get(0);
//存在一种极端情况,就是买家和卖家是同一个账户,这时就将剩余金额加在一起
if (to0.getAssetsChainId() == to.getAssetsChainId() && to0.getAssetsId() == to.getAssetsId() && Arrays.equals(to0.getAddress(), to.getAddress())) {
to0.setAmount(to0.getAmount().add(to.getAmount()));
} else {
to.setLockTime(0);
coinData.addTo(to);
}
} else {
to.setLockTime(DexConstant.DEX_LOCK_TIME);
coinData.addTo(to);
}
return buyOver;
}
private static boolean addSellLeftAmountCoinTo(CoinData coinData, CoinTradingPo tradingPo, TradingOrderPo sellOrder, BigInteger leftAmount) {
//如果剩余卖单未成交的币已经小于一定数量时(最小成交额的1/10),
//或者剩余币数量已经无法购买到兑换币的最小单位则退还给用户,否则继续锁定
boolean sellOver = false;
if (leftAmount.compareTo(tradingPo.getMinBaseAmount().divide(BigInteger.TEN)) <= 0 || leftAmount.compareTo(BigInteger.TEN) <= 0) {
sellOver = true;
}
if (!sellOver) {
//用卖单的价格作为最终成交价, 计算卖单剩余数量的交易币种,可以兑换多少基础币种
BigDecimal price = new BigDecimal(sellOrder.getPrice()).movePointLeft(tradingPo.getQuoteDecimal());
BigDecimal sellDecimal = new BigDecimal(leftAmount);
sellDecimal = sellDecimal.movePointLeft(tradingPo.getBaseDecimal());
sellDecimal = sellDecimal.multiply(price).movePointRight(tradingPo.getQuoteDecimal()); //总量 * 单价 = 总兑换数量
sellDecimal = sellDecimal.setScale(0, RoundingMode.DOWN);
//如果一个都不能兑换,则视为挂单已完全成交
//这里比较的时候为10,是因为包含手续费需要支付3-8个最小单位
if (sellDecimal.compareTo(BigDecimal.TEN) <= 0) {
sellOver = true;
}
}
CoinTo to = new CoinTo(sellOrder.getAddress(), tradingPo.getBaseAssetChainId(), tradingPo.getBaseAssetId(), leftAmount);
if (sellOver) {
CoinTo to1 = coinData.getTo().get(1);
//存在一种极端情况,就是买家和卖家是同一个账户,这时就将剩余金额加在一起
if (to1.getAssetsChainId() == to.getAssetsChainId() && to1.getAssetsId() == to.getAssetsId() && Arrays.equals(to1.getAddress(), to.getAddress())) {
to1.setAmount(to1.getAmount().add(to.getAmount()));
} else {
to.setLockTime(0);
coinData.addTo(to);
}
} else {
to.setLockTime(DexConstant.DEX_LOCK_TIME);
coinData.addTo(to);
}
return sellOver;
}
/**
* 组装交易对txData
*
* @param param
* @return
*/
public static CoinTrading createCoinTrading(Map<String, Object> param, String address) {
CoinTrading trading = new CoinTrading();
trading.setAddress(AddressTool.getAddress(address));
trading.setQuoteAssetChainId((Integer) param.get("quoteAssetChainId"));
trading.setQuoteAssetId((Integer) param.get("quoteAssetId"));
trading.setScaleQuoteDecimal(Byte.parseByte(param.get("scaleQuoteDecimal").toString()));
trading.setBaseAssetChainId((Integer) param.get("baseAssetChainId"));
trading.setBaseAssetId((Integer) param.get("baseAssetId"));
trading.setScaleBaseDecimal(Byte.parseByte(param.get("scaleBaseDecimal").toString()));
trading.setMinBaseAmount(new BigInteger(param.get("minBaseAmount").toString()));
trading.setMinQuoteAmount(new BigInteger(param.get("minQuoteAmount").toString()));
return trading;
}
public static TradingOrder createTradingOrder(NulsHash tardingHash, int type, BigInteger amount, BigInteger price, String address) {
TradingOrder order = new TradingOrder();
order.setTradingHash(tardingHash.getBytes());
order.setAmount(amount);
order.setPrice(price);
order.setType((byte) type);
order.setAddress(AddressTool.getAddress(address));
// order.setFeeScale((byte) 5);
// order.setFeeAddress(AddressTool.getAddress("TNVTdTSPSrHdJthxhRTCnMZZkUPtPPrrkJKWA"));
return order;
}
}
|
package dwz.common.util.ip;
/**
* @Author: LCF
* @Date: 2020/1/8 15:35
* @Package: dwz.common.util.ip
*/
public class IpRangeUtils {
private static final String REGX_IP = "((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";
private static final String REGX_IPB = REGX_IP + "\\-" + REGX_IP;
/**
* 判断IP是否在指定范围;
*/
public static boolean ipIsValid(String ipSection, String ip) {
if (ipSection == null)
throw new NullPointerException("IP段不能为空!");
if (ip == null)
throw new NullPointerException("IP不能为空!");
ipSection = ipSection.trim();
ip = ip.trim();
//单IP匹配
if (ipSection.matches(REGX_IP)) {
return ipSection.equals(ip);
}
//IP段匹配 102.168.1.1-192.168.1.100
if (!ipSection.matches(REGX_IPB) || !ip.matches(REGX_IP))
return false;
int idx = ipSection.indexOf('-');
String[] sips = ipSection.substring(0, idx).split("\\.");
String[] sipe = ipSection.substring(idx + 1).split("\\.");
String[] sipt = ip.split("\\.");
long ips = 0L, ipe = 0L, ipt = 0L;
for (int i = 0; i < 4; ++i) {
ips = ips << 8 | Integer.parseInt(sips[i]);
ipe = ipe << 8 | Integer.parseInt(sipe[i]);
ipt = ipt << 8 | Integer.parseInt(sipt[i]);
}
if (ips > ipe) {
long t = ips;
ips = ipe;
ipe = t;
}
return ips <= ipt && ipt <= ipe;
}
/**
* @param ipRangeContent:192.168.1.1-192.168.1.100 过个IP段用换行风格
* @return
*/
public static String fixIpRanges(String ipRangeContent) {
StringBuilder sb = new StringBuilder();
if (ipRangeContent != null && ipRangeContent.length() > 0) {
String[] rows = ipRangeContent.split("(\\r\\n|\\n)");
for (String row : rows) {
if (row.matches(REGX_IPB) || row.matches(REGX_IP)) {
sb.append(row).append("\n");
}
}
}
return sb.toString();
}
public static void main(String[] args) {
if (ipIsValid("192.168.1.1-192.168.1.100", "192.168.1.1")) {
System.out.println("ip属于该网段");
} else
System.out.println("ip不属于该网段");
System.out.println(ipIsValid("192.168.1.1", "192.168.1.1"));
}
}
|
package com.mountblue.kbrshoppingsite.model;
import org.hibernate.annotations.Formula;
import javax.persistence.*;
@Entity
@Table(name = "stocks")
public class Stock {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "stock_id")
private long id;
@OneToOne(targetEntity = Product.class, fetch = FetchType.EAGER)
@JoinColumn(nullable = false, name = "product_id")
private Product product;
private Float productQuantityInStock;
private boolean isEmptyStock;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Float getProductQuantityInStock() {
return productQuantityInStock;
}
public void setProductQuantityInStock(Float productQuantityInStock) {
this.productQuantityInStock = productQuantityInStock;
}
public boolean isEmptyStock() {
return isEmptyStock;
}
public void setEmptyStock(boolean emptyStock) {
isEmptyStock = emptyStock;
}
}
|
package packageclass;
public class Bai5 {
public static void main(String[] args) {
int a=2;
System.out.println("Bảng Cửu Chương 2");
for (int i=1; i<=10 ; i++) {
System.out.println(a + " x " + i + " = " + a*i);
if (i==10) {
a++;
i=0;
if (a==11) {
break;
}
System.out.println("Bảng Cửu Chương " + a);
}
}
}
}
|
package Teatrus.model;
import java.io.Serializable;
public class Pozitie implements Serializable {
private int rand,coloana;
public Pozitie(int rand, int coloana) {
this.rand = rand;
this.coloana = coloana;
}
public int getRand() {
return rand;
}
public void setRand(int rand) {
this.rand = rand;
}
public int getColoana() {
return coloana;
}
public void setColoana(int coloana) {
this.coloana = coloana;
}
}
|
//----------------------------------------------------
// The following code was generated by CUP v0.11b 20160615 (GIT 4ac7450)
//----------------------------------------------------
/** CUP generated class containing symbol constants. */
public class sym {
/* terminals */
public static final int _new = 13;
public static final int _plus = 22;
public static final int _assignop = 36;
public static final int _mod = 26;
public static final int _println = 16;
public static final int _greater = 29;
public static final int _return = 18;
public static final int _leftbrace = 44;
public static final int _minus = 23;
public static final int _null = 15;
public static final int _rightbracket = 43;
public static final int _readln = 17;
public static final int _void = 20;
public static final int _comma = 38;
public static final int _class = 4;
public static final int _multiplication = 24;
public static final int UNARYMINUS = 51;
public static final int _else = 6;
public static final int _division = 25;
public static final int _boolean = 2;
public static final int _equal = 31;
public static final int _rightbrace = 45;
public static final int _leftbracket = 42;
public static final int EOF = 0;
public static final int _string = 19;
public static final int error = 1;
public static final int _break = 3;
public static final int _interface = 12;
public static final int _or = 34;
public static final int _leftparen = 40;
public static final int _notequal = 32;
public static final int _semicolon = 37;
public static final int _if = 9;
public static final int _id = 50;
public static final int _while = 21;
public static final int _lessequal = 28;
public static final int _doubleconstant = 47;
public static final int _int = 11;
public static final int _implements = 10;
public static final int _greaterequal = 30;
public static final int _period = 39;
public static final int _extends = 7;
public static final int _for = 8;
public static final int _not = 35;
public static final int _and = 33;
public static final int _double = 5;
public static final int _newarray = 14;
public static final int _stringconstant = 48;
public static final int _intconstant = 46;
public static final int _booleanconstant = 49;
public static final int _less = 27;
public static final int _rightparen = 41;
public static final String[] terminalNames = new String[] {
"EOF",
"error",
"_boolean",
"_break",
"_class",
"_double",
"_else",
"_extends",
"_for",
"_if",
"_implements",
"_int",
"_interface",
"_new",
"_newarray",
"_null",
"_println",
"_readln",
"_return",
"_string",
"_void",
"_while",
"_plus",
"_minus",
"_multiplication",
"_division",
"_mod",
"_less",
"_lessequal",
"_greater",
"_greaterequal",
"_equal",
"_notequal",
"_and",
"_or",
"_not",
"_assignop",
"_semicolon",
"_comma",
"_period",
"_leftparen",
"_rightparen",
"_leftbracket",
"_rightbracket",
"_leftbrace",
"_rightbrace",
"_intconstant",
"_doubleconstant",
"_stringconstant",
"_booleanconstant",
"_id",
"UNARYMINUS"
};
}
|
package com.lifeix.football.games.module.competition.service;
import java.util.List;
import com.lifeix.football.games.model.MatchTeam;
public interface MatchTeamService {
public List<MatchTeam> findMatchTeams(Long competitionId, Long teamId);
public MatchTeam findMatchTeam(Long matchTeamId);
}
|
package by.orion.onlinertasks.data.datasource.profiles.local;
import android.support.annotation.NonNull;
import com.pushtorefresh.storio.sqlite.StorIOSQLite;
import javax.inject.Inject;
import by.orion.onlinertasks.data.datasource.profiles.ProfilesDataSource;
import by.orion.onlinertasks.data.models.common.requests.ProfilesRequestParams;
import by.orion.onlinertasks.data.models.profile.ProfilesPage;
import io.reactivex.Completable;
import io.reactivex.Single;
public class LocalProfilesDataSource implements ProfilesDataSource {
@NonNull
private final StorIOSQLite storIOSQLite;
@Inject
public LocalProfilesDataSource(@NonNull StorIOSQLite storIOSQLite) {
this.storIOSQLite = storIOSQLite;
}
@Override
public Single getValue(@NonNull Object key) {
throw new UnsupportedOperationException();
}
@Override
public Completable setValue(@NonNull Object key, @NonNull Object value) {
throw new UnsupportedOperationException();
}
@Override
public Single<ProfilesPage> getAllProfiles(@NonNull ProfilesRequestParams params) {
throw new UnsupportedOperationException();
}
}
|
package com.game;
public class Player {
private String name;
private Disc[] discs;
private int playId = 0;
private boolean isMyTurn = true;
public Player(int count, String color) {
discs = new Disc[count];
for (int i = 0; i < count; i++) {
discs[i] = new Disc(color);
}
}
public boolean play(boolean isMyMove) {
if (playId > discs.length)
return false;
discs[playId++].setAlreadyPlayed(true);
isMyTurn = isMyMove;
return true;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Disc[] getDiscs() {
return discs;
}
public void setDiscs(Disc[] discs) {
this.discs = discs;
}
public int getPlayId() {
return playId;
}
public void setPlayId(int playId) {
this.playId = playId;
}
public boolean isMyTurn() {
return isMyTurn;
}
public void setMyTurn(boolean isMyTurn) {
this.isMyTurn = isMyTurn;
}
}
|
package com.vincent.algorithm.misc;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 交替打印0和1 ,美团面试题
*/
public class PrintOneAndZero {
public static void main(String[] args) {
method1();
}
/**
* 思路:
* 1.要交替打印,那么肯定是死循环
* 2.线程1要输出1后,线程2才能输出0.那意味着线程之间肯定有线程同步,需要使用一个共享变量去判断
* 3.所以这里使用AtomicInteger作为flag,保证两个线程使用这个共享变量时,线程可见。
* 4.每个线程再使用后,修改变量值,使得另外一个线程可以继续打印使用
*/
public static void method1(){
AtomicInteger flag = new AtomicInteger(1);
new Thread(() -> {
while (true) {
if(flag.get() == 1) {
System.out.println(1);
flag.set(0);
}
}
}).start();
new Thread(() -> {
while (true) {
if(flag.get() == 0) {
System.out.println(0);
flag.set(1);
}
}
}).start();
}
}
|
package com.baby.babygrowthrecord.user;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.baby.babygrowthrecord.R;
/**
* Created by think on 2016/11/22.
*/
public class UserSetting extends Activity {
private TextView tvHeadPic;
private TextView tvName;
private TextView tvUname;
private TextView tvPwd;
private View.OnClickListener myClickListener=new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent();
switch (v.getId()){
case R.id.tv_userSetting_pic:
i.setClass(UserSetting.this, UserSettingHeadPic.class);
startActivity(i);
break;
case R.id.tv_userSetting_name:
i.setClass(UserSetting.this,UserSettingName.class);
startActivity(i);
break;
case R.id.tv_userSetting_pwd:
i.setClass(UserSetting.this,UserSettingPwd.class);
startActivity(i);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_setting);
init();
}
private void init() {
tvHeadPic=(TextView)findViewById(R.id.tv_userSetting_pic);
tvName=(TextView)findViewById(R.id.tv_userSetting_name);
tvUname=(TextView)findViewById(R.id.tv_userSetting_uName);
tvPwd=(TextView)findViewById(R.id.tv_userSetting_pwd);
tvHeadPic.setOnClickListener(myClickListener);
tvName.setOnClickListener(myClickListener);
tvPwd.setOnClickListener(myClickListener);
}
}
|
package app;
import core.framework.module.App;
import core.framework.module.SystemModule;
/**
* @author neo
*/
public class DemoServiceApp extends App {
@Override
protected void initialize() {
http().httpsPort(8443);
load(new SystemModule("sys.properties"));
http().httpPort(8081);
load(new ProductModule());
load(new JobModule());
// load(new CustomerModule());
}
}
|
package DataStructures.string;
public class Atoi {
/**
* Input:
"2147483648"
Output:
-2147483648
Expected:
2147483647
" 010" --> 10
*/
public int atoi(String str) {
if (str == null || str.length() < 1) return 0;
str = str.trim();
double result = 0;
int s = 0;
char f = '+';
if (str.charAt(s) == '-') {
f = '-';
s++;
}
else if (str.charAt(s) == '+')
s++;
while (s < str.length() && str.charAt(s) >= '0' && str.charAt(s) <= '9') {
result = result * 10 + Character.getNumericValue(str.charAt(s)); //or result = result * 10 + (str.charAt(s) - '0');
s++;
}
if (f == '-') result = -result;
if (result > Integer.MAX_VALUE)
result = Integer.MAX_VALUE;
else if (result < Integer.MIN_VALUE)
result = Integer.MIN_VALUE;
return (int)result;
}
public static void main(String a[]) {
int val = -1;
System.out.println(Math.abs(val));
Atoi atoi = new Atoi();
System.out.println(atoi.atoi("-54332872018247709407 4 54"));
}
}
|
package com.sims.bo.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sims.bo.PatientBillPaymentBo;
import com.sims.dao.PatientBillPaymentDao;
import com.sims.model.PatientBillPayment;
/**
*
* @author dward
*
*/
@Service
public class PatientBillPaymentBoImpl implements PatientBillPaymentBo{
@Autowired
PatientBillPaymentDao patientBillPaymentDao;
public void setPatientBillPaymentDao(PatientBillPaymentDao patientBillPaymentDao){
this.patientBillPaymentDao = patientBillPaymentDao;
}
@Override
@Transactional
public boolean save(PatientBillPayment entity) {
entity.setDateOfPayment(new java.sql.Timestamp(System.currentTimeMillis()));
entity.setCreatedOn(new java.sql.Timestamp(System.currentTimeMillis()));
entity.setVersion(1);
entity.setActive(true);
return patientBillPaymentDao.save(entity);
}
}
|
package f.star.iota.milk.ui.mm8mm88.mm8mm;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import f.star.iota.milk.R;
import f.star.iota.milk.base.BaseAdapter;
public class MM8MMAdapter extends BaseAdapter<MM8MMViewHolder, MM8MMBean> {
@Override
public MM8MMViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MM8MMViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_description, parent, false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((MM8MMViewHolder) holder).bindView(mBeans.get(position));
}
}
|
package com.lyj.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author yingjie.lu
* @version 1.0
* @date 2020/1/6 3:56 下午
*/
@Component
public class IndexBean {
@Autowired
UserBean userBean;
}
|
/**
* Created by becky on 9/5/17.
*/
public class longestPalindrom {
public static String longestPalindrome(String s) {
if(s == null || s.length() < 2) return s;
char[] chars = s.toCharArray();
int len = s.length();
while (len >= 0) {
for (int i = 0; i + len - 1 < chars.length; i++) {
int left = i;
int right = i + len - 1;
boolean good = true;
while (left < right) {
if (chars[left] != chars[right]) {
good = false;
break;
}
left++;
right--;
}
if (good)
return s.substring(i, i + len);
}
--len;
}
return "";
}
public static int max, start, end;
public static String longestPalindrome1(String s) {
max = 0;
start = 0;
end = 0;
if(s == null || s.length() < 2) return s;
for(int i = 0; i < s.length(); i++)
{
findPalindrome(s, i, i);
if(i + 1 < s.length() && s.charAt(i) == s.charAt(i + 1)) findPalindrome(s, i, i + 1);
}
return s.substring(start, end + 1);
}
private static void findPalindrome(String s, int l, int r)
{
while(l - 1 >= 0 && r + 1 < s.length() && s.charAt(l - 1) == s.charAt(r + 1))
{
l--;
r++;
}
if(r - l + 1 > max)
{
max = r - l + 1;
start = l;
end = r;
}
}
public static void main(String[] args) {
System.out.println(longestPalindrome("babad"));
System.out.println(longestPalindrome1("babad"));
}
}
|
package decisao;
import javax.swing.JOptionPane;
public class DecisaoSimples {
public static void main(String[] args) {
// TODO Auto-generated method stub
String materia = JOptionPane.showInputDialog("Materia");
float nota1 = Float.parseFloat(JOptionPane.showInputDialog("nota1"));
float nota2 = Float.parseFloat(JOptionPane.showInputDialog("nota2"));
float media = (nota1 + nota2) /2;
if (media>=6) {
System.out.println("Parabens APROVADO em " + materia + " com Media: " + media);
}
if (media<4) {
System.out.println("Mandou muito mal em " + materia + " Refaça o curso pois sua media foi: " + media);
}
if (media>=4) {
System.out.println("Mais esforço em " + materia + " você foi reprovado com Media: " + media);
}
System.out.println("Media: " + media);
//else
}
}
|
package cn.android.support.v7.lib.sin.crown.widget;
import android.content.Context;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import java.util.HashMap;
import java.util.Map;
/**
* 弹性ScrollView【滑动原理,对scrollview里面的第一个View进行位置上下偏移滑动。】
* Created by 彭治铭 on 2018/4/25.
*/
public class BounceScrollView extends NestedScrollView {
private View inner;// 孩子View
private float y;// 点击时y坐标
private Rect normal = new Rect();// 矩形(这里只是个形式,只是用于判断是否需要动画.)
private boolean isCount = false;// 是否开始计算
private float lastX = 0;
private float lastY = 0;
private float currentX = 0;
private float currentY = 0;
private float distanceX = 0;
private float distanceY = 0;
private boolean upDownSlide = false; //判断上下滑动的flag
public BounceScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BounceScrollView(@NonNull Context context) {
super(context);
}
/***
* 根据 XML 生成视图工作完成.该函数在生成视图的最后调用,在所有子视图添加完之后. 即使子类覆盖了 onFinishInflate
* 方法,也应该调用父类的方法,使该方法得以执行.
*/
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if (getChildCount() > 0) {
inner = getChildAt(0);
}
}
public boolean isSlidingDown = false;//是否下滑。true 下滑,false上滑
private boolean isDownAnime = true;
private boolean isUpAnime = true;
public boolean openUpAnime = true;//fixme 上滑弹性动画开启。
public boolean openDownAnime = true;//fixme 下滑弹性动画开启
//解决嵌套滑动冲突。
@Override
public boolean startNestedScroll(int axes) {
//子View滑动时,禁止弹性动画。
isDownAnime = false;
isUpAnime = false;
return super.startNestedScroll(axes);
}
@Override
public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
//Log.e("test", "dyConsumed:\t" + dyConsumed + "\tdyUnconsumed:\t" + dyUnconsumed);
if (dyConsumed == 0) {
isDownAnime = true;
isUpAnime = true;
} else {
isDownAnime = false;
isUpAnime = false;
}
if (dyConsumed == 0 && dyUnconsumed == 0) {
isDownAnime = false;
isUpAnime = false;
}
return super.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow);
}
@Override
public void stopNestedScroll() {
super.stopNestedScroll();
//结束时,开启弹性滑动。
isDownAnime = true;
isUpAnime = true;
}
boolean isHorizon = false;//是否属于横屏滑动(水平滑动,不具备弹性效果)
boolean isfirst = true;//是否为第一次滑动。
byte isfirstDirection = 0;//第一次滑动方向,0初始化,没有方向,1 横屏方法,2 竖屏方向。
int inerTop = 0;//记录原始的顶部高度。
Map map = new HashMap<Integer, MPoint>();
class MPoint {
public float y;// 点击时y坐标
public float preY = y;// 按下时的y坐标
public float nowY = y;// 时时y坐标
public int deltaY = 0;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
if (inner == null) {
if (getChildCount() > 0) {
inner = getChildAt(0);
} else {
return super.dispatchTouchEvent(ev);
}
}
currentX = ev.getX();
currentY = ev.getY();
switch (ev.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
map.put(ev.getPointerId(ev.getActionIndex()), new MPoint());
// Log.e("test", "按下:\t" + ev.getPointerCount());
inerTop = inner.getTop();//原始顶部,不一定都是0,所以要记录一下。
isfirst = true;
isfirstDirection = 0;
break;
case MotionEvent.ACTION_POINTER_DOWN://第二个手指按下
map.put(ev.getPointerId(ev.getActionIndex()), new MPoint());
break;
case MotionEvent.ACTION_POINTER_UP:
map.remove(ev.getPointerId(ev.getActionIndex()));
break;
case MotionEvent.ACTION_MOVE:
distanceX = currentX - lastX;
distanceY = currentY - lastY;
// Log.e("test", "x滑动:\t" + distanceX + "\ty滑动:\t" + distanceY);
// Log.e("test", "currentX:\t" + currentX + "\tcurrentY:\t" + currentY);
if (distanceY > 0) {
isSlidingDown = true;//下滑大于0
} else {
isSlidingDown = false;//上滑小于0
}
if ((Math.abs(distanceX) < Math.abs(distanceY)) && Math.abs(distanceY) > 12) {
if (isfirstDirection == 0) {
isfirstDirection = 2;//上下方向
}
upDownSlide = true;//表示上下滑动
} else {
if (isfirstDirection == 0 && (Math.abs(distanceX) > Math.abs(distanceY))) {
isfirstDirection = 1;//水平滑动方向
}
}
if (isfirst) {
isHorizon = !upDownSlide;//横屏滑动(水平滑动,不具备弹性效果)
isfirst = false;
}
if (isfirstDirection == 2) {
isHorizon = false;//上下方向
} else if (isfirstDirection == 1) {
isHorizon = true;//水平方向
}
//Log.e("test", "x:\t" + Math.abs(distanceX) + "\ty:\t" + Math.abs(distanceY) + "\tisHorizon:\t" + isHorizon);
//Log.e("test","isSlidingDown:\t"+isSlidingDown+"\tisDownAnime:\t"+isDownAnime+"\tisHorizon:\t"+isHorizon+"\tupDownSlide:\t"+upDownSlide+"\tinner:\t"+inner+"\topenDownAnime:\t"+openDownAnime);
if (isSlidingDown && isDownAnime && !isHorizon) {
if (upDownSlide && inner != null && openDownAnime) {
commOnTouchEvent(ev);//fixme 开启下拉弹性
}
} else if (!isSlidingDown && isUpAnime && !isHorizon) {
if (upDownSlide && inner != null && openUpAnime) {
commOnTouchEvent(ev);//fixme 开启上拉弹性
}
}
break;
case MotionEvent.ACTION_UP:
// Log.e("test", "离开");
//以防万一,恢复原始状态
isDownAnime = true;
isUpAnime = true;
if (upDownSlide && inner != null) {
commOnTouchEvent(ev);
}
map.remove(ev.getPointerId(ev.getActionIndex()));
map.clear();
break;
default:
break;
}
lastX = currentX;
lastY = currentY;
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
//Log.e("test", "顶部Y:\t" + inner.getTop());
if (inner != null && inner.getTop() != inerTop) {
return true;//子View在移动的时候,拦截对子View的事件处理。
}
return super.onInterceptTouchEvent(e);
}
/***
* 监听touch
*/
@Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(ev);
}
boolean bAnime = false;//是否开始动画
/***
* 触摸事件
*
* @param ev
*/
public void commOnTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
// 手指松开.
if (isNeedAnimation()) {
animation();
isCount = false;
}
clear0();
break;
case MotionEvent.ACTION_MOVE:
final float preY = y;// 按下时的y坐标
float nowY = ev.getY();// 时时y坐标
int deltaY = (int) (preY - nowY);// 滑动距离
if (ev.getPointerCount() > 1) {
//多指滑动
for (int i = 0; i < ev.getPointerCount(); i++) {
MPoint m = (MPoint) map.get(ev.getPointerId(i));
m.preY = m.y;
m.nowY = ev.getY(i);
m.deltaY = (int) (m.preY - m.nowY);
if (i == 0) {
deltaY = (int) m.deltaY;
} else {
//移动距离取最大的
if (Math.abs(deltaY) < Math.abs(m.deltaY)) {
deltaY = (int) m.deltaY;
}
}
m.y = m.nowY;
}
}
if (!isCount) {
deltaY = 0; // 在这里要归0.
}
//Log.e("test","按下y:\t"+preY+"\tnowY:\t"+nowY+"\t距离:\t"+deltaY+"\t是否移动:\t"+isNeedMove());
y = nowY;
// Log.e("test", "deltaY滑动:\t" + deltaY);
// 当滚动到最上或者最下时就不会再滚动,这时移动布局/速度大于了200都是异常。不做移动处理
if (isNeedMove() && Math.abs(deltaY) < 200) {
// 初始化头部矩形
if (normal.isEmpty()) {
// 保存正常的布局位置
normal.set(inner.getLeft(), inner.getTop(),
inner.getRight(), inner.getBottom());
}
// 移动布局
int top = inner.getTop() - deltaY / 2;
int bottom = inner.getBottom() - deltaY / 2;
//移动最大不能超过总高度的一半
if (top < getHeight() / 2 && bottom > getHeight() / 2 && !bAnime) {
inner.layout(inner.getLeft(), top,
inner.getRight(), bottom);
} else {
animation();//恢复原状
}
}
isCount = true;
break;
default:
break;
}
}
/***
* 回缩动画
*/
public void animation() {
if (!bAnime) {
bAnime = true;//开始动画
int top = inner.getTop();
// 开启移动动画
TranslateAnimation ta = new TranslateAnimation(0, 0, inner.getTop(),
normal.top);
ta.setDuration(200);
ta.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
bAnime = false;//动画结束
}
@Override
public void onAnimationRepeat(Animation animation) {
bAnime = false;
}
});
inner.startAnimation(ta);
// 设置回到正常的布局位置
inner.layout(normal.left, normal.top, normal.right, normal.bottom);
normal.setEmpty();
}
}
// 是否需要开启动画
public boolean isNeedAnimation() {
return !normal.isEmpty();
}
/***
* 是否需要移动布局 inner.getMeasuredHeight():获取的是控件的总高度
*
* getHeight():获取的是屏幕的高度
*
* @return
*/
public boolean isNeedMove() {
int offset = inner.getMeasuredHeight() - getHeight();
int scrollY = getScrollY();
// 0是顶部,后面那个是底部
if (scrollY == 0 || scrollY == offset) {
return true;
}
return false;
}
private void clear0() {
lastX = 0;
lastY = 0;
distanceX = 0;
distanceY = 0;
upDownSlide = false;
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (scrollViewForTabListener != null) {
scrollViewForTabListener.onScrollChanged(this, l, t, oldl, oldt);
}
}
private ScrollViewForTabListener scrollViewForTabListener;
public void setScrollViewForTabListener(ScrollViewForTabListener scrollViewForTabListener) {
this.scrollViewForTabListener = scrollViewForTabListener;
}
public interface ScrollViewForTabListener {
void onScrollChanged(BounceScrollView bounceScrollView, int x, int y, int oldx, int oldy);
}
}
|
package view;
import controller.Features;
import image.Image;
/**
* Represents the operations that a multi-layer image processing GUI view has such as being able
* to add features from the Feature interface to the view.
*/
public interface ImageProcessingGUIView {
/**
* Adds all the features in the given feature to this view.
* @param features the features to implement
*/
void addFeatures(Features features);
/**
* Creates a pop-up error message with the given message in the multi-layer image processing
* program.
* @param message the error message
*/
void notifyErrorMessage(String message);
/**
* Shows the top-most visible image in all current layers.
* @param im The image to be shown.
* @param name The name of the image to be shown.
*/
void showTopMostImage(Image im, String name);
/**
* Adds the given name to the view's layer selection list.
* @param name The name to be added.
*/
void addToLayerSelectionList(String name);
/**
* Removes the given name from the view's layer selection list.
* @param name The name to be removed.
*/
void removeFromLayerSelectionList(String name);
}
|
package Validators;
import javax.swing.JOptionPane;
public class DateValidator implements Validator<String> {
public void validate(String date) {
if (!date.matches("^[0-9]{4}\\-[0-9]{2}\\-[0-9]{2}$")) { // match numbers
String message = "Wrong date format";
JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
|
package com.edasaki.rpg.commands.owner;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.edasaki.core.utils.RMessages;
import com.edasaki.core.utils.RScheduler;
import com.edasaki.core.utils.RTicks;
import com.edasaki.rpg.PlayerDataRPG;
import com.edasaki.rpg.commands.RPGAbstractCommand;
public class ShutdownCommand extends RPGAbstractCommand {
private boolean cancel = false;
// private boolean inProgress = false;
public ShutdownCommand(String... commandNames) {
super(commandNames);
}
@Override
public void execute(CommandSender sender, String[] args) {
StringBuilder sb = new StringBuilder();
if (args[0].equalsIgnoreCase("stop") || args[0].equalsIgnoreCase("cancel")) {
// inProgress = false;
cancel = true;
sender.sendMessage("Shutdown cancelled");
return;
}
// if (inProgress) {
// sender.sendMessage("Shutdown already in progress. Cancel it first.");
// return;
// }
int min = Integer.parseInt(args[0]);
String message = null;
if (args.length > 1) {
for (int k = 1; k < args.length; k++) {
sb.append(args[k]);
sb.append(' ');
}
message = sb.toString().trim();
}
final String fMessage = message;
// inProgress = true;
sender.sendMessage("Scheduled shutdown for " + min + " minutes");
RScheduler.schedule(plugin, new Runnable() {
int count = min;
public void run() {
if (cancel) {
cancel = false;
// inProgress = false;
return;
}
if (count > 0) {
RMessages.announce(ChatColor.translateAlternateColorCodes('&', "&c&l The server will be shutting down in &e&l" + count + " minute" + (count != 1 ? "s" : "") + "&c&l."));
if (count <= 5)
RMessages.announce(ChatColor.translateAlternateColorCodes('&', "&e&l Prepare to log off. &c&lSorry for the inconvenience!"));
if (fMessage != null) {
RMessages.announce(ChatColor.translateAlternateColorCodes('&', "&c&l The reason for the shutdown is:"));
RMessages.announce(ChatColor.translateAlternateColorCodes('&', "&7&l > &e&l" + fMessage));
}
int time = 1;
if (count >= 30)
time = 10;
else if (count >= 10)
time = 5;
count -= time;
RScheduler.schedule(plugin, this, RTicks.minutes(time));
} else {
RMessages.announce(ChatColor.translateAlternateColorCodes('&', "&c&l The server will be shutting down in &e&l10 seconds&c&l."));
RMessages.announce(ChatColor.translateAlternateColorCodes('&', "&e&l Prepare to log off. &c&lSorry for the inconvenience!"));
if (fMessage != null) {
RMessages.announce(ChatColor.translateAlternateColorCodes('&', "&c&l The reason for the shutdown is:"));
RMessages.announce(ChatColor.translateAlternateColorCodes('&', "&7&l > &e&l" + fMessage));
}
RScheduler.schedule(plugin, new Runnable() {
public void run() {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "maintenance owner");
}
}, RTicks.seconds(10));
}
}
});
}
@Override
public void executePlayer(Player p, PlayerDataRPG pd, String[] args) {
}
@Override
public void executeConsole(CommandSender sender, String[] args) {
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class bj1003 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
int[] one = new int[41];
one[0] = 0;
one[1] = 1;
int[] zero = new int[41];
zero[0] = 1;
zero[1] = 0;
for (int j = 2; j < 41; j++) {
one[j] = one[j - 1] + one[j - 2];
zero[j] = zero[j - 1] + zero[j - 2];
}
for (int i = 0; i < T; i++) {
int N = Integer.parseInt(br.readLine());
sb.append(zero[N]).append(" ").append(one[N]).append("\n");
}
System.out.println(sb);
}
}
|
package za.ac.ngosa.domain;
import javax.persistence.Entity;
import java.io.Serializable;
/**
* Created by User on 2015/08/10.
*/
@Entity
public class TVShow extends Showing implements Serializable{
private String episode;
private String season;
private TVShow(){}
public String getEpisode()
{
return episode;
}
public String getSeason()
{
return season;
}
public TVShow (Builder build)
{
this.episode= build.episode;
this.season= build.season;
setPrice(build.price);
setDuration(build.duration);
setGenre(build.genre);
setId(build.id);
setTitle(build.title);
}
public static class Builder
{
private String episode;
private String season;
private String duration;
private String genre;
private String title;
private double price;
private long id;
public Builder copy(TVShow value)
{
this.episode= value.getEpisode();
this.season= value.getSeason();
this.id= value.getId();
this.duration= value.getDuration();
this.genre= value.getGenre();
this.title= value.getTitle();
this.price= value.getPrice();
return this;
}
public Builder (long idValue)
{
this.id=idValue;
}
public Builder episode(String episodeValue)
{
this.episode=episodeValue;
return this;
}
public Builder season(String seasonValue)
{
this.season= seasonValue;
return this;
}
public Builder title(String titleValue)
{
this.title= titleValue;
return this;
}
public Builder duration(String durationValue)
{
this.duration=durationValue;
return this;
}
public Builder genre(String genreValue)
{
this.genre=genreValue;
return this;
}
public Builder price(double priceValue)
{
this.price=priceValue;
return this;
}
public TVShow build()
{
return new TVShow(this);
}
}
}
|
package com.bestseller.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bestseller.pojo.Buyer;
import com.bestseller.service.BuyerService;
import com.bestseller.service.staticPage.StaticPageService;
@Controller
public class ControllerTest{
@RequestMapping(value="/test/index",method=RequestMethod.POST)
public String test01(String name,Date birth){
System.out.println(name);
return "";
}
/*
@InitBinder
public void initBinder(HttpServletRequest request,ServletRequestDataBinder binder){
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}*/
@Autowired
private StaticPageService staticPageService;
@RequestMapping("/test/freemarker.do")
public String test02(){
Map<String,Object> map=new HashMap<>();
map.put("hello", "世界你好!");
staticPageService.productStaticized(map, 123456);
System.out.println("生成完成!");
return "";
}
@Autowired
private BuyerService buyerService;
@RequestMapping("/test/jsonp.do")
@ResponseBody
public Object testJsonp(String callback){
List<Buyer> buyers = buyerService.getBuyerList(null);
Buyer buyer=buyers.get(0);
MappingJacksonValue mjv=new MappingJacksonValue(buyer);
mjv.setJsonpFunction(callback);
return mjv;
}
}
|
package by.academy.homework.homework6.Task3;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class Application {
public static void main(String[] args) {
List<User> arrayList = new ArrayList<User>();
arrayList.add(new User("name1", "surname1", 1));
arrayList.add(new User("name2", "surname2", 2));
arrayList.add(new User("name3", "surname3", 3));
arrayList.add(new User("name4", "surname4", 4));
arrayList.add(new User("name5", "surname5", 5));
arrayList.add(new User("name6", "surname6", 6));
arrayList.add(new User("name7", "surname7", 7));
arrayList.add(new User("name8", "surname8", 8));
arrayList.add(new User("name9", "surname9", 9));
arrayList.add(new User("name10", "surname10", 10));
File catalog = new File("src\\by\\academy\\homework\\homework6\\Task3\\Users");
if (catalog.mkdirs() && arrayList != null) {
for (User user : arrayList) {
File file = new File(catalog, user.getName() + "_" + user.getSurname() + ".txt");
try (ObjectOutputStream oos = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(file)))) {
oos.writeObject(user.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
}
|
package com.accolite.au.mappers;
import com.accolite.au.dto.TrainerDTO;
import com.accolite.au.models.Trainer;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import java.util.List;
import java.util.Set;
@Mapper(componentModel = "spring")
public interface TrainerMapper {
@Mapping(source = "trainerDTO.businessUnit.buId", target = "businessUnit.buId")
Trainer toTrainer(TrainerDTO trainerDTO);
@Mapping(source = "trainer.businessUnit", target = "businessUnit")
TrainerDTO toTrainerDTO(Trainer trainer);
List<TrainerDTO> toTrainerDTOs(List<Trainer> trainers);
Set<TrainerDTO> toTrainerDTOsSet(Set<Trainer> trainers);
}
|
package com.pjb.springbootjjwt.service;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.pjb.springbootjjwt.entity.Device;
import com.pjb.springbootjjwt.entity.User;
import org.springframework.stereotype.Service;
/**
* @author jinbin
* @date 2018-07-08 21:04
*/
@Service("TokenService")
public class TokenService {
public String getToken(User user) {
String token="";
token= JWT.create().withAudience(user.getId())// 将 user id 保存到 token 里面
.sign(Algorithm.HMAC256(user.getPassword()));// 以 password 作为 token 的密钥
return token;
}
public String getDeviceToken(Device device) {
String token="";
token= JWT.create().withAudience(device.getId().toString())// 将 device id 保存到 token 里面
.sign(Algorithm.HMAC256(device.getImei()+device.getProjectName()));// 以 imei+projectName 作为 token 的密钥
return token;
}
}
|
package com.psl.training;
import java.util.Scanner;
public class CalculatePayback {
static Scanner scan = new Scanner (System.in);
static double calPayback(double amount) {
double pb;
if(amount<=500){
pb=(amount/100)*0.25;
}
else{
pb=(500/100)*0.25;
amount=amount-500;
if(amount<=1000){
pb=pb+(amount/100)*0.50;
}
else{
pb=pb+(1000/100)*0.50;
amount=amount-1000;
if(amount<=1000)
{
pb=pb+(amount/100)*0.75;
}
else
{
pb=pb+(1000/100)*0.75;
amount=amount-1000;
if(amount>=1)
{
pb=pb+(amount/100)*1.0;
}
}
}
}
return pb;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter Amount :");
double amount = scan.nextDouble();
double payback = calPayback(amount);
System.out.println("Payback amount is "+payback);
}
}
|
package com.duanc.web.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.duanc.api.web.CartService;
import com.duanc.api.web.ShowService;
import com.duanc.model.User;
import com.duanc.model.base.BaseCart;
import com.duanc.model.dto.PhoneDTO;
@Controller
@RequestMapping(value = "/cart")
public class CartController {
@Autowired
private ShowService showService;
@Autowired
private CartService cartService;
@RequestMapping(value = "")
public String getCartPage(HttpServletRequest request) {
User u = (User) request.getSession().getAttribute("current_user");
if(u != null) {
List<BaseCart> list = cartService.getCarts(u.getId());
if(list != null && list.size() != 0) {
BaseCart baseCart = list.get(0);
List<PhoneDTO> carts = (List<PhoneDTO>) JSON.parseArray(baseCart.getCarts(), PhoneDTO.class);
request.getSession().setAttribute("cartList", carts);
}
}
return "/user/cart";
}
@RequestMapping(value = "/ajax-addToCart")
@ResponseBody
public String addToCart(Integer phoneId, HttpServletRequest request){
if(phoneId != null ) {
PhoneDTO phone = showService.getPhoneDTO(phoneId);
if(phone != null) {
User u = (User) request.getSession().getAttribute("current_user");
if(u != null) {
List<BaseCart> list = cartService.getCarts(u.getId());
if(list == null || list.size() == 0) {
BaseCart baseCart = new BaseCart();
baseCart.setCarts(JSON.toJSONString(phone));
baseCart.setUserId(u.getId());
cartService.addToCart(baseCart);
} else {
BaseCart baseCart = list.get(0);
List<PhoneDTO> carts = (List<PhoneDTO>) JSON.parseArray(baseCart.getCarts(), PhoneDTO.class);
carts.add(phone);
String json = JSON.toJSONString(carts);
baseCart.setCarts(json);
cartService.updataCarts(baseCart, u.getId());
}
return JSON.toJSONString(true);
} else {
@SuppressWarnings("unchecked")
List<PhoneDTO> cartList = (List<PhoneDTO>) request.getSession().getAttribute("cartList");
if(cartList == null) {
cartList = new ArrayList<PhoneDTO>();
}
cartList.add(phone);
request.getSession().setAttribute("cartList", cartList);
return JSON.toJSONString(true);
}
}
}
return JSON.toJSONString(false);
}
@RequestMapping(value = "/ajax-removeFromCart")
@ResponseBody
public String removeFromCart(Integer phoneId, HttpServletRequest request){
if(phoneId != null ) {
PhoneDTO phone = showService.getPhoneDTO(phoneId);
if(phone != null) {
User u = (User) request.getSession().getAttribute("current_user");
if(u != null) {
List<BaseCart> list = cartService.getCarts(u.getId());
if(list != null && list.size() != 0) {
BaseCart baseCart = list.get(0);
List<PhoneDTO> cartList = (List<PhoneDTO>) JSON.parseArray(baseCart.getCarts(), PhoneDTO.class);
for (int i = 0; i < cartList.size(); i++) {
if(cartList.get(i).getId() == phone.getId()) {
cartList.remove(i);
}
}
baseCart.setCarts(JSON.toJSONString(cartList));
cartService.updataCarts(baseCart, u.getId());
return JSON.toJSONString(true);
}
} else {
@SuppressWarnings("unchecked")
List<PhoneDTO> cartList = (List<PhoneDTO>) request.getSession().getAttribute("cartList");
for (int i = 0; i < cartList.size(); i++) {
if(cartList.get(i).getId() == phone.getId()) {
cartList.remove(i);
}
}
request.getSession().setAttribute("cartList", cartList);
return JSON.toJSONString(true);
}
}
}
return JSON.toJSONString(false);
}
@RequestMapping(value = "/ajax-removeListFromCart")
@ResponseBody
public String removeListFromCart(@RequestParam("arr[]") Integer[] arr, HttpServletRequest request){
if(arr != null && arr.length != 0) {
@SuppressWarnings("unchecked")
List<PhoneDTO> cartList = (List<PhoneDTO>) request.getSession().getAttribute("cartList");
for (Integer integer : arr) {
PhoneDTO phone = showService.getPhoneDTO(integer);
if(phone != null) {
User u = (User) request.getSession().getAttribute("current_user");
if(u != null) {
List<BaseCart> list = cartService.getCarts(u.getId());
if(list != null && list.size() != 0) {
BaseCart baseCart = list.get(0);
List<PhoneDTO> carts = (List<PhoneDTO>) JSON.parseArray(baseCart.getCarts(), PhoneDTO.class);
for (int i = 0; i < carts.size(); i++) {
if(carts.get(i).getId() == phone.getId()) {
carts.remove(i);
}
}
baseCart.setCarts(JSON.toJSONString(carts));
cartService.updataCarts(baseCart, u.getId());
return JSON.toJSONString(true);
}
} else {
for (int i = 0; i < cartList.size(); i++) {
if(cartList.get(i).getId() == phone.getId()) {
cartList.remove(i);
}
}
}
}
}
request.getSession().setAttribute("cartList", cartList);
return JSON.toJSONString(true);
}
return JSON.toJSONString(false);
}
}
|
package com.zimu.ao.state;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import com.zimu.ao.controller.GameProcessController;
import com.zimu.ao.enums.GameState;
/**
* 游戏主类,初始化每个游戏地图的窗口
* @author zimu
*
*/
public class AOGame extends StateBasedGame {
public static final int WIDTH = 640;
public static final int HEIGHT = 480;
public AOGame(String name) {
super(name);
}
@Override
public void initStatesList(GameContainer gc) throws SlickException {
//this.addState(new Labyrinth(GameState.LABYRINTH));
this.addState(new Village(GameState.START_VILLAGE));
this.enterState(GameProcessController.CURRENT_STATE);
}
public static void main(String[] args) {
try {
AppGameContainer app = new AppGameContainer(new AOGame("AO Game"));
app.setDisplayMode(WIDTH, HEIGHT, false);
app.start();
} catch (SlickException e){
e.printStackTrace();
}
}
}
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.Base64;
import java.util.Scanner;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class ServerOperation extends UnicastRemoteObject implements RMIInterface{
private static final long serialVersionUID = 1L;
private volatile static RMIClientInterface client;
private static PrivateKey privateKey;
public static PublicKey publicKey;
static PublicKey clientPublicKey;
static SecretKey macKey;
static byte[] macKeyBytes;
public static boolean confidentiality, integrity, authentication = false;
protected ServerOperation() throws RemoteException {
super();
}
@Override
public void sendMessageServerEncrypted(byte[] encryptedKey, byte[] encryptedText) throws RemoteException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
Cipher aesCipher = Cipher.getInstance("AES");
SecretKey originalKey = decryptKey(encryptedKey);
aesCipher.init(Cipher.DECRYPT_MODE, originalKey);
// Decrypt the ciphertext
byte[] cleartext1 = aesCipher.doFinal(encryptedText);
String decryptedText = new String(cleartext1);
System.err.println("Client: "+ decryptedText);
Scanner sc = new Scanner(System.in);
String txt = sc.nextLine();
SecretKey key = generateKey();
byte[] encodedKey = encryptKey(key);
byte[] cipherText = encryptMessage(txt,key);
client.sendMessageClientEncrypted(encodedKey, cipherText);
}
public void sendMessageServerIntegrity(String txt, byte[] macKey, byte[] macData) throws NoSuchAlgorithmException, InvalidKeyException, RemoteException{
SecretKeySpec spec = new SecretKeySpec(macKey, "HmacMD5");
Mac mac = Mac.getInstance("HmacMd5");
mac.init(spec);
mac.update(txt.getBytes());
byte [] macCode = mac.doFinal();
if (macCode.length != macData.length){
System.out.println("ERROR: Integrity check failed, possible intercept");
} else if (!Arrays.equals(macCode, macData)){
System.out.println ("ERROR: Integrity check failed, possible intercept");
} else {
System.out.println("Client: " + txt);
}
Scanner sc = new Scanner(System.in);
String toSend = sc.nextLine();
generateMACKey();
client.sendMessageClientIntegrity(toSend, macKeyBytes, generateMACData(toSend));
}
public void sendMessageServerEncryptedIntegrity(byte[] encryptedKey, byte[] encryptedText, byte[] macKey, byte[] macData) throws RemoteException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
/* First decrypt the text to plaintext */
Cipher aesCipher = Cipher.getInstance("AES");
SecretKey originalKey = decryptKey(encryptedKey);
aesCipher.init(Cipher.DECRYPT_MODE, originalKey);
// Decrypt the ciphertext
byte[] cleartext1 = aesCipher.doFinal(encryptedText);
String decryptedText = new String(cleartext1);
/*Integrity check the decrypted text */
SecretKeySpec spec = new SecretKeySpec(macKey, "HmacMD5");
Mac mac = Mac.getInstance("HmacMd5");
mac.init(spec);
mac.update(decryptedText.getBytes());
byte [] macCode = mac.doFinal();
if (macCode.length != macData.length){
System.out.println("ERROR: Integrity check failed, possible intercept");
} else if (!Arrays.equals(macCode, macData)){
System.out.println ("ERROR: Integrity check failed, possible intercept");
} else {
System.out.println("Client: " + decryptedText);
}
Scanner sc = new Scanner(System.in);
String toSend = sc.nextLine();
SecretKey key = generateKey();
byte[] encodedKey = encryptKey(key);
byte[] cipherText = encryptMessage(toSend,key);
generateMACKey();
client.sendMessageClientEncryptedIntegrity(encodedKey, cipherText, macKeyBytes, generateMACData(toSend));
}
public void sendMessageServer(String txt) throws RemoteException {
System.out.println("Client: " + txt);
Scanner sc = new Scanner(System.in);
String toSend = sc.nextLine();
client.sendMessageClient(toSend);
}
public PublicKey getPublicKey() throws RemoteException{
return publicKey;
}
public int authenticateClient(String usr, String pwd) throws IOException, NoSuchAlgorithmException{
String correctLogin[] = getLoginsClient();
String correctUsr = correctLogin[0];
String hashedCorrectPwd = correctLogin[1];
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(pwd.getBytes());
byte[] bytes = sha.digest();
String hashedInput = Base64.getEncoder().encodeToString(bytes);
if (usr.equals(correctUsr)){
System.out.println("User matches");
if (hashedInput.equals(hashedCorrectPwd)){
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
public void registerClient(RMIClientInterface client) throws RemoteException {
ServerOperation.client = client;
clientPublicKey = ServerOperation.client.getPublicKey();
}
public boolean isConfidentialitySet() throws RemoteException{
return confidentiality;
}
public boolean isIntegritySet() throws RemoteException{
return integrity;
}
public boolean isAuthenticationSet() throws RemoteException{
return authentication;
}
public static void main(String[] args){
for (int i=0; i < args.length; i++){
if (args[i].equals("c")){
confidentiality = true;
System.out.println("Confidentiality Set");
} else if (args[i].equals("i")){
integrity = true;
System.out.println("Integrity Set");
} else if (args[i].equals("a")){
authentication = true;
System.out.println("Authentication Set");
}
}
try {
Naming.rebind("//localhost/MyServer", new ServerOperation());
if (authentication){
int authenticate = 0;
int tries = 0;
final JPanel frame = new JPanel();
while (authenticate != 1){
String usr = JOptionPane.showInputDialog("Enter Username:");
String pswd = JOptionPane.showInputDialog("Enter Password:");
authenticate = validateLogin(usr, pswd);
if (authenticate != 1){
JOptionPane.showMessageDialog(frame, "Incorrect user or password", "Inane error", JOptionPane.ERROR_MESSAGE);
}
tries++;
if (tries > 3){
System.out.println("Too many incorrect tries... Exiting");
System.exit(0);
}
}
}
System.err.println("Server ready");
generateKeys();
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
/* Key Functions */
private static SecretKey generateKey() throws NoSuchAlgorithmException{
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey aesKey = keygen.generateKey();
return aesKey;
}
private SecretKey decryptKey(byte[] encryptedKey) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException{
Cipher decrypt = Cipher.getInstance("RSA/ECB/PKCS1Padding");
decrypt.init(Cipher.PRIVATE_KEY, privateKey);
byte[] decodedKey = decrypt.doFinal(encryptedKey);
String decoded = new String (decodedKey);
byte[] originalKey = Base64.getDecoder().decode(decoded);
SecretKey decryptedKey = new SecretKeySpec(originalKey, 0, originalKey.length, "AES");
return decryptedKey;
}
public static byte[] encryptKey(SecretKey key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
String ciphertext = Base64.getEncoder().encodeToString(key.getEncoded());
Cipher encryption = Cipher.getInstance("RSA/ECB/PKCS1Padding");
encryption.init(Cipher.PUBLIC_KEY, clientPublicKey);
byte[] encryptedKey = encryption.doFinal(ciphertext.getBytes());
return encryptedKey;
}
private static void generateKeys() throws NoSuchAlgorithmException{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair pair = keyGen.generateKeyPair();
privateKey = pair.getPrivate();
publicKey = pair.getPublic();
}
/*Message Encrypt */
private static byte[] encryptMessage(String text, SecretKey aesKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
Cipher aesCipher = Cipher.getInstance("AES");
// Initialize the cipher for encryption
aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);
// Our cleartext
byte[] cleartext = text.getBytes();
// Encrypt the cleartext
byte[] ciphertext = aesCipher.doFinal(cleartext);
return ciphertext;
}
/* MAC FUNCTIONS */
private static void generateMACKey() throws NoSuchAlgorithmException{
KeyGenerator keygen = KeyGenerator.getInstance("HmacMD5");
SecretKey macKeyGen = keygen.generateKey();
macKey = macKeyGen;
byte[] keyBytes = macKey.getEncoded();
macKeyBytes = keyBytes;
}
private static byte[] generateMACData(String txt) throws NoSuchAlgorithmException, InvalidKeyException{
Mac mac = Mac.getInstance("HmacMD5");
mac.init(macKey);
mac.update(txt.getBytes());
byte[] macData = mac.doFinal();
mac.reset();
return macData;
}
/*
*
* Login/Authentication Functions
*
* */
private static int validateLogin(String usr, String pwd) throws NoSuchAlgorithmException, IOException{
String correctLogin[] = getLoginsServer();
String correctUsr = correctLogin[0];
String hashedCorrectPwd = correctLogin[1];
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(pwd.getBytes());
byte[] bytes = sha.digest();
String hashedInput = Base64.getEncoder().encodeToString(bytes);
if (usr.equals(correctUsr)){
if (hashedInput.equals(hashedCorrectPwd)){
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
private static String[] getLoginsServer() throws IOException{
BufferedReader br;
br = new BufferedReader(new FileReader("server_auth.txt"));
String line = br.readLine();
String[] parts = line.split(" ");
br.close();
return parts;
}
private static String[] getLoginsClient() throws IOException{
BufferedReader br;
br = new BufferedReader(new FileReader("client_auth.txt"));
String line = br.readLine();
String[] parts = line.split(" ");
br.close();
return parts;
}
}
|
package homework1;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ToBinaryStringTest {
Home1_7 obj = new Home1_7();
@Test
public void toBinaryStringTest(){
Assertions.assertEquals("00001111", obj.toBinaryString((byte) 15));
Assertions.assertEquals("11110001", obj.toBinaryString((byte) -15));
Assertions.assertEquals("00101010", obj.toBinaryString((byte) 42));
Assertions.assertEquals("11010110", obj.toBinaryString((byte) -42));
}
}
|
package cz.muni.fi.pa165.monsterslayers.service;
import cz.muni.fi.pa165.monsterslayers.dao.ClientRequestRepository;
import cz.muni.fi.pa165.monsterslayers.entities.ClientRequest;
import cz.muni.fi.pa165.monsterslayers.entities.User;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.Collection;
import static org.mockito.Mockito.*;
/**
* Tests for ClientRequestService.
*
* @author David Kizivat
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/service-context.xml")
public class ClientRequestServiceTest {
@Mock
private ClientRequestRepository repository;
@Autowired
@InjectMocks
private ClientRequestService service;
@Mock
private User client;
private ClientRequest cr1;
private ClientRequest cr2;
private Collection<ClientRequest> crs = new ArrayList<>();
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
cr1 = new ClientRequest("cr1", client);
cr1.setId(1L);
cr2 = new ClientRequest("cr2", client);
cr2.setId(2L);
}
@Test
public void findClientRequestById_IdExistsTest() {
when(repository.findOne(cr1.getId())).thenReturn(cr1);
ClientRequest result = service.findClientRequestById(1L);
verify(repository).findOne(1L);
Assert.assertEquals(cr1, result);
}
@Test
public void findClientRequestById_IdDoesNotExistText() {
when(repository.findOne(cr1.getId())).thenReturn(null);
ClientRequest result = service.findClientRequestById(1L);
verify(repository).findOne(1L);
Assert.assertNull(result);
}
@Test
public void getAllClientRequestsTest() {
when(repository.findAll()).thenReturn(crs);
Assert.assertEquals(crs, service.getAllClientRequests());
crs.add(cr1);
Assert.assertEquals(crs, service.getAllClientRequests());
crs.add(cr2);
Assert.assertEquals(crs, service.getAllClientRequests());
verify(repository, atLeast(3)).findAll();
}
@Test
public void getAllClientRequestByTitle_TitleExistsTest() {
when(repository.findByTitle(cr1.getTitle())).thenReturn(cr1);
ClientRequest result = service.findClientRequestByTitle("cr1");
verify(repository).findByTitle("cr1");
Assert.assertEquals(cr1, result);
}
@Test
public void findClientRequestByTitle_TitleDoesNotExistText() {
when(repository.findByTitle(cr1.getTitle())).thenReturn(null);
ClientRequest result = service.findClientRequestByTitle("cr3");
verify(repository).findByTitle("cr3");
Assert.assertNull(result);
}
@Test
public void removeClientRequestTest() {
service.removeClientRequest(cr1);
ArgumentCaptor<ClientRequest> crCaptor = ArgumentCaptor.forClass(ClientRequest.class);
verify(repository, atLeast(0)).delete(crCaptor.capture());
ArgumentCaptor<Long> idCaptor = ArgumentCaptor.forClass(Long.class);
verify(repository, atLeast(0)).delete(idCaptor.capture());
Assert.assertTrue(
(!crCaptor.getAllValues().isEmpty() && crCaptor.getValue().equals(cr1)) ||
(!idCaptor.getAllValues().isEmpty() && idCaptor.getValue().equals(cr1.getId()))
);
}
@Test
public void saveClientRequestTest() {
when(repository.save(cr1)).thenReturn(cr1);
service.saveClientRequest(cr1);
verify(repository).save(cr1);
}
}
|
/*
* 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 test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;
/**
*
* @author hugo
*/
public class Test extends JFrame{
private JTextPane receivePane;
private JScrollPane scroller;
// Model myModel;
private StyledDocument doc;
private SimpleAttributeSet keyWord;
public static void main(String[] args){
// JFrame frame = new JFrame();
// String[] s = {"Server","Client"};
// JOptionPane p = new JOptionPane("Server or Client?");
//
// p.setOptions(s);
// frame.add(p);
// frame.pack();
// frame.setVisible(true);
// frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
// String[] s = {"Server","Client"};
// int userType = JOptionPane.showOptionDialog(null,"Server or Client?","Pick one.",JOptionPane.DEFAULT_OPTION,
// JOptionPane.QUESTION_MESSAGE,null,s,s[0]);
// System.out.println(userType);
// JFrame f = new JFrame();
//
// JLabel l = new JLabel("hejhejhej");
// f.add(l);
// f.pack();
// f.setVisible(true);
// f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Test();
}
public Test(){
receivePane = new JTextPane();
receivePane.setPreferredSize(new Dimension(800,400));
receivePane.setEditable(false);
receivePane.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
receivePane.setLayout(new GridBagLayout());
doc = receivePane.getStyledDocument();
keyWord = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.RED);
StyleConstants.setBackground(keyWord, Color.YELLOW);
StyleConstants.setBold(keyWord, true);
scroller = new JScrollPane();
scroller.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setPreferredSize(new Dimension(800, 400));
scroller.setMinimumSize(new Dimension(800, 400));
scroller.add(receivePane);
add(scroller);
Thread thr = new Thread(new Runnable() {
public void run() {
while (true) {
showMessage();
}
}
});
thr.start();
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void showMessage(){
try {
doc.insertString(0, "Start of text\n", null);
doc.insertString(doc.getLength(), "test\n", keyWord);
} catch (Exception e) {
System.out.println(e);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.