text
stringlengths 10
2.72M
|
|---|
package com.savvycom.gametank.Common;
import com.savvycom.gametank.Entity.Orientation;
import java.awt.*;
public class Item {
private TypeItem typeItem;
private Image image;
protected int x,y;
protected int size;
private int id;
private Orientation orientation;
public Item(TypeItem typeItem, int x, int y, int size) {
this.typeItem = typeItem;
this.image = typeItem.getImageFromType(this.typeItem);
this.x = x;
this.y = y;
this.size = size;
}
public TypeItem getTypeItem() {
return typeItem;
}
public void setTypeItem(TypeItem typeItem) {
this.typeItem = typeItem;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Orientation getOrientation() {
return orientation;
}
public void setOrientation(Orientation orientation) {
this.orientation = orientation;
}
public void draw(Graphics2D g2d){
g2d.drawImage(image,x,y, size, size,null);
}
}
|
package com.hackathon.lib;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpServerErrorException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ApiRequest{
public static JsonObject getRequest(Url apiUrl){
try {
URL url = new URL(apiUrl.getBase());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
StringBuffer stringBuffer = new StringBuffer();
if( con.getResponseCode() == HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String line;
while((line = br.readLine()) != null){
stringBuffer.append(line).append("\n");
}
br.close();
}
JsonParser jsonParser = new JsonParser();
return (JsonObject) jsonParser.parse(stringBuffer.toString());
}catch (Exception e){
e.printStackTrace();
throw new HttpServerErrorException(HttpStatus.BAD_REQUEST, "잘못된 요청");
}
}
}
|
package com.esum.comp.dbc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.comp.dbc.listener.DbcChannelListener;
import com.esum.comp.dbc.listener.DbcTaskScheduleListener;
import com.esum.comp.dbc.listener.DbcTemplateJobListener;
import com.esum.comp.dbc.table.DbcInfoTable;
import com.esum.framework.core.component.DefaultComponent;
import com.esum.framework.core.component.table.InfoTableManager;
import com.esum.framework.core.exception.SystemException;
/**
* DB Connector Component(DBC)
* DBC는 특정 DB에 대해 TaskHandler를 통해 어떤 작업을 수행하거나, Template기반의 DB to DB 작업을 지원하기 위한 컴포넌트이다.
*/
public class DbcConnector extends DefaultComponent {
private Logger log = LoggerFactory.getLogger(DbcConnector.class);
public void onInit() throws SystemException {
initComponentConfig(new DbcConfig(getId()));
initInfoTable(DbcConfig.DBC_INFO_TABLE_ID, DbcInfoTable.class);
setLegacyListener(new DbcTemplateJobListener());
setDummyListener(new DbcTaskScheduleListener());
setInputChannelListener(DbcChannelListener.class);
}
@Override
public void onStartup() throws SystemException {
super.onStartup();
}
@Override
public void onShutdown() throws SystemException {
super.onShutdown();
}
public void onReload(String[] reloadIds, boolean channel, boolean etc) throws SystemException {
DbcInfoTable dbIfInfoTable = (DbcInfoTable)InfoTableManager.getInstance().getInfoTable(DbcConfig.DBC_INFO_TABLE_ID);
if(reloadIds==null || reloadIds.length==0)
dbIfInfoTable.reloadAllInfoRecord();
else
dbIfInfoTable.reloadInfoRecord(reloadIds);
}
}
|
package ru.itmo.ctlab.sgmwcs.solver;
import ru.itmo.ctlab.sgmwcs.Signals;
import ru.itmo.ctlab.sgmwcs.graph.Edge;
import ru.itmo.ctlab.sgmwcs.graph.Graph;
import ru.itmo.ctlab.sgmwcs.graph.Node;
import ru.itmo.ctlab.sgmwcs.graph.Unit;
import java.util.*;
/**
* Created by Nikolay Poperechnyi on 17.03.18.
*/
public class TreeSolver {
class Solution {
Set<Unit> units;
Solution() {
this.units = new HashSet<>();
}
Set<Integer> sets() {
return s.unitSets(units);
}
Solution(Set<Unit> units) {
this.units = units;
}
}
private final Graph g;
private final Signals s;
private Set<Unit> withoutRoot;
private Set<Unit> withRoot;
public Set<Unit> solutionWithoutRoot() {
return withoutRoot;
}
public Set<Unit> solutionWithRoot() {
return withRoot;
}
public TreeSolver(Graph g, Signals s) {
this.g = g;
this.s = s;
}
public Solution solveRooted(Node root) {
return solve(root, null, Collections.emptySet());
}
private Solution solve(Node root, Node parent, Set<Integer> parentSets) {
List<Node> nodes = g.neighborListOf(root);
assert (parent == null || nodes.contains(parent));
Set<Unit> rootSet = new HashSet<>();
rootSet.add(root);
Solution nonEmpty = new Solution(rootSet);
Solution empty = new Solution();
if (parent != null) {
Edge e = g.getEdge(root, parent);
nodes.remove(parent);
rootSet.add(e);
}
if (nodes.isEmpty()
&& s.minSum(root) < 0
&& parentSets.containsAll(
s.positiveUnitSets(nonEmpty.units))) {
return empty;
} else {
List<Solution> childSols = new ArrayList<>();
Set<Integer> signals = new HashSet<>(nonEmpty.sets());
signals.addAll(parentSets);
for (Node node : nodes) {
childSols.add(solve(node, root, signals));
}
/*while (!childSols.isEmpty()) {
Solution max = childSols.stream().max(
Comparator.comparingDouble(sol -> s.weightSum(sol.sets()))
).get();
max.sets().removeAll(sigs);
if (s.weightSum(max.sets()) < 0) {
break;
} else {
childSols.remove(max);
nonEmpty.units.addAll(max.units);
}
}*/
for (Solution childSol: childSols) {
Set<Integer> childSets = new HashSet<>(childSol.sets());
// Set<Integer> setSum = new HashSet<>(childSets);
// setSum.addAll(sigs);
childSets.addAll(signals);
if (s.weightSum(childSets) >= s.weightSum(signals)) {
nonEmpty.units.addAll(childSol.units);
}
}
}
return nonEmpty;
}
}
|
package interfaces.ColorInterface.impl;
import interfaces.ColorInterface.Color;
/**
* @Description:
* @Author: lay
* @Date: Created in 9:50 2018/12/4
* @Modified By:IntelliJ IDEA
*/
public class Blue implements Color {
@Override
public void fill() {
System.out.println("Inside Blue::fill() method.");
}
}
|
/*
* 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.util;
import com.innovaciones.reporte.model.DTO.MantenimientoDTO;
import com.innovaciones.reporte.model.DetalleCatalogoReporte;
import com.innovaciones.reporte.model.ProductoClienteReporte;
import com.innovaciones.reporte.model.ReporteGenericoItems;
import com.innovaciones.reporte.model.TipoVisita;
import com.innovaciones.reporte.service.CabeceraCatalogoReporteService;
import com.innovaciones.reporte.service.DetalleCatalogoReporteService;
import com.innovaciones.reporte.service.ParametrosService;
import com.innovaciones.reporte.service.TipoVisitaService;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedProperty;
import lombok.Getter;
import lombok.Setter;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
/**
*
* @author Fernando
*/
public class ReporteTecnico extends Utilities implements Serializable {
/**
* Creates a new instance of ReporteTecnicoBean
*/
@Getter
@Setter
@ManagedProperty("#{parametrosService}")
private ParametrosService parametrosService;
private Map<String, Object> parameters;
private final static String IMAGEN_EMBEBIDA_FORMAT = "data:image/png;base64,";
private final static String REPORTE_TECNICO_PATH = "/reports/reporte_tecnico.jasper";
private final static String REPORTE_INSTALACION_NUEVA_PATH = "/reports/instalacion_nueva.jasper";
private final static String REPORTE_INSTALACION_TEMPORAL_PATH = "/reports/instalacion_temporal.jasper";
private final static String REPORTE_MONITOR_PATH = "/reports/reporte_monitor.jasper";
private final static String REPORTE_ETIQUETADORAS_PATH = "/reports/reporte_etiquetadora.jasper";
private final static String REPORTE_SCANNERS_PATH = "/reports/reporte_scanner.jasper";
private final static String REPORTE_TRITURADORAS_PATH = "/reports/reporte_trituradora.jasper";
private final static String REPORTE_CUBO_ANVERSO_PATH = "/reports/reporte_cubo_anverso.jasper";
private final static String REPORTE_CUBO_REVERSO_PATH = "/reports/reporte_cubo_reverso.jasper";
private final static String REPORTE_TECNICO_GENERICO_PATH = "/reports/reporte_generico.jasper";
private final static String SELECCIONAR = "X";
private final static String DG_VISITA_POR_GARANTIA = "Vista por Garantía";
private final static String DG_EQUIPOS_BAJO_CONTARTO = "Equipo bajo Contrato";
private final static String DG_VISITA_DE_CORTESIA = "Visita de Cortesía";
private final static String DG_CAPACITACION_MANEJO = "Capacitación / Manejo";
private final static String DG_ARRENDAMIENTO = "Arrendamiento";
private final static String DG_INSPECCION = "Inspección";
private final static String DG_LABORATORIO = "Laboratorio";
private final static String MP_UNIDAD_TRANSFERENCIA = "Unidad de Transferencia";
private final static String MP_REGISTRO = "Registro";
private final static String MP_SENSORES_PROCESAMIENTO = "Unidad de Revelado";
private final static String MP_CORONA_TRANSFERENCIA = "Corona de Transferencia";
private final static String MP_SECCION_PROCESAMIENTO = "Sección de Procesamiento";
private final static String MP_PRESS_ROLLER = "Press Roller / Unidad Fusora";
private final static String MP_HEAT_ROLLER = "Heat Roller / Unidad Fusora";
private final static String MP_GUIAS = "Guías";
private final static String MP_RODILLOS_ARRASTRE = "Rodillos de Alimentación";
private final static String MP_SENSORES_FIJACION = "Rodillos de Transporte";
private final static String MP_PINON_ACOPLE = "Piñón de Acople";
private final static String MP_VIDRIOS = "Vidrios";
private final static String MP_CUBIERTAS = "Cubiertas";
private final static String MP_ALIMENTADOR_ORIGINALES = "Alimentador de Originales";
private final static String MP_BANDEJA_PAPEL = "Bandejas de Papel";
private final static String MP_BY_PASS = "By Pass (Manual)";
private final static String MP_LUBRICACION_GENERAL = "Lubricación General";
private final static String MC_TONER_K = "Toner K";
private final static String MC_TONER_CMY = "Toner C,M,Y";
private final static String MC_TONER_C = "Toner C";
private final static String MC_TONER_M = "Toner M";
private final static String MC_TONER_Y = "Toner Y";
private final static String TANQUE_DESECHO = "Tanque de Desechos";
private final static String MC_UNIDAD_IMAGEN_K = "Unidad de Imagen K";
private final static String MC_CILINDRO = "Cilindro";
private final static String MC_BANDA_TRANSFERENCIA = "Banda Transferencia";
private final static String MC_UNIDAD_IMAGEN_C = "Unidad Imagen C";
private final static String MC_UNIDAD_IMAGEN_M = "Unidad Imagen M";
private final static String MC_UNIDAD_IMAGEN_Y = "Unidad Imagen Y";
private final static String MC_UNIDAD_FUSION = "Unidad de Fusión";
private final static String MC_PRESS_ROLLER = "Press Roller";
private final static String MC_HEAT_ROLLER = "Heat Roller";
private final static String MC_UNIDAD_REVELADO = "Unidad Revelado";
private final static String MC_REVELADOR = "Revelador";
private final static String MC_PICKUP_ROLLER = "Pick up Roller";
private final static String MC_FEED_ROLLER = "Feed Roller";
private final static String MC_SEPARATION_ROLLER = "Separation Roller";
private final static String MC_UNIDAD_LASER = "Unidad Láser";
private final static String MC_REGULADOR_VOLTAJE = "Regulador de Voltaje";
public ReporteTecnico() {
}
public static byte[] jasperBytesReportes(ProductoClienteReporte productoClienteReporte,
TipoVisitaService tipoVisitaService, DetalleCatalogoReporteService detalleCatalogoReporteService,
CabeceraCatalogoReporteService cabeceraCatalogoReporteService) {
/* Map<String, Object> */
Map<String, Object> parametros = loadParametersReporteBytes(productoClienteReporte, tipoVisitaService,
detalleCatalogoReporteService, cabeceraCatalogoReporteService);;
String path = "";
if (productoClienteReporte.getIdReporte().getTipo().equals(Enums.TIPO_REPORTE_DIAGNOSTICO.getValue())) {
path = REPORTE_TECNICO_PATH;
}
if (productoClienteReporte.getIdReporte().getTipo().equals(Enums.TIPO_REPORTE_REPARACION.getValue())) {
path = REPORTE_TECNICO_PATH;
}
if (productoClienteReporte.getIdReporte().getTipo().equals(Enums.TIPO_REPORTE_CONTADORES.getValue())) {
path = REPORTE_TECNICO_PATH;
}
if (productoClienteReporte.getIdReporte().getTipo().equals(Enums.TIPO_REPORTE_GENERICO.getValue())) {
path = REPORTE_TECNICO_GENERICO_PATH;
}
return jasperBytes(parametros, path);
}
public static Map<String, Object> loadParametersReporteBytes(ProductoClienteReporte productoClienteReporte,
TipoVisitaService tipoVisitaService, DetalleCatalogoReporteService detalleCatalogoReporteService,
CabeceraCatalogoReporteService cabeceraCatalogoReporteService) {
Map<String, Object> parametros = new HashMap();
try {
parametros.put("codigo", productoClienteReporte.getIdReporte().getIdUsuario().getCodigo());
parametros.put("fecha", fomatearFecha(productoClienteReporte.getIdReporte().getFecha()));
//DATOS GENERALES
parametros.put("cliente", productoClienteReporte.getIdCliente().getCliente());
parametros.put("ruc", productoClienteReporte.getIdCliente().getRuc());
parametros.put("atencion", productoClienteReporte.getAtencion());
parametros.put("telefono", productoClienteReporte.getIdCliente().getTelefono());
parametros.put("telefono2", productoClienteReporte.getIdCliente().getTelefono2());
parametros.put("direccion", productoClienteReporte.getIdCliente().getDireccion());
parametros.put("factura", productoClienteReporte.getIdReporte().getFactura());
parametros.put("referencia", productoClienteReporte.getIdReporte().getReferencia());
parametros.put("departamento", productoClienteReporte.getDepartamento());
parametros.put("ciudad", productoClienteReporte.getIdCliente().getCiudad());
parametros.put("email", productoClienteReporte.getIdCliente().getEmail());
parametros.put("numero_reporte", "N° " + productoClienteReporte.getIdReporte().getIdUsuario().getCodigo() + " - " + formatoNumeroFactura(productoClienteReporte.getIdReporte().getId()));
parametros.put("direccion_equipo", productoClienteReporte.getDireccionEquipo());
parametros.put("telefono_equipo", productoClienteReporte.getTelefonoEquipo());
parametros.put("mail_equipo", productoClienteReporte.getCelularEquipo());
//FIRMA
String image64Cliente = productoClienteReporte.getIdReporte().getFirmaClienteBase64();
String image64Tecnico = productoClienteReporte.getIdReporte().getIdUsuario().getFirmaBase64();
if (image64Cliente != null && !image64Cliente.isEmpty()) {
image64Cliente = image64Cliente.replace(IMAGEN_EMBEBIDA_FORMAT, "").trim();
parametros.put("firma_cliente", image64Cliente);
}
if (image64Tecnico != null && !image64Tecnico.isEmpty()) {
image64Tecnico = image64Tecnico.replace(IMAGEN_EMBEBIDA_FORMAT, "").trim();
parametros.put("firma_tecnico", image64Tecnico);
}
List<TipoVisita> tiposVisita = tipoVisitaService.getAllTipoVisitas();
//Asignacion de visitas en Datos Generales
for (TipoVisita tipoVisita : tiposVisita) {
tipoVisita.setDescripcion(tipoVisita.getDescripcion().trim());
if (tipoVisita.getId().intValue() == productoClienteReporte.getIdReporte().getIdVisita().getId().intValue()) {
if (tipoVisita.getDescripcion().equalsIgnoreCase(DG_VISITA_POR_GARANTIA)) {
parametros.put("visita_garantia", SELECCIONAR);
}
if (tipoVisita.getDescripcion().equalsIgnoreCase(DG_EQUIPOS_BAJO_CONTARTO)) {
parametros.put("equipos_bajo_contrato", SELECCIONAR);
}
if (tipoVisita.getDescripcion().equalsIgnoreCase(DG_VISITA_DE_CORTESIA)) {
parametros.put("visita_cortesia", SELECCIONAR);
}
if (tipoVisita.getDescripcion().equalsIgnoreCase(DG_CAPACITACION_MANEJO)) {
parametros.put("capacitacion_manejo", SELECCIONAR);
}
if (tipoVisita.getDescripcion().equalsIgnoreCase(DG_ARRENDAMIENTO)) {
parametros.put("arrendamiento", SELECCIONAR);
}
if (tipoVisita.getDescripcion().equalsIgnoreCase(DG_INSPECCION)) {
parametros.put("inspeccion", SELECCIONAR);
}
if (tipoVisita.getDescripcion().equalsIgnoreCase(DG_LABORATORIO)) {
parametros.put("laboratorio", SELECCIONAR);
}
break;
}
}
//DATOS DEL EQUIPO
parametros.put("equipo", productoClienteReporte.getIdProducto().getIdCategoria().getNombre());
parametros.put("marca", productoClienteReporte.getIdProducto().getIdModelo().getIdMarca().getMarca());
parametros.put("modelo", productoClienteReporte.getIdProducto().getIdModelo().getModelo());
parametros.put("serie", productoClienteReporte.getSerie());
parametros.put("ip", productoClienteReporte.getIpEquipo());
parametros.put("firmware", productoClienteReporte.getIdProducto().getVersionFirmware());
//DATOS SUCURSAL
parametros.put("empty1", productoClienteReporte.getIdClienteSucursal().getNombreContacto());
parametros.put("empty1", productoClienteReporte.getIdClienteSucursal().getEmailContacto());
parametros.put("departamento", productoClienteReporte.getIdClienteSucursal().getCiudad());
parametros.put("direccion_equipo", productoClienteReporte.getIdClienteSucursal().getDireccion());
parametros.put("telefono_equipo", productoClienteReporte.getIdClienteSucursal().getTelefonoContacto());
parametros.put("mail_equipo", productoClienteReporte.getIdClienteSucursal().getCelularContacto());
System.out.println(" SETEAR CONTADORES ..... ");
//DATOS DE CONTADORES
if (productoClienteReporte.getIdProductoDetalleReporte().getContadorTotalAnterior() != null) {
parametros.put("contador_total_anterior", productoClienteReporte.getIdProductoDetalleReporte().getContadorTotalAnterior().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getContadorColorAnterior() != null) {
parametros.put("contador_color_anterior", productoClienteReporte.getIdProductoDetalleReporte().getContadorColorAnterior().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getContadorBnAnterior() != null) {
parametros.put("contador_bn_anterior", productoClienteReporte.getIdProductoDetalleReporte().getContadorBnAnterior().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getContadorTotalActual() != null) {
parametros.put("contador_total_actual", productoClienteReporte.getIdProductoDetalleReporte().getContadorTotalActual().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getContadorColorActual() != null) {
parametros.put("contador_color_actual", productoClienteReporte.getIdProductoDetalleReporte().getContadorColorActual().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getContadorBnActual() != null) {
parametros.put("contador_bn_actual", productoClienteReporte.getIdProductoDetalleReporte().getContadorBnActual().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getContadorTotalImpReal() != null) {
parametros.put("contador_total_real", productoClienteReporte.getIdProductoDetalleReporte().getContadorTotalImpReal().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getContadorColorImpReal() != null) {
parametros.put("contador_color_real", productoClienteReporte.getIdProductoDetalleReporte().getContadorColorImpReal().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getContadorBnImpReal() != null) {
parametros.put("contador_bn_real", productoClienteReporte.getIdProductoDetalleReporte().getContadorBnImpReal().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getMantenimiento() != null) {
parametros.put("mantenimiento", productoClienteReporte.getIdProductoDetalleReporte().getMantenimiento().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getOtros() != null) {
parametros.put("otros", productoClienteReporte.getIdProductoDetalleReporte().getOtros().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getServicioFacturar() != null) {
parametros.put("servicio_facturar", productoClienteReporte.getIdProductoDetalleReporte().getServicioFacturar().toString());
}
if (productoClienteReporte.getIdProductoDetalleReporte().getServicioFacturarEstado() != null && productoClienteReporte.getIdProductoDetalleReporte().getServicioFacturarEstado()) {
parametros.put("servicio_facturar_estado", SELECCIONAR);
}
System.out.println(" CONTADORES SETEADO ");
parametros.put("sintomas", productoClienteReporte.getIdReporte().getSintomasEquipo());
parametros.put("observacion", productoClienteReporte.getIdReporte().getObservacionMantenimiento());
parametros.put("observaciones_recomendaciones", productoClienteReporte.getIdReporte().getObservacionesRecomendaciones());
try {
} catch (Exception e) {
}
// parametros.put("hora_inicio", fomatearHora(productoClienteReporte.getIdReporte().getHoraInicio()));
// parametros.put("hora_finalizacion", fomatearHora(productoClienteReporte.getIdReporte().getHoraFin()));
parametros.put("nombre_tecnico", productoClienteReporte.getIdReporte().getIdUsuario().getNombreCompleto());
parametros.put("nombre_cliente", productoClienteReporte.getIdReporte().getNombreCliente());
System.out.println(" TIPO IF " + productoClienteReporte.getIdReporte().getTipo());
if (productoClienteReporte.getIdReporte().getTipo().equals(Enums.TIPO_REPORTE_DIAGNOSTICO.getValue())) {
parametros.putAll(loadParametersReportesRepuestosByte(productoClienteReporte, detalleCatalogoReporteService, cabeceraCatalogoReporteService));
}
if (productoClienteReporte.getIdReporte().getTipo().equals(Enums.TIPO_REPORTE_REPARACION.getValue())) {
parametros.putAll(loadParametersReportesRepuestosByte(productoClienteReporte, detalleCatalogoReporteService, cabeceraCatalogoReporteService));
}
if (productoClienteReporte.getIdReporte().getTipo().equals(Enums.TIPO_REPORTE_CONTADORES.getValue())) {
parametros.putAll(loadParametersReportesRepuestosByte(productoClienteReporte, detalleCatalogoReporteService, cabeceraCatalogoReporteService));
}
if (productoClienteReporte.getIdReporte().getTipo().equals(Enums.TIPO_REPORTE_GENERICO.getValue())) {
parametros.putAll(loadParametersReporteGenerico(productoClienteReporte));
}
} catch (Exception e) {
System.out.println("Error cargar Parametros " + e.getMessage());
e.getStackTrace();
}
return parametros;
}
public static Map<String, Object> loadParametersReporteGenerico(ProductoClienteReporte productoClienteReporte) {
Map<String, Object> parametros = new HashMap();
parametros.put("lbl_cont_anterior", productoClienteReporte.getIdProductoDetalleReporte().getEtiquetaAnterior());
parametros.put("lbl_cont_actual", productoClienteReporte.getIdProductoDetalleReporte().getEtiquetaActual());
parametros.put("lbl_cont_real", productoClienteReporte.getIdProductoDetalleReporte().getEtiquetaImpresionReal());
parametros.put("lbl_cont_total", productoClienteReporte.getIdProductoDetalleReporte().getEtiquetaContadorTotal());
parametros.put("lbl_cont_color", productoClienteReporte.getIdProductoDetalleReporte().getEtiquetaContadorColor());
parametros.put("lbl_cont_bn", productoClienteReporte.getIdProductoDetalleReporte().getEtiquetaContadorBn());
parametros.put("lbl_sintomas", productoClienteReporte.getIdReporte().getEtiquetaSintomasEquipo());
List<MantenimientoDTO> mantenimientosPreventivos = new ArrayList<>();
List<MantenimientoDTO> mantenimientosCorrectivos = new ArrayList<>();
MantenimientoDTO mantenimiento = null;
for (ReporteGenericoItems item : productoClienteReporte.getReporteGenericoItemsList()) {
mantenimiento = new MantenimientoDTO();
mantenimiento.setDescripcion(item.getDescripcion());
if (item.getTipo().charValue() == 'P') {
mantenimiento.setCodigo("");
mantenimiento.setValor1(true);
mantenimientosPreventivos.add(mantenimiento);
} else {
mantenimiento.setValor1(item.getCambiado());
mantenimiento.setValor2(item.getSolicitar());
mantenimiento.setCodigo(item.getCodigoRepuesto());
mantenimientosCorrectivos.add(mantenimiento);
}
}
JRBeanCollectionDataSource itemsJRBean = new JRBeanCollectionDataSource(mantenimientosPreventivos);
JRBeanCollectionDataSource itemsJRBean2 = new JRBeanCollectionDataSource(mantenimientosCorrectivos);
parametros.put("ItemDataSource", itemsJRBean);
parametros.put("ItemDataSource2", itemsJRBean2);
return parametros;
}
public static Map<String, Object> loadParametersReportesRepuestosByte(ProductoClienteReporte productoClienteReporte,
DetalleCatalogoReporteService detalleCatalogoReporteService,
CabeceraCatalogoReporteService cabeceraCatalogoReporteService) {
Map<String, Object> parametros = new HashMap();
List<DetalleCatalogoReporte> listProcesamiento = llenarRepuestosPreventivos(detalleCatalogoReporteService.getDetalleCatalogoReporteByCabeceraCodigo(Enums.MANTENIMIENTO_PROCESAMIENTO.getValue()), productoClienteReporte);
List<DetalleCatalogoReporte> listPreventivoImagen = llenarRepuestosPreventivos(detalleCatalogoReporteService.getDetalleCatalogoReporteByCabeceraCodigo(Enums.MANTENIMIENTO_PREVENTIVO_IMAGEN.getValue()), productoClienteReporte);
List<DetalleCatalogoReporte> listPreventivoFijacion = llenarRepuestosPreventivos(detalleCatalogoReporteService.getDetalleCatalogoReporteByCabeceraCodigo(Enums.MANTENIMIENTO_PREVENTIVO_FIJACION.getValue()), productoClienteReporte);
List<DetalleCatalogoReporte> listPreventivoLimpieza = llenarRepuestosPreventivos(detalleCatalogoReporteService.getDetalleCatalogoReporteByCabeceraCodigo(Enums.MANTENIMIENTO_EXTERIORES.getValue()), productoClienteReporte);
List<DetalleCatalogoReporte> listCorrectivoSuministros = llenarRepuestosCorrectivos(detalleCatalogoReporteService.getDetalleCatalogoReporteByCabeceraCodigo(Enums.MANTENIMIENTO_SUMINISTROS.getValue()), productoClienteReporte);
List<DetalleCatalogoReporte> listCorrectivoImagen = llenarRepuestosCorrectivos(detalleCatalogoReporteService.getDetalleCatalogoReporteByCabeceraCodigo(Enums.MANTENIMIENTO_CORRECTIVO_IMAGEN.getValue()), productoClienteReporte);
List<DetalleCatalogoReporte> listCorrectivoFijacion = llenarRepuestosCorrectivos(detalleCatalogoReporteService.getDetalleCatalogoReporteByCabeceraCodigo(Enums.MANTENIMIENTO_CORRECTIVO_FIJACION.getValue()), productoClienteReporte);
List<DetalleCatalogoReporte> listCorrectivoRevelado = llenarRepuestosCorrectivos(detalleCatalogoReporteService.getDetalleCatalogoReporteByCabeceraCodigo(Enums.MANTENIMIENTO_CORRECTIVO_REVELADO.getValue()), productoClienteReporte);
List<DetalleCatalogoReporte> listCorrectivoAlimentacion = llenarRepuestosCorrectivos(detalleCatalogoReporteService.getDetalleCatalogoReporteByCabeceraCodigo(Enums.MANTENIMIENTO_ALIMENTACION.getValue()), productoClienteReporte);
List<DetalleCatalogoReporte> otros = llenarRepuestosOtros(listCorrectivoOtros(cabeceraCatalogoReporteService.getCabeceraCatalogoReportesByCodigo(Enums.MANTENIMIENTO_OTROS.getValue())), productoClienteReporte,
cabeceraCatalogoReporteService.getCabeceraCatalogoReportesByCodigo(Enums.MANTENIMIENTO_OTROS.getValue()));
//MANTENIMIENTO PREVENTIVO
for (DetalleCatalogoReporte detalleCatalogoReporte : listProcesamiento) {
detalleCatalogoReporte.setDescripcion(detalleCatalogoReporte.getDescripcion().trim());
if (detalleCatalogoReporte.isSeleccion()) {
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_UNIDAD_TRANSFERENCIA)) {
parametros.put("unidad_transferencia", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_REGISTRO)) {
parametros.put("registro", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_SENSORES_PROCESAMIENTO)) {
parametros.put("sensores_procesamiento", SELECCIONAR);
}
}
}
for (DetalleCatalogoReporte detalleCatalogoReporte : listPreventivoImagen) {
detalleCatalogoReporte.setDescripcion(detalleCatalogoReporte.getDescripcion().trim());
if (detalleCatalogoReporte.isSeleccion()) {
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_CORONA_TRANSFERENCIA)) {
parametros.put("corona_transferencia", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_SECCION_PROCESAMIENTO)) {
parametros.put("seccion_procesamiento", SELECCIONAR);
}
}
}
for (DetalleCatalogoReporte detalleCatalogoReporte : listPreventivoFijacion) {
detalleCatalogoReporte.setDescripcion(detalleCatalogoReporte.getDescripcion().trim());
if (detalleCatalogoReporte.isSeleccion()) {
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_PRESS_ROLLER)) {
parametros.put("press_roller", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_HEAT_ROLLER)) {
parametros.put("heat_roller", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_GUIAS)) {
parametros.put("guias", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_RODILLOS_ARRASTRE)) {
parametros.put("rodillo_arrastre", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_SENSORES_FIJACION)) {
parametros.put("sensores_fijacion", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_PINON_ACOPLE)) {
parametros.put("pinon_acople", SELECCIONAR);
}
}
}
for (DetalleCatalogoReporte detalleCatalogoReporte : listPreventivoLimpieza) {
detalleCatalogoReporte.setDescripcion(detalleCatalogoReporte.getDescripcion().trim());
if (detalleCatalogoReporte.isSeleccion()) {
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_VIDRIOS)) {
parametros.put("vidrios", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_CUBIERTAS)) {
parametros.put("cubiertas", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_ALIMENTADOR_ORIGINALES)) {
parametros.put("alimentador_originales", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_BANDEJA_PAPEL)) {
parametros.put("bandeja_papel", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_BY_PASS)) {
parametros.put("by_pass", SELECCIONAR);
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MP_LUBRICACION_GENERAL)) {
parametros.put("lubricacion_general", SELECCIONAR);
}
}
}
//MANTENIMIENTO CORRECTIVO
for (DetalleCatalogoReporte detalleCatalogoReporte : listCorrectivoSuministros) {
detalleCatalogoReporte.setDescripcion(detalleCatalogoReporte.getDescripcion().trim());
if (detalleCatalogoReporte.getTipoRepuesto() != null && !detalleCatalogoReporte.getTipoRepuesto().equals("") && detalleCatalogoReporte.getCodigoRepuesto() != null) {
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_TONER_K)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("toner_k_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("toner_k_s", SELECCIONAR);
}
parametros.put("tonerk_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("toner_k_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_TONER_CMY)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("toner_cmy_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("toner_cmy_s", SELECCIONAR);
}
parametros.put("tonercmy_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("toner_cmy_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_TONER_C)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("toner_c_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("toner_c_s", SELECCIONAR);
}
parametros.put("tonerc_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("toner_c_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_TONER_M)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("toner_m_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("toner_m_s", SELECCIONAR);
}
parametros.put("tonerm_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("toner_m_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_TONER_Y)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("toner_y_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("toner_y_s", SELECCIONAR);
}
parametros.put("tonery_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("toner_y_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(TANQUE_DESECHO)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("tanque_desechos_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("tanque_desechos_s", SELECCIONAR);
}
parametros.put("tanque_desechos_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("tanque_desechos_code", detalleCatalogoReporte.getCodigoRepuesto());
}
}
}
for (DetalleCatalogoReporte detalleCatalogoReporte : listCorrectivoImagen) {
detalleCatalogoReporte.setDescripcion(detalleCatalogoReporte.getDescripcion().trim());
if (detalleCatalogoReporte.getTipoRepuesto() != null && !detalleCatalogoReporte.getTipoRepuesto().equals("") && detalleCatalogoReporte.getCodigoRepuesto() != null) {
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_UNIDAD_IMAGEN_K)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("u_imagen_k_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("u_imagen_k_s", SELECCIONAR);
}
parametros.put("u_imagen_k_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("u_imagen_k_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_CILINDRO)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("cilindro_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("cilindro_s", SELECCIONAR);
}
parametros.put("cilindro_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("cilindro_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_BANDA_TRANSFERENCIA)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("banda_transferencia_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("banda_transferencia_s", SELECCIONAR);
}
parametros.put("banda_trans_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("banda_transferencia_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_UNIDAD_IMAGEN_C)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("u_imagen_c_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("u_imagen_c_s", SELECCIONAR);
}
parametros.put("u_imagen_c_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("u_imagen_c_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_UNIDAD_IMAGEN_M)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("u_imagen_m_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("u_imagen_m_s", SELECCIONAR);
}
parametros.put("u_imagen_m_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("u_imagen_m_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_UNIDAD_IMAGEN_Y)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("u_imagen_y_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("u_imagen_y_s", SELECCIONAR);
}
parametros.put("u_imagen_y_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("u_imagen_y_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
}
}
for (DetalleCatalogoReporte detalleCatalogoReporte : listCorrectivoFijacion) {
detalleCatalogoReporte.setDescripcion(detalleCatalogoReporte.getDescripcion().trim());
if (detalleCatalogoReporte.getTipoRepuesto() != null && !detalleCatalogoReporte.getTipoRepuesto().equals("") && detalleCatalogoReporte.getCodigoRepuesto() != null) {
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_UNIDAD_FUSION)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("unidad_fusion_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("unidad_fusion_s", SELECCIONAR);
}
parametros.put("u_fusion_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("unidad_fusion_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_PRESS_ROLLER)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("press_roller_correctivo_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("press_roller_correctivo_s", SELECCIONAR);
}
parametros.put("press_roller_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("press_roller_correctivo_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_HEAT_ROLLER)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("heat_roller_correctivo_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("heat_roller_correctivo_s", SELECCIONAR);
}
parametros.put("heat_roller_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("heat_roller_correctivo_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
}
}
for (DetalleCatalogoReporte detalleCatalogoReporte : listCorrectivoRevelado) {
detalleCatalogoReporte.setDescripcion(detalleCatalogoReporte.getDescripcion().trim());
if (detalleCatalogoReporte.getTipoRepuesto() != null && !detalleCatalogoReporte.getTipoRepuesto().equals("") && detalleCatalogoReporte.getCodigoRepuesto() != null) {
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_UNIDAD_REVELADO)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("unidad_revelado_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("unidad_revelado_s", SELECCIONAR);
}
parametros.put("u_revelado_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("unidad_revelado_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_REVELADOR)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("revelador_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("revelador_s", SELECCIONAR);
}
parametros.put("revelador_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("revelador_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
}
}
for (DetalleCatalogoReporte detalleCatalogoReporte : listCorrectivoAlimentacion) {
detalleCatalogoReporte.setDescripcion(detalleCatalogoReporte.getDescripcion().trim());
if (detalleCatalogoReporte.getTipoRepuesto() != null && !detalleCatalogoReporte.getTipoRepuesto().equals("") && detalleCatalogoReporte.getCodigoRepuesto() != null) {
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_PICKUP_ROLLER)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("pickup_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("pickup_s", SELECCIONAR);
}
parametros.put("pick_uproller_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("pickup_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_FEED_ROLLER)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("feed_roller_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("feed_roller_s", SELECCIONAR);
}
parametros.put("feed_roller_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("feed_roller_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_SEPARATION_ROLLER)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("separation_roller_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("separation_roller_s", SELECCIONAR);
}
parametros.put("sep_roller_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("separation_roller_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_UNIDAD_LASER)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("unidad_laser_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("unidad_laser_s", SELECCIONAR);
}
parametros.put("u_laser_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("unidad_laser_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
if (detalleCatalogoReporte.getDescripcion().equalsIgnoreCase(MC_REGULADOR_VOLTAJE)) {
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("regulador_voltaje_c", SELECCIONAR);
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("regulador_voltaje_s", SELECCIONAR);
}
parametros.put("r_voltaje_porc", detalleCatalogoReporte.getPorcentaje() != null ? detalleCatalogoReporte.getPorcentaje().toString().concat(" %") : null);
parametros.put("regulador_voltaje_code_rep", detalleCatalogoReporte.getCodigoRepuesto());
}
}
}
int c = 1;
for (DetalleCatalogoReporte detalleCatalogoReporte : otros) {
detalleCatalogoReporte.setDescripcion(detalleCatalogoReporte.getDescripcion().trim());
if (detalleCatalogoReporte.getTipoRepuesto() != null
&& !detalleCatalogoReporte.getTipoRepuesto().equals("")
&& !detalleCatalogoReporte.getDescripcion().equals("")) {
parametros.put("otros_" + c, detalleCatalogoReporte.getDescripcion());
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("C")) {
parametros.put("otros_c_" + c, "( " + SELECCIONAR + " )");
}
if (detalleCatalogoReporte.getTipoRepuesto().equalsIgnoreCase("S")) {
parametros.put("otros_s_" + c, "( " + SELECCIONAR + " )");
}
parametros.put("otros_cod_rep_" + c, detalleCatalogoReporte.getCodigoRepuesto());
}
c++;
}
return parametros;
}
}
|
package com.example.lablnet.quizapp;
import android.content.Context;
/**
* Created by lablnet on 9/23/2017.
*/
public class addQuestion {
Context context;
public addQuestion(Context context) {
this.context = context;
}
public void WriteData() {
DatabaseHelper databaseHelper;
Question_Data data;
databaseHelper = new DatabaseHelper(context);
data = new Question_Data("Which element is represented by symbol Au", "Titanium", "Gold", "Silver", "Gold");
databaseHelper.saveData(data);
data = new Question_Data("What is an example of a viral infection", "Polio", "Polio", "Cancer", "Polio");
databaseHelper.saveData(data);
data = new Question_Data("Which country sold Alaska to the USA in 1867", "Russia", "Canada", "Mexico", "Russia");
databaseHelper.saveData(data);
data = new Question_Data("Computer network is a collection of ___ connected togather", "Computers", "Machines", "Servers", "Computers");
databaseHelper.saveData(data);
data = new Question_Data("Android is an/a", "Operating system", "Programming language", "Vir" +
"" +
"tual machine", "Operating system");
databaseHelper.saveData(data);
data = new Question_Data("Which gas is highly flammable", "phosgene", "Carbon dioxide", "Hydrogen", "Hydrogen");
databaseHelper.saveData(data);
data = new Question_Data("Which US president was NOT assassinated", "James A.Garfield", "Hubert Hover", "Abraham Linoln", "Hubert Hover");
databaseHelper.saveData(data);
data = new Question_Data("What is the Largest living fish", "Whale shark", "Sunfiah", "Blue Whale", "Blue Whale");
databaseHelper.saveData(data);
data = new Question_Data("Who is the European inventor of movable type printing", "Friedrich Sciller", "Leoanrdo da Vinci", "Johannes Gutenberg", "Johannes Gutenberg");
databaseHelper.saveData(data);
data = new Question_Data("Google parent company is", "Google Inc", "Alphabet Inc", "Yahoo", "Alphabet Inc");
databaseHelper.saveData(data);
}
}
|
package Catalogue;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Formatter;
import java.util.Currency;
/**
* Holds a collection of products from the CatShop.
* @author Michael Alexander Smith
* @version 2.2
*
*/
public class Basket implements Serializable
{
private static final long serialVersionUID = 1;
private ArrayList<Product> theContents = new ArrayList<Product>(10);
/**
* Adds a product to the Basket.
*/
public void add( Product pr ) // Add a product to the
{ // product list
theContents.add( pr ); //
}
/**
* Returns the number of products held in the basket.
* @return number of products
*/
public int number() // Return the number of
{ // entries in the
return theContents.size(); // product list
}
/**
* The last product added (to the basket) is removed and returned.
* It is an error to attempt to remove a non existent product.
* @return product removed
*/
public Product remove() // Remove and return last item
{
int items = theContents.size();
if ( items < 1 )
throw new Error("EMPTY: Basket.remove()");
return theContents.remove( items-1 );
}
/**
* All items stored are removed.
*/
public void clear() // Clear the
{ // the product list
theContents.clear();
}
/**
* Returns a reference to a copy of the ArrayList that holds
* the products contained in the Basket.
* @return ArrayList of held products
*/
@SuppressWarnings("unchecked")
public ArrayList<Product> getProducts()
{
return (ArrayList<Product>)theContents.clone(); // return
}
/**
* Changes the contents of the Basket to that contained
* in the passed ArrayList.
* @param items - List of products
*/
@SuppressWarnings("unchecked")
public void setProducts( ArrayList<Product> items )
{
theContents = (ArrayList<Product>)items.clone(); // copy
}
/**
* Returns a string containing a description of all the products held.
* @return string description of products
*/
public String getDetails() // Return list of products as string
{
Locale uk = Locale.UK;
StringBuilder sb = new StringBuilder(256);
Formatter fr = new Formatter(sb, uk);
String csign = (Currency.getInstance( uk )).getSymbol();
double total = 0.00;
for ( Product pr: theContents )
{
int no = pr.getQuantity();
fr.format("%-7s", pr.getProductNo() );
fr.format("%-14.14s ", pr.getDescription() );
fr.format("(%3d) ", no );
fr.format("%s%7.2f", csign, pr.getPrice()*no );
fr.format("\n");
total += pr.getPrice() * no;
}
fr.format("----------------------------\n");
fr.format("Total ");
fr.format("%s%7.2f\n", csign, total );
return sb.toString();
}
}
|
package com.dassa.controller.guest;
import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dassa.mapper.UserMapper;
import com.dassa.service.UserService;
import com.dassa.vo.UserVO;
@Controller
@RequestMapping("/regCheck")
public class RegCheckController {
@Resource
private UserService userService;
//idCheck
/*@RequestMapping(value="/idChk.do")*/
@ResponseBody
@RequestMapping("/idChk")
public void idCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
String userId = request.getParameter("userId");
UserVO m = userService.idCheck(userId);
boolean result;
if(m != null) {
result = true;
}else {
result = false;
}
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
if(result) {
out.print("이미 사용중인 아이디 입니다.");
}else {
out.print("사용 가능한 아이디 입니다.");
}
}
}
|
package com.peternwerner.iagogame;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.util.Log;
public class Tutorial {
private static final String TAG = Tutorial.class.getSimpleName();
// constants
private int WIDTH, WIDTHactual;
private int HEIGHT;
private int spaceTop, widthRibbon, widthSquare, widthPages, buffer, widthThird, heightMode, spacer;
private int scaleOffset = MainGame.scaleOffset;
// paths
private int xPtsRibbons[][] = new int[3][4];
private int yPtsRibbons[][] = new int[3][4];
private boolean canProceed = false;
private int step = -1;
private int countClicks = 0;
Dots dotsObj = null;
Connectors connectorsObj = null;
//run when the object is first instantiated
public void init(Dots dotsObj, Connectors connectorsObj) {
// initialize variables
this.dotsObj = dotsObj;
this.connectorsObj = connectorsObj;
MainGame.n = 3;
dotsObj.init();
connectorsObj.init();
WIDTH = MainGame.WIDTH; HEIGHT = MainGame.HEIGHT; WIDTHactual = MainGame.WIDTHactual;
spaceTop = MainGame.distFromTopSquare - (int) (0.0520833 * HEIGHT); // subtract width of puzzle mode scoreboard
widthRibbon = (int) (0.065625 * HEIGHT);
widthPages = (int) (0.0520833 * HEIGHT);
widthSquare = MainGame.widthSquare;
buffer = MainGame.distBufferSide;
spacer = (int) (0.5 * (spaceTop - widthRibbon));
// Top ribbon
xPtsRibbons[0][0] = 0; yPtsRibbons[0][0] = spacer;
xPtsRibbons[0][1] = WIDTHactual; yPtsRibbons[0][1] = spacer;
xPtsRibbons[0][2] = WIDTHactual; yPtsRibbons[0][2] = widthRibbon + spacer;
xPtsRibbons[0][3] = 0; yPtsRibbons[0][3] = widthRibbon + spacer;
// Sub ribbon
xPtsRibbons[1][0] = WIDTHactual; yPtsRibbons[1][0] = spaceTop + MainGame.widthSquare + spacer + widthPages;
xPtsRibbons[1][1] = 0; yPtsRibbons[1][1] = spaceTop + MainGame.widthSquare + spacer + widthPages;
xPtsRibbons[1][2] = 0; yPtsRibbons[1][2] = widthRibbon + spaceTop + MainGame.widthSquare + spacer + widthPages;
xPtsRibbons[1][3] = WIDTHactual; yPtsRibbons[1][3] = widthRibbon + spaceTop + MainGame.widthSquare + spacer + widthPages;
// Bottom ribbon
xPtsRibbons[2][0] = 0; yPtsRibbons[2][0] = yPtsRibbons[1][2] + spacer;
xPtsRibbons[2][1] = WIDTHactual; yPtsRibbons[2][1] = yPtsRibbons[1][3] + spacer;
xPtsRibbons[2][2] = WIDTHactual; yPtsRibbons[2][2] = HEIGHT;
xPtsRibbons[2][3] = 0; yPtsRibbons[2][3] = HEIGHT;
nextStep();
}
// what we do when the user clicks on the screen...
public boolean checkClick(float x, float y) {
// user clicks on the proceed button
if(y >= yPtsRibbons[1][0] && y <= yPtsRibbons[1][2]) {
countClicks++;
if(canProceed)
nextStep();
return true;
}
// user clicks on dots
if(dotsObj != null && connectorsObj != null && dotsObj.checkClick(x, y, connectorsObj, dotsObj)) {
countClicks++;
if(checkWin())
canProceed = true;
}
return false;
}
// paint everything
public void paint(Canvas canvas) {
paintRibbons(canvas);
paintText(canvas);
connectorsObj.paintConnectors(canvas);
dotsObj.paintDots(canvas);
for(int i = 0; i < MainGame.tracerList.size(); i++)
MainGame.tracerList.get(i).paint(canvas);
}
// paint ribbons (for each step)
private void paintRibbons(Canvas canvas) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(MainGame.color_dark);
for(int i = 0; i < xPtsRibbons.length; i++) {
Path path = new Path();
path.moveTo(xPtsRibbons[i][0], yPtsRibbons[i][0]);
for(int j = 1; j < xPtsRibbons[i].length; j++) {
path.lineTo(xPtsRibbons[i][j], yPtsRibbons[i][j]);
}
path.close();
canvas.drawPath(path, paint);
}
}
// paint text
private void paintText(Canvas canvas) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setTypeface(MainGame.tf);
paint.setTextScaleX((float) 1.15);
paint.setTextAlign(Paint.Align.CENTER);
// paint ribbon text
paint.setTextSize(widthRibbon);
paint.setColor(MainGame.color_white);
canvas.drawText("How to Play", WIDTHactual / 2, (float) (yPtsRibbons[0][2] - (0.14 * widthRibbon)), paint);
if(!canProceed)
paint.setColor(MainGame.color_medium);
canvas.drawText("I'm Ready", WIDTHactual / 2, (float) (yPtsRibbons[1][2] - (0.14 * widthRibbon)), paint);
int textSize = WIDTH * 2 / 21;
// paint first step text
if(step == 0) {
paint.setTextSize(textSize);
paint.setColor(MainGame.color_medium);
canvas.drawText("Touch a dot to toggle", WIDTHactual / 2, spaceTop + (float) (textSize * 1.7), paint);
canvas.drawText("on (color) and off (grey)", WIDTHactual / 2, spaceTop + (float) (textSize * 2.6), paint);
paint.setTextSize((float) (textSize * 1.15));
paint.setColor(Color.rgb(195,161,149));
if(!canProceed)
canvas.drawText("Try it out!", WIDTHactual / 2, spaceTop + (float) (textSize * 4.2), paint);
else
canvas.drawText("You've got it!", WIDTHactual / 2, spaceTop + (float) (textSize * 4.2), paint);
paint.setTextSize(textSize);
paint.setColor(MainGame.color_medium);
canvas.drawText("A puzzle is solved when", WIDTHactual / 2, spaceTop + (float) (textSize * 8.6), paint);
canvas.drawText("All dots are colored", WIDTHactual / 2, spaceTop + (float) (textSize * 9.5), paint);
}
// paint second step text
else if(step == 1) {
paint.setTextSize(textSize);
paint.setColor(MainGame.color_medium);
canvas.drawText("Dots that are connected", WIDTHactual / 2, spaceTop + (float) (textSize * 1.7), paint);
canvas.drawText("Toggle with each other", WIDTHactual / 2, spaceTop + (float) (textSize * 2.6), paint);
paint.setTextSize((float) (textSize * 1.15));
paint.setColor(Color.rgb(195,161,149));
if(!canProceed)
canvas.drawText("Try it out!", WIDTHactual / 2, spaceTop + (float) (textSize * 4.2), paint);
else
canvas.drawText("Get it?", WIDTHactual / 2, spaceTop + (float) (textSize * 4.2), paint); }
}
// move to the next step
private void nextStep() {
countClicks = 0;
// start first step
if(step < 0) {
resetPuzzle();
dotsObj.matrix[0][1] = 0;
dotsObj.matrix[1][1] = 1;
dotsObj.matrix[2][1] = 0;
step = 0;
}
// start second step
else if(step == 0) {
resetPuzzle();
dotsObj.matrix[0][1] = 1;
dotsObj.matrix[0][2] = 1;
connectorsObj.connectorsVertical[0][1] = 1;
dotsObj.matrix[1][1] = 0;
dotsObj.matrix[2][1] = 0;
dotsObj.matrix[1][2] = 0;
dotsObj.matrix[2][2] = 0;
connectorsObj.connectorsHorizontal[1][1] = 1;
connectorsObj.connectorsHorizontal[1][2] = 1;
connectorsObj.connectorsVertical[1][1] = 1;
connectorsObj.connectorsVertical[2][1] = 1;
step = 1;
}
// tutorial is complete
else if(step > 0) {
resetPuzzle();
MainGame.gameState = 4;
MainGame.didTutorial = true;
}
canProceed = false;
}
// check if we can move to next step
private boolean checkWin() {
// second step: click 2 dots
if(step == 1) {
if(countClicks >= 2)
return true;
return false;
}
// first step: all dots must be colored
for(int i = 0; i < dotsObj.matrix.length; i++) {
for(int j = 0; j < dotsObj.matrix[i].length; j++) {
if(dotsObj.matrix[i][j] == 0)
return false;
}
}
return true;
}
// reset all puzzle values to -1
private void resetPuzzle() {
setAllMatrixValues(dotsObj.matrix, -1);
setAllMatrixValues(connectorsObj.connectorsDiagDown, -1);
setAllMatrixValues(connectorsObj.connectorsDiagUp, -1);
setAllMatrixValues(connectorsObj.connectorsHorizontal, -1);
setAllMatrixValues(connectorsObj.connectorsVertical, -1);
}
// helper method for resetPuzzle
private void setAllMatrixValues(int[][] matrix, int value) {
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = value;
}
}
}
}
|
package rent;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class CarDetails extends JFrame {
PreparedStatement pst;
Connection con;
ResultSet rs;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CarDetails frame = new CarDetails();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public CarDetails() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 690, 471);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("CarDetails");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 16));
lblNewLabel.setBounds(287, 11, 126, 14);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("CarId");
lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_1.setBounds(115, 74, 46, 14);
contentPane.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("CarName");
lblNewLabel_2.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_2.setBounds(115, 120, 66, 14);
contentPane.add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel("RegistrationNo");
lblNewLabel_3.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_3.setBounds(115, 167, 97, 14);
contentPane.add(lblNewLabel_3);
JLabel lblNewLabel_4 = new JLabel("CarType");
lblNewLabel_4.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_4.setBounds(115, 204, 97, 14);
contentPane.add(lblNewLabel_4);
JLabel lblNewLabel_5 = new JLabel("CarFare");
lblNewLabel_5.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_5.setBounds(115, 243, 66, 14);
contentPane.add(lblNewLabel_5);
JLabel lblNewLabel_6 = new JLabel("CarColour");
lblNewLabel_6.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_6.setBounds(115, 279, 66, 14);
contentPane.add(lblNewLabel_6);
JLabel lblNewLabel_7 = new JLabel("CarPaper");
lblNewLabel_7.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_7.setBounds(115, 315, 97, 14);
contentPane.add(lblNewLabel_7);
JButton btnNewButton = new JButton("Insert");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String sql = "insert into cardetails(CarId,CarName,RegistratioNo,CarType,CarFare,CarColour,CarPaper)values ( ?,?,?,?,?,?,?)";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/backend", "root","root");
pst = con.prepareStatement(sql);
String CarId = textField.getText();
pst.setString(1,CarId);
String CarName = textField_1.getText();
pst.setString(2,CarName);
String RegistrationNo = textField_2.getText();
pst.setString(3,RegistrationNo);
String CarType = textField_3.getText();
pst.setString(4,CarType);
String CarFare = textField_4.getText();
pst.setString(5,CarFare);
String CarColour = textField_5.getText();
pst.setString(6,CarColour);
String CarPaper = textField_6.getText();
pst.setString(7,CarPaper);
pst.executeUpdate();
//if(rs.next()) {
JOptionPane.showMessageDialog(null," inserted Sucessfully" );
/*}
else {
JOptionPane.showMessageDialog(null," not inserted Sucessfully" );
}*/
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex );
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 12));
btnNewButton.setBounds(181, 366, 89, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("Delete");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String sql = "delete from cardetails where CarId=? ";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/backend", "root","root");
pst = con.prepareStatement(sql);
String CarId = textField.getText();
pst.setString(1,CarId);
pst.executeUpdate();
JOptionPane.showMessageDialog(null," Deleted Sucessfully" );
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex );
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnNewButton_1.setFont(new Font("Tahoma", Font.BOLD, 12));
btnNewButton_1.setBounds(324, 366, 89, 23);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Update");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/backend", "root","root");
pst = con.prepareStatement("UPDATE cardetails SET CarFare=?,CarPaper=? where CarId=?");
String CarFare = textField_4.getText();
pst.setString(1,CarFare);
String CarPaper = textField_6.getText();
pst.setString(2,CarPaper);
String CarId = textField.getText();
pst.setString(3,CarId);
pst.executeUpdate();
System.out.print(pst);
JOptionPane.showMessageDialog(null," Updated Sucessfully" );
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex );
} catch (ClassNotFoundException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
});
btnNewButton_2.setFont(new Font("Tahoma", Font.BOLD, 12));
btnNewButton_2.setBounds(456, 366, 89, 23);
contentPane.add(btnNewButton_2);
textField = new JTextField();
textField.setBounds(304, 71, 131, 20);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(304, 117, 131, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(304, 164, 131, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(304, 201, 131, 20);
contentPane.add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(304, 240, 131, 20);
contentPane.add(textField_4);
textField_4.setColumns(10);
textField_5 = new JTextField();
textField_5.setBounds(304, 276, 131, 20);
contentPane.add(textField_5);
textField_5.setColumns(10);
textField_6 = new JTextField();
textField_6.setBounds(304, 312, 131, 20);
contentPane.add(textField_6);
textField_6.setColumns(10);
}
}
|
package com.ggtf.xieyingwu.demotest;
/**
* Created by xieyingwu on 2017/3/23.
*/
public class Son extends Father {
private int age;
public Son(String name) {
super(name);
}
}
|
/*
* 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 compiler.syntaxAnalyzer;
import static compiler.syntaxAnalyzer.SyntaxAnalyzer.tokenList;
import static compiler.syntaxAnalyzer.SyntaxAnalyzer.index;
/**
*
* @author Muhammad Huzaifa
*/
public class Array {
static boolean assign() {
if ("ID".equals(tokenList.get(index).getClassName())) {
index++;
if ("OSB".equals(tokenList.get(index).getClassName())) {
index++;
if (Expression.expression()) {
if ("CSB".equals(tokenList.get(index).getClassName())) {
index++;
return true;
}
return false;
}
index--;
return false;
}
index--;
return false;
}
return false;
}
}
|
package question.abstractQuestion;
import answer.Answer;
import answer.GiveNumberAnswer;
import question.Question;
public abstract class GiveNumberQuestion implements Question {
protected GiveNumberAnswer answer;
}
|
package com.deepakm.webservice.util;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Date;
public class PKIUtil {
private PKIUtil() {
}
public static void generateSelfSignedCertificate(
String domainName, String pathToKeyStore, String pathToCertificate, String keyStorePassword)
throws PKIException {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt(1000000000)));
v3CertGen.setIssuerDN(new X509Principal("CN=" + domainName + ", OU=None, O=None L=None, C=None"));
v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
v3CertGen.setSubjectDN(new X509Principal("CN=" + domainName + ", OU=None, O=None L=None, C=None"));
v3CertGen.setPublicKey(keyPair.getPublic());
v3CertGen.setSignatureAlgorithm("MD5WITHRSA");
X509Certificate publicKeyCertificate = v3CertGen.generate(keyPair.getPrivate());
FileOutputStream fos = new FileOutputStream(pathToCertificate);
fos.write(publicKeyCertificate.getEncoded());
fos.close();
KeyStore privateKS = KeyStore.getInstance("JKS");
privateKS.load(null /* fis */, keyStorePassword.toCharArray());
privateKS.setKeyEntry(domainName, keyPair.getPrivate(),
keyStorePassword.toCharArray(),
new java.security.cert.Certificate[]{publicKeyCertificate});
privateKS.store(new FileOutputStream(pathToKeyStore), keyStorePassword.toCharArray());
} catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException | IOException |
CertificateException | KeyStoreException ex) {
throw new PKIException(ex.getMessage(), ex);
}
}
public static void importCertToKeystore(String certificatePath, String keyStorePath, String keyStorePassword)
throws PKIException {
try {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
FileInputStream fis = new FileInputStream(certificatePath);
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
java.security.cert.Certificate cert = null;
while (bis.available() > 0) {
cert = cf.generateCertificate(bis);
ks.setCertificateEntry("SGCert", cert);
}
ks.setCertificateEntry("SGCert", cert);
ks.store(new FileOutputStream(keyStorePath), keyStorePassword.toCharArray());
} catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException e) {
throw new PKIException(e.getMessage(), e);
}
}
}
|
package model;
import java.util.Date;
public class WayBill {
private String w_num;
private Date w_regdate;
private String w_dtn;
private int m_num;
private String w_req;
private String sender_nm;
private String sender_tel;
private String sender_add;
private String receiver_nm;
private String receiver_tel;
private String receiver_add;
private String w_div;
private int w_weight;
private int n_start;
private int n_via;
private int n_end;
private String w_duedate;
private int c_num;
public String getW_duedate() {
return w_duedate;
}
public void setW_duedate(String w_duedate) {
this.w_duedate = w_duedate;
}
public String getW_num() {
return w_num;
}
public void setW_num(String w_num) {
this.w_num = w_num;
}
public Date getW_regdate() {
return w_regdate;
}
public void setW_regdate(Date w_regdate) {
this.w_regdate = w_regdate;
}
public String getW_dtn() {
return w_dtn;
}
public void setW_dtn(String w_dtn) {
this.w_dtn = w_dtn;
}
public int getM_num() {
return m_num;
}
public void setM_num(int m_num) {
this.m_num = m_num;
}
public String getW_req() {
return w_req;
}
public void setW_req(String w_req) {
this.w_req = w_req;
}
public String getSender_nm() {
return sender_nm;
}
public void setSender_nm(String sender_nm) {
this.sender_nm = sender_nm;
}
public String getSender_tel() {
return sender_tel;
}
public void setSender_tel(String sender_tel) {
this.sender_tel = sender_tel;
}
public String getSender_add() {
return sender_add;
}
public void setSender_add(String sender_add) {
this.sender_add = sender_add;
}
public String getReceiver_nm() {
return receiver_nm;
}
public void setReceiver_nm(String receiver_nm) {
this.receiver_nm = receiver_nm;
}
public String getReceiver_tel() {
return receiver_tel;
}
public void setReceiver_tel(String receiver_tel) {
this.receiver_tel = receiver_tel;
}
public String getReceiver_add() {
return receiver_add;
}
public void setReceiver_add(String receiver_add) {
this.receiver_add = receiver_add;
}
public String getW_div() {
return w_div;
}
public void setW_div(String w_div) {
this.w_div = w_div;
}
public int getW_weight() {
return w_weight;
}
public void setW_weight(int w_weight) {
this.w_weight = w_weight;
}
public int getN_start() {
return n_start;
}
public void setN_start(int n_start) {
this.n_start = n_start;
}
public int getN_via() {
return n_via;
}
public void setN_via(int n_via) {
this.n_via = n_via;
}
public int getN_end() {
return n_end;
}
public void setN_end(int n_end) {
this.n_end = n_end;
}
public int getC_num() {
return c_num;
}
public void setC_num(int c_num) {
this.c_num = c_num;
}
@Override
public String toString() {
return "WayBill [w_num=" + w_num + ", w_regdate=" + w_regdate + ", w_dtn=" + w_dtn + ", m_num=" + m_num
+ ", w_req=" + w_req + ", sender_nm=" + sender_nm + ", sender_tel=" + sender_tel + ", sender_add="
+ sender_add + ", receiver_nm=" + receiver_nm + ", receiver_tel=" + receiver_tel + ", receiver_add="
+ receiver_add + ", w_div=" + w_div + ", w_weight=" + w_weight + ", n_start=" + n_start + ", n_via="
+ n_via + ", n_end=" + n_end + ", w_duedate=" + w_duedate + ", c_num=" + c_num + "]";
}
}
|
package com.example.joker.newsapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.comix.overwatch.HiveProgressView;
import com.example.joker.newsapp.Adapter.NavAdapter;
import com.example.joker.newsapp.Adapter.PagerAdapter;
import com.example.joker.newsapp.Database.CRUDHelper;
import com.example.joker.newsapp.Database.SQLHelperClass;
import com.example.joker.newsapp.ModelClass.TopHeadlines;
import com.example.joker.newsapp.Utils.HttpHandler;
import com.example.joker.newsapp.Utils.NewsDataSet;
import com.example.joker.newsapp.Utils.ParseTopHeadline;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener, LoaderManager.LoaderCallbacks<String> , ClickListener{
private static final String API_KEY = "ded182f8057546f1b36f4cd3461219d4";
private static final String THE_TIMES_OF_INDIA = "the-times-of-india";
private static final int NEWS_LOADER = 121;
private static final String TAG = MainActivity.class.getSimpleName();
private Toast toast = null;
ArrayList<TopHeadlines> topHeadlines = new ArrayList<>();
private FragmentManager fm;
// private TopNewListAdapter topNewListAdapter;
private ViewPager viewPager;
private PagerAdapter pagerAdapter;
private LoaderManager loaderManager;
private SQLiteDatabase database;
private SQLHelperClass dbHelper;
//Instace of loadingAnimantion
private HiveProgressView hiveProgressView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get default shared preference instance
SharedPreferences preferences = android.support.v7.preference.PreferenceManager.getDefaultSharedPreferences(this);
loadPreferences(preferences);
//register the shared preference
preferences.registerOnSharedPreferenceChangeListener(MainActivity.this);
loaderManager = getSupportLoaderManager();
//getting database reference
dbHelper = new SQLHelperClass(this);
database = dbHelper.getWritableDatabase();
//topNewListAdapter = new TopNewListAdapter(this);
fm = getSupportFragmentManager();
pagerAdapter = new PagerAdapter(this,fm,CRUDHelper.getAllRecords(database));
viewPager = findViewById(R.id.newsViewPager);
//recyclerView.setLayoutManager(new LinearLayoutManager(this));
// recyclerView.setLayoutManager(new LinearLayoutManager(this));
// topNewListAdapter.swapAdapters(CRUDHelper.getAllRecords(database));
// recyclerView.setAdapter(topNewListAdapter);
// //Loading Animation
// insLoadingView = findViewById(R.id.loading_view);
// insLoadingView.setVisibility(View.GONE);
hiveProgressView = findViewById(R.id.hiveProgress);
hiveProgressView.setVisibility(View.GONE);
viewPager.setAdapter(pagerAdapter);
makeNetworkCall(THE_TIMES_OF_INDIA);
setupNavigationDrawer();
}
//setting up navigation drawer
private void setupNavigationDrawer() {
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
RecyclerView navList = findViewById(R.id.navList);
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL);
navList.setLayoutManager(staggeredGridLayoutManager);
NavAdapter navAdapter = new NavAdapter(this);
navList.setAdapter(navAdapter);
}
//method to handle initiate and restart of
private void makeNetworkCall(String source) {
Bundle queryBundle = new Bundle();
queryBundle.putString("SOURCE", source);
//Log.d(TAG, " source " + source);
hiveProgressView.setVisibility(View.VISIBLE);
Loader<String> newsLoader = loaderManager.getLoader(NEWS_LOADER);
if (newsLoader == null) {
loaderManager.initLoader(NEWS_LOADER, queryBundle, this).forceLoad();
} else {
loaderManager.restartLoader(NEWS_LOADER, queryBundle, this).forceLoad();
}
}
//to load the preferences
private void loadPreferences(SharedPreferences preferences) {
// boolean bname = preferences.getBoolean(getString(R.string.key_name), true);
//
// if (!bname)
// name.setVisibility(View.INVISIBLE);
// else
// name.setVisibility(View.VISIBLE);
}
//the create option menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
//to read clicks on OptionItems
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_setting) {
Intent intent = new Intent(MainActivity.this, SettingActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
//Override methods to detect preferenceChange
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
loadPreferences(sharedPreferences);
}
//methods to make async network calls
@Override
public Loader<String> onCreateLoader(int id, final Bundle args) {
return new AsyncTaskLoader<String>(this) {
@Override
public String loadInBackground() {
String source = args.getString("SOURCE");
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("newsapi.org")
.appendPath("v2")
.appendPath("top-headlines")
.appendQueryParameter("sources", source)
.appendQueryParameter("apiKey", API_KEY);
String url = builder.build().toString();
return HttpHandler.makeServiceCall(url);
}
};
}
@Override
public void onLoadFinished(Loader<String> loader, String response) {
hiveProgressView.setVisibility(View.GONE);
if (response == null) {
showToast("Check newtork connection.");
return;
}
topHeadlines.clear();
topHeadlines = ParseTopHeadline.parseTopHeadline(response);
CRUDHelper.dropAllRecord(database);
CRUDHelper.insertDataToDatabase(database, topHeadlines);
pagerAdapter = new PagerAdapter(getApplicationContext(),fm,CRUDHelper.getAllRecords(database));
//pagerAdapter.swapAdapters(CRUDHelper.getAllRecords(database));
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
}
@Override
public void onLoaderReset(Loader<String> loader) {
}
//method to show the toast
private void showToast(String s) {
if (toast != null)
toast.cancel();
toast = Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT);
toast.show();
}
@Override
public void DrawerClickListerner(String source) {
makeNetworkCall(source);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawers();
}
}
}
|
package com.zareca.factory.abstractfactory;
/**
* @Auther: ly
* @Date: 2020/10/10 22:59
* @Description:
*/
public class OvalSealsFactory implements ISealsFactory {
public IColor createColor() {
return new OvalColorSeal();
}
public IStar createStar() {
return new OvalStarSeal();
}
}
|
package net.shangtai.snmplights;
import android.os.AsyncTask;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.TextView;
import android.widget.Button;
import android.widget.SeekBar;
import android.support.v7.widget.RecyclerView;
import net.shangtai.snmplights.dataholders.*;
import android.util.Log;
class DevicesAdapter extends RecyclerView.Adapter<DevicesAdapter.ViewHolder> {
private final static int EMPTY = 0;
private final static int INVALID = 1;
private final static int SWITCH = 2;
private final static int DIMMER = 3;
private Context context;
private View.OnClickListener buttonListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
final View _v = v;
final ViewHolder viewHolder = (ViewHolder)_v.getTag();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Integer type = viewHolder.getType();
if (type == SWITCH) {
Switch device = (Switch)viewHolder.getDevice();
switch (_v.getId()) {
case R.id.on_button:
device.on();
break;
case R.id.off_button:
device.off();
break;
}
} else if (type == DIMMER) { // this can only ever be off
Dimmer device = (Dimmer)viewHolder.getDevice();
device.dim(0);
SeekBar sb = viewHolder.getView().findViewById(R.id.seekbar);
sb.setProgress(0);
}
}
});
t.start();
}
};
private SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(final SeekBar seekBar) {
final ViewHolder viewHolder = (ViewHolder)seekBar.getTag();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Dimmer device = (Dimmer)viewHolder.getDevice();
device.dim(seekBar.getProgress());
}
});
t.start();
}
};
private DeviceManager dm = null;
DevicesAdapter(Context context) {
setHasStableIds(true);
this.context = context;
refresh();
}
void refresh() {
new LoadDevicesTask(context, this).execute();
}
private boolean isValid() {
return dm != null && dm.isValid();
}
// Adapter methods
@Override
public int getItemCount() {
int count = 1; // invalid view
if (isValid()) {
count = dm.countDevices();
if (count == 0)
count = 1; // empty view
}
return count;
}
@Override
public int getItemViewType(int position) {
if (!isValid())
return INVALID;
Device device = dm.getDeviceByIndex(position);
if (device instanceof Switch) {
return SWITCH;
} else if (device instanceof Dimmer) {
return DIMMER;
}
return EMPTY;
}
@Override
public long getItemId(int position) {
return position; // there's a 1:1 relationship between position and device index (the id)
}
@Override
public DevicesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout;
Log.d(SNMPLightsActivity.TAG, "The view type is " + Integer.valueOf(viewType).toString());
switch (viewType) {
default:
case EMPTY:
layout = R.layout.empty;
break;
case INVALID:
layout = R.layout.invalid;
break;
case SWITCH:
layout = R.layout.toggle;
break;
case DIMMER:
layout = R.layout.dimmer;
break;
}
final View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
final ViewHolder holder = new ViewHolder(v, viewType);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Integer type = holder.getType();
// short circuit for invalid and empty types
if (type == INVALID || type == EMPTY)
return;
Device device = dm.getDeviceByIndex(position);
holder.setDevice(device);
View base = holder.getView();
TextView title = base.findViewById(R.id.title);
title.setText(device.getName());
Button on = base.findViewById(R.id.on_button);
Button off = base.findViewById(R.id.off_button);
SeekBar sb = base.findViewById(R.id.seekbar);
// they all have off buttons
off.setTag(holder);
off.setOnClickListener(buttonListener);
if (on != null) {
on.setTag(holder);
on.setOnClickListener(buttonListener);
}
if (sb != null) {
sb.setTag(holder);
sb.setMax(255);
sb.setProgress(Integer.valueOf(device.getValue()));
sb.setOnSeekBarChangeListener(seekBarChangeListener);
}
}
class ViewHolder extends RecyclerView.ViewHolder {
View view;
private Integer type;
private Device device;
ViewHolder(View view, Integer type) {
super(view);
setView(view);
setType(type);
}
void setView(View view) {
this.view = view;
}
View getView() {
return view;
}
void setType(int type) {
this.type = type;
}
int getType() {
return type;
}
void setDevice(Device device) {
this.device = device;
}
Device getDevice() {
return device;
}
}
private class LoadDevicesTask extends AsyncTask<Void, Void, DeviceManager> {
Context context;
RecyclerView.Adapter adapter;
LoadDevicesTask(Context context, RecyclerView.Adapter adapter) {
this.adapter = adapter;
this.context = context;
}
protected DeviceManager doInBackground(Void... none) {
return new DeviceManager(context);
}
protected void onPostExecute(DeviceManager result) {
dm = result;
adapter.notifyDataSetChanged();
}
}
}
|
import java.util.*;
class Student{
int rollno;
String name;
static String colname;
void display(){
int x=10;
System.out.println(name +" "+ rollno);
}
}
class Static1{
public static void main(String[] args){
Student s1=new Student();
Student s2=new Student();
s2.display();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.inbio.ara.dto.format;
import java.util.GregorianCalendar;
import org.inbio.ara.dto.BaseEntityOrDTOFactory;
import org.inbio.ara.persistence.format.FuncionalityType;
import org.inbio.ara.persistence.format.ReportLayout;
/**
*
* @author pcorrales
*/
public class ReportLayoutDTOFactory extends BaseEntityOrDTOFactory<ReportLayout,ReportLayoutDTO>{
@Override
public ReportLayout getEntityWithPlainValues(ReportLayoutDTO dto) {
if(dto == null) return null;
ReportLayout result = new ReportLayout();
result.setReportLayoutId(dto.getReportLayoutId());
result.setContents(dto.getContents());
result.setDescription(dto.getDescription());
result.setReportLayoutKeyWord(dto.getReportLayoutkeyWord());
result.setCreatedBy(dto.getUserName());
result.setFuncionalityTypeId( new FuncionalityType(dto.getFuncionalityTypeId()));
result.setLastModificationDate(new GregorianCalendar());
return result;
}
@Override
public ReportLayout updateEntityWithPlainValues(ReportLayoutDTO dto, ReportLayout e) {
if(dto == null || e == null) return null;
e.setReportLayoutId(dto.getReportLayoutId());
e.setContents(dto.getContents());
e.setReportLayoutKeyWord(dto.getReportLayoutkeyWord());
e.setDescription(dto.getDescription());
e.setCreatedBy(dto.getUserName());
e.setFuncionalityTypeId( new FuncionalityType(dto.getFuncionalityTypeId()));
e.setLastModificationDate(new GregorianCalendar());
return e;
}
/**
* create the LabelDTO with the information of entity label
* @param entity
* @return
*/
public ReportLayoutDTO createDTO(ReportLayout entity) {
if(entity == null) return null;
ReportLayoutDTO result = new ReportLayoutDTO();
result.setReportLayoutId(entity.getReportLayoutId());
result.setContents(entity.getContents());
result.setDescription(entity.getDescription());
result.setReportLayoutkeyWord(entity.getReportLayoutKeyWord());
result.setFuncionalityTypeId(entity.getFuncionalityTypeId().getFuncionalityTypeId());
result.setSelected(false); //Initially must be false
result.setFinalTimestand(entity.getLastModificationDate());
return result;
}
}
|
package ObserverDesignPattern;
/**
* Created by Frank Fang on 8/25/18.
*/
public interface IStateObserver {
void onStateChange();
}
|
public class StaticSynchronization {
public static void main(String[] args) {
Table5 table1 = new Table5();
Table5 table2 = new Table5();
Thread t1 = new MyThread1(table1);
Thread t2 = new MyThread1(table1);
Thread t3 = new MyThread2(table2);
Thread t4 = new MyThread2(table2);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Table5 {
synchronized static void printTable(int n) {
for (int i = 1; i <= 10; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
}
}
}
}
class MyThread1 extends Thread {
Table5 table;
public MyThread1(Table5 table) {
this.table = table;
}
public void run() {
table.printTable(1);
}
}
class MyThread2 extends Thread {
Table5 table;
public MyThread2(Table5 table) {
this.table = table;
}
public void run() {
table.printTable(100);
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.filter;
import java.io.IOException;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.util.WebUtils;
/**
* Filter base class that aims to guarantee a single execution per request
* dispatch, on any servlet container. It provides a {@link #doFilterInternal}
* method with HttpServletRequest and HttpServletResponse arguments.
*
* <p>A filter may be invoked as part of a
* {@link jakarta.servlet.DispatcherType#REQUEST REQUEST} or
* {@link jakarta.servlet.DispatcherType#ASYNC ASYNC} dispatches that occur in
* separate threads. A filter can be configured in {@code web.xml} whether it
* should be involved in async dispatches. However, in some cases servlet
* containers assume different default configuration. Therefore, subclasses can
* override the method {@link #shouldNotFilterAsyncDispatch()} to declare
* statically if they should indeed be invoked, <em>once</em>, during both types
* of dispatches in order to provide thread initialization, logging, security,
* and so on. This mechanism complements and does not replace the need to
* configure a filter in {@code web.xml} with dispatcher types.
*
* <p>Subclasses may use {@link #isAsyncDispatch(HttpServletRequest)} to
* determine when a filter is invoked as part of an async dispatch, and use
* {@link #isAsyncStarted(HttpServletRequest)} to determine when the request
* has been placed in async mode and therefore the current dispatch won't be
* the last one for the given request.
*
* <p>Yet another dispatch type that also occurs in its own thread is
* {@link jakarta.servlet.DispatcherType#ERROR ERROR}. Subclasses can override
* {@link #shouldNotFilterErrorDispatch()} if they wish to declare statically
* if they should be invoked <em>once</em> during error dispatches.
*
* <p>The {@link #getAlreadyFilteredAttributeName} method determines how to
* identify that a request is already filtered. The default implementation is
* based on the configured name of the concrete filter instance.
*
* @author Juergen Hoeller
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 06.12.2003
*/
public abstract class OncePerRequestFilter extends GenericFilterBean {
/**
* Suffix that gets appended to the filter name for the
* "already filtered" request attribute.
* @see #getAlreadyFilteredAttributeName
*/
public static final String ALREADY_FILTERED_SUFFIX = ".FILTERED";
/**
* This {@code doFilter} implementation stores a request attribute for
* "already filtered", proceeding without filtering again if the
* attribute is already there.
* @see #getAlreadyFilteredAttributeName
* @see #shouldNotFilter
* @see #doFilterInternal
*/
@Override
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (!((request instanceof HttpServletRequest httpRequest) && (response instanceof HttpServletResponse httpResponse))) {
throw new ServletException("OncePerRequestFilter only supports HTTP requests");
}
String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
boolean hasAlreadyFilteredAttribute = request.getAttribute(alreadyFilteredAttributeName) != null;
if (skipDispatch(httpRequest) || shouldNotFilter(httpRequest)) {
// Proceed without invoking this filter...
filterChain.doFilter(request, response);
}
else if (hasAlreadyFilteredAttribute) {
if (DispatcherType.ERROR.equals(request.getDispatcherType())) {
doFilterNestedErrorDispatch(httpRequest, httpResponse, filterChain);
return;
}
// Proceed without invoking this filter...
filterChain.doFilter(request, response);
}
else {
// Do invoke this filter...
request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
try {
doFilterInternal(httpRequest, httpResponse, filterChain);
}
finally {
// Remove the "already filtered" request attribute for this request.
request.removeAttribute(alreadyFilteredAttributeName);
}
}
}
private boolean skipDispatch(HttpServletRequest request) {
if (isAsyncDispatch(request) && shouldNotFilterAsyncDispatch()) {
return true;
}
if (request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE) != null && shouldNotFilterErrorDispatch()) {
return true;
}
return false;
}
/**
* The dispatcher type {@code jakarta.servlet.DispatcherType.ASYNC} means a
* filter can be invoked in more than one thread over the course of a single
* request. This method returns {@code true} if the filter is currently
* executing within an asynchronous dispatch.
* @param request the current request
* @since 3.2
* @see WebAsyncManager#hasConcurrentResult()
*/
protected boolean isAsyncDispatch(HttpServletRequest request) {
return DispatcherType.ASYNC.equals(request.getDispatcherType());
}
/**
* Whether request processing is in asynchronous mode meaning that the
* response will not be committed after the current thread is exited.
* @param request the current request
* @since 3.2
* @see WebAsyncManager#isConcurrentHandlingStarted()
*/
protected boolean isAsyncStarted(HttpServletRequest request) {
return WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted();
}
/**
* Return the name of the request attribute that identifies that a request
* is already filtered.
* <p>The default implementation takes the configured name of the concrete filter
* instance and appends ".FILTERED". If the filter is not fully initialized,
* it falls back to its class name.
* @see #getFilterName
* @see #ALREADY_FILTERED_SUFFIX
*/
protected String getAlreadyFilteredAttributeName() {
String name = getFilterName();
if (name == null) {
name = getClass().getName();
}
return name + ALREADY_FILTERED_SUFFIX;
}
/**
* Can be overridden in subclasses for custom filtering control,
* returning {@code true} to avoid filtering of the given request.
* <p>The default implementation always returns {@code false}.
* @param request current HTTP request
* @return whether the given request should <i>not</i> be filtered
* @throws ServletException in case of errors
*/
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
return false;
}
/**
* The dispatcher type {@code jakarta.servlet.DispatcherType.ASYNC} means a
* filter can be invoked in more than one thread over the course of a single
* request. Some filters only need to filter the initial thread (e.g. request
* wrapping) while others may need to be invoked at least once in each
* additional thread for example for setting up thread locals or to perform
* final processing at the very end.
* <p>Note that although a filter can be mapped to handle specific dispatcher
* types via {@code web.xml} or in Java through the {@code ServletContext},
* servlet containers may enforce different defaults with respect to
* dispatcher types. This flag enforces the design intent of the filter.
* <p>The default return value is "true", which means the filter will not be
* invoked during subsequent async dispatches. If "false", the filter will
* be invoked during async dispatches with the same guarantees of being
* invoked only once during a request within a single thread.
* @since 3.2
*/
protected boolean shouldNotFilterAsyncDispatch() {
return true;
}
/**
* Whether to filter error dispatches such as when the servlet container
* processes and error mapped in {@code web.xml}. The default return value
* is "true", which means the filter will not be invoked in case of an error
* dispatch.
* @since 3.2
*/
protected boolean shouldNotFilterErrorDispatch() {
return true;
}
/**
* Same contract as for {@code doFilter}, but guaranteed to be
* just invoked once per request within a single request thread.
* See {@link #shouldNotFilterAsyncDispatch()} for details.
* <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
* default ServletRequest and ServletResponse ones.
*/
protected abstract void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException;
/**
* Typically an ERROR dispatch happens after the REQUEST dispatch completes,
* and the filter chain starts anew. On some servers however the ERROR
* dispatch may be nested within the REQUEST dispatch, e.g. as a result of
* calling {@code sendError} on the response. In that case we are still in
* the filter chain, on the same thread, but the request and response have
* been switched to the original, unwrapped ones.
* <p>Sub-classes may use this method to filter such nested ERROR dispatches
* and re-apply wrapping on the request or response. {@code ThreadLocal}
* context, if any, should still be active as we are still nested within
* the filter chain.
* @since 5.1.9
*/
protected void doFilterNestedErrorDispatch(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(request, response);
}
}
|
package dk.webbies.tscreate.cleanup.heuristics;
import com.google.common.collect.ArrayListMultimap;
import dk.webbies.tscreate.analysis.declarations.types.DeclarationType;
import dk.webbies.tscreate.analysis.declarations.types.InterfaceDeclarationType;
import dk.webbies.tscreate.analysis.declarations.types.UnnamedObjectType;
import java.util.Set;
/**
* Created by Erik Krogh Kristensen on 16-03-2016.
*/
public class HeuristicsUtil {
public static int numberOfFields(DeclarationType type) {
if (type instanceof UnnamedObjectType) {
return ((UnnamedObjectType) type).getDeclarations().size();
} else if (type instanceof InterfaceDeclarationType) {
UnnamedObjectType object = ((InterfaceDeclarationType) type).getObject();
if (object == null) {
return 0;
}
return numberOfFields(object);
}
throw new RuntimeException("Whut?");
}
public static boolean hasDynAccess(DeclarationType type) {
if (type instanceof UnnamedObjectType) {
return false;
} else if (type instanceof InterfaceDeclarationType) {
return ((InterfaceDeclarationType) type).getDynamicAccess() != null;
}
throw new RuntimeException("Wut?!?");
}
public static boolean hasObject(DeclarationType type) {
if (type instanceof UnnamedObjectType) {
return true;
} else if (type instanceof InterfaceDeclarationType) {
return ((InterfaceDeclarationType) type).getObject() != null;
}
throw new RuntimeException("What???");
}
public static void combine(DeclarationType inter1, DeclarationType inter2, ArrayListMultimap<DeclarationType, DeclarationType> replacements, Set<DeclarationType> heap) {
if (heap.contains(inter1) && heap.contains(inter2)) {
replacements.put(inter1, inter2);
replacements.put(inter2, inter1);
} else if (heap.contains(inter1)) {
replacements.put(inter2, inter1);
} else if (heap.contains(inter2)) {
replacements.put(inter1, inter2);
} else {
replacements.put(inter1, inter2);
replacements.put(inter2, inter1);
}
}
public static boolean hasFunction(DeclarationType type) {
if (type instanceof UnnamedObjectType) {
return false;
} else if (type instanceof InterfaceDeclarationType) {
return ((InterfaceDeclarationType) type).getFunction() != null;
}
throw new RuntimeException("Wit!?!?");
}
}
|
package estudo1.model.vo;
public class PessoaVo {
private int idPessoa;
private String nome;
private String cpf;
private int telefone;
private String sexo;
private double salario;
public PessoaVo() {
super();
// TODO Auto-generated constructor stub
}
public PessoaVo(String nome, String cpf, int telefone, String sexo, double salario) {
super();
this.nome = nome;
this.cpf = cpf;
this.telefone = telefone;
this.sexo = sexo;
this.salario = salario;
}
public int getIdPessoa() {
return idPessoa;
}
public void setIdPessoa(int idPessoa) {
this.idPessoa = idPessoa;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public int getTelefone() {
return telefone;
}
public void setTelefone(int telefone) {
this.telefone = telefone;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public double getSalario() {
return salario;
}
public void setSalario(double salario) {
this.salario = salario;
}
}
|
import java.util.List;
public class Airports {
private List<Airport> airports;
public List<Airport> getAirports() {
return airports;
}
}
|
package sop.filegen.jasperreport;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.File;
import java.io.IOException;
import net.sf.jasperreports.engine.DefaultJasperReportsContext;
import net.sf.jasperreports.engine.JRFont;
import net.sf.jasperreports.engine.JRPropertiesUtil;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperReportsContext;
import net.sf.jasperreports.engine.fonts.FontFace;
import net.sf.jasperreports.engine.fonts.FontUtil;
import net.sf.jasperreports.engine.util.JRStyledText;
/**
* @Author: LCF
* @Date: 2020/1/9 9:32
* @Package: sop.filegen.jasperreport
*/
public class AbsolutePathSimpleFontFace implements FontFace {
private String file;
private Font font;
public AbsolutePathSimpleFontFace(JasperReportsContext jasperReportsContext, String file) {
this.file = file;
// InputStream is = null;
// try
// {
// is = RepositoryUtil.getInstance(jasperReportsContext).getInputStreamFromLocation(file);
// }
// catch(JRException e)
// {
// throw new JRRuntimeException(e);
// }
//
try {
font = Font.createFont(Font.TRUETYPE_FONT, new File(file));
} catch (FontFormatException e) {
throw new JRRuntimeException(e);
} catch (IOException e) {
throw new JRRuntimeException(e);
} finally {
// try
// {
// is.close();
// }
// catch (IOException e)
// {
// }
}
}
/**
* @see #SimpleFontFace(JasperReportsContext, String)
*/
public AbsolutePathSimpleFontFace(String file) {
this(DefaultJasperReportsContext.getInstance(), file);
}
public AbsolutePathSimpleFontFace(Font font) {
this.font = font;
}
public static AbsolutePathSimpleFontFace getInstance(JasperReportsContext jasperReportsContext, String fontName) {
AbsolutePathSimpleFontFace fontFace = null;
if (fontName != null) {
if (fontName.trim().toUpperCase().endsWith(".TTF")) {
fontFace = new AbsolutePathSimpleFontFace(fontName);
} else {
FontUtil.getInstance(jasperReportsContext).checkAwtFont(fontName, JRPropertiesUtil.getInstance(jasperReportsContext).getBooleanProperty(JRStyledText.PROPERTY_AWT_IGNORE_MISSING_FONT));
fontFace = new AbsolutePathSimpleFontFace(new Font(fontName, Font.PLAIN, JRPropertiesUtil.getInstance(jasperReportsContext).getIntegerProperty(JRFont.DEFAULT_FONT_SIZE)));
}
}
return fontFace;
}
public String getName() {
//(String)font.getAttributes().get(TextAttribute.FAMILY);
return font.getName();
}
public String getFile() {
return file;
}
public Font getFont() {
return font;
}
@Override
public String getEot() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getPdf() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getSvg() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getTtf() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getWoff() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.itheima.mapper;
import com.itheima.domain.User;
import java.util.List;
public interface UserMapper {
List<User> listAll();
User getById(Long id);
}
|
package de.haw.wpcgar.structure.biomes;
import de.haw.wpcgar.generator.WorldGenerator;
import de.haw.wpcgar.structure.Biome;
import de.haw.wpcgar.structure.params.HeightMap;
import edu.hawhamburg.shared.math.Vector;
public class Plain extends Biome {
public Plain(WorldGenerator generator) {
super(generator, new Vector(0, 1, 0, "plain"));
}
@Override
public boolean check(double x, double y) {
double height = getValue(HeightMap.class, x, y);
return height <= 0.7;
}
@Override
public Vector getColor() {
return color;
}
}
|
package test.m2;
public class P {
//年货节1折抢爆品Redmi AirDots真无线蓝牙耳机 黑色 : 99
static public String P_AIRDOT_99 = "Yeo-esIE7vOuqBfZeMX90hBNjJRRJOY23b0vQkVP0YKf0LH_vy2oFkB1p3-6OP3xPL7XQMmrolBRGlia6siM3DdA9WaVE9EqT70K_STOMU0=";
//年货节1折抢爆品米家空气净化器3 白色 : 899
static public String P_JINGHUAQI_899 = "Yeo-esIE7vOuqBfZeMX90hBNjJRRJOY23b0vQkVP0YIUsSR7YsZObWOMUfEBFGnIYgqLVP4ub0wS0WudbbTuTqfX3nsmcFaJLqLzl2w9vxs=";
//年货节1折抢爆品米家毛球修剪器 白色 : 39
static public String P_MAORONG_39 = "Yeo-esIE7vOuqBfZeMX90hBNjJRRJOY23b0vQkVP0YK60BfPxny25aP2zzqjXwhnw7MP8_FehEMfI2kosfLZncHhnfFDUvav-N_1NhK2MRQ=";
//年货节1折抢爆品小米手环3 NFC版 : 159
static public String P_SHOUHUAN_159 = "Yeo-esIE7vOuqBfZeMX90hBNjJRRJOY23b0vQkVP0YLbFYCvKPyHw6Gomp79LN67JJjdknt04TASa_llbGACUXaRor_xJk8gWw_lcoKFmfg=";
//年货节1折抢爆品小米小背包 //29
static public String P_BEIBAO_29 = "Yeo-esIE7vOuqBfZeMX90hBNjJRRJOY23b0vQkVP0YJ0ZRxAXVgq_6IiIOQKGRSR6TbVlsJfsh_vr4hDeYnxDI48uh4xZKT9gVBNhOLhkRo=";
// 年货节1折抢爆品小米降噪耳机Type-C版 黑色 : 149
static public String P_TYPEC_149 = "Yeo-esIE7vOuqBfZeMX90hBNjJRRJOY23b0vQkVP0YKz0WO1NlxDuSw6gmbcQ1R56PUUlFk0km53y1mYxmrV6YdpNReY1LVg4E6QO_xvrRM=";
static public String Q_300 =
"Yeo-esIE7vOuqBfZeMX90hBNjJRRJOY23b0vQkVP0YJ6zL0gCHHHFmohw_HjszvYz3M2o0nMmc2dF3C__rPQkyqwYe8GUTHYftyLi1DJugc%3D";//20027
static public String Q_500 = "Yeo-esIE7vOuqBfZeMX90hBNjJRRJOY23b0vQkVP0YIXTAuB7ZmaRpOGhZlD6gDG1yp_uXbzzhp23-ieytw0oPLMZ2nRr6_sWnIwlCbdWDk=";//207
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
package com.solr.test;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;
public class TestSolrCloud {
@Test
public void testsolrCloud() {
try{
// 第一步:把solrJ相关的jar包添加到工程中。
// 第二步:创建一个SolrServer对象,需要使用CloudSolrServer子类。构造方法的参数是zookeeper的地址列表。
CloudSolrServer solrServer = new CloudSolrServer("192.168.208.40:2182,192.168.208.40:2183,192.168.208.40:2184");
// 第三步:需要设置DefaultCollection属性。
solrServer.setDefaultCollection("collection2");
// 第四步:创建一SolrInputDocument对象。
SolrInputDocument document = new SolrInputDocument();
// 第五步:向文档对象中添加域
document.addField("item_title", "测试商品");
document.addField("item_price", "100");
document.addField("id", "test001");
// 第六步:把文档对象写入索引库。
solrServer.add(document);
// 第七步:提交。
solrServer.commit();
}catch(Exception e) {
e.printStackTrace();
}
}
@Test
public void test(){
System.out.println("a" + "b");
}
}
|
package unit2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/testtrang"})
public class vd2 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.println("He Thong Dang Bao Tri! Moi Ban Quay Lai Sau.");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
}
|
package be.openclinic.sync;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import be.mxs.common.model.vo.healthrecord.HealthRecordVO;
import be.mxs.common.model.vo.healthrecord.ItemVO;
import be.mxs.common.model.vo.healthrecord.TransactionVO;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.Debug;
import be.mxs.common.util.system.Pointer;
import be.mxs.common.util.system.ScreenHelper;
import be.openclinic.medical.RequestedLabAnalysis;
import be.openclinic.system.Encryption;
import net.admin.AdminPerson;
public class GHBNetwork {
public static void readMessages() {
if(MedwanQuery.getInstance().getConfigString("ghb_ref_serverid","").trim().length()==0) {
return;
}
try {
Debug.println("Getting GHB message count from "+MedwanQuery.getInstance().getConfigString("ghb_ref_countmessagesurl","http://www.globalhealthbarometer.net/globalhealthbarometer/util/getGHBMessageCount.jsp"));
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(MedwanQuery.getInstance().getConfigString("ghb_ref_countmessagesurl","http://www.globalhealthbarometer.net/globalhealthbarometer/util/getGHBMessageCount.jsp"));
Part[] parts= {
new StringPart("serverid",MedwanQuery.getInstance().getConfigString("ghb_ref_serverid","")),
new StringPart("project",MedwanQuery.getInstance().getConfigString("defaultProject",""))
};
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
client.executeMethod(method);
String sResponse = IOUtils.toString(method.getResponseBodyAsStream(), StandardCharsets.UTF_8);
if(sResponse.contains("<messages")){
Document document=DocumentHelper.parseText(sResponse.substring(sResponse.indexOf("<messages")));
Element root = document.getRootElement();
Debug.println("Received message count: "+root.attributeValue("count"));
if(ScreenHelper.checkString(root.attributeValue("count")).length()>0) {
if(Integer.parseInt(root.attributeValue("count"))>0) {
//Read all the messages
method = new PostMethod(MedwanQuery.getInstance().getConfigString("ghb_ref_readmessagesurl","http://www.globalhealthbarometer.net/globalhealthbarometer/util/readGHBMessages.jsp"));
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
client.executeMethod(method);
Debug.println("Retrieving GHB message list from "+MedwanQuery.getInstance().getConfigString("ghb_ref_readmessagesurl","http://www.globalhealthbarometer.net/globalhealthbarometer/util/readGHBMessages.jsp"));
sResponse = IOUtils.toString(method.getResponseBodyAsStream(), StandardCharsets.UTF_8);
if(sResponse.contains("<messages")){
document=DocumentHelper.parseText(sResponse.substring(sResponse.indexOf("<messages")));
root = document.getRootElement();
Iterator iMessages = root.elementIterator("message");
while(iMessages.hasNext()) {
Element message = (Element)iMessages.next();
String messageid = message.attributeValue("id");
Debug.println("Retrieving message id "+messageid);
//Now load this message
method = new PostMethod(MedwanQuery.getInstance().getConfigString("ghb_ref_readmessageurl","http://www.globalhealthbarometer.net/globalhealthbarometer/util/readGHBMessage.jsp"));
Part[] parts2= {
new StringPart("messageid",messageid)
};
method.setRequestEntity(new MultipartRequestEntity(parts2, method.getParams()));
client.executeMethod(method);
sResponse = IOUtils.toString(method.getResponseBodyAsStream(), StandardCharsets.UTF_8);
if(sResponse.contains("<message")){
Debug.println("Received message id "+messageid);
document=DocumentHelper.parseText(sResponse.substring(sResponse.indexOf("<message")));
root = document.getRootElement();
String targetserverid = root.elementText("targetserverid");
String sourceserverid = root.elementText("sourceserverid");
String encryptedData = root.elementText("data");
String encryptedToken = root.elementText("token");
Debug.println("ENC-- Decrypting token with private key");
Debug.println("ENC-- Encrypted token = "+encryptedToken);
String token = Encryption.decryptTextWithPrivateKey(encryptedToken, MedwanQuery.getInstance().getConfigString("ghb_ref_privkey"));
Debug.println("ENC-- Decrypted token = "+token);
Debug.println("ENC-- Decrypting text with token");
String data = Encryption.decryptTextSymmetric(encryptedData, token);
//For security reasons: check that this server is indeed the intended target
Debug.println("Target server "+MedwanQuery.getInstance().getConfigString("ghb_ref_serverid","")+" = "+targetserverid);
if(MedwanQuery.getInstance().getConfigString("ghb_ref_serverid","").equalsIgnoreCase(targetserverid)) {
Debug.println("Source server "+MedwanQuery.getInstance().getConfigString("ghb_ref_serverid","")+" <> "+sourceserverid);
//We don't want to treat messages that come from ourselves
if(!MedwanQuery.getInstance().getConfigString("ghb_ref_serverid","").equalsIgnoreCase(sourceserverid)) {
//Now integrate the message into the medical record system
//Replace the serverid in every record by the serverid of the source server
Debug.println("Integrating message");
document=DocumentHelper.parseText(data);
Element record = document.getRootElement();
Element patient = record.element("person");
String personid="";
if(ScreenHelper.checkString(patient.attributeValue("destpersonid")).length()>0) {
personid=patient.attributeValue("destpersonid");
if(personid.length()>0 && AdminPerson.getAdminPerson(personid).lastname.length()==0) {
//The destination personid does not exist (anymore)
personid="";
}
}
AdminPerson person = new AdminPerson();
person.fromXmlElement(patient, true);
String pointer="GHB.PATIENTREF."+sourceserverid+"."+person.personid;
if(personid.length()==0) {
//First match based on pointer
personid=Pointer.getPointer(pointer);
if(personid.length()>0 && AdminPerson.getAdminPerson(personid).lastname.length()==0) {
personid="";
}
}
if(personid.length()>0 && Pointer.getPointer("GHB.PATIENTBACKREF."+sourceserverid+"."+personid).length()==0) {
Pointer.storePointer("GHB.PATIENTBACKREF."+sourceserverid+"."+personid,person.personid);
}
if(MedwanQuery.getInstance().getConfigInt("enableGHBMatchOnNatreg",0)==1 && personid.length()==0 && person.getID("natreg").length()>0) {
//Match patient on natreg and name and firstname
personid = AdminPerson.getUniquePersonIdByNatReg(person.getID("natreg"));
if(personid!=null) {
AdminPerson dbPerson = AdminPerson.getAdminPerson(personid);
if(!dbPerson.lastname.equalsIgnoreCase(person.lastname) || !dbPerson.firstname.equalsIgnoreCase(person.firstname)) {
personid="";
}
if(personid.length()>0) {
Pointer.storePointer(pointer, personid);
Pointer.storePointer("GHB.PATIENTBACKREF."+sourceserverid+"."+personid,person.personid);
}
}
else {
personid="";
}
}
if(MedwanQuery.getInstance().getConfigInt("enableGHBMatchOnNameAndDateOfBirth",1)==1 && personid.length()==0 && person.lastname.length()>0 && person.firstname.length()>0 && person.dateOfBirth.length()>0) {
//Match patient on lastname, firstname and date of birth
Hashtable hSelect = new Hashtable();
hSelect.put(" lastname = ? AND",person.lastname);
hSelect.put(" firstname = ? AND",person.firstname);
hSelect.put(" dateofbirth = ? AND",person.dateOfBirth);
personid = ScreenHelper.checkString(AdminPerson.getUniquePersonIdBySearchNameDateofBirth(hSelect));
if(personid.length()>0) {
pointer="GHB.PATIENTREF."+sourceserverid+"."+person.personid;
Pointer.storePointer(pointer, personid);
Pointer.storePointer("GHB.PATIENTBACKREF."+sourceserverid+"."+personid,person.personid);
}
}
if(personid.length()==0) {
//This is a new, unknown patient. Let's save the record
person.personid="";
person.store();
Pointer.storePointer("GHB.PATIENTBACKREF."+sourceserverid+"."+personid,person.personid);
personid=person.personid;
Pointer.storePointer(pointer, personid);
}
Iterator transactions = record.elementIterator("Transaction");
while(transactions.hasNext()) {
Element transaction = (Element)transactions.next();
TransactionVO transactionVO = TransactionVO.fromXMLElement(transaction);
if(transactionVO.getServerId()!=Integer.parseInt(targetserverid)) {
//We don't handle our own transactions
if(transactionVO.getServerId()==1) {
//We don't translate already translated ids
transactionVO.setServerId(Integer.parseInt(sourceserverid));
transactionVO.setVersionServerId(Integer.parseInt(sourceserverid));
}
//Remove encounter data because we don't import encounters
for(int n=0;n<transactionVO.getItems().size();n++) {
ItemVO i = (ItemVO)new Vector(transactionVO.getItems()).elementAt(n);
if(i.getType().equalsIgnoreCase("be.mxs.common.model.vo.healthrecord.IConstants.ITEM_TYPE_CONTEXT_ENCOUNTERUID")) {
transactionVO.getItems().remove(i);
}
}
//Replace transaction user by default system user because original userid is unknown
transactionVO.setUser(MedwanQuery.getInstance().getUser(MedwanQuery.getInstance().getConfigString("externalUserId","4")));
MedwanQuery.getInstance().updateTransaction(Integer.parseInt(personid), transactionVO);
}
}
Iterator labanalyses = record.elementIterator("RequestedLabAnalysis");
while(labanalyses.hasNext()) {
Element labanalysis = (Element)labanalyses.next();
RequestedLabAnalysis requestedLabAnalysis = RequestedLabAnalysis.fromXMLElement(labanalysis);
if(!requestedLabAnalysis.getServerId().equalsIgnoreCase(targetserverid)) {
//We don't handle our own transactions
if(requestedLabAnalysis.getServerId().equalsIgnoreCase("1")) {
//We don't translate already translated ids
requestedLabAnalysis.setServerId(sourceserverid);
}
requestedLabAnalysis.setPatientId(personid);
requestedLabAnalysis.store();
}
}
}
else {
Debug.println("ERROR: Discarding message because comes from this server");
}
//The message was correctly read, store the delivery date on the server
method = new PostMethod(MedwanQuery.getInstance().getConfigString("ghb_ref_delivermessageurl","http://www.globalhealthbarometer.net/globalhealthbarometer/util/deliverGHBMessage.jsp"));
method.setRequestEntity(new MultipartRequestEntity(parts2, method.getParams()));
client.executeMethod(method);
}
else {
//Wrong target server, discard the message
Debug.println("ERROR: Discarding message because not addressed to this server");
}
}
}
}
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void sendMessages() {
if(MedwanQuery.getInstance().getConfigString("ghb_ref_serverid","").trim().length()==0) {
return;
}
try {
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = conn.prepareStatement("select * from GHB_Messages where GHB_MESSAGE_DELIVEREDDATETIME is null and GHB_MESSAGE_ERROR is null");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
int targetServerId = rs.getInt("GHB_MESSAGE_TARGETSERVERID");
String data = new String(rs.getBytes("GHB_MESSAGE_DATA"));
int messageid=rs.getInt("GHB_MESSAGE_ID");
Debug.println("Sending GHB message id "+messageid);
Debug.println("Getting pubkey for destination server "+targetServerId);
//Get pubkey for this targetserver
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(MedwanQuery.getInstance().getConfigString("ghb_ref_getpubkeyurl","http://www.globalhealthbarometer.net/globalhealthbarometer/util/getGHBPubkey.jsp"));
Part[] parts= {
new StringPart("serverid",targetServerId+""),
};
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
client.executeMethod(method);
String sResponse = IOUtils.toString(method.getResponseBodyAsStream(), StandardCharsets.UTF_8);
if(sResponse.contains("<pubkey")){
Document document=DocumentHelper.parseText(sResponse.substring(sResponse.indexOf("<pubkey")));
Element root = document.getRootElement();
if(ScreenHelper.checkString(root.attributeValue("error")).length()>0) {
Debug.println("Received ERROR "+root.attributeValue("error"));
PreparedStatement ps2 = conn.prepareStatement("update GHB_MESSAGES set GHB_MESSAGE_ERROR=? where GHB_MESSAGE_ID=?");
ps2.setString(1, root.attributeValue("error"));
ps2.setInt(2, messageid);
ps2.execute();
ps2.close();
}
else {
Debug.println("Received pubkey for destination server "+targetServerId);
String pubkey = root.getText();
String token = Encryption.getToken(16);
String encryptedData = Encryption.encryptTextSymmetric(data, token);
//Now we post the encrypted data to the GHB server
String storeurl=MedwanQuery.getInstance().getConfigString("ghb_ref_storemessageurl","http://www.globalhealthbarometer.net/globalhealthbarometer/util/storeGHBMessage.jsp");
Debug.println("Posting message to "+storeurl);
PostMethod post = new PostMethod(storeurl);
Part[] parts2= {
new StringPart("sourceserverid",MedwanQuery.getInstance().getConfigString("ghb_ref_serverid","")),
new StringPart("targetserverid",targetServerId+""),
new StringPart("data",encryptedData),
new StringPart("token",Encryption.encryptTextWithPublicKey(token, pubkey))
};
post.setRequestEntity(new MultipartRequestEntity(parts2, post.getParams()));
int status = client.executeMethod(post);
sResponse = IOUtils.toString(post.getResponseBodyAsStream(), StandardCharsets.UTF_8);
if(sResponse.contains("<ok>")){
Debug.println("Message successfully posted");
//Message successfully delivered
PreparedStatement ps2 = conn.prepareStatement("update GHB_MESSAGES set GHB_MESSAGE_DELIVEREDDATETIME=? where GHB_MESSAGE_ID=?");
ps2.setTimestamp(1, new java.sql.Timestamp(new java.util.Date().getTime()));
ps2.setInt(2, messageid);
ps2.execute();
ps2.close();
}
else {
Debug.println("Error posting message");
}
}
}
}
rs.close();
ps.close();
conn.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
|
package hwarang.artg.exhibition.model;
import java.util.Date;
import lombok.Data;
@Data
public class FavoriteMarkVO {
private int exh_seq;
private String member_id;
private Date favorite_date;
private String favorite_group;
private String favorite_status;
private String exh_title;
private String exh_place;
private String exh_price;
private String exh_imgurl;
private String exh_realmName;
private Date exh_startDate;
private Date exh_endDate;
}
|
package xyz.mcallister.seth.HG.commands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import xyz.mcallister.seth.HG.GameState;
/**
* Created by sethm on 20/04/2016.
*/
public class ForceEnd implements CommandExecutor
{
public boolean onCommand(CommandSender sender, Command command, String s, String[] strings)
{
if(command.getName().equalsIgnoreCase("forceend"))
{
if(!sender.hasPermission("hg.admin"))
{
sender.sendMessage(ChatColor.RED + "You do not have permission to execute that command.");
return true;
}
if(GameState.ended.get() == true)
sender.sendMessage(ChatColor.RED + "The game has already ended.");
else
{
Bukkit.broadcastMessage(ChatColor.RED + "The game has been forcefully ended by an admin.");
}
}
return false;
}
}
|
package com.ngocdt.tttn.entity;
import java.util.List;
import javax.persistence.*;
import com.ngocdt.tttn.enums.ROLE;
import lombok.Getter;
import lombok.Setter;
@Entity
@Table(name="Role")
@Getter
@Setter
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int roleID;
@Column(unique = true)
@Enumerated(EnumType.STRING)
private ROLE roleName;
public int getRoleID() {
return roleID;
}
public void setRoleID(int roleID) {
this.roleID = roleID;
}
public ROLE getRoleName() {
return roleName;
}
public void setRoleName(ROLE roleName) {
this.roleName = roleName;
}
}
|
package example7;
import java.time.Duration;
import java.util.Optional;
import java.util.stream.Stream;
public class DurationsStream implements ForwardingStream<Duration> {
private final Stream<Duration> stream;
private DurationsStream(Stream<Duration> stream) {
this.stream = stream;
}
public static DurationsStream stream(Stream<Duration> stream) {
return new DurationsStream(stream);
}
@Override
public Stream<Duration> getStream() {
return this.stream;
}
public Duration maxOfMany() {
return this.getStream().max(Duration::compareTo).get();
}
public Optional<Duration> min() {
return this.getStream().min(Duration::compareTo);
}
}
|
package Pro977.SquaresofaSortedArray;
import java.util.Arrays;
/**
* Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
* <p>
* <p>
* <p>
* Example 1:
* <p>
* Input: [-4,-1,0,3,10]
* Output: [0,1,9,16,100]
* Example 2:
* <p>
* Input: [-7,-3,2,3,11]
* Output: [4,9,9,49,121]
*/
public class Solution {
public static void main(String[] args) {
int[] A = {-7, -3, 2, 3, 11};
int[] res = sortedSquares(A);
for (int i = 0; i <res.length ; i++) {
System.out.println(res[i]);
}
}
public static int[] sortedSquares(int[] A) {
int[] res = new int[A.length];
for (int i = 0; i < A.length; i++) {
int tmp = A[i] * A[i];
res[i] = tmp;
}
Arrays.sort(res);
return res;
}
}
|
package com.ifeng.recom.mixrecall.negative;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ifeng.recom.mixrecall.common.model.RecordInfo;
import com.ifeng.recom.mixrecall.common.model.UserCluster;
import com.ifeng.recom.mixrecall.common.model.UserModel;
import com.ifeng.recom.mixrecall.common.model.item.EvItem;
import com.ifeng.recom.mixrecall.common.model.request.MixRequestInfo;
import com.ifeng.recom.mixrecall.common.service.UserProfile;
import com.ifeng.recom.mixrecall.common.util.DocUtils;
import com.ifeng.recom.mixrecall.template.behavior.IncreaseBehavior;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.*;
import static com.ifeng.recom.mixrecall.core.util.RecallUtils.getCateAndSubcateFilterForDoc;
import static com.ifeng.recom.mixrecall.core.util.RecallUtils.getCateAndSubcateFilterForVideo;
@Service
public class NegativeSupport {
private static final Logger logger = LoggerFactory.getLogger(NegativeSupport.class);
// private MixRequestInfo mixRequestInfo;
@Autowired
@Qualifier("SessionServiceImpl")
SessionServiceImpl sessionService;
public Map<String,Map<String,Double>> getNegativeTag(MixRequestInfo mixRequestInfo) {
logger.info("check negative uid:{} step1",mixRequestInfo.getUid());
UserModel userModel = mixRequestInfo.getUserModel();
logger.info("check negative uid:{} step2",mixRequestInfo.getUid());
List<EvItem> evInfos = mixRequestInfo.getEvItems();
if (evInfos == null || evInfos.size() == 0) {
return Maps.newHashMap();
}
Map<String, ItemProfile> itemProfileMap = sessionService.getClick(mixRequestInfo, evInfos);
evInfos = sessionService.merge_add(evInfos, mixRequestInfo);//得到30分钟内的相关数据
logger.info("check negative uid:{} step3",mixRequestInfo.getUid());
List<EvItem.EvObj> evList = sessionService.getevListFromSessionList(evInfos); //保存ev信息 docid 是否点击等
/**
* 获取用户画像信息 包括 长期、短期、实时
*/
List<RecordInfo> combineTagList = userModel.getRecentCombineTagList();
List<RecordInfo> Docpic_cotagList = userModel.getDocpic_cotag();
List<RecordInfo> Recent_docpic_cotagList = userModel.getRecent_docpic_cotag();
List<RecordInfo> Video_cotagList = userModel.getVideo_cotag();
List<RecordInfo> Recent_video_cotagList = userModel.getRecent_video_cotag();
List<RecordInfo> last_t1_recordList = userModel.getLastt1RecordList();
List<RecordInfo> last_t2_recordList = userModel.getLastt2RecordList();
List<RecordInfo> last_t3_recordList = userModel.getLastt3RecordList();
List<RecordInfo> recentInfoList = new ArrayList<>();
List<RecordInfo> longInfoList = new ArrayList<>();
List<RecordInfo> lastInfoList = new ArrayList<>();
if(combineTagList != null && combineTagList.size() >= 1){
longInfoList.addAll(combineTagList);
}
if(Docpic_cotagList != null && Docpic_cotagList.size() >= 1){
longInfoList.addAll(Docpic_cotagList);
}
if(Video_cotagList != null && Video_cotagList.size() >= 1){
longInfoList.addAll(Video_cotagList);
}
if(Recent_docpic_cotagList != null && Recent_docpic_cotagList.size() >= 1){
recentInfoList.addAll(Recent_docpic_cotagList);
}
if(Recent_video_cotagList != null && Recent_video_cotagList.size() >= 1){
recentInfoList.addAll(Recent_video_cotagList);
}
if(last_t1_recordList != null && last_t1_recordList.size() >= 1 ){
lastInfoList.addAll(last_t1_recordList);
}
if(last_t2_recordList != null && last_t2_recordList.size() >= 1){
lastInfoList.addAll(last_t2_recordList);
}
if(last_t3_recordList != null && last_t3_recordList.size() >= 1){
lastInfoList.addAll(last_t3_recordList);
}
Map<String,Integer> longCotagMap = new HashMap<>();
Map<String,Integer> recentCotagMap = new HashMap<>();
longInfoList = longInfoList.subList(0,longInfoList.size()/2);
recentInfoList = recentInfoList.subList(0,recentInfoList.size()/2);
for(RecordInfo item : longInfoList){
String cate = item.getRecordName().split("-")[0];
if(!longCotagMap.containsKey(cate)){
longCotagMap.put(cate,1);
}else{
longCotagMap.put(cate,longCotagMap.get(cate)+1);
}
}
for(RecordInfo item : recentInfoList){
String cate = item.getRecordName().split("-")[0];
if(!recentCotagMap.containsKey(cate)){
recentCotagMap.put(cate,1);
}else{
recentCotagMap.put(cate,recentCotagMap.get(cate)+1);
}
}
Set<String> RecentCotagSets = new HashSet<>();
Set<String> LongCotagSets = new HashSet<>();
Map<String,Double> LastCotagMap = new HashMap<>();
for(Map.Entry<String,Integer> item : longCotagMap.entrySet()){
if(item.getValue() > longInfoList.size()/longCotagMap.keySet().size()){
LongCotagSets.add(item.getKey());
}
}
for(Map.Entry<String,Integer> item : recentCotagMap.entrySet()){
if(item.getValue() > recentInfoList.size()/recentCotagMap.keySet().size()){
RecentCotagSets.add(item.getKey());
}
}
LongCotagSets.addAll(RecentCotagSets);
logger.info("get longCotagSets:{} result:{}",mixRequestInfo.getUid(),LongCotagSets.toString());
lastInfoList.forEach(item -> {
if(item.getWeight() < 0.51){
LastCotagMap.put(item.getRecordName(),(double)item.getReadFrequency()/item.getExpose());
}
});
/**
* Version 1.1 得到最近曝光的文章的 pv 、点击和 添加衰减因子 并根据时间进行降权 ,并在负反馈中应用相关的权重进行降权
*/
Map<String, FeatureExposeClick> featureExposeClickMap = getExposeClickStatistic(evList, userModel);
logger.info("check negative uid:{} step4",mixRequestInfo.getUid());
//此处用于测试
// if(featureExposeClickMap.size() >0){
// for(Map.Entry<String,FeatureExposeClick> item : featureExposeClickMap.entrySet()){
// logger.info("check featureExpose uid:{} type:{} expo:{} click:{} feature:{}",mixRequestInfo.getUid(),item.getValue().getType(),item.getValue().getExpose(),item.getValue().getClick(),item.getValue().getFeatureWord());
//
// }
// }
Map<String, Map<String, Double>> negResult = ContentBasedRecallNew(mixRequestInfo, featureExposeClickMap,userModel,LongCotagSets,LastCotagMap);
if (negResult == null) {
return Maps.newHashMap();
}
return negResult;
}
/**
* mixcotag召回
* @param ucombinetag
* @param weight 判定新兴趣阈值,小于该阈值走强插逻辑
* @param featureExposeClickMap session内用户正负反馈信息
* @return
*/
public static Map<String,List<String>> ContentBasedRecall(Map<String, FeatureExposeClick> featureExposeClickMap) {
//解析ucombinetag画像
// JSONArray cotagarray = JSONObject.parseArray(ucombinetag);
if (featureExposeClickMap == null || featureExposeClickMap.size() == 0) {
return null;
} else {
Map<String, List<String>> filterTag = new HashMap<>();
List<String> cotagList = new ArrayList<String>();
List<String> cateList = new ArrayList<String>();
List<String> subCateList = new ArrayList<String>();
List<String> topicList = new ArrayList<String>();
for (Map.Entry<String, FeatureExposeClick> entry : featureExposeClickMap.entrySet()) {
String[] arr = entry.getKey().split("_");
String type = arr[0];
String tag = arr[1];
if (type.equals("cotag")) {
Double click = entry.getValue().getClick();
Double expose = entry.getValue().getExpose();
Double ctr = click / expose;
if (expose >= 3 && ctr < 0.2) {
cotagList.add(tag);
}
}
if (type.equals("c")) {
Double click = entry.getValue().getClick();
Double expose = entry.getValue().getExpose();
Double ctr = click / expose;
if (expose >= 5 && ctr < 0.1) {
cateList.add(tag);
}
}
if (type.equals("sc")) {
Double click = entry.getValue().getClick();
Double expose = entry.getValue().getExpose();
Double ctr = click / expose;
if (expose >= 4 && ctr < 0.1) {
subCateList.add(tag);
}
}
if (type.equals("topic")) {
Double click = entry.getValue().getClick();
Double expose = entry.getValue().getExpose();
Double ctr = click / expose;
if (expose >= 3 && ctr < 0.1) {
topicList.add(tag);
}
}
}
filterTag.put("cotag", cotagList);
filterTag.put("C", cateList);
filterTag.put("sc", subCateList);
filterTag.put("topic", topicList);
return filterTag;
}
}
/**
* mixcotag召回
* @param ucombinetag
* @param weight 判定新兴趣阈值,小于该阈值走强插逻辑
* @param featureExposeClickMap session内用户正负反馈信息
* @return
*/
public static Map<String,Map<String,Double>> ContentBasedRecallNew(MixRequestInfo mixRequestInfo,Map<String, FeatureExposeClick> featureExposeClickMap,UserModel userProfile,Set<String> longCotagSets,Map<String,Double> lastCotagMap) {
if (featureExposeClickMap == null || featureExposeClickMap.size() == 0) {
return Maps.newHashMap();
} else {
//得到最终的需要召回比例
Map<String, Map<String, Double>> finalWightMap = Maps.newHashMap();
Map<String, Double> cotagMap = Maps.newHashMap();
Map<String, Double> cotag_feedMap = Maps.newHashMap();
Map<String, Double> cotagMap_1 = Maps.newHashMap();
Map<String, Double> cotagMap_2 = Maps.newHashMap();
Map<String, Double> cotagMap_3 = Maps.newHashMap();
Map<String, Double> cotagMap_4 = Maps.newHashMap();
Map<String, String> cotagMap_5 = Maps.newHashMap();
Map<String, String> cotagMap_6 = Maps.newHashMap();
Map<String, String> cotagMap_7 = Maps.newHashMap();
Map<String, String> cotagMap_8 = Maps.newHashMap();
Map<String, String> cotagMap_9 = Maps.newHashMap();
Map<String, Double> featureMap = Maps.newHashMap();
Map<String, Double> featureMap_ratio = Maps.newHashMap();
Map<String, Double> ldaMap = Maps.newHashMap();
double filterThre = 3.0;
double fullness;
try {
fullness = Double.parseDouble(mixRequestInfo.getUserModel().getFullness());
} catch (Exception e) {
fullness = 0.0;
}
if(fullness > 0.0 && fullness <= 0.4){
filterThre = 2.2;
}
// Set<String> cScFilter_Doc = getCateAndSubcateFilterForDoc(mixRequestInfo.getUserModel());
// Set<String> cScFilter_Video = getCateAndSubcateFilterForVideo(mixRequestInfo.getUserModel());
// Set<String> cScFilter_Set = new HashSet<>();
//
// if(cScFilter_Doc != null && cScFilter_Doc.size() >= 1){
// cScFilter_Set.addAll(cScFilter_Doc);
// }
//
// if(cScFilter_Video != null && cScFilter_Video.size() >= 1){
// cScFilter_Set.addAll(cScFilter_Video);
// }
for (Map.Entry<String, FeatureExposeClick> entry : featureExposeClickMap.entrySet()) {
double weight = 1.0;
String[] arr = entry.getKey().split("_");
if(arr.length !=2){
logger.info("check arr:{}",arr);
}
String type = arr[0];
String tag = arr[1];
if (type.equals("c")) {
Double click = entry.getValue().getClick();
Double expose = entry.getValue().getExpose();
Double ctr = click / expose;
if (expose >= filterThre && ctr < 0.25) {
if(longCotagSets.contains(tag)){
weight -= 0.12 * (expose - click);
cotagMap_1.put(tag,weight);
}else{
weight -= 0.17 * (expose - click);
cotagMap_2.put(tag,weight);
}
if (weight < 0.1) {
weight = 0.1;
}
cotagMap.put(tag, weight);
}
/**
* C 正反馈 增加曝光
*/
if (expose >= filterThre && ctr > 0.6) {
if(longCotagSets.contains(tag)){
weight += 0.25 * click;
}else{
weight += 0.40 * click;
}
if (weight > 2.0) {
weight = 2.0;
}
cotagMap_5.put(tag,ctr+"_"+weight+"_"+expose+"_"+click);
cotag_feedMap.put(tag, weight);
}
}
if (type.equals("sc")) {
Double click = entry.getValue().getClick();
Double expose = entry.getValue().getExpose();
Double ctr = click / expose;
if (expose >= filterThre - 0.5 && ctr < 0.33) {
if(longCotagSets.contains(tag)){
weight -= 0.18 * (expose - click);
cotagMap_3.put(tag,weight);
}else{
weight -= 0.23 * (expose - click);
cotagMap_4.put(tag,weight);
}
if (weight < 0.1) {
weight = 0.1;
}
cotagMap.put(tag, weight);
}
/**
* SC 正反馈 增加曝光
*/
if (expose >= filterThre -0.5 && ctr > 0.6) {
if(longCotagSets.contains(tag)){
weight += 0.25 * click;
}else{
weight += 0.40 * click;
}
if (weight > 2.0) {
weight = 2.0;
}
cotagMap_6.put(tag,ctr+"_"+weight+"_"+expose+"_"+click);
cotag_feedMap.put(tag, weight);
}
}
if (type.equals("featureWord")) {
Double click = entry.getValue().getClick();
Double expose = entry.getValue().getExpose();
Double ctr = click / expose;
/**
* 此处对媒体放宽过滤条件
*/
Double filterFeature = filterThre;
if(tag.contains("(s)")){
filterFeature = filterThre + 1.0;
}
if (expose >= filterFeature && ctr < 0.1) {
if(lastCotagMap.containsKey(tag) && lastCotagMap.get(tag) < 0.3){
weight -= 0.20 * (expose - click);
if (weight < 0.1) {
weight = 0.1;
}
featureMap_ratio.put(tag,weight);
}else{
featureMap.put(tag, 1.0);
}
}
if (expose >= filterFeature - 1.0 && ctr >= 0.9) {
if(lastCotagMap.containsKey(tag)){
weight += 0.25 * click;
}else{
weight += 0.40 * click;
if (weight > 2.5) {
weight = 2.5;
}
cotagMap_7.put(tag,ctr+"_"+weight+"_"+expose+"_"+click);
featureMap_ratio.put(tag,weight);
}
}
}
if (type.equals("lda")) {
Double click = entry.getValue().getClick();
Double expose = entry.getValue().getExpose();
Double ctr = click / expose;
if (expose >= filterThre + 0.2 && ctr < 0.33) {
weight -= 0.15 * (expose - click);
if (weight < 0.1) {
weight = 0.1;
}
cotagMap_8.put(tag,ctr+"_"+weight+"_"+expose+"_"+click);
ldaMap.put(tag, weight);
}
if (expose >= filterThre - 0.2 && ctr > 0.75) {
weight += 0.2 * click;
if (weight > 2.0) {
weight = 2.0;
}
cotagMap_9.put(tag,ctr+"_"+weight+"_"+expose+"_"+click);
ldaMap.put(tag, weight);
}
}
// if(cScFilter_Set.contains(tag)){
// Double click = entry.getValue().getClick();
// Double expose = entry.getValue().getExpose();
// Double ctr = click / expose;
// if (ctr < 0.5) {
// weight = 0.0;
// cotagMap.put(tag, weight);
// logger.info("check here for uid:{} tag:{} weight:{}",mixRequestInfo.getUid(),tag,weight);
//
// }
// }
}
finalWightMap.put("cotag",cotagMap);
finalWightMap.put("cotag_posFeed",cotag_feedMap);
finalWightMap.put("featureWord",featureMap);
finalWightMap.put("featureWord_ratio",featureMap_ratio);
finalWightMap.put("lda",ldaMap);
logger.info("uid:{} ______________NegativeFinalMap______________:{},cotag1:{},cotag2:{},cotag3:{},cotag4:{},cotag5:{},cotag6:{},cotag7:{},cotag8:{},cotag9:{},{},{},{} ",mixRequestInfo.getUid(),cotagMap,cotagMap_1,cotagMap_2,cotagMap_3,cotagMap_4,
cotagMap_5,cotagMap_6,cotagMap_7,cotagMap_8,cotagMap_9,featureMap,featureMap_ratio,ldaMap);
// logger.info("uid:{} ______________NegativeFinalMap______________:{},{},{} ",mixRequestInfo.getUid(),cotagMap,featureMap,ldaMap);
return finalWightMap;
}
}
/**
* 解析user_cluster为一个map,key为一级分类
* @param userProfile
* @return
*/
private Map<String, UserCluster> getCategoryUserClusterMap(UserModel userProfile) {
if (userProfile == null) {
return null;
}
List<UserCluster> userClusterFeature = userProfile.getUserClusterList();
if (userClusterFeature == null) {
return null;
}
Map<String, UserCluster> resultMap = new HashMap<>();
for (UserCluster element : userClusterFeature) {
if (element.getCate() != null) {
resultMap.put(element.getCate(), element); //科技
}
}
return resultMap;
}
/**
* 统计evList中各个特征词的曝光点击数,存入Map,key为type_featureWord
* 统计过程中考虑文章本身的CTR,CTR较高的文章对应的点击作降权(也就是曝光加权)
* @param evList
* @return
*/
private static Map<String, FeatureExposeClick> getExposeClickStatistic(List<EvItem.EvObj> evList, UserModel userProfile) {
Map<String, FeatureExposeClick> featureExposeClickMap = new HashMap<>();
Map<Long,Map<String,Integer>> evPullnumMap = FeatureUtil.getEvpullnumMap(evList);
/**
* 此处添加cotagSets 对数据来源进行过滤 以保证过滤数据不被噪声影响 add by YX 20191016
*/
// cotagSets.addAll(recentCotagSets);
//按照时间戳 30分钟一个session 的文章进行排序 <time,Map<expo:1,cli:0,
double decay = 1.0;
if(userProfile == null || !StringUtils.isDouble(userProfile.getFullness())){
decay = 0.3;
}else{
double fullness = Double.parseDouble(userProfile.getFullness());
decay -= fullness * 0.3; //丰满度越高衰减因子越低 丰满度越低的用户对不感兴趣的文章更需要避免刷屏
}
List<String> check4weight = new ArrayList<>();
for (EvItem.EvObj exposeInfo : evList) {
boolean isClick = exposeInfo.isC();
Long t = exposeInfo.getT();
Map<String,Integer> valueMap = evPullnumMap.get(t);
if(valueMap!=null){
int pullnum = valueMap.get("pullnum");
int clk = valueMap.get("clk");
if(pullnum==1 && clk==0){//预载逻辑最近一刷特殊处理
continue;
}
}
int pullnum = valueMap.get("pullnum");
Set<String> cotags = exposeInfo.getCotags();
// cotagSets.retainAll(cotags);
double aic = 1.0;
// if(cotagSets.size() != 0){
// aic = 1.3;
// }
/**
* 此处对于C和SC的过滤暂时注释 待之后需要对C以及SC通道进行过滤时使用 add by YX 2019-10-09
*/
// c
if(exposeInfo.getCategories() != null) {
for (String category : exposeInfo.getCategories()) {
String key = "c" + "_" + category;
FeatureExposeClick featureExposeClick = featureExposeClickMap.get(key);
if (featureExposeClick == null) {
featureExposeClick = new FeatureExposeClick("c", category);
featureExposeClickMap.put(key, featureExposeClick);
}
featureExposeClick.addExpose(aic * Math.pow(decay,(1+pullnum)*0.5));
if (isClick) {
featureExposeClick.addClick(aic * Math.pow(decay,(1+pullnum)*0.5));
}
}
}
// sc
if(exposeInfo.getSubcates() != null ) {
for (String subcate : exposeInfo.getSubcates()) {
if(subcate.length() >=1 ){
String key = "sc" + "_" + subcate;
FeatureExposeClick featureExposeClick = featureExposeClickMap.get(key);
if (featureExposeClick == null) {
featureExposeClick = new FeatureExposeClick("sc", subcate);
featureExposeClickMap.put(key, featureExposeClick);
}
featureExposeClick.addExpose(aic * Math.pow(decay,(1+pullnum)*0.5));
if (isClick) {
featureExposeClick.addClick(aic * Math.pow(decay,(1+pullnum)*0.5));
}
}
}
}
//lda
if(exposeInfo.getLdatopics() != null) {
for (String lda : exposeInfo.getLdatopics()) {
String key = "lda" + "_" + lda;
FeatureExposeClick featureExposeClick = featureExposeClickMap.get(key);
if (featureExposeClick == null) {
featureExposeClick = new FeatureExposeClick("lda", lda);
featureExposeClickMap.put(key, featureExposeClick);
}
featureExposeClick.addExpose(aic * Math.pow(decay,(1+pullnum)*0.5));
if (isClick) {
featureExposeClick.addClick(aic * Math.pow(decay,(1+pullnum)*0.5) );
}
}
}
//cotag
if(exposeInfo.getCotags() != null) {
Set<String> featureSet = new HashSet<>();
for (String cotag : exposeInfo.getCotags()) {
String[] arr = cotag.split("-");
if(arr.length == 2){
String featureWord = "featureWord" + "_" + arr[1];
if(!featureSet.contains(arr[1])){
FeatureExposeClick featureExposeClick_featureWord = featureExposeClickMap.get(featureWord);
if (featureExposeClick_featureWord == null) {
featureExposeClick_featureWord = new FeatureExposeClick("featureWord", arr[1]);
featureExposeClickMap.put(featureWord, featureExposeClick_featureWord);
}
featureExposeClick_featureWord.addExpose(1.0);
if (isClick) {
featureExposeClick_featureWord.addClick(1.0);
}
featureSet.add(arr[1]);
}
}
}
}
}
return featureExposeClickMap;
}
/**
* 统计evList中各个特征词的曝光点击数,存入Map,key为type_featureWord
* 统计过程中考虑文章本身的CTR,CTR较高的文章对应的点击作降权(也就是曝光加权)
* @param evList
* @return
*/
private static Map<String, FeatureExposeClick> getExposeClickStatisticNew(List<EvItem.EvObj> evList, UserModel userProfile) {
Map<String, FeatureExposeClick> featureExposeClickMap = new HashMap<>();
Map<Long,Map<String,Integer>> evPullnumMap = FeatureUtil.getEvpullnumMap(evList);
logger.info("get _______________evpullNumMap:{}",evPullnumMap.toString());
//此处添加衰减因子
double decay = 1.8;
if(userProfile == null || !StringUtils.isDouble(userProfile.getFullness())){
decay = 1.5;
}else{
double fullness = Double.parseDouble(userProfile.getFullness());
decay += fullness * 1.1; //丰满度越高衰减因子越低 丰满度越低的用户对不感兴趣的文章更需要避免刷屏
}
for (EvItem.EvObj exposeInfo : evList) {
boolean isClick = exposeInfo.isC();
Long t = exposeInfo.getT();
Map<String,Integer> valueMap = evPullnumMap.get(t);
if(valueMap!=null){
int pullnum = valueMap.get("pullnum");
int clk = valueMap.get("clk");
if(pullnum==1 && clk==0){//预载逻辑最近一刷特殊处理
continue;
}
}
int pullnum = valueMap.get("pullnum");
// c
if(exposeInfo.getCategories() != null) {
for (String category : exposeInfo.getCategories()) {
String key = "c" + "_" + category;
FeatureExposeClick featureExposeClick = featureExposeClickMap.get(key);
if (featureExposeClick == null) {
featureExposeClick = new FeatureExposeClick("c", category);
featureExposeClickMap.put(key, featureExposeClick);
}
featureExposeClick.addExpose(0.58 * Math.pow(decay, -1-(0.1*pullnum)));
if (isClick) {
featureExposeClick.addClick(0.58 * Math.pow(decay, -1-(0.1*pullnum)));
}
}
}
// sc
if(exposeInfo.getSubcates() != null) {
for (String subcate : exposeInfo.getSubcates()) {
String key = "sc" + "_" + subcate;
FeatureExposeClick featureExposeClick = featureExposeClickMap.get(key);
if (featureExposeClick == null) {
featureExposeClick = new FeatureExposeClick("sc", subcate);
featureExposeClickMap.put(key, featureExposeClick);
}
featureExposeClick.addExpose(0.58 * Math.pow(decay, -1-(0.1*pullnum)));
if (isClick) {
featureExposeClick.addClick(0.58 * Math.pow(decay, -1-(0.1*pullnum)));
}
}
}
//lda
if(exposeInfo.getLdatopics() != null) {
for (String lda : exposeInfo.getLdatopics()) {
String key = "lda" + "_" + lda;
FeatureExposeClick featureExposeClick = featureExposeClickMap.get(key);
if (featureExposeClick == null) {
featureExposeClick = new FeatureExposeClick("lda", lda);
featureExposeClickMap.put(key, featureExposeClick);
}
featureExposeClick.addExpose(0.5 * Math.pow(decay, -1-(0.1*pullnum)));
if (isClick) {
featureExposeClick.addClick(0.5 *Math.pow(decay, -1-(0.1*pullnum)));
}
}
}
//cotag
if(exposeInfo.getCotags() != null) {
for (String cotag : exposeInfo.getCotags()) {
String[] arr = cotag.split("-");
String key = "cotag" + "_" + arr[0];
String featureWord = "featureWord" + "_" + arr[1];
FeatureExposeClick featureExposeClick_cotag = featureExposeClickMap.get(key);
FeatureExposeClick featureExposeClick_featureWord = featureExposeClickMap.get(key);
if (featureExposeClick_cotag == null) {
featureExposeClick_cotag = new FeatureExposeClick("cotag", cotag);
featureExposeClickMap.put(key, featureExposeClick_cotag);
}
featureExposeClick_cotag.addExpose(1.0);
if (featureExposeClick_featureWord == null) {
featureExposeClick_featureWord = new FeatureExposeClick("featureWord", cotag);
featureExposeClickMap.put(key, featureExposeClick_featureWord);
}
featureExposeClick_featureWord.addExpose(1.0);
if (isClick) {
featureExposeClick_cotag.addClick(1.0);
featureExposeClick_featureWord.addClick(1.0);
}
}
}
}
return featureExposeClickMap;
}
}
|
package com.test.base;
/**
* Given an array of integers, return indices of the two numbers such that they add up to a specific target.
* You may assume that each input would have exactly one solution.
*
* 给定一个整数数组,找出两个数满足相加等于制定的数组
* 可以假设每一组,有且仅有一组解
*
* @author YLine
*
* 2018年7月19日 上午10:59:01
*/
public interface Solution
{
int[] twoSum(int[] nums, int target);
}
|
package com.manish.javadev;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.manish.javadev.model.AccountEntity;
import com.manish.javadev.service.AccountService;
@SpringBootApplication
public class SpringBootApplicationDemo implements CommandLineRunner {
@Autowired
private AccountService accountService;
public static void main(String[] args) {
SpringApplication.run(SpringBootApplicationDemo.class, args);
}
@Override
public void run(String... args) throws Exception {
// Save data
saveData();
// Find data
findData();
// Update data
updateData();
// Delete data
deleteData();
}
private void saveData() {
// Save Single Entity
AccountEntity accountEntity = new AccountEntity("Saving Account", "Manish", new Double(2300));
accountService.save(accountEntity);
// Save Multiple Entity
List<AccountEntity> accountEntities = new ArrayList<>();
AccountEntity accountEntity1 = new AccountEntity("Saving Account", "Bala JI", new Double(2500));
AccountEntity accountEntity2 = new AccountEntity("Current Account", "Shashi Mishra", new Double(2000));
AccountEntity accountEntity3 = new AccountEntity("Credit Account", "Varsha", new Double(1800));
accountEntities.add(accountEntity1);
accountEntities.add(accountEntity2);
accountEntities.add(accountEntity3);
accountService.saveAll(accountEntities);
}
private void findData() {
System.out.println("ReadFromDatabase called");
// find By Id
System.out.println("Find AccountEntity By ID");
AccountEntity resultAccountEntity = accountService.find(new Long(1));
System.out.println(resultAccountEntity);
// find By Ids
System.out.println("Find Multiple AccountEntity By IDS");
List<Long> ids = new ArrayList<>();
ids.add(new Long(1));
ids.add(new Long(2));
ids.add(new Long(3));
Iterable<AccountEntity> accountEntityLists = accountService.find(ids);
accountEntityLists.forEach(System.out::println);
// find All
System.out.println("Find All AccountEntity");
accountEntityLists = accountService.findAll();
accountEntityLists.forEach(System.out::println);
}
private void updateData() {
System.out.println("UpdateAccountEntity called");
// Update AccountEntity By Id
System.out.println("Find AccountEntity By ID");
AccountEntity resultAccountEntity = accountService.updateAmount(new Long(1), 10000);
System.out.println(resultAccountEntity);
// Update AccountEntity By Ids
System.out.println("Update Multiple AccountEntity By IDS");
Map<Long, String> updatorMap = new HashMap<>();
updatorMap.put(new Long(1), "Salary Account");
updatorMap.put(new Long(2), "PPF Account");
List<AccountEntity> accountEntityLists = accountService.update(updatorMap);
accountEntityLists.forEach(System.out::println);
}
private void deleteData() {
System.out.println("DeleteAccountEntity called");
// Delete AccountEntity By Id
System.out.println("Delete AccountEntity By ID");
accountService.delete(new Long(1));
// Delete AccountEntity By Ids
System.out.println("Delete Multiple AccountEntity By IDS");
List<Long> ids = new ArrayList<>();
ids.add(new Long(2));
ids.add(new Long(3));
accountService.delete(ids);
// Delete All AccountEntity
accountService.deleteAll();
}
}
|
package com.sen.myshop.web.api.dao;
import com.sen.myshop.domain.Content;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @Auther: Sen
* @Date: 2019/8/11 16:09
* @Description:
*/
@Repository
public interface ContentDao {
/**
* 根据CategoryId查找
* @param content
* @return
*/
List<Content> findByCategoryId(Content content);
}
|
package net.inveed.rest.jpa.jackson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import org.hibernate.proxy.HibernateProxy;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.CollectionSerializer;
public class EntityCollectionSerializer extends JsonSerializer<Collection<?>> {
private final CollectionSerializer master;
public EntityCollectionSerializer(CollectionSerializer master) {
this.master = master;
}
@Override
public void serialize(Collection<?> value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
if (value != null) {
ArrayList<Object> l = new ArrayList<>();
for (Object v : value) {
if (v instanceof HibernateProxy) {
v = ((HibernateProxy) v).getHibernateLazyInitializer().getImplementation();
}
l.add(v);
}
value = l;
}
master.serialize(value, jgen, provider);
}
}
|
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
public class GP_PilotStudy_v19 {
public static final boolean PROFILEPOWER = false;
static int DEMES = 3, MASTER_GENERATIONS = 10000, DEME_GENERATIONS = 1, POPSIZE_PER_PROCESSOR = 20, MINRANDOM = 0,
MAXRANDOM = 1, PROFILES_PER_CAT = 2000, MINSYSTEM = 2, MAXSYSTEM = 3, MAX_LEN = 10000,
DEPTH = 5, TSIZE = 2, simulations = 20, stabilityNum = 10;
static final int RANDOMNUMBERS = 50, CAPMED = RANDOMNUMBERS, CAPAVG = RANDOMNUMBERS + 1,
CAPSTD = RANDOMNUMBERS + 2, CAPMIN = CAPMED + 3, CAPMAX = CAPMED + 4, MYCAP = CAPMED + 5,
OPPCAP = CAPMED + 6, MYSIDECAP = CAPMED + 7, LEFTCAPSUM = CAPMED + 8, ADD = LEFTCAPSUM + 1, SUB = ADD + 1,
MUL = ADD + 2, DIV = ADD + 3, GT = ADD + 4, LT = ADD + 5, EQ = ADD + 6, AND = ADD + 7, OR = ADD + 8,
TSET_START = CAPMED, TSET_END = LEFTCAPSUM, FSET_1_START = ADD, FSET_1_END = DIV, FSET_2_START = GT,
FSET_2_END = EQ, FSET_3_START = AND, FSET_3_END = OR;
public static final double RANDOMPLAYER_PROB = 0.05, STRATEGY_CHANGE_PROB = 0.05, ENHANCMENT_MARGIN = 0,
PMUT_PER_NODE = 0.1, MOD_CROSSOVER_PROB = 0, REPLICATION_PROB = 0, CROSSOVER_PROB = 0,
SUBTREE_MUT_PROB = 0, PMUT_PROB = 0, ABIOGENSIS_PROB = 1, GAUSS_PROB_FACTOR = 0;
static final int CAPCHANGE = 2;
static int currentGen, uniqueWorldSizes, currentSimulation, currentTestedSize, currentDeme;
static implementClass_v19[] implement;
static Thread[] thread;
static int processors, TOTAL_POPSIZE, TOTAL_TESTCASES;
static double[] fitness, randNum;
static char[][][] init_strategy, join_strategy;
static char[][][][] demes_init_strategy, demes_join_strategy;
static char[][][] FT_init_strategy, FT_join_strategy;
static World_System_Shell_v19[][] profilingWorlds_Attacks, profilingWorlds_Joins;
static Random rd = new Random();
static boolean[][][] attackProfiles, joinProfiles;
static boolean sortedFit, shuffled;
static char[][][][] temp_init_strategy, temp_join_strategy;
static double[][] tempFitness;
static int prevAttacks, prevJoins, prevSimilarityCount;
static double avg_len;
static double[] similarityWarInit_Avg, similarityWarJoin_Avg;
static final boolean BLOATFIGHT = false, PRINTINDIV = false, PRINTPROFILE = false;
static int previousBestHash_1, previousBestHash_2;
static int[] length, testedStrategyIndex, world_sizes, TESTCASES = {100, 1000};
static int[][][] testStrategyIndexes;
static double[][] capabilities, probabilities, GaussProb;
static double[][][] capChangeRates;
static int[][][] changeIndexes;
static WriteFile writer, stateStats_writer, state_profiles_writer;
static String outputString;
public static void main(String[] args) {
master_initalize();
for (currentSimulation = 1; currentSimulation <= simulations; currentSimulation++) {
Simulation_v19 simulation_v19 = new Simulation_v19();
}
}
private static void master_initalize() {
System.out.println("START OF PROGRAM");
if (MINSYSTEM != 2) {
System.out.println("Error!!! MINSYSTEM must be 2");
System.exit(0);
}
if (Math.abs(1 - (MOD_CROSSOVER_PROB + REPLICATION_PROB + CROSSOVER_PROB + SUBTREE_MUT_PROB + PMUT_PROB + ABIOGENSIS_PROB)) > 1E-10) {
System.out.println("Error!!! Probabilities of evolutionary operators don't add up to 1");
System.exit(0);
}
if (DEMES!= MAXSYSTEM){
System.out.println("Error!!! DEMES not equal to MAXSYSTEM");
System.exit(0);
}
processors = Runtime.getRuntime().availableProcessors();
TOTAL_POPSIZE = POPSIZE_PER_PROCESSOR * processors;
System.out.println("\nThis program runs " + simulations + " simulations");
System.out.println("In each simulation,");
System.out.println("There are " + DEMES + " demes, each with " + TOTAL_POPSIZE + " strategies");
System.out.println("i.e., total population size per simulation is " + TOTAL_POPSIZE * DEMES);
System.out.println("Processing is divided over " + processors + " processors");
try {
writer = new WriteFile("output_data.txt", false);
writer.writeToFile("simulation" + "," + "generation" + "," + "gen_att_perc" + "," + "gen_join_perc" + ","
+ "world_size" + "," + "att_similarity" + "," + "att_perc" + "," + "att_median_cap" + ","
+ "att_cap_min" + "," + "att_cap_1st_quart" + "," + "att_cap_ratio_min" + ","
+ "att_cap_ratio_1st_quart" + "," + "join_similarity" + "," + "join_perc" + "," + "balance_perc"
+ "," + "bandwagon_perc" + "," + "join_median_cap" + "," + "join_cap_min" + ","
+ "join_cap_1st_quart" + "\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
stateStats_writer = new WriteFile("stateStats.txt", false);
stateStats_writer.writeToFile("simulation" + "," + "stateNum" + "," + "generation" + "," + "world_size" + ","
+ "indiv_attacks" + "," + "indiv_balances" + "," + "indiv_bandwagones" + "\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
randNum = new double[RANDOMNUMBERS];
for (int i = 0; i < RANDOMNUMBERS; i++)
randNum[i] = (MAXRANDOM - MINRANDOM) * rd.nextDouble() + MINRANDOM;
uniqueWorldSizes = 1 + MAXSYSTEM - MINSYSTEM;
if (uniqueWorldSizes!= TESTCASES.length){
System.out.println("Error!!! Test cases array and mina dn max system don't match!!");
System.exit(0);
}
TOTAL_TESTCASES = 0;
for (int i = 0; i < TESTCASES.length; i++)
TOTAL_TESTCASES += TESTCASES[i];
length = new int[TOTAL_TESTCASES];
testedStrategyIndex = new int[TOTAL_TESTCASES];
capabilities = new double[TOTAL_TESTCASES][];
probabilities = new double[TOTAL_TESTCASES][];
GaussProb = new double[TOTAL_TESTCASES][];
changeIndexes = new int[TOTAL_TESTCASES][CAPCHANGE][];
testStrategyIndexes = new int[TOTAL_TESTCASES][CAPCHANGE + 1][];
capChangeRates = new double[TOTAL_TESTCASES][CAPCHANGE][];
world_sizes = new int[uniqueWorldSizes];
FT_init_strategy = new char[DEMES + 1][uniqueWorldSizes][];
FT_join_strategy = new char[DEMES + 1][uniqueWorldSizes - 1][];
profilingWorlds_Attacks = new World_System_Shell_v19[uniqueWorldSizes][PROFILES_PER_CAT];
profilingWorlds_Joins = new World_System_Shell_v19[uniqueWorldSizes - 1][PROFILES_PER_CAT];
WriteFile profiles_writer = null;
try {
profiles_writer = new WriteFile("profiles.txt", false);
profiles_writer.writeToFile("profie_id" + "," + "simulate_Joiner" + "," + "world_size" + "," + "capMed"
+ "," + "capAvg" + "," + "capStd" + "," + "capMin" + "," + "capMax" + "," + "myCap" + ","
+ "oppCap" + "," + "mySideCap" + "," + "leftCapSum" + "\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int profile_id = 1;
for (int i = 0; i < uniqueWorldSizes; i++) {
for (int k = 0; k < PROFILES_PER_CAT; k++) {
profilingWorlds_Attacks[i][k] = new World_System_Shell_v19(false, (i + MINSYSTEM));
profiles_writer.writeToFile(profile_id + "," + "0" + "," + (i + MINSYSTEM) + ","
+ profilingWorlds_Attacks[i][k].capMed + "," + profilingWorlds_Attacks[i][k].capAvg + ","
+ profilingWorlds_Attacks[i][k].capStd + "," + profilingWorlds_Attacks[i][k].capMin + ","
+ profilingWorlds_Attacks[i][k].capMax + "," + profilingWorlds_Attacks[i][k].myCap + ","
+ profilingWorlds_Attacks[i][k].oppCap + "," + profilingWorlds_Attacks[i][k].mySideCap + ","
+ profilingWorlds_Attacks[i][k].leftCapSum + "\n");
profile_id++;
}
}
for (int i = 0; i < uniqueWorldSizes - 1; i++) {
for (int k = 0; k < PROFILES_PER_CAT; k++) {
profilingWorlds_Joins[i][k] = new World_System_Shell_v19(true, i + MINSYSTEM + 1);
profiles_writer.writeToFile(profile_id + "," + "1" + "," + (i + MINSYSTEM + 1) + ","
+ profilingWorlds_Attacks[i][k].capMed + "," + profilingWorlds_Attacks[i][k].capAvg + ","
+ profilingWorlds_Attacks[i][k].capStd + "," + profilingWorlds_Attacks[i][k].capMin + ","
+ profilingWorlds_Attacks[i][k].capMax + "," + profilingWorlds_Attacks[i][k].myCap + ","
+ profilingWorlds_Attacks[i][k].oppCap + "," + profilingWorlds_Attacks[i][k].mySideCap + ","
+ profilingWorlds_Attacks[i][k].leftCapSum + "\n");
profile_id++;
}
}
try {
state_profiles_writer= new WriteFile("state_profiles.txt", false);
outputString = ("simulation" + "," + "stateNum" + "," + "generation" + "," + "world_size") ;
for (int k = 0; k < PROFILES_PER_CAT; k++) {
outputString += ("," + "init_profile_" + (k + 1) );
}
for (int k = 0; k < PROFILES_PER_CAT; k++) {
outputString += ("," + "join_profile_" + (k + 1) );
}
state_profiles_writer.writeToFile(outputString + "\n");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int prevLevelTests = 0;
for (int currentLevel = 0; currentLevel < TESTCASES.length; currentLevel++) {
int currentLevelTests = TESTCASES[currentLevel];
if (currentLevel > 0) {
prevLevelTests += TESTCASES[currentLevel - 1];
currentLevelTests += prevLevelTests;
}
for (int test = prevLevelTests; test < currentLevelTests; test++) {
length[test] = MINSYSTEM + currentLevel;
world_sizes[length[test] - MINSYSTEM]++;
testedStrategyIndex[test] = rd.nextInt(length[test]);
capabilities[test] = new double[length[test]];
for (int i = 0; i < length[test]; i++) {
capabilities[test][i] = rd.nextDouble();
}
for (int k = 0; k < CAPCHANGE; k++) {
capChangeRates[test][k] = new double[length[test]];
for (int i = 0; i < length[test]; i++) {
capChangeRates[test][k][i] = rd.nextDouble();
}
}
for (int k = 0; k < CAPCHANGE; k++) {
int random;
changeIndexes[test][k] = new int[length[test]];
int[] temp = new int[length[test]];
for (int i = 0; i < length[test]; i++) {
temp[i] = i;
}
for (int i = 0; i < length[test]; i++) {
random = rd.nextInt(length[test]);
while (temp[random] == -99)
random = rd.nextInt(length[test]);
changeIndexes[test][k][i] = temp[random];
temp[random] = -99;
}
}
for (int k = 0; k <= CAPCHANGE; k++) {
testStrategyIndexes[test][k] = new int[length[test]];
for (int i = 0; i < length[test]; i++) {
if (k == 0 || rd.nextDouble() < STRATEGY_CHANGE_PROB) {
testStrategyIndexes[test][k][i] = rd.nextInt(FT_init_strategy.length - 2);
if (rd.nextDouble() < RANDOMPLAYER_PROB)
testStrategyIndexes[test][k][i] = FT_init_strategy.length - 2;
} else {
testStrategyIndexes[test][k][i] = testStrategyIndexes[test][k - 1][i];
}
}
}
probabilities[test] = new double[30 * MAXSYSTEM];
for (int i = 0; i < 30 * MAXSYSTEM; i++)
probabilities[test][i] = rd.nextDouble();
GaussProb[test] = new double[10 * MAXSYSTEM];
for (int i = 0; i < 10 * MAXSYSTEM; i++)
GaussProb[test][i] = 1 + Math.abs(rd.nextGaussian() * GAUSS_PROB_FACTOR);
}
}
System.out.println("Among " + TOTAL_TESTCASES + " test cases there are");
for (int i = 0; i < uniqueWorldSizes; i++) {
System.out.println(world_sizes[i] + " test cases of world size " + (i + MINSYSTEM));
}
}
}
|
package LojaCadastro.Controller.Dto;
import java.util.List;
import java.util.stream.Collectors;
import LojaCadastro.Modelo.Usuario;
//////////////CLASE DTO///////////////
public class UsuarioDto {
private Long cpf;
private String nome;
/////////GET E SET//////////
public Long getCpf() {
return cpf;
}
public void setCpf(Long cpf) {
this.cpf = cpf;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getNome() {
return nome;
}
/////////////CONSTRUCTOR////////////////
public static UsuarioDto converter(Usuario u) {
UsuarioDto dUs = new UsuarioDto();
dUs.setNome(u.getNome());
dUs.setCpf(u.getCpf());
return dUs;
}
public static List<UsuarioDto> converter(List<Usuario> usuario){
return usuario.stream().map(us -> converter (us)).collect(Collectors.toList());
}
}
|
package com.glassboxtech.evansmunatsa.lincoln.activities;//package com.glassboxtech.evansmunatsa.lincoln.activities;
import com.glassboxtech.evansmunatsa.lincoln.R;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class DataViewActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private AlbumsAdapter adapter;
private List<Album> albumList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_view);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
albumList = new ArrayList<>();
adapter = new AlbumsAdapter(this, albumList);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
prepareAlbums();
}
/**
* Adding few albums for testing
*/
private void prepareAlbums() {
int[] covers = new int[]{
R.drawable.gengame,
R.drawable.g2000,
R.drawable.g4000,
R.drawable.g9000,
R.drawable.lito,
R.drawable.xbox1,
R.drawable.tvbox2,
R.drawable.smartwatch,
R.drawable.wristwatchy5,
R.drawable.rainbow,
R.drawable.album11};
Album a = new Album("Gen Game Bluetooth Controller ", 13, covers[0]);
albumList.add(a);
a = new Album("g2000", 8, covers[1]);
albumList.add(a);
a = new Album("G4000", 11, covers[2]);
albumList.add(a);
a = new Album("g9000", 12, covers[3]);
albumList.add(a);
a = new Album("Lito T3", 14, covers[4]);
albumList.add(a);
a = new Album("Xbox1 Bluetooth controller", 1, covers[5]);
albumList.add(a);
a = new Album("MXQ Pro", 11, covers[6]);
albumList.add(a);
a = new Album("Smart watch DZ 09", 14, covers[7]);
albumList.add(a);
a = new Album("Y5 Smart watch", 11, covers[8]);
albumList.add(a);
a = new Album("Airpods", 17, covers[9]);
albumList.add(a);
adapter.notifyDataSetChanged();
}
/**
* RecyclerView item decoration - give equal margin around grid item
*/
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
/**
* Converting dp to pixel
*/
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
}
|
/*
Copyright (C) 2013-2014, Securifera, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Securifera, Inc nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
Pwnbrew is provided under the 3-clause BSD license above.
The copyright on this package is held by Securifera, Inc
*/
/*
* LogMsg.java
*
* Created on June 7, 2013, 11:01:10 PM
*/
package pwnbrew.network.control.messages;
import java.io.UnsupportedEncodingException;
import pwnbrew.host.HostController;
import pwnbrew.log.Log;
import pwnbrew.log.LogLevel;
import pwnbrew.manager.PortManager;
import pwnbrew.manager.ServerManager;
import pwnbrew.network.ControlOption;
/**
*
*
*/
@SuppressWarnings("ucd")
public final class LogMsg extends ControlMessage {
private static final byte OPTION_LOG_MSG = 21;
private String theMessage = "";
public static final short MESSAGE_ID = 0x40;
//Class name
private static final String NAME_Class = LogMsg.class.getSimpleName();
// ==========================================================================
/**
* Constructor
*
* @param passedId
*/
public LogMsg( byte[] passedId ) {
super(passedId);
}
//=========================================================================
/**
* Sets the variable in the message related to this TLV
*
* @param tempTlv
* @return
*/
@Override
public boolean setOption( ControlOption tempTlv ){
boolean retVal = true;
try {
byte[] theValue = tempTlv.getValue();
switch( tempTlv.getType()){
case OPTION_LOG_MSG:
theMessage = new String( theValue, "US-ASCII");
break;
default:
retVal = false;
break;
}
} catch (UnsupportedEncodingException ex) {
ex = null;
}
return retVal;
}
//===============================================================
/**
* Returns the number of seconds to sleep before trying to connect to the server.
*
* @return
*/
public String getMessage() {
return theMessage;
}
//===============================================================
/**
* Performs the logic specific to the message.
*
* @param passedManager
*/
@Override
public void evaluate( PortManager passedManager ) {
if( passedManager instanceof ServerManager ){
ServerManager theManager = (ServerManager)passedManager;
String clientIdStr = Integer.toString( getSrcHostId() );
//Get the host controller
HostController theController = theManager.getHostController( clientIdStr );
if( theController != null ){
String hostStr = theController.getItemName();
StringBuilder aSB = new StringBuilder();
aSB.append("Remote Exception: ").append(hostStr).append("-").append(theMessage);
//Log it
Log.log( LogLevel.SEVERE, NAME_Class, "evaluate()", aSB.toString(), null );
}
}
}
}
|
package Basic_of_OOP.calendar;
import java.time.LocalDate;
//Задача 3.
//Создать класс Календарь с внутренним классом, с помощью объектов которого можно хранить информацию о
//выходных и праздничных днях.
public class Main {
public static void main(String []args){
Calendar calendar = new Calendar();
calendar.addDate(new Calendar().new Weekend(LocalDate.of(2021, 3, 20), HolidayType.WEEKEND));
calendar.addDate(new Calendar().new Weekend(LocalDate.of(2021, 3, 21), HolidayType.WEEKEND));
calendar.addDate(new Calendar().new Weekend(LocalDate.of(2021, 5, 9), HolidayType.FESTIVE));
calendar.addDate(new Calendar().new Weekend(LocalDate.of(2021, 7, 3), HolidayType.FESTIVE));
calendar.addDate(new Calendar().new Weekend(LocalDate.of(2021, 4, 4), HolidayType.FESTIVE));
calendar.addDate(new Calendar().new Weekend(LocalDate.of(2021, 5, 9), HolidayType.FESTIVE));
calendar.addDate(new Calendar().new Weekend(LocalDate.of(2021, 5, 2), HolidayType.FESTIVE));
calendar.showHolidays();
}
}
|
/*
* Copyright 2014 Basho Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.basho.riak.client.api.convert;
import com.basho.riak.client.core.query.Location;
import com.basho.riak.client.core.query.Namespace;
import com.basho.riak.client.core.query.RiakObject;
import com.basho.riak.client.core.util.BinaryValue;
/**
* Converter that passes Strings through unmodified.
*
* Worth noting is that when using String directly with StoreValue
* there's no way to determine the character set. This converter uses the
* default character set for conversion.
*
* @author Brian Roach <roach at basho dot com>
* @since 2.0
*/
public class StringConverter extends Converter<String>
{
public StringConverter()
{
super(String.class);
}
@Override
public String toDomain(RiakObject obj, Location location)
{
return obj.getValue().toString();
}
@Override
public Converter.OrmExtracted fromDomain(String domainObject, Namespace namespace, BinaryValue key)
{
RiakObject obj = new RiakObject()
.setValue(BinaryValue.create(domainObject))
.setContentType("text/plain");
return new Converter.OrmExtracted(obj, namespace, key);
}
@Override
public String toDomain(BinaryValue value, String contentType) throws ConversionException
{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public ContentAndType fromDomain(String domainObject) throws ConversionException
{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_3.8.2/xslt/JavaClass.xsl
package com.aof.webapp.form.helpdesk;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import com.shcnc.struts.form.BaseQueryForm;
/**
* MyEclipse Struts
* Creation date: 12-01-2004
*
* XDoclet definition:
* @struts:form name="tableTypeQueryForm"
*/
public class TableTypeQueryForm extends BaseQueryForm {
// --------------------------------------------------------- Instance Variables
/** desc property */
private String desc="";
private String disabledTableType="";
// --------------------------------------------------------- Methods
/**
* Returns the desc.
* @return String
*/
public String getDesc() {
return desc;
}
/**
* Set the desc.
* @param desc The desc to set
*/
public void setDesc(String desc) {
this.desc = desc;
}
/**
* @return Returns the disabledTableType.
*/
public String getDisabledTableType() {
return disabledTableType;
}
/**
* @param disabledTableType The disabledTableType to set.
*/
public void setDisabledTableType(String disabledTableType) {
this.disabledTableType = disabledTableType;
}
}
|
public class Hope {
public void hope(String people, boolean success) {
if (success==false) {
System.out.println("Надежды "+people+" оказались напрасными");
} else {
System.out.println("Надежды "+people+" оказались ненапрасными");
}
}
}
|
package com.kopo.memoprogram;
public class Memo {
int idx;
String title;
String content;
String created;
String updated;
int userIdx;
Memo() {
}
Memo(String new_title, String new_content, String first_created, String now, int userIdx) {
this.title = new_title;
this.content = new_content;
this.created = first_created;
this.updated = now;
this.userIdx = userIdx;
}
Memo(int idx, String new_title, String new_content, String first_created, String now) {
this.idx = idx;
this.title = new_title;
this.content = new_content;
this.created = first_created;
this.updated = now;
}
}
|
package com.nisira.core.entity;
import com.nisira.annotation.ClavePrimaria;
import com.nisira.annotation.Columna;
import com.nisira.annotation.Tabla;
import com.google.gson.annotations.SerializedName;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import java.io.Serializable;
import java.util.Date;
import java.util.ArrayList;
@Tabla(nombre = "TSYNCMOVIL")
@XStreamAlias("TSYNCMOVIL")
public class Tsyncmovil implements Serializable {
@ClavePrimaria
@Columna
@SerializedName("idempresa")
@XStreamAlias("IDEMPRESA")
private String idempresa = "" ;
@ClavePrimaria
@Columna
@SerializedName("idappmovil")
@XStreamAlias("IDAPPMOVIL")
private String idappmovil = "" ;
@ClavePrimaria
@Columna
@SerializedName("tabla")
@XStreamAlias("TABLA")
private String tabla = "" ;
@ClavePrimaria
@Columna
@SerializedName("item")
@XStreamAlias("ITEM")
private Integer item;
@Columna
@SerializedName("datos")
@XStreamAlias("DATOS")
private String datos = "" ;
@Columna
@SerializedName("idseriemovil")
@XStreamAlias("IDSERIEMOVIL")
private String idseriemovil = "" ;
@Columna
@SerializedName("fecha")
@XStreamAlias("FECHA")
private Date fecha;
@Columna
@SerializedName("idusuario")
@XStreamAlias("IDUSUARIO")
private String idusuario = "" ;
@Columna
@SerializedName("type")
@XStreamAlias("TYPE")
private String type = "" ;
/* Sets & Gets */
public void setIdempresa(String idempresa) {
this.idempresa = idempresa;
}
public String getIdempresa() {
return this.idempresa;
}
public void setIdappmovil(String idappmovil) {
this.idappmovil = idappmovil;
}
public String getIdappmovil() {
return this.idappmovil;
}
public void setTabla(String tabla) {
this.tabla = tabla;
}
public String getTabla() {
return this.tabla;
}
public void setItem(Integer item) {
this.item = item;
}
public Integer getItem() {
return this.item;
}
public void setDatos(String datos) {
this.datos = datos;
}
public String getDatos() {
return this.datos;
}
public void setIdseriemovil(String idseriemovil) {
this.idseriemovil = idseriemovil;
}
public String getIdseriemovil() {
return this.idseriemovil;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public Date getFecha() {
return this.fecha;
}
public void setIdusuario(String idusuario) {
this.idusuario = idusuario;
}
public String getIdusuario() {
return this.idusuario;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
/* Sets & Gets FK*/
}
|
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
/*
* Header
* @Author: Aaron Lack, alack
* Last edited: 3/11/20
* Class Oval, inherits Shape.
* Create instance variables radius1 and radius2
* The area and circumference will also be slightly different than Oval, so override that as well.
* Will be less code than the inherited method.
*/
public class Oval extends Shape{
//x and y are the locations
//An oval has a radius1 a, and a radius2 b, where a > b. similar to height and width
private int radius1;
private int radius2;
//Constructor number 1: border color and a fill color
public Oval(Color fillColor, Color borderColor, int x, int y, int radius1, int radius2) {
super(fillColor, borderColor, x, y);
this.radius1 = radius1;
this.radius2 = radius2;
}
//Second constructor case for set borderColor to Black since not provided
public Oval(Color fillColor, int x, int y, int radius1, int radius2) {
super(fillColor, x, y);
this.radius1 = radius1;
this.radius2 = radius2;
}
//Third constructor case: set fillColor to white and border color to black
public Oval(int x, int y, int radius1, int radius2) {
super(x,y);
this.radius1 = radius1;
this.radius2 = radius2;
}
public int getRadius2() {
return radius2;
}
public void setRadius2(int radius2) {
this.radius2 = radius2;
}
public void setRadius1(int radius1) {
this.radius1 = radius1;
}
//Name of shape, color and location, area, and perimeter of shape
public String toString() {
return "[" + "Name of Shape: Oval " + "Location: " + this.getLocation() + "Fill Color: " + this.getFillColor() + "Border Color: " + this.getBorderColor() + "Area: " + this.getArea() + "Circumference: " + this.getPerimeter() + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Oval other = (Oval) obj;
if (radius1 != other.radius1)
return false;
if (radius2 != other.radius2)
return false;
return true;
}
//Gets radius1 for the circle when overriding the area and perimeter methods.
public int getRadius1() {
return radius1;
}
@Override
void draw(Graphics g) {
g.drawOval(this.getX(), this.getY(), radius1, radius2);
g.fillOval(this.getX(), this.getY(), radius1, radius2);
}
@Override
double getArea() {
return Math.PI * radius1 * radius2;
}
@Override
//This is an approx of the circumference sine the equation for this shape is complicated.
double getPerimeter() {
return 2 * Math.PI * Math.sqrt((radius1 + radius2) /2);
}
}
|
package com.leo_sanchez.itunestopalbums.Activities.Main;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.leo_sanchez.itunestopalbums.Utilities.BitMapUtility;
import com.leo_sanchez.itunestopalbums.Models.Album;
import com.leo_sanchez.itunestopalbums.R;
import java.util.List;
/**
* Created by ldjam on 3/29/2018.
*/
class ListRecyclerViewAdapter extends RecyclerView.Adapter<AlbumViewHolder> {
private final List<Album> mAlbums;
public ListRecyclerViewAdapter(List<Album> mAlbums) {
this.mAlbums = mAlbums;
}
@Override
public AlbumViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.album_list_item, parent, false);
return new AlbumViewHolder(view);
}
@Override
public void onBindViewHolder(AlbumViewHolder holder, int position) {
Album album = mAlbums.get(position);
holder.mAlbum =album;
holder.mAlbumName.setText(album.name);
holder.mAlbumArtist.setText(album.atist);
holder.mAlbumCover.setImageBitmap(BitMapUtility.loadBitmap(album.getThumbnail()));
holder.mAlbumId.setText(album.id);
}
@Override
public int getItemCount() {
return mAlbums.size();
}
}
|
import Lists.ListNode;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import static java.util.Arrays.asList;
/**
* Created by Daniel on 2/7/2017.
*/
public class ListNodeTest {
private static ListNode sut;
@BeforeClass
public static void init(){
sut = new ListNode(1);
}
@Test
public void test1(){
ArrayList expected = new ArrayList(asList(1));
Assert.assertEquals(expected, sut.toList());
}
@Test
public void test2(){
sut.next = new ListNode(2);
ArrayList expected = new ArrayList(asList(1, 2));
Assert.assertEquals(expected, sut.toList());
}
}
|
/**
* Copyright 2014 Google
*
* 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.example.android.io2014;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Outline;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Bundle;
import android.support.v7.graphics.Palette;
import android.transition.Transition;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewOutlineProvider;
import android.view.WindowInsets;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android.io2014.ui.AnimatedPathView;
import com.example.android.io2014.ui.TransitionAdapter;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class DetailActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Bitmap photo = setupPhoto(getIntent().getIntExtra("photo", R.drawable.photo1));
colorize(photo);
setupMap();
setupText();
setOutlines(R.id.star, R.id.info);
applySystemWindowsBottomInset(R.id.container);
getWindow().getEnterTransition().addListener(new TransitionAdapter() {
@Override
public void onTransitionEnd(Transition transition) {
ImageView hero = (ImageView) findViewById(R.id.photo);
ObjectAnimator color = ObjectAnimator.ofArgb(hero.getDrawable(), "tint",
getResources().getColor(R.color.photo_tint), 0);
color.start();
findViewById(R.id.info).animate().alpha(1.0f);
findViewById(R.id.star).animate().alpha(1.0f);
getWindow().getEnterTransition().removeListener(this);
}
});
}
@Override
public void onBackPressed() {
ImageView hero = (ImageView) findViewById(R.id.photo);
ObjectAnimator color = ObjectAnimator.ofArgb(hero.getDrawable(), "tint",
0, getResources().getColor(R.color.photo_tint));
color.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
finishAfterTransition();
}
});
color.start();
findViewById(R.id.info).animate().alpha(0.0f);
findViewById(R.id.star).animate().alpha(0.0f);
}
private void setupText() {
TextView titleView = (TextView) findViewById(R.id.title);
titleView.setText(getIntent().getStringExtra("title"));
TextView descriptionView = (TextView) findViewById(R.id.description);
descriptionView.setText(getIntent().getStringExtra("description"));
}
private void setupMap() {
GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
double lat = getIntent().getDoubleExtra("lat", 37.6329946);
double lng = getIntent().getDoubleExtra("lng", -122.4938344);
float zoom = getIntent().getFloatExtra("zoom", 15.0f);
LatLng position = new LatLng(lat, lng);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, zoom));
map.addMarker(new MarkerOptions().position(position));
}
private void setOutlines(int star, int info) {
final int size = getResources().getDimensionPixelSize(R.dimen.floating_button_size);
final ViewOutlineProvider vop = new ViewOutlineProvider() {
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, size, size);
}
};
findViewById(star).setOutlineProvider(vop);
findViewById(info).setOutlineProvider(vop);
}
private void applySystemWindowsBottomInset(int container) {
View containerView = findViewById(container);
containerView.setFitsSystemWindows(true);
containerView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
if (metrics.widthPixels < metrics.heightPixels) {
view.setPadding(0, 0, 0, windowInsets.getSystemWindowInsetBottom());
} else {
view.setPadding(0, 0, windowInsets.getSystemWindowInsetRight(), 0);
}
return windowInsets.consumeSystemWindowInsets();
}
});
}
private void colorize(Bitmap photo) {
Palette palette = Palette.generate(photo);
applyPalette(palette);
}
private void applyPalette(Palette palette) {
getWindow().setBackgroundDrawable(new ColorDrawable(palette.getDarkMutedColor().getRgb()));
TextView titleView = (TextView) findViewById(R.id.title);
titleView.setTextColor(palette.getVibrantColor().getRgb());
TextView descriptionView = (TextView) findViewById(R.id.description);
descriptionView.setTextColor(palette.getLightVibrantColor().getRgb());
colorRipple(R.id.info, palette.getDarkMutedColor().getRgb(),
palette.getDarkVibrantColor().getRgb());
colorRipple(R.id.star, palette.getMutedColor().getRgb(),
palette.getVibrantColor().getRgb());
View infoView = findViewById(R.id.information_container);
infoView.setBackgroundColor(palette.getLightMutedColor().getRgb());
AnimatedPathView star = (AnimatedPathView) findViewById(R.id.star_container);
star.setFillColor(palette.getVibrantColor().getRgb());
star.setStrokeColor(palette.getLightVibrantColor().getRgb());
}
private void colorRipple(int id, int bgColor, int tintColor) {
View buttonView = findViewById(id);
RippleDrawable ripple = (RippleDrawable) buttonView.getBackground();
GradientDrawable rippleBackground = (GradientDrawable) ripple.getDrawable(0);
rippleBackground.setColor(bgColor);
ripple.setColor(ColorStateList.valueOf(tintColor));
}
private Bitmap setupPhoto(int resource) {
Bitmap bitmap = MainActivity.sPhotoCache.get(resource);
((ImageView) findViewById(R.id.photo)).setImageBitmap(bitmap);
return bitmap;
}
public void showStar(View view) {
toggleStarView();
}
private void toggleStarView() {
final AnimatedPathView starContainer = (AnimatedPathView) findViewById(R.id.star_container);
if (starContainer.getVisibility() == View.INVISIBLE) {
findViewById(R.id.photo).animate().alpha(0.2f);
starContainer.setAlpha(1.0f);
starContainer.setVisibility(View.VISIBLE);
starContainer.reveal();
} else {
findViewById(R.id.photo).animate().alpha(1.0f);
starContainer.animate().alpha(0.0f).withEndAction(new Runnable() {
@Override
public void run() {
starContainer.setVisibility(View.INVISIBLE);
}
});
}
}
public void showInformation(View view) {
toggleInformationView(view);
}
private void toggleInformationView(View view) {
final View infoContainer = findViewById(R.id.information_container);
int cx = (view.getLeft() + view.getRight()) / 2;
int cy = (view.getTop() + view.getBottom()) / 2;
float radius = Math.max(infoContainer.getWidth(), infoContainer.getHeight()) * 2.0f;
Animator reveal;
if (infoContainer.getVisibility() == View.INVISIBLE) {
infoContainer.setVisibility(View.VISIBLE);
reveal = ViewAnimationUtils.createCircularReveal(
infoContainer, cx, cy, 0, radius);
reveal.setInterpolator(new AccelerateInterpolator(2.0f));
} else {
reveal = ViewAnimationUtils.createCircularReveal(
infoContainer, cx, cy, radius, 0);
reveal.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
infoContainer.setVisibility(View.INVISIBLE);
}
});
reveal.setInterpolator(new DecelerateInterpolator(2.0f));
}
reveal.setDuration(600);
reveal.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.detail, menu);
return true;
}
}
|
package jthrift;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class TConstValue {
public static enum Type {
INTEGER,
DOUBLE,
STRING,
MAP,
LIST,
IDENTIFIER
}
Map<TConstValue, TConstValue> mapVal;
List<TConstValue> listVal;
String stringVal;
IConst intVal;
DConst doubleVal;
Id identifierVal;
TEnum enumVal;
Type valType;
public TConstValue() {}
public TConstValue(String s) {
setString(s);
}
public TConstValue(IConst i) {
setInteger(i);
}
private void setString(String s) {
stringVal = s;
valType = Type.STRING;
}
public void setEnum(TEnum tenum) {
enumVal = tenum;
// used with identifier
}
public void setInteger(IConst iconst) {
intVal = iconst;
valType = Type.INTEGER;
}
public void setDouble(DConst dconst) {
doubleVal = dconst;
valType = Type.DOUBLE;
}
public void setIdentifier(Id id) {
identifierVal = id;
valType = Type.IDENTIFIER;
}
public void addList(TConstValue value) {
if (listVal == null) listVal = new LinkedList<TConstValue>();
listVal.add(value);
}
public void setList() {
valType = Type.LIST;
}
public void addMap(TConstValue key, TConstValue value) {
if (mapVal == null) mapVal = new HashMap<TConstValue, TConstValue>();
mapVal.put(key, value);
}
public void setMap() {
valType = Type.MAP;
}
}
|
package com.training.iface;
@FunctionalInterface
public interface Converter {
public double dollarToInr(double val);
}
|
package me.arasple.mc.uncrafter;
import io.izzel.taboolib.module.config.TConfig;
import io.izzel.taboolib.module.inject.TInject;
import io.izzel.taboolib.module.locale.TLocale;
import io.izzel.taboolib.module.locale.logger.TLogger;
import me.arasple.mc.uncrafter.bstats.Metrics;
import me.arasple.mc.uncrafter.objects.UncrafterItem;
/**
* @author Arasple
*/
@UncrafterPlugin.Version(5.04)
public final class Uncrafter extends UncrafterPlugin {
@TInject
private static Uncrafter instance;
private static UncrafterItem uncrafterItem;
@TInject("§3L§bChat")
private static TLogger logger;
@TInject("settings.yml")
private static TConfig settings;
public static TLogger getTLogger() {
return logger;
}
public static TConfig getSettings() {
return settings;
}
public static Uncrafter getInstance() {
return instance;
}
public static UncrafterItem getUncrafterItem() {
return uncrafterItem;
}
@Override
public void onStarting() {
settings.listener(() -> {
loadUncrafterItem();
getTLogger().fine("&7重新载入配置...");
});
loadUncrafterItem();
new Metrics(this);
TLocale.sendToConsole("PLUGIN.ENABLED", getDescription().getVersion());
}
@Override
public void onStopping() {
}
private void loadUncrafterItem() {
uncrafterItem = new UncrafterItem(settings.getString("UNCREATER-ITEM.ID", "PLAYER_HEAD"), settings.getString("UNCREATER-ITEM.SKULL-TEXTURE", null), settings.getStringColored("UNCREATER-ITEM.NAME", "§f分解者"), settings.getStringListColored("UNCREATER-ITEM.LORES"), settings.getBoolean("UNCREATER-ITEM.SNEAKING-OPEN", false));
}
}
|
import java.util.ArrayList;
public class ViewIncome {
private ArrayList accountTransaction = new ArrayList();
private String account = new String();
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public ArrayList getAccountTransaction() {
return accountTransaction;
}
public void setAccountTransaction(ArrayList accountTransaction) {
this.accountTransaction = accountTransaction;
}
public ViewIncome(String account, ArrayList accountTransaction) {
super();
this.account = account;
this.accountTransaction = accountTransaction;
}
}
|
package org.carlook.gui.views;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.server.VaadinSession;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.*;
import org.carlook.gui.components.TopPanel;
import org.carlook.gui.windows.InseratPopUp;
import org.carlook.model.objects.entities.Auto;
import org.carlook.model.objects.dao.AutoDAO;
import org.carlook.model.objects.entities.User;
import org.carlook.services.util.GridBuild;
import org.carlook.services.util.Konstanten;
import org.carlook.services.util.Roles;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class VertrieblerMainView extends VerticalLayout implements View {
User user;
public void enter(ViewChangeListener.ViewChangeEvent event) {
user = (User) VaadinSession.getCurrent().getAttribute(Roles.CURRENT);
if(user == null || !user.getRole().equals(Roles.VERTRIEBLER)) UI.getCurrent().getNavigator().navigateTo(Konstanten.START);
else this.setUp();
}
public void setUp() {
Label spacer = new Label(" ", ContentMode.HTML);
InseratPopUp inserat = new InseratPopUp();
Button addAuto = new Button("Neues Auto hinzufügen", VaadinIcons.PLUS);
addAuto.addClickListener(e-> {
UI.getCurrent().addWindow(inserat);
inserat.setModal(true);
});
addAuto.setId("addButton");
addAuto.setDescription("Klicken sie hier, um ein neues Auto einzustellen.");
inserat.addCloseListener(e-> UI.getCurrent().getNavigator().navigateTo(Konstanten.VER_MAIN));
HorizontalLayout buttonPan = new HorizontalLayout();
buttonPan.addComponents(addAuto);
List<Auto> autos = null;
try {
autos = AutoDAO.getInstance().getMyAutos(user.getVerId());
} catch (SQLException throwables) {
Logger.getLogger(ReservierteAutosView.class.getName()).log(Level.SEVERE, null, throwables);
}
Grid<Auto> autoGrid = GridBuild.basicGrid(autos);
autoGrid.setCaption(" <span style='color:#EAECEC; font-size:25px; text-shadow: 1px 1px 1px black; font-family: Roboto, sans-serif;'> " + "Meine inserierten Autos: " + " </span>");
VerticalLayout content = new VerticalLayout();
content.addComponents(new TopPanel(), spacer, buttonPan, autoGrid);
content.setComponentAlignment(buttonPan, Alignment.MIDDLE_RIGHT);
this.addComponents(content);
this.setComponentAlignment(content, Alignment.MIDDLE_CENTER);
}
}
|
package com.bestone.service.Impl;
import com.bestone.dao.CommentDao;
import com.bestone.dao.UserDao;
import com.bestone.model.CommentModel;
import com.bestone.model.UserModel;
import com.bestone.service.CommentService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Service
public class CommentServiceImpl implements CommentService {
Logger log = Logger.getLogger(CommentServiceImpl.class);
@Resource
private CommentDao dao;
@Resource
private UserDao userDao;
//写文章的根评论
public void addRootComment(CommentModel comment){
log.debug("-------------------->>addRootComment"+comment);
dao.addRootComment(comment);
}
//获取文章根评论
public List<CommentModel> getRootComments(CommentModel comment){
List<CommentModel> rootComments=null;
try{
rootComments=dao.getRootComments(comment);
log.debug("-------------------->>>>> getRootComments");
}catch (Exception e){
log.debug("-------------------->>>>> getRootComments error");
}
return rootComments;
}
//查询文章子评论
public List<CommentModel> getChildComments(CommentModel comment){
List<CommentModel> childComments=null;
try{
log.debug("-------------------->>>>> getChildComments");
childComments=dao.getChildComments(comment);
if(childComments!=null){
for(CommentModel child:childComments){
UserModel temp=new UserModel();
temp.setPhoneNum(child.getPhoneNum());
UserModel author=userDao.getUserById(temp);
child.setUserName(author.getUserName());
temp.setPhoneNum(child.getReply_id());
UserModel replyName=userDao.getUserById(temp);
child.setReplyName(replyName.getUserName());
log.debug("------------------>>>>>>>>>>>>>>>>>childComment=============="+child);
}
}
}catch (Exception e){
log.debug("-------------------->>>>> getChildComments error");
childComments=null;
}
return childComments;
}
//写回复评论
public void addReplyComment(CommentModel comment){
try{
dao.addReplyComment(comment);
log.debug("-------------------->>>>> addReplyComment");
}catch (Exception e){
e.printStackTrace();
log.debug("-------------------->>>>> addReplyComment error");
}
}
}
|
package persistence;
import exception.DaoException;
import model.Statistics;
import model.Article;
import java.util.List;
public interface StatisticsDao {
/**
* Adds statistics to database.
* @param stats the Statistics to add
* @return userID if successful
* @throws DaoException if no connection can be established with database
*/
int add(Statistics stats) throws DaoException;
/**
* Lists all statistics in database.
* @return list of statistics if successful
* @throws DaoException if no connection can be established with database
*/
List<Statistics> listAll() throws DaoException;
/**
* Deletes statistic from database.
* @param userID the id of the user
* @return If sql query is successfully executed, true is returned
* @throws DaoException if no connection can be established with database
*/
boolean delete(int userID) throws DaoException;
/**
* Updates statistics in database.
* @param id the id of the User.
* @param articles article history of User
* @return If sql query is successfully executed, true is returned
* @throws DaoException if no connection can be established with database
*/
boolean update(int id, List<Article> articles) throws DaoException;
/**
* Finds statistics in database.
* @param userID the id of the User whose Statistics are to be found
* @return the list of Statistics matching userID
* @throws DaoException if no connection can be established with database
*/
List<Statistics> find(int userID) throws DaoException;
}
|
package com.suifeng.javaparsertool;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import com.github.javaparser.symbolsolver.JavaSymbolSolver;
import com.github.javaparser.symbolsolver.model.resolution.TypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.suifeng.javaparsertool.operation.ClassOp;
import com.suifeng.javaparsertool.operation.GenerationOp;
import com.suifeng.javaparsertool.operation.MethodOp;
import com.suifeng.javaparsertool.operation.XmlOp;
import com.suifeng.javaparsertool.support.config.Config;
import com.suifeng.javaparsertool.support.data.ClassGroup;
import com.suifeng.javaparsertool.support.data.MethodData;
import com.suifeng.javaparsertool.support.data.MethodGroup;
import com.suifeng.javaparsertool.support.utils.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class Main {
private static Map<String, String> mAllStringMap = new HashMap<>();//所有非空字符串的map,用于生成sdkToolConfig.xml
private static ClassGroup mClassGroup;//所有类信息
private static MethodGroup mMethodGroup;//所有方法信息
public static JavaParser mJavaParser;//解析类对象
public static Config mConfig;//随机配置信息
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("args length error");
return;
}
Gson gson = new Gson();
try {
mConfig = gson.fromJson(args[0], Config.class);
} catch (JsonSyntaxException e) {
System.out.println("json error");
return;
}
if (mConfig.getType() == 0) {
randomForeign();
} else if (mConfig.getType() == 1) {
randomQlj();
} else {
System.out.println("type error");
}
}
private static void randomQlj() {
}
private static void randomForeign() {
File projectDir = new File(mConfig.getSrcPath());
if (!projectDir.exists()) {
System.out.println("projectDir is not exist");
return;
}
initJavaParser(projectDir);
buildClassesGroup(projectDir);
buildMethodGroup();
buildAllStringsMap();
if (mClassGroup.getClassCount() <= 0) {
System.out.println("there is no class");
return;
}
if (mMethodGroup.getMethodCount() <= 0) {
System.out.println("there is no method");
return;
}
File outFileDir = new File(mConfig.getOutPath() + File.separator);
initDir(outFileDir);
ArrayList<MethodData> allMethods = mMethodGroup.getAllMethodAsList();
Collections.shuffle(allMethods);//乱序
//生成每个类的CompilationUnit
ArrayList<CompilationUnit> allClassUnits = GenerationOp.CompilationUnitGenerate(mConfig.getClassCount(), mConfig.getPackageName(), mConfig.getPreClassName());
//分配每个类的方法个数
Map<Integer, Integer> methodCountMap = ClassOp.getMethodCountInClasses(allMethods.size(), mConfig.getMethodLowLimit(), mConfig.getClassCount());
int methodIndex = 0;
//记录方法被分配到的类
for (int i = 0; i < allClassUnits.size(); i++) {
String classFileName = mConfig.getPreClassName() + i;
int methodCount = methodCountMap.get(i);
for (int j = 0; j < methodCount; j++) {
MethodData srcMethod = allMethods.get(methodIndex++);
srcMethod.setBelongToClass(classFileName);
}
}
if (!Utils.isStringEmpty(mConfig.getConfigXmlName())) {
XmlOp.getInstance(mConfig).buildXml(mConfig.getOutPath() + File.separator + mConfig.getConfigXmlName(), mConfig.getClassCount(), mConfig.getPreClassName(), mMethodGroup.getAllMethodNames(), mAllStringMap, mMethodGroup.getAllMethodMap(), mConfig.getPackageName(), mConfig.getEntryMethod());
}
methodIndex = 0;
//把方法添加到类中
for (int i = 0; i < allClassUnits.size(); i++) {
String classFileName = mConfig.getPreClassName() + i;
CompilationUnit classUnit = allClassUnits.get(i);
ClassOrInterfaceDeclaration thisClass = classUnit.getClassByName(classFileName).get();
int methodCount = methodCountMap.get(i);
//添加方法
for (int j = 0; j < methodCount; j++) {
MethodData methodData = allMethods.get(methodIndex);
MethodDeclaration addMethod = thisClass.addMethod(methodData.getName(), Modifier.publicModifier().getKeyword());
methodIndex++;
MethodOp.cloneMethod(methodData, addMethod);
MethodOp.setMethodScope(addMethod, mMethodGroup.getAllMethodNames(), mMethodGroup.getAllMethodMap());
ArrayList<String> imports = methodData.getImports();
for (String anImport : imports) {
classUnit.addImport(anImport);
}
}
if (outFileDir.exists()) {
ClassOp.generalClassFile(outFileDir, classFileName + ".java", classUnit);
}
}
}
/**
* 初始化JavaParser
*/
private static void initJavaParser(File projectDir) {
ReflectionTypeSolver reflectionTypeSolver = new ReflectionTypeSolver();
JavaParserTypeSolver javaParserTypeSolver = new JavaParserTypeSolver(projectDir);
TypeSolver typeSolver = new CombinedTypeSolver();
((CombinedTypeSolver) typeSolver).add(reflectionTypeSolver);
((CombinedTypeSolver) typeSolver).add(javaParserTypeSolver);
JavaSymbolSolver solver = new JavaSymbolSolver(typeSolver);
mJavaParser = new JavaParser();
mJavaParser.getParserConfiguration().setSymbolResolver(solver);
}
/**
* 构建所有string的map
*/
private static void buildAllStringsMap() {
class ForCount {
int count = 1;
}
ForCount forCount = new ForCount();
ArrayList<MethodData> allMethodList = mMethodGroup.getAllMethodAsList();
//遍历所有方法
for (MethodData method : allMethodList) {
new VoidVisitorAdapter<Object>() {
@Override
public void visit(StringLiteralExpr n, Object arg) {
String matchStr = n.asString();
if (matchStr != null && matchStr.length() > 0 && !matchStr.equals("\"\"") && !":".equals(matchStr) && !"%x".equals(matchStr) && !"true".equals(matchStr) && !"false".equals(matchStr)) {
if ("PluginConfig".equals(matchStr) || "AssetName".equals(matchStr)) {
mAllStringMap.put(matchStr, matchStr);
} else {
mAllStringMap.put(matchStr, "Label" + forCount.count++);
}
}
super.visit(n, arg);
}
}.visit(method.getOriginData(), null);
}
mAllStringMap.put("noIdea", "Label" + forCount.count++);
mAllStringMap.put("loadAttachContext", "Label" + forCount.count++);
}
/**
* 创建所有类的数据集合
*
* @param projectDir 资源目录
*/
private static void buildClassesGroup(File projectDir) {
ArrayList<ClassOrInterfaceDeclaration> allClasses = ClassOp.getAllClasses(projectDir);
//把class排序,把内部类或内部接口放到后面,保证在处理内部类时父类已经处理好了
allClasses.sort((t0, t1) -> {
if ((t0.isNestedType() && t1.isNestedType()) || (!t0.isNestedType() && !t1.isNestedType())) {
return 0;
} else if (t0.isNestedType() && !t1.isNestedType()) {
return 1;
}else {
return -1;
}
});
mClassGroup = new ClassGroup(allClasses);
}
/**
* 创建所有方法的数据集合
*/
private static void buildMethodGroup() {
ArrayList<MethodDeclaration> allMethods = mClassGroup.getAllMethods();
mMethodGroup = new MethodGroup(allMethods, mClassGroup);
}
/**
* 删除文件及目录
*
* @param curFile 当前文件
* @param deleteCur 是否删除当前目录
*/
private static void deleteDirectory(File curFile, boolean deleteCur) {
if (curFile.isDirectory()) {
File[] files = curFile.listFiles();
for (File file : files) {
deleteDirectory(file, true);
}
if (deleteCur) {
curFile.delete();
}
} else {
curFile.delete();
}
}
/**
* 初始化输出路径,有文件就删掉
*
* @param outFileDir
*/
private static void initDir(File outFileDir) {
if (outFileDir.exists()) {
File[] files = outFileDir.listFiles();
if (files != null && files.length > 0) {
deleteDirectory(outFileDir, false);
}
} else {
outFileDir.mkdirs();
}
}
}
|
package com.coder.model;
// Generated Jan 23, 2020 8:11:18 PM by Hibernate Tools 5.0.6.Final
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* PaymentMethod generated by hbm2java
*/
@Entity
@Table(name = "payment_method", catalog = "traveldb")
public class PaymentMethod implements java.io.Serializable {
private Integer paymentMethodId;
private String paymentMethods;
private String cardNumber;
private String cardOwner;
private String securityCode;
private Date expirationDate;
private Set<OrderLine> orderLines = new HashSet<OrderLine>(0);
public PaymentMethod() {
}
public PaymentMethod(String paymentMethods, String cardNumber, String cardOwner, String securityCode,
Date expirationDate) {
this.paymentMethods = paymentMethods;
this.cardNumber = cardNumber;
this.cardOwner = cardOwner;
this.securityCode = securityCode;
this.expirationDate = expirationDate;
}
public PaymentMethod(String paymentMethods, String cardNumber, String cardOwner, String securityCode,
Date expirationDate, Set<OrderLine> orderLines) {
this.paymentMethods = paymentMethods;
this.cardNumber = cardNumber;
this.cardOwner = cardOwner;
this.securityCode = securityCode;
this.expirationDate = expirationDate;
this.orderLines = orderLines;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "payment_method_id", unique = true, nullable = false)
public Integer getPaymentMethodId() {
return this.paymentMethodId;
}
public void setPaymentMethodId(Integer paymentMethodId) {
this.paymentMethodId = paymentMethodId;
}
@Column(name = "payment_methods", nullable = false, length = 100)
public String getPaymentMethods() {
return this.paymentMethods;
}
public void setPaymentMethods(String paymentMethods) {
this.paymentMethods = paymentMethods;
}
@Column(name = "card_number", nullable = false, length = 100)
public String getCardNumber() {
return this.cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
@Column(name = "card_owner", nullable = false, length = 300)
public String getCardOwner() {
return this.cardOwner;
}
public void setCardOwner(String cardOwner) {
this.cardOwner = cardOwner;
}
@Column(name = "security_code", nullable = false, length = 100)
public String getSecurityCode() {
return this.securityCode;
}
public void setSecurityCode(String securityCode) {
this.securityCode = securityCode;
}
@Temporal(TemporalType.DATE)
@Column(name = "expiration_date", nullable = false, length = 10)
public Date getExpirationDate() {
return this.expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "paymentMethod")
public Set<OrderLine> getOrderLines() {
return this.orderLines;
}
public void setOrderLines(Set<OrderLine> orderLines) {
this.orderLines = orderLines;
}
}
|
//Problem No 14 : Longest Common Prefix
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class LongestCommonPrefix {
static String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
int n = strs.length;
String lcp = strs[0];
int l = lcp.length();
for(int i = 1; i < n ; i++){
int index = 0;
while(index < strs[i].length() && index < l &&lcp.charAt(index) == strs[i].charAt(index)){
index++;
}
l = index;
}
return lcp.substring(0, l);
}
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] strs = new String[n];
for(int i = 0; i < strs.length; i++)
strs[i] = br.readLine();
String r =longestCommonPrefix(strs);
System.out.println(r);
}
}
|
package com.example.uiassit;
public class haomiaotoshijian {
public haomiaotoshijian(){
}
//把毫秒数变成时间格式 如 01:00
public String formattime(long time){
time = time/ 1000;
String strHour = "" + (time/3600);
String strMinute = "" + time%3600/60;
String strSecond = "" + time%3600%60;
strHour = strHour.length() < 2? "0" + strHour: strHour;
strMinute = strMinute.length() < 2? "0" + strMinute: strMinute;
strSecond = strSecond.length() < 2? "0" + strSecond: strSecond;
String strRsult = "";
if (!strHour.equals("00"))
{
strRsult += strHour + ":";
}
if (!strMinute.equals("00"))
{
strRsult += strMinute + ":";
}
strRsult += strSecond;
return strRsult;
}
}
|
package controladvanced.duplicate;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
public class DuplicateFinderTest {
@Test
public void findDuplicates() {
assertEquals(Arrays.asList(), new DuplicateFinder().findDuplicates(Arrays.asList()));
assertEquals(Arrays.asList(), new DuplicateFinder().findDuplicates(Arrays.asList(1, 2, 3)));
assertEquals(Arrays.asList(2), new DuplicateFinder().findDuplicates(Arrays.asList(1, 2, 2, 3)));
assertEquals(Arrays.asList(2, 3), new DuplicateFinder().findDuplicates(Arrays.asList(1, 2, 2, 3, 3, 4)));
assertEquals(Arrays.asList(3, 3), new DuplicateFinder().findDuplicates(Arrays.asList(1, 2, 3, 3, 3, 4)));
assertEquals(Arrays.asList(2, 3, 3), new DuplicateFinder().findDuplicates(Arrays.asList(1, 2, 2, 3, 3, 3, 4)));
}
}
|
/*
* (c) 2009 Thomas Smits
*/
package de.smits_net.tpe.abstrakt3;
public abstract class Mitarbeiter {
protected abstract int berechneZahlung();
}
|
package com.wangzhu.spring.scanv2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* Created by wang.zhu on 2020-06-13 21:50.
**/
public class SelfComponentScanRegisteringPostProcessor implements BeanFactoryPostProcessor, ApplicationContextAware, InitializingBean {
protected final Logger logger = LoggerFactory.getLogger(getClass());
private static final List<AbstractComponentHandler> HANDLERS;
static {
final List<AbstractComponentHandler> handlers = new ArrayList<>();
handlers.add(new SelfComponentHandler());
HANDLERS = Collections.unmodifiableList(handlers);
}
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
private Set<String> packagesToScan;
public void setPackagesToScan(Set<String> packagesToScan) {
this.packagesToScan = packagesToScan;
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("packagesToScan===" + packagesToScan);
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("postProcessBeanFactory-----");
final BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
final ClassPathScanningCandidateComponentProvider scanner = getScanner();
for (final String basePackage : packagesToScan) {
scanPackage(registry, scanner, basePackage);
}
}
protected final ClassPathScanningCandidateComponentProvider getScanner() {
final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false) {
};
scanner.setEnvironment(applicationContext.getEnvironment());
scanner.setResourceLoader(applicationContext);
HANDLERS.forEach(abstractComponentHandler -> scanner.addIncludeFilter(abstractComponentHandler.getTypeFilter()));
return scanner;
}
private void scanPackage(final BeanDefinitionRegistry registry, final ClassPathScanningCandidateComponentProvider scanner, final String basePackage) {
final Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(basePackage);
logger.info("detail basePackage|{}|beanDefinitions|{}", basePackage, beanDefinitions);
for (final BeanDefinition candidate : beanDefinitions) {
if (candidate instanceof AnnotatedBeanDefinition) {
HANDLERS.forEach(abstractComponentHandler -> abstractComponentHandler.handler((AnnotatedBeanDefinition) candidate, registry));
}
}
}
}
|
package vnfoss2010.smartshop.webbased.client;
import java.util.List;
import vnfoss2010.smartshop.webbased.share.WProduct;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* @author VoMinhTam
*/
public class RelatedProductsPanel extends VerticalPanel {
private static RelatedProductsPanel instance = null;
// private Grid grid;
private VerticalPanel pnl;
private Image imgThumb;
public static RelatedProductsPanel getInstance() {
if (instance == null)
instance = new RelatedProductsPanel();
return instance;
}
private RelatedProductsPanel() {
initUI();
setStyleName("pnl-related-product");
//initMockTest();
}
private void initUI() {
pnl = new VerticalPanel();
// grid = new Grid(5, 1);
add(pnl);
}
public void showData(List<WProduct> listProducts) {
pnl.clear();
pnl.add(new HTML("<b>Các sản phẩm liên quan:</b> "));
for (WProduct product : listProducts) {
pnl.add(eachProduct(product));
}
}
public void clearData(){
pnl.clear();
}
public Panel eachProduct(final WProduct product) {
HorizontalPanel pnlProduct = new HorizontalPanel();
imgThumb = new Image(product.getRandomThumbImage());
imgThumb.addStyleName("img-product");
imgThumb.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
History.newItem("product;" + product.id);
}
});
imgThumb.addMouseOverHandler(new MouseOverHandler() {
@Override
public void onMouseOver(MouseOverEvent event) {
imgThumb.addStyleName("cursor-pointer");
}
});
imgThumb.addMouseOutHandler(new MouseOutHandler() {
@Override
public void onMouseOut(MouseOutEvent event) {
imgThumb.addStyleName("cursor-default");
}
});
HTML htmlTitle = new HTML("<b>" + product.name + "</b>");
HTML htmlDes = new HTML(product.getShortDescription());
VerticalPanel pnlNameDes = new VerticalPanel();
pnlNameDes.add(htmlTitle);
pnlNameDes.add(htmlDes);
pnlProduct.add(imgThumb);
pnlProduct.add(pnlNameDes);
return pnlProduct;
}
private void initMockTest() {
WebbasedServiceAsync serviceAsync = WebbasedService.Util.getInstance();
serviceAsync.getProduct(58L, new AsyncCallback<WProduct>() {
@Override
public void onSuccess(WProduct result) {
showData(result.listRelatedProduct);
}
@Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
});
}
}
|
package com.company;
public class Coffee extends CaffeinatedBeverage{
// all of the drinks start out witha gradual heating process
@Override
void brewBeverage() {
System.out.println("Dripping coffee through filter.");
}
// the hooks - eliminate the extras that are not wanted
@Override
boolean wantsLemon() {
return false;
}
@Override
boolean wantsSugar() {
return false;
}
}
|
package com.company.leetcode.linkedlist;
import com.company.leetcode.ListNode;
public class LeetCode1290 {
public static int getDecimalValue(ListNode head) {
int result = 0;
while (head != null){
result = 2 * result + head.val;
head = head.next;
}
return result;
}
public static void main(String[] args) {
ListNode root = new ListNode(1);
root.next = new ListNode(0);
root.next.next = new ListNode(1);
System.out.println(getDecimalValue(root));
}
}
|
package com.sportzcourt.booking.ui.activity;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
import com.sportzcourt.booking.R;
import com.sportzcourt.booking.model.events.UserCredsEvent;
import com.sportzcourt.booking.util.AppUtils;
import com.sportzcourt.booking.util.Constants;
import com.sportzcourt.booking.util.UIUtils;
import com.sportzcourt.booking.util.ValidationHelper;
import de.greenrobot.event.EventBus;
/**
* Copyright 2016 (C) Happiest Minds Pvt Ltd..
* <p/>
* <P> Splash Screen, Shows the Privacy Policy, checks for network & does
* some basic app initialisation operations
* <p/>
* <P>Notes:
* <P>Dependency:
*
* @authors Ravindra Kamble (ravindra.kambale@happiestminds.com)
* Sunil Rao S (sunil.sindhe@happiestminds.com)
* @created on: 4-Jan-2016
*/
public class SplashActivity extends Activity {
SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
View parentLayout = findViewById(R.id.root_view);
if (!ValidationHelper.isNetworkAvailable(this)) {
Snackbar.make(parentLayout, "No Network Connection, Auto Exiting...", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}
@Override
protected void onStart() {
super.onStart();
AppUtils.registerToDefaultBus(this, true);
//User is not logged in yet
if (EventBus.getDefault().getStickyEvent(UserCredsEvent.class) == null) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startLoginActivity();
}
}, Constants.App.SPLASH_TIME_IN_MILISECONDS);
}
}
@Override
protected void onStop() {
AppUtils.unregisterFromDefaultBus(this);
super.onStop();
}
private void startLoginActivity() {
View parentLayout = findViewById(R.id.root_view);
if (!ValidationHelper.isNetworkAvailable(this)) {
Snackbar.make(parentLayout, "No Network Connection, Auto Exiting...", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} else {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean(Constants.App.KEY_EULA_ACCEPTED, false)) {
showEula();
return;
}
UIUtils.startActivity(this, LoginActivity.class);
}
this.finish();
}
private void showEula() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("DISCLAIMER");
alert.setCancelable(false);
alert.setMessage("While we work to ensure that product information is correct, on occasion manufacturers may alter their ingredient lists. Actual product packaging and materials may contain more and/or different information than that shown on our Web site. We recommend that you do not solely rely on the information presented and that you always read labels, warnings, and directions before using or consuming a product.");
alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
});
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Determine if EULA was accepted this time
prefs.edit().putBoolean(Constants.App.KEY_EULA_ACCEPTED, true).commit();
startLoginActivity();
}
});
alert.show();
}
private void startMainActivity() {
UIUtils.startActivity(this, MainActivity.class);
this.finish();
}
public void onEvent(UserCredsEvent event) {
if (event.loggedIn) {
//User is already logged in. Launch Main Activity
Toast.makeText(this, event.userName + " is logged in.", Toast.LENGTH_SHORT).show();
startMainActivity();
} else {
//User is not logged in
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startLoginActivity();
}
}, Constants.App.SPLASH_TIME_IN_MILISECONDS);
}
}
}
|
package sr.hakrinbank.intranet.api.controller;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sr.hakrinbank.intranet.api.dto.BlackListedPersonRetailBankingDto;
import sr.hakrinbank.intranet.api.dto.ResponseDto;
import sr.hakrinbank.intranet.api.model.BlackListedPerson;
import sr.hakrinbank.intranet.api.model.BlackListedPersonRetailBanking;
import sr.hakrinbank.intranet.api.service.BlackListedPersonRetailBankingService;
import sr.hakrinbank.intranet.api.util.Constant;
import java.util.ArrayList;
import java.util.List;
/**
* Created by clint on 5/29/17.
*/
@RestController
@RequestMapping(value = "/api/blacklistretailbanking")
public class BlackListedPersonRetailBankingController {
@Autowired
private BlackListedPersonRetailBankingService blackListedPersonRetailBankingService;
//-------------------Retrieve All BlackListedPersonRetailBanking--------------------------------------------------------
@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> listAllBlackListedPersonRetailBanking() {
List<BlackListedPersonRetailBanking> blackListedPersonRetailBanking = blackListedPersonRetailBankingService.findAllActiveBlackListedPersonRetailBanking();
if(blackListedPersonRetailBanking.isEmpty()){
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT);
}
return new ResponseEntity<ResponseDto>(new ResponseDto(mapModelToDto(blackListedPersonRetailBanking), null), HttpStatus.OK);
}
//-------------------Retrieve All BlackListedPersonRetailBanking By Search--------------------------------------------------------
@RequestMapping(value = "search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> listBlackListedPersonRetailBankingBySearchQuery(@RequestParam String qry) {
List<BlackListedPersonRetailBanking> blackListedPersonRetailBanking = blackListedPersonRetailBankingService.findAllActiveBlackListedPersonRetailBankingBySearchQuery(qry);
if(blackListedPersonRetailBanking.isEmpty()){
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT);
}
return new ResponseEntity<ResponseDto>(new ResponseDto(mapModelToDto(blackListedPersonRetailBanking), mapModelToDto(blackListedPersonRetailBanking).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK);
}
//-------------------Retrieve All BlackListedPersonRetailBanking With Pagination--------------------------------------------------------
// @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
// public ResponseEntity<Page<BlackListedPersonRetailBanking>> listAllBlackListedPersonRetailBanking(Pageable pageable) {
// Page<BlackListedPersonRetailBanking> blackListedPersonRetailBanking = blackListedPersonRetailBankingService.findAllBlackListedPersonRetailBankingByPage(pageable);
// return new ResponseEntity<Page<BlackListedPersonRetailBanking>>(blackListedPersonRetailBanking, HttpStatus.OK);
// }
//-------------------Retrieve Single BlackListedPersonRetailBanking--------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BlackListedPersonRetailBanking> getBlackListedPersonRetailBanking(@PathVariable("id") long id) {
System.out.println("Fetching BlackListedPersonRetailBanking with id " + id);
BlackListedPersonRetailBanking blackListedPersonRetailBanking = blackListedPersonRetailBankingService.findById(id);
if (blackListedPersonRetailBanking == null) {
System.out.println("BlackListedPersonRetailBanking with id " + id + " not found");
return new ResponseEntity<BlackListedPersonRetailBanking>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<BlackListedPersonRetailBanking>(blackListedPersonRetailBanking, HttpStatus.OK);
}
//-------------------Create a BlackListedPersonRetailBanking--------------------------------------------------------
@RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> createBlackListedPersonRetailBanking(@RequestBody BlackListedPersonRetailBankingDto blackListedPersonRetailBankingBasisDto) {
System.out.println("Creating BlackListedPersonRetailBanking with name " + blackListedPersonRetailBankingBasisDto.getName());
if (blackListedPersonRetailBankingBasisDto.getId() != null) {
System.out.println("A BlackListedPersonRetailBanking with id " + blackListedPersonRetailBankingBasisDto.getId() + " already exist");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "A BlackListedPersonRetailBanking with id " + blackListedPersonRetailBankingBasisDto.getId() + " already exist"), HttpStatus.CONFLICT);
}
ModelMapper modelMapper = new ModelMapper();
blackListedPersonRetailBankingService.updateBlackListedPersonRetailBanking(modelMapper.map(blackListedPersonRetailBankingBasisDto, BlackListedPersonRetailBanking.class));
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_SAVED), HttpStatus.CREATED);
}
//------------------- Update a BlackListedPersonRetailBanking --------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> updateBlackListedPersonRetailBanking(@PathVariable("id") long id, @RequestBody BlackListedPersonRetailBankingDto blackListedPersonRetailBankingBasisDto) {
System.out.println("Updating BlackListedPersonRetailBanking " + id);
BlackListedPersonRetailBanking currentBlackListedPersonRetailBanking = blackListedPersonRetailBankingService.findById(id);
if (currentBlackListedPersonRetailBanking == null) {
System.out.println("BlackListedPersonRetailBanking with id " + id + " not found");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "BlackListedPersonRetailBanking with id " + id + " not found"), HttpStatus.NOT_FOUND);
}
ModelMapper modelMapper = new ModelMapper();
blackListedPersonRetailBankingService.updateBlackListedPersonRetailBanking(modelMapper.map(blackListedPersonRetailBankingBasisDto, BlackListedPersonRetailBanking.class));
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_UPDATED), HttpStatus.OK);
}
//------------------- Delete a BlackListedPersonRetailBanking --------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<ResponseDto> deleteBlackListedPersonRetailBanking(@PathVariable("id") long id) {
System.out.println("Fetching & Deleting BlackListedPersonRetailBanking with id " + id);
BlackListedPersonRetailBanking blackListedPersonRetailBanking = blackListedPersonRetailBankingService.findById(id);
if (blackListedPersonRetailBanking == null) {
System.out.println("Unable to delete. BlackListedPersonRetailBanking with id " + id + " not found");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "Unable to delete. BlackListedPersonRetailBanking with id " + id + " not found"), HttpStatus.NOT_FOUND);
}
blackListedPersonRetailBanking.setDeleted(true);
blackListedPersonRetailBankingService.updateBlackListedPersonRetailBanking(blackListedPersonRetailBanking);
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_DELETED), HttpStatus.OK);
}
//------------------- HELPER METHODS --------------------------------------------------------
public List<BlackListedPersonRetailBankingDto> mapModelToDto(List<BlackListedPersonRetailBanking> blackListedPersonRetailBanking) {
List<BlackListedPersonRetailBankingDto> blackListedPersonRetailBankingBasisDtoList = new ArrayList<>();
ModelMapper modelMapper = new ModelMapper();
for(BlackListedPerson blackListedPersonRetailBankingItem: blackListedPersonRetailBanking){
if(blackListedPersonRetailBankingItem instanceof BlackListedPersonRetailBanking){
BlackListedPersonRetailBankingDto blackListedPersonRetailBankingBasisDto = modelMapper.map(blackListedPersonRetailBankingItem, BlackListedPersonRetailBankingDto.class);
blackListedPersonRetailBankingBasisDtoList.add(blackListedPersonRetailBankingBasisDto);
}
}
return blackListedPersonRetailBankingBasisDtoList;
}
}
|
package cn.edu.swufe.myapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class TwoPActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two_p);
}
public void onClick(View btn) {
Intent intent=new Intent();
if(btn.getId()==R.id.known){//转到 已知选项
intent.setClass(TwoPActivity.this,KnownActivity.class);//前面是本页面,后面是下一页面
}
else if(btn.getId()==R.id.unknown){//转到 未知选项
intent.setClass(TwoPActivity.this,UnknownActivity.class);//前面是本页面,后面是下一页面
}
else{//转到 我的记录
intent.setClass(TwoPActivity.this,RecordActivity.class);//前面是本页面,后面是下一页面
}
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.menu_index){
Intent list= new Intent(this,BoringActivity.class);
startActivity(list);
}
else if(item.getItemId()==R.id.menu_choice){
//打开列表窗口
Intent list= new Intent(this,TwoPActivity.class);
startActivity(list);
}
else if(item.getItemId()==R.id.menu_record){
//打开列表窗口
Intent list= new Intent(this,RecordActivity.class);
startActivity(list);
}
else{
System.exit(0);
}
return super.onOptionsItemSelected(item);
}
}
|
package com.example.demo.service;
import com.example.demo.entity.FrameworkContract;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author zjp
* @since 2020-11-30
*/
public interface IFrameworkContractService extends IService<FrameworkContract> {
}
|
import java.io.*;
import java.util.*;
public class Main {
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int n = in.nextInt();
int k = in.nextInt();
int[] submissions_length = new int[n];
for (int i = 0; i < n; i++) {
submissions_length[i] = in.nextInt();
}
int time_end = 0;
int current_time = 1;
int[] remaining_test = new int[k];
int[] current_test = new int[k];
int next_job = 0;
for (int i = 0; i < Math.min(n, k); i++) {
remaining_test[i] = submissions_length[i];
time_end = Math.max(time_end, remaining_test[i]);
current_test[i] = i;
next_job++;
}
int finished_job = 0;
int interesting_submission = 0;
HashSet<Integer> interesting_submission_list = new HashSet<>();
while (current_time <= 150 * n) {
// update each process
for (int i = 0; i < k; i++) {
// out.println("remaining test: " + remaining_test[i]);
if (remaining_test[i] == -1) continue;
if (remaining_test[i] >= 0) remaining_test[i]--;
// finished submission
if (remaining_test[i] == -1) {
// out.println("finished job: " + (current_test[i] + 1) + " k: " + (i + 1));
finished_job++;
if (next_job < n) {
current_test[i] = next_job;
remaining_test[i] = submissions_length[next_job] - 1;
time_end = Math.max(time_end, current_time + submissions_length[next_job]);
next_job++;
}
}
}
// calculate interest
long d = Math.round((double) (100 * finished_job) / (double) n);
for (int i = 0; i < k; i++) {
// already interesting!!!
if (interesting_submission_list.contains(current_test[i])) continue;
// already end
if (remaining_test[i] == -1) continue;
// out.println("time: " + current_time + " machine: " + (i + 1) + " %: " + d + " submission: " + (submissions_length[current_test[i]] - remaining_test[i]));
if ((submissions_length[current_test[i]] - remaining_test[i]) == d) {
// out.println("interesting !!!");
interesting_submission++;
interesting_submission_list.add(current_test[i]);
}
}
current_time++;
}
out.println(interesting_submission);
in.close();
out.close();
}
}
|
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* This class stores information for an author including
* metric statistics, maps, and the authors name
* @author Trever Mock
* @version 2.0
*/
public class Author implements Serializable {
/**
* Generated serialVersionUID
*/
private static final long serialVersionUID = -3811976208381351352L;
/** The authors name */
private String name = null;
/** A Map containing words the author uses to their relative frequencies */
private Map<String, Double> wordMap = new HashMap<String, Double>();
/** A Map containing letters the author uses to their relative frequencies */
private Map<Character, Double> letterMap = new HashMap<Character, Double>();
/** A Map containing letter pairs to their relative frequencies */
private Map<String, Double> letterPairMap = new HashMap<String, Double>();
/** Average Sentence Length recorded for this authors works. */
private double avgSentenceLength = -1;
/**
* Constructor that sets the authors name.
* @param name - the name of the author
*/
public Author(String name) {
this.name = name;
this.avgSentenceLength = -1;
}
/**
* Gets the authors name for this object.
* @return the authors name
*/
private String getName() {
return name;
}
/**
* Calculates and returns the average word length
* for this author based on the map of words to
* frequencies stored in the WordMap variable.
* @return the average word length this author uses
*/
public double getAvgWordLength() {
String word;
double lengthSum = 0;
double numberOfWords = 0;
Iterator<String> itr = this.getWordMap().keySet().iterator();
while (itr.hasNext()) {
word = (String) itr.next();
lengthSum = (double) (lengthSum + (word.length() * this.getWordMap().get(word)));
numberOfWords = (double) (numberOfWords + this.getWordMap().get(word));
}
return (lengthSum/numberOfWords);
}
/**
* Calculates and returns the ratio of average
* word length to average sentence length.
* @return average word length / average sentence length
*/
public double getWordToSentenceRatio() {
return (this.getAvgWordLength() / this.avgSentenceLength);
}
/**
* Get the Word Map
* @return the Word Map
*/
public Map<String, Double> getWordMap() {
return this.wordMap;
}
/**
* Get the Letter Map
* @return the Letter Map
*/
public Map<Character, Double> getLetterMap() {
return this.letterMap;
}
/**
* Get the Letter Pair Map
* @return the Letter Pair Map
*/
public Map<String, Double> getLetterPairMap() {
return this.letterPairMap;
}
/**
* Gets the average sentence length for this author.
* @return the average sentence length for this author
*/
public double getAvgSentenceLength() {
return avgSentenceLength;
}
/**
* Sets the average sentence length for this author.
* @param avgSentenceLength - the new average sentence length for this author
*/
public void setAvgSentenceLength(double avgSentenceLength) {
this.avgSentenceLength = avgSentenceLength;
}
/**
* Sets the Word Map for this author.
* @param map - the new Word Map for this author
*/
public void setWordMap(Map<String, Double> map) {
this.wordMap = map;
}
/**
* Sets the Letter Map for this author.
* @param map - the new Letter Map for this author
*/
public void setLetterMap(Map<Character, Double> map) {
this.letterMap = map;
}
/**
* Sets the Letter Pair Map for this author.
* @param map - the new Letter Pair Map for this author
*/
public void setLetterPairMap(Map<String, Double> map) {
this.letterPairMap = map;
}
/**
* Calculates and returns the Vocabulary Richness
* for this author. Vocabulary Richness is calculated
* by dividing the number of words with 1 frequency
* by the total number of words in the map.
* @return - the Vocabulary Richness Metric
*/
@SuppressWarnings({ "rawtypes" })
public Double getVocabularyRichness() {
Iterator itr = this.getWordMap().keySet().iterator();
double richWords = 0;
while (itr.hasNext()) {
Double next = this.getWordMap().get(itr.next());
if (next.equals(new Double(1))) {
richWords++;
}
}
return ((double) richWords) / ((double) this.getWordMap().size());
}
/**
* Calculate and return the most frequent letter used by this author.
* @return the most frequent letter
*/
@SuppressWarnings({ "rawtypes" })
public Character getMostFrequentLetter() {
Iterator itr = this.getLetterMap().values().iterator();
Double tempMost = new Double(0);
Double currentValue;
while (itr.hasNext()) {
currentValue = (Double) itr.next();
if ((double) currentValue > (double) tempMost) {
tempMost = currentValue;
}
}
itr = this.getLetterMap().keySet().iterator();
Character currentChar;
while (itr.hasNext()) {
currentChar = (Character) itr.next();
if (tempMost.equals(this.letterMap.get(currentChar))) {
return currentChar;
}
}
return null;
}
/**
* Calculate and return the least frequent letter used by this author.
* @return the least frequent letter
*/
@SuppressWarnings("rawtypes")
public Character getLeastFrequentLetter() {
Iterator itr = this.getLetterMap().values().iterator();
Double tempLeast = new Double(Integer.MAX_VALUE);
Double currentValue;
while (itr.hasNext()) {
currentValue = (Double) itr.next();
if ((double) currentValue < (double) tempLeast) {
tempLeast = currentValue;
}
}
itr = this.getLetterMap().keySet().iterator();
Character currentChar;
while (itr.hasNext()) {
currentChar = (Character) itr.next();
if (tempLeast.equals(this.letterMap.get(currentChar))) {
return currentChar;
}
}
return null;
}
/**
* Calculate and return the most frequent letter pair used by this author.
* @return the most frequent letter pair
*/
@SuppressWarnings("rawtypes")
public String getMostFrequentLetterPair() {
Iterator itr = this.getLetterPairMap().values().iterator();
Double tempMost = new Double(0);
Double currentValue;
while (itr.hasNext()) {
currentValue = (Double) itr.next();
if ((double) currentValue > (double) tempMost) {
tempMost = currentValue;
}
}
itr = this.getLetterPairMap().keySet().iterator();
String currentPair;
while (itr.hasNext()) {
currentPair = (String) itr.next();
if (tempMost.equals(this.letterPairMap.get(currentPair))) {
return currentPair;
}
}
return null;
}
/**
* Calculate and return the least frequent letter pair used by this author.
* @return the least frequent letter pair
*/
@SuppressWarnings("rawtypes")
public String getLeastFrequentLetterPair() {
Iterator itr = this.getLetterPairMap().values().iterator();
Double tempLeast = new Double(Integer.MAX_VALUE);
Double currentValue;
while (itr.hasNext()) {
currentValue = (Double) itr.next();
if ((double) currentValue < (double) tempLeast) {
tempLeast = currentValue;
}
}
itr = this.getLetterPairMap().keySet().iterator();
String currentPair;
while (itr.hasNext()) {
currentPair = (String) itr.next();
if (tempLeast.equals(this.letterPairMap.get(currentPair))) {
return currentPair;
}
}
return null;
}
/**
* Renders Author as a string.
* @return string rendering of this object
*/
@Override
public String toString() {
return this.getName();
}
}
|
package manager;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.ManagedBean;
import javax.ejb.EJB;
import org.junit.Before;
import org.junit.Test;
import model.AccountType;
import model.ItemDoesNotExistException;
@ManagedBean
public class AccountTypeManagerTest extends EjbContainerTest{
@EJB
private AccountTypeManager accountTypeManager;
AccountType accountType1;
AccountType accountType2;
AccountType accountType3;
@Before
public void init(){
accountType1 = new AccountType("type de compte");
accountType2 = new AccountType("type de compte1");
accountType3 = new AccountType("type de compte2");
}
@Test
public void persistTransactionType() throws Exception{
accountTypeManager.save(accountType1);
AccountType a = accountTypeManager.findByName("type de compte");
assertThat(a.getAccountType(), is("type de compte"));
}
@Test(expected=ItemDoesNotExistException.class)
public void accountTypeDoesNotExist() throws ItemDoesNotExistException{
accountTypeManager.findByName("type de compte inexistant");
}
@Test
public void retrieveAllAccountType(){
accountTypeManager.save(accountType1);
accountTypeManager.save(accountType2);
accountTypeManager.save(accountType3);
List<AccountType> types = accountTypeManager.findAll();
List<String> retrivedTypes = new ArrayList<String>();
List<String> expectedTypes = new ArrayList<String>();
expectedTypes.add("type de compte");
expectedTypes.add("type de compte1");
expectedTypes.add("type de compte2");
for(AccountType a : types){
retrivedTypes.add(a.getAccountType());
}
assertThat(retrivedTypes, is(expectedTypes));
}
}
|
package ru.yamblz.translatetraining;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ru.yamblz.translatetraining.api.API;
import ru.yamblz.translatetraining.api.APIService;
import ru.yamblz.translatetraining.model.WordPair;
/**
* Created by Litun on 23.07.2016.
*/
public class DataManager {
private Realm realm;
public static final String API_KEY = "dict.1.1.20160723T103526Z.a6023816b945356b.da2a4a3bad61c82cef86d45a6acd69d2b04e6f02";
private InputStream wordsJson;
public DataManager(Context context) {
realm = Realm.getInstance(
new RealmConfiguration.Builder(context)
.name("myOtherRealm.realm")
.schemaVersion(0)
.deleteRealmIfMigrationNeeded()
.build());
}
public WordPair getWordPair() {
RealmResults<WordPair> all = realm.where(WordPair.class).findAll();
return all.get(new Random().nextInt(all.size()));
}
void loadData() {
new AsyncTaskLoadDictionary() {
@Override
protected void onPostExecute(final List<WordPair> wordPairs) {
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(wordPairs);
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
Log.i("realm", "ok");
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
Log.i("realm", "fail");
}
});
}
}.execute();
}
class AsyncTaskLoadDictionary extends AsyncTask<Void, Void, List<WordPair>> {
@Override
protected List<WordPair> doInBackground(Void... params) {
Words words;
try {
words = readJsonFile();
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (words == null)
return null;
List<WordPair> pairs = new ArrayList<>(200);
APIService service = API.createService(APIService.class);
for (String s : words.en) {
Call<APIService.APIResponse> translate = service.getTranslate(API_KEY, "en-ru", s);
try {
Response<APIService.APIResponse> response = translate.execute();
if (!response.isSuccessful())
continue;
String translateString = response.body().getTranslate();
if (translateString == null)
continue;
WordPair pair = new WordPair();
pair.setEn(s);
pair.setRu(translateString);
pairs.add(pair);
} catch (IOException e) {
e.printStackTrace();
}
}
for (String s : words.ru) {
Call<APIService.APIResponse> translate = service.getTranslate(API_KEY, "ru-en", s);
try {
Response<APIService.APIResponse> response = translate.execute();
if (!response.isSuccessful())
continue;
String translateString = response.body().getTranslate();
if (translateString == null)
continue;
WordPair pair = new WordPair();
pair.setRu(s);
pair.setEn(translateString);
pairs.add(pair);
} catch (IOException e) {
e.printStackTrace();
}
}
return pairs;
}
}
void getTranslates() {
Call<APIService.APIResponse> tasks = API.createService(APIService.class)
.getTranslate(API_KEY, "en-ru", "time");
tasks.enqueue(new Callback<APIService.APIResponse>() {
@Override
public void onResponse(Call<APIService.APIResponse> call, Response<APIService.APIResponse> response) {
Log.i("api", String.valueOf(response.isSuccessful()));
}
@Override
public void onFailure(Call<APIService.APIResponse> call, Throwable t) {
Log.i("api", t.getMessage());
}
});
}
Words readJsonFile() throws IOException {
InputStream is = this.wordsJson;
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
String jsonString = writer.toString();
Words words = new Gson().fromJson(jsonString, Words.class);
return words;
}
public void setWordsJson(InputStream wordsJson) {
this.wordsJson = wordsJson;
}
static class Words {
List<String> en;
List<String> ru;
}
}
|
package old.DefaultPackage;
public class sortList {
class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
this.next = null;
}
}
public static void main(String[] args) {
sortList list = new sortList();
ListNode head = list.new ListNode(2);
head.next = list.new ListNode(3);
head.next.next = list.new ListNode(1);
head.next.next.next = list.new ListNode(4);
head.next.next.next.next = list.new ListNode(5);
head.next.next.next.next.next = list.new ListNode(7);
list.sortList1(head);
}
public ListNode sortList1(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode middle = head, l2 = head;
while(l2.next != null && l2.next.next != null){
l2 = l2.next.next;
middle = middle.next;
}
ListNode right = middle.next;
middle.next = null;
return mergeSortedList(sortList1(head), sortList1(right));
}
public ListNode mergeSortedList(ListNode l1, ListNode l2){
ListNode head = new ListNode(0);
ListNode p = head;
while(l1 != null && l2 != null){
if(l1.val <= l2.val){
p.next = l1;
l1 = l1.next;
}else{
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if(l1 != null){
p.next = l1;
}
else{
p.next = l2;
}
return head.next;
}
}
|
package com.ooteedemo.todo.data;
import android.content.Context;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.ooteedemo.todo.model.ToDo;
@Database(entities = {ToDo.class}, version = 1)
public abstract class ToDoRoomDatabase extends RoomDatabase {
// DBINSTANCE is a singleton that we create to make sure we don't instantiate the DB more than once
public static volatile ToDoRoomDatabase DBINSTANCE;
public abstract ToDoDao toDoDao_abstract();
public static ToDoRoomDatabase getDatabase(final Context context) {
if (DBINSTANCE==null) {
synchronized (ToDoRoomDatabase.class) {
if (DBINSTANCE==null) {
DBINSTANCE = Room.databaseBuilder(context.getApplicationContext(),
ToDoRoomDatabase.class,"todo_db")
.addCallback(roomDatabaseCallback)
.build();
}
}
}
return DBINSTANCE;
}
private static RoomDatabase.Callback roomDatabaseCallback = new RoomDatabase.Callback() {
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
new PopulateDbAsync(DBINSTANCE).execute();
}
};
private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {
private final ToDoDao toDoDao;
public PopulateDbAsync(ToDoRoomDatabase db) {
toDoDao = db.toDoDao_abstract();
}
@Override
protected Void doInBackground(Void... voids) {
testDBPopulation (toDoDao);
return null;
}
}
private static void testDBPopulation(ToDoDao toDoDao) {
toDoDao.deleteAll();
ToDo toDo = new ToDo("Wash the car");
toDoDao.insert(toDo);
toDo = new ToDo("Fill up car gas");
toDoDao.insert(toDo);
toDo = new ToDo("Get a car");
toDoDao.insert(toDo);
}
}
|
package net.paulheintz.kickthehabit;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
public class SettingsActivity extends AppCompatActivity {
// Temporary
Smoker mySmoker = new Smoker();
private LinearLayout parentLinearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//parentLinearLayout = (LinearLayout)findViewById(R.id.reasons_layout);
// Set default TextView values
final NumberFormat NF = NumberFormat.getCurrencyInstance();
final TextView cigsPerPackTV = (TextView)findViewById(R.id.cigs_per_pack_value);
cigsPerPackTV.setText(Integer.toString(mySmoker.getCigsPerPack()));
final TextView pricePerPackTV = (TextView)findViewById(R.id.price_per_pack_value);
pricePerPackTV.setText(NF.format(mySmoker.getPricePerPack()));
final TextView pricePerCigTV = (TextView)findViewById(R.id.price_per_cig_value);
pricePerCigTV.setText(NF.format(mySmoker.getPricePerCig()));
// On focus changed listeners to update price per cig
cigsPerPackTV.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// Update object variable
mySmoker.setCigsPerPack(Integer.parseInt(cigsPerPackTV.getText().toString()));
mySmoker.setPricePerCig();
// Update field
pricePerCigTV.setText(NF.format(mySmoker.getPricePerCig()));
}
}
});
pricePerPackTV.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
try {
mySmoker.setPricePerPack(Double.parseDouble(pricePerPackTV.getText().toString()));
} catch (NumberFormatException e) {
try {
Number tempPricePerPack = NF.parse(pricePerPackTV.getText().toString());
mySmoker.setPricePerPack((Double)tempPricePerPack);
} catch (ParseException ex) {
e.printStackTrace();
}
}
// Update object variable
mySmoker.setPricePerCig();
// Update fields
pricePerPackTV.setText(NF.format(mySmoker.getPricePerPack()));
pricePerCigTV.setText(NF.format(mySmoker.getPricePerCig()));
}
}
});
// On check changed listener to determine if data should be entered or collected
CheckBox gatherData = (CheckBox)findViewById(R.id.gather_data_chk);
gatherData.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
View smokerInfo = (View)findViewById(R.id.smoker_info);
if (isChecked) {
smokerInfo.setVisibility(View.GONE);
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} else {
smokerInfo.setVisibility(View.VISIBLE);
}
}
});
TextView reasonsBtn = (TextView)findViewById(R.id.reasons_button);
reasonsBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SettingsActivity.this, ReasonsActivity.class);
Bundle bundle = new Bundle();
bundle.putStringArray("reasonsArray", mySmoker.getReasonsToQuit());
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
|
package com.webproject.compro.web.controllers;
import com.webproject.compro.utility.Converter;
import com.webproject.compro.web.Constants;
import com.webproject.compro.web.containers.UserResetResultContainer;
import com.webproject.compro.web.enums.UserModifyResult;
import com.webproject.compro.web.enums.UserResetResult;
import com.webproject.compro.web.services.ApiService;
import com.webproject.compro.web.services.UserService;
import com.webproject.compro.web.vos.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
@Controller
public class RootController {
private final UserService userService;
@Autowired
public RootController(UserService userService) {
this.userService = userService;
}
@RequestMapping(value = "/")
public String index(HttpServletRequest request, HttpServletResponse response) {
return "main";
}
@RequestMapping(value = "/mypage")
public String mypage(HttpServletRequest request, HttpServletResponse response) {
UserVo userVo = Converter.getUserVo(request);
if (userVo != null) {
return "my/mypage";
} else {
return "main/login";
}
}
@RequestMapping(value = "/myorder")
public String order(HttpServletRequest request, HttpServletResponse response) {
UserVo userVo = Converter.getUserVo(request);
if (userVo != null) {
return "my/myorder";
} else {
return "main/login";
}
}
@RequestMapping(value = "/mybasket")
public String mybasket(HttpServletRequest request, HttpServletResponse response) {
UserVo userVo = Converter.getUserVo(request);
if (userVo != null) {
return "my/mybasket";
} else {
return "main/login";
}
}
@RequestMapping(value = "/login")
public String login(HttpServletRequest request, HttpServletResponse response) {
return "main/login";
}
@RequestMapping(value = "/register")
public String register(HttpServletRequest request, HttpServletResponse response) {
return "main/register";
}
@RequestMapping(value = "/reset", method = RequestMethod.GET)
public String resetGet(HttpServletRequest request, HttpServletResponse response,
@RequestParam(name="step", defaultValue = "1") String step) {
switch (step) {
case "2" :
return "main/reset-code";
case "3" :
return "main/reset-modify";
default :
return "main/reset";
}
}
@RequestMapping(value = "/reset", method = RequestMethod.POST)
public void resetPost(HttpServletRequest request, HttpServletResponse response,
@RequestParam(name = "step", defaultValue = "1") String step,
@RequestParam(name = "email", defaultValue = "") String email,
@RequestParam(name = "name", defaultValue = "") String name,
@RequestParam(name = "contact", defaultValue = "") String contact,
@RequestParam(name = "code", defaultValue = "") String code,
@RequestParam(name = "code_key", defaultValue = "") String codeKey,
@RequestParam(name = "new", defaultValue = "") String newPassword) throws SQLException, IOException {
switch (step) {
case "1" :
ResetVo resetVo = new ResetVo(email,name,contact);
UserResetResultContainer userResetResultContainer = this.userService.reset(resetVo);
if (userResetResultContainer.getUserResetResult() == UserResetResult.CODE_SENT) {
response.sendRedirect("/reset?step=2&code_key="+userResetResultContainer.getCodeKey());
} else {
response.sendRedirect("/reset?result=no_matching_user");
}
break;
case "2" :
UserResetResult codeCheckResult = this.userService.reset(code, codeKey);
if (codeCheckResult == UserResetResult.CODE_GOOD) {
response.sendRedirect("/reset?step=3&code="+code+"&code_key="+codeKey);
} else {
response.sendRedirect("/reset?step=2&result=code_nono&code_key="+codeKey);
}
break;
case "3" :
ChangePasswordVo changePasswordVo = new ChangePasswordVo(code, codeKey, newPassword);
UserModifyResult passwordModifyResult = this.userService.changePassword(changePasswordVo);
if (passwordModifyResult == UserModifyResult.SUCCESS) {
response.getWriter().print("CHANGE_SUCCESS");
} else {
response.getWriter().print("CHANGE_FAILURE");
}
break;
}
}
@RequestMapping(value = "/logout")
public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
Converter.setUserVo(request);
response.sendRedirect("/");
}
@RequestMapping(value = "/concept")
public String concept(HttpServletRequest request, HttpServletResponse response) {
return "content/concept";
}
@RequestMapping(value = "/board")
public String board(HttpServletRequest request, HttpServletResponse response) {
return "content/board";
}
@RequestMapping(value = "/product")
public String product(HttpServletRequest request, HttpServletResponse response) {
return "content/product";
}
@RequestMapping(value = "/contact")
public String contact(HttpServletRequest request, HttpServletResponse response) {
return "content/contact";
}
@RequestMapping(value = "/myinfo")
public String myinfo(HttpServletRequest request, HttpServletResponse response) {
return "my/myinfo";
}
@RequestMapping(value = "/qna")
public String qna(HttpServletRequest request, HttpServletResponse response) {
UserVo userVo = Converter.getUserVo(request);
if (userVo != null) {
return "my/qna";
} else {
return "main/login";
}
}
@RequestMapping(value = "/faq")
public String faq(HttpServletRequest request, HttpServletResponse response) {
return "content/faq";
}
}
|
package com.example.qiumishequouzhan;
/**
* Created with IntelliJ IDEA.
* User: jinxing
* Date: 14-3-19
* Time: 上午11:34
* To change this template use File | Settings | File Templates.
*/
public class Category {
String mTitle;
Category(String title) {
mTitle = title;
}
}
|
package com.mongodb.queue;
import java.util.concurrent.Executor;
import com.mongodb.BasicDBObject;
/**
* 消息监听器
* @author wens
*/
public interface MessageListener {
/**
*
* @param message
*/
public void recieveMessages(BasicDBObject message) ;
public Executor getExecutor();
}
|
package test;
//通过配置式注入的前置通知,在进入每个Controller方法之前执行
public class AOP {
public void say(){
System.out.println("--------------------------------------------ctlr--------------------------------------------");
}
}
|
package com.larryhsiao.nyx.core.attachments;
import com.silverhetch.clotho.Action;
import com.silverhetch.clotho.Source;
import java.sql.Connection;
import java.sql.PreparedStatement;
/**
* Remove Attachments by given Jot id.
*/
public class RemovalAttachment implements Action {
private final Source<Connection> dbConn;
private final long id;
public RemovalAttachment(Source<Connection> dbConn, long id) {
this.dbConn = dbConn;
this.id = id;
}
@Override
public void fire() {
try (PreparedStatement stmt = dbConn.value().prepareStatement(
// language=H2
"UPDATE attachments " +
"SET DELETE = 1 , VERSION = VERSION + 1 " +
"WHERE ID=?1;"
)) {
stmt.setLong(1, id);
stmt.executeUpdate();
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}
|
package nl.ronaldvandenbroek.worldgen.calculation;
import nl.ronaldvandenbroek.worldgen.calculation.array.ITwoDimensionalArrayUtility;
import nl.ronaldvandenbroek.worldgen.calculation.noise.INoiseMapGenerator;
import nl.ronaldvandenbroek.worldgen.properties.Config;
import nl.ronaldvandenbroek.worldgen.properties.Preset;
import java.util.ArrayList;
import java.util.List;
public class WorldGenerator {
// Variables
private float currentMap;
private float currentTime;
// Utilities
private INoiseMapGenerator noiseMapGenerator;
private ITwoDimensionalArrayUtility mapUtil;
// Generated maps
private List<HeightMap> heightMapLayers;
private HeightMap heightMap;
private TemperatureMap temperatureMap;
public WorldGenerator(INoiseMapGenerator noiseMapGenerator, ITwoDimensionalArrayUtility mapUtil) {
this.noiseMapGenerator = noiseMapGenerator;
this.mapUtil = mapUtil;
this.currentMap = Config.DEFAULT_MAP;
createDefaultMaps();
}
public void incrementCurrentTime() {
this.currentTime += Preset.HEIGHT_MAP_BASE_INTENSITY / Config.PERLIN_INTENSITY_MODIFIER * 2;
}
public void setCurrentMap(float currentMap) {
this.currentMap = currentMap;
}
public List<HeightMap> getHeightMapLayers() {
return heightMapLayers;
}
public TemperatureMap getTemperatureMap() {
return temperatureMap;
}
public void generateMaps() {
heightMap = null;
// Combine all heightMaps
for (HeightMap heightMapLayer : heightMapLayers) {
heightMapLayer.setTime(currentTime);
heightMapLayer.generate();
if (heightMap == null) {
heightMap = heightMapLayer;
} else {
heightMap = heightMap.merge(heightMapLayer);
}
}
// Generate final heightMap
if (heightMap != null) {
heightMap.setCircularFalloff(Preset.HEIGHT_MAP_TOTAL_CIRCULAR_FALLOFF);
heightMap.generate();
temperatureMap.generate(heightMap);
}
}
public float[][] finalizeSelectedMap() {
switch ((int) currentMap) {
case 1:
return temperatureMap.finalise();
default: //also 0
return heightMap.finalise();
}
}
private void createDefaultMaps() {
heightMapLayers = new ArrayList<>();
heightMapLayers.add(new HeightMap(
Preset.HEIGHT_MAP_BASE_NAME,
noiseMapGenerator,
mapUtil,
Config.IMAGE_HEIGHT,
Config.IMAGE_WIDTH,
Preset.HEIGHT_MAP_BASE_SEED,
Config.TIME,
Preset.HEIGHT_MAP_BASE_OCTAVE,
Preset.HEIGHT_MAP_BASE_NOISE_FALLOFF,
Preset.HEIGHT_MAP_BASE_INTENSITY,
Preset.HEIGHT_MAP_BASE_RIDGE,
Preset.HEIGHT_MAP_BASE_POWER,
Preset.HEIGHT_MAP_BASE_CIRCULAR_FALLOFF,
Preset.HEIGHT_MAP_BASE_WEIGHT)
);
heightMapLayers.add(new HeightMap(
Preset.HEIGHT_MAP_RIDGE_NAME,
noiseMapGenerator,
mapUtil,
Config.IMAGE_HEIGHT,
Config.IMAGE_WIDTH,
Preset.HEIGHT_MAP_RIDGE_SEED,
Config.TIME,
Preset.HEIGHT_MAP_RIDGE_OCTAVE,
Preset.HEIGHT_MAP_RIDGE_NOISE_FALLOFF,
Preset.HEIGHT_MAP_RIDGE_INTENSITY,
Preset.HEIGHT_MAP_RIDGE_RIDGE,
Preset.HEIGHT_MAP_RIDGE_POWER,
Preset.HEIGHT_MAP_RIDGE_CIRCULAR_FALLOFF,
Preset.HEIGHT_MAP_RIDGE_WEIGHT)
);
temperatureMap = new TemperatureMap(
mapUtil,
Preset.TEMPERATURE_MAP_EQUATOR_OFFSET,
Preset.TEMPERATURE_MAP_LATITUDE_STRENGTH,
Preset.TEMPERATURE_MAP_ALTITUDE_STRENGTH,
Preset.TEMPERATURE_MAP_GLOBAL_MODIFIER
);
}
}
|
package will.com.github.slidefinish.ui;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import will.com.github.slidefinish.R;
import will.com.github.slidefinish.layout.SlidingFinishLayout;
public class SlideFinishActivity extends AppCompatActivity implements SlidingFinishLayout.OnActivityFinishListener {
SlidingFinishLayout sf_test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slide_finish);
sf_test = (SlidingFinishLayout) findViewById(R.id.sf_test);
sf_test.setOnActivityFinishListener(this);
sf_test.attachActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
sf_test.detachActivity();
}
@Override
public void onActivityFinish() {
finish();
}
}
|
package ru.bookstore.domain;
import javax.persistence.*;
import java.sql.Date;
@Entity
@Table(name = "Orders")
public class OrderEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Integer id;
@Column(name = "date", nullable = false)
private Date date;
@Column(name = "buyer", nullable = false)
private int buyer;
@Column(name = "status", nullable = false)
private int status;
@Column(name = "delivery", nullable = false)
private int delivery;
@Column(name = "sum", nullable = false)
private double sum;
@Column(name = "address", nullable = true)
private Integer address;
public OrderEntity(Date date, int buyer, int status, int delivery, double sum, Integer address) {
this.date = date;
this.buyer = buyer;
this.status = status;
this.delivery = delivery;
this.sum = sum;
this.address = address;
}
public OrderEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getBuyer() {
return buyer;
}
public void setBuyer(int buyer) {
this.buyer = buyer;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getDelivery() {
return delivery;
}
public void setDelivery(int delivery) {
this.delivery = delivery;
}
public double getSum() {
return sum;
}
public void setSum(double sum) {
this.sum = sum;
}
public Integer getAddress() {
return address;
}
public void setAddress(Integer address) {
this.address = address;
}
}
|
package com.smart.droidies.tamil.natkati.library;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsAdapter extends FragmentPagerAdapter {
public TabsAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
return null;
}
@Override
public int getCount() {
return 0;
}
}
|
package com.karya.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.karya.dao.IStockEntryDAO;
import com.karya.model.StockEntry001MB;
import com.karya.service.IStockEntryService;
@Service("StockService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class StockEntryServiceImpl implements IStockEntryService {
@Autowired
private IStockEntryDAO stockentrydao;
public List<StockEntry001MB> liststockentry () {
return stockentrydao.liststockentry();
}
@Override
public void addstock(StockEntry001MB stock) {
stockentrydao.addstock(stock);
}
@Override
public StockEntry001MB getstockdetails(int stockid) {
return stockentrydao.getstockdetails(stockid);
}
@Override
public void deletestockdetails(int stockid) {
stockentrydao.deletestockdetails(stockid);
}
}
|
package edu.cb.lunch.sweezy.kenneth;
import edu.jenks.dist.cb.lunch.AbstractTrio;
import edu.jenks.dist.cb.lunch.Drink;
import edu.jenks.dist.cb.lunch.Salad;
import edu.jenks.dist.cb.lunch.Sandwich;
public class Trio extends AbstractTrio {
public Trio(Sandwich sand, Salad sald, Drink d) {
super(sand, sald, d);
}
public String getName() {
return getName();
}
public double getPrice() {
double low = Integer.MAX_VALUE;
double s = 0;
double[] t = new double[3];
t[0] = getSalad().getPrice();
t[1] = getSandwich().getPrice();
t[2] = getDrink().getPrice();
for (double d : t) {
if (d <= low) {
low = d;
}
s += d;
}
return s - low;
}
public static void main(String[] args) {
Drink testDrink = new Drink("Drink1", 4.00);
Salad testSalad = new Salad("Salad1", 13.00);
Sandwich testSandwich = new Sandwich("Sandwich1", 7.00);
Trio testTrio = new Trio(testSandwich, testSalad, testDrink);
System.out.println(testTrio.getPrice());
}
}
|
package com.myvodafone.android.model.service;
import com.myvodafone.android.utils.GlobalData;
import com.myvodafone.android.utils.VFPreferences;
/**
* Created by p.koutsias on 3/9/2016.
*/
public class PPDestination {
private String friendlyDescGr;
private String name;
private String friendlyDescEn;
private String expireDate;
private String value;
private String type;
private String destination;
public String getFriendlyDescGr ()
{
return friendlyDescGr;
}
public void setFriendlyDescGr (String friendlyDescGr)
{
this.friendlyDescGr = friendlyDescGr;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getFriendlyDescEn ()
{
return friendlyDescEn;
}
public void setFriendlyDescEn (String friendlyDescEn)
{
this.friendlyDescEn = friendlyDescEn;
}
public String getExpireDate ()
{
return expireDate;
}
public void setExpireDate (String expireDate)
{
this.expireDate = expireDate;
}
public String getValue ()
{
return value;
}
public void setValue (String value)
{
this.value = value;
}
public String getType ()
{
return type;
}
public void setType (String type)
{
this.type = type;
}
public String getDestination ()
{
return destination;
}
public void setDestination (String destination)
{
this.destination = destination;
}
public String getFriendlyName() {
if (VFPreferences.getLanguage() != GlobalData.LANGUAGE_GR) {
return this.friendlyDescEn;
} else {
return this.friendlyDescGr;
}
}
}
|
package com.zenwerx.findierock.data;
import java.util.Date;
import com.zenwerx.findierock.model.Status;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class StatusHelper {
private final String TAG = "findierock.StatusHelper";
public final String DATABASE_TABLE_STATUS = "status";
public final String COL_STATUSID = "_id";
public final String COL_LASTLATITUDE = "lastLatitude";
public final String COL_LASTLONGITUDE = "lastLongitude";
public final String COL_LASTUPDATE = "lastUpdate";
private final SQLiteDatabase mDb;
public StatusHelper(SQLiteDatabase db)
{
this.mDb = db;
}
private final ContentValues getContentValues(Status s)
{
final ContentValues cv = new ContentValues();
cv.put(COL_STATUSID, s.getStatusId());
cv.put(COL_LASTLATITUDE, s.getLastLatitude());
cv.put(COL_LASTLONGITUDE, s.getLastLongitude());
cv.put(COL_LASTUPDATE, (s.getLastUpdate().getTime()/1000));
return cv;
}
private Status readStatus(Cursor c)
{
final int iId = c.getColumnIndex(COL_STATUSID);
final int iUp = c.getColumnIndex(COL_LASTUPDATE);
final int iLat = c.getColumnIndex(COL_LASTLATITUDE);
final int iLong = c.getColumnIndex(COL_LASTLONGITUDE);
Status s = new Status();
s.setStatusId(c.getInt(iId));
s.setLastUpdate(new Date(c.getLong(iUp) * 1000));
s.setLastLatitude(c.getDouble(iLat));
s.setLastLongitude(c.getDouble(iLong));
return s;
}
public Status getLatestStatus()
{
Status result = null;
final Cursor c = mDb.query(DATABASE_TABLE_STATUS, null, null, null, null, null, COL_LASTUPDATE + " DESC", "1");
if (c != null && c.moveToFirst())
{
result = readStatus(c);
}
if (c != null)
{
c.close();
}
return result;
}
public void saveStatus(Status status)
{
if (status != null)
{
try
{
mDb.beginTransaction();
final ContentValues cv = getContentValues(status);
try
{
long id = mDb.insertOrThrow(DATABASE_TABLE_STATUS, null, cv);
Log.d(TAG, "Inserted id " + Long.toString(id));
} catch (SQLiteConstraintException ex)
{
if (!(mDb.update(DATABASE_TABLE_STATUS, cv, "_id=?", new String[] { Integer.toString(status.getStatusId()) }) == 1))
throw ex;
}
mDb.setTransactionSuccessful();
}
catch (Exception ex)
{
ex.printStackTrace();
Log.e(TAG, "Can't insert: " + ex.toString());
}
finally
{
mDb.endTransaction();
}
}
}
}
|
package com.minhvu.proandroid.sqlite.database.main.view.Activity;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.minhvu.proandroid.sqlite.database.R;
import com.minhvu.proandroid.sqlite.database.main.view.Fragment.PagerDialog;
import com.minhvu.proandroid.sqlite.database.main.view.Activity.view.SortView;
import com.minhvu.proandroid.sqlite.database.main.view.Fragment.AFragment;
import com.minhvu.proandroid.sqlite.database.main.view.Fragment.DeleteFragment;
import com.minhvu.proandroid.sqlite.database.main.view.Fragment.MainFragment;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by vomin on 10/10/2017.
*/
public class MainActivity2 extends AppCompatActivity implements SortView {
private Toolbar toolbar;
private FloatingActionButton fab;
private ImageButton btnDeletePage;
private ImageButton btnSort;
private ImageButton btnSyncCloud;
private PagerDialog pagerDialog;
private AFragment fragment;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setupInit();
toolbar.setTitleTextColor(getResources().getColor(R.color.black));
openMainPage();
requestPermission();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
void openMainPage() {
toolbar.setTitle(getString(R.string.main_page));
fab.setVisibility(View.VISIBLE);
btnDeletePage.setTag(true);
btnDeletePage.setImageResource(R.drawable.ic_delete_black_40dp);
FragmentManager fManager = getSupportFragmentManager();
fragment = (MainFragment) fManager.findFragmentByTag(MainFragment.class.getSimpleName());
if (fragment == null) {
fragment = new MainFragment();
}
FragmentTransaction transaction = fManager.beginTransaction();
transaction.replace(R.id.place, fragment, MainFragment.class.getSimpleName());
transaction.commit();
}
void openDeletePage() {
toolbar.setTitle(getString(R.string.delete_page));
fab.setVisibility(View.GONE);
btnDeletePage.setImageResource(R.drawable.ic_home_black_24dp);
btnDeletePage.setTag(false);
FragmentManager fManager = getSupportFragmentManager();
fragment = (DeleteFragment) fManager.findFragmentByTag(DeleteFragment.class.getSimpleName());
if (fragment == null) {
fragment = new DeleteFragment();
}
FragmentTransaction transaction = fManager.beginTransaction();
transaction.replace(R.id.place, fragment, DeleteFragment.class.getSimpleName());
transaction.commit();
}
void setupInit() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
btnSort = (ImageButton) findViewById(R.id.btnSort);
btnDeletePage = (ImageButton) findViewById(R.id.btnDeletePage);
btnSort.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sortVew();
}
});
btnDeletePage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!((boolean) btnDeletePage.getTag())) {
openMainPage();
} else {
openDeletePage();
}
}
});
btnSyncCloud = (ImageButton) findViewById(R.id.btnSync_cloud);
btnSyncCloud.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openSyncWindow();
}
});
fab = (FloatingActionButton) findViewById(R.id.fabInsert);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openActivity();
}
});
}
private void openSyncWindow(){
Intent intent = new Intent(this, LogInActivity.class);
startActivity(intent);
}
void sortVew() {
pagerDialog = new PagerDialog(this);
pagerDialog.setCancelable(true);
pagerDialog.show(getSupportFragmentManager(), "dialog");
}
void openActivity() {
Intent intent = new Intent(MainActivity2.this, BookDetailActivity.class);
startActivity(intent);
}
void requestPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.USE_FINGERPRINT}, 2);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@Override
public void colorSort(int position) {
fragment.colorSort(position);
pagerDialog.dismiss();
}
@Override
public void alphaSort() {
fragment.alphaSort();
pagerDialog.dismiss();
}
@Override
public void colorOrderSort() {
fragment.colorOrderSort();
pagerDialog.dismiss();
}
@Override
public void modifiedTimeSort() {
fragment.sortByModifiedTime();
pagerDialog.dismiss();
}
@Override
public void sortByImportant() {
fragment.sortByImportant();
pagerDialog.dismiss();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.