text
stringlengths 10
2.72M
|
|---|
package com.needii.dashboard.model;
public enum SupplierBalanceTypeEnum {
DEPOSIT(1),
WITHDRAW(2),
CHARGE(3),
PUNISH(4),
UNKNOW(5),
REFUND(6);
private final int value;
private SupplierBalanceTypeEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
|
package org.hpin.webservice.bean.yg;
import java.io.Serializable;
import java.util.Date;
/**
* 保险公司客户预置表
* @description:
* create by henry.xu 2016年12月15日
*/
public class ErpBxCompanyPreSet implements Serializable{
/**
* 序列号
*/
private static final long serialVersionUID = -1432198565286869337L;
private String id; //主键ID
private String applicationNo; //申请单号
private String eventsNo; //场次号
private String customerRelationshipId;//支公司ID
private String customerSkuNum;//客户唯一识别号
private String customerName;//姓名
private String comboName;//套餐
private Date createTime;//创建时间
private String createUserId;//创建人
private Date updateTime;//修改时间
private String updateUserId;//修改人
private String isUseable;//可用标记
private String comboShowName;//套餐显示名称
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getApplicationNo() {
return applicationNo;
}
public void setApplicationNo(String applicationNo) {
this.applicationNo = applicationNo;
}
public String getEventsNo() {
return eventsNo;
}
public void setEventsNo(String eventsNo) {
this.eventsNo = eventsNo;
}
public String getCustomerRelationshipId() {
return customerRelationshipId;
}
public void setCustomerRelationshipId(String customerRelationshipId) {
this.customerRelationshipId = customerRelationshipId;
}
public String getCustomerSkuNum() {
return customerSkuNum;
}
public void setCustomerSkuNum(String customerSkuNum) {
this.customerSkuNum = customerSkuNum;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getComboName() {
return comboName;
}
public void setComboName(String comboName) {
this.comboName = comboName;
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
public String getUpdateUserId() {
return updateUserId;
}
public void setUpdateUserId(String updateUserId) {
this.updateUserId = updateUserId;
}
public String getIsUseable() {
return isUseable;
}
public void setIsUseable(String isUseable) {
this.isUseable = isUseable;
}
public String getComboShowName() {
return comboShowName;
}
public void setComboShowName(String comboShowName) {
this.comboShowName = comboShowName;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
|
package com.trump.auction.web.service.impl;
import com.trump.auction.cust.api.NotificationDeviceStubService;
import com.trump.auction.cust.model.NotificationDeviceModel;
import com.trump.auction.web.service.NotificationDeviceService;
import com.trump.auction.web.util.HandleResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Author: zhanping
*/
@Service
public class NotificationDeviceServiceImpl implements NotificationDeviceService {
@Autowired
private NotificationDeviceStubService notificationDeviceStubService;
@Override
public HandleResult save(NotificationDeviceModel obj) {
HandleResult handleResult = new HandleResult(false);
if (obj.getDeviceId() == null || StringUtils.isBlank(obj.getDeviceId())) {
return handleResult.setCode(1).setMsg("deviceId为空");
}
if (obj.getDeviceTokenUmeng() == null || StringUtils.isBlank(obj.getDeviceTokenUmeng())) {
return handleResult.setCode(1).setMsg("deviceToken为空");
}
if (obj.getDeviceType() == null) {
return handleResult.setCode(1).setMsg("设备类型为空或无效");
}
int count = notificationDeviceStubService.save(obj);
if (count == 1){
handleResult.setResult(true).setCode(0);
}
return handleResult;
}
}
|
/*
* 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 model;
import dao.ClienteDAO;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import util.Checa;
/**
*
* @author linux
*/
public class Cliente {
private int codigo;
private String nome;
private String cpf;
private String fone;
private String celular;
private String email;
public Cliente(String nome, String cpf, String fone, String celular, String email) {
setNome(nome);
setCpf(cpf);
setFone(fone);
setCelular(celular);
setEmail(email);
}
public Cliente(int codigo, String nome, String cpf, String fone, String celular, String email) {
this.codigo = codigo;
setNome(nome);
setCpf(cpf);
setFone(fone);
setCelular(celular);
setEmail(email);
}
public int getCodigo(){
return this.codigo;
}
private void setCodigo(int codigo){
this.codigo = codigo;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
if (!Checa.nome(nome)) throw new RuntimeException("Nome inválido.");
this.nome = nome;
}
/**
* @return the cpf
*/
public String getCpf() {
return cpf;
}
/**
* @param cpf the cpf to set
*/
public void setCpf(String cpf) {
this.cpf = cpf;
}
/**
* @return the fone
*/
public String getFone() {
return fone;
}
/**
* @param fone the fone to set
*/
public void setFone(String fone) {
this.fone = fone;
}
/**
* @return the celular
*/
public String getCelular() {
return celular;
}
/**
* @param celular the celular to set
*/
public void setCelular(String celular) {
this.celular = celular;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
public void gravar(){
ClienteDAO.getInstance().insert(this);
}
public static DefaultTableModel getTableModel(){
List<Cliente> lista = ClienteDAO.getInstance().select();
DefaultTableModel modelo = new DefaultTableModel();
modelo.addColumn("Nome");
modelo.addColumn("Telefone");
modelo.addColumn("Celular");
modelo.addColumn("Email");
for (Cliente c: lista){
String[] s = {c.getNome(), c.getFone(), c.getCelular(), c.getEmail(), c.getCpf()};
modelo.addRow(s);
}
return modelo;
}
public String toString() {
String ret;
ret = "Nome....: [" + getNome() +
"]\nCPF.....: [" + getCpf() +
"]\nTelefone: [" + getFone() +
"]\nCelular.: [" + getCelular() +
"]\nEmail...: [" + getEmail() +
"]";
return ret;
}
}
|
package fmi;
public class GoatCheese extends FarmProduct {
@Override
public void prepare() {
System.out.println("Preparing goat cheese");
}
}
|
package com.school.sms.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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;
import com.school.sms.constants.Constants;
import com.school.sms.constants.Constants.UserType;
import com.school.sms.model.Student;
import com.school.sms.model.UserAuthenticationDetails;
import com.school.sms.service.UserManagementService;
@Controller
public class UserManagementController {
@Resource(name = "userManagementService")
private UserManagementService userManagementService;
@RequestMapping(value = "/admin/userManagement/manageStudent**", method = RequestMethod.GET)
public ModelAndView manageStudent() {
ModelAndView modelAndView = new ModelAndView("manageStudent", "command",
new Student());
modelAndView.addObject("batchList", Arrays.asList(Constants.BATCH_ARRAY));
modelAndView.addObject("sectionList", Arrays.asList(Constants.CLASS_SECTIONS));
return modelAndView;
}
@RequestMapping(value = "/admin/userManagement/manageAdminUsers", method = RequestMethod.GET)
public ModelAndView manageAdminUsers() {
ModelAndView modelAndView = new ModelAndView("manageAdminUsers", "command",
new UserAuthenticationDetails());
return modelAndView;
}
@RequestMapping(value = "/admin/userManagement/listAdminUsers", method = RequestMethod.GET)
public ModelAndView listAdminUsers() {
ModelAndView modelAndView = new ModelAndView("listAdminUsers");
List<UserAuthenticationDetails> list = userManagementService.loadAdminUsers();
modelAndView.addObject("adminUsersList", list);
return modelAndView;
}
@RequestMapping(value = "/admin/userManagement/listStudents", method = RequestMethod.GET)
public ModelAndView listStudents() {
ModelAndView modelAndView = new ModelAndView("listStudents");
modelAndView.addObject("classList", Arrays.asList(Constants.BATCH_ARRAY));
modelAndView.addObject("sectionList", Arrays.asList(Constants.CLASS_SECTIONS));
return modelAndView;
}
@RequestMapping(value = "/admin/userManagement/listStudents", method = RequestMethod.POST)
public ModelAndView listStudents(@RequestParam(value = "action",required = false) String action,HttpServletRequest request) {
List<Student> requestedList = new ArrayList<Student>();
if(action.equalsIgnoreCase("listStudents")){
String cl = request.getParameter("class");
String section = request.getParameter("section");
String roll = request.getParameter("roll");
List<Student> list = userManagementService.loadStudents();
requestedList = getStudentsList(cl,section,roll,list);
}
ModelAndView modelAndView = new ModelAndView("listStudents");
modelAndView.addObject("classList", Arrays.asList(Constants.BATCH_ARRAY));
modelAndView.addObject("studentList", requestedList);
return modelAndView;
}
private List<Student> getStudentsList(String cl, String section,
String roll, List<Student> list) {
List<Student> list2 = new ArrayList<Student>();
for(Student student : list){
if(student.getCurrentClassBatch().equalsIgnoreCase(cl)){
if(section !=null && !section.isEmpty()){
if(section.equalsIgnoreCase(student.getCurrentClassSection())){
if(roll !=null && !roll.isEmpty()){
if(roll.equalsIgnoreCase(String.valueOf(student.getRoll()))){
list2.add(student);
}
}
else{
list2.add(student);
}
}
}
else{
list2.add(student);
}
}
}
return list2;
}
@RequestMapping(value = "/admin/userManagement/manageStudent", method = RequestMethod.POST)
public ModelAndView manageStudent(@ModelAttribute("student")Student student,
@RequestParam(value = "action",required = false) String action,HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("manageStudent", "command",
student);
if("search".equalsIgnoreCase(action)){
Student student1= userManagementService.findStudent((String)request.getParameter("searchEnrolementNo"));
if(null==student1){
modelAndView = new ModelAndView("manageStudent","command",student);
modelAndView.addObject("noStudentFound",true);
student1= new Student();
}
else{
modelAndView = new ModelAndView("manageStudent","command",student1);
}
}
else if("save".equalsIgnoreCase(action)) {
student.setStatus(true);
if(null==student.getRoll() || student.getRoll()==0){
createRollNo(student);
}
if(null==student.getEnrolementNo() || student.getEnrolementNo().isEmpty()){
createEnrolementNo(student);
}
userManagementService.updateStudent(student);
modelAndView.addObject("studentSaved",true);
}
else if("deactivate".equalsIgnoreCase(action)) {
userManagementService.deactivateStudent(student);
modelAndView = new ModelAndView("manageStudent","command",student);
modelAndView.addObject("studentDeactivated",true);
}
else if("reset".equalsIgnoreCase(action)) {
modelAndView = new ModelAndView("manageStudent","command",new Student());
}
// modelAndView.setViewName("fixed-fees");
modelAndView.addObject("batchList", Arrays.asList(Constants.BATCH_ARRAY));
return modelAndView;
}
@RequestMapping(value = "/admin/userManagement/manageAdminUsers", method = RequestMethod.POST)
public ModelAndView manageAdminUsers(@ModelAttribute("user")UserAuthenticationDetails user,
@RequestParam(value = "action",required = false) String action,HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("manageAdminUsers", "command",
user);
if("search".equalsIgnoreCase(action)){
UserAuthenticationDetails user1= userManagementService.findUser((String)request.getParameter("userId"));
if(null==user1){
modelAndView = new ModelAndView("manageAdminUsers","command",user);
modelAndView.addObject("noUserFound",true);
user1= new UserAuthenticationDetails();
}
else{
modelAndView = new ModelAndView("manageAdminUsers","command",user1);
}
}
else if("save".equalsIgnoreCase(action)) {
UserAuthenticationDetails user1= userManagementService.findUser((String)request.getParameter("userId"));
if(user1==null){
user.setEnabled("TRUE");
user.setUserType(UserType.ADMIN.toString());
userManagementService.updateUser(user);
userManagementService.updateUserRoles(user.getUserId(),"ROLE_ADMIN");
modelAndView.addObject("userSaved",true);
}
else{
modelAndView.addObject("userAlreadyExists",true);
}
}
else if("deactivate".equalsIgnoreCase(action)) {
userManagementService.deactivateUser(user);
modelAndView = new ModelAndView("manageAdminUsers","command",user);
modelAndView.addObject("userDeactivated",true);
}
else if("reset".equalsIgnoreCase(action)) {
modelAndView = new ModelAndView("manageAdminUsers","command",new UserAuthenticationDetails());
}
return modelAndView;
}
private void createRollNo(Student student) {
Integer maxRoll = userManagementService.getMaxRollInClassAndSection(student.getCurrentClassBatch(),student.getCurrentClassSection());
student.setRoll(maxRoll+1);
}
private void createEnrolementNo(Student student) {
// SimpleDateFormat dateFormat = new SimpleDateFormat("MM/DD/YYYY");
// dateFormat.parse(student.getDateOfAdmission());
String enrolementNo= Calendar.getInstance().get(Calendar.YEAR) + "/"+ student.getCurrentClassBatch().charAt(0)+student.getCurrentClassSection()+"/"+student.getRoll();
student.setEnrolementNo(enrolementNo);
}
@RequestMapping(value = "admin/userManagement", method = RequestMethod.GET)
public ModelAndView userManagement() {
ModelAndView model = new ModelAndView();
/*
* model.addObject("title", "Spring Security Custom Login Form");
* model.addObject("message", "This is protected page!");
*/
model.setViewName("userManagement");
return model;
}
}
|
package algorithms;
import graph.*;
import log.*;
import java.util.*;
import java.io.*;
public class ColorizeVersion3 extends ColorizeVersion2 {
/**
*
*/
Hashtable<Integer, Integer> colors;
/**
*
*/
protected ArrayList<Vertex> vertexByDegree;
/**
* [V3 description]
* @param graph [description]
* @return [description]
* @throws IOException [description]
*/
public ColorizeVersion3 (Graph graph) throws IOException {
super(graph, "V3");
colors = new Hashtable<Integer, Integer>();
vertexByDegree = graph.getVertexByDegree();
}
/**
*
* @param id
*/
public void setColorVertex (int id) {
Vertex vertex;
if (id == -1)
vertex = vertexList.get(vertexByDegree.get(vertexByDegree.size()-1).getId());
else
vertex = vertexList.get(vertexByDegree.get(id).getId());
log.write("Get", "first color that is available for vertex", Integer.toString(vertex.getId()+1));
int color = getFirstColorAvailable();
log.writeln("Available[" + Integer.toString(color) + "]");
log.writef("Set", "in " + color + " the color of vertex ", Integer.toString(vertex.getId()+1), "");
vertex.setColor(color);
}
/**
* [saveNeighborColors description]
* @param j [description]
*/
public void saveNeighborColors (int j) {
log.writef("Clear", "table of colors");
colors = new Hashtable<Integer, Integer>();
for (int i = 0; i < vertexList.get(vertexByDegree.get(j).getId()).getNeighborList().size(); i++) {
log.writef("Add", vertexList.get(vertexList.get(vertexByDegree.get(j).getId()).getNeighborList().get(i)).getColor() + " to table of colors", "", " from vertex " + Integer.toString(vertexList.get(vertexList.get(vertexByDegree.get(j).getId()).getNeighborList().get(i)).getId()+1));
colors.put(vertexList.get(vertexList.get(vertexByDegree.get(j).getId()).getNeighborList().get(i)).getColor(), 1);
}
}
/**
* [getFirstColorAvailable description]
* @return [description]
*/
protected int getFirstColorAvailable () {
int k = 1;
while(colors.containsKey(k)) {
log.write(Integer.toString(k));
k++;
}
return k;
}
}
|
package uk.co.travelai_public.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import uk.co.travelai_public.model.HERE.HEREExtraDetails;
import java.util.Locale;
/**
* A class that represents a Location.
*/
@Getter
@Setter
@NoArgsConstructor
public class Location {
private double timestamp;
private double latitude;
private double longitude;
private double accuracy;
private double speed;
private double dspeed;
private double tzOffset_ms;
private HEREExtraDetails extraDetails;
// Allow switching location overwritten state
private boolean overwrittenByGISProcess = false;
/**
* Format timestamp
*
* @return formatted timestamp
*/
private String getTimestampString() {
return String.format(Locale.UK, "%.3f", timestamp);
}
@Override
public String toString() {
return "Loc {" + getTimestampString() + "," + latitude + "," + longitude + "," + accuracy + "," + speed;
}
}
|
package graphs.maxflow;
import java.util.LinkedList;
import java.util.Queue;
public class FordFulkerson {
// marked[v.getId()] = true -> v in the residual graph
private boolean[] marked;
// edgeTo[v] -> edges in the augmenting path
private Edge[] edgeTo;
private double maxFlow;
// Edmonds-Karp implementation
public FordFulkerson(FlowNetwork network, Vertex s, Vertex t) {
while (hasAugmentingPath(network, s, t)) {
double min = Double.POSITIVE_INFINITY;
for (Vertex v = t; v != s; v = edgeTo[v.getId()].getOther(v)) {
min = Math.min(min, edgeTo[v.getId()].getResidualFlow(v));
}
for (Vertex v = t; v != s; v = edgeTo[v.getId()].getOther(v)) {
edgeTo[v.getId()].addResidualFlow(v, min);
}
maxFlow += min;
}
}
private boolean hasAugmentingPath(FlowNetwork network, Vertex s, Vertex t) {
edgeTo = new Edge[network.getVertices()];
marked = new boolean[network.getVertices()];
Queue<Vertex> queue = new LinkedList<>();
queue.add(s);
marked[s.getId()] = true;
while (!queue.isEmpty() && !marked[t.getId()]) {
Vertex v = queue.remove();
for (Edge edge : network.getAdjacencies(v)) {
Vertex u = edge.getOther(v);
if (edge.getResidualFlow(u) > 0) {
if (!marked[u.getId()]) {
edgeTo[u.getId()] = edge;
marked[u.getId()] = true;
queue.add(u);
}
}
}
}
return marked[t.getId()];
}
public boolean isInCut(int index) {
return marked[index];
}
public double getMaxFlow() {
return maxFlow;
}
}
|
package br.com.transportadora.service.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import br.com.transportadora.constants.TransportadoraConstants;
import br.com.transportadora.service.vo.ColetaVo;
import br.com.transportadora.util.Conexao;
public class TransportadoraDAO {
public ColetaVo consultarColetaPorId(String id){
Connection conn = null;
Statement stm = null;
ResultSet rset = null;
StringBuilder query = new StringBuilder();
ColetaVo coletaRetorno = new ColetaVo();
query.append("SELECT ID,DATA_COLETA,DATA_ENTREGA,CEP_COLETA,CEP_DESTINO,VALOR_COLETA FROM tb_tr_coleta WHERE ID=");
query.append(""+id+";");
try{
conn = Conexao.connect();
stm = conn.createStatement();
rset = stm.executeQuery(query.toString());
if(rset.next()){
coletaRetorno = new ColetaVo();
coletaRetorno.setId(rset.getInt("ID"));
//VERIFICAR MODO DE RETORNO DE DATA DO MYSQL
coletaRetorno.setDataColeta(rset.getDate("DATA_COLETA"));
coletaRetorno.setDataEntrega(rset.getDate("DATA_ENTREGA"));
coletaRetorno.setCepColeta(rset.getString("CEP_COLETA"));
coletaRetorno.setCepDestino(rset.getString("CEP_DESTINO"));
coletaRetorno.setValorColeta(rset.getDouble("VALOR_COLETA"));
}
} catch (SQLException sqlex) {
System.out.println("ERRO: "+getClass().getCanonicalName()+".consultarEstoque()");
sqlex.printStackTrace();
} catch(Exception e) {
System.out.println("ERRO: "+getClass().getCanonicalName()+".consultarEstoque()");
e.printStackTrace();
} finally {
Conexao.disconnect(rset, stm, conn);
}
return coletaRetorno;
}
public List<ColetaVo> consultarColetaPorDataColeta(Date dataInicio, Date dataFim) throws Exception{
Connection conn = null;
Statement stm = null;
ResultSet rset = null;
StringBuilder query = new StringBuilder();
ColetaVo coletaRetorno;
List<ColetaVo> listaRetorno = new ArrayList<ColetaVo>();
//
// query.append("SELECT ID,DATA_COLETA,DATA_ENTREGA,CEP_COLETA,CEP_DESTINO,VALOR_COLETA FROM tb_tr_coleta WHERE ID=");
// query.append(""+id+";");
conn = Conexao.connect();
stm = conn.createStatement();
rset = stm.executeQuery(query.toString());
if(rset.next()){
coletaRetorno = new ColetaVo();
//coletaRetorno.setIdWeb(id);
//coletaRetorno.setQuantidade(rset.getInt(1));
listaRetorno.add(coletaRetorno);
}
Conexao.disconnect(rset, stm, conn);
return listaRetorno;
}
public int inserirColeta(ColetaVo coleta) throws Exception{
Connection conn = null;
Statement stm = null;
ResultSet rset = null;
StringBuilder query = new StringBuilder();
int idRetorno = 0;
query.append("INSERT INTO tb_tr_coleta(DATA_COLETA,DATA_ENTREGA,CEP_COLETA,CEP_DESTINO,VALOR_COLETA)VALUES");
query.append("("+coleta.getDataColeta()+",");
query.append(coleta.getDataEntrega()+",");
query.append(coleta.getCepColeta()+",");
query.append(coleta.getCepDestino()+",");
query.append(coleta.getValorColeta()+",");
query.append(TransportadoraConstants.ATIVO +");");
conn = Conexao.connect();
stm = conn.createStatement();
stm.executeUpdate(query.toString(), Statement.RETURN_GENERATED_KEYS);
rset = stm.getGeneratedKeys();
if(rset.next()){
idRetorno = rset.getInt(1);
}
Conexao.disconnect(rset, stm, conn);
return idRetorno;
}
public void cancelarColeta(int id) throws Exception{
Connection conn = null;
Statement stm = null;
ResultSet rset = null;
StringBuilder query = new StringBuilder();
query.append("UPDATE 'tb_tr_coleta' SET CANCELADA = '2' WHERE id =");
query.append(id + ";");
conn = Conexao.connect();
stm = conn.createStatement();
stm.executeQuery(query.toString());
Conexao.disconnect(rset, stm, conn);
}
// public ProdutoVo consultarEstoque(int id){
// Connection conn = null;
// Statement stm = null;
// ResultSet rset = null;
// StringBuilder query = new StringBuilder();
// ProdutoVo produtoRetorno = new ProdutoVo();
//
// query.append("SELECT QUANTIDADE FROM tb_md_produto WHERE ID_WEB=");
// query.append(""+id+";");
// try{
// conn = Conexao.connect();
// stm = conn.createStatement();
// rset = stm.executeQuery(query.toString());
//
// if(rset.next()){
// produtoRetorno = new ProdutoVo();
// produtoRetorno.setIdWeb(id);
// produtoRetorno.setQuantidade(rset.getInt(1));
// }
//
// } catch (SQLException sqlex) {
// System.out.println("ERRO: "+getClass().getCanonicalName()+".consultarEstoque()");
// sqlex.printStackTrace();
//
// } catch(Exception e) {
// System.out.println("ERRO: "+getClass().getCanonicalName()+".consultarEstoque()");
// e.printStackTrace();
//
// } finally {
// Conexao.disconnect(rset, stm, conn);
// }
// return produtoRetorno;
//
// }
//
// public String consultarEstoqueString(int id){
// Connection conn = null;
// Statement stm = null;
// ResultSet rset = null;
// StringBuilder query = new StringBuilder();
// String produtoRetorno = null;
//
// query.append("SELECT QUANTIDADE FROM tb_md_produto WHERE ID_WEB=");
// query.append(""+id+";");
// try{
// conn = Conexao.connect();
// stm = conn.createStatement();
// rset = stm.executeQuery(query.toString());
//
// if(rset.next()){
// produtoRetorno = String.valueOf(rset.getInt(1));
// }
//
// } catch (SQLException sqlex) {
// System.out.println("ERRO: "+getClass().getCanonicalName()+".consultarEstoque()");
// sqlex.printStackTrace();
//
// } catch(Exception e) {
// System.out.println("ERRO: "+getClass().getCanonicalName()+".consultarEstoque()");
// e.printStackTrace();
//
// } finally {
// Conexao.disconnect(rset, stm, conn);
// }
// return produtoRetorno;
//
// }
}
|
package usc.cs310.ProEvento.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import usc.cs310.ProEvento.model.Account;
import usc.cs310.ProEvento.model.requestbody.ChangePasswordRequestBody;
import usc.cs310.ProEvento.service.AccountService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
public class AccountController {
@Autowired
private AccountService accountService;
@PostMapping("/api/account/register")
public Account registerAccount(@RequestBody Account account,
HttpServletRequest request,
HttpServletResponse response) {
account = accountService.registerAccount(account);
if (account == null) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
return account;
}
@PostMapping("/api/account/login")
public Account loginAccount(@RequestBody Account account,
HttpServletRequest request,
HttpServletResponse response
) {
account = accountService.loginAccount(account);
if (account == null) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
return account;
}
@PostMapping("/api/account/change_password")
public String changePassword(@RequestBody ChangePasswordRequestBody requestBody) {
boolean success = accountService.changePassword(
requestBody.accountId,
requestBody.currentPassword,
requestBody.newPassword
);
if (success) {
return "success";
}
return "failure";
}
@PostMapping("/api/account/deactivate")
public String deactivate(@RequestBody Account account) {
boolean success = accountService.deactivateAccount(account);
if (success) {
return "success";
}
return "failure";
}
}
|
package com.boku.auth.http.it.support;
import javax.servlet.http.HttpServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.boku.auth.http.server.servletfilter.BokuHttpAuthFilter;
public class AuthTestingServer {
private static final Logger logger = LoggerFactory.getLogger(AuthTestingServer.class);
private final Server jetty;
private final int port;
private final ServletHandler servletHandler;
public AuthTestingServer(BokuHttpAuthFilter authFilter) {
this.jetty = new Server(0);
this.servletHandler = new ServletHandler();
servletHandler.addFilterWithMapping(new FilterHolder(authFilter), "/auth/*", 0);
HandlerCollection handlers = new HandlerCollection();
handlers.addHandler(servletHandler);
this.jetty.setHandler(handlers);
try {
this.jetty.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
this.port = ((ServerConnector)this.jetty.getConnectors()[0]).getLocalPort();
logger.info("Listening on {}", this.port);
}
public void addServlet(String path, HttpServlet servlet) {
this.servletHandler.addServletWithMapping(new ServletHolder(servlet), path);
}
public void stop() {
try {
this.jetty.stop();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String getBaseURL() {
return "http://127.0.0.1:" + this.port;
}
}
|
package com.example.logsys.controller;
import com.alibaba.fastjson.JSON;
import com.example.logsys.mapper.ReportMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Controller
@RequestMapping("/index")
public class IndexController extends BaseController{
@Autowired
private ReportMapper reportMapper;
@GetMapping("/getTotal")
@ResponseBody
public String getTotal() {
Map resultMap = new HashMap(16);
List result = new ArrayList();
int devicesTotal = reportMapper.getDeviceAllTotal();
int devicesDay = reportMapper.getDeviceDay();
int devicesMonth = reportMapper.getDeviceMonth();
int devicesYear = reportMapper.getDeviceYear();
int devicesWeek = reportMapper.getDeviceWeek();
int usersTotal = reportMapper.getUserAllTotal();
int usersDay = reportMapper.getUserDay();
int usersMonth = reportMapper.getUserMonth();
int usersYear = reportMapper.getUserYear();
int usersWeek = reportMapper.getUserWeek();
int exceptionsTotal = reportMapper.getExceptionAllTotal();
int exceptionsDay = reportMapper.getExceptionDay();
int exceptionsMonth = reportMapper.getExceptionMonth();
int exceptionsYear = reportMapper.getExceptionYear();
int exceptionsWeek = reportMapper.getExceptionWeek();
Map map = new HashMap();
map.put("name","总数");
map.put("devices",devicesTotal);
map.put("exceptions",exceptionsTotal);
map.put("users",usersTotal);
map.put("vip",1);
Map map1 = new HashMap();
map1.put("name","今日");
map1.put("devices",devicesDay);
map1.put("exceptions",exceptionsDay);
map1.put("users",usersDay);
map1.put("vip",0);
Map map2 = new HashMap();
map2.put("name","本周");
map2.put("devices",devicesWeek);
map2.put("exceptions",exceptionsWeek);
map2.put("users",usersWeek);
map2.put("vip",0);
Map map3 = new HashMap();
map3.put("name","本月");
map3.put("devices",devicesMonth);
map3.put("exceptions",exceptionsMonth);
map3.put("users",usersMonth);
map3.put("vip",0);
Map map4 = new HashMap();
map4.put("name","本年");
map4.put("devices",devicesYear);
map4.put("exceptions",exceptionsYear);
map4.put("users",usersYear);
map4.put("vip",0);
result.add(map);
result.add(map1);
result.add(map2);
result.add(map3);
result.add(map4);
resultMap .put("code",0);
resultMap .put("data",result);
resultMap .put("msg","success");
resultMap .put("count",5);
return JSON.toJSONString(resultMap);
}
}
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE file for licensing information.
*
* Created on 4 mar 2014
* Author: K. Benedyczak
*/
/**
* Realms support for the generic DB
* @author K. Benedyczak
*/
package pl.edu.icm.unity.db.generic.realm;
|
package com.exam.models;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;
import java.io.Serializable;
import java.time.ZonedDateTime;
@Value
@AllArgsConstructor
@Builder
public class Message implements Serializable {
private static final long serialVersionUID = 3179109666291410918L;
private final Long id;
private final Long chatID;
private final Long senderID;
private final String senderName;
private final String text;
private final ZonedDateTime sendingTime;
}
|
package org.sky.base.model;
import java.math.BigDecimal;
import java.util.Date;
public class BaseAccount {
private String id;
private String code;
private String chaCode;
private BigDecimal balance;
private String state;
private String creater;
private Date createTime;
private String updater;
private Date updateTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getChaCode() {
return chaCode;
}
public void setChaCode(String chaCode) {
this.chaCode = chaCode;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCreater() {
return creater;
}
public void setCreater(String creater) {
this.creater = creater;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdater() {
return updater;
}
public void setUpdater(String updater) {
this.updater = updater;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
|
package com.example.demo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public abstract class People<T extends Person> implements Iterable<T>{
ArrayList<T> personList;
People(){
personList = new ArrayList<T>();
}
public void add(T person){
personList.add(person);
}
public void remove(T person) {
personList.remove(person);
}
public Integer size(){
return personList.size();
}
public void clear(){
personList.clear();
}
public void addAll(Iterable<? extends Person> persons){
for(Person person: persons){
personList.add((T) person);
}
}
public T findById(Long id){
Person returnedPerson = null;
for(Person person: personList){
if(person.getId()==id)
returnedPerson = person;
}
return (T) returnedPerson;
}
public List<T> findAll(){
return personList;
}
@Override
public String toString() {
return "People{" +
"personList=" + personList +
'}';
}
@Override
public Iterator<T> iterator() {
return personList.iterator();
}
// public T[] getArray(){
//
// T[] returnArray = (T[]) personList.toArray(new Person[0]);
//
// return returnArray;
// }
// private static final People peopleinstance = new People(){};
//
// public static People getPeopleinstanceInstance(){
// return peopleinstance;
// }
}
|
package architecture.layer.storage;
import architecture.layer.storage.blueprint.IdData;
import architecture.layer.storage.storage.MapStorage;
import java.util.Map;
public class IdDataAccess implements IdData {
//
private Map<String, String> nextIdMap;
IdDataAccess(){
//
nextIdMap = MapStorage.getInstance().getNextIdMap();
}
@Override
public String retrieveId(String className) {
return nextId(className);
}
@Override
public String retrieveId(String className, String boardId) {
String nextId = nextId(className);
return boardId+":"+nextId;
}
private String nextId(String className){
if(!nextIdMap.containsKey(className)){
nextIdMap.put(className, String.format("%05d", 1));
}else{
int nextId = Integer.valueOf(nextIdMap.get(className))+1;
nextIdMap.put(className, String.format("%05d", nextId));
}
return nextIdMap.get(className);
}
}
|
package com.example.androidquizapp.model;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.androidquizapp.R;
import com.example.androidquizapp.studSetActivity;
import java.util.List;
import java.util.Random;
public class studCatGridAdapter extends BaseAdapter
{
List<String> studCatList;
public studCatGridAdapter(List<String> studCatList)
{
this.studCatList = studCatList;
}
@Override
public int getCount() {
return studCatList.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(final int i, View view, final ViewGroup viewGroup)
{
View v;
if(view==null)
{
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.stud_cat_item_layout, viewGroup, false);
}
else
{
v = view;
}
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
Intent intent = new Intent(viewGroup.getContext(), studSetActivity.class);
intent.putExtra("subjectName", studCatList.get(i));
intent.putExtra("subjectID", i+1);
viewGroup.getContext().startActivity(intent);
}
});
((TextView) v.findViewById(R.id.studCatName)).setText(studCatList.get(i));
Random rand = new Random();
int color = Color.argb(255, rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
v.setBackgroundColor(color);
return v;
}
}
|
package ru.steagle.protocol.responce;
import android.sax.Element;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.sax.StartElementListener;
import android.util.Xml;
import org.xml.sax.Attributes;
import java.util.ArrayList;
import java.util.List;
import ru.steagle.datamodel.SimpleDictionaryElem;
/**
* Created by bmw on 15.02.14.
*/
abstract public class SimpleDictionary<T extends SimpleDictionaryElem> extends BaseResult {
private List<T> list = new ArrayList<>();
public SimpleDictionary(String xml) {
parse(xml);
}
public List<T> getList() {
return list;
}
abstract public T getNewInstance();
abstract public String getIdName();
public String getDescriptionName() {
return "descr";
}
protected void parse(String xml) {
RootElement root = new RootElement("root");
Element var = root.getChild("var");
var.setStartElementListener(new StartElementListener() {
public void start(Attributes attrib) {
readBaseFields(attrib);
}
});
Element row = var.getChild("data").getChild("row");
row.setStartElementListener(new StartElementListener() {
public void start(Attributes attrib) {
list.add(getNewInstance());
}
});
row.getChild(getIdName()).setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String s) {
list.get(list.size() - 1).setId(s);
}
});
row.getChild(getDescriptionName()).setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String s) {
list.get(list.size()-1).setDescription(s);
}
});
row.getChild("key").setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String s) {
list.get(list.size()-1).setKey(s);
}
});
try {
Xml.parse(xml, root.getContentHandler());
} catch (Exception e) {
setParsingError(e);
}
}
}
|
package com.yxb.contentproviderdemo;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import static com.yxb.contentproviderdemo.MyContentProvider.AUTHORY;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// insertWithContentResolver();
// insertWithContentProviderClient();
// insertWithClientAndOperation();
// insertWithResolverAndOperation();
// insertWithAsyncQueryHandler();
initView();
setContentObserver();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
insertByMultiMethread();
}
private void initView() {
Button insert = (Button) findViewById(R.id.btn_insert);
Button queryAll = (Button) findViewById(R.id.btn_query_all);
Button queryOne = (Button) findViewById(R.id.btn_query_one);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//insertWithClientAndOperation();
insertFromInput();
}
});
queryAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Cursor cursor = queryAllFromProvider();
// Log.d(MainActivity.this.getClass().getSimpleName(), "Cursor size is " + cursor.getCount());
queryPerformanceTest();
}
});
queryOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor cursor = queryOneFromProvider();
cursor.moveToFirst();
Log.d(MainActivity.this.getClass().getSimpleName(), "Cursor size is " + cursor.getCount() + " and id is "
+ cursor.getString(cursor.getColumnIndex(ContentProviderDemoSQLiteHelper.USER_ID)));
}
});
}
private void insertWithContentResolver() {
long timeB = SystemClock.uptimeMillis();
ContentResolver contentResolverCompat = getContentResolver();
int loop = 0;
while (loop++ < 100) {
ContentValues v = new ContentValues();
v.put(ContentProviderDemoSQLiteHelper.USER_NAME, "A");
v.put(ContentProviderDemoSQLiteHelper.USER_PHONE, "1");
contentResolverCompat.insert(MyContentProvider.USER_INTO_URI, v);
}
long timeA = SystemClock.uptimeMillis();
Log.d(getClass().getSimpleName(), String.format("Insert value in insertWithContentResolver() %s cost %d ms.",
"all info", timeA - timeB));
}
private void insertWithContentProviderClient() {
long timeB = SystemClock.uptimeMillis();
ContentProviderClient contentProviderClient = getContentResolver().acquireContentProviderClient(MyContentProvider.USER_INTO_URI);
int loop = 0;
try {
while (loop++ < 100) {
ContentValues v = new ContentValues();
v.put(ContentProviderDemoSQLiteHelper.USER_NAME, "A");
v.put(ContentProviderDemoSQLiteHelper.USER_PHONE, "1");
contentProviderClient.insert(MyContentProvider.USER_INTO_URI, v);
}
} catch (RemoteException e) {
e.printStackTrace();
} finally {
contentProviderClient.release();
}
long timeA = SystemClock.uptimeMillis();
Log.d(getClass().getSimpleName(), String.format("Insert value in insertWithContentProviderClient() %s cost %d ms.", "all info ", timeA - timeB));
}
private void insertWithClientAndOperation() {
long timeB = SystemClock.uptimeMillis();
ContentProviderClient contentProviderClient = getContentResolver().acquireContentProviderClient(MyContentProvider.USER_INTO_URI);
int index = 0;
ArrayList<ContentProviderOperation> ops = new ArrayList<>(100);
try {
while (index++ < 100) {
ops.add(ContentProviderOperation.newInsert(MyContentProvider.USER_INTO_URI)
.withValue(ContentProviderDemoSQLiteHelper.USER_NAME, "A")
.withValue(ContentProviderDemoSQLiteHelper.USER_PHONE, "1")
.build());
}
timeB = SystemClock.uptimeMillis();
ContentProviderResult[] results = contentProviderClient.applyBatch(ops);
} catch (OperationApplicationException e) {
Log.e(getClass().getSimpleName(), "e", e);
e.printStackTrace();
} catch (RemoteException e) {
Log.e(getClass().getSimpleName(), "e", e);
e.printStackTrace();
} finally {
contentProviderClient.release();
}
long timeA = SystemClock.uptimeMillis();
Log.d(getClass().getSimpleName(), String.format("Insert value in insertWithClientAndOperation() %s cost %d ms.", "all info ", timeA - timeB));
}
private void insertWithResolverAndOperation() {
long timeB = SystemClock.uptimeMillis();
ContentResolver contentResolver = getContentResolver();
int index = 0;
ArrayList<ContentProviderOperation> ops = new ArrayList<>(100);
try {
while (index++ < 100) {
ops.add(ContentProviderOperation.newInsert(MyContentProvider.USER_INTO_URI)
.withValue(ContentProviderDemoSQLiteHelper.USER_NAME, "A")
.withValue(ContentProviderDemoSQLiteHelper.USER_PHONE, "1")
.build());
}
timeB = SystemClock.uptimeMillis();
contentResolver.applyBatch(AUTHORY, ops);
} catch (OperationApplicationException e) {
Log.e(getClass().getSimpleName(), "e", e);
e.printStackTrace();
} catch (RemoteException e) {
Log.e(getClass().getSimpleName(), "e", e);
e.printStackTrace();
} finally {
// do s.th
}
long timeA = SystemClock.uptimeMillis();
Log.d(getClass().getSimpleName(), String.format("Insert value in insertWithResolverAndOperation() %s cost %d ms.", "all info ", timeA - timeB));
}
private void insertWithAsyncQueryHandler() {
MyAsyncQueryHandler asyncQueryHandler = new MyAsyncQueryHandler(getContentResolver());
ContentValues contentValues = new ContentValues();
contentValues.put(ContentProviderDemoSQLiteHelper.USER_NAME, "A");
contentValues.put(ContentProviderDemoSQLiteHelper.USER_PHONE, "1");
asyncQueryHandler.startInsert(0, null, MyContentProvider.USER_INTO_URI, contentValues);
}
private Cursor queryAllFromProvider() {
long timeB = SystemClock.uptimeMillis();
Cursor cursor = getContentResolver().query(MyContentProvider.USER_INTO_URI, new String[]{ContentProviderDemoSQLiteHelper.USER_NAME,
ContentProviderDemoSQLiteHelper.USER_PHONE}, null, null, null);
long timeA = SystemClock.uptimeMillis();
Log.d(getClass().getSimpleName(), String.format("queryAllFromProvider() %s cost %d ms.", "all info ", timeA - timeB));
return cursor;
}
private void queryPerformanceTest() {
new Thread(new Runnable() {
int loop = 100;
@Override
public void run() {
long timeB = SystemClock.uptimeMillis();
while (loop-- > 0) {
Cursor cursor = getContentResolver().query(MyContentProvider.USER_INTO_URI, new String[]{ContentProviderDemoSQLiteHelper.USER_NAME,
ContentProviderDemoSQLiteHelper.USER_PHONE}, ContentProviderDemoSQLiteHelper.USER_NAME + "=? and "
+ ContentProviderDemoSQLiteHelper.USER_PHONE + "=?", new String[]{"A", "1"}, null);
}
long timeA = SystemClock.uptimeMillis();
Log.d(MainActivity.this.getClass().getSimpleName(),
"queryPerformanceTest() loop " + loop + " times cost " + (timeA - timeB) + "ms");
}
}).start();
}
private Cursor queryOneFromProvider() {
Uri uri = Uri.parse(MyContentProvider.CONTENT + MyContentProvider.AUTHORY + "/" + ContentProviderDemoSQLiteHelper.USER_INFO + "/1");
Log.d(getClass().getSimpleName(), uri.toString());
Cursor cursor = getContentResolver().query(uri,
null, null, null, null);
return cursor;
}
private void insertFromInput() {
TextInputEditText nameText = (TextInputEditText) findViewById(R.id.name_input_edit);
TextInputEditText phoneText = (TextInputEditText) findViewById(R.id.phone_input_edit);
String name = nameText.getText().toString();
String phone = phoneText.getText().toString();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone)) {
Toast.makeText(this, "输入信息不全", Toast.LENGTH_SHORT).show();
return;
}
ContentValues contentValues = new ContentValues();
contentValues.put(ContentProviderDemoSQLiteHelper.USER_NAME, name);
contentValues.put(ContentProviderDemoSQLiteHelper.USER_PHONE, phone);
Uri uri = getContentResolver().insert(MyContentProvider.USER_INTO_URI, contentValues);
Log.d(getClass().getSimpleName(), "Uri = " + uri.toString());
Toast.makeText(this, "插入id为 " + uri.getLastPathSegment(), Toast.LENGTH_SHORT).show();
}
private void insertByMultiMethread() {
int loop = 100;
while (loop-- > 0) {
new ContentProviderCommand<Cursor>() {
@Override
protected Cursor doCommand() {
Cursor cursor = getContentResolver().query(MyContentProvider.USER_INTO_URI, new String[]{ContentProviderDemoSQLiteHelper.USER_NAME,
ContentProviderDemoSQLiteHelper.USER_PHONE}, ContentProviderDemoSQLiteHelper.USER_NAME + "=? and "
+ ContentProviderDemoSQLiteHelper.USER_PHONE + "=?", new String[]{"A", "1"}, null);
return cursor;
}
@Override
protected void onPostExecute(Cursor result) {
Log.d(MainActivity.this.getClass().getSimpleName(),
"query success in thread " + Thread.currentThread().getName());
}
}.execute();
}
}
private final int MESSAGE_DATA_CHANGED = 1000;
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == MESSAGE_DATA_CHANGED) {
Uri uri = (Uri) msg.obj;
Log.d(MainActivity.this.getClass().getSimpleName(), "handle data change " + uri);
}
}
};
ContentObserver contentObserver = new MyContentObserver(new Handler());
private void setContentObserver() {
Log.d(getClass().getSimpleName(), "registerContentObserver uri = " + MyContentProvider.USER_INTO_URI.toString());
getContentResolver().registerContentObserver(MyContentProvider.USER_INTO_URI, true, contentObserver);
}
@Override
protected void onDestroy() {
getContentResolver().unregisterContentObserver(contentObserver);
super.onDestroy();
}
public static class MyContentObserver extends ContentObserver {
/**
* Creates a content observer.
*
* @param handler The handler to run {@link #onChange} on, or null if none.
*/
public MyContentObserver(Handler handler) {
super(handler);
Log.d(getClass().getSimpleName(), "MyContentObserver constructed ");
}
/**
* 当观察到数据改变时,回调此方法
*
* @param selfChange
* @param uri
*/
@Override
public void onChange(boolean selfChange, Uri uri) {
Log.d(getClass().getSimpleName(), "ContentObserver onChange(boolean,Uri) start");
super.onChange(selfChange, uri);
Log.d(getClass().getSimpleName(), "ContentObserver onChange(boolean,Uri) end");
}
/**
* 当观察到数据改变时,回调此方法
*
* @param selfChange
*/
@Override
public void onChange(boolean selfChange) {
Log.d(getClass().getSimpleName(), "ContentObserver onChange(boolean) start");
super.onChange(selfChange);
Log.d(getClass().getSimpleName(), "ContentObserver onChange(boolean) start");
}
}
}
|
package PA165.language_school_manager.Facade;
import PA165.language_school_manager.DTO.CourseDTO;
import PA165.language_school_manager.DTO.LectureCreateDTO;
import PA165.language_school_manager.DTO.LectureDTO;
import PA165.language_school_manager.DTO.LecturerDTO;
import java.time.LocalDateTime;
import java.util.List;
public interface LectureFacade {
/**
* Finds lecture by ID
* @param id - ID of the lecture
* @return LectureDTO of searched lecture
*/
LectureDTO findLectureById(Long id);
/**
* Finds all lectures
* @return List of LectureDTOs
*/
List<LectureDTO> findAllLectures();
/**
* Finds lecture by its topic
* @param topic - topic of the lecture
* @return - LectureDTO of searchd lecture
*/
LectureDTO findLectureByTopic(String topic);
/**
* Method to delete lecture
* @param lecture - lecture to be deleted
*/
void deleteLecture(LectureDTO lecture);
/**
* Method to create lecture
* @param lecture - lecture to be created
*/
Long createLecture(LectureCreateDTO lecture);
/**
* Method to update lecture
* @param lecture - lecture to be updated
*/
void updateLecture(LectureDTO lecture);
/**
* Find all lectures by course
*
* @param courseDTO course
* @return list of lectures
*/
List<LectureDTO> findLectureByCourse(CourseDTO courseDTO);
/**
* method to find all lectures of given lecturer
* @param lecturer - lecturer of lectures
* @return List of LectureDTOs
*/
List<LectureDTO> findLecturesByLecturer(LecturerDTO lecturer);
/**
* Find all lectures between the specific time
*
* @param from time from
* @param to time to
* @return List of lectures
*/
List<LectureDTO> findByTime(LocalDateTime from, LocalDateTime to);
}
|
package com.trump.auction.reactor.bid;
import com.google.common.collect.ImmutableList;
import com.trump.auction.reactor.api.AuctionContextFactory;
import com.trump.auction.reactor.api.AuctionLifeCycle;
import com.trump.auction.reactor.api.exception.BidException;
import com.trump.auction.reactor.api.model.AuctionContext;
import com.trump.auction.reactor.bid.support.BidEvent;
import com.trump.auction.reactor.bid.support.BidTimer;
import com.trump.auction.reactor.bid.support.DelegateBidEvent;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import static org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent.*;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.shaded.com.google.common.collect.Sets;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* 委托出价任务调度
*
* @author Owen
* @since 2018/1/22
*/
@Slf4j
@Component
public class DelegateBidScheduler implements AuctionLifeCycle, InitializingBean {
@Autowired
private CuratorFramework zkClient;
@Autowired
private BidTimer<BidEvent> timer;
@Autowired
private AuctionContextFactory contextFactory;
@Autowired
private BidConfig bidConfig;
private LeaderSelector leaderSelector;
private PathChildrenCache auctionOnBidCache;
private final Object mutex = new Object();
/**
* 已委托出价的竞拍
*/
private Set<String> delegatedData = Sets.newConcurrentHashSet();
/**
* 委托出价任务 leader 选举对应的路径
*/
public static final String DELEGATE_BID_LEADER_PATH = "/apps/auction/reactor/leader-selector/delegate-bid";
/**
* 进行中的竞拍对应的路径
*/
public static final String AUCTION_ON_BID_PATH = "/apps/auction/reactor/config/auction-on-bid";
@Override
public void onStart(@NonNull String auctionNo) {
try {
zkClient.create()
.creatingParentContainersIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath(ZKPaths.makePath(AUCTION_ON_BID_PATH, auctionNo));
} catch (KeeperException.NodeExistsException e) {
log.warn("[node] exists, auctionNo = {}", auctionNo);
} catch (Exception e) {
throw BidException.defaultError(e);
}
}
@Override
public void onComplete(@NonNull String auctionNo) {
try {
zkClient.delete()
.guaranteed()
.forPath(ZKPaths.makePath(AUCTION_ON_BID_PATH, auctionNo));
} catch (KeeperException.NoNodeException e) {
log.warn("[node] has already been deleted, auctionNo = {}", auctionNo);
} catch (Throwable e) {
log.warn("[node] delete error, auctionNo = {}", auctionNo, e);
}
}
private boolean addDelegatedData(String auctionNo) {
return delegatedData.add(auctionNo);
}
private boolean clearDelegatedData(String auctionNo) {
return delegatedData.remove(auctionNo);
}
/**
* 获取所有进行中的竞拍
*/
private List<String> allOfOnBid() throws Exception {
try {
return zkClient.getChildren().forPath(AUCTION_ON_BID_PATH);
} catch (KeeperException.NoNodeException e) {
return Collections.EMPTY_LIST;
} catch (Exception e) {
log.warn("[node] get children cause an error", e);
throw e;
}
}
/**
* 触发委托出价
*/
private void startDelegateBid(String auctionNo) {
log.debug("[start delegate bid], auctionNo = {}", auctionNo);
if (!addDelegatedData(auctionNo)) {
return;
}
try {
AuctionContext context = contextFactory.create(auctionNo);
if (invalidAuction(context)) {
log.warn("[node] auction is invalid, auctionNo = {}", auctionNo);
clearDelegatedData(auctionNo);
return;
}
timer.add(DelegateBidEvent.create(context), bidConfig.nextDelegateBidDelayTime(context.getBidCountDown()));
} catch (Throwable e) {
log.error("[start delegate bid] cause an error", e);
clearDelegatedData(auctionNo);
}
}
private void removeDelegateBid(String auctionNo) {
clearDelegatedData(auctionNo);
timer.remove(DelegateBidEvent.create(auctionNo));
}
private boolean invalidAuction(AuctionContext context) {
return context == null || context.isComplete();
}
@Override
public void afterPropertiesSet() throws Exception {
this.leaderSelector = new LeaderSelector(zkClient, DELEGATE_BID_LEADER_PATH, leaderSelectorListener());
this.auctionOnBidCache = new PathChildrenCache(this.zkClient, AUCTION_ON_BID_PATH, false);
this.auctionOnBidCache.getListenable().addListener(
new AuctionOnBidListener(ImmutableList.of(Type.CHILD_ADDED, Type.CHILD_REMOVED)));
auctionOnBidCache.start();
leaderSelector.autoRequeue();
leaderSelector.start();
}
private LeaderSelectorListenerAdapter leaderSelectorListener() {
return new LeaderSelectorListenerAdapter() {
@Override
public void takeLeadership(CuratorFramework client) throws Exception {
try {
takeLeaderShip0();
} catch (Throwable e) {
log.error("[leader] selector", e);
throw e;
}
return;
}
private void takeLeaderShip0() throws Exception {
List<String> auctionNos = allOfOnBid();
auctionNos.stream().forEach((auctionNo) -> startDelegateBid(auctionNo));
while (leaderSelector.hasLeadership()) {
synchronized (mutex) {
log.debug("[leader] wait for notify");
try {
mutex.wait();
} catch (InterruptedException e) {
log.warn("[leader] interrupted");
}
}
}
}
};
}
private class AuctionOnBidListener implements PathChildrenCacheListener {
private List<Type> requiredEventTypes;
public AuctionOnBidListener(List<Type> requiredEventTypes) {
this.requiredEventTypes = requiredEventTypes;
}
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
log.debug("[zk event] event = {}", event);
if (!leaderSelector.hasLeadership()) {
synchronized (mutex) {
mutex.notify();
}
}
if (!isRequiredEvent(event)) {
return;
}
final String auctionNo = ZKPaths.getNodeFromPath(event.getData().getPath());
if (Type.CHILD_REMOVED.equals(event.getType())) {
log.info("[zk watch] remove delegate bid, auctionNo = {}", auctionNo);
removeDelegateBid(auctionNo);
return;
}
if (!leaderSelector.hasLeadership()) {
return;
}
if (Type.CHILD_ADDED.equals(event.getType())) {
log.info("[zk watch] start delegate bid, event = {}", event);
startDelegateBid(auctionNo);
}
}
private boolean isRequiredEvent(PathChildrenCacheEvent event) {
return this.requiredEventTypes.contains(event.getType());
}
}
}
|
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
*Pilot class represents pilot of the user plane
*/
public class Pilot extends GameObject{
//Constructor for shoot
public Pilot( int speed){
super( ImageConstants.nickPilotImage, 0, 0, speed, 0);
setScaledImage(100);
}
//Returns borders of the scaled image
public Rectangle getBorders() {
Rectangle rectangle = new Rectangle(getPositionX(), getPositionY(), getScaledImage().getWidth(null), getScaledImage().getWidth(null));
return rectangle;
}
//Draws the scaled image
@Override
public void draw(Graphics g) {
g.drawImage(getScaledImage(), getPositionX(), getPositionY(), null);
}
}
|
package mt.com.vodafone.service.impl;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import mt.com.vodafone.entity.User;
import mt.com.vodafone.repository.UserRepository;
import mt.com.vodafone.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserRepository dao;
@Autowired
private BCryptPasswordEncoder encoder;
@Override
public User save(final User user) throws Throwable {
user.setPassword(encoder.encode(user.getPassword()));
user.setCreationAt(new Date());
return dao.save(user);
}
@Override
public Iterable<User> findAll() {
return dao.findAll();
}
}
|
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.csp.sentinel.property;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.util.StringUtil;
public class DynamicSentinelProperty<T> implements SentinelProperty<T> {
protected Set<PropertyListener<T>> listeners = Collections.synchronizedSet(new HashSet<PropertyListener<T>>());
private T value = null;
public DynamicSentinelProperty() {
}
public DynamicSentinelProperty(T value) {
super();
this.value = value;
}
@Override
public void addListener(PropertyListener<T> listener) {
listeners.add(listener);
listener.configLoad(value);
}
@Override
public void removeListener(PropertyListener<T> listener) {
listeners.remove(listener);
}
@Override
public boolean updateValue(T newValue) {
if (isEqual(value, newValue)) {
return false;
}
newValue = getFlowRulesWithIp(newValue);
RecordLog.info("[DynamicSentinelProperty] Config will be updated to: " + newValue);
value = newValue;
for (PropertyListener<T> listener : listeners) {
listener.configUpdate(newValue);
}
return true;
}
private T getFlowRulesWithIp (T newValue){
if(null == newValue){
return null;
}
String ipAddress = getIpAddress();
List rules = (List) newValue;
List<FlowRule> flowRules = new ArrayList<>();
for (Object rule : rules){
if(rule instanceof FlowRule){
FlowRule flowRule = (FlowRule)rule;
if(flowRule.isApplyAll()){
flowRules.add(flowRule);
continue;
}
if(StringUtil.isEmpty(flowRule.getIp()) || flowRule.getIp().equals(ipAddress)){
flowRules.add(flowRule);
}
}
}
if(!flowRules.isEmpty()){
newValue = (T)flowRules;
}
return newValue;
}
public String getIpAddress(){
try{
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()){
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (!netInterface.isLoopback() && !netInterface.isVirtual() && netInterface.isUp()){
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()){
ip = addresses.nextElement();
if (ip instanceof Inet4Address){
return ip.getHostAddress();
}
}
}
}
} catch (Exception e){
RecordLog.info("[DynamicSentinelProperty] Fail to get ip address: " + e.getMessage());
throw new RuntimeException("获取本地ip地址失败");
}
throw new RuntimeException("获取本地ip地址失败");
}
private boolean isEqual(T oldValue, T newValue) {
if (oldValue == null && newValue == null) {
return true;
}
if (oldValue == null) {
return false;
}
return oldValue.equals(newValue);
}
public void close() {
listeners.clear();
}
}
|
module com.nbuproject.javaprojectbuildingmngmnt {
requires javafx.controls;
requires javafx.fxml;
requires org.controlsfx.controls;
requires com.dlsc.formsfx;
requires validatorfx;
requires org.kordamp.bootstrapfx.core;
opens com.nbuproject.javaprojectbuildingmngmnt to javafx.fxml;
exports com.nbuproject.javaprojectbuildingmngmnt;
}
|
package com.example.bruce_drawboll;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout main =(LinearLayout) findViewById(R.id.root);
final DrawView draw = new DrawView(this);
draw.setMinimumWidth(300);
draw.setMinimumHeight(500);
draw.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1)
{
// TODO Auto-generated method stub
draw.currentx = arg1.getX();
draw.currenty = arg1.getY();
draw.invalidate();
return true;
}
});
main.addView(draw);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
|
package org.sky.sys.service;
import java.util.List;
import org.sky.sys.client.SysAreaMapper;
import org.sky.sys.model.SysArea;
import org.sky.sys.model.SysAreaExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SysAreaService {
@Autowired
private SysAreaMapper sysAreaMapper;
public List<SysArea> listSysAreaByExample(SysAreaExample example) {
// TODO Auto-generated method stub
return sysAreaMapper.selectByExample(example);
}
}
|
package cn.ablocker.FoodBlog.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import cn.ablocker.FoodBlog.response.BaseResponse;
@Configuration
public class LoginResponseConfig
{
// 登录成功的响应
@Bean
@Scope("prototype")
public BaseResponse loginSuccessResponse()
{
BaseResponse response = new BaseResponse();
response.setStatus(201);
response.setSuccess(true);
return response;
}
// 登陆失败的响应
@Bean
@Scope("prototype")
public BaseResponse loginFailResponse()
{
BaseResponse response = new BaseResponse();
response.setStatus(403);
response.setSuccess(false);
return response;
}
// 注销的响应
@Bean
@Scope("prototype")
public BaseResponse unLoginResponse()
{
BaseResponse response = new BaseResponse();
response.setStatus(200);
response.setSuccess(true);
return response;
}
@Bean
@Scope("prototype")
public BaseResponse loginNeededResponse()
{
BaseResponse response = new BaseResponse();
response.setStatus(401);
response.setSuccess(false);
response.setInfo("You should login first.");
return response;
}
}
|
package com.company;
import java.util.Scanner;
public class Ejercicio3_3 {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
System.out.print("Introduzca un numero de tipo Double de 2 cifras: ");
double primernumero = teclado.nextDouble();
System.out.print("Introduzca un numero de tipo Double de 2 cifras: ");
double segundonumero = teclado.nextDouble();
System.out.print("Su division es: ");
System.out.println(primernumero / segundonumero);
}
}
|
package com.javarush.task.task18.task1828;
/*
Прайсы 2
*/
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) throws IOException {
if(!args[0].isEmpty()){
//читаем имя файла
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String filename = read.readLine();
read.close();
//открываем потоки чтения и записи
BufferedReader reader = new BufferedReader(new FileReader(filename));
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
if(args[0].equals("-d")){
//собираем все строки, которые НЕ будем удалять
List<String> strings = new ArrayList<>();
while(reader.ready()){
String line = reader.readLine();
strings.add(line);
}
strings.removeIf(s-> s.substring(0,8).trim().equals(args[1]));
//записываем все строки кроме, той которую нужно удалить (и очищаем файл)
for(String s: strings){
writer.write(s);
writer.newLine();
}
}else if(args[0].equals("-u")){
//ищем строку, которую нужно заменить и копируем все строки в арэйлист
List<String> strings = new ArrayList<>();
while(reader.ready()){
String line = reader.readLine();
if (line.contains(args[1].trim())){
String id = String.format("%-8.8s",args[1]);
String productName = String.format("%-30.30s",args[2]);
String price = String.format("%-8.8s",args[3]);
String quantity = String.format("%-4.4s",args[4]);
line = id+productName+price+quantity;
}
strings.add(line);
}
//записываем все строки кроме, той которую нужно удалить (и очищаем файл)
for(String s: strings){
writer.write(s);
writer.newLine();
}
}
reader.close();
writer.flush();
writer.close();
}
}
}
|
package com.redvector.udemyspringBoot.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.redvector.udemyspringBoot.entities.Order;
public interface OrderRepository extends JpaRepository<Order, Long>{
}
|
public class SpawnPoint
{
public String name;
public float x;
public float y;
public SpawnPoint(String n, float xx, float yy)
{
name = n;
x = xx;
y = yy;
}
}
|
package business.concretes;
import java.time.LocalDate;
import java.time.Period;
import business.abstracts.GamePlayService;
import entities.concretes.Gamer;
public class GamePlayManager implements GamePlayService {
@Override
public int calculateAge(Gamer gamer) {
Period yasFarki = Period.between(gamer.getYearOfBirth(), LocalDate.now());
if (yasFarki.getYears()>70) {
return 1;
}else if(yasFarki.getYears()>=18){
return 2;
}else {
return 3;
}
}
@Override
public boolean calculateGender(Gamer gamer) {
if (gamer.getGender()==1) {
return true;
}else {
return false;
}
}
}
|
package exam.iz0_803;
public class Exam_057 {
}
/*
Given:
public class X implements Z {
public String toString() {
return "I am X";
}
public static void main(String[] args) {
Y myY = new Y();
X myX = myY;
Z myZ = myX;
System.out.println(myZ);
}
}
class Y extends X {
public String toString() {
return "I am Y";
}
}
interface Z {}
What is the reference type of myZ and what is the type of the object is reference?
A. Reference type is Z; object type is Z
B. Reference type is Y; object type is Y
C. Reference type is Z; object type is Y
D. Reference type is X; object type is Z
Answer: C
*/
|
package GTEs;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* listens to scheduler for incoming suspend/activate packages
* @author babz
*
*/
public class SchedulerListener implements Runnable {
private DatagramSocket socket;
private DatagramPacket packet;
private AliveSignalEmitter emitter;
private boolean alive;
public SchedulerListener(DatagramSocket datagramSocket, AliveSignalEmitter emitter) {
socket = datagramSocket;
this.emitter = emitter;
int packetLength = 100;
byte[] buf = new byte[packetLength];
packet = new DatagramPacket(buf, buf.length);
alive = true;
}
@Override
public void run() {
while (alive) {
try {
//receive packages and forward them
socket.receive(packet);
unpack(packet);
} catch (IOException e) {
// shutdown
}
}
}
private void unpack(DatagramPacket packet) {
String msg = new String(packet.getData(), 0, packet.getLength());
//msg decode
if(msg.equals("suspend")) {
emitter.stopEmitter();
} else if (msg.equals("activate")) {
emitter.restart();
} else {
//TODO exception werfen: unknown command
}
}
public void terminate() {
alive = false;
}
}
|
package landmarker.pickapp.landmarker;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import java.lang.reflect.Array;
import java.util.Arrays;
import landmarker.pickapp.landmarker.MainActivity;
/**
* Created by Walter on 06/10/2016.
*/
public class LoginActivity extends AppCompatActivity {
private ImageView imageView;
private CallbackManager callbackManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
}
@Override
public void onCancel() {
Toast.makeText(getApplicationContext(),"Se cancelo login", Toast.LENGTH_LONG).show();
}
@Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(),"Error en el login", Toast.LENGTH_LONG).show();
}
});
imageView = (ImageView) findViewById(R.id.facebook_login);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile","user_friends"));
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
}
});
}
public void onRegistroClick(View view) {
Intent intent = new Intent(this,RegistroActivity.class);
startActivity(intent);
}
}
|
package pl.artursienkowski.service.search;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import pl.artursienkowski.model.Customer;
import pl.artursienkowski.model.User;
import pl.artursienkowski.repository.CustomerRepository;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Service
public class CustomerSeacherServisWorker {
private CustomerRepository customerRepository;
public CustomerSeacherServisWorker(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
public List<Customer> executeQuery(String searchMode, String query, User user) {
if (StringUtils.isEmpty(searchMode)) {
return customerRepository.findCustomerByUserAndStatusReverse(user, "SELL");
}
if(StringUtils.isEmpty(query)) {
return customerRepository.findCustomerByUserAndStatusReverse(user, "SELL");
}
switch (searchMode) {
case "firstName":
return customerRepository.findCustomerByFirstNamePart(query, user, "SELL");
case "lastName":
return customerRepository.findCustomerByLastNamePart(query, user, "SELL");
case "type":
return customerRepository.findCustomerByType(query, user, "SELL");
case "pesel":
return customerRepository.findCustomerByPESELPart(query, user, "SELL");
case "nip":
return customerRepository.findCustomerByNIPPart(query, user, "SELL");
case "status":
List<Customer> soldCustomers = new ArrayList<>();
if(query.equals("SELL")) {
return soldCustomers;
}
return customerRepository.findCustomerByStatus(query, user);
}
return Collections.emptyList();
}
}
|
package Bouton;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import Fenetre.Fenetre;
import Type.TypeBouton;
public class BoutonGenerique extends JButton implements ActionListener{
private static final long serialVersionUID = 1L;
private final Fenetre fenetre;
private final TypeBouton type;
private JLabel label2;
public BoutonGenerique(Fenetre fenetre, TypeBouton type) {
super();
this.fenetre = fenetre;
this.type = type;
setVisible(true);
setBackground(new Color(206,206,255));
addActionListener(this);
switch(type) {
case COMMENCER:
setText("Commencer");
setPreferredSize(new Dimension(105, 50));
break;
case RECOMMENCER:
setPreferredSize(new Dimension(150, 75));
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.weighty = 1.0;
c.gridy = 0;
add(new JLabel("Perdu !"), c);
c.weighty = 1.0;
c.gridy = 1;
add(label2 = new JLabel("Score : 0:0:0"), c);
c.weighty = 1.0;
c.gridy = 2;
add(new JLabel("Recommencer ?"), c);
break;
case REPRENDRE:
setText("Reprendre");
setPreferredSize(new Dimension(95, 50));
break;
case OK:
setText("OK");
break;
}
}
public void actionPerformed(ActionEvent e) {
switch(type) {
case RECOMMENCER:
fenetre.reinitialiser();
case COMMENCER:
case REPRENDRE:
fenetre.resume();
break;
case OK:
fenetre.fermerFenetreDifficulte();
break;
}
}
public void actualiser() {
switch(type) {
case RECOMMENCER:
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.weighty = 1.0;
c.gridy = 1;
remove(label2);
label2 = new JLabel("Score : " + fenetre.getTemps());
add(label2, c);
revalidate();
repaint();
break;
default:
break;
}
}
}
|
package org.aksw.autosparql.server;
public class QueryTreeChange {
static enum ChangeType{
REPLACE_LABEL,
REMOVE_NODE;
}
private int nodeId;
private ChangeType type;
private String object;
private String edge;
public QueryTreeChange(int nodeId, ChangeType type){
this.nodeId = nodeId;
this.type = type;
}
public int getNodeId() {
return nodeId;
}
public ChangeType getType() {
return type;
}
public String getObject() {
return object;
}
public void setObject(String object) {
this.object = object;
}
public String getEdge() {
return edge;
}
public void setEdge(String edge) {
this.edge = edge;
}
@Override
public String toString() {
// return "nodeId" + (type==ChangeType.REPLACE_LABEL ? "Replace" : "Remove");
return nodeId + (type==ChangeType.REPLACE_LABEL ? "a" : "b");
}
@Override
public boolean equals(Object obj) {
if(obj == this){
return true;
}
if(obj == null || !(obj instanceof QueryTreeChange)){
return false;
}
QueryTreeChange other = (QueryTreeChange)obj;
return nodeId == other.getNodeId() && type == other.getType();
}
@Override
public int hashCode() {
return nodeId + type.hashCode() + 37;
}
}
|
package com.maco.blackjack.jsonMessage;
import edu.uclm.esi.common.jsonMessages.JSONMessage;
import edu.uclm.esi.common.jsonMessages.JSONable;
public class RequestCardMessage extends JSONMessage{
@JSONable
private String text;
public RequestCardMessage(String text) {
super(false);
this.text = text;
}
public String getText() {
return text;
}
}
|
package com.ripple.price.util;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
/**
* Created by Geert Weening (geert@ripple.com) on 2/6/14.
*/
public class JSONRequest extends Request<JSONObject>
{
private final Response.Listener<JSONObject> mListener;
public JSONRequest(int method, String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener)
{
super(method, url, errorListener);
mListener = listener;
}
@Override public Response<JSONObject> parseNetworkResponse(NetworkResponse response)
{
try {
String charset = HttpHeaderParser.parseCharset(response.headers);
return Response.success(new JSONObject(new String(response.data, charset.equals(HTTP.DEFAULT_CONTENT_CHARSET) ? HTTP.UTF_8 : charset)), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException e) {
return Response.error(new ParseError(e));
}
}
@Override protected VolleyError parseNetworkError(VolleyError volleyError)
{
return super.parseNetworkError(volleyError);
}
@Override public void deliverError(VolleyError error)
{
super.deliverError(error);
}
@Override protected void deliverResponse(JSONObject response)
{
mListener.onResponse(response);
}
}
|
package edu.wctc;
import java.math.BigDecimal;
import java.math.BigInteger;
public class Letters {
private static final long WI_POPULATION = 5_726_398;
private static final long CA_POPULATION = 38_041_430;
private static final long TX_POPULATION = 26_059_203;
private static final double COPY_PRICE = 3.23;
public static void main(String[] args) {
System.out.println("USING PRIMITIVE NUMBERS");
usingPrimitives();
System.out.println("USING BIG NUMBERS");
usingBigNumbers();
}
private static void usingBigNumbers() {
BigInteger wisco = BigInteger.valueOf(WI_POPULATION);
BigInteger cali = BigInteger.valueOf(CA_POPULATION);
BigInteger texas = BigInteger.valueOf(TX_POPULATION);
BigDecimal price = BigDecimal.valueOf(COPY_PRICE);
BigInteger wiscoToCali = wisco.multiply(cali);
System.out.printf("Wisconsin letters written to California: %d%n", wiscoToCali);
BigInteger copiesForTexas = wiscoToCali.multiply(texas);
System.out.printf("Copies for Texans: %d%n", copiesForTexas);
// Can only do operations on same type, so create BigDecimal from BigInteger
BigDecimal priceForCopies = price.multiply(new BigDecimal(copiesForTexas));
System.out.printf("Cost of copies at $%.2f each: $%,.2f%n", COPY_PRICE, priceForCopies);
}
public static void usingPrimitives() {
long wiscoToCali = WI_POPULATION * CA_POPULATION;
System.out.printf("Wisconsin letters written to California: %d%n", wiscoToCali);
long copiesForTexas = wiscoToCali * TX_POPULATION;
System.out.printf("Copies for Texans: %d%n", copiesForTexas);
double priceForCopies = copiesForTexas * COPY_PRICE;
System.out.printf("Cost of copies at $%.2f each: $%,.2f%n", COPY_PRICE, priceForCopies);
}
}
|
package cn.test.wheelTimer;
import com.alibaba.fastjson.JSON;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by xiaoni on 2019/11/5.
*/
@Slf4j
public class WheelTimerTest {
public static void main(String[] args) {
log.info("" + -1/3);
ExecutorService executorService = new ThreadPoolExecutor(5, 10, 5000L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024),
new ThreadFactoryBuilder().setNameFormat("myWheelTimer-Pool-%d").build(),
new ThreadPoolExecutor.AbortPolicy());
MyWheelTimer myWheelTimer = new MyWheelTimer(executorService, 600L, TimeUnit.MILLISECONDS, 10);
// MyWheelTimer myWheelTimer2 = new MyWheelTimer(executorService, 600L, TimeUnit.MILLISECONDS, 10);
long now = System.currentTimeMillis();
Runnable runnable1 = new Runnable() {
@Override
public void run() {
log.info("I'm run 1");
}
};
MyWheelWorker myWheelWorker1 = new MyWheelWorker(now + 10000L, runnable1);
Runnable runnable2 = new Runnable() {
@Override
public void run() {
log.info("I'm run 2");
}
};
MyWheelWorker myWheelWorker2 = new MyWheelWorker(now + 15000L, runnable2);
Runnable runnable3 = new Runnable() {
@Override
public void run() {
log.info("I'm run 3");
}
};
MyWheelWorker myWheelWorker3 = new MyWheelWorker(now + 200000000L, runnable3);
myWheelTimer.addWheelWorker(myWheelWorker1);
myWheelTimer.addWheelWorker(myWheelWorker2);
myWheelTimer.addWheelWorker(myWheelWorker3);
myWheelTimer.start();
// myWheelTimer2.start();
try {
Thread.sleep(20000L);
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
}
log.info("try stop myWheelTimer");
log.info(JSON.toJSONString(myWheelTimer.stop()));
}
}
|
import java.util.Scanner;
public class ActivationKeys {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuilder activationCode = new StringBuilder(scanner.nextLine());
String input = scanner.nextLine();
String[] commands = input.split(">>>");
while (!commands[0].equals("Generate")){
String mainCommand = commands[0];
switch (mainCommand){
case "Contains":
String searchQueryString = commands[1];
if (activationCode.toString().contains(searchQueryString)){
System.out.printf("%s contains %s%n", activationCode, searchQueryString);
}else {
System.out.println("Substring not found!");
}
break;
case "Flip":
String upperOrLower = commands[1];
int indexFrom = Integer.parseInt(commands[2]);
int toIndex = Integer.parseInt(commands[3]);
String substringToUpperLower = activationCode.substring(indexFrom, toIndex);
if (upperOrLower.equals("Upper")){
activationCode = new StringBuilder(activationCode.toString()
.replace(substringToUpperLower, substringToUpperLower.toUpperCase()));
System.out.println(activationCode);
}else if (upperOrLower.equals("Lower")){
activationCode = new StringBuilder(activationCode.toString()
.replace(substringToUpperLower, substringToUpperLower.toLowerCase()));
System.out.println(activationCode);
}
break;
case "Slice":
int startIndex = Integer.parseInt(commands[1]);
int endIndex = Integer.parseInt(commands[2]);
activationCode.delete(startIndex, endIndex);
System.out.println(activationCode);
break;
default:
break;
}
input = scanner.nextLine();
commands = input.split(">>>");
}
System.out.println("Your activation key is: " + activationCode);
}
}
|
package mekfarm.common;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
/**
* Created by CF on 2016-11-12.
*/
public class BlockPosUtils {
public static BlockCube getCube(BlockPos entityPos, EnumFacing facing, int radius, int height) {
EnumFacing left = facing.rotateYCCW();
EnumFacing right = facing.rotateY();
BlockPos pos1 = entityPos
.offset(left, radius)
.offset(facing, 1);
BlockPos pos2 = entityPos
.offset(right, radius)
.offset(facing, radius * 2 + 1)
.offset(EnumFacing.UP, height - 1);
return new BlockCube(pos1, pos2);
}
}
|
package com.kaizenmax.taikinys_icl.view;
import android.app.DatePickerDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.kaizenmax.taikinys_icl.R;
import com.kaizenmax.taikinys_icl.model.MobileDatabase;
import com.kaizenmax.taikinys_icl.pojo.FarmerDetailsPojo;
import com.kaizenmax.taikinys_icl.pojo.PromoFarmerMeetingPojo;
import com.kaizenmax.taikinys_icl.pojo.RetailerDetailsPojo;
import com.kaizenmax.taikinys_icl.presenter.FarmerMeetingActivityPresenterInterface;
import com.kaizenmax.taikinys_icl.presenter.FarmerMeetingPresenter;
import com.kaizenmax.taikinys_icl.presenter.IndividualFarmerContactActivityPresenter;
import com.kaizenmax.taikinys_icl.presenter.IndividualFarmerContactActivityPresenterInterface;
import com.kaizenmax.taikinys_icl.util.ActivityNames;
import com.kaizenmax.taikinys_icl.util.MultiSelectionSpinner;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class FarmerMeetingActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
EditText dateOfActivityEditText;
EditText noOfFarmersEditText;
EditText expensesEditText;
AutoCompleteTextView villageNameEditText;
Spinner cropCategorySpinner;
Spinner cropFocusSpinner;
MultiSelectionSpinner productFocusMultiSpinner;
Spinner meetingPurposeSpinner;
EditText meetingHighlightsEditText;
Button uploadButton;
Button saveButton;
DatePickerDialog picker;
TextView selectedFilesCountTextview;
private static FarmerMeetingActivity instance;
private Button addRowBtn;
private Button addRowFarmerBtn;
private FarmerMeetingActivityPresenterInterface farmerMeetingActivityInterface;
String clientName;
String faOfficeState;
List<String> cropCategories=new ArrayList<String>();
List<String> cropFocusList=new ArrayList<String>();
MobileDatabase dbHelper= new MobileDatabase(this);
String selectedCropCategory;
String selectedCropFocus;
String selectedMeetingPurpose;
private android.support.v7.widget.LinearLayoutCompat parentLinearLayout;
public LinearLayout retailerLayout;
//private android.support.v7.widget.LinearLayoutCompat parentLinearLayout_farmers;
public LinearLayout farmerLayout;
List<View> viewList=new ArrayList<View>();
List<RetailerDetailsPojo> retailerDetailsPojoList=new ArrayList<RetailerDetailsPojo>();
List<View> farmerViewList=new ArrayList<View>();
List<FarmerDetailsPojo> farmerDetailsPojoList=new ArrayList<FarmerDetailsPojo>();
AutoCompleteTextView firmName;
EditText proprietorName;
EditText retailerMobile;
EditText farmerNameEditText;
EditText acresEditText;
EditText farmerMobileEditText;
//For upload
int PICK_IMAGE_MULTIPLE = 1;
List<byte []> attachmentList =new ArrayList<byte []>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_farmer_meeting);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}); */
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
instance=this;
// testingFMLocalRetrival();
dateOfActivityEditText = findViewById(R.id.dateOfActivity);
dateOfActivityEditText.setInputType(InputType.TYPE_NULL);
// // it will not allow cursor to go to this field i.e non-focusable
//method for pop-up of calender by vinod on 13/08/2019
dateOfActivityEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar clndr = Calendar.getInstance();
int day = clndr.get(Calendar.DAY_OF_MONTH);
int month = clndr.get(Calendar.MONTH);
int year = clndr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(FarmerMeetingActivity.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
dateOfActivityEditText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.getDatePicker().setMaxDate(new Date().getTime());
picker.show();
dateOfActivityEditText.setFocusable(false);
}
});
// dateOfActivityEditText.setShowSoftInputOnFocus(false);
noOfFarmersEditText = findViewById(R.id.nooffarmers);
expensesEditText = findViewById(R.id.expenses);
villageNameEditText = findViewById(R.id.village);
cropCategorySpinner = findViewById(R.id.cropCategory);
cropFocusSpinner = findViewById(R.id.cropFocus);
meetingPurposeSpinner = findViewById(R.id.meetingpurpose);
productFocusMultiSpinner = findViewById(R.id.productFocus);
meetingHighlightsEditText = findViewById(R.id.meetinghighlights);
addRowBtn = findViewById(R.id.addButton);
addRowFarmerBtn = findViewById(R.id.addButtonFarmers);
saveButton = findViewById(R.id.saveBtn);
uploadButton= findViewById(R.id.upload);
selectedFilesCountTextview = findViewById(R.id.filescount);
firmName=findViewById(R.id.firmName);
proprietorName = findViewById(R.id.propName);
retailerMobile = findViewById(R.id.retailerMobile);
farmerMeetingActivityInterface = new FarmerMeetingPresenter();
parentLinearLayout = findViewById(R.id.parent_linear_layout);
retailerLayout = findViewById(R.id.retailerDetails);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.retailer_details_multiple_layout, null);
// Add the new row before the add field button.
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 2);
// firmName=rowView.findViewById(R.id.firmName);
viewList.add(rowView);
setAdapterOnFirmName(rowView);
farmerLayout = findViewById(R.id.farmerDetails);
LayoutInflater inflater1 = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView2 = inflater.inflate(R.layout.farmer_details_multipe_layout, null);
parentLinearLayout.addView(rowView2, parentLinearLayout.getChildCount() - 5);
farmerViewList.add(rowView2);
//setAdapterOnFarmerName();
try {
clientName = farmerMeetingActivityInterface.getClientName();
} catch (Exception e) {
e.printStackTrace();
}
try {
faOfficeState=farmerMeetingActivityInterface.getStateName();
} catch (Exception e) {
e.printStackTrace();
}
//SETTING LIST IN PRODUCT FOCUS
List<String> productlist = new ArrayList<String>();
productlist.add("ASD");
//String clientName = dbHelper.getClientName();
//String faOfficeState=dbHelper.getStateName();
try {
productlist=farmerMeetingActivityInterface.getProductFocusList(clientName,faOfficeState);
productFocusMultiSpinner.setItems(productlist);
} catch (Exception e) {
e.printStackTrace();
}
// Toast.makeText(IndividualFarmerContactActivity.this, "ClientName "+clientName +" State"+faOfficeState, Toast.LENGTH_SHORT).show();
//SETTING LIST IN PRODUCT FOCUS ENDS
//SETTING LIST IN VILLAGE DROP DOWN
List<String> villageList=new ArrayList<String>();
// villageList=dbHelper.getVillageList();
try {
villageList = farmerMeetingActivityInterface.getVillageList();
} catch (Exception e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,villageList);
villageNameEditText.setAdapter(adapter);
villageNameEditText.setThreshold(1);
// SETTING LIST IN VILLAGE DROP DOWN ENDS
//GETTING CROP CATEGORIES
try {
cropCategories=farmerMeetingActivityInterface.getCropCategories();
} catch (Exception e) {
e.printStackTrace();
}
// GETTINNG CROP CATEGORIES ENDS
//Adding List to Crop Category
ArrayAdapter<String> cropCategoryDataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, cropCategories);
cropCategoryDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cropCategorySpinner.setAdapter(cropCategoryDataAdapter);
//Adding List Crop Category Ends
// Adding List to CropFocus
//Adding Listener to Crop category so that crop Focus list can be according to selected crop category
cropCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedCropCategory= cropCategories.get(position);
// cropFocusList= dbHelper.getCropFocus(selectedCropCategory);
try {
cropFocusList= farmerMeetingActivityInterface.getCropFocus(selectedCropCategory);
} catch (Exception e) {
e.printStackTrace();
}
ArrayAdapter<String> cropFocusDataAdapter = new ArrayAdapter<String>(FarmerMeetingActivity.this, android.R.layout.simple_spinner_dropdown_item, cropFocusList);
cropFocusDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cropFocusSpinner.setAdapter(cropFocusDataAdapter);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Adding Listener to Crop category so that crop Focus list can be according to selected crop category
//Adding Listener to CropFocus to get selectedCropFocus
cropFocusSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedCropFocus= cropFocusList.get(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Adding Listener to CropFocus to get selectedCropFocus Ends
//Adding method to get meeting purposes by vinod on 13/08/2019
List<String> meetingPurposeList = new ArrayList<String>();
// meetingPurposeList.add("Select Meeting Purpose*");
//meetingPurposeList.add("A");
//String clientName = dbHelper.getClientName();
//String faOfficeState=dbHelper.getStateName();
try {
meetingPurposeList=farmerMeetingActivityInterface.getMeetingPurposeList(ActivityNames.FARMER_MEETING);
ArrayAdapter<String> meetingPurposeDataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, meetingPurposeList);
meetingPurposeDataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
meetingPurposeSpinner.setAdapter(meetingPurposeDataAdapter);
} catch (Exception e) {
e.printStackTrace();
}
//Adding listener on meetingPurpose by vinod on 16/08/2019
final List<String> finalMeetingPurposeList = meetingPurposeList;
meetingPurposeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedMeetingPurpose= finalMeetingPurposeList.get(position);
// Toast.makeText(FarmerMeetingActivity.this, ""+selectedMeetingPurpose, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Toast.makeText(IndividualFarmerContactActivity.this, "ClientName "+clientName +" State"+faOfficeState, Toast.LENGTH_SHORT).show();
//SETTING LIST IN PRODUCT FOCUS ENDS
// Adding method to get meeting purposes ends
//Adding listener to upload image button by vinod on 21/08/2019
uploadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
// Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//startActivityForResult(intent,0);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select File"), PICK_IMAGE_MULTIPLE);
}
});
//Adding listener toupload image ends
//Adding listener to save button by vinod on 16/08/2019
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String dateofActivity_entered = dateOfActivityEditText.getText().toString();
String noOfFarmers_entered = noOfFarmersEditText.getText().toString();
String expenses_entered = expensesEditText.getText().toString();
String village_entered = villageNameEditText.getText().toString();
List<String> selectedProductsList = productFocusMultiSpinner.getSelectedStrings();
String uploadFlagStatus = "No";
String meetingHighlights = meetingHighlightsEditText.getText().toString();
Boolean errorStatus = false;
for (int i = 0; i < farmerViewList.size(); i++) {
farmerNameEditText = farmerViewList.get(i).findViewById(R.id.farmerName);
acresEditText = farmerViewList.get(i).findViewById(R.id.landacres);
farmerMobileEditText = farmerViewList.get(i).findViewById(R.id.farmerMobile);
errorStatus = false;
if (farmerNameEditText.getText().toString() == null || farmerNameEditText.getText().toString().equals("")) {
farmerNameEditText.setError("Please enter farmer name.");
errorStatus = true;
// Toast.makeText(FarmerMeetingActivity.getInstance(), "ERROR hai "+farmerMobileEditText.getText()
// .toString(), Toast.LENGTH_SHORT).show();
}
if (acresEditText.getText().toString() == null || acresEditText.getText().toString().equals("")) {
acresEditText.setError("Please enter land in acres.");
errorStatus = true;
}
if (farmerMobileEditText.getText().toString() == null || farmerMobileEditText.getText().toString().equals("")) {
farmerMobileEditText.setError("Please enter farmer mobile.");
errorStatus = true;
}
if (farmerMobileEditText.getText().toString() != null && !farmerMobileEditText.getText().toString().equals("")
&& farmerMobileEditText.getText().toString().trim().length() != 10) {
farmerMobileEditText.setError("Please enter 10 digits in farmer mobile.");
// Toast.makeText(FarmerMeetingActivity.getInstance(), "Length "+farmerMobileEditText.getText().toString().length(), Toast.LENGTH_SHORT).show();
errorStatus = true;
}
if (errorStatus == true)
break;
}
if (dateofActivity_entered != null && !dateofActivity_entered.equals("")
&& village_entered!=null && !village_entered.equals("") && !(village_entered.trim().length()<2)
&& selectedCropCategory != null && !selectedCropCategory.equals("") && !selectedCropCategory.equals("Select Crop Category*")
&& selectedCropFocus != null && !selectedCropFocus.equals("") && !selectedCropFocus.equals("Select Crop Focus*")
&& selectedMeetingPurpose != null && !selectedMeetingPurpose.equals("") && !selectedMeetingPurpose.equals("Select Meeting Purpose*")
&& selectedProductsList.size() != 0 && !(selectedProductsList.size() == 1 && selectedProductsList.get(0).equals("Select Product Focus*"))
&& errorStatus == false)
{
Toast.makeText(FarmerMeetingActivity.this, "Saved successfully", Toast.LENGTH_SHORT).show();
for (int i = 0; i < viewList.size(); i++) {
EditText firmName = (viewList.get(i)).findViewById(R.id.firmName);
EditText retailerMobile = (viewList.get(i)).findViewById(R.id.retailerMobile);
EditText proprietorName = (viewList.get(i)).findViewById(R.id.propName);
// String as=zx.getText().toString();
RetailerDetailsPojo retailerDetailsPojo = new RetailerDetailsPojo();
retailerDetailsPojo.setFirmName(firmName.getText().toString());
retailerDetailsPojo.setRetailerMobile(retailerMobile.getText().toString());
retailerDetailsPojo.setPropName(proprietorName.getText().toString());
// Toast.makeText(FarmerMeetingActivity.this, "FirmName: " + firmName.getText(), Toast.LENGTH_SHORT).show();
retailerDetailsPojoList.add(retailerDetailsPojo);
}
for (int i = 0; i < farmerViewList.size(); i++) {
EditText farmerName = (farmerViewList.get(i)).findViewById(R.id.farmerName);
EditText farmerLand = (farmerViewList.get(i)).findViewById(R.id.landacres);
EditText farmerMobile = (farmerViewList.get(i)).findViewById(R.id.farmerMobile);
// String as=zx.getText().toString();
FarmerDetailsPojo farmerDetailsPojo = new FarmerDetailsPojo();
farmerDetailsPojo.setFarmerName(farmerName.getText().toString());
farmerDetailsPojo.setFarmerLand(farmerLand.getText().toString());
farmerDetailsPojo.setFarmerMobile(farmerMobile.getText().toString());
// Toast.makeText(FarmerMeetingActivity.this, "Farmer Name: " + farmerName.getText(), Toast.LENGTH_SHORT).show();
farmerDetailsPojoList.add(farmerDetailsPojo);
}
String faOfficeDistrict="";
try {
faOfficeDistrict=farmerMeetingActivityInterface.getFaOfficeDistrict();
} catch (Exception e) {
e.printStackTrace();
}
Calendar cal=Calendar.getInstance();
Date createdOn=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String createdOn_string = dateFormat.format(createdOn);
String createdby="";
try {
createdby=farmerMeetingActivityInterface.getMobileFromSharedpreference();
} catch (Exception e) {
e.printStackTrace();
}
try {
//inserting Farmer Meeting data into local database using this method created by vinod on 14/08/2019
farmerMeetingActivityInterface.insertFMdata("FM", dateofActivity_entered,
noOfFarmers_entered,expenses_entered,
village_entered,selectedCropCategory,selectedCropFocus,
selectedMeetingPurpose,selectedProductsList,
meetingHighlights,farmerDetailsPojoList,retailerDetailsPojoList,
uploadFlagStatus,
createdOn_string,createdby,clientName,faOfficeDistrict,attachmentList);
} catch (Exception e) {
e.printStackTrace();
}
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
try {
IndividualFarmerContactActivityPresenterInterface individualFarmerContactActivityPresenterInterface = new IndividualFarmerContactActivityPresenter();
individualFarmerContactActivityPresenterInterface.sendingDataToWebService();
} catch (Exception e) {
e.printStackTrace();
}
//sendingDataToWebService(); to be removed
}
Intent intent = new Intent(FarmerMeetingActivity.this, FarmerMeetingActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
} else {
if (dateofActivity_entered == null || dateofActivity_entered.equals(""))
dateOfActivityEditText.setError("Please select date of activity");
if(village_entered==null || village_entered.equals(""))
villageNameEditText.setError("Please enter village");
if( village_entered!=null && !village_entered.equals("") && village_entered.trim().length()<2)
{
villageNameEditText.setError("Please enter minimum two characters in village");
}
if (selectedCropCategory == null || selectedCropCategory.equals("") || selectedCropCategory.equals("Select Crop Category*")) {
TextView errorText = (TextView) cropCategorySpinner.getSelectedView();
errorText.setError("Please select crop category");
}
if (selectedCropFocus == null || selectedCropFocus.equals("") || selectedCropFocus.equals("Select Crop Focus*")) {
TextView errorText = (TextView) cropFocusSpinner.getSelectedView();
errorText.setError("Please select crop focus");
}
if (selectedMeetingPurpose == null || selectedMeetingPurpose.equals("") || selectedMeetingPurpose.equals("Select Meeting Purpose*")) {
TextView errorText = (TextView) meetingPurposeSpinner.getSelectedView();
errorText.setError("Please select meeting purpose");
}
if (selectedProductsList.size() == 0 || (selectedProductsList.size() == 1 && selectedProductsList.get(0).equals("Select Product Focus*"))) {
TextView errorText = (TextView) productFocusMultiSpinner.getSelectedView();
errorText.setError("Please select product focus");
}
}
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.farmer_meeting, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
/* if (id == R.id.action_settings) {
return true;
} */
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.ifc) {
// IFC Activity clicked by user
Intent intent = new Intent(FarmerMeetingActivity.this, IndividualFarmerContactMainActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
} else if (id == R.id.fm) {
Intent intent = new Intent(FarmerMeetingActivity.this, FarmerMeetingActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
} else if (id == R.id.fd) {
Intent intent = new Intent(FarmerMeetingActivity.this, FieldDayActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
} else if (id == R.id.dv) {
Intent intent = new Intent(FarmerMeetingActivity.this, DiagnosticVisitActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
}
else if(id==R.id.mc){
Intent intent = new Intent(FarmerMeetingActivity.this, MandiCampaignActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
}
else if (id == R.id.demol3) {
Intent intent = new Intent(FarmerMeetingActivity.this, DemoL3Activity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
}
else if (id == R.id.demol3_progress) {
Intent intent = new Intent(FarmerMeetingActivity.this, DemoL3_InProgressActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
}
else if (id == R.id.pastRecord) {
Intent intent = new Intent(FarmerMeetingActivity.this, PastRecordActivity.class);
//pgsBar.setVisibility(View.GONE);
startActivity(intent);
finish();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void setAdapterOnFirmName(final View v) {
List<String> firmNameList = new ArrayList<String>();
// firmNameList = dbHelper.getFirmNameList(); //to be removed
farmerMeetingActivityInterface = new FarmerMeetingPresenter();
try {
firmNameList = farmerMeetingActivityInterface.getFirmNameList();
} catch (Exception e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, firmNameList);
firmName = v.findViewById(R.id.firmName);
// firmName.setInputType(InputType.TYPE_NULL);
firmName.setAdapter(adapter);
firmName.setThreshold(1);
final View view=v;
firmName.setOnDismissListener(new AutoCompleteTextView.OnDismissListener() {
@Override
public void onDismiss() {
// Toast.makeText(IndividualFarmerContactActivity.this, "DISMISS", Toast.LENGTH_SHORT).show();
// String propName= dbHelper.getPropName(firmName.getText().toString()); to be removed
// String retailerMobile=dbHelper.getRetailerMobile(firmName.getText().toString()); to be removed
String propName= null;
try {
propName = farmerMeetingActivityInterface.getPropName(firmName.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
String retailerMobile= null;
try {
retailerMobile = farmerMeetingActivityInterface.getRetailerMobile(firmName.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
if(!propName.equals("") && !retailerMobile.equals("")) {
EditText propNameEditText = view.findViewById(R.id.propName);
propNameEditText.setText(propName);
EditText retailerMobileEditText=view.findViewById(R.id.retailerMobile);
retailerMobileEditText.setText(retailerMobile);
}
else
{
firmName.setError("Please enter firm name from suggested values only");
}
}
});
}
public static FarmerMeetingActivity getInstance() {
return instance;
}
public void addFarmerRow(View v) {
Boolean errorStatus=false;
for(int i=0;i<farmerViewList.size();i++) {
farmerNameEditText = farmerViewList.get(i).findViewById(R.id.farmerName);
acresEditText = farmerViewList.get(i).findViewById(R.id.landacres);
farmerMobileEditText = farmerViewList.get(i).findViewById(R.id.farmerMobile);
if (farmerNameEditText.getText().toString() == null || farmerNameEditText.getText().toString().equals(""))
{
farmerNameEditText.setError("Please enter farmer name.");
errorStatus = true;
// Toast.makeText(FarmerMeetingActivity.getInstance(), "ERROR hai "+farmerMobileEditText.getText()
// .toString(), Toast.LENGTH_SHORT).show();
}
if(acresEditText.getText().toString() == null || acresEditText.getText().toString().equals(""))
{
acresEditText.setError("Please enter land in acres.");
errorStatus = true;
}
if(farmerMobileEditText.getText().toString() == null || farmerMobileEditText.getText().toString().equals(""))
{
farmerMobileEditText.setError("Please enter farmer mobile.");
errorStatus = true;
}
if(farmerMobileEditText.getText().toString() != null && !farmerMobileEditText.getText().toString().equals("")
&& farmerMobileEditText.getText().toString().trim().length() != 10)
{
farmerMobileEditText.setError("Please enter 10 digits in farmer mobile.");
// Toast.makeText(FarmerMeetingActivity.getInstance(), "Length "+farmerMobileEditText.getText().toString().length(), Toast.LENGTH_SHORT).show();
errorStatus = true;
}
if(errorStatus==true)
break;
}
if(errorStatus== false) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.farmer_details_multipe_layout, null);
// Add the new row before the add field button.
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 5);
// firmName = ((View) rowView.getParent().getParent()).findViewById(R.id.firmName);
farmerViewList.add(rowView);
}
}
public void addRetailerRow(View v) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.retailer_details_multiple_layout, null);
// Add the new row before the add field button.
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 2);
//firmName = ((View) rowView.getParent().getParent()).findViewById(R.id.firmName);
viewList.add(rowView);
setAdapterOnFirmName(rowView);
// Toast.makeText(IndividualFarmerContactActivity.getInstance(), "FIRM NAME "+rowView.findViewById(R.id.farmerName), Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "FIRM NAME " + firmName.getText(), Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "Proprietor NAME "+proprietorName.getText(), Toast.LENGTH_SHORT).show();
//Toast.makeText(this, "Retailer Name "+retailerMobile.getText(), Toast.LENGTH_SHORT).show();
}
public void testingFMLocalRetrival()
{
Cursor z=dbHelper.getAllPromoFMEntries();
Integer id=null;
if (z != null && z.moveToFirst()) {
do {
id = z.getInt(z.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_ID));
String flagStatus=z.getString(z.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_UPLOAD_FLAG));
String village=z.getString(z.getColumnIndex(PromoFarmerMeetingPojo.PROMOFARMERMEETING_COLUMN_VILLAGE));
Toast.makeText(this, "ID "+id+" FlagStatus "+flagStatus+" Village "+village, Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "Farmer Name "+fmname, Toast.LENGTH_SHORT).show();
// do what ever you want here
// List<FarmerDetailsPojo> farmerDetailsPojoList= dbHelper.getFarmerDetails();
List<FarmerDetailsPojo> FarmerDetailsPojoList=dbHelper.getFarmerDetails(id);
for (int i=0;i<FarmerDetailsPojoList.size();i++)
{
FarmerDetailsPojo farmerDetailsPojo=FarmerDetailsPojoList.get(i);
String farmerName=farmerDetailsPojo.getFarmerName();
Toast.makeText(instance, "Farmer Name "+farmerName, Toast.LENGTH_SHORT).show();
}
List<RetailerDetailsPojo> retailerList=dbHelper.getRetailerDetails(id);
for (int i=0;i<retailerList.size();i++)
{
RetailerDetailsPojo retailerDetailsPojo=retailerList.get(i);
Toast.makeText(instance, "Firm Name "+retailerDetailsPojo.getFirmName(), Toast.LENGTH_SHORT).show();
}
} while (z.moveToNext());
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
}
// Toast.makeText(this, "TOTAL FETCHED COUNT "+x, Toast.LENGTH_SHORT).show();
z.close();
}
public void deleteRetailerRow(View v) {
// Toast.makeText(this, "aaaa ", Toast.LENGTH_SHORT).show();
//https://stackoverflow.com/questions/3995215/add-and-remove-views-in-android-dynamically
View namebar = ((View) v.getParent().getParent()).findViewById(R.id.retailerDetails);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
parent.removeView(namebar);
}
viewList.remove(namebar);
}
public void deleteFarmerRow(View v) {
// Toast.makeText(this, "aaaa ", Toast.LENGTH_SHORT).show();
//https://stackoverflow.com/questions/3995215/add-and-remove-views-in-android-dynamically
View namebar = ((View) v.getParent().getParent()).findViewById(R.id.farmerDetails);
// View namebar = findViewById(R.id.farmerDetails);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
parent.removeView(namebar);
}
farmerViewList.remove(namebar);
}
/* public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(FarmerMeetingActivity.getInstance().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(FarmerMeetingActivity.getInstance(), "Canceled", Toast.LENGTH_SHORT).show();
}
}
}*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
attachmentList = new ArrayList<byte []>();
if(data!=null && data.getData()==null) {
// Toast.makeText(this, "Request Code " + requestCode, Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "Result Code " + resultCode, Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// Toast.makeText(this, "Data " + data.getClipData(), Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "Files count " + data.getClipData().getItemCount(), Toast.LENGTH_SHORT).show();
ClipData clipData = data.getClipData();
if(data!=null && data.getClipData()!=null && data.getClipData().getItemCount()==0 )
selectedFilesCountTextview.setText("");
if(clipData!=null && clipData.getItemCount()<=5 && clipData.getItemCount()!=0)
{
selectedFilesCountTextview.setText(clipData.getItemCount()+" files selected");
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
Uri uri = clipData.getItemAt(i).getUri();
InputStream iStream = null;
try {
iStream = getContentResolver().openInputStream(uri);
File f = new File(uri.getPath());
long size = f.length();
// Toast.makeText(this, "FILE SIZE "+size, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
byte[] inputData = getBytes(iStream);
// Toast.makeText(this, "count : "+i+" byte array "+inputData , Toast.LENGTH_SHORT).show();
attachmentList.add(inputData);
// dbHelper.insertDataSetMaster(inputData);
//Toast.makeText(this, "BYTE ARRAY " + inputData, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else
Toast.makeText(this, "Maximum 5 files can be uploaded.", Toast.LENGTH_SHORT).show();
}
}
else if(data!=null)
{
Uri singleFileUri = data.getData();
InputStream iStream = null;
try {
iStream = getContentResolver().openInputStream(singleFileUri);
// File f = new File(singleFileUri.getPath());
// long size = f.length();
//Toast.makeText(this, "FILE SIZE "+size, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
byte[] inputData = getBytes(iStream);
attachmentList.add(inputData);
// dbHelper.insertDataSetMaster(inputData);
selectedFilesCountTextview.setText("1 file selected");
// Toast.makeText(this, "SINGLE BYTE ARRAY " + inputData, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
}
|
/*
* 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 clases;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author jesus
*/
public class potenciaServlet extends HttpServlet {
private ModeloDatos bd;
private ArrayList<Circuito> circuitos;
private ArrayList<Coche> coches;
@Override
public void init(ServletConfig cfg) throws ServletException {
bd = new ModeloDatos();
bd.abrirConexion();
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
circuitos = bd.getCircuitos();
coches = bd.getCoches();
if (circuitos.isEmpty() || coches.isEmpty()) {
response.sendRedirect(response.encodeRedirectURL("/Practica6/noHayDatos.html"));
} else {
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<link rel=\"stylesheet\" href=\"style/style.css\">");
out.println("<title>Servlet potenciaServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<ul class=\"menu\">\n"
+ " <li><a href=\"/Practica6/index.html\">Inicio</a></li>\n"
+ " <li><a href=\"/Practica6/nuevoCircuito.html\">Nuevo circuito</a></li>\n"
+ " <li><a href=\"/Practica6/nuevoCoche.html\">Nuevo coche</a></li>\n"
+ " <li><a href=\"/Practica6/verTodoServlet\">Ver todos</a></li>"
+ " <li><a href=\"/Practica6/potenciaServlet\">Calculo Kers</a></li>\n"
+ " </ul>");
out.println("<h2>Elige un circuito y un coche</h2>");
out.println("<form name=\"formulario\" action=\"/Practica6/CalculoServlet\">");
//circuitos
out.println("<select id=\"circuitos\" name=\"circuitos\" size=7 > ");
Iterator it = circuitos.iterator();
Circuito circuito = new Circuito();
while (it.hasNext()) {
circuito = (Circuito) it.next();
out.println("<option value=\"" + circuito.getNombre() + "\">" + circuito.getNombre() + "</option>");
}
out.println("</select>");
//coches
out.println("<select id=\"coches\" name=\"coches\" size=7 > ");
it = coches.iterator();
Coche coche = new Coche();
while (it.hasNext()) {
coche = (Coche) it.next();
out.println("<option value=\"" + coche.getNombre() + "\">" + coche.getNombre() + "</option>");
}
out.println("</select>");
out.println("<br>");
out.println("<input class=\"boton\" type=\"submit\" value=\"Calcular\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
} catch (Exception e) {
System.out.println("excepcion: " + e.getMessage());
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package com.stk123.service;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.stk123.model.bo.StkDataPpiType;
import com.stk123.model.bo.StkIndexNode;
import com.stk123.model.Industry;
import com.stk123.common.db.connection.Pool;
import com.stk123.model.tree.Tree;
import com.stk123.model.tree.TreeNode;
import com.stk123.common.util.CacheUtils;
import com.stk123.common.util.JdbcUtils;
import com.stk123.common.util.JsonUtils;
import com.stk123.common.CommonConstant;
import com.stk123.model.dto.MetaData;
import com.stk123.model.dto.Node;
public class IndexService {
public final static String ID_XZH = "3000";
public final static int ID_INDUSTRY_PE = 60000;
public final static int ID_PPI = 700000;
//private static Tree tree = null;
public Tree getTree() throws Exception {
Tree tree = (Tree)CacheUtils.getForever(CacheUtils.KEY_INDEX_TREE);
if(tree != null){
return tree;
}
Connection conn = null;
List<TreeNode> treeNodes = new ArrayList<TreeNode>();
try{
conn = Pool.getPool().getConnection();
List<StkIndexNode> nodes = JdbcUtils.list(conn, "select * from stk_index_node where disp_order >= 0 order by node_level asc,disp_order asc", StkIndexNode.class);
for(StkIndexNode node : nodes){
TreeNode tn = new TreeNode(node.getId(), node.getNodeLevel(), node.getParentId(), node);
treeNodes.add(tn);
}
tree = Tree.getTree(treeNodes, 1);
//行业平均PE
TreeNode industryPENode = tree.getNode(ID_INDUSTRY_PE);
List<Industry> industryTypes = Industry.getIndsutriesBySource(conn, Industry.INDUSTRY_CNINDEX);
for(Industry ind : industryTypes){
StkIndexNode node = new StkIndexNode();
node.setId(ind.getType().getId().intValue() + ID_INDUSTRY_PE);
node.setName(ind.getType().getName());
node.setNodeLevel(2);
node.setParentId(ID_INDUSTRY_PE);
TreeNode tn = new TreeNode(node.getId(), node.getNodeLevel(), node.getParentId(), node);
tn.setParent(industryPENode);
industryPENode.addChild(tn);
}
//大宗商品指标
TreeNode ppiNode = tree.getNode(ID_PPI);
List<StkDataPpiType> ppis = JdbcUtils.list(conn, "select * from stk_data_ppi_type order by name asc", StkDataPpiType.class);
for(StkDataPpiType ppi : ppis){
StkIndexNode node = new StkIndexNode();
node.setId(ppi.getId().intValue() + ID_PPI);
node.setName(ppi.getName());
node.setNodeLevel(2);
node.setParentId(ID_PPI);
TreeNode tn = new TreeNode(node.getId(), node.getNodeLevel(), node.getParentId(), node);
tn.setParent(ppiNode);
ppiNode.addChild(tn);
}
CacheUtils.putForever(CacheUtils.KEY_INDEX_TREE, tree);
return tree;
}finally{
Pool.getPool().free(conn);
}
}
public String getTreeJson() throws Exception {
return JsonUtils.getJsonString4JavaPOJO(convertToNode(this.getTree().getChildren()));
}
private List<Node> convertToNode(List<TreeNode> list){
List<Node> rs = new ArrayList<Node>();
for(TreeNode node : list){
Node n = indexNodeToNode((StkIndexNode)node.getStkIndexNode());
if(node.getChildren().size() > 0){
n.getChildren().addAll(convertToNode(node.getChildren()));
}else{
n.getAttr().setIsLeaf(CommonConstant.YES_Y);
}
rs.add(n);
}
return rs;
}
private Node indexNodeToNode(StkIndexNode indexNode){
Node node = new Node();
node.setData(indexNode.getName());
MetaData metadata = new MetaData();
metadata.setId(indexNode.getId().toString());
//metadata.setTitle(indexNode.getName());
node.setAttr(metadata);
if(node.getAttr().getId().equals(ID_XZH)){
node.setState("open");
}
return node;
}
public List<Map> bias(int id) throws Exception {
Connection conn = null;
try{
conn = Pool.getPool().getConnection();
List<Map> list = JdbcUtils.list2Map(conn, "select distinct report_date d, bias \""+id+"\" from stk_pe order by report_date asc");
return list;
}finally{
Pool.getPool().free(conn);
}
}
public List<Map> getPPI(int id) throws Exception {
Connection conn = null;
try{
conn = Pool.getPool().getConnection();
List<Map> list = JdbcUtils.list2Map(conn, "select ppi_date d, value \""+id+"\" from stk_data_ppi where type_id="+(id-IndexService.ID_PPI)+" order by ppi_date asc");
return list;
}finally{
Pool.getPool().free(conn);
}
}
public final static String SQL_INDEX_INDUSTRY_PE = "with " +
"t1 as (select pe_date,pe_ttm from stk_data_industry_pe where industry_id=? and type=1)," +
"t2 as (select pe_date,pe_ttm from stk_data_industry_pe where industry_id=? and type=2)," +
"t3 as (select pe_date,pe_ttm from stk_data_industry_pe where industry_id=? and type=3)," +
"t4 as (select avg(pe_ttm) pe_ttm,pe_date from stk_data_industry_pe where industry_id=? group by pe_date) " +
"select t1.pe_date d,t1.pe_ttm a,t2.pe_ttm b,t3.pe_ttm c,trunc(t4.pe_ttm,2) v from t1,t2,t3,t4 where t1.pe_date=t2.pe_date and t2.pe_date=t3.pe_date and t3.pe_date=t4.pe_date order by t1.pe_date asc";
public List<Map> industryPE(int id) throws Exception {
Connection conn = null;
try{
List params = new ArrayList();
params.add(id);
params.add(id);
params.add(id);
params.add(id);
conn = Pool.getPool().getConnection();
List<Map> list = JdbcUtils.list2Map(conn, SQL_INDEX_INDUSTRY_PE, params);
return list;
}finally{
Pool.getPool().free(conn);
}
}
public static void main(String[] args) throws Exception {
IndexService is = new IndexService();
String json = is.getTreeJson();
System.out.println(json);
}
}
|
package com.gxtc.huchuan.ui.mine.deal.orderList;
import com.gxtc.commlibrary.BasePresenter;
import com.gxtc.commlibrary.BaseUserView;
import com.gxtc.huchuan.bean.PurchaseListBean;
import java.util.List;
public interface PurchaseListContract {
interface View extends BaseUserView<PurchaseListContract.Presenter>{
void showData(List<PurchaseListBean> datas);
void showRefreshFinish(List<PurchaseListBean> datas);
void showLoadMore(List<PurchaseListBean> datas);
void showNoMore();
}
interface Presenter extends BasePresenter{
void getData(boolean isRefresh);
void loadMrore();
}
}
|
package com.daylyweb.music.dao;
import java.util.List;
import java.util.Map;
import com.daylyweb.music.mapper.Music;
public interface MusicDao {
int insert(Music music);
int insertByBatch(List<Object> list);
int deleteByIds(String songids);
Music getById(int songid);
List<Object> select(Map<String,Object> map);
List<Object> fuzzyQuery(Map<String,Object> map);
int getKeywordCount(String keyword);
int getLastCount();
int setCommend(String ids);
int unCommend(String ids);
int update(Music music);
}
|
import javax.swing.*;
import java.awt.*;
import java.util.LinkedList;
public class EmailGUI extends JFrame{
JTextArea studentInfoTArea = new JTextArea();
JLabel idLabel = new JLabel("ID: ");
JTextField idTfield = new JTextField(10);
JLabel nameLabel = new JLabel("Name: ");
JTextField nameTfield = new JTextField(10);
JButton testButton = new JButton("Test");
JButton addButton = new JButton("Add");
JButton deleteButton = new JButton("Delete");
JButton editButton = new JButton("Edit");
JButton saveButton = new JButton("Save");
// Class Instance Data
private LinkedList<StudentEmail> studentLList = new LinkedList<StudentEmail>(); //to display student info in a linked list
private int i;
public EmailGUI(){
JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
JPanel gridPanel = new JPanel(new GridLayout(2, 1)); //first row = id and name
//second row = buttons
studentInfoTArea.setEditable(false); //can't be written on, read only
panel1.add(idLabel);
panel1.add(idTfield);
panel1.add(nameLabel);
panel1.add(nameTfield);
panel2.add(testButton);
panel2.add(addButton);
panel2.add(deleteButton);
panel2.add(editButton);
panel2.add(saveButton);
gridPanel.add (panel1); //add to user interface
gridPanel.add (panel2);
saveButton.setEnabled(false); //we have to disable it because we can't save anything before editing a data
add(studentInfoTArea, BorderLayout.CENTER);
add(gridPanel, BorderLayout.SOUTH); // to display the panels south of the interface
testButton.addActionListener(actionEvent -> testData());
addButton.addActionListener(actionEvent -> addStudent());
deleteButton.addActionListener(actionEvent -> deleteEmail());
editButton.addActionListener(actionEvent -> editStudent());
saveButton.addActionListener(actionEvent -> saveStudent());
setTitle("Student Linked List");
}
private boolean isStudentIDInLL(String IDString){
boolean inList = false;
for (StudentEmail student : studentLList) {
if (student.getID().compareTo(IDString) == 0){
inList = true;
}
}
return inList;
}
private void addStudent() { // display the data in a linked list to the text area
if (isStudentIDInLL(idTfield.getText()) == true){
JOptionPane.showMessageDialog(EmailGUI.this,"Error! Student ID is already in the linked list."); // EmailGUI.this = to make the error appear on the middle of the GUI
}
else {
studentLList.add(new StudentEmail(idTfield.getText(), nameTfield.getText())); //new studentEmail class object to create new student
displayAll();
nameTfield.setText("");
idTfield.setText("");
}
}
private void displayAll(){
studentInfoTArea.setText("");
for (StudentEmail student : studentLList) { //each student in Llist we append the student to the LList
studentInfoTArea.append(student + "\n");
}
}
private void deleteEmail(){
if (studentLList.size() == 0){
JOptionPane.showMessageDialog(EmailGUI.this,"Error! Linked list is empty.");
}
else if (isStudentIDInLL(idTfield.getText()) == false){
JOptionPane.showMessageDialog(EmailGUI.this,"Error! Student ID is not in the linked list.");
}
else {
for (int s = 0; s < studentLList.size(); s++) {
String currentId = studentLList.get(s).getID();
if (currentId.compareTo(idTfield.getText()) == 0){
studentLList.remove(s);
}
}
displayAll();
nameTfield.setText("");
idTfield.setText("");
}
}
//gets the name of the specified id
private void editStudent(){
if (studentLList.size() == 0){
JOptionPane.showMessageDialog(EmailGUI.this,"Error! Linked list is empty.");
}
else if (isStudentIDInLL(idTfield.getText()) == false){
JOptionPane.showMessageDialog(EmailGUI.this,"Error! Student ID is not in the linked list.");
}
else {
i = -1;
for (int s = 0; s < studentLList.size(); s++) {
String currentId = studentLList.get(s).getID();
if (currentId.compareTo(idTfield.getText()) == 0){
i = s;
s = studentLList.size(); //to exit loop
}
}// while using the edit button set other buttons to disabled however save button is enabled
// because after editing we have to save it
saveButton.setEnabled(true);
testButton.setEnabled(false);
addButton.setEnabled(false);
deleteButton.setEnabled(false);
editButton.setEnabled(false);
nameTfield.setText(studentLList.get(i).getName());
}
}
//data that always appears to test
private void testData() {
nameTfield.setText("Selma");
idTfield.setText("1");
addStudent();
nameTfield.setText("Asel");
idTfield.setText("2");
addStudent();
nameTfield.setText("Osman");
idTfield.setText("3");
addStudent();
nameTfield.setText("Gunduz");
idTfield.setText("4");
addStudent();
}
private void saveStudent(){
studentLList.get(i).setName(nameTfield.getText());
studentLList.get(i).setID(idTfield.getText());
displayAll();
nameTfield.setText("");
idTfield.setText("");
// enables back the buttons after saving the data
saveButton.setEnabled(false);
testButton.setEnabled(true);
addButton.setEnabled(true);
deleteButton.setEnabled(true);
editButton.setEnabled(true);
}
public static void main(String[] args) {
EmailGUI gui = new EmailGUI();
gui.setVisible(true);
gui.setSize(400, 350);
gui.setLocation(200, 100);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //to close when clicked on close button
}
}
|
package com.juannarvaez.taskworkout.view.Adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.juannarvaez.taskworkout.R;
import com.juannarvaez.taskworkout.model.entily.Nutricion;
import java.util.ArrayList;
public class NutricionAdapter extends RecyclerView.Adapter <NutricionAdapter.NutricionViewHolder>{
private ArrayList<Nutricion> listado;
private OnItemClickListener onItemClickListener;
public void setListado(ArrayList<Nutricion> listado){
this.listado = listado;
notifyDataSetChanged();
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public NutricionAdapter(ArrayList<Nutricion> listado){
this.listado=listado;
}
public class NutricionViewHolder extends RecyclerView.ViewHolder {
private TextView tituloNutricion;
private ImageView imagenNutricion;
public NutricionViewHolder(@NonNull View itemView) {
super(itemView);
tituloNutricion =itemView.findViewById(R.id.titulo_nutricion);
imagenNutricion = itemView.findViewById(R.id.image_nutricion);
}
public void onBind(Nutricion miNutricion){
tituloNutricion.setText(miNutricion.getTituloNutricion());
Glide.with(itemView.getContext()).load(miNutricion.getImagenNutricion()).into(imagenNutricion);
if(onItemClickListener != null){
imagenNutricion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClickListener.onItemClickImagen(miNutricion, getAdapterPosition());
//Toast.makeText(itemView.getContext(), "Imagen "+miNutricion.getTituloNutricion(), Toast.LENGTH_SHORT).show();
}
});
tituloNutricion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClickListener.onItemClickNombre(miNutricion, getAdapterPosition());
//Toast.makeText(itemView.getContext(), "Imagen "+miNutricion.getTituloNutricion(), Toast.LENGTH_SHORT).show();
}
});
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClickListener.onItemClick(miNutricion, getAdapterPosition());
//Toast.makeText(itemView.getContext(), "Card "+miNutricion.getTituloNutricion(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
@NonNull
@Override
public NutricionViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View miVista = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_nutricion, parent, false);
return new NutricionViewHolder(miVista);
}
@Override
public void onBindViewHolder(@NonNull NutricionViewHolder holder, int position) {
Nutricion miNutricion = listado.get(position);
NutricionViewHolder miHolder = (NutricionViewHolder) holder;
miHolder.onBind(miNutricion);
}
@Override
public int getItemCount() {
return listado.size();
}
//inicio interfaz
public interface OnItemClickListener{
void onItemClick(Nutricion miNutricion, int posicion);
void onItemClickImagen(Nutricion miNutricion, int posicion);
void onItemClickNombre(Nutricion miNutricion, int posicion);
}
}
|
/**
* Package for calculate task.
*
* @author Sidorov Dmitriy
* @version $Id$
* @since 0.1
*/
package ru.javaprac.calculate;
|
package com.pelephone_mobile.mypelephone.network.rest.pojos;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/**
* Created by Gali.Issachar on 25/12/13.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class BranchesList extends Pojo {
// to map to the property in json
@JsonProperty("responseError")
public ResponseErrorItem responseError;
// to map to the property in json
@JsonProperty("Branches")
public List<BranchItem> branchesList;
@JsonProperty("GeneralText")
public String GeneralText;
}
|
package com.fsj.entity;
import java.io.Serializable;
import java.util.Date;
// 价格走势类
public class Pricetrend implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int ptid;// 走势编号(主键)
private Date recorddate;// 记录日期
private String grade;// 记录级别(日,月,年)
private String price;// 价格
private Users users;// 录入用户
private House house;// 所属房屋
public Pricetrend() {
super();
}
public Pricetrend(int ptid, Date recorddate, String grade, String price,
Users users, House house) {
super();
this.ptid = ptid;
this.recorddate = recorddate;
this.grade = grade;
this.price = price;
this.users = users;
this.house = house;
}
public int getPtid() {
return ptid;
}
public void setPtid(int ptid) {
this.ptid = ptid;
}
public Date getRecorddate() {
return recorddate;
}
public void setRecorddate(Date recorddate) {
this.recorddate = recorddate;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
public House getHouse() {
return house;
}
public void setHouse(House house) {
this.house = house;
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ActiveEon Team
* http://www.activeeon.com/
* Contributor(s):
*
* ################################################################
* $$ACTIVEEON_INITIAL_DEV$$
*/
package functionaltests.workflow;
import org.ow2.proactive.scheduler.common.task.flow.FlowActionType;
/**
* Tests the correctness of workflow-controlled jobs including {@link FlowActionType#LOOP} actions
*
* @author The ProActive Team
* @since ProActive Scheduling 2.2
*/
public class TestWorkflowLoopJobs2 extends TWorkflowJobs {
@Override
public final String[][] getJobs() {
return new String[][] {
// 1: complex multiple nested loops
{ "T1 0", "T2 1", "T3 2", "T11 3", "T12 4", "T11#1 5", "T12#1 6", "T11#2 7", "T12#2 8", "T10 11",
"T4 2", "T5 3", "T8 4", "T5#1 5", "T8#1 6", "T5#2 7", "T8#2 8", "T6 3", "T7 4", "T7#1 5",
"T7#2 6", "T9 15", "T4#1 16", "T5#3 17", "T8#3 18", "T5#4 19", "T8#4 20", "T5#5 21",
"T8#5 22", "T6#1 17", "T7#3 18", "T7#4 19", "T7#5 20", "T9#1 43", "T4#2 44", "T5#6 45",
"T8#6 46", "T5#7 47", "T8#7 48", "T5#8 49", "T8#8 50", "T6#2 45", "T7#6 46", "T7#7 47",
"T7#8 48", "T9#2 99", "T13 111", "T2#1 112", "T3#1 113", "T11#3 114", "T12#3 115",
"T11#4 116", "T12#4 117", "T11#5 118", "T12#5 119", "T10#1 233", "T4#3 113", "T5#9 114",
"T8#9 115", "T5#10 116", "T8#10 117", "T5#11 118", "T8#11 119", "T6#3 114", "T7#9 115",
"T7#10 116", "T7#11 117", "T9#3 237", "T4#4 238", "T5#12 239", "T8#12 240", "T5#13 241",
"T8#13 242", "T5#14 243", "T8#14 244", "T6#4 239", "T7#12 240", "T7#13 241", "T7#14 242",
"T9#4 487", "T4#5 488", "T5#15 489", "T8#15 490", "T5#16 491", "T8#16 492", "T5#17 493",
"T8#17 494", "T6#5 489", "T7#15 490", "T7#16 491", "T7#17 492", "T9#5 987", "T13#1 1221",
"T2#2 1222", "T3#2 1223", "T11#6 1224", "T12#6 1225", "T11#7 1226", "T12#7 1227",
"T11#8 1228", "T12#8 1229", "T10#2 2453", "T4#6 1223", "T5#18 1224", "T8#18 1225",
"T5#19 1226", "T8#19 1227", "T5#20 1228", "T8#20 1229", "T6#6 1224", "T7#18 1225",
"T7#19 1226", "T7#20 1227", "T9#6 2457", "T4#7 2458", "T5#21 2459", "T8#21 2460",
"T5#22 2461", "T8#22 2462", "T5#23 2463", "T8#23 2464", "T6#7 2459", "T7#21 2460",
"T7#22 2461", "T7#23 2462", "T9#7 4927", "T4#8 4928", "T5#24 4929", "T8#24 4930",
"T5#25 4931", "T8#25 4932", "T5#26 4933", "T8#26 4934", "T6#8 4929", "T7#24 4930",
"T7#25 4931", "T7#26 4932", "T9#8 9867", "T13#2 12321", "T14 12322", "T15 12322" },
//
};
}
@Override
public final String getJobPrefix() {
return "/functionaltests/workflow/descriptors/flow_loop_2_";
}
@org.junit.Test
public void run() throws Throwable {
internalRun();
}
}
|
package edu.udc.psw.modelo.manipulador;
public class ManipuladorPoligono {
}
|
/**
* Copyright 2017 伊永飞
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yea.web.jsonbody;
import java.lang.annotation.Annotation;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.yea.core.json.jackson.JsonMapper;
public class JsonReturnHandler implements HandlerMethodReturnValueHandler {
@Override
public boolean supportsReturnType(MethodParameter returnType) {
// 如果有自定义的 JSON 注解 就用这个Handler 来处理
return (AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), JsonBody.class) ||
returnType.hasMethodAnnotation(JsonBody.class) ||
AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), JsonPropFilter.class) ||
returnType.hasMethodAnnotation(JsonPropFilter.class));
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest) throws Exception {
// 设置这个就是最终的处理类了,处理完不再去找下一个类进行处理
mavContainer.setRequestHandled(true);
// 获得注解并执行filter方法 最后返回
HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
Annotation[] annos = returnType.getMethodAnnotations();
JsonMapper jsonMapper = new JsonMapper();
// 序列换成json时,将所有的long变成string
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
jsonMapper.registerModules(simpleModule);
// 序列换成json时,将所有的日期类型变成string
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
jsonMapper.setDateFormat(formatter);
/*
* @param filterId 需要设置规则的Class
* @param include 转换时包含哪些字段
* @param filter 转换时过滤哪些字段
*/
for (Annotation anno : annos) {
if (anno instanceof JsonPropFilter) {
JsonPropFilter json = (JsonPropFilter) anno;
if (json.type() == null)
continue;
if (!StringUtils.isEmpty(json.include())) {
jsonMapper.filter(json.type().getName(), SimpleBeanPropertyFilter.filterOutAllExcept(json.include().replaceAll(" ", "").split(",")));
} else if (!StringUtils.isEmpty(json.filter())) {
jsonMapper.filter(json.type().getName(), SimpleBeanPropertyFilter.serializeAllExcept(json.filter().replaceAll(" ", "").split(",")));
}
}
if (anno instanceof JsonBody) {
JsonBody jsonbody = (JsonBody) anno;
for(JsonPropFilter json : jsonbody.filters()) {
if (json.type() == null)
continue;
if (!StringUtils.isEmpty(json.include())) {
jsonMapper.filter(json.type().getName(), SimpleBeanPropertyFilter.filterOutAllExcept(json.include().replaceAll(" ", "").split(",")));
} else if (!StringUtils.isEmpty(json.filter())) {
jsonMapper.filter(json.type().getName(), SimpleBeanPropertyFilter.serializeAllExcept(json.filter().replaceAll(" ", "").split(",")));
}
}
}
}
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
String json = jsonMapper.generatorJson(returnValue);
response.getWriter().write(json);
}
}
|
package com.bofsoft.laio.customerservice.Database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.bofsoft.laio.database.DBCacheHelper;
/**
* 欢迎页面显示记录
*/
public class IntroDBAdapter {
private DBCacheHelper helper;
public IntroDBAdapter(Context context) {
// helper = new DBCacheHelper(context);
helper = DBCacheHelper.getInstance(context);
}
public int introBool() {
SQLiteDatabase sdb = helper.getReadableDatabase();
Cursor cursor = sdb.query("intro", new String[]{"_id"}, null, null, null, null, null);
int a = cursor.getCount();
cursor.close();
sdb.close();
return a;
}
public void insert(String introBool, String boolString) {
SQLiteDatabase sdb = helper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(introBool, boolString);
long s = sdb.insert("intro", null, cv);
sdb.close();
}
}
|
/*
* 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 Logica;
import Datos.vpersona;
import Datos.vtrabajador;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
*
*/
public class ftrabajador {
private conexion mysql = new conexion();
private Connection cn = mysql.conectar();
private String sSQL = "";
private String sSQL2 = "";
public Integer totalregistros;
public DefaultTableModel mostrar(String buscar) {
DefaultTableModel modelo;
String[] titulos = {"ID", "Nombres", "P_apellido", "S_pellido", "Doc", "Número Documento", "Dirección", "Teléfono", "Email", "Cargo","Acceso","Login","Clave","Estado"};
String[] registro = new String[14];
totalregistros = 0;
modelo = new DefaultTableModel(null, titulos);
sSQL = "select p.idpersona,p.Nombres,p.P_apellido,p.S_apellido,p.tipo_documento,p.num_documento,"
+ "p.direccion,p.telefono,p.email,t.Cargo,t.acceso,t.login,t.password,t.estado from persona p inner join Trabajador t "
+ "on p.idpersona=t.idpersona where num_documento like '%"
+ buscar + "%' order by idpersona desc";
try {
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery(sSQL);
while (rs.next()) {
registro[0] = rs.getString("idpersona");
registro[1] = rs.getString("Nombres");
registro[2] = rs.getString("P_apellido");
registro[3] = rs.getString("S_apellido");
registro[4] = rs.getString("tipo_documento");
registro[5] = rs.getString("num_documento");
registro[6] = rs.getString("direccion");
registro[7] = rs.getString("telefono");
registro[8] = rs.getString("email");
registro[9] = rs.getString("Cargo");
registro[10] = rs.getString("acceso");
registro[11] = rs.getString("login");
registro[12] = rs.getString("password");
registro[13] = rs.getString("estado");
totalregistros = totalregistros + 1;
modelo.addRow(registro);
}
return modelo;
} catch (Exception e) {
JOptionPane.showConfirmDialog(null, e);
return null;
}
}
public boolean insertar(vtrabajador dts) {
sSQL = "insert into persona (Nombres,P_apellido,S_apellido,tipo_documento,num_documento,direccion,telefono,email)"
+ "values (?,?,?,?,?,?,?,?)";
sSQL2 = "insert into trabajador (idpersona,Cargo,acceso,login,password,estado)"
+ "values ((select idpersona from persona order by idpersona desc limit 1),?,?,?,?,?)";
try {
PreparedStatement pst = cn.prepareStatement(sSQL);
PreparedStatement pst2 = cn.prepareStatement(sSQL2);
pst.setString(1, dts.getNombres());
pst.setString(2, dts.getP_apellido());
pst.setString(3, dts.getS_apellido());
pst.setString(4, dts.getTipo_documento());
pst.setString(5, dts.getNum_documento());
pst.setString(6, dts.getDireccion());
pst.setString(7, dts.getTelefono());
pst.setString(8, dts.getEmail());
pst2.setString(1, dts.getCargo());
pst2.setString(2, dts.getAcceso());
pst2.setString(3, dts.getLogin());
pst2.setString(4, dts.getPassword());
pst2.setString(5, dts.getEstado());
int n = pst.executeUpdate();
if (n != 0) {
int n2 = pst2.executeUpdate();
if (n2 != 0) {
return true;
} else {
return false;
}
} else {
return false;
}
} catch (Exception e) {
JOptionPane.showConfirmDialog(null, e);
return false;
}
}
public boolean editar(vtrabajador dts) {
sSQL = "update persona set Nombres=?,P_apellido=?,S_apellido=?,tipo_documento=?,num_documento=?,"
+ " direccion=?,telefono=?,email=? where idpersona=?";
sSQL2 = "update trabajador set Cargo=?,acceso=?,login=?,password=?,estado=?"
+ " where idpersona=?";
try {
PreparedStatement pst = cn.prepareStatement(sSQL);
PreparedStatement pst2 = cn.prepareStatement(sSQL2);
pst.setString(1, dts.getNombres());
pst.setString(2, dts.getP_apellido());
pst.setString(3, dts.getS_apellido());
pst.setString(4, dts.getTipo_documento());
pst.setString(5, dts.getNum_documento());
pst.setString(6, dts.getDireccion());
pst.setString(7, dts.getTelefono());
pst.setString(8, dts.getEmail());
pst.setInt(9, dts.getIdpersona());
pst2.setString(1, dts.getCargo());
pst2.setString(2, dts.getAcceso());
pst2.setString(3, dts.getLogin());
pst2.setString(4, dts.getPassword());
pst2.setString(5, dts.getEstado());
pst2.setInt(6, dts.getIdpersona());
int n = pst.executeUpdate();
if (n != 0) {
int n2 = pst2.executeUpdate();
if (n2 != 0) {
return true;
} else {
return false;
}
} else {
return false;
}
} catch (Exception e) {
JOptionPane.showConfirmDialog(null, e);
return false;
}
}
public boolean eliminar(vtrabajador dts) {
sSQL = "delete from trabajador where idpersona=?";
sSQL2 = "delete from persona where idpersona=?";
try {
PreparedStatement pst = cn.prepareStatement(sSQL);
PreparedStatement pst2 = cn.prepareStatement(sSQL2);
pst.setInt(1, dts.getIdpersona());
pst2.setInt(1, dts.getIdpersona());
int n = pst.executeUpdate();
if (n != 0) {
int n2 = pst2.executeUpdate();
if (n2 != 0) {
return true;
} else {
return false;
}
} else {
return false;
}
} catch (Exception e) {
JOptionPane.showConfirmDialog(null, e);
return false;
}
}
public DefaultTableModel login(String login,String password) {
DefaultTableModel modelo;
String[] titulos = {"ID", "Nombres", "Apaterno", "Amaterno","Acceso","Login","Clave","Estado"};
String[] registro = new String[8];
totalregistros = 0;
modelo = new DefaultTableModel(null, titulos);
sSQL = "select p.idpersona,p.Nombres,p.P_apellido,p.S_apellido,"
+ "t.acceso,t.login,t.password,t.estado from persona p inner join Trabajador t "
+ "on p.idpersona=t.idpersona where t.login='"
+ login + "' and t.password='" + password + "' and t.estado='A'";
try {
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery(sSQL);
while (rs.next()) {
registro[0] = rs.getString("idpersona");
registro[1] = rs.getString("Nombres");
registro[2] = rs.getString("P_apellido");
registro[3] = rs.getString("S_apellido");
registro[4] = rs.getString("acceso");
registro[5] = rs.getString("login");
registro[6] = rs.getString("password");
registro[7] = rs.getString("estado");
totalregistros = totalregistros + 1;
modelo.addRow(registro);
}
return modelo;
} catch (Exception e) {
JOptionPane.showConfirmDialog(null, e);
return null;
}
}
}
|
import java.util.*; //import this to create an ArrayList
public class commonJavaProgramming{
public static void main(String [] args){
//For loop
for(int a = 0; a< 1 ; a++){
System.out.println("Test One");
}
//While loop
int b = 0;
while (b < 1){
System.out.println("Test Two");
b++;
}
//Create a list (It can grow dynamically)
ArrayList<Integer> listOne=new ArrayList<Integer>();
listOne.add(1);
System.out.println(listOne);
//Create an array. Must print a specific index.
int [] listTwo = new int[2];
listTwo[0] = 1;
listTwo[1] = 2;
System.out.println(listTwo[0]);
//Iterate a list or an array
for(int x : listTwo){
System.out.println(x);
}
//Try Clause
int age = 19;
if(age < 18){
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else{
System.out.println("Access granted - You are old enough!");
}
//User input
Scanner inputValue = new Scanner(System.in);
System.out.println("Enter an string, then a integer: ");
String stringValue = inputValue.nextLine();
int value = inputValue.nextInt();
System.out.println("Your integer is: " + value + " Your string is: " + stringValue);
//Switch Statements
String day = "Tuesday";
switch(day){
case "Tuesday":
System.out.println("You entered Tuesday.");
break;
case "Wednesday":
System.out.println("You enter Wednesday.");
break;
}
}
}
|
package heylichen.problem;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
/**
* @author lichen
* @date 2020/10/22 10:16
* @desc post-order non-recursive
*/
public class PostOrderSerializer implements BinaryTreeSerializable {
private static Node<Integer> NOT_INITIALIZED = new Node<Integer>(-1000);
@Override
public String serialize(Node<Integer> node) {
Deque<Integer> list = new LinkedList<>();
Deque<Node<Integer>> stack = new LinkedList<>();
stack.push(node);
while (!stack.isEmpty()) {
Node<Integer> c = stack.pop();
if (c == null) {
list.push(null);
} else {
//to make left to be processed first
list.push(c.getData());
stack.push(c.getRight());
stack.push(c.getLeft());
}
}
return SerializeUtils.toString(list);
}
@Override
public Node<Integer> deserialize(String string) {
List<Integer> list = SerializeUtils.parse(string);
Deque<Node<Integer>> stack = new LinkedList<>();
Node<Integer> result = null;
for (int i = list.size() - 1; i >= 0; i--) {
Integer integer = list.get(i);
if (integer != null) {
Node<Integer> c = new Node<>(integer, NOT_INITIALIZED, NOT_INITIALIZED);
stack.push(c);
continue;
}
Node<Integer> existed = stack.pop();
boolean full = setRelation(existed, null);
while (full) {
if (stack.isEmpty()) {
result = existed;
break;
}
Node<Integer> p = stack.pop();
if (p == null) {
throw new IllegalStateException("not valid");
}
full = setRelation(p, existed);
existed = p;
}
stack.push(existed);
}
return result;
}
private static boolean setRelation(Node<Integer> existed, Node<Integer> c) {
if (existed.getLeft() == NOT_INITIALIZED) {
existed.setLeft(c);
return false;
} else if (existed.getRight() == NOT_INITIALIZED) {
existed.setRight(c);
}
return true;
}
}
|
package edu.palindrome.tran.don;
import edu.jenks.dist.palindrome.*;
public class PalindromeChecker extends AbstractPalindromeChecker
{
public static void main (String[] args) {
PalindromeChecker pc = new PalindromeChecker();
boolean act = pc.isPalindrome("%%");
System.out.println(act);
}
public boolean isPalindrome(String arg) {
arg = arg.replaceAll("[^A-Za-z_0-9]", "");
//System.out.println(yyes + "what");
if(arg.length() == 0) {
return false;
}
System.out.println(arg);
String firstHalf = "";
String firstHalfReal = "";
String secondHalfReal = "";
if(arg.length() % 2 == 0) {
firstHalf = arg.substring(0, arg.length() / 2);
firstHalfReal = firstHalf.toLowerCase();
} else {
firstHalf = arg.substring(0, (arg.length() / 2) + 1);
firstHalfReal = firstHalf.toLowerCase();
}
//System.out.println(firstHalf);
String secondHalf = "";
int halfLength = arg.length() / 2;
int length = arg.length();
for(int i = length - 1; i > halfLength - 1; i--) {
secondHalf += arg.charAt(i);
}
secondHalfReal = secondHalf.toLowerCase();
//System.out.println(secondHalf);
if(secondHalfReal.equals(firstHalfReal)) {
return true;
} else {
return false;
}
}
}
|
package by.academy.homework.homework2;
import java.util.Arrays;
import java.util.Scanner;
public class Task3 {
public static void main(String[] args) {
String[] array = new String[2];
boolean check = false;
Scanner str = new Scanner(System.in);
System.out.println("Введите 2 слова: ");
do {
for (int i = 0; i < 2; i++) {
array[i] = str.nextLine();
check = array[i].isBlank() || array[i].length() % 2 != 0;
if (check == true) {
System.out.println("Ввод слов некорректный. Повторите ввод");
break;
}
}
} while (check == true);
str.close();
String result = array[0].substring(0, array[0].length()/2) + array[1].substring(array[1].length()/2, array[1].length());
System.out.println(Arrays.toString(array));
System.out.println("Результат: " + result);
}
}
|
/**
* @author Dylan Ragaishis (Dylanrr)
*/
package hw4;
import java.util.Comparator;
import hw4.api.Die;
/**
* Comparator for ordering Die objects. Dice are ordered first by value;
* dice with the same value are ordered by their max value, and dice
* with the same value and the same max value are ordered by whether they are
* available, with available dice preceding non-available dice.
*/
public class DieComparator implements Comparator<Die>
{
/* ~Notes~ For compare method
Returning a -1 means left is first
Returning a 1 means right is first
Returning a 0 means they where equal (There is a chance that 0 could return if there is an error comparing the two die)
*/
/**
* {@inheritDoc}
*/
@Override
public int compare(Die left, Die right)
{
if(left.value() > right.value()) //Check: Left Larger
return 1;
else if(left.value() < right.value()) //Check: Right Larger
return -1;
else if (left.value() == right.value()) //If equal
if(left.maxValue() > right.maxValue()) //If equal Check: Left larger maxValue
return -1;
else if(left.maxValue() < right.maxValue()) //If equal Check: Right larger maxValue
return 1;
else if(left.maxValue() == right.maxValue()) //If equal and maxValue equal
if(left.isAvailable() && !right.isAvailable()) // Check left availability
return -1;
else if(!left.isAvailable() && right.isAvailable()) // Check Right availability
return 1;
else
return 0;
else
return 0;
else
return 0;
}
}
|
package ebay;
import model.*;
import vo.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.sql.*;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
public class BiddingStatus
{
ArrayList<BiddingStatusVo> bidhis = new ArrayList<BiddingStatusVo>();
public ArrayList<BiddingStatusVo> getBidhis()
{
return bidhis;
}
public void setBidhis(ArrayList<BiddingStatusVo> bidhis)
{
this.bidhis = bidhis;
}
public String execute()
{
Map session = ActionContext.getContext().getSession();
String username = session.get("username").toString();
BiddingStatusMo b = new BiddingStatusMo();
bidhis = b.gethistory(username);
return "success";
}
}
|
package com.example.ManHire.Repository;
import com.example.ManHire.Entity.Admin;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AdminRepository extends CrudRepository<Admin, Long>
{
Admin findByuserName(String name);
}
|
package com.cloudaping.cloudaping.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class KeyUtil {
public static synchronized String getUniqueKey(){
Random random=new Random();
Integer number=random.nextInt(900000)+100000;
return System.currentTimeMillis()+ String.valueOf(number);
}
public static synchronized String getOrderKey(){
Date date=new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = formatter.format(date);
Random random=new Random();
return dateString+random.nextInt(900000)+100000;
}
}
|
package com.example.aizat.shrifti;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import java.util.List;
/**
* Created by Aizat on 13.11.2017.
*/
public class Adapter extends RecyclerView.Adapter<Holder> {
private String [] photos;
private String [] name;
private ViewGroup viewGroup;
public Adapter(String [] photos, String [] name) {
this.photos = photos;
this.name = name;
}
@Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main,parent,false);
viewGroup = parent;
return new Holder(view);
}
@Override
public void onBindViewHolder(Holder holder, int position) {
Glide
.with(viewGroup.getContext())
.load(photos[position])
.transition(DrawableTransitionOptions.withCrossFade(1000))
.into(holder.imageView);
holder.textView.setText(name[position]);
}
@Override
public int getItemCount() {
return photos.length;
}
}
|
/*
* 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.innovaciones.reporte.service;
import com.innovaciones.reporte.dao.ReporteGenericoItemsDAO;
import com.innovaciones.reporte.model.ReporteGenericoItems;
import com.innovaciones.reporte.model.ReporteMantenimiento;
import com.innovaciones.reporte.util.Utilities;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import lombok.Setter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author pisama
*/
@Service
@ManagedBean(name = "reporteGenericoItemsService")
@ViewScoped
public class ReporteGenericoItemsServiceImpl extends Utilities implements ReporteGenericoItemsService, Serializable {
@Setter
private ReporteGenericoItemsDAO reporteGenericoItemsDAO;
@Override
@Transactional
public ReporteGenericoItems save(ReporteGenericoItems reporteGenericoItem) {
reporteGenericoItemsDAO.save(reporteGenericoItem);
return reporteGenericoItem;
}
@Override
@Transactional
public ReporteGenericoItems update(ReporteGenericoItems reporteGenericoItem) {
reporteGenericoItemsDAO.update(reporteGenericoItem);
return reporteGenericoItem;
}
@Override
@Transactional
public void eliminar(ReporteGenericoItems reporteGenericoItem) {
reporteGenericoItemsDAO.eliminar(reporteGenericoItem);
}
@Override
@Transactional
public List<ReporteMantenimiento> getReporteMantenimientoByReporteId(Integer id) {
return reporteGenericoItemsDAO.getReporteMantenimientoByReporteId(id);
}
}
|
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* User: dexctor
* Date: 12-12-10
* Time: 上午10:27
* To change this template use File | Settings | File Templates.
*/
public class HeapSort {
public static void sort(Comparable[] a)//貌似a[0]排不进去了
{
int N = a.length - 1;
for(int i = N / 2; i >= 1; --i)
sink(a, i, N);
StdOut.println(Arrays.toString(a));
for(int i = 1; i < a.length; ++i)
{
exch(a, 1, N--);
sink(a, 1, N);
}
}
public static void sink(Comparable[] a, int k, int N)
{
while(2 * k <= N)
{
int next = 2 * k;
if(next < N && less(a[next], a[next + 1])) next++;
if(!less(a[k], a[next])) break;
exch(a, k, next);
k = next;
}
}
private static boolean less(Comparable a, Comparable b)
{
return a.compareTo(b) < 0;
}
private static void exch(Comparable[] a, int i, int j)
{
Comparable tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public static void main(String[] args)
{
int N = StdIn.readInt();
Integer[] a = new Integer[N];
for(int i = 0; i < N; ++i)
a[i] = i;
StdRandom.shuffle(a);
StdOut.println(Arrays.toString(a));
sort(a);
StdOut.println(Arrays.toString(a));
}
}
|
package com.test;
import java.util.HashMap;
import java.util.Map;
/**
* Given four lists A, B, C, D of integer values,
* compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
* 给4个数组,计算A[i] + B[j] + C[k] + D[l] == 0,组合的个数
*
* To make problem a bit easier,
* all A, B, C, D have same length of N where 0 ≤ N ≤ 500. // 长度为 0-500之间
* All integers are in the range of -2^28 to 2^28 - 1 // 单个值在-2^28和2^28-1 之间
* and the result is guaranteed to be at most 2^31 - 1. // 4个值,结果不超过int的最大值
*
* 思路1:
* 1,逐个移动方案,可能会导致内容缺失,不可靠
*
* 思路2:
* 1,将两个数组AB、CD,合并。O(n^2)
* 2,利用Hash,找相反数。O(n^2)
*
* @author YLine
*
* 2019年10月26日 下午6:30:24
*/
public class SolutionA
{
public int fourSumCount(int[] A, int[] B, int[] C, int[] D)
{
Map<Integer, Integer> mapA = new HashMap<>();
Map<Integer, Integer> mapB = new HashMap<>();
buildHash(mapA, A, B);
buildHash(mapB, C, D);
int result = 0;
for (Integer key : mapA.keySet())
{
if (mapB.containsKey(-key))
{
result += (mapA.get(key) * mapB.get(-key));
}
}
return result;
}
private void buildHash(Map<Integer, Integer> map, int[] a, int[] b)
{
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < b.length; j++)
{
int key = a[i] + b[j];
Integer oldValue = map.get(key);
if (null == oldValue)
{
map.put(key, 1);
}
else
{
map.put(key, oldValue + 1);
}
}
}
}
}
|
package com.justcode.hxl.viewutil.recycleview_util.layoutmanager.flowdraglayoutmanager;
import android.support.annotation.IntDef;
public interface FlowDragLayoutConstant {
/**
* 设置每一行的对齐模式
*/
int TWO_SIDE = 0;
int LEFT = 1;
int RIGHT = 2;
int CENTER = 3;
@IntDef({TWO_SIDE, LEFT, RIGHT, CENTER})
@interface AlignMode {
}
}
|
package util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import model.ArrayDeRetorno;
import model.Localizacao;
public class RequisicaoWebService {
public ArrayDeRetorno request(String origem, String destino) throws IOException{
String url = this.criaUrl(origem,destino);
String jsonString = this.chamarWebService(url);
ParseWebService parse = new ParseWebService();
ArrayList<Localizacao> arrayLocalizacao = new ArrayList<Localizacao>();
arrayLocalizacao = parse.parseJson(jsonString);
ArrayDeRetorno arrayDeRetorno = new ArrayDeRetorno();
arrayDeRetorno.setArrayAPI1(arrayLocalizacao);
return arrayDeRetorno;
}
public String criaUrl(String origem, String destino) throws UnsupportedEncodingException {
// a string da url
String urlString = "http://maps.googleapis.com/maps/api/directions/json";
// os parametros a serem enviados
Properties parametrosDirecoes = new Properties();
parametrosDirecoes.setProperty("origin", URLEncoder.encode(origem, "UTF-8"));
parametrosDirecoes.setProperty("destination",URLEncoder.encode(destino, "UTF-8"));
parametrosDirecoes.setProperty("sensor","false");
// o iterador, para criar a URL
Iterator<?> i = parametrosDirecoes.keySet().iterator();
// o contador
int counter = 0;
// enquanto ainda existir parametros
while (i.hasNext()) {
// pega o nome
String name = (String) i.next();
// pega o valor
String value = parametrosDirecoes.getProperty(name);
// adiciona com um conector (? ou &)
// o primeiro é ?, depois são &
urlString += (++counter == 1 ? "?" : "&")
+ name
+ "="
+ value;
}
return urlString;
}
public String chamarWebService (String urlString) throws IOException{
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// seta o metodo
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
// seta a variavel para ler o resultado
connection.setDoInput(true);
connection.setDoOutput(true);
// conecta com a url destino
try {
connection.setRequestProperty("User-Agent", "Chrome/27.0.1453.110");
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
// abre a conexão pra input
BufferedReader br =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
// le ate o final
StringBuffer newData = new StringBuffer(10000);
String s = "";
while (null != ((s = br.readLine()))) {
newData.append(s);
}
br.close();
return new String(newData);
}
}
|
/*
* @(#) BaseTpstif.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.tpstif.base;
import com.esum.appframework.dmo.BaseDMO;
import com.esum.imsutil.common.CommonUtil;
/**
* This is an object that contains data related to the TPSTIF table.
* Do not modify this class because it will be overwritten if the configuration file
* related to this class is modified.
*
* @hibernate.class
* table="TPSTIF"
*/
public abstract class BaseTpstif extends BaseDMO {
public static String REF = "Tpstif";
public static String PROP_STI_INTID = "StiIntid";
public static String PROP_STI_SEGSEP = "StiSegsep";
public static String PROP_STI_COMMPSWD = "StiCommpswd";
public static String PROP_STI_STDID = "StiStdid";
public static String PROP_STI_RPSWD = "StiRpswd";
public static String PROP_STI_DECPNT = "StiDecpnt";
public static String PROP_STI_TPID = "StiTpid";
public static String PROP_STI_ACKRQST = "StiAckrqst";
public static String PROP_STI_RSVD3 = "StiRsvd3";
public static String PROP_STI_SVCDRNO = "StiSvcdrno";
public static String PROP_STI_INTERSID = "StiIntersid";
public static String PROP_STI_RELCHR = "StiRelchr";
public static String PROP_STI_ENCDSCHM = "StiEncdschm";
public static String PROP_STI_SECUQL = "StiSecuql";
public static String PROP_STI_FGIDQL = "StiFgidql";
public static String PROP_STI_INTERID = "StiInterid";
public static String PROP_STI_WHICHSTD = "StiWhichstd";
public static String PROP_STI_PRIORTY = "StiPriorty";
public static String PROP_STI_ELEMSEP = "StiElemsep";
public static String PROP_STI_COMPSEP = "StiCompsep";
public static String PROP_STI_FGID = "StiFgid";
public static String PROP_STI_INTIDQL = "StiIntidql";
public static String PROP_STI_COMAGRID = "StiComagrid";
public static String PROP_STI_RPSWDQL = "StiRpswdql";
public static String PROP_STI_TESTID = "StiTestid";
public static String PROP_STI_RSVD2 = "StiRsvd2";
public static String PROP_STI_REPSEP = "StiRepsep";
public static String PROP_STI_COMMID = "StiCommid";
public static String PROP_STI_AGNCODE = "StiAgncode";
public static String PROP_STI_SECUINFO = "StiSecuinfo";
public static String PROP_STI_SYNTXID = "StiSyntxid";
public static String PROP_STI_SYNTXVER = "StiSyntxver";
public static String PROP_STI_RAPPSWD = "StiRappswd";
public static String PROP_STI_ROUTADDR = "StiRoutaddr";
public static String PROP_STI_RSVD1 = "StiRsvd1";
public static String PROP_STI_AUTHQL = "StiAuthql";
public static String PROP_STI_AUTHINFO = "StiAuthinfo";
// constructors
public BaseTpstif () {
initialize();
}
/**
* Constructor for primary key
*/
public BaseTpstif (java.lang.String stiTpid) {
this.setStiTpid(stiTpid);
initialize();
}
/**
* Constructor for required fields
*/
public BaseTpstif (
java.lang.String stiTpid,
java.lang.String stiWhichstd) {
this.setStiTpid(stiTpid);
this.setStiWhichstd(stiWhichstd);
initialize();
}
protected void initialize () {
stiWhichstd = " ";
stiStdid = " ";
stiSyntxid = " ";
stiSyntxver = " ";
stiCompsep = " ";
stiElemsep = " ";
stiSegsep = " ";
stiRepsep = " ";
stiDecpnt = " ";
stiRelchr = " ";
stiIntid = " ";
stiIntidql = " ";
stiRoutaddr = " ";
stiRpswd = " ";
stiRpswdql = " ";
stiPriorty = " ";
stiAckrqst = " ";
stiComagrid = " ";
stiAuthql = " ";
stiAuthinfo = " ";
stiSecuql = " ";
stiSecuinfo = " ";
stiTestid = " ";
stiCommid = " ";
stiCommpswd = " ";
stiFgid = " ";
stiFgidql = " ";
stiRappswd = " ";
stiAgncode = " ";
stiSvcdrno = " ";
stiEncdschm = " ";
stiInterid = " ";
stiIntersid = " ";
stiRsvd1 = " ";
stiRsvd2 = " ";
stiRsvd3 = " ";
}
// primary key
protected java.lang.String stiTpid;
// fields
protected java.lang.String stiWhichstd;
protected java.lang.String stiStdid;
protected java.lang.String stiSyntxid;
protected java.lang.String stiSyntxver;
protected java.lang.String stiCompsep;
protected java.lang.String stiElemsep;
protected java.lang.String stiSegsep;
protected java.lang.String stiRepsep;
protected java.lang.String stiDecpnt;
protected java.lang.String stiRelchr;
protected java.lang.String stiIntid;
protected java.lang.String stiIntidql;
protected java.lang.String stiRoutaddr;
protected java.lang.String stiRpswd;
protected java.lang.String stiRpswdql;
protected java.lang.String stiPriorty;
protected java.lang.String stiAckrqst;
protected java.lang.String stiComagrid;
protected java.lang.String stiAuthql;
protected java.lang.String stiAuthinfo;
protected java.lang.String stiSecuql;
protected java.lang.String stiSecuinfo;
protected java.lang.String stiTestid;
protected java.lang.String stiCommid;
protected java.lang.String stiCommpswd;
protected java.lang.String stiFgid;
protected java.lang.String stiFgidql;
protected java.lang.String stiRappswd;
protected java.lang.String stiAgncode;
protected java.lang.String stiSvcdrno;
protected java.lang.String stiEncdschm;
protected java.lang.String stiInterid;
protected java.lang.String stiIntersid;
protected java.lang.String stiRsvd1;
protected java.lang.String stiRsvd2;
protected java.lang.String stiRsvd3;
/**
* Return the unique identifier of this class
* @hibernate.id
* column="STI_TPID"
*/
public java.lang.String getStiTpid () {
return stiTpid;
}
/**
* Set the unique identifier of this class
* @param stiTpid the new ID
*/
public void setStiTpid (java.lang.String stiTpid) {
if (stiTpid==null || stiTpid.length()==0)
this.stiTpid = " ";
else
this.stiTpid = CommonUtil.getStringTrim(stiTpid);
}
/**
* Return the value associated with the column: STI_WHICHSTD
*/
public java.lang.String getStiWhichstd () {
return stiWhichstd;
}
/**
* Set the value related to the column: STI_WHICHSTD
* @param stiWhichstd the STI_WHICHSTD value
*/
public void setStiWhichstd (java.lang.String stiWhichstd) {
if (stiWhichstd==null || stiWhichstd.length()==0)
this.stiWhichstd = " ";
else
this.stiWhichstd = CommonUtil.getStringTrim(stiWhichstd);
}
/**
* Return the value associated with the column: STI_STDID
*/
public java.lang.String getStiStdid () {
return stiStdid;
}
/**
* Set the value related to the column: STI_STDID
* @param stiStdid the STI_STDID value
*/
public void setStiStdid (java.lang.String stiStdid) {
if (stiStdid==null || stiStdid.length()==0)
this.stiStdid = " ";
else
this.stiStdid = CommonUtil.getStringTrim(stiStdid);
}
/**
* Return the value associated with the column: STI_SYNTXID
*/
public java.lang.String getStiSyntxid () {
return stiSyntxid;
}
/**
* Set the value related to the column: STI_SYNTXID
* @param stiSyntxid the STI_SYNTXID value
*/
public void setStiSyntxid (java.lang.String stiSyntxid) {
if (stiSyntxid==null || stiSyntxid.length()==0)
this.stiSyntxid = " ";
else
this.stiSyntxid = CommonUtil.getStringTrim(stiSyntxid);
}
/**
* Return the value associated with the column: STI_SYNTXVER
*/
public java.lang.String getStiSyntxver () {
return stiSyntxver;
}
/**
* Set the value related to the column: STI_SYNTXVER
* @param stiSyntxver the STI_SYNTXVER value
*/
public void setStiSyntxver (java.lang.String stiSyntxver) {
if (stiSyntxver==null || stiSyntxver.length()==0)
this.stiSyntxver = " ";
else
this.stiSyntxver = CommonUtil.getStringTrim(stiSyntxver);
}
/**
* Return the value associated with the column: STI_COMPSEP
*/
public java.lang.String getStiCompsep () {
return stiCompsep;
}
/**
* Set the value related to the column: STI_COMPSEP
* @param stiCompsep the STI_COMPSEP value
*/
public void setStiCompsep (java.lang.String stiCompsep) {
if (stiCompsep==null || stiCompsep.length()==0)
this.stiCompsep = " ";
else
this.stiCompsep = CommonUtil.getStringTrim(stiCompsep);
}
/**
* Return the value associated with the column: STI_ELEMSEP
*/
public java.lang.String getStiElemsep () {
return stiElemsep;
}
/**
* Set the value related to the column: STI_ELEMSEP
* @param stiElemsep the STI_ELEMSEP value
*/
public void setStiElemsep (java.lang.String stiElemsep) {
if (stiElemsep==null || stiElemsep.length()==0)
this.stiElemsep = " ";
else
this.stiElemsep = CommonUtil.getStringTrim(stiElemsep);
}
/**
* Return the value associated with the column: STI_SEGSEP
*/
public java.lang.String getStiSegsep () {
return stiSegsep;
}
/**
* Set the value related to the column: STI_SEGSEP
* @param stiSegsep the STI_SEGSEP value
*/
public void setStiSegsep (java.lang.String stiSegsep) {
if (stiSegsep==null || stiSegsep.length()==0)
this.stiSegsep = " ";
else
this.stiSegsep = CommonUtil.getStringTrim(stiSegsep);
}
/**
* Return the value associated with the column: STI_REPSEP
*/
public java.lang.String getStiRepsep () {
return stiRepsep;
}
/**
* Set the value related to the column: STI_REPSEP
* @param stiRepsep the STI_REPSEP value
*/
public void setStiRepsep (java.lang.String stiRepsep) {
if (stiRepsep==null || stiRepsep.length()==0)
this.stiRepsep = " ";
else
this.stiRepsep = CommonUtil.getStringTrim(stiRepsep);
}
/**
* Return the value associated with the column: STI_DECPNT
*/
public java.lang.String getStiDecpnt () {
return stiDecpnt;
}
/**
* Set the value related to the column: STI_DECPNT
* @param stiDecpnt the STI_DECPNT value
*/
public void setStiDecpnt (java.lang.String stiDecpnt) {
if (stiDecpnt==null || stiDecpnt.length()==0)
this.stiDecpnt = " ";
else
this.stiDecpnt = CommonUtil.getStringTrim(stiDecpnt);
}
/**
* Return the value associated with the column: STI_RELCHR
*/
public java.lang.String getStiRelchr () {
return stiRelchr;
}
/**
* Set the value related to the column: STI_RELCHR
* @param stiRelchr the STI_RELCHR value
*/
public void setStiRelchr (java.lang.String stiRelchr) {
if (stiRelchr==null || stiRelchr.length()==0)
this.stiRelchr = " ";
else
this.stiRelchr = CommonUtil.getStringTrim(stiRelchr);
}
/**
* Return the value associated with the column: STI_INTID
*/
public java.lang.String getStiIntid () {
return stiIntid;
}
/**
* Set the value related to the column: STI_INTID
* @param stiIntid the STI_INTID value
*/
public void setStiIntid (java.lang.String stiIntid) {
if (stiIntid==null || stiIntid.length()==0)
this.stiIntid = " ";
else
this.stiIntid = CommonUtil.getStringTrim(stiIntid);
}
/**
* Return the value associated with the column: STI_INTIDQL
*/
public java.lang.String getStiIntidql () {
return stiIntidql;
}
/**
* Set the value related to the column: STI_INTIDQL
* @param stiIntidql the STI_INTIDQL value
*/
public void setStiIntidql (java.lang.String stiIntidql) {
if (stiIntidql==null || stiIntidql.length()==0)
this.stiIntidql = " ";
else
this.stiIntidql = CommonUtil.getStringTrim(stiIntidql);
}
/**
* Return the value associated with the column: STI_ROUTADDR
*/
public java.lang.String getStiRoutaddr () {
return stiRoutaddr;
}
/**
* Set the value related to the column: STI_ROUTADDR
* @param stiRoutaddr the STI_ROUTADDR value
*/
public void setStiRoutaddr (java.lang.String stiRoutaddr) {
if (stiRoutaddr==null || stiRoutaddr.length()==0)
this.stiRoutaddr = " ";
else
this.stiRoutaddr = CommonUtil.getStringTrim(stiRoutaddr);
}
/**
* Return the value associated with the column: STI_RPSWD
*/
public java.lang.String getStiRpswd () {
return stiRpswd;
}
/**
* Set the value related to the column: STI_RPSWD
* @param stiRpswd the STI_RPSWD value
*/
public void setStiRpswd (java.lang.String stiRpswd) {
if (stiRpswd==null || stiRpswd.length()==0)
this.stiRpswd = " ";
else
this.stiRpswd = CommonUtil.getStringTrim(stiRpswd);
}
/**
* Return the value associated with the column: STI_RPSWDQL
*/
public java.lang.String getStiRpswdql () {
return stiRpswdql;
}
/**
* Set the value related to the column: STI_RPSWDQL
* @param stiRpswdql the STI_RPSWDQL value
*/
public void setStiRpswdql (java.lang.String stiRpswdql) {
if (stiRpswdql==null || stiRpswdql.length()==0)
this.stiRpswdql = " ";
else
this.stiRpswdql = CommonUtil.getStringTrim(stiRpswdql);
}
/**
* Return the value associated with the column: STI_PRIORTY
*/
public java.lang.String getStiPriorty () {
return stiPriorty;
}
/**
* Set the value related to the column: STI_PRIORTY
* @param stiPriorty the STI_PRIORTY value
*/
public void setStiPriorty (java.lang.String stiPriorty) {
if (stiPriorty==null || stiPriorty.length()==0)
this.stiPriorty = " ";
else
this.stiPriorty = CommonUtil.getStringTrim(stiPriorty);
}
/**
* Return the value associated with the column: STI_ACKRQST
*/
public java.lang.String getStiAckrqst () {
return stiAckrqst;
}
/**
* Set the value related to the column: STI_ACKRQST
* @param stiAckrqst the STI_ACKRQST value
*/
public void setStiAckrqst (java.lang.String stiAckrqst) {
if (stiAckrqst==null || stiAckrqst.length()==0)
this.stiAckrqst = " ";
else
this.stiAckrqst = CommonUtil.getStringTrim(stiAckrqst);
}
/**
* Return the value associated with the column: STI_COMAGRID
*/
public java.lang.String getStiComagrid () {
return stiComagrid;
}
/**
* Set the value related to the column: STI_COMAGRID
* @param stiComagrid the STI_COMAGRID value
*/
public void setStiComagrid (java.lang.String stiComagrid) {
if (stiComagrid==null || stiComagrid.length()==0)
this.stiComagrid = " ";
else
this.stiComagrid = CommonUtil.getStringTrim(stiComagrid);
}
/**
* Return the value associated with the column: STI_AUTHQL
*/
public java.lang.String getStiAuthql () {
return stiAuthql;
}
/**
* Set the value related to the column: STI_AUTHQL
* @param stiAuthql the STI_AUTHQL value
*/
public void setStiAuthql (java.lang.String stiAuthql) {
if (stiAuthql==null || stiAuthql.length()==0)
this.stiAuthql = " ";
else
this.stiAuthql = CommonUtil.getStringTrim(stiAuthql);
}
/**
* Return the value associated with the column: STI_AUTHINFO
*/
public java.lang.String getStiAuthinfo () {
return stiAuthinfo;
}
/**
* Set the value related to the column: STI_AUTHINFO
* @param stiAuthinfo the STI_AUTHINFO value
*/
public void setStiAuthinfo (java.lang.String stiAuthinfo) {
if (stiAuthinfo==null || stiAuthinfo.length()==0)
this.stiAuthinfo = " ";
else
this.stiAuthinfo = CommonUtil.getStringTrim(stiAuthinfo);
}
/**
* Return the value associated with the column: STI_SECUQL
*/
public java.lang.String getStiSecuql () {
return stiSecuql;
}
/**
* Set the value related to the column: STI_SECUQL
* @param stiSecuql the STI_SECUQL value
*/
public void setStiSecuql (java.lang.String stiSecuql) {
if (stiSecuql==null || stiSecuql.length()==0)
this.stiSecuql = " ";
else
this.stiSecuql = CommonUtil.getStringTrim(stiSecuql);
}
/**
* Return the value associated with the column: STI_SECUINFO
*/
public java.lang.String getStiSecuinfo () {
return stiSecuinfo;
}
/**
* Set the value related to the column: STI_SECUINFO
* @param stiSecuinfo the STI_SECUINFO value
*/
public void setStiSecuinfo (java.lang.String stiSecuinfo) {
if (stiSecuinfo==null || stiSecuinfo.length()==0)
this.stiSecuinfo = " ";
else
this.stiSecuinfo = CommonUtil.getStringTrim(stiSecuinfo);
}
/**
* Return the value associated with the column: STI_TESTID
*/
public java.lang.String getStiTestid () {
return stiTestid;
}
/**
* Set the value related to the column: STI_TESTID
* @param stiTestid the STI_TESTID value
*/
public void setStiTestid (java.lang.String stiTestid) {
if (stiTestid==null || stiTestid.length()==0)
this.stiTestid = " ";
else
this.stiTestid = CommonUtil.getStringTrim(stiTestid);
}
/**
* Return the value associated with the column: STI_COMMID
*/
public java.lang.String getStiCommid () {
return stiCommid;
}
/**
* Set the value related to the column: STI_COMMID
* @param stiCommid the STI_COMMID value
*/
public void setStiCommid (java.lang.String stiCommid) {
if (stiCommid==null || stiCommid.length()==0)
this.stiCommid = " ";
else
this.stiCommid = CommonUtil.getStringTrim(stiCommid);
}
/**
* Return the value associated with the column: STI_COMMPSWD
*/
public java.lang.String getStiCommpswd () {
return stiCommpswd;
}
/**
* Set the value related to the column: STI_COMMPSWD
* @param stiCommpswd the STI_COMMPSWD value
*/
public void setStiCommpswd (java.lang.String stiCommpswd) {
if (stiCommpswd==null || stiCommpswd.length()==0)
this.stiCommpswd = " ";
else
this.stiCommpswd = CommonUtil.getStringTrim(stiCommpswd);
}
/**
* Return the value associated with the column: STI_FGID
*/
public java.lang.String getStiFgid () {
return stiFgid;
}
/**
* Set the value related to the column: STI_FGID
* @param stiFgid the STI_FGID value
*/
public void setStiFgid (java.lang.String stiFgid) {
if (stiFgid==null || stiFgid.length()==0)
this.stiFgid = " ";
else
this.stiFgid = CommonUtil.getStringTrim(stiFgid);
}
/**
* Return the value associated with the column: STI_FGIDQL
*/
public java.lang.String getStiFgidql () {
return stiFgidql;
}
/**
* Set the value related to the column: STI_FGIDQL
* @param stiFgidql the STI_FGIDQL value
*/
public void setStiFgidql (java.lang.String stiFgidql) {
if (stiFgidql==null || stiFgidql.length()==0)
this.stiFgidql = " ";
else
this.stiFgidql = CommonUtil.getStringTrim(stiFgidql);
}
/**
* Return the value associated with the column: STI_RAPPSWD
*/
public java.lang.String getStiRappswd () {
return stiRappswd;
}
/**
* Set the value related to the column: STI_RAPPSWD
* @param stiRappswd the STI_RAPPSWD value
*/
public void setStiRappswd (java.lang.String stiRappswd) {
if (stiRappswd==null || stiRappswd.length()==0)
this.stiRappswd = " ";
else
this.stiRappswd = CommonUtil.getStringTrim(stiRappswd);
}
/**
* Return the value associated with the column: STI_AGNCODE
*/
public java.lang.String getStiAgncode () {
return stiAgncode;
}
/**
* Set the value related to the column: STI_AGNCODE
* @param stiAgncode the STI_AGNCODE value
*/
public void setStiAgncode (java.lang.String stiAgncode) {
if (stiAgncode==null || stiAgncode.length()==0)
this.stiAgncode = " ";
else
this.stiAgncode = CommonUtil.getStringTrim(stiAgncode);
}
/**
* Return the value associated with the column: STI_SVCDRNO
*/
public java.lang.String getStiSvcdrno () {
return stiSvcdrno;
}
/**
* Set the value related to the column: STI_SVCDRNO
* @param stiSvcdrno the STI_SVCDRNO value
*/
public void setStiSvcdrno (java.lang.String stiSvcdrno) {
if (stiSvcdrno==null || stiSvcdrno.length()==0)
this.stiSvcdrno = " ";
else
this.stiSvcdrno = CommonUtil.getStringTrim(stiSvcdrno);
}
/**
* Return the value associated with the column: STI_ENCDSCHM
*/
public java.lang.String getStiEncdschm () {
return stiEncdschm;
}
/**
* Set the value related to the column: STI_ENCDSCHM
* @param stiEncdschm the STI_ENCDSCHM value
*/
public void setStiEncdschm (java.lang.String stiEncdschm) {
if (stiEncdschm==null || stiEncdschm.length()==0)
this.stiEncdschm = " ";
else
this.stiEncdschm = CommonUtil.getStringTrim(stiEncdschm);
}
/**
* Return the value associated with the column: STI_INTERID
*/
public java.lang.String getStiInterid () {
return stiInterid;
}
/**
* Set the value related to the column: STI_INTERID
* @param stiInterid the STI_INTERID value
*/
public void setStiInterid (java.lang.String stiInterid) {
if (stiInterid==null || stiInterid.length()==0)
this.stiInterid = " ";
else
this.stiInterid = CommonUtil.getStringTrim(stiInterid);
}
/**
* Return the value associated with the column: STI_INTERSID
*/
public java.lang.String getStiIntersid () {
return stiIntersid;
}
/**
* Set the value related to the column: STI_INTERSID
* @param stiIntersid the STI_INTERSID value
*/
public void setStiIntersid (java.lang.String stiIntersid) {
if (stiIntersid==null || stiIntersid.length()==0)
this.stiIntersid = " ";
else
this.stiIntersid = CommonUtil.getStringTrim(stiIntersid);
}
/**
* Return the value associated with the column: STI_RSVD1
*/
public java.lang.String getStiRsvd1 () {
return stiRsvd1;
}
/**
* Set the value related to the column: STI_RSVD1
* @param stiRsvd1 the STI_RSVD1 value
*/
public void setStiRsvd1 (java.lang.String stiRsvd1) {
if (stiRsvd1==null || stiRsvd1.length()==0)
this.stiRsvd1 = " ";
else
this.stiRsvd1 = CommonUtil.getStringTrim(stiRsvd1);
}
/**
* Return the value associated with the column: STI_RSVD2
*/
public java.lang.String getStiRsvd2 () {
return stiRsvd2;
}
/**
* Set the value related to the column: STI_RSVD2
* @param stiRsvd2 the STI_RSVD2 value
*/
public void setStiRsvd2 (java.lang.String stiRsvd2) {
if (stiRsvd2==null || stiRsvd2.length()==0)
this.stiRsvd2 = " ";
else
this.stiRsvd2 = CommonUtil.getStringTrim(stiRsvd2);
}
/**
* Return the value associated with the column: STI_RSVD3
*/
public java.lang.String getStiRsvd3 () {
return stiRsvd3;
}
/**
* Set the value related to the column: STI_RSVD3
* @param stiRsvd3 the STI_RSVD3 value
*/
public void setStiRsvd3 (java.lang.String stiRsvd3) {
if (stiRsvd3==null || stiRsvd3.length()==0)
this.stiRsvd3 = " ";
else
this.stiRsvd3 = CommonUtil.getStringTrim(stiRsvd3);
}
}
|
/*
* Copyright (C) 2018 Instituto Nacional de Telecomunicações
*
* All rights are reserved. Reproduction in whole or part is
* prohibited without the written consent of the copyright owner.
*
*/
package inatel.br.nfccontrol.di.module;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import inatel.br.nfccontrol.BuildConfig;
import inatel.br.nfccontrol.di.qualifier.RetrofitQualifier;
import inatel.br.nfccontrol.network.HeaderInterceptor;
import inatel.br.nfccontrol.network.ResponseInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* {@link Module} containing classes needed to do network operations.
*
* @author Daniela Mara Silva <danielamara@inatel.br>
* @since 30/01/2018.
*/
@Module
public class NetworkModule {
@RetrofitQualifier
@Provides
@Singleton
Retrofit providesRetrofitAdapter() {
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new HeaderInterceptor())
.addInterceptor(new ResponseInterceptor())
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
return new Retrofit.Builder()
.baseUrl(BuildConfig.API_ENDPOINT)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
}
|
package com.human.ex;
public class quiz0228_12 {
public static void main(String[] args) {
//제일 큰 수 출력하기
java.util.Scanner sc = new java.util.Scanner(System.in);
int a = Integer.parseInt(sc.nextLine());
int b = Integer.parseInt(sc.nextLine());
int c = Integer.parseInt(sc.nextLine());
if(a>b) {
if(a>c) {
System.out.println(a);
}else {
System.out.println(c);
}
}else if(b>c) {
System.out.println(b);
}else {
System.out.println(c);
}
sc.close();
}
}
|
package com.thoughtworks.ketsu.domain.users;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.thoughtworks.ketsu.infrastructure.records.Record;
import com.thoughtworks.ketsu.web.jersey.Routes;
import java.util.HashMap;
import java.util.Map;
public class OrderItem implements Record {
@JsonProperty("product_id")
String prodId;
int quantity;
double amount;
@Override
public Map<String, Object> toRefJson(Routes routes) {
return new HashMap() {{
put("uri", routes.productUrl(prodId));
put("product_id", prodId);
put("quantity", quantity);
put("amount", amount);
}};
}
@Override
public Map<String, Object> toJson(Routes routes) {
return toRefJson(routes);
}
}
|
package mf0227.uf2404.actividad3;
import java.util.Comparator;
public class LibroComparatorPaginas implements Comparator<Libro>{
@Override
public int compare(Libro o1, Libro o2) {
return o1.getNumeroPaginas() - o2.getNumeroPaginas();
}
}
|
package com.debugger.car.web;
import java.util.NoSuchElementException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.debugger.car.domain.CarClient;
import com.debugger.car.domain.Reservation;
import com.debugger.car.dto.CarClientDto;
import com.debugger.car.repository.ClientsRepository;
import com.debugger.car.repository.ReservationRepository;
import com.debugger.car.service.CarClientService;
@RestController
@RequestMapping
public class CarClientController {
private ClientsRepository clientsRepository;
public CarClientController(ClientsRepository clientsRepository) {
super();
this.clientsRepository = clientsRepository;
}
@GetMapping("/clients")
public Iterable<CarClient> getAllCarClients() {
return this.clientsRepository.findAll();
}
// improve this with custom exception
@GetMapping("/clients/{id}")
public ResponseEntity<CarClient> getClientById(@PathVariable(value = "id") Long ClientID) throws Exception {
CarClient carClient = clientsRepository.findById(ClientID)
.orElseThrow(() -> new Exception("client for this id " + ClientID + " not found "));
return ResponseEntity.ok().body(carClient);
}
@PostMapping("/clients")
public CarClient createClient(@RequestBody CarClient clients) {
return clientsRepository.save(clients);
}
@PutMapping("/employees/{id}")
CarClient replaceClient(@RequestBody CarClient newCarClient, @PathVariable Long clientId) {
return clientsRepository.findById(clientId)
.map(clients -> {
clients.setClientID(newCarClient.getClientID());
clients.setFirstName(newCarClient.getFirstName());
clients.setLastName(newCarClient.getLastName());
clients.setEmailAddress(newCarClient.getEmailAddress());
clients.setMobileNumber(newCarClient.getMobileNumber());
return clientsRepository.save(newCarClient);
})
.orElseGet(() -> {
newCarClient.setClientID(clientId);
return clientsRepository.save(newCarClient);
});
}
@DeleteMapping("/clients/{clientId}")
void deleteClient(@PathVariable Long clientId) {
clientsRepository.deleteById(clientId);
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoSuchElementException.class)
public String return400(NoSuchElementException ex) {
return ex.getMessage();
}
}
|
package com.lenovohit.hcp.base.web.rest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.lenovohit.core.dao.Page;
import com.lenovohit.core.exception.BaseException;
import com.lenovohit.core.manager.GenericManager;
import com.lenovohit.core.utils.JSONUtils;
import com.lenovohit.core.utils.StringUtils;
import com.lenovohit.core.web.MediaTypes;
import com.lenovohit.core.web.utils.Result;
import com.lenovohit.core.web.utils.ResultUtils;
import com.lenovohit.hcp.base.model.Department;
import com.lenovohit.hcp.base.utils.PinyinUtil;
import com.lenovohit.hcp.base.utils.WubiUtil;
/**
* 医院基本信息管理
*/
@RestController
@RequestMapping("/hcp/base/dept")
public class DepartmentRestController extends HcpBaseRestController {
@Autowired
private GenericManager<Department, String> departmentManager;
//获取专科菜单
@RequestMapping(value = "/deptlist", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forDeptList() {
String hosId = this.getCurrentUser().getHosId() ;
List<Department> Depts = departmentManager.find(" from Department dept where hosId = ? order by deptId ",hosId);
return ResultUtils.renderSuccessResult(Depts);
}
@RequestMapping(value = "/info/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forInfo(@PathVariable("id") String id){
Department model= departmentManager.get(id);
System.out.print(model);
return ResultUtils.renderSuccessResult(model);
}
@RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forList(@RequestParam(value = "data", defaultValue = "") String data) {
JSONObject jsonObj = JSONObject.parseObject(data);
String hosId = jsonObj.getString("hosId");
List<Department> models = departmentManager.find(" from Department dept where hosId = ?",StringUtils.isEmpty(hosId)?this.getCurrentUser().getHosId():hosId);
return ResultUtils.renderSuccessResult(models);
}
//新建科室
@RequestMapping(value="/create",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8/*TEXT_PLAIN_UTF_8*/)
public Result forCreate(@RequestBody String data){
Department model = JSONUtils.deserialize(data, Department.class);
/*if(model.getHosId() == null)
model.setHosId(hosId);*/
if(model.getSpellCode()== null)
model.setSpellCode(PinyinUtil.getFirstSpell(model.getDeptName()));
if(model.getWbCode()== null)
model.setWbCode(WubiUtil.getWBCode(model.getDeptName()));
//getWBCode
model.setStopFlag("1");
//TODO 校验
List<Department> Depts = departmentManager.find(" from Department dept where deptName = ?",model.getDeptName());
if(Depts.size()!=0){
return ResultUtils.renderFailureResult("科室名称已存在,请重新输入");
}
else{
Department saved = this.departmentManager.save(model);
return ResultUtils.renderSuccessResult(saved);
}
}
//更新科室信息
@RequestMapping(value = "/update", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forUpdate(@RequestBody String data) {
Department model = JSONUtils.deserialize(data, Department.class);
if(model==null || StringUtils.isBlank(model.getId())){
return ResultUtils.renderFailureResult("不存在此对象");
}
this.departmentManager.save(model);
return ResultUtils.renderSuccessResult();
}
//删除某个科室信息
@RequestMapping(value = "/remove/{id}",method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
public Result forDelete(@PathVariable("id") String id){
try {
this.departmentManager.delete(id);
} catch (Exception e) {
throw new BaseException("删除失败");
}
return ResultUtils.renderSuccessResult();
}
//删除选中的科室信息
@RequestMapping(value = "/removeAll",method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
public Result forDeleteAll(@RequestBody String data){
@SuppressWarnings("rawtypes")
List ids = JSONUtils.deserialize(data, List.class);
StringBuilder idSql = new StringBuilder();
List<String> idvalues = new ArrayList<String>();
try {
idSql.append("DELETE FROM B_deptinfo WHERE ID IN (");
for(int i=0;i<ids.size();i++){
idSql.append("?");
idvalues.add(ids.get(i).toString());
if(i != ids.size()-1)idSql.append(",");
}
idSql.append(")");
System.out.println(idSql.toString());
this.departmentManager.executeSql(idSql.toString(), idvalues.toArray());
} catch (Exception e) {
e.printStackTrace();
throw new BaseException("删除失败");
}
return ResultUtils.renderSuccessResult();
}
/**
* 传入多个科室id查询科室信息
*
* @param data
* @return
*/
@RequestMapping(value = "/findByIds", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forFindByIds(@RequestBody String data) {
@SuppressWarnings("rawtypes")
List ids = JSONUtils.deserialize(data, List.class);
StringBuilder idSql = new StringBuilder();
List<String> idvalues = new ArrayList<String>();
try {
idSql.append(" from Department dept where where id in (");
for (int i = 0; i < ids.size(); i++) {
idSql.append("?");
idvalues.add(ids.get(i).toString());
if (i != ids.size() - 1)
idSql.append(",");
}
idSql.append(")");
System.out.println(idSql.toString());
List<Department> Depts = departmentManager.find(idSql.toString());
return ResultUtils.renderSuccessResult(Depts);
} catch (Exception e) {
e.printStackTrace();
throw new BaseException("查询失败");
}
}
@RequestMapping(value = "/listByDeptType", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forListByDeptType(@RequestParam(value = "data", defaultValue = "") String data) {
@SuppressWarnings("rawtypes")
List ids = JSONUtils.deserialize(data, List.class);
StringBuilder idSql = new StringBuilder();
List<String> idValues = new ArrayList<String>();
String hosId = this.getCurrentUser().getHosId();
idValues.add(hosId);
idSql.append("SELECT dept from Department dept WHERE hosId = ? and deptType IN (");
for(int i=0;i<ids.size();i++){
idSql.append("?");
idValues.add(ids.get(i).toString());
if(i != ids.size()-1)idSql.append(",");
}
idSql.append(") order by deptId");
System.out.println(idValues);
List<Department> models = departmentManager.find(idSql.toString(), idValues.toArray());
return ResultUtils.renderSuccessResult(models);
}
@RequestMapping(value = "/listByDeptIsRegDept", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forListByDeptIsRegDept(@RequestParam(value = "data", defaultValue = "") String data) {
@SuppressWarnings("rawtypes")
Department model = JSONUtils.deserialize(data, Department.class);
StringBuilder jql = new StringBuilder();
List<String> values = new ArrayList<String>();
jql.append("SELECT dept from Department dept WHERE 1=1");
if(StringUtils.isNotBlank(model.getIsRegdept())){
jql.append(" and dept.isRegdept = ? ");
values.add(model.getIsRegdept());
}
jql.append(" and dept.hosId = ? ");
values.add(this.getCurrentUser().getHosId());
jql.append(" order by deptId ");
System.out.println(values);
List<Department> models = departmentManager.find(jql.toString(), values.toArray());
return ResultUtils.renderSuccessResult(models);
}
public String ObjectIsNull(Object obj) {
if (obj == null)
return "";
return obj.toString();
}
}
|
package com.chandlerobaker.alcchallenge.android.journalapp;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.chandlerobaker.alcchallenge.android.journalapp.database.User;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Objects;
import static com.chandlerobaker.alcchallenge.android.journalapp.MainActivity.PREF_APP;
public class SignInActivity extends AppCompatActivity {
private GoogleSignInClient mGoogleSignInClient;
private static final String TAG = SignInActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 9001;
private DatabaseReference mDatabaseReferenceUsers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mDatabaseReferenceUsers = FirebaseDatabase.getInstance().getReference(getResources().getText(R.string.firebase_db_users).toString());
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
if(extras.getBoolean("SIGN_OUT", false)){
signOut();
}
}
}
@Override
protected void onStart() {
super.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if(account != null){
updatePreferences(account);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
else {
updateUI();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void updateUI() {
SignInButton mSignInButton = (SignInButton) findViewById(R.id.button_signIn);
mSignInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_signIn:
signIn();
break;
}
}
});
mSignInButton.setSize(SignInButton.SIZE_STANDARD);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void updatePreferences(GoogleSignInAccount account) {
if(account != null) {
User user = new User(account.getId(), account.getDisplayName(), account.getEmail());
mDatabaseReferenceUsers.child(Objects.requireNonNull(account.getId())).setValue(user);
SharedPreferences sharedPreferences = getSharedPreferences(PREF_APP, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("USER_ACCOUNT_ID", account.getId());
editor.putString("USER_ACCOUNT_EMAIL", account.getEmail());
editor.putString("USER_ACCOUNT_NAME", account.getDisplayName());
editor.apply();
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// Signed in successfully, show authenticated UI.
updatePreferences(account);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
Toast.makeText(this, getResources().getText(R.string.success_sign_in_message).toString(), Toast.LENGTH_SHORT).show();
finish();
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
updatePreferences(null);
}
}
private void signOut(){
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// ...
}
});
}
}
|
package maxPathSum124;
import dataStructure.TreeNode;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null)
return 0;
if (root.left == null && root.right == null)
return root.val;
dfs(root);
return max;
}
private int dfs(TreeNode node) {
if (node == null)
return 0;
//左右子树和为负则置为0, 表示最大路径不包含子树
int left = Math.max(0, dfs(node.left));
int right = Math.max(0 , dfs(node.right));
//最大路径包含左右两子树
max = Math.max(node.val + left + right, max);
//最大路径包含一子树
return (right > left ? right : left) + node.val;
}
}
|
package com.pwc.sort.test;
import com.pwc.sort.ExternalSorting;
import com.pwc.test.TestBase;
import com.pwc.util.BinaryObject;
import static junit.framework.Assert.assertEquals;
public class ExternalSortingTest extends TestBase {
// @Test
public void testSort() throws Exception {
final int from = 0;
final int to = 1024 * 1024 * 10 - 1;
final String source = "external_sorting_test";
BinaryObject.generateOrderNumber(from, to, source);
gc.add(source);
ExternalSorting externalSorting = new ExternalSorting(source);
String out = externalSorting.sort();
gc.add(out);
int[] a = BinaryObject.loadAsIntArray(out);
for (int i = from; i <= to; i++) {
assertEquals(i, a[i]);
}
}
}
|
/**
* _31_NextPermutation
*/
public class _31_NextPermutation {
public void nextPermutation(int[] nums) {
int i = nums.length - 1;
while (i > 0) {
if (nums[i] > nums[i - 1])
break;
i--;
}
for (int k = nums.length - 1; k >= i && i != 0; --k) {
if (nums[k] > nums[i - 1]) {
int tmp = nums[i - 1];
nums[i - 1] = nums[k];
nums[k] = tmp;
break;
}
}
Arrays.sort(nums, i, nums.length);
}
}
|
package com.company;
public class Fier extends Metal {
boolean prelucrat;
int cantitate;
public Fier(int anAparitie, boolean calitate, String nume, boolean esteScump, boolean esteRar, boolean prelucrat, int cantitate) {
super(anAparitie, calitate, nume, esteScump, esteRar);
this.prelucrat = prelucrat;
this.cantitate = cantitate;
}
void showFier() {
System.out.println("Este/nu este prelucrat: " + prelucrat);
System.out.println("Cantitate: " + cantitate);
}
}
|
package maze.logic;
import java.util.Random;
public class Dragon extends Piece{
private static final int UP = 0;
private static final int DOWN = 1;
private static final int LEFT = 2;
private static final int RIGHT = 3;
private static final int STAY = 4;
private enum State{
AWAKE, ASLEEP, DEAD
}
private State state;
public Dragon(int x, int y){
super(x,y,'D');
state = State.AWAKE;
}
public Dragon(){
super(1,3,'D');
state = State.AWAKE;
}
public void kill(){
state = State.DEAD;
symbol = ' ';
}
public void wakeUp(){
state = State.AWAKE;
symbol = 'D';
}
public void fallAsleep(){
state = State.ASLEEP;
symbol = 'd';
}
public int update(Mode mode){
Random r = new Random();
boolean change = r.nextBoolean();
if(state != State.DEAD & mode != Mode.STILL){
if(change & mode == Mode.SLEEP){
if(state == State.ASLEEP)
wakeUp();
else
fallAsleep();
}
else
if(state == State.AWAKE)
return move();
}
return STAY;
}
public int move(){
Random r = new Random();
int dir = r.nextInt(4);
switch(dir){
case UP:
posY--;
break;
case DOWN:
posY++;
break;
case RIGHT:
posX++;
break;
case LEFT:
posX--;
}
return dir;
}
public void undoMove(int dir){
switch(dir){
case DOWN:
posY--;
break;
case UP:
posY++;
break;
case LEFT:
posX++;
break;
case RIGHT:
posX--;
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vootoo.search;
import java.util.Map;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.search.QParser;
import org.apache.solr.search.QParserPlugin;
/**
* CollectorFilter ({@link org.apache.solr.search.PostFilter}). create {@link CollectorFilterQuery}(not use query cache)
* <p/>
* add solrconfig.xml<br/>
* <code><queryParser name="cf" class="org.vootoo.search.CollectorFilterQParserPlugin"/></code><p/>
* example:<p/>
* <code>fq={!cf name=in}status:(-1, 2)</code><br/>
* <code>fq={!cf name=in not=true}status:(3,4)</code><br/>
* <code>fq={!cf name=range}price:[100 TO 500]</code><br/>
* <code>fq={!cf name=range}log(page_view):[50 TO 120]</code><br/>
* <code>fq={!cf name=range}geodist():[* TO 5]</code><br/>
* <code>fq={!cf name=bit}bit_field:(0b01100)</code><br/>
* <code>fq={!cf name=bit}bit_field:(0xa)</code><br/>
* <code>fq={!cf name=bit}bit_field:(3)</code><br/>
* <code>fq={!cf name=cbit}bit_field:(0b01100)</code><br/>
*/
public class CollectorFilterQParserPlugin extends QParserPlugin {
public static final String NAME = "cf";
protected Map<String,CollectorFilterablePlugin> customPlugins = null;
@SuppressWarnings("rawtypes")
@Override
public void init(NamedList args) {
// TODO init custom CollectorFilterablePlugins
}
@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
return new CollectorFilterQParser(qstr, localParams, params, req,
customPlugins);
}
}
|
package com.roundarch.repository.impl;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Repository;
import com.annconia.api.repository.AfterSaveEvent;
import com.annconia.api.repository.BeforeSaveEvent;
import com.annconia.api.repository.RepositoryEvent;
import com.roundarch.entity.RecruitEntity;
import com.roundarch.repository.ActivityRepositoryExtension;
@Repository("activityRepository")
public class ActivityRepositoryImpl implements ActivityRepositoryExtension, ApplicationListener<RepositoryEvent> {
public final void onApplicationEvent(RepositoryEvent event) {
if (!(event.getSource() instanceof RecruitEntity)) {
return;
}
RecruitEntity entity = (RecruitEntity) event.getSource();
if (event instanceof BeforeSaveEvent) {
onBeforeSave(entity);
} else if (event instanceof AfterSaveEvent) {
}
}
/**
* Override this method if you are interested in {@literal beforeSave} events.
*
* @param entity
*/
protected void onBeforeSave(RecruitEntity entity) {
}
}
|
package com.jd.myadapterlib;
import android.animation.Animator;
import android.content.Context;
import android.support.annotation.IntDef;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.jd.myadapterlib.animation.AlphaInAnimation;
import com.jd.myadapterlib.animation.BaseAnimation;
import com.jd.myadapterlib.animation.ScaleInAnimation;
import com.jd.myadapterlib.animation.SlideInBottomAnimation;
import com.jd.myadapterlib.animation.SlideInLeftAnimation;
import com.jd.myadapterlib.animation.SlideInRightAnimation;
import com.jd.myadapterlib.delegate.ItemViewDelegate;
import com.jd.myadapterlib.delegate.ItemViewDelegateManager;
import com.jd.myadapterlib.delegate.RecyViewHolder;
import com.jd.myadapterlib.dinterface.DOnItemChildClickListener;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.List;
/**
* Auther: Jarvis Dong
* Time: on 2016/12/16 0016 56
* Name:
* OverView: 基准适配器
* Usage: for recyclerview
*/
public class RecyMultiItemTypeAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
protected Context mContext;
protected List<T> mDatas;
protected ItemViewDelegateManager mItemViewDelegateManager;//代理管理类;
protected OnItemClickListener mOnItemClickListener;//View的点击
protected DOnItemChildClickListener mOnItemChildClickListener;//子VIew的点击;
public interface OnItemClickListener {
void onItemClick(View view, RecyclerView.ViewHolder holder, int position);
boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.mOnItemClickListener = onItemClickListener;
}
public void setOnItemChildClickListener(DOnItemChildClickListener onItemChildClickListener) {
this.mOnItemChildClickListener = onItemChildClickListener;
}
public RecyMultiItemTypeAdapter(Context context, List<T> datas) {
mContext = context;
mDatas = datas;
mItemViewDelegateManager = new ItemViewDelegateManager();
}
public RecyMultiItemTypeAdapter(Context context) {
mContext = context;
mItemViewDelegateManager = new ItemViewDelegateManager();
}
@Override
public int getItemViewType(int position) {
if (!useItemViewDelegateManager()) return super.getItemViewType(position);
return mItemViewDelegateManager.getItemViewType(mDatas.get(position), position);
}
protected boolean useItemViewDelegateManager() {
return mItemViewDelegateManager.getItemViewDelegateCount() > 0;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemViewDelegate itemViewDelegate = mItemViewDelegateManager.getItemViewDelegate(viewType);
int layoutId = itemViewDelegate.getItemViewLayoutId();
RecyViewHolder holder = RecyViewHolder.createViewHolder(mContext, parent, layoutId);
onViewHolderCreated(holder, holder.getConvertView());
setListener(parent, holder, viewType);
return holder;
}
public void onViewHolderCreated(RecyclerView.ViewHolder holder, View itemView) {
}
public void convert(RecyclerView.ViewHolder holder, T t) {
mItemViewDelegateManager.convert(holder, t, holder.getAdapterPosition());
}
protected boolean isEnabled(int viewType) {
return true;
}
protected void setListener(final ViewGroup parent, final RecyViewHolder viewHolder, int viewType) {
if (!isEnabled(viewType)) return;
viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
int position = viewHolder.getAdapterPosition();
mOnItemClickListener.onItemClick(v, viewHolder, position);
}
}
});
viewHolder.getConvertView().setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (mOnItemClickListener != null) {
int position = viewHolder.getAdapterPosition();
return mOnItemClickListener.onItemLongClick(v, viewHolder, position);
}
return false;
}
});
if (mOnItemChildClickListener != null)
viewHolder.setOnItemChildClickListener(mOnItemChildClickListener);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
convert(holder, mDatas.get(position));
}
@Override
public int getItemCount() {
return mDatas == null ? 0 : mDatas.size();
}
public List<T> getDatas() {
return mDatas;
}
public void setDatas(List<T> mDatas) {
this.mDatas = mDatas;
notifyDataSetChanged();
}
public RecyMultiItemTypeAdapter addItemViewDelegate(ItemViewDelegate<T> itemViewDelegate) {
mItemViewDelegateManager.addDelegate(itemViewDelegate);
return this;
}
public RecyMultiItemTypeAdapter addItemViewDelegate(int viewType, ItemViewDelegate<T> itemViewDelegate) {
mItemViewDelegateManager.addDelegate(viewType, itemViewDelegate);
return this;
}
public void addExpandAll(int position, Collection collection) {
mDatas.addAll(position, collection);
notifyItemRangeInserted(position, collection.size());
}
public void removeExpandAll(int position, Collection collection) {
mDatas.removeAll(collection);
notifyItemRangeRemoved(position, collection.size());
}
public void clear() {
if (mDatas != null) {
mDatas.clear();
notifyDataSetChanged();
}
}
public T getItemObject(int pos) {
if (mDatas != null && mDatas.size() > pos) {
return mDatas.get(pos);
} else {
return null;
}
}
//**************************************************************
//************************添加item动画**************************
//**************************************************************
//Animation
/**
* Use with {@link #openLoadAnimation}
*/
public static final int ALPHAIN = 0x00000001;
/**
* Use with {@link #openLoadAnimation}
*/
public static final int SCALEIN = 0x00000002;
/**
* Use with {@link #openLoadAnimation}
*/
public static final int SLIDEIN_BOTTOM = 0x00000003;
/**
* Use with {@link #openLoadAnimation}
*/
public static final int SLIDEIN_LEFT = 0x00000004;
/**
* Use with {@link #openLoadAnimation}
*/
public static final int SLIDEIN_RIGHT = 0x00000005;
@IntDef({ALPHAIN, SCALEIN, SLIDEIN_BOTTOM, SLIDEIN_LEFT, SLIDEIN_RIGHT})
@Retention(RetentionPolicy.SOURCE)
public @interface AnimationType {
}
private boolean mFirstOnlyEnable = true;
private boolean mOpenAnimationEnable = false;
private Interpolator mInterpolator = new LinearInterpolator();
private int mDuration = 300;
private int mLastPosition = -1;
private BaseAnimation mCustomAnimation;
private BaseAnimation mSelectAnimation = new AlphaInAnimation();
@Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
super.onViewAttachedToWindow(holder);
addAnimation(holder);
}
/**
* Sets the duration of the animation.
*
* @param duration The length of the animation, in milliseconds.
*/
public void setDuration(int duration) {
mDuration = duration;
}
/**
* add animation when you want to show time
*
* @param holder
*/
private void addAnimation(RecyclerView.ViewHolder holder) {
if (mOpenAnimationEnable) {
if (!mFirstOnlyEnable || holder.getLayoutPosition() > mLastPosition) {
BaseAnimation animation = null;
if (mCustomAnimation != null) {
animation = mCustomAnimation;
} else {
animation = mSelectAnimation;
}
for (Animator anim : animation.getAnimators(holder.itemView)) {
startAnim(anim, holder.getLayoutPosition());
}
mLastPosition = holder.getLayoutPosition();
}
}
}
/**
* set anim to start when loading
*
* @param anim
* @param index
*/
protected void startAnim(Animator anim, int index) {
anim.setDuration(mDuration).start();
anim.setInterpolator(mInterpolator);
}
/**
* Set the view animation type.
*
* @param animationType One of {@link #ALPHAIN}, {@link #SCALEIN}, {@link #SLIDEIN_BOTTOM}, {@link #SLIDEIN_LEFT}, {@link #SLIDEIN_RIGHT}.
*/
public void openLoadAnimation(@RecyMultiItemTypeAdapter.AnimationType int animationType) {
this.mOpenAnimationEnable = true;
mCustomAnimation = null;
switch (animationType) {
case ALPHAIN:
mSelectAnimation = new AlphaInAnimation();
break;
case SCALEIN:
mSelectAnimation = new ScaleInAnimation();
break;
case SLIDEIN_BOTTOM:
mSelectAnimation = new SlideInBottomAnimation();
break;
case SLIDEIN_LEFT:
mSelectAnimation = new SlideInLeftAnimation();
break;
case SLIDEIN_RIGHT:
mSelectAnimation = new SlideInRightAnimation();
break;
default:
break;
}
}
/**
* Set Custom ObjectAnimator
*
* @param animation ObjectAnimator
*/
public void openLoadAnimation(BaseAnimation animation) {
this.mOpenAnimationEnable = true;
this.mCustomAnimation = animation;
}
/**
* To open the animation when loading
*/
public void openLoadAnimation() {
this.mOpenAnimationEnable = true;
}
/**
* {@link #addAnimation(RecyclerView.ViewHolder)}
*
* @param firstOnly true just show anim when first loading false show anim when load the data every time
*/
public void isFirstOnly(boolean firstOnly) {
this.mFirstOnlyEnable = firstOnly;
}
}
|
package com.fanfte.algorithm.dp;
public class LCS {
public static void main(String[] args) {
String str1 = "1A2C3D4B56";
String str2 = "B1D23CA45B6A";
String lcse = lcse(str1, str2);
System.out.println(lcse);
}
public static int[][] getDP(String str1, String str2) {
char[] chars1 = str1.toCharArray();
char[] chars2 = str2.toCharArray();
int m = chars1.length;
int n = chars2.length;
int[][] dp = new int[m][n];
dp[0][0] = chars1[0] == chars2[0] ? 1 : 0;
for(int i = 1; i < m;i++) {
dp[i][0] = Math.max(dp[i - 1][0], chars1[i] == chars2[0] ? 1 : 0);
}
for(int j = 1;j < n;j++) {
dp[0][j] = Math.max(dp[0][j -1], chars1[0] == chars2[j] ? 1 : 0);
}
for(int i = 1;i < m;i++) {
for(int j = 1;j < n;j++) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
if(chars1[i] == chars2[j]) {
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + 1);
}
}
}
return dp;
}
public static String lcse(String str1, String str2) {
if(str1 == null || str2 == null ||str1.equals("") || str2.equals("")) {
return "";
}
int m = str1.length() - 1;
int n = str2.length() - 1;
int[][] dp = getDP(str1, str2);
char[] res = new char[dp[m][n]];
int index = res.length - 1;
while(index >= 0 ) {
if(m > 0 && dp[m][n] == dp[m - 1][n]) {
m--;
} else if(n > 0 && dp[m][n] == dp[m][n - 1]) {
n--;
} else{
res[index--] = str1.charAt(m);
m--;
n--;
}
}
return String.valueOf(res);
}
}
|
package no.nav.vedtak.sikkerhet.kontekst;
import no.nav.vedtak.sikkerhet.oidc.token.OpenIDToken;
public interface RequestKontekstProvider extends KontekstProvider {
default OpenIDToken getToken() {
return getKontekst() instanceof RequestKontekst tk ? tk.getToken() : null;
}
}
|
package egovframework.com.file.excel.download;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;
public class LcmsExcelView extends AbstractExcelView{
@Override
protected void buildExcelDocument(Map model, HSSFWorkbook wb, HttpServletRequest request, HttpServletResponse response) throws Exception{
HSSFCell cell = null;
HSSFSheet sheet = wb.createSheet("Lcms List");
sheet.setDefaultColumnWidth((short)12);
Map<String, Object> map = (Map)model.get("lcmsMap");
List<Object> list = (List)map.get("list");
String contentType = (String)map.get("contentType");
if( map.get("contentType") != null ){
if( contentType.equals("C") ){
for( int i=0; i<list.size(); i++ ){
Map lcms = (Map)list.get(i);
cell = getCell(sheet, i, 0);
setText(cell, lcms.get("module").toString());
cell = getCell(sheet, i, 1);
setText(cell, lcms.get("owner").toString());
cell = getCell(sheet, i, 2);
setText(cell, lcms.get("lessonCd").toString());
cell = getCell(sheet, i, 3);
setText(cell, lcms.get("depth").toString());
cell = getCell(sheet, i, 4);
setText(cell, lcms.get("orderNum").toString());
cell = getCell(sheet, i, 5);
setText(cell, lcms.get("lessonName").toString());
cell = getCell(sheet, i, 6);
setText(cell, lcms.get("progressYn").toString());
cell = getCell(sheet, i, 7);
setText(cell, lcms.get("starting").toString());
cell = getCell(sheet, i, 8);
setText(cell, lcms.get("pageCount").toString());
}
}else{
for( int i=0; i<list.size(); i++){
Map lcms = (Map)list.get(i);
cell = getCell(sheet, i, 0);
setText(cell, (String)lcms.get("module"));
cell = getCell(sheet, i, 1);
setText(cell, (String)lcms.get("moduleName"));
cell = getCell(sheet, i, 2);
setText(cell, (String)lcms.get("lesson"));
cell = getCell(sheet, i, 3);
setText(cell, (String)lcms.get("lessonName"));
cell = getCell(sheet, i, 4);
setText(cell, (String)lcms.get("starting"));
}
}
}
}
}
|
package com.as.boot;
/**
* @ClassName: ModOrder_DWD
* @Description:定位胆
* @author Ason
* @date 2018年12月13日 下午3:15:13
*/
public class ModOrder_DWD {
private String method;
private String code;
private String nums;
private String piece;
private String price;
private String odds;
private String point;
private String amount;
public ModOrder_DWD(String method, String code, String piece, String price, String odds,
String point, String amount, String nums){
this.method = method;
this.piece = piece;
price = price.startsWith(".")?("0"+price):price;
this.price = price;
this.odds = odds;
this.point = point;
amount = amount.startsWith(".")?("0"+amount):amount;
this.amount = amount;
this.code = code;
this.nums = nums;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = serializeCode(code);
}
public String getNums() {
return nums;
}
public void setNums(String nums) {
this.nums = nums;
}
public String getPiece() {
return piece;
}
public void setPiece(String piece) {
this.piece = piece;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getOdds() {
return odds;
}
public void setOdds(String odds) {
this.odds = odds;
}
public String getPoint() {
return point;
}
public void setPoint(String point) {
this.point = point;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
/**
* @Title: serializePosition
* @Description: 格式化position
* @author: Ason
* @param position
* @return
* @return: String
* @throws
*/
public String serializePosition(String position){
String aimPistion = "";
for (int i = 0; i < position.length(); i++)
aimPistion += Integer.parseInt(position.charAt(i)+"")+1+",";
return aimPistion.substring(0,aimPistion.length()-1);
}
/**
* @Title: serializePosition
* @Description: 格式化position
* @author: Ason
* @param position
* @return
* @return: String
* @throws
*/
public String serializeCode(String code){
String aimCode = "";
code = code.replace("[", "").replace("]", "");
String[] codeArr = code.split(",");
//计算注数
this.nums = codeArr.length+"";
for (int i = 0; i < codeArr.length; i++) {
for (int j = 0; j < codeArr[i].length(); j++) {
aimCode += codeArr[i].charAt(j)+",";
}
aimCode = aimCode.substring(0,aimCode.length()-1)+"|";
}
return aimCode.substring(0,aimCode.length()-1).replace("| ,", "|");
}
}
|
package com.andybotting.oystermate.activity;
import com.andybotting.oystermate.R;
import com.andybotting.oystermate.utils.PreferenceHelper;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebLaunch extends Activity {
public static final String INTENT_URL = "intent_url";
WebView mWebView;
String mUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
// Get the URL
mUrl = getIntent().getExtras().getString(INTENT_URL);
mWebView = (WebView) findViewById(R.id.webview);
new WebViewTask().execute();
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
loadingStatus(progress < 100 ? true : false);
}
});
}
/**
* Update refresh status spinner
*/
private void loadingStatus(boolean isLoading) {
findViewById(R.id.title_refresh_progress).setVisibility(isLoading ? View.VISIBLE : View.GONE);
}
/**
* WebView which handles cookie sync in the background
* @author andy
*
*/
private class WebViewTask extends AsyncTask<Void, Void, Boolean> {
String sessionCookie;
CookieManager cookieManager;
@Override
protected void onPreExecute() {
loadingStatus(true);
PreferenceHelper preferenceHelper = new PreferenceHelper();
String sessionId = preferenceHelper.getSessionId();
CookieSyncManager.createInstance(WebLaunch.this);
cookieManager = CookieManager.getInstance();
sessionCookie = "JSESSIONID=" + sessionId + "; domain=oyster.tfl.gov.uk";
if (sessionCookie != null)
cookieManager.removeSessionCookie();
super.onPreExecute();
}
protected Boolean doInBackground(Void... param) {
// this is very important - THIS IS THE HACK
SystemClock.sleep(1000);
return false;
}
@Override
protected void onPostExecute(Boolean result) {
if (sessionCookie != null) {
cookieManager.setCookie(OysterDetails.TFL_URL + "/", sessionCookie);
CookieSyncManager.getInstance().sync();
}
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(true);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
});
mWebView.loadUrl(mUrl);
}
}
}
|
package bigdata;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Cluster;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Reducer;
public class PageRankReducer extends Reducer<Text, ObjectWritable, Text, Text> {
private long totalNodes;
@Override
public void setup(Context context) throws IOException, InterruptedException{
Configuration conf = context.getConfiguration();
Cluster cluster = new Cluster(conf);
Job currentJob = cluster.getJob(context.getJobID());
totalNodes = currentJob.getCounters().findCounter(PageRankDriver.Counter.totalNodes).getValue();
}
@Override
protected void reduce(Text key, Iterable<ObjectWritable> values, Context context)
throws IOException, InterruptedException {
PageRank p= null;
double pageRankValue=0;
for (ObjectWritable object: values)
{
if ( object.get() instanceof PageRank )
{
p= (PageRank) object.get(); //get the graph
}
else //otherwise the class is DoubleWritable
{
pageRankValue+= PageRankDriver.BETA*( (DoubleWritable) object.get()).get(); //BETA=0.8
}
}
pageRankValue+= ( (1- context.getConfiguration().getDouble("sumOfPageRanks",-1))/totalNodes); //sumOfPageRanks is S which comes from the S_Calculation_Reducer (the other mapreduce job)
p.setPageRankValue(pageRankValue);
context.write(new Text(p.getNode()), new Text(p.toString()));
}
}//end of Reduce class
|
package com.beike.util.lucene;
import com.beike.util.PropertiesReader;
import com.beike.util.StringUtils;
public class URLFormat {
public static String getGoodsURL(String goodsid){
if (StringUtils.validNull(goodsid)) {
String static_url = PropertiesReader.getValue("project",
"STATIC_URL");
if ("false".equals(static_url)) {
return "goods/showGoodDetail.do?goodId=" + goodsid;
} else {
return "goods/" + goodsid + ".html";
}
}
return "";
}
public static String getCouponURL(String coupoid){
return "";
}
public static String getBrandURL(String brandid){
return "";
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http;
import java.net.URI;
/**
* Represents an HTTP request message, consisting of a
* {@linkplain #getMethod() method} and a {@linkplain #getURI() URI}.
*
* @author Arjen Poutsma
* @since 3.1
*/
public interface HttpRequest extends HttpMessage {
/**
* Return the HTTP method of the request.
* @return the HTTP method as an HttpMethod value
* @see HttpMethod#valueOf(String)
*/
HttpMethod getMethod();
/**
* Return the URI of the request (including a query string if any,
* but only if it is well-formed for a URI representation).
* @return the URI of the request (never {@code null})
*/
URI getURI();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.