text stringlengths 10 2.72M |
|---|
package exemplos.aula09.classeabstrata;
public class TrianguloRetangulo extends Triangulo{
private double hipotenusa;
public TrianguloRetangulo(double cateto1, double cateto2) {
super(cateto1, cateto2);
this.hipotenusa = Math.sqrt(Math.pow(cateto1, 2) + Math.pow(cateto2, 2));
}
public double getHipotenusa() {
return this.hipotenusa;
}
}
|
package com.acnbank.api.whoami;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Base64;
@RestController
@RequestMapping("/api")
@Slf4j
public class ApiController {
@RequestMapping("/whoami")
public String decipherAccessToken() {
return getDecodedToken();
}
private String getDecodedToken() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof OAuth2Authentication) {
String token = ((OAuth2AuthenticationDetails) ((OAuth2Authentication) auth).getDetails()).getTokenValue();
String decoded = new String(Base64.getUrlDecoder().decode(token.split("\\.")[1]));
log.info("{}", decoded);
return decoded;
}
return "not an OAUTH2 access token";
}
@RequestMapping("/offers")
@PreAuthorize("#oauth2.hasScope('api:prelogin')")
public String getOffers() {
log.info("sending offers....");
return "{\"offers\" : [] }";
}
@RequestMapping("/transactions")
@PreAuthorize("#oauth2.hasScope('api:authenticated')")
public String getTransactionHistory() {
log.info("sending transactions history....");
return "{\"transactions\" : [] }";
}
@RequestMapping("/transfers")
@PreAuthorize("#oauth2.hasScope('api:mfa')")
public String performFundTransfer() {
return "{\"status\" : \"success\"}";
}
}
|
/*
* Copyright (c) 2007, 2008 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE file for licencing information.
*
* Created on Mar 17, 2007
* Author: K. Benedyczak <golbi@mat.umk.pl>
*/
package pl.edu.icm.unity.db;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.exceptions.InternalException;
import pl.edu.icm.unity.server.utils.Log;
import eu.unicore.util.db.DBPropertiesHelper;
/**
* Provides initial MyBatis initialization and support for obtaining MyBatis SqlSessions.
*
* @author K. Benedyczak
*/
@Component
public class DBSessionManager implements SessionManager
{
private static final Logger log = Log.getLogger(Log.U_SERVER_DB, DBSessionManager.class);
public static final String DEF_MAPCONFIG_LOCATION = "pl/edu/icm/unity/db/mapper/mapconfig.xml";
public static final int SESSION_KEEP_WARN_TIME = 3000;
private SqlSessionFactory sqlMapFactory;
private Map<SqlSession, Holder> used = new HashMap<SqlSession, Holder>();
@Autowired
public DBSessionManager(DBConfiguration config) throws InternalException, IOException
{
sqlMapFactory = loadMybatis(config);
}
private SqlSessionFactory loadMybatis(DBConfiguration config) throws IOException
{
String mapFile = config.getFileValueAsString(DBConfiguration.DBCONFIG_FILE, false);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
Reader reader;
if (mapFile != null)
reader = new FileReader(mapFile);
else
reader = Resources.getResourceAsReader(DEF_MAPCONFIG_LOCATION);
Properties properties = new Properties();
properties.setProperty(DBPropertiesHelper.DIALECT,
config.getValue(DBPropertiesHelper.DIALECT));
properties.setProperty(DBPropertiesHelper.DRIVER,
config.getValue(DBPropertiesHelper.DRIVER));
properties.setProperty(DBPropertiesHelper.PASSWORD,
config.getValue(DBPropertiesHelper.PASSWORD));
properties.setProperty(DBPropertiesHelper.URL,
config.getValue(DBPropertiesHelper.URL));
properties.setProperty(DBPropertiesHelper.USER,
config.getValue(DBPropertiesHelper.USER));
return builder.build(reader, properties);
}
private static class Holder
{
private long timestamp;
private long reportDelay = 1000;
private long lastReport = -1000;
private StackTraceElement[] stackTrace;
private String threadName;
public Holder(long timestamp, StackTraceElement[] stackTrace,
String threadName)
{
this.timestamp = timestamp;
this.stackTrace = stackTrace;
this.threadName = threadName;
}
}
@Override
public Configuration getMyBatisConfiguration()
{
return sqlMapFactory.getConfiguration();
}
@Override
public SqlSession getSqlSession(boolean transactional)
{
return getSqlSession(ExecutorType.SIMPLE, transactional);
}
@Override
public SqlSession getSqlSession(ExecutorType executor, boolean transactional)
{
runSessionWatchdog();
SqlSession newSession = sqlMapFactory.openSession(executor, !transactional);
synchronized(this)
{
Holder h = new Holder(System.currentTimeMillis(),
Thread.currentThread().getStackTrace(),
Thread.currentThread().getName());
Holder p = used.put(newSession, h);
if (p != null)
log.warn("Ups! MyBatis returned a SqlSession which is already used!");
}
return newSession;
}
private synchronized void runSessionWatchdog()
{
long now = System.currentTimeMillis();
Iterator<Entry<SqlSession, Holder>> it = used.entrySet().iterator();
while(it.hasNext())
{
Holder e = it.next().getValue();
long wait = now - e.timestamp;
long sinceLastLog = now - e.lastReport;
if (wait > SESSION_KEEP_WARN_TIME && sinceLastLog > e.reportDelay)
{
e.lastReport = now;
e.reportDelay *= 2;
log.warn("SqlSession is kept for more than " +
SESSION_KEEP_WARN_TIME/1000 +
"s: " + wait/1000.0 + "s by " +
e.threadName + ". Next report in at least " +
e.reportDelay + "ms. Stacktrace is:\n" +
produceStackTrace(e.stackTrace));
}
}
}
private String produceStackTrace(StackTraceElement[] stackTrace)
{
StringBuilder sb = new StringBuilder();
for (StackTraceElement se: stackTrace)
sb.append(" ").append(se.toString()).append("\n");
return sb.toString();
}
@Override
public void releaseSqlSession(SqlSession session)
{
synchronized(this)
{
Holder p = used.remove(session);
if (p == null)
{
log.warn("Thread trying to release not known session:\n"
+ produceStackTrace(
Thread.currentThread().getStackTrace()));
}
}
session.close();
}
}
|
package org.nistagram.campaignmicroservice.data.repository;
import org.nistagram.campaignmicroservice.data.model.Campaign;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface CampaignRepository extends CrudRepository<Campaign, Long> {
List<Campaign> findAllByAgentAccountUsername(String id);
@Query(value = "SELECT c.campaign_type, c.id, c.agent_account_username, c.deleted, c.gender, c.max_age, c.min_age, c.exposure_end, c.exposure_start, c.last_update, c.required_daily_displays, c.exposure_date, c.advertisement_id" +
" FROM hire_request as hr, campaign as c where c.id=hr.campaign_id and hr.id=:id", nativeQuery = true)
Campaign findByHireRequestId(Long id);
}
|
package com.engin.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.engin.utils.LogUtil;
/**
* Created by zhaoningqiang on 16/6/26.
*/
public class FixViewPager extends ViewPager {
private int mPosition;
private float mPositionOffset;
private int mPositionOffsetPixels;
public FixViewPager(Context context) {
super(context);
init();
}
public FixViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// addOnPageChangeListener(new OnPageChangeListener() {
// @Override
// public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// mPosition = position;
// mPositionOffset = positionOffset;
// mPositionOffsetPixels = positionOffsetPixels;
// LogUtil.d("VVVVV onPageScrolled position = "+position+" positionOffset = "+positionOffset+" positionOffsetPixels = "+positionOffsetPixels);
// }
//
// @Override
// public void onPageSelected(int position) {
// LogUtil.d("VVVVV ---- onPageSelected position = "+position);
// }
//
// @Override
// public void onPageScrollStateChanged(int state) {
//
// }
// });
// setPageTransformer(false, new PageTransformer() {
// @Override
// public void transformPage(View page, float position) {
// LogUtil.d("VVVVV +++ setPageTransformer position = "+position);
// }
// });
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(ev);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
|
package com.pepel.games.shuttle.model;
import com.pepel.games.shuttle.model.ports.Port;
import com.pepel.games.shuttle.model.shuttles.Shuttle;
import javax.annotation.Generated;
import javax.persistence.metamodel.ListAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="Dali", date="2012-08-27T22:56:30.088+0700")
@StaticMetamodel(Player.class)
public class Player_ {
public static volatile SingularAttribute<Player, Long> id;
public static volatile SingularAttribute<Player, String> name;
public static volatile SingularAttribute<Player, String> password;
public static volatile SingularAttribute<Player, String> rememberedLoginCookie;
public static volatile ListAttribute<Player, Port> ports;
public static volatile ListAttribute<Player, Shuttle> shuttles;
public static volatile SingularAttribute<Player, Boolean> saved;
public static volatile SingularAttribute<Player, String> email;
public static volatile SingularAttribute<Player, String> phone;
}
|
package cn.bdqn.third.impl;
//¼õ·¨
public class Minus implements Operation {
@Override
public double getResult(double num1, double num2) {
return num1 - num2;
}
}
|
package com.sap.als.security;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class HashCode {
private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
public static String getHashPassword(String password) {
String encodePassword = passwordEncoder.encode(password);
return encodePassword;
}
public static boolean isPasswordEquel(String password, String encodePassword) {
return passwordEncoder.matches(password.toString() , encodePassword);
}
}
|
package com.davivienda.sara.constantes;
/**
* EstadoProceso.java
*
* Fecha :11 de abril de 2007, 12:20 PM
*
* Descripción : Enumeración con los posibles estados de un proceso
*
* @author :jjvargas
*
* @vesion : $Id
*
* Estados que puede presentar un proceso
* @see com.davivienda.adminatm.modelodatos.enumeraciones.CodigoError
*
*/
public enum EstadoProceso {
/**
* Proceso finalizado correctamente
*/
FINALIZADO(0),
/**
* Se inicia el proceso
*/
INICIADO(1),
/**
* Proceso I/O Aperura de un archivo
*/
APERTURA_ARCHIVO(2),
/**
* Proceso I/O Lectura de un archivo
*/
LECTURA_ARCHIVO(3),
/**
* Proceso I/O Cierre de in archivo
*/
CIERRE_ARCHIVO(4),
/**
* Proceso en espera
*/
ESPERA(5),
/**
* Conectando con un recurso externo puede ser una base de datos
*/
CONECTANDO(6),
/**
* Proceso de Persistencia - Graba el registro o entity
*/
PERSISTENCIA_GRABAR_REGISTRO(7),
/**
* Proceso de Persistencia - Asocia el objeto a la unidad de persistencia
*/
PERSISTENCIA_ASOCIAR_REGISTRO(8),
/**
* Tipo de proceso no definido, se retorna cuando se busca un proceso por código y no existe
*/
ESTADO_PROCESO_INDEFINIDO(9),
/**
*Estado generico de procesando
*/
PROCESANDO(10),
//NUEVO ALVARO 22 MAYO
/**
*Estado error SOLO para RegCargueArchivo
*/
ERROR(11),
/**
* Código de error cuando no se cargan todos los archivos
*/
ERROR_NO_SE_CARGARON_TODOS_LOSARCHIVOS(15),
/**
* Código de Cargue manual
*/
CARGUEMANUAL(16);
public int codigo;
/**
* Estados que puede presentar un proceso
* @see com.davivienda.adminatm.modelodatos.enumeraciones.CodigoError
* {@link com.davivienda.adminatm.modelodatos.enumeraciones.CodigoError}
* @param estado Código del estado del proceso
*/
EstadoProceso(int estado) {
this.codigo = estado;
}
public Integer getEstado() {
return this.codigo;
}
public static EstadoProceso getEstadoProceso(int codigo) {
EstadoProceso estadoProceso = EstadoProceso.ESTADO_PROCESO_INDEFINIDO ;
for (EstadoProceso elem : EstadoProceso.values()) {
if (elem.codigo == codigo) {
estadoProceso = elem;
break;
}
}
return estadoProceso;
}
}
|
package com.gaby.exception;
/**
* @Description: 业务异常类
* @Author: wengzhongjie
* @CreateDate: 2019-03-14 14:04
*/
public class BssException extends BaseException{
public BssException() {
}
public BssException(Throwable cause) {
super(cause);
}
public BssException(String message) {
super(message);
}
public BssException(String message, Throwable cause) {
super(message, cause);
}
}
|
package DataStructures.codility;
public class Test {
public int solution(int[] A) {
int minAverage = Integer.MAX_VALUE;
int index = 0;
int avg = 0;
for (int i = 0; i < A.length - 1; i++) {
avg = (A[i] + A[i + 1]) / 2 ;
if (avg < minAverage) {
minAverage = avg;
index = i;
}
}
for (int i = 0; i < A.length - 2; i++) {
avg = (A[i] + A[i + 1] + A[i + 2]) / 3 ;
if (avg < minAverage) {
minAverage = avg;
index = i;
}
}
return index;
}
public static void main(String a[]) {
Test t = new Test();
System.out.println(t.solution(new int[]{4,2,2,5,1,5,8}));
}
}
|
package com.davivienda.sara.entitys.transaccion;
import com.davivienda.sara.entitys.*;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Version;
/**
* Entity class Transaccion
* Transaccion.java
*
* Fecha :24 de enero de 2007, 11:47 PM
*
* Descripción :Entity para el registro de transacciones de tipoTransacción en la base de datos.
* Se debe tener en cuenta que utiliza queries nativos Oracle para generar estadísticas
*
* @author :jjvargas
*
* @version :$Id: Transaccion.java,v 1.2 2007/05/18 23:22:41 jjvargas Exp $
*/
@Entity
@Table(name = "TRANSACCION")
@NamedQueries( {
@NamedQuery(
name = "Transaccion.RegistroUnico",
query = "select object(edc) from Transaccion edc where edc.cajero = :cajero"),
@NamedQuery(
name = "Transaccion.Todos",
query = "select object(edc) from Transaccion edc order by edc.transaccionPK.codigoCajero, edc.transaccionPK.fechaTransaccion"),
@NamedQuery(
name = "Transaccion.CajeroRangoFecha",
query = "select object(obj) from Transaccion obj " +
" where obj.transaccionPK.codigoCajero =:codigoCajero and " +
" obj.transaccionPK.fechaTransaccion between :fechaInicial and :fechaFinal " +
" order by obj.transaccionPK.fechaTransaccion"),
@NamedQuery(
name = "Transaccion.CajeroTransaccionFecha",
query = "select object(obj) from Transaccion obj " +
" where obj.transaccionPK.codigoCajero =:codigoCajero and " +
" obj.transaccionPK.fechaTransaccion between :fechaInicial and :fechaFinal and" +
" obj.transaccionPK.numeroTransaccion = :numeroTransaccion" +
" order by obj.transaccionPK.fechaTransaccion"),
@NamedQuery(
name = "Transaccion.TransaccionBuscarReintegros",
query = "select object(obj) from Transaccion obj " +
" where obj.transaccionPK.codigoCajero =:codigoCajero and " +
" obj.transaccionPK.fechaTransaccion between :fechaInicial and :fechaFinal and " +
" obj.codigoTerminacionTransaccion IN ('0121','0030','0131') " +
" order by obj.transaccionPK.fechaTransaccion")
})
public class Transaccion implements Serializable {
@EmbeddedId
protected TransaccionPK transaccionPK;
private Integer tipoTransaccion;
private Integer codigoTransaccion;
private String errorTransaccion;
private Long valorSolicitado;
private Long valorEntregado;
private String tarjeta;
private String cuenta;
private String codigoTerminacionTransaccion;
private String referencia;
@Version
private Integer version;
@JoinColumn(name = "CODIGOCAJERO", referencedColumnName = "CODIGOCAJERO", insertable = false, updatable = false)
@ManyToOne
private Cajero cajero;
/** Crea una nueva instancia de Transaccion */
public Transaccion() {
}
/**
* Creates a new instance of Transaccion with the specified values.
*
*
* @param idtransaccion
*/
public Transaccion(TransaccionPK transaccionPK) {
this.transaccionPK = transaccionPK;
}
public Transaccion(TransaccionPK transaccionPK, Integer tipotransaccion, Integer codigotransaccion) {
this.transaccionPK = transaccionPK;
this.tipoTransaccion = tipotransaccion;
this.codigoTransaccion = codigotransaccion;
}
public Transaccion(Integer codigocajero, Integer numerotransaccion, Date fechatransaccion) {
this.transaccionPK = new TransaccionPK(codigocajero, numerotransaccion, fechatransaccion);
}
public TransaccionPK getTransaccionPK() {
return transaccionPK;
}
public void setTransaccionPK(TransaccionPK transaccionPK) {
this.transaccionPK = transaccionPK;
}
/**
* Gets the tipoTransaccion of this Transaccion.
*
* @return the tipoTransaccion
*/
public Integer getTipoTransaccion() {
return this.tipoTransaccion;
}
/**
* Sets the tipoTransaccion of this Transaccion to the specified value.
*
* @param tipotransaccion
*/
public void setTipoTransaccion(Integer tipotransaccion) {
this.tipoTransaccion = tipotransaccion;
}
/**
* Gets the codigoTransaccion of this Transaccion.
*
* @return the codigoTransaccion
*/
public Integer getCodigoTransaccion() {
return this.codigoTransaccion;
}
/**
* Sets the codigoTransaccion of this Transaccion to the specified value.
*
* @param codigotransaccion
*/
public void setCodigoTransaccion(Integer codigotransaccion) {
this.codigoTransaccion = codigotransaccion;
}
/**
* Gets the errorTransaccion of this Transaccion.
*
* @return the errorTransaccion
*/
public String getErrorTransaccion() {
return this.errorTransaccion;
}
/**
* Sets the errorTransaccion of this Transaccion to the specified value.
*
* @param errortransaccion
*/
public void setErrorTransaccion(String errortransaccion) {
this.errorTransaccion = errortransaccion;
}
/**
* Gets the valorSolicitado of this Transaccion.
*
* @return the valorSolicitado
*/
public Long getValorSolicitado() {
return this.valorSolicitado;
}
/**
* Sets the valorSolicitado of this Transaccion to the specified value.
*
* @param valorsolicitado
*/
public void setValorSolicitado(Long valorsolicitado) {
this.valorSolicitado = valorsolicitado;
}
/**
* Gets the valorEntregado of this Transaccion.
*
* @return the valorEntregado
*/
public Long getValorEntregado() {
return this.valorEntregado;
}
/**
* Sets the valorEntregado of this Transaccion to the specified value.
*
* @param valorentregado
*/
public void setValorEntregado(Long valorentregado) {
this.valorEntregado = valorentregado;
}
/**
* Gets the tarjeta of this Transaccion.
* @return the tarjeta
*/
public String getTarjeta() {
return this.tarjeta;
}
/**
* Sets the tarjeta of this Transaccion to the specified value.
* @param tarjeta the new tarjeta
*/
public void setTarjeta(String tarjeta) {
this.tarjeta = tarjeta;
}
/**
* Gets the cuenta of this Transaccion.
* @return the cuenta
*/
public String getCuenta() {
return this.cuenta;
}
/**
* Sets the cuenta of this Transaccion to the specified value.
* @param cuenta the new cuenta
*/
public void setCuenta(String cuenta) {
this.cuenta = cuenta;
}
/**
* Gets the codigoTerminacionTransaccion of this Transaccion.
*
* @return the codigoTerminacionTransaccion
*/
public String getCodigoTerminacionTransaccion() {
return this.codigoTerminacionTransaccion;
}
/**
* Sets the codigoTerminacionTransaccion of this Transaccion to the specified value.
*
* @param codigoterminaciontransaccion
*/
public void setCodigoTerminacionTransaccion(String codigoterminaciontransaccion) {
this.codigoTerminacionTransaccion = codigoterminaciontransaccion;
}
/**
* Gets the referencia of this Transaccion.
* @return the referencia
*/
public String getReferencia() {
return this.referencia;
}
/**
* Sets the referencia of this Transaccion to the specified value.
* @param referencia the new referencia
*/
public void setReferencia(String referencia) {
this.referencia = referencia;
}
/**
* Gets the version of this Transaccion.
* @return the version
*/
public Integer getVersion() {
return this.version;
}
/**
* Sets the version of this Transaccion to the specified value.
* @param version the new version
*/
public void setVersion(Integer version) {
this.version = version;
}
/**
* Gets the cajero of this Transaccion.
*
* @return the cajero
*/
public Cajero getCajero() {
return this.cajero;
}
/**
* Sets the cajero of this Transaccion to the specified value.
*
* @param cajero
*/
public void setCajero(Cajero cajero) {
this.cajero = cajero;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Transaccion)) {
return false;
}
Transaccion other = (Transaccion) object;
if ((this.transaccionPK == null && other.transaccionPK != null) || (this.transaccionPK != null && !this.transaccionPK.equals(other.transaccionPK))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + (this.transaccionPK != null ? this.transaccionPK.hashCode() : 0);
return hash;
}
@Override
public String toString() {
return "com.davivienda.sara.entitys.transaccion.Transaccion[transaccionPK=" + transaccionPK + "]";
}
}
|
package tn.esprit.spring;
import java.util.EnumSet;
import javax.faces.webapp.FacesServlet;
import javax.servlet.DispatcherType;
import org.apache.log4j.Logger;
import org.ocpsoft.rewrite.servlet.RewriteFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import javassist.bytecode.stackmap.BasicBlock.Catch;
import tn.esprit.spring.config.LoginFilter;
@SpringBootApplication
@EnableAutoConfiguration
public class TimesheetApplication {
private static final Logger l =Logger.getLogger(TimesheetApplication.class);
public static void main(String[] args) {SpringApplication.run(TimesheetApplication.class, args);}
//TimesheetApplication tim = new TimesheetApplication();
// tim.getAlEmployer();
@Bean
public ServletRegistrationBean servletRegistrationBean() {
FacesServlet servlet = new FacesServlet();
return new ServletRegistrationBean(servlet, "*.jsf");
}
@Bean
public FilterRegistrationBean rewriteFilter() {
FilterRegistrationBean rwFilter = new FilterRegistrationBean(new RewriteFilter());
rwFilter.setDispatcherTypes(EnumSet.of(DispatcherType.FORWARD, DispatcherType.REQUEST, DispatcherType.ASYNC, DispatcherType.ERROR));
rwFilter.addUrlPatterns("/*");
return rwFilter;
}
@Bean
public FilterRegistrationBean loginFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.addUrlPatterns("/pages/*");
registration.setFilter(new LoginFilter());
return registration;
}
public void getAlEmployer() {
try {
l.info("ajout de getAlEmployer():");
int i =1/0;
l.debug("lancement de la division par 0"+i);
l.info("out getAlEmployer() ");
}
catch(Exception e)
{
l.error("y'a une erreur deans getAlEmployer()"+e);
}
}
}
|
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Ship {
public static void main(String[] args) {
mainGUI();
}
public static void mainGUI() {
JFrame frame = new JFrame("Bouncing Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.add(new Move());
frame.setVisible(true);
}
}
class Move extends JComponent implements KeyListener {
public Move() {
addKeyListener(this);
setFocusable(true);
Thread animationThread = new Thread(new Runnable() {
public void run() {
while (true) {
repaint();
try {
Thread.sleep(20);
} catch (Exception ex) {
}
}
}
});
}
static double directionOfRotation = 0;
static double rotation = 0;
public void paint(Graphics g) {
Graphics2D ship = (Graphics2D) g;
directionOfRotation += rotation;
ship.fillOval(100, 100, 10, 35);
ship.rotate(directionOfRotation);
}
public static void rotateLeft() {
rotation -= 5;
}
public static void rotateRight() {
rotation += 5;
}
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
Move.rotateLeft();
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
Move.rotateRight();
}
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
rotation = 0;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rotation = 0;
}
}
}
|
package com.dadashova.aytaj.callsignature.containers;
public class NotifViewHolder {
}
|
/**
* Multipart support.
*/
@NonNullApi
@NonNullFields
package org.springframework.http.codec.multipart;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package com.alex.patterns.adapter.example;
public class AdapterVideoToMusic implements Sender {
private VideoSender adapte;
public AdapterVideoToMusic(VideoSender sender) {
this.adapte = sender;
}
@Override
public void send() {
adapte.sendVideo();
}
}
|
package analytics.database;
import static analytics.database.DBCredentials.*;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.sql.PreparedStatement;
/**
* Singleton class used for basic database operations
*
* @author Razvan Nedelcu
*/
public class DBBasicOperations {
static {
dbConnection = new DBBasicOperations();
}
private static DBBasicOperations dbConnection;
private static Connection connection;
private DBBasicOperations() {}
/**
* @return an instance of the DBBasicOperations class
*/
public static DBBasicOperations getInstance() {
return dbConnection;
}
/**
* This method is the first one that should be called after obtaining an instance of the DBBasicOperations class
*/
public void openConnection() {
try {
Class.forName(DRIVER).newInstance();
connection = DriverManager.getConnection(LINK);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @return a list containing all the products' names
*/
public List<String> getAvailableProducts() {
List<String> products = new ArrayList<String>();
try{
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = statement.executeQuery("SELECT " + PROD_NAME + " FROM " + TABLE_PROD);
while(rs.next())
products.add(rs.getString(PROD_NAME));
}catch(Exception e)
{
e.printStackTrace();
}
return products;
}
public int getEntryTotalValuePerDay(String product, Date day) {
int value = 0;
try {
String query =
"SELECT SUM(bons." + BON_CANT + ") " +
"FROM " + TABLE_PROD + " prods, " + TABLE_BON + " bons " +
"WHERE bons." + BON_DATE + "='" + day + "' AND " +
"bons." + BON_CODART + "=prods." + PROD_CODE + " AND " +
"prods." + PROD_NAME + "='" + product + "'";
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet resultSet = statement.executeQuery(query);
if(resultSet.next())
value = resultSet.getInt(1);
}catch(Exception e) {
e.printStackTrace();
}
return value;
}
public int getEntryTotalValuePerInterval(String product, Date ini, Date fin) {
int value = 0;
try {
String query =
"SELECT SUM(bons." + BON_CANT + ") " +
"FROM " + TABLE_PROD + " prods, " + TABLE_BON + " bons " +
"WHERE bons." + BON_DATE + " BETWEEN '" + ini + "' AND '" + fin + "' AND " +
"bons." + BON_CODART + "=prods." + PROD_CODE + " AND " +
"prods." + PROD_NAME + "='" + product + "'";
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet resultSet = statement.executeQuery(query);
if(resultSet.next())
value = resultSet.getInt(1);
}catch(Exception e) {
e.printStackTrace();
}
return value;
}
/**
* @return a HashMap that has as key the transaction's code and as value the list of consumed products' codes
*/
public HashMap<Integer, List<Integer>> getTransactions() {
HashMap<Integer, List<Integer>> transactions = new HashMap<Integer, List<Integer>>();
try {
String query = "SELECT " + BON_CODBON + ", " + BON_CODART + " FROM " + TABLE_BON;
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next()) {
Integer nrBon = resultSet.getInt(BON_CODBON);
Integer codArt = resultSet.getInt(BON_CODART);
if(codArt == 0) {
//THIS IS A DATABASE BUG!!!
continue;
}
if(transactions.containsKey(nrBon)){
if(!transactions.get(nrBon).contains(codArt)) {
transactions.get(nrBon).add(codArt);
}
} else {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(codArt);
transactions.put(nrBon, list);
}
}
} catch(Exception e) {
e.printStackTrace();
}
return transactions;
}
/**
* @return a HashMap that has as key the transaction's code and as value the list of consumed products' category
*/
public HashMap<Integer, List<String>> getCategories() {
HashMap<Integer, List<String>> categories = new HashMap<Integer, List<String>>();
HashMap<Integer, List<Integer>> transactions = this.getTransactions();
try {
String query = "SELECT a." + CLASS_NAME + ", b." + PROD_CATEGORY +
" FROM " + TABLE_CLASS + " a, " + TABLE_PROD + " b" +
" WHERE b." + PROD_CODE + " = ? AND a." + CLASS_CODE + " = b." + PROD_CATEGORY;
PreparedStatement statement = connection.prepareStatement(query);
List<Integer> codes = new ArrayList<Integer>(transactions.keySet());
Collections.sort(codes);
for(int code : codes) {
categories.put(code, new ArrayList<String>());
List<Integer> prods = transactions.get(code);
for(int prod : prods) {
statement.setInt(1, prod);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String category = resultSet.getString(CLASS_NAME);
//this allows duplicates
categories.get(code).add(category);
/*this does not allow duplicates
List<String> categs = categories.get(code);
if(!categs.contains(category)) {
categs.add(category);
}
*/
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
return categories;
}
/**
* @return a String corresponding to the most of the parameter list of elements' category
*/
public String getCategory(List<Integer> productsCodes) {
List<String> categories = new ArrayList<String>();
List<Integer> occurences = new ArrayList<Integer>();
try {
String query = "SELECT a." + CLASS_NAME + ", b." + PROD_CATEGORY +
" FROM " + TABLE_CLASS + " a, " + TABLE_PROD + " b" +
" WHERE b." + PROD_CODE + " = ? AND a." + CLASS_CODE + " = b." + PROD_CATEGORY;
PreparedStatement statement = connection.prepareStatement(query);
for(int code : productsCodes) {
statement.setInt(1, code);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String category = resultSet.getString(CLASS_NAME);
if(!categories.contains(category)) {
int index = categories.size();
categories.add(category);
occurences.add(index, new Integer(1));
} else {
int index = categories.indexOf(category);
int val = occurences.get(index);
occurences.remove(index);
occurences.add(index, new Integer(val + 1));
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
int max = Integer.MIN_VALUE;
int maxIndex = -1;
for(Integer occurence : occurences) {
if(occurence.intValue() > max) {
max = occurence.intValue();
maxIndex = occurences.indexOf(occurence);
}
}
return categories.get(maxIndex);
}
/**
* @return a HashMap that has as key the product's code and as value the product's name
*/
public HashMap<Integer,String> getProducts() {
HashMap<Integer, String> products = new HashMap<Integer, String>();
try {
String query = "SELECT " + PROD_CODE + ", " + PROD_NAME + " FROM " + TABLE_PROD;
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next()) {
Integer prodCode = resultSet.getInt(PROD_CODE);
String prodName = resultSet.getString(PROD_NAME);
if(prodName.startsWith("*")){
continue;
}
if(!products.containsKey(prodCode)) {
products.put(prodCode, prodName);
}
}
} catch(Exception e) {
e.printStackTrace();
}
return products;
}
public List<String> getNamesForProducts(Integer[] codes) {
List<String> prods = new ArrayList<String>();
try {
String query = "SELECT " + PROD_NAME + " FROM " + TABLE_PROD + " WHERE " + PROD_CODE + " = ?";
PreparedStatement statement = connection.prepareStatement(query);
for(Integer code : codes) {
statement.setInt(1, code);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
prods.add(resultSet.getString(PROD_NAME));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return prods;
}
/**
* Closes the connection with the database.
* This is the last function that should be called.
*/
public void closeConnection() {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package Implements;
import java.util.List;
import Entity.Size;
public interface SizeImp {
List<Size> lstSize();
Size showSize(int idSize);
String themSize(Size size);
String updateSize(int idSize, String tenSize);
}
|
package hw5.ch7.q1;
import java.io.*;
import java.util.ArrayList;
public class PairTest {
public static void main(String[] args) throws Exception {
ArrayList<Pair> pairs = deserializePairs();
showPairData(pairs);
serializePairs(pairs);
}
/**
* Reads a file of serialized Pairs and generates an ArrayList of them.
* If no serialized Pairs exist yet, random Pairs are generated.
* @return An ArrayList of Pairs
* @throws Exception on input stream errors
* @see #serializePairs(ArrayList)
*/
private static ArrayList<Pair> deserializePairs() throws Exception {
FileInputStream fis;
ObjectInputStream ois;
ArrayList<Pair> pairs;
try {
fis = new FileInputStream("object.ser");
ois = new ObjectInputStream(fis);
pairs = new ArrayList<>();
boolean done = false;
while (!done) {
try {
pairs.add((Pair) ois.readObject());
} catch (EOFException e) {
done = true;
}
}
ois.close();
fis.close();
} catch (FileNotFoundException e) {
pairs = Utils.randomPairsWithClone();
}
return pairs;
}
/**
* Helper function that demonstrates all the required Pair methods.
* @param pairs ArrayList of Pairs to be used for the demonstration.
* Note: clone() is used when the Pairs are generated. The Pairs are
* ordered such that the first and third Pair in the ArrayList
* are clones.
* @see Utils randomPairsWithClone()
*/
private static void showPairData(ArrayList<Pair> pairs) {
for (Pair pair : pairs) {
System.out.println(" Key: " + pair.k());
System.out.println(" Value: " + pair.v());
System.out.println("To String: " + pair.toString());
System.out.println("Hash Code: " + pair.hashCode() + "\n");
}
System.out.println("First == Third: " + pairs.get(0).equals(pairs.get(2))); // should be true
System.out.println("First == Second: " + pairs.get(0).equals(pairs.get(1)));// should be false
}
/**
* Serializes Pairs and saves them to a file.
* @param pairs Pairs to be serialized.
* @throws Exception on output stream errors
* @see #deserializePairs()
*/
private static void serializePairs(ArrayList<Pair> pairs) throws Exception {
FileOutputStream fos = new FileOutputStream("object.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
for (Pair pair : pairs) {
oos.writeObject(pair);
}
oos.close();
fos.close();
}
}
|
package extensionExamples;
import IK.AbstractBone;
import IK.AbstractIKPin;
import sceneGraph.AbstractAxes;
public class IKPinExample extends AbstractIKPin{
public IKPinExample(AxesExample inAxes, boolean enabled, BoneExample bone) {
super(inAxes, enabled, bone);
}
public IKPinExample(AxesExample inAxes, BoneExample bone) {
super(inAxes, bone);
}
///WRAPPER FUNCTIONS. Basically just ctrl+f and replace these with the appropriate class names and
//any conversion functions you modified in AxesExample and you should be good to go.
public ExampleVector getLocation() {
return AxesExample.toExampleVector(super.getLocation_());
}
public void translateTo(ExampleVector v) {
super.translateTo_(AxesExample.toSGVec(v));
}
public void translateBy(ExampleVector v) {
super.translateBy_(AxesExample.toSGVec(v));
}
}
|
package controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import pojo.Role;
import pojo.User;
import service.RoleService;
import service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@RequestMapping(value = "/list")
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView();
List<User> userList = userService.list();
modelAndView.addObject("userList", userList);
modelAndView.setViewName("user-list");
return modelAndView;
}
@RequestMapping(value = "/saveUI")
public ModelAndView saveUI(){
ModelAndView modelAndView = new ModelAndView();
List<Role> roleList = roleService.list();
modelAndView.addObject("roleList", roleList);
modelAndView.setViewName("user-add");
return modelAndView;
}
@RequestMapping(value = "/save")
public String save(User user, long[] roleIds){
for (long roleId : roleIds) {
System.out.println(roleId);
}
userService.save(user, roleIds);
return "redirect:/user/list";
}
@RequestMapping(value = "/delete/{userId}")
public String delete(@PathVariable("userId")long userId){
userService.delete(userId);
return "redirect:/user/list";
}
@RequestMapping(value = "/login")
public ModelAndView login(String username, String password, HttpServletRequest request){
ModelAndView modelAndView = new ModelAndView();
System.out.println(username + ":" + password);
boolean flag = userService.login(username,password);
if(flag){
HttpSession session = request.getSession();
session.setAttribute("username", username);
session.setAttribute("password", password);
modelAndView.setViewName("main");
}else {
modelAndView.addObject("flag", true);
modelAndView.setViewName("login");
}
return modelAndView;
}
}
|
package br.com.mixfiscal.prodspedxnfe.domain.nfe;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Objects;
public class ICMS30 extends ICMS implements Serializable {
private static final long serialVersionUID = -6382517831939574808L;
private int modalidadeBaseCalculoST;//<modBcSt>
private BigDecimal valorBCST;//<vBcSt>
private BigDecimal aliquotaICMSST;//<pIcmsSt>
private BigDecimal valorICMSST;//<vIcmsSt>
private BigDecimal percentualMargemValorAdicionadoST;//<pMvaSt>
private BigDecimal motivoDesoneracaoICMS;//<motDesIcms>
private BigDecimal valorICMSDesoneracao;//<vIcmsDeson>;
private BigDecimal percentualReducaoBCST;//<pRedBcSt>
public int getModalidadeBaseCalculoST() {
return modalidadeBaseCalculoST;
}
public void setModalidadeBaseCalculoST(int modalidadeBaseCalculoST) {
this.modalidadeBaseCalculoST = modalidadeBaseCalculoST;
}
public BigDecimal getValorBCST() {
return valorBCST;
}
public void setValorBCST(BigDecimal valorBCST) {
this.valorBCST = valorBCST;
}
public BigDecimal getAliquotaICMSST() {
return aliquotaICMSST;
}
public void setAliquotaICMSST(BigDecimal aliquotaICMSST) {
this.aliquotaICMSST = aliquotaICMSST;
}
public BigDecimal getValorICMSST() {
return valorICMSST;
}
public void setValorICMSST(BigDecimal valorICMSST) {
this.valorICMSST = valorICMSST;
}
public BigDecimal getPercentualMargemValorAdicionadoST() {
return percentualMargemValorAdicionadoST;
}
public void setPercentualMargemValorAdicionadoST(BigDecimal percentualMargemValorAdicionadoST) {
this.percentualMargemValorAdicionadoST = percentualMargemValorAdicionadoST;
}
public BigDecimal getMotivoDesoneracaoICMS() {
return motivoDesoneracaoICMS;
}
public void setMotivoDesoneracaoICMS(BigDecimal motivoDesoneracaoICMS) {
this.motivoDesoneracaoICMS = motivoDesoneracaoICMS;
}
public BigDecimal getValorICMSDesoneracao() {
return valorICMSDesoneracao;
}
public void setValorICMSDesoneracao(BigDecimal valorICMSDesoneracao) {
this.valorICMSDesoneracao = valorICMSDesoneracao;
}
public BigDecimal getPercentualReducaoBCST() {
return percentualReducaoBCST;
}
public void setPercentualReducaoBCST(BigDecimal percentualReducaoBCST) {
this.percentualReducaoBCST = percentualReducaoBCST;
}
@Override
public int hashCode() {
int hash = 5;
hash = 73 * hash + this.modalidadeBaseCalculoST;
hash = 73 * hash + Objects.hashCode(this.valorBCST);
hash = 73 * hash + Objects.hashCode(this.aliquotaICMSST);
hash = 73 * hash + Objects.hashCode(this.valorICMSST);
hash = 73 * hash + Objects.hashCode(this.percentualMargemValorAdicionadoST);
hash = 73 * hash + Objects.hashCode(this.motivoDesoneracaoICMS);
hash = 73 * hash + Objects.hashCode(this.valorICMSDesoneracao);
hash = 73 * hash + Objects.hashCode(this.percentualReducaoBCST);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ICMS30 other = (ICMS30) obj;
if (this.modalidadeBaseCalculoST != other.modalidadeBaseCalculoST) {
return false;
}
if (!Objects.equals(this.valorBCST, other.valorBCST)) {
return false;
}
if (!Objects.equals(this.aliquotaICMSST, other.aliquotaICMSST)) {
return false;
}
if (!Objects.equals(this.valorICMSST, other.valorICMSST)) {
return false;
}
if (!Objects.equals(this.percentualMargemValorAdicionadoST, other.percentualMargemValorAdicionadoST)) {
return false;
}
if (!Objects.equals(this.motivoDesoneracaoICMS, other.motivoDesoneracaoICMS)) {
return false;
}
if (!Objects.equals(this.valorICMSDesoneracao, other.valorICMSDesoneracao)) {
return false;
}
if (!Objects.equals(this.percentualReducaoBCST, other.percentualReducaoBCST)) {
return false;
}
return true;
}
}
|
package com.webserver.shoppingmall.post.model;
import com.webserver.shoppingmall.member.model.Member;
import com.webserver.shoppingmall.shared.BaseTimeEntity;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Getter
@NoArgsConstructor
@Entity
public class Post extends BaseTimeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "post_id")
private Long id;
private String title;
private String content;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member;
@OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE)
private List<Comment> comments = new ArrayList<>();
@Builder
public Post(String title, String content) {
this.title = title;
this.content = content;
}
public void addMember(Member member) {
this.member = member;
}
public void editPost(String title, String content) {
this.title = title;
this.content = content;
}
}
|
package com.zantong.mobilecttx.base.bean;
/**
* 分组项
* @author zyb
*
*
* * * * *
* * * *
* * *
* * *
* * *
* *
*
*
* create at 17/5/4 下午4:54
*/
public class SuperBean {
String name;
boolean hasArrow;
public SuperBean(String name, boolean hasArrow) {
this.name = name;
this.hasArrow = hasArrow;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isHasArrow() {
return hasArrow;
}
public void setHasArrow(boolean hasArrow) {
this.hasArrow = hasArrow;
}
}
|
package cus1156_groupproject;
import java.awt.Window.Type;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
public class ExamController {
private ExamView theView;
private ExamModel theModel;
public ExamController (ExamView theView, ExamModel theModel) {
this.theView = theView;
this.theModel = theModel;
this.theView.LoginListener(new LoginListener());
this.theView.TakeExamListener(new TakeExamListener ());
this.theView.QuestionListener(new QuestionListener ());
this.theView.PrintExamListener(new PrintExamListener ());
this.theView.LogoutListener(new LogoutListener ());
this.theView.RandomizeListener(new RandomizeListener ());
}
//login button attempt
class LoginListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent h) {
String username, password, userType;
username = theView.getUsername();
password = theView.getPassword();
userType = theModel.verifyUser(username, password);
theModel.createExam("Exam");
theView.userType(userType);
}
}
class QuestionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String question1, answer1, answer2, answer3;
question1 = theView.getQuestion1();
answer1 = theView.getAnswer1();
answer2 = theView.getAnswer2();
answer3 = theView.getAnswer3();
theModel.addQuestion(question1, answer1, answer2, answer3);
}
}
class TakeExamListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent f) {
theModel.printExam();
}
}
class PrintExamListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent g) {
theModel.printExam();
}
}
class LogoutListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent h) {
theView.userType("revert");
}
}
class RandomizeListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent i) {
theModel.randomize();
}
}
} |
package com.example.marios.mathlearn;
/**
* Created by Marios on 5/10/2016.
*/
public class Assignment {
public String assignTitle="";
public String assignLink="";
public boolean assignSelected=false;
public int assignID;
public int assignSequence;
public Assignment(String t, String l, boolean s, int i, int seq){
assignTitle=t;
assignLink=l;
assignSelected=s;
assignID=i;
assignSequence=seq;
}
}
|
package com.springapp.mvc.core.cookie;
import javax.inject.Inject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* Created by max.lu on 2016/1/6.
*/
public class CookieContext {
@Inject
private HttpServletResponse httpServletResponse;
private Map<String, Object> cookies = new HashMap<String, Object>();
public Object getCookie(String key) {
return cookies.get(key);
}
public void setCookie(String key, String value) {
Cookie cookie = new Cookie(key, value);
cookie.setMaxAge(3600);
httpServletResponse.addCookie(cookie);
cookies.put(key, value);
}
public void deleteCookie(String key) {
Cookie cookie = new Cookie(key, null);
cookie.setMaxAge(0);
httpServletResponse.addCookie(cookie);
cookies.remove(key);
}
void setHttpServletResponse(HttpServletResponse httpServletResponse) {
this.httpServletResponse = httpServletResponse;
}
public void addCookie(Cookie cookie) {
cookies.put(cookie.getName(), cookie.getValue());
}
}
|
/*
* 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 database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import modelo.Articulo;
import modelo.InterfazBaseDatos;
import modelo.OracleBaseDatos;
/**
*
* @author ruiz
*/
public class DBArticulo {
private InterfazBaseDatos iBd;
public DBArticulo() {
try {
iBd = new OracleBaseDatos();
} catch (Exception e) {
System.err.println("DBArticulo => " + e.getMessage());
}
}
public ArrayList<Articulo> listaArticulos() {
ArrayList<Articulo> lstArticulos = new ArrayList<>();
Articulo articulo;
Connection con = null;
PreparedStatement ps = null;
try {
con = iBd.getConnection();
String consulta = "SELECT * FROM ARTICULO ORDER BY NOMBRE";
ps = con.prepareStatement(consulta);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
articulo = new Articulo();
articulo.setIdArticulo(rs.getInt("ID_ARTICULO"));
articulo.setNombre(rs.getString("NOMBRE"));
articulo.setPrecio(rs.getDouble("PRECIO"));
articulo.setFechaCreacion(rs.getDate("FECHA_CREACION"));
articulo.setFechaModificacion(rs.getDate("FECHA_MODIFICACION"));
lstArticulos.add(articulo);
}
} catch (SQLException e) {
System.err.println("DBArticulo - listaArticulos - Error al leer la tabla Articulos => " + e.getMessage());
} finally {
try { // cierro la conexion con la base de datos
if (con != null && !con.isClosed()) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
System.err.println("Error al cerrar la base de datos => " + e.getMessage());
}
}
return lstArticulos;
}
public int dameIdArticulo() {
Connection con = null;
int idEquipo = 0;
PreparedStatement ps = null;
try {
con = iBd.getConnection();
String consulta = "SELECT MAX(ID_ARTICULO) AS MAXIMO FROM ARTICULO";
ps = con.prepareStatement(consulta);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
idEquipo = rs.getInt("MAXIMO");
}
} catch (SQLException e) {
System.err.println("DBArticulo - dameIdArticulo - Error al leer la tabla ARTICULO => " + e.getMessage());
} finally {
try { // cierro la conexion con la base de datos
if (con != null && !con.isClosed()) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
System.err.println("Error al cerrar la base de datos => " + e.getMessage());
}
}
return idEquipo;
}
public boolean insertaArticulo(Articulo articulo) {
boolean exito = false;
Connection con = null;
PreparedStatement ps = null;
try {
con = iBd.getConnection();
String consulta = "INSERT INTO ARTICULO (ID_ARTICULO, NOMBRE, PRECIO, FECHA_CREACION) VALUES (?,?,?,SYSDATE)";
ps = con.prepareStatement(consulta);
ps.setInt(1, articulo.getIdArticulo());
ps.setString(2, articulo.getNombre());
ps.setDouble(3, articulo.getPrecio());
ps.executeUpdate();
exito = true;
} catch (SQLException e) {
System.err.println("DBArticulo - insertaArticulo - Error al insertar en la tabla ARTICULO => " + e.getMessage());
} finally {
try { // cierro la conexion con la base de datos
if (con != null && !con.isClosed()) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
System.err.println("Error al cerrar la base de datos => " + e.getMessage());
}
}
return exito;
}
public boolean actualizaArticulo(Articulo articulo) {
boolean exito = false;
Connection con = null;
PreparedStatement ps = null;
try {
con = iBd.getConnection();
String consulta = "UPDATE ARTICULO SET NOMBRE = ?, PRECIO = ?, FECHA_MODIFICACION = SYSDATE WHERE ID_ARTICULO = ?";
ps = con.prepareStatement(consulta);
ps.setString(1, articulo.getNombre());
ps.setDouble(2, articulo.getPrecio());
ps.setInt(3, articulo.getIdArticulo());
ps.executeUpdate();
exito = true;
} catch (SQLException e) {
System.err.println("DBArticulo - actualizaArticulo - Error al actualizar la tabla ARTICULO => " + e.getMessage());
} finally {
try { // cierro la conexion con la base de datos
if (con != null && !con.isClosed()) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
System.err.println("Error al cerrar la base de datos => " + e.getMessage());
}
}
return exito;
}
public double damePrecio(int idArticulo) {
double precio = 0;
Connection con = null;
PreparedStatement ps = null;
try {
con = iBd.getConnection();
String consulta = "SELECT PRECIO FROM ARTICULO WHERE ID_ARTICULO = ?";
ps = con.prepareStatement(consulta);
ps.setInt(1, idArticulo);
// ps = con.prepareStatement(consulta);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
precio = rs.getDouble("PRECIO");
}
} catch (SQLException e) {
System.err.println("DBArticulo - damePrecio - Error al leer la tabla ARTICULO => " + e.getMessage());
} finally {
try { // cierro la conexion con la base de datos
if (con != null && !con.isClosed()) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
System.err.println("Error al cerrar la base de datos => " + e.getMessage());
}
}
return precio;
}
public Articulo dameArticulo(int idArticulo) {
Articulo articulo = new Articulo();
Connection con = null;
PreparedStatement ps = null;
try {
con = iBd.getConnection();
String consulta = "SELECT * FROM ARTICULO WHERE ID_ARTICULO = ?";
ps = con.prepareStatement(consulta);
ps.setInt(1, idArticulo);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
articulo.setIdArticulo(rs.getInt("ID_ARTICULO"));
articulo.setNombre(rs.getString("NOMBRE"));
articulo.setPrecio(rs.getDouble("PRECIO"));
articulo.setFechaCreacion(rs.getDate("FECHA_CREACION"));
articulo.setFechaModificacion(rs.getDate("FECHA_MODIFICACION"));
}
} catch (SQLException e) {
System.err.println("DBArticulo - dameArticulo - Error al leer la tabla ARTICULO => " + e.getMessage());
} finally {
try { // cierro la conexion con la base de datos
if (con != null && !con.isClosed()) {
con.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
System.err.println("Error al cerrar la base de datos => " + e.getMessage());
}
}
return articulo;
}
}
|
package br.assembleia.service.impl;
import br.assembleia.dao.PatrimonioDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.assembleia.entidades.Patrimonio;
import br.assembleia.service.PatrimonioService;
import java.math.BigDecimal;
import java.util.List;
@Service
@Transactional
public class PatrimonioServiceImpl implements PatrimonioService {
@Autowired
private PatrimonioDAO dao;
@Override
public void salvar(Patrimonio patrimonio) throws IllegalArgumentException {
dao.salvar(patrimonio);
}
@Override
public List<Patrimonio> listarTodos() {
return dao.listarTodos();
}
@Override
public void editar(Patrimonio patrimonio) {
dao.editar(patrimonio);
}
@Override
public void deletar(Patrimonio patrimonio) {
dao.deletar(patrimonio);
}
@Override
public Patrimonio getById(Long id) {
return dao.getById(id);
}
@Override
public BigDecimal valorPatrimonio() {
return dao.valorPatrimonio();
}
}
|
package gui;
import java.awt.Choice;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import blood.model.BloodAdvisor;
public class BloodForm extends JFrame{
Choice ch;
JButton bt;
BloodAdvisor adviser = new BloodAdvisor();
public BloodForm() {
ch = new Choice();
bt = new JButton("분석보기");
//혈액형 유형 추가
ch.add("A");
ch.add("B");
ch.add("O");
ch.add("AB");
setLayout(new FlowLayout());
ch.setPreferredSize(new Dimension(120,30));
add(ch);
add(bt);
bt.addActionListener((e)->{
showResult();
});
setSize(400,200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void showResult() {
String msg = adviser.getAdvice(ch.getSelectedItem());
JOptionPane.showMessageDialog(this, msg);
}
public static void main(String[] args) {
new BloodForm();
}
}
|
package com.company;
import java.util.Scanner;
public class Ejercicio2_4 {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
System.out.print("Introduzca el numero de millas: ");
int millas = teclado.nextInt();
System.out.print("El numero de millas a metros es: ");
System.out.println(millas * 1609);
}
}
|
package it.unive.java.util.exceptions;
@SuppressWarnings("serial")
public class NotFoundException extends Exception{
public NotFoundException (String msg) {
super(msg);
}
}
|
/*
* ### Copyright (C) 2005-2007 Michael Fuchs ###
* ### All Rights Reserved . ###
*
* Author: Michael Fuchs
* E-Mail: michael.fuchs@unico-group.com
* URL: http://www.michael-a-fuchs.de
*/
package org.dbdoclet.tidbit.medium;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.Vector;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dbdoclet.Sfv;
import org.dbdoclet.io.EndsWithFilter;
import org.dbdoclet.jive.dialog.ErrorBox;
import org.dbdoclet.progress.InfoListener;
import org.dbdoclet.progress.MessageListener;
import org.dbdoclet.service.ExecResult;
import org.dbdoclet.service.ExecServices;
import org.dbdoclet.service.FileServices;
import org.dbdoclet.service.ResourceServices;
import org.dbdoclet.service.StringServices;
import org.dbdoclet.tidbit.common.Constants;
import org.dbdoclet.tidbit.common.Output;
import org.dbdoclet.tidbit.common.StaticContext;
import org.dbdoclet.tidbit.project.Project;
import org.dbdoclet.tidbit.project.driver.AbstractDriver;
import org.dbdoclet.html.parser.HtmlParser;
import org.dbdoclet.html.parser.ParserException;
import org.dbdoclet.html.tokenizer.TokenizerException;
import org.dbdoclet.xiphias.XPathServices;
import org.dbdoclet.xiphias.XmlServices;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* Superklasse für die Mediengeneratoren.
*/
public abstract class Generator extends Thread implements InfoListener {
public static int IDLE = 1;
public static int RUNNING = 2;
private final static Log logger = LogFactory.getLog(Generator.class);
protected final static String FSEP = System.getProperty("file.separator");
protected final static String PSEP = System.getProperty("path.separator");
private boolean killed = false;
private int monitorPort;
private Process process;
private int idleStatus = IDLE;
private Vector<String> targets;
protected MessageListener messageListener;
protected Project project;
protected ResourceBundle res;
private String viewerCommand;
private final ArrayList<GenerationListener> listenerList;
public Generator() {
targets = new Vector<String>();
res = StaticContext.getResourceBundle();
listenerList = new ArrayList<GenerationListener>();
}
public static String processPlaceholders(String cmd, File file)
throws IOException {
String fileName = "\"" + file.getCanonicalPath() + "\"";
cmd = StringServices.replace(cmd, "%u", fileName);
cmd = StringServices.replace(cmd, "%f", fileName);
cmd = StringServices.replace(cmd, "${f}", fileName);
cmd = StringServices.replace(cmd, "${u}", fileName);
cmd = StringServices.replace(cmd, "${file}", fileName);
cmd = StringServices.replace(cmd, "${url}", fileName);
cmd = StringServices.replace(cmd, "\"\"", "\"");
return cmd;
}
public void addGenerationListener(GenerationListener listener) {
if (listenerList.contains(listener) == false) {
listenerList.add(listener);
}
}
public void addTarget(String target) {
if (target == null) {
throw new IllegalArgumentException(
"The argument target must not be null!");
}
targets.add(target);
}
public File getDestinationDir() {
return project.getBuildDirectory();
}
public Process getProcess() {
return process;
}
public int getStatus() {
return idleStatus;
}
public String getViewerCommand() {
return viewerCommand;
}
public void fatal(String msg, Throwable oops) {
if (messageListener != null && msg != null) {
messageListener.fatal(msg, oops);
}
}
public void error(String msg) {
if (messageListener != null && msg != null) {
messageListener.error(msg);
}
}
public void info(String msg) {
if (messageListener != null && msg != null) {
messageListener.info(msg);
}
}
public boolean isCanceled() {
return killed;
}
/**
* Liefert wahr, falls der Generator DocBook erzeugt und nicht
* weiterverarbeitet.
*
* @return flag
*/
public boolean isSourceCreator() {
return false;
}
public void kill() {
if (process == null) {
return;
}
try {
process.exitValue();
} catch (IllegalThreadStateException oops) {
process.destroy();
}
setStatus(IDLE);
}
@Override
public abstract void run();
public void setMessageListener(MessageListener listener) {
this.messageListener = listener;
}
public void setMonitorPort(int monitorPort) {
this.monitorPort = monitorPort;
}
public void setProject(Project project) {
this.project = project;
}
public void setTarget(String target) {
if (target == null) {
throw new IllegalArgumentException(
"The argument target must not be null!");
}
targets = new Vector<String>();
addTarget(target);
}
public void setViewerCommand(String viewerCommand) {
this.viewerCommand = viewerCommand;
}
private int getMonitorPort() {
return monitorPort;
}
private void relocateRelativeHtmlImages(File htmlFile, Output output)
throws IOException, ParserException, TokenizerException,
ParserConfigurationException, SAXException {
File docBookFileDir = new File(project.getFileManager()
.getDocBookFileDirName());
AbstractDriver driver = project.getDriver(output);
String imgSrcPath = driver.getParameter(Constants.PARAM_IMG_SRC_PATH,
"");
ArrayList<Node> imgNodeList = new ArrayList<Node>();
if (output == Output.webhelp) {
Document doc = XmlServices.loadDocument(htmlFile);
imgNodeList = XPathServices.getNodes(doc, "xhtml", Sfv.NS_XHTML,
"//xhtml:img");
} else {
HtmlParser parser = new HtmlParser();
Document doc = parser.parseDocument(htmlFile);
imgNodeList = XPathServices.getNodes(doc, "//img");
}
for (Node node : imgNodeList) {
Element img = (Element) node;
String srcAttr = img.getAttribute("src");
if (srcAttr == null || srcAttr.trim().length() == 0) {
continue;
}
String toFileName = FileServices.appendPath(
htmlFile.getParentFile(), srcAttr);
File toFile = new File(toFileName);
if (toFile.exists() == true) {
continue;
}
File fromFile;
if (FileServices.isAbsolutePath(srcAttr) == true) {
continue;
}
if (imgSrcPath.trim().length() > 0) {
srcAttr = FileServices.removeParentPath(srcAttr, imgSrcPath);
}
String path = FileServices.appendFileName(docBookFileDir, srcAttr);
fromFile = new File(path);
if (fromFile.exists() == false) {
continue;
}
info("Relocating image " + srcAttr + "...");
FileServices.copyFileToFile(fromFile, toFile);
}
}
protected boolean buildFailed(ExecResult result) {
if (result == null) {
return true;
}
if (result.getOutput() != null
&& result.getOutput().trim().endsWith("BUILD FAILED")) {
return true;
}
if (result.getExitCode() > 0) {
return true;
}
return false;
}
protected ExecResult executeAntTarget() {
if (targets == null) {
throw new IllegalStateException(
"The fields target must not be null!");
}
ExecResult result = new ExecResult();
result.setExitCode(0);
File file = project.getProjectFile();
File jdkHome = project.getJdkHome();
String memory = project.getJvmMaxMemory();
ResourceBundle res = StaticContext.getResourceBundle();
if (file == null) {
error(ResourceServices.getString(res,
"C_ERROR_PROJECT_FILE_IS_NOT_DEFINED"));
result.setOutput(new StringBuffer(ResourceServices.getString(res,
"C_ERROR_PROJECT_FILE_IS_NOT_DEFINED")));
return result;
}
try {
String javaCmd = FileServices.appendPath(jdkHome, "bin");
javaCmd = FileServices.appendFileName(javaCmd, "java");
String jarFileName = FileServices.appendPath(
StaticContext.getHome(), "jars");
jarFileName = FileServices.appendFileName(jarFileName, "arun.jar");
if (memory == null || memory.trim().length() == 0) {
memory = "2048";
}
String[] cmd = new String[targets.size() + 6];
cmd[0] = javaCmd;
cmd[1] = "-Xmx" + memory + "m";
cmd[2] = "-jar";
cmd[3] = jarFileName;
cmd[4] = "--file=" + file.getCanonicalPath();
cmd[5] = "--port=" + getMonitorPort();
for (int i = 0; i < targets.size(); i++) {
String target = targets.get(i);
cmd[i + 6] = "--target=" + target;
}
if (getStatus() == RUNNING) {
result.setOutput(new StringBuffer(ResourceServices.getString(
res, "C_ERROR_GENERATION_ALREADY_STARTED")));
return result;
}
setStatus(RUNNING);
ExecServices.exec(javaCmd + " -version", this);
StringBuilder cmdline = new StringBuilder();
for (String token : cmd) {
cmdline.append(token);
cmdline.append(' ');
}
info(cmdline.toString());
result = ExecServices.exec(cmd, null, null, true, this);
killed = false;
process = result.getProcess();
if (process == null) {
StringBuilder buffer = new StringBuilder();
buffer.append("Execution of generator failed: ");
buffer.append("\nOutput: ");
buffer.append(result.getOutput());
result.setExitCode(2);
if (result.getThrowable() != null) {
buffer.append("\nThrowable: ");
buffer.append(result.getStackTrace());
}
error(buffer.toString());
} else {
try {
process.waitFor();
} catch (InterruptedException oops) {
fatal("Generator was interrupted: ", oops);
}
}
String output = result.getOutput();
if (output != null && output.trim().endsWith("BUILD FAILED")) {
result.setExitCode(1);
}
String msg = MessageFormat.format(
ResourceServices.getString(res, "C_GENERATION_FINISHED"),
StaticContext.getDate());
info(msg);
} catch (Throwable oops) {
fatal("Unexcepted exception while execting generator: ", oops);
String output = oops.getMessage();
if (output == null) {
output = "";
}
result.setOutput(new StringBuffer(output));
result.setThrowable(oops);
return result;
} finally {
setStatus(IDLE);
}
if (buildFailed(result)) {
String buffer = result.getOutput() + "\n" + result.getStackTrace();
if (buffer.length() > 4096) {
buffer = buffer.substring(0, 4093) + "...";
}
ErrorBox.show(ResourceServices.getString(res, "C_ERROR"),
buffer.trim());
}
return result;
}
protected void finished() {
for (GenerationListener listener : listenerList) {
listener.generationFinished(0);
}
}
protected File getBaseDir(AbstractDriver driver) {
String baseDirName = driver.getParameter("base.dir", "./build/");
if (baseDirName == null || baseDirName.trim().length() == 0) {
baseDirName = "./build/";
}
if (FileServices.isAbsolutePath(baseDirName) == false) {
String path = project.getFileManager().getDocBookFileDirName();
baseDirName = FileServices.appendPath(path, baseDirName);
}
return new File(baseDirName);
}
protected void relocateHtml(File baseDir, Output output) {
for (File htmlFile : baseDir.listFiles(new EndsWithFilter(".html",
".htm"))) {
try {
relocateRelativeHtmlImages(htmlFile, output);
} catch (TokenizerException oops) {
logger.error("Tokenizer error\n" + htmlFile.getAbsolutePath()
+ "\n" + oops.getMessage());
} catch (Exception oops) {
oops.printStackTrace();
}
}
}
protected void setStatus(int status) {
this.idleStatus = status;
}
}
|
package com.cg.service;
import com.cg.entity.Guest;
public interface GuestService {
public long registerGuest(Guest guest);
public long validateGuest(String email, String password);
}
|
package com.agilesoftware.bookgonara.bookgo.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.agilesoftware.bookgonara.bookgo.R;
import com.agilesoftware.bookgonara.bookgo.databinding.ActivitySearchBinding;
public class SearchActivity extends AppCompatActivity {
private ActivitySearchBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
|
import java.util.Arrays;
import java.util.Random;
public class WorldSystem_v3 {
public int initialStatesNum, currentStatesNum, PC;
public double capAvg, capMed, capSS, capStdDev, capLeading_1, capLeading_2, myCap, oppCap, mySideCap;
public double sideA_cap, sideB_cap;
public double[] capabilities;
public boolean isStable;
static Random rd = new Random();
public char[][] strategy_1, strategy_2;
char[] strategy;
int[] popID;
boolean[] warringA, warringB ;
int capChangeCount;
public WorldSystem_v3(char[][] strategy_1, char[][] strategy_2) {
this.strategy_1 = strategy_1;
this.strategy_2 = strategy_2;
initialStatesNum = strategy_1.length;
currentStatesNum = initialStatesNum;
isStable = false;
GP_PilotStudy_v2.TC1++;
GP_PilotStudy_v2.TC11++;
GP_PilotStudy_v2.TC2 +=initialStatesNum;
// generate randomly capabilities so that they add up to 1
capabilities = new double[initialStatesNum];
for (int i = 0; i < initialStatesNum; i++)
capabilities[i] = rd.nextDouble();
normalizeCapabilities();
calculateSystemicVariables();
GP_PilotStudy_v2.TC3 += capAvg;
GP_PilotStudy_v2.TC4 += capStdDev;
GP_PilotStudy_v2.TC5 += capMed;
capChangeCount=GP_PilotStudy_v2.CAPCHANGE;
// because the passed population will be later shuffled, popID will keep
// track of the initial order of the population
popID=new int[initialStatesNum];
for (int i = 0; i < initialStatesNum; i++) {
popID[i] = i;
}
}
private void normalizeCapabilities() {
int lastSuvivIndex = initialStatesNum - 1;
while (strategy_1[lastSuvivIndex] == null)
lastSuvivIndex -= 1;
double total = 0;
for (int i = 0; i <= lastSuvivIndex; i++)
if (strategy_1[i] != null)
total += capabilities[i];
double sum = 0;
for (int i = 0; i < lastSuvivIndex; i++)
if (strategy_1[i] != null) {
capabilities[i] = capabilities[i] / total;
sum += capabilities[i];
}
capabilities[lastSuvivIndex] = 1 - sum;
}
private void calculateSystemicVariables() {
// since capabilities should already be normalized average can be
// calculated as follows
capAvg = 1.0 / (double) currentStatesNum;
capSS = 0;
for (int i = 0; i < initialStatesNum; i++)
if (strategy_1[i] != null)
capSS += (capabilities[i] - capAvg) * (capabilities[i] - capAvg);
capStdDev = Math.sqrt(capSS / currentStatesNum);
// calculate median
double[] temp = new double[currentStatesNum];
int counter = 0;
for (int i = 0; i < initialStatesNum; i++)
if (strategy_1[i] != null)
temp[counter++] = capabilities[i];
Arrays.sort(temp);
int middle = currentStatesNum / 2;
if (currentStatesNum % 2 == 1) {
capMed = temp[middle];
} else {
capMed = (temp[middle - 1] + temp[middle]) / 2;
}
capLeading_1 = temp[currentStatesNum - 1];
capLeading_2 = temp[currentStatesNum - 2];
}
public boolean[] simulate() {
while (!isStable) {
// Implementing Fisher–Yates shuffle of strategies, capabilities,
// and popID
// arrays
int index, tempID;
double tempCap;
char[] tempIndiv_1, tempIndiv_2;
for (int i = initialStatesNum - 1; i > 0; i--) {
index = rd.nextInt(i + 1);
tempID = popID[index];
popID[index] = popID[i];
popID[i] = tempID;
tempCap = capabilities[index];
capabilities[index] = capabilities[i];
capabilities[i] = tempCap;
tempIndiv_1 = strategy_1[index];
strategy_1[index] = strategy_1[i];
strategy_1[i] = tempIndiv_1;
tempIndiv_2 = strategy_2[index];
strategy_2[index] = strategy_2[i];
strategy_2[i] = tempIndiv_2;
}
isStable = true;
warringA = new boolean[initialStatesNum];
warringB = new boolean[initialStatesNum];
sideA_cap = 0;
sideB_cap = 0;
for (int i = 0; i < initialStatesNum; i++) {
if (strategy_1[i] != null) {
myCap = capabilities[i];
mySideCap = myCap;
strategy = strategy_1[i];
for (int j = 0; j < initialStatesNum; j++) {
if (i == j || strategy_1[j] == null)
continue;
PC = 0;
oppCap = capabilities[j];
if (run() == 1) {
sideA_cap = capabilities[i];
sideB_cap = capabilities[j];
warringA[i] = true;
warringB[j] = true;
// check if others want to join either side
boolean newJoiner;
findJoiners: do {
newJoiner = false;
for (int n = 0; n < initialStatesNum; n++)
if (strategy_2[n] != null && !warringA[n] && !warringB[n]) {
myCap = capabilities[n];
strategy = strategy_2[n];
int rand = rd.nextInt(2);
switch (rand) {
case 0:
mySideCap = sideA_cap;
oppCap = sideB_cap;
PC = 0;
if (run() == 1) {
sideA_cap += myCap;
warringA[n] = true;
newJoiner = true;
continue findJoiners;
}
mySideCap = sideB_cap;
oppCap = sideA_cap;
PC = 0;
if (run() == 1) {
sideB_cap += myCap;
warringB[n] = true;
newJoiner = true;
continue findJoiners;
}
case 1:
mySideCap = sideB_cap;
oppCap = sideA_cap;
PC = 0;
if (run() == 1) {
sideB_cap += myCap;
warringB[n] = true;
newJoiner = true;
continue findJoiners;
}
mySideCap = sideA_cap;
oppCap = sideB_cap;
PC = 0;
if (run() == 1) {
sideA_cap += myCap;
warringA[n] = true;
newJoiner = true;
continue findJoiners;
}
}
}
} while (newJoiner);
excuteAttack();
calculateStatesNo();
if (currentStatesNum == 1) {
boolean[] survivors = new boolean[initialStatesNum];
for (int n = 0; n < initialStatesNum; n++)
if (strategy_1[n] != null)
survivors[popID[n]] = true;
return survivors;
}
normalizeCapabilities();
calculateSystemicVariables();
isStable = false;
break;
}
}
if (!isStable)
break;
}
}
}
if (capChangeCount > 0) {
capChangeCount--;
for (int i = 0; i < initialStatesNum; i++)
capabilities[i] = capabilities[i] * rd.nextDouble() ;
calculateStatesNo();
normalizeCapabilities();
calculateSystemicVariables();
isStable=false;
return(simulate());
}
boolean[] survivors = new boolean[initialStatesNum];
for (int i = 0; i < initialStatesNum; i++)
if (strategy_1[i] != null)
survivors[popID[i]] = true;
return survivors;
}
private void calculateStatesNo() {
currentStatesNum = 0;
for (int i = 0; i < initialStatesNum; i++)
if (strategy_1[i] != null)
currentStatesNum++;
}
private void excuteAttack() {
// This method should set the loosing side to null and adjust the
// capability of the winner
if (sideA_cap >= sideB_cap) {
// kill side B states
// assign their capabilities to side A depending on their power
for (int i = 0; i < initialStatesNum; i++) {
if (warringA[i]) {
capabilities[i] = capabilities[i] + (capabilities[i] / sideA_cap * sideB_cap);
} else if (warringB[i]) {
strategy_1[i] = null;
strategy_2[i] = null;
}
}
} else {
// kill side A states
// assign their capabilities to side B depending on their power
for (int i = 0; i < initialStatesNum; i++) {
if (warringB[i]) {
capabilities[i] = capabilities[i] + (capabilities[i] / sideB_cap * sideA_cap);
} else if (warringA[i]) {
strategy_1[i] = null;
strategy_2[i] = null;
}
}
}
GP_PilotStudy_v2.TC6++;
GP_PilotStudy_v2.TC12++;
}
private double run() {
char primitive = strategy[PC++];
switch (primitive) {
case GP_PilotStudy_v2.CAPAVG:
return (capAvg);
case GP_PilotStudy_v2.CAPMED:
return (capMed);
case GP_PilotStudy_v2.CAPSS:
return (capSS);
case GP_PilotStudy_v2.CAPSTDEV:
return (capStdDev);
case GP_PilotStudy_v2.CAPLEADING_1:
return (capLeading_1);
case GP_PilotStudy_v2.CAPLEADING_2:
return (capLeading_2);
case GP_PilotStudy_v2.MYCAP:
return (myCap);
case GP_PilotStudy_v2.OPPCAP:
return (oppCap);
case GP_PilotStudy_v2.MYSIDECAP:
return (mySideCap);
case GP_PilotStudy_v2.GT:
if (run() > run())
return (1);
else
return (0);
case GP_PilotStudy_v2.LT:
if (run() < run())
return (1);
else
return (0);
case GP_PilotStudy_v2.AND:
if (run() == 1 && run() == 1)
return (1);
else
return (0);
case GP_PilotStudy_v2.OR:
if (run() == 1 || run() == 1)
return (1);
else
return (0);
case GP_PilotStudy_v2.ADD:
return (run() + run());
case GP_PilotStudy_v2.SUB:
return (run() - run());
case GP_PilotStudy_v2.MUL:
return (run() * run());
case GP_PilotStudy_v2.DIV: {
double num = run(), den = run();
if (Math.abs(den) <= 0.001)
return (num);
else
return (num / den);
}
default:
return (GP_PilotStudy_v2.randNum[primitive]);
}
}
}
|
package collection;
import java.util.LinkedList;
public class LinkedListDemo {
private static final String[] EX_CLASS = {
"Dung",
"Thu A",
"Thu B",
"H. Thu",
"Truong",
"Hung",
"Tho",
"Anh",
"Hue",
"Huyen",
"NVH",
"Vu",
"Ngoc",
"T. Thuy",
"Tam",
"Giang",
"Mai",
"Quyen",
"Son",
"V.Tuan",
"A.Tuan",
"T. Anh",
"Thanh",
"D. Anh",
"T. Tan",
"D. Tan",
"M. Thuy",
"V. Thuan",
"B. Thuan",
"Trung",
"Huong",
"Long",
"Bach"
};
public static void main(String[] args) {
LinkedList<String> list = new LinkedList();
for (String s : EX_CLASS) {
list.addLast(s);
}
System.out.println(list.size());
}
}
|
package model;
public enum EnumTipoPagamento {
DÉBITO,
CRÉDITO,
Dinheiro;
}
|
package com.example.faisal.dto.errors;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@JsonNaming(PropertyNamingStrategy.LowerCaseStrategy.class)
public final class ApiErrorsField {
private String field;
private String message;
public ApiErrorsField(String field, String message) {
this.field = field;
this.message = message;
}
public static List<ApiErrorsField> buildErrorFields(Map<String, String> errorMap) {
List<ApiErrorsField> apiErrorsFields = new ArrayList();
errorMap.forEach((key, value) -> {
apiErrorsFields.add(new ApiErrorsField(key, value));
});
return apiErrorsFields;
}
public String getField() {
return this.field;
}
public String getMessage() {
return this.message;
}
public void setField(String field) {
this.field = field;
}
public void setMessage(String message) {
this.message = message;
}
}
|
/**
*
*/
package com.vinodborole.portal.email;
import java.io.UnsupportedEncodingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.common.collect.Lists;
import it.ozimov.springboot.mail.model.Email;
import it.ozimov.springboot.mail.model.defaultimpl.DefaultEmail;
import it.ozimov.springboot.mail.service.EmailService;
import it.ozimov.springboot.mail.service.exception.CannotSendEmailException;
/**
* @author vinodborole
*
*/
@Component
public class PortalEmailClient {
@Autowired
private EmailService emailService;
public void sendEmailWithoutTemplating(PortalEmail portalEmail) throws UnsupportedEncodingException, AddressException {
final Email email = DefaultEmail.builder().from(new InternetAddress(portalEmail.getFrom()))
.to(Lists.newArrayList(new InternetAddress(portalEmail.getTo()))).subject(portalEmail.getSubject())
.body(portalEmail.getBody() == null ? "" : portalEmail.getBody()).encoding("UTF-8").build();
emailService.send(email);
}
public void sendMimeEmailWithTemplate(PortalEmail portalEmail) throws AddressException, CannotSendEmailException {
final Email email = DefaultEmail.builder().from(new InternetAddress(portalEmail.getFrom()))
.to(Lists.newArrayList(new InternetAddress(portalEmail.getTo()))).subject(portalEmail.getSubject())
.body(portalEmail.getBody() == null ? "" : portalEmail.getBody()).encoding("UTF-8").build();
String template = portalEmail.getTemplate().toString();
emailService.send(email, template, portalEmail.getTemplateContent());
}
}
|
package com.sims.controller;
import java.beans.PropertyEditorSupport;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.sims.bo.ItemBo;
import com.sims.bo.ListValueBo;
import com.sims.bo.PODetailsBo;
import com.sims.bo.RODetailsBo;
import com.sims.bo.ROHeaderBo;
import com.sims.bo.SupplierBo;
import com.sims.bo.POHeaderBo;
import com.sims.constant.SIMSConstant;
import com.sims.model.Item;
import com.sims.model.ListValue;
import com.sims.model.PODetails;
import com.sims.model.RODetails;
import com.sims.model.ROHeader;
import com.sims.model.Supplier;
import com.sims.model.POHeader;
import com.sims.model.UserAccount;
import com.sims.util.SIMSUtil;
@Controller
@SessionAttributes(value = {"userid","name"})
public class ROController {
private final static Logger logger = Logger.getLogger(ROController.class);
@Autowired
private POHeaderBo pOHeaderBo;
@Autowired
private ROHeaderBo rOHeaderBo;
@Autowired
private RODetailsBo rODetailsBo;
@Autowired
private SupplierBo supplierBo;
@Autowired
private ListValueBo listValueBo;
@Autowired
private ItemBo itemBo;
private List<Supplier> supplierList = new ArrayList<>();
private List<Item> itemList = new ArrayList<>();
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(ListValue.class, new PropertyEditorSupport() {
@Override
public void setAsText(String id) throws IllegalArgumentException {
this.setValue(new ListValue(Integer.parseInt(id)));
}
});
}
@RequestMapping("/goToSearchPOInRO")
public ModelAndView goToSearchPOInRO(ModelMap model) {
if (!SIMSUtil.isUserSessionValid(model)) {
logger.info(SIMSConstant.USER_INVALID_SESSION);
return new ModelAndView("security/login", "poHeader", new POHeader());
}
ModelAndView mv = new ModelAndView();
mv.addObject("searchFlag", false);
mv.addObject("poHeader", new POHeader());
mv.setViewName("transaction/receiveorder/searchPOHeaderInRO");
return mv;
}
@RequestMapping("/goToAddROHeader")
public ModelAndView goToAddROHeader(ModelMap model) {
if (!SIMSUtil.isUserSessionValid(model)) {
logger.info(SIMSConstant.USER_INVALID_SESSION);
return new ModelAndView("security/login", "poHeader", new POHeader());
}
//get the PO header list with status = In Progress (601)
supplierList = getSupplierList();
model.addAttribute("supplierList", supplierList);
return new ModelAndView("transaction/receiveorder/addROHeader", "roHeader", new ROHeader());
}
@SuppressWarnings("unchecked")
@RequestMapping("/searchPOHeaderInRO")
public ModelAndView searchPOHeaderInRO(@RequestParam("page") String page, @ModelAttribute("roHeader") POHeader poHeader,
BindingResult result, ModelMap model) throws Exception {
if (!SIMSUtil.isUserSessionValid(model)) {
logger.info(SIMSConstant.USER_INVALID_SESSION);
return new ModelAndView("security/login", "roHeader", new ROHeader());
}
//Note: can use modelattribute in a form in jsp
//or can simply pass a parameter
Map<Object,Object> mapCriteria = new HashMap<Object,Object>();
mapCriteria.put("search_criteria", poHeader.getSupplier().getName()!=null ? poHeader.getSupplier().getName() : "");
mapCriteria.put("record_start", SIMSUtil.getRecordStartIndex(page!=null ? Integer.parseInt(page) : 1));
mapCriteria.put("max_result", SIMSConstant.RECORDS_PER_PAGE);
Map<Object,Object> resultMap = pOHeaderBo.findBySupplierName(mapCriteria);
List<POHeader> resultList = (List<POHeader>) resultMap.get("resultList");
Integer noOfPages = (Integer) resultMap.get("noOfPages");
boolean gotRecords = resultList!=null && resultList.size() > 0 ? true : false;
model.addAttribute("resultList", resultList);
model.addAttribute("searchFlag", true);
model.addAttribute("gotRecords", gotRecords);
model.addAttribute("currentPage", page);
model.addAttribute("noOfPages", noOfPages);
return new ModelAndView("transaction/receiveorder/searchPOHeaderInRO", "poHeader", poHeader);
}
@RequestMapping(value = "/saveROHeader", method = RequestMethod.POST)
public ModelAndView saveROHeader(@ModelAttribute("roHeader") @Validated ROHeader roHeader,
BindingResult result, ModelMap model) throws Exception {
if (!SIMSUtil.isUserSessionValid(model)) {
logger.info(SIMSConstant.USER_INVALID_SESSION);
return new ModelAndView("security/login", "roHeader", new ROHeader());
}
if (result.hasErrors()) {
return new ModelAndView("transaction/receiveorder/addROHeader", "roHeader", roHeader);
}
// poHeader.setPoNo(generatePONo());
// poHeader.setStatus(new ListValue(601)); //In Progress
// poHeader.setTransDate(new java.sql.Date(System.currentTimeMillis()));
// poHeader.setRequestedBy(SIMSUtil.getUserNameFromSession(model));
// poHeader.setCreatedBy(SIMSUtil.getUserIdFromSession(model));
//
// boolean isSuccess = pOHeaderBo.save(poHeader);
//
// if (isSuccess) {
// logger.info("Added PO Header.. Proceed to View PO Details");
// poHeader = pOHeaderBo.findByPONo(poHeader.getPoNo());
// }
//
// model.addAttribute("supplierList", supplierList);
// model.addAttribute("isSuccess", isSuccess);
return new ModelAndView("transaction/receiveorder/addROHeader", "roHeader", roHeader);
}
@RequestMapping(value = "/viewPOHeaderInRO", method=RequestMethod.GET)
public ModelAndView viewPOHeaderInRO(@RequestParam("poId") int poId, ModelMap model) throws Exception {
if (!SIMSUtil.isUserSessionValid(model)) {
logger.info(SIMSConstant.USER_INVALID_SESSION);
return new ModelAndView("security/login", "roHeader", new ROHeader());
}
POHeader poHeader = pOHeaderBo.findById(poId);
itemList = getItemList();
model.addAttribute("itemList", itemList);
model.addAttribute("totalAmount", poHeader.getTotalAmount());
return new ModelAndView("transaction/receiveorder/viewPOHeaderInRO", "poHeader", poHeader);
}
@RequestMapping(value = "/updateROHeader", method = RequestMethod.POST)
public ModelAndView updateROHeader(@ModelAttribute("roHeader" ) @Validated ROHeader roHeader,
BindingResult result, ModelMap model) throws Exception {
if (!SIMSUtil.isUserSessionValid(model)) {
logger.info(SIMSConstant.USER_INVALID_SESSION);
return new ModelAndView("security/login", "roHeader", new ROHeader());
}
if (result.hasErrors()) {
return new ModelAndView("transaction/receiveorder/viewROHeader", "roHeader", roHeader);
}
roHeader.setModifiedBy(SIMSUtil.getUserIdFromSession(model));
boolean isSuccess = rOHeaderBo.update(roHeader);
model.addAttribute("isSuccess", isSuccess);
return new ModelAndView("transaction/receiveorder/viewROHeader", "roHeader", roHeader);
}
@RequestMapping(value = "/deleteROHeader", method=RequestMethod.GET)
public ModelAndView deleteROHeader(@RequestParam("id") int id, ModelMap model) throws Exception {
if (!SIMSUtil.isUserSessionValid(model)) {
logger.info(SIMSConstant.USER_INVALID_SESSION);
return new ModelAndView("security/login", "roHeader", new ROHeader());
}
ROHeader user = rOHeaderBo.findById(id);
user.setModifiedBy(SIMSUtil.getUserIdFromSession(model));
boolean isSuccess = rOHeaderBo.delete(user);
model.addAttribute("isDeleted", isSuccess);
return new ModelAndView("transaction/receiveorder/searchROHeader", "roHeader", new ROHeader());
}
@RequestMapping(value = "/addNewRODetails", method = RequestMethod.GET)
public ModelAndView addNewRODetails(@RequestParam("roHeaderId") int roHeaderId,
@RequestParam("itemId") int itemId, @RequestParam("qty") int qty, ModelMap model) throws Exception {
if (!SIMSUtil.isUserSessionValid(model)) {
logger.info(SIMSConstant.USER_INVALID_SESSION);
return new ModelAndView("security/login", "poHeader", new POHeader());
}
boolean isSuccess = false;
ROHeader roHeader = rOHeaderBo.findById(roHeaderId);
Item item = itemBo.findById(itemId);
RODetails entity = new RODetails();
entity.setRoHeader(roHeader);
entity.setItem(item);
entity.setQty(qty);
entity.setPrice(item.getRetailOrigPrice());//temp code
double amount = entity.getQty() * (entity.getPrice()!=null ? entity.getPrice().doubleValue() : 0.00D);
entity.setAmount(new BigDecimal(amount));
List<RODetails> list = new ArrayList<>();
if (rODetailsBo.save(entity)) {
//get the total amount
list = rODetailsBo.getListByROHeader(roHeader);
double totalAmount = 0.0D;
for (RODetails itemDetails: list) {
totalAmount = totalAmount + itemDetails.getAmount().doubleValue();
}
roHeader.setTotalAmount(new BigDecimal(totalAmount));
roHeader.setModifiedBy(SIMSUtil.getUserIdFromSession(model));
if (rOHeaderBo.update(roHeader)) {
isSuccess = true;
logger.info("Added RO Details..");
};
}
//update the header to get the details
roHeader = rOHeaderBo.findById(roHeaderId);
model.addAttribute("isSuccess", isSuccess);
model.addAttribute("totalAmount", roHeader.getTotalAmount());
return new ModelAndView("transaction/receiveorder/ajaxRODetails", "roHeader", roHeader);
}
@RequestMapping("/deleteRODetails")
public ModelAndView deleteRODetails(@RequestParam("roHeaderId") int roHeaderId,
@RequestParam("roDetailsId") int roDetailsId, ModelMap model) {
if (!SIMSUtil.isUserSessionValid(model)) {
logger.info(SIMSConstant.USER_INVALID_SESSION);
return new ModelAndView("security/login", "userAccount", new UserAccount());
}
ROHeader roHeader = rOHeaderBo.findById(roHeaderId);
//delete the item details
RODetails entity = rODetailsBo.findById(roDetailsId);
List<RODetails> list = new ArrayList<>();
if (rODetailsBo.delete(entity)) {
//get the total amount
list = rODetailsBo.getListByROHeader(roHeader);
double totalAmount = 0.0D;
for (RODetails itemDetails: list) {
totalAmount = totalAmount + itemDetails.getAmount().doubleValue();
}
roHeader.setTotalAmount(new BigDecimal(totalAmount));
roHeader.setModifiedBy(SIMSUtil.getUserIdFromSession(model));
if (rOHeaderBo.update(roHeader)) {
logger.info("Deleted RO Details..");
};
}
roHeader = rOHeaderBo.findById(roHeaderId);
model.addAttribute("totalAmount", roHeader.getTotalAmount());
return new ModelAndView("transaction/receiveorder/ajaxRODetails", "roHeader", roHeader);
}
private List<Supplier> getSupplierList() {
List<Supplier> list = supplierBo.getAllEntity();
return list;
}
private List<Item> getItemList() {
List<Item> list = itemBo.getAllEntity();
return list;
}
}
|
package by.orion.onlinertasks.presentation.profile.details.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import by.orion.onlinertasks.R;
import by.orion.onlinertasks.presentation.profile.details.pages.information.InformationProfileDetailsFragment;
import by.orion.onlinertasks.presentation.profile.details.pages.reviews.ReviewsProfileDetailsFragment;
public class ProfileDetailsPageAdapter extends FragmentStatePagerAdapter {
private static final int MAX_PAGE = 3;
@NonNull
private final Context context;
@NonNull
private final Integer profileId;
public ProfileDetailsPageAdapter(@NonNull Context context, @NonNull Integer profileId, @NonNull FragmentManager fm) {
super(fm);
this.context = context;
this.profileId = profileId;
}
@Override
public int getCount() {
return MAX_PAGE;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return InformationProfileDetailsFragment.newInstance(profileId);
case 1:
return InformationProfileDetailsFragment.newInstance(profileId);
case 2:
return ReviewsProfileDetailsFragment.newInstance(profileId);
default:
return null;
}
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return context.getString(R.string.title_profile_details_page_information);
case 1:
return context.getString(R.string.title_profile_details_page_portfolio);
case 2:
return context.getString(R.string.title_profile_details_page_reviews);
default:
return null;
}
}
}
|
package com.javarush.test.level07.lesson12.home06;
/* Семья
Создай класс Human с полями имя(String), пол(boolean),возраст(int), отец(Human), мать(Human). Создай объекты и заполни их так, чтобы получилось: Два дедушки, две бабушки, отец, мать, трое детей. Вывести объекты на экран.
Примечание:
Если написать свой метод String toString() в классе Human, то именно он будет использоваться при выводе объекта на экран.
Пример вывода:
Имя: Аня, пол: женский, возраст: 21, отец: Павел, мать: Катя
Имя: Катя, пол: женский, возраст: 55
Имя: Игорь, пол: мужской, возраст: 2, отец: Михаил, мать: Аня
…
*/
import java.util.ArrayList;
public class Solution
{
public static void main(String[] args)
{
//Написать тут ваш код
Human granpa1 = new Human();
Human granpa2 = new Human();
Human granma1 = new Human();
Human granma2 = new Human();
Human dad = new Human();
Human mom = new Human();
Human c1 = new Human();
Human c2 = new Human();
Human c3 = new Human();
Human[] family = {granpa1, granpa2, granma1, granma2, dad, mom, c1, c2, c3}; //new ArrayList<Human>();
//family
granpa1.name = "GP1";
granpa1.age = 78;
granpa1.sex = true;
granpa2.name = "GP2";
granpa2.age = 75;
granpa2.sex = true;
granma1.name = "GM1";
granma1.age = 65;
granma1.sex = false;
granma2.name = "GM2";
granma2.age = 68;
granma2.sex = false;
dad.name = "Dad";
dad.age = 35;
dad.sex = true;
dad.father = granpa1;
dad.mother = granma1;
mom.name = "Mom";
mom.age = 30;
mom.sex = false;
mom.father = granpa2;
mom.mother = granma2;
c1.name = "c1";
c1.age = 5;
c1.sex = true;
c1.father = dad;
c1.mother = mom;
c2.name = "c2";
c2.age = 10;
c2.sex = true;
c2.father = dad;
c2.mother = mom;
c3.name = "c1";
c3.age = 9;
c3.sex = false;
c3.father = dad;
c3.mother = mom;
for (Human x : family) {
System.out.println(x);
}
}
public static class Human
{
//Написать тут ваш код
String name;
boolean sex;
int age;
Human father, mother;
public String toString()
{
String text = "";
text += "Имя: " + this.name;
text += ", пол: " + (this.sex ? "мужской" : "женский");
text += ", возраст: " + this.age;
if (this.father != null)
text += ", отец: " + this.father.name;
if (this.mother != null)
text += ", мать: " + this.mother.name;
return text;
}
}
}
|
/*
* Lesson 3 Coding Activity Question 1
*
* Write the code to ask the user to enter their name and print the following message:
Hi ______, nice to see you.
* Remember, you'll need to use the method println and Scanner class method nextLine.
*/
import java.util.Scanner;
class Lesson_3_Activity_One {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String name = input.nextLine();
System.out.println(String.format("Hi %s, nice to see you.", name));
input.close();
}
} |
package com.blogspot.yourfavoritekaisar.learnfragmentimastudio.ui.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.blogspot.yourfavoritekaisar.learnfragmentimastudio.R;
/**
* A simple {@link Fragment} subclass.
*/
public class List2Fragment extends Fragment {
ListView listView;
public List2Fragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_list2, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = view.findViewById(R.id.list_view);
String [] namaKota = {"bekasi","jakarta","bogor","depok","tangerang"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, android.R.id.text1, namaKota);
listView.setAdapter(adapter);
}
} |
package clientPackage;
interface GameCall {
void gameCommunications(int index, int openCards, boolean toPass);
void sendChatMessage(String message, boolean toPass);
void sendEndOfGame(boolean win, boolean draw, boolean toPass, boolean logOut);
void logOut(boolean toPass);
void showLeaderBoard();
}
|
package TurtleRefactored;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class TurtleTest {
SketchPad mySketchPad;
Turtle myTurtle;
@BeforeEach
void setUp() throws Exception {
mySketchPad = new SketchPad();
myTurtle = new Turtle();
}
@AfterEach
void tearDown() throws Exception {
}
@Test
void test() {
fail("Not yet implemented");
}
}
|
package com.yoga.controller;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.yoga.dao.TbMemberTypeDAO;
import com.yoga.entity.TbMemberType;
import com.yoga.util.Constants;
import com.yoga.util.JsonResponse;
/**
* action
*
* @author wwb
*
*/
@Controller
@RequestMapping("/")
public class TbMemberTypeController {
/**
* 获取dao
*/
private TbMemberTypeDAO dao = new TbMemberTypeDAO();
/**
* 添加信息
* @param id
* @param name
* @param price
* @return
*/
@RequestMapping(value = "memberType/add", method = RequestMethod.GET)
@ResponseBody
public JsonResponse<TbMemberType> add(final int id, String type) {
JsonResponse<TbMemberType> jsonResponse = new JsonResponse<TbMemberType>();
try {
TbMemberType entity = getBean(id,type);
dao.save(entity);
jsonResponse.setMsg(Constants.getTip(Constants.ADD, Constants.MEMBER, Constants.SUCCESS));
jsonResponse.setSuccess(true);
} catch (Exception e) {
e.printStackTrace();
jsonResponse.setSuccess(false);
jsonResponse.setMsg(Constants.getTip(Constants.ADD, Constants.MEMBER, Constants.FAILURE));
}
return jsonResponse;
}
/**
* 编辑信息
* @param id
* @param name
* @param price
* @return
*/
@RequestMapping(value = "memberType/edit", method = RequestMethod.GET)
@ResponseBody
public JsonResponse<TbMemberType> edit(final int id, String type) {
JsonResponse<TbMemberType> jsonResponse = new JsonResponse<TbMemberType>();
try {
TbMemberType entity = getBean(id, type);
// dao.update(entity);
jsonResponse.setMsg(Constants.getTip(Constants.EDIT, Constants.MEMBER, Constants.SUCCESS));
jsonResponse.setSuccess(true);
} catch (Exception e) {
e.printStackTrace();
jsonResponse.setSuccess(false);
jsonResponse.setMsg(Constants.getTip(Constants.EDIT, Constants.MEMBER, Constants.FAILURE));
}
return jsonResponse;
}
/**
* 删除信息
* @param id
* @param name
* @param price
* @return
*/
@RequestMapping(value = "memberType/delete", method = RequestMethod.GET)
public ModelAndView delete(final int id,String type) {
try {
TbMemberType entity = getBean(id,type);
// dao.update(entity);
dao.delete(entity);
} catch (Exception e) {
e.printStackTrace();
}
return new ModelAndView("memberType/index");
}
/**
* 获取列表
* @param page
* @param size
* @param id
* @param name
* @param price
* @return
*/
@RequestMapping(value = "memberType/list.html", method = RequestMethod.GET)
@ResponseBody
public JsonResponse<TbMemberType> list() {
JsonResponse<TbMemberType> jsonResponse = new JsonResponse<TbMemberType>();
try {
List<TbMemberType> findAll = dao.findAll();
// for(TbMemberType tb :findAll){
// tb.setTbMembers(null);
// }
jsonResponse.setSuccess(true);
jsonResponse.setMsg(Constants.getTip(Constants.GET, Constants.MEMBER, Constants.SUCCESS));
jsonResponse.setList(findAll);
} catch (Exception e) {
jsonResponse.setSuccess(false);
jsonResponse.setMsg(Constants.getTip(Constants.GET, Constants.MEMBER, Constants.FAILURE));
}
return jsonResponse;
}
/**
* 获取其中一个信息,并跳转页面
* @param id
* @param modelMap
* @return
*/
@RequestMapping(value = "memberType/showOne.html", method = RequestMethod.GET)
public ModelAndView showOne(@RequestParam final int id,ModelMap modelMap) {
TbMemberType memberType = new TbMemberType();
try {
memberType =dao.findById(id);
modelMap.put("update", "update");
modelMap.put("memberType", memberType);
}catch(Exception exception){
exception.printStackTrace();
}
return new ModelAndView("member/add");
}
/**
* 重构代码
* @param id
* @param name
* @param price
* @return
*/
private TbMemberType getBean(int id, String type) {
TbMemberType entity = null;
try {
String newtype = new String(type.getBytes("iso8859-1"), "UTF-8");
entity = new TbMemberType();
entity.setId(id);
entity.setType(newtype);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return entity;
}
}
|
package com.adwork.microservices.users;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit4.SpringRunner;
import com.adwork.microservices.users.service.KeysService;
import com.adwork.microservices.users.service.KeysService.KeyInfo;
import com.adwork.microservices.users.service.KeysService.PublicKeyInfo;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = UsersApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AuthControllerRestTemplateTest {
@LocalServerPort
private int port;
TestRestTemplate restTemplate = new TestRestTemplate();
@Autowired
private KeysService keysService;
@Test
public void shouldReturnPublicKey() throws Exception {
// load public key from server
PublicKeyInfo pubkey = restTemplate.getForObject(url("/api/auth/public-key"), PublicKeyInfo.class);
assertNotNull(pubkey);
// obtain keys from service
KeyInfo key = keysService.getKeyInfo(pubkey.keyId);
// compare both keys
assertNotNull(key);
assertEquals(pubkey.keyId, key.keyId);
assertEquals(pubkey.publicKey, key.pubKeyB64);
}
private String url(String path) {
return "http://localhost:" + port + path;
}
}
|
package model;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class ConceptLattice {
List<LatticeNode> lattices;
//无参构造,格里面有一个空结点
public ConceptLattice(){
lattices = new LinkedList<>();
}
public List<LatticeNode> getLattices() {
return lattices;
}
public void setLattices(List<LatticeNode> lattice) {
this.lattices = lattice;
}
//向格中添加一个结点,按照|c.intension|升序增加
public void addNode(LatticeNode c){
/*
能否用游标来控制???
*/
if(lattices.size()==0) {
lattices.add(c);
}
else {
int i = 0;
for (; i < lattices.size(); i++)
if (c.getIntension().size() <= lattices.get(i).getIntension().size()) {
lattices.add(i, c);
break;
}
if(i==lattices.size())
lattices.add(c);
}
}
//降序插入
public void addNodeDes(LatticeNode c){
if(lattices.size()==0) {
lattices.add(c);
}
else {
int i = 0;
for (; i < lattices.size(); i++)
if (c.getIntension().size() > lattices.get(i).getIntension().size()) {
lattices.add(i, c);
break;
}
if(i==lattices.size())
lattices.add(c);
}
}
public String toString(){
String s = "";
for(LatticeNode c :this.lattices){
s = s + c.toString();
}
return s;
}
}
|
package src.entity;
public class Placeholder extends Crop {
public Placeholder() {
stage = -1;
waterLevel = 1;
url = "@../../images/emptyBKG.png";
}
}
|
package com.nanyin.config.enums;
public enum ResultCodeEnum {
/**
* illegal token : code : 50008
*/
ILLEGAL_TOKEN(50008,"illegal token"),
/**
* TOKEN_EXPIRED : code : 50014
*/
TOKEN_EXPIRED(50014,"token expired"),
/**
* SUCCESS : code : 20000
*/
SUCCESS(20000,"success"),
/**
* FAIL : code : 10000
*/
FAIL(10000,"fail"),
/**
* NO_PERMISSION: code : 10005
*/
NO_PERMISSION(10005,"no permission"),
/**
* WRONG_USERNAME_OR_PASSWORD : code :10006
*/
WRONG_USERNAME_OR_PASSWORD(10006,"wrong username or password");
private Integer code;
private String message;
ResultCodeEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
|
package com.freddygenicho.sample.mpesa;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.freddy.sample.mpesa.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class login extends AppCompatActivity {
//remove ine case
private FirebaseUser currentUser;
private FirebaseAuth mAUTH;
private ProgressDialog loadingbar;
TextView register,forgotpass,admin;
Button login;
EditText Email,Password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAUTH=FirebaseAuth.getInstance();
//remove ine case
currentUser=mAUTH.getCurrentUser();
// register=(TextView) findViewById(R.id.gotoRegister);
// forgotpass=(TextView) findViewById(R.id.forgotPassword);
Email=(EditText)findViewById(R.id.inputEmail);
Password=(EditText) findViewById(R.id.inputPassword);
loadingbar=new ProgressDialog(this);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(login.this,Registration.class);
startActivity(intent);
}
});
login=(Button) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AllowUserToLogin();
}
});
forgotpass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(login.this, Resetpassword.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.loginoptions,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId()== R.id.foradmin){
Intent intent=new Intent(login.this,AdminLoginActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
private void AllowUserToLogin() {
String email=Email.getText().toString();
String pass=Password.getText().toString();
if (TextUtils.isEmpty(email)){
Email.setError("please enter your email address");
Toast.makeText(this, "please enter your email address", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(pass)){
Password.setError("please enter your password");
Toast.makeText(this, "please enter your password", Toast.LENGTH_SHORT).show();
}
else{
loadingbar.setTitle("Sign in");
loadingbar.setMessage("Please Wait...");
loadingbar.setCanceledOnTouchOutside(true);
loadingbar.show();
mAUTH.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(login.this, "Login Successfull", Toast.LENGTH_SHORT).show();
loadingbar.dismiss();
}
else{
String message=task.getException().toString();
Toast.makeText(login.this, "Error : " + message, Toast.LENGTH_SHORT).show();
loadingbar.dismiss();
}
}
});
}
}
/* @Override
protected void onStart() {
super.onStart();
if (currentUser !=null){
SendUserToMainActivity();
}
}*/
private void SendUserToMainActivity() {
Intent intent=new Intent(login.this, MainActivity2.class);
startActivity(intent);
}
}
|
package com.bsty.base;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.bsty.base.dao")
public class BaseserverApplication {
public static void main(String[] args) {
SpringApplication.run(BaseserverApplication.class, args);
}
}
|
package com.github.banner;
import android.util.SparseArray;
/***
* created by android on 2019/4/11
*/
public class BannerItemManager<T> {
private SparseArray<BannerItem> helperSparseArray=new SparseArray<>();
public void addBannerItem(BannerItem helper){
helperSparseArray.put(helperSparseArray.size(),helper);
}
public boolean hasMultiItem(){
return helperSparseArray!=null&&helperSparseArray.size()>0;
}
public BannerItem getBannerItem(int viewType){
return helperSparseArray.get(viewType);
}
public int getItemViewType(T item,int position,int dataCount){
for (int i = 0; i < helperSparseArray.size(); i++) {
BannerItem bannerItem = helperSparseArray.valueAt(i);
if(bannerItem.isItemType(item,position,dataCount)){
int viewType = helperSparseArray.keyAt(i);
return viewType;
}
}
throw new IllegalStateException("getItemViewType没有找到item布局,BannerItem.isItemType()请按需求返回true");
}
public void bindData(BannerHolder holder, T item, int position, int dataCount){
for (int i = 0; i < helperSparseArray.size(); i++) {
BannerItem bannerItem = helperSparseArray.valueAt(i);
if(bannerItem.isItemType(item,position,dataCount)){
bannerItem.bindData(holder,item,position,dataCount);
return;
}
}
throw new IllegalStateException("bindData没有找到item布局,BannerItem.isItemType()请按需求返回true");
};
}
|
package cn.test.demo05;
public class CFXtest {
public static void main(String[] args) {
CFX cfx = new CFX(2,75);
System.out.println(cfx.getArea());
}
}
|
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
if(gas.length == 0){
return 0;
}
if(gas.length == 1){
return gas[0] >= cost[0] ? 0 : -1;
}
int size = gas.length;
for(int i = 0; i < size; i++){
int sum = 0;
if(gas[i] < cost[i]){
continue;
}
for(int j = 0; j < size; j++){
sum = sum + gas[(i + j) % size] - cost[(i + j) % size];
if(sum < 0){
break;
}
}
if(sum >= 0){
return i;
}
}
return -1;
}
} |
package mb.tianxundai.com.toptoken.bean;
import java.util.List;
/**
* @author txd_dbb
* @emil 15810277571@163.com
* create at 2018/10/1817:05
* description:
*/
public class QuanQiuBean {
/**
* code : 101
* message : 获取成功
* data : {"applyStatus":603,"recordList":[{"waid":1,"userWalletId":null,"userId":1,"date":"2018-10-18","state":604,"comment":"5000TOP"},{"waid":2,"userWalletId":null,"userId":1,"date":"2018-10-18","state":605,"comment":"5000TOP"},{"waid":4,"userWalletId":null,"userId":1,"date":"2018-10-18","state":604,"comment":"5000TOP"},{"waid":5,"userWalletId":null,"userId":1,"date":"2018-10-18","state":605,"comment":"5000TOP"}]}
*/
private int code;
private String message;
private DataBean data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* applyStatus : 603
* recordList : [{"waid":1,"userWalletId":null,"userId":1,"date":"2018-10-18","state":604,"comment":"5000TOP"},{"waid":2,"userWalletId":null,"userId":1,"date":"2018-10-18","state":605,"comment":"5000TOP"},{"waid":4,"userWalletId":null,"userId":1,"date":"2018-10-18","state":604,"comment":"5000TOP"},{"waid":5,"userWalletId":null,"userId":1,"date":"2018-10-18","state":605,"comment":"5000TOP"}]
*/
private int applyStatus;
public boolean isReject() {
return reject;
}
public void setReject(boolean reject) {
this.reject = reject;
}
private boolean reject;
private List<RecordListBean> recordList;
public int getApplyStatus() {
return applyStatus;
}
public void setApplyStatus(int applyStatus) {
this.applyStatus = applyStatus;
}
public List<RecordListBean> getRecordList() {
return recordList;
}
public void setRecordList(List<RecordListBean> recordList) {
this.recordList = recordList;
}
public static class RecordListBean {
/**
* waid : 1
* userWalletId : null
* userId : 1
* date : 2018-10-18
* state : 604
* comment : 5000TOP
*/
private int waid;
private Object userWalletId;
private int userId;
private String date;
private int state;
private String comment;
public int getWaid() {
return waid;
}
public void setWaid(int waid) {
this.waid = waid;
}
public Object getUserWalletId() {
return userWalletId;
}
public void setUserWalletId(Object userWalletId) {
this.userWalletId = userWalletId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
}
}
|
package de.lezleoh.mathgame.game;
import java.util.Set;
import de.lezleoh.mathgame.term.TermInt;
public class TermWithHitPositions {
TermInt term;
Set<Integer> hitPositions;
public TermWithHitPositions(TermInt term, Set<Integer> hitPositions) {
super();
this.term = term;
this.hitPositions = hitPositions;
}
public TermInt getTerm() {
return term;
}
public Set<Integer> getHitPositions() {
return hitPositions;
}
@Override
public String toString() {
return "TermWithHitPositions [term=" + term + ", hitPositions=" + hitPositions + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TermWithHitPositions other = (TermWithHitPositions) obj;
if (hitPositions == null) {
if (other.hitPositions != null)
return false;
} else if (!hitPositions.equals(other.hitPositions))
return false;
if (term == null) {
if (other.term != null)
return false;
} else if (!term.equals(other.term))
return false;
return true;
}
}
|
package misc.StringBuffer;
public class StringBufferExample {
public static void main(String[] args) {
/**
* String object is immutable and StringBuffer/StringBuilder objects are
* mutable.
*/
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // 16; updated by (c+1)*2 where c = 16 initially
sb.append("abcdefghijklmnopqrstuvxyz");
System.out.println(sb.capacity()); // 34 => (16+1) * 2 = 34
sb.append("abcdefghijklmnopqrstuvxyz");
System.out.println(sb.capacity()); // 70 => (34+1) * 2 = 70
StringBuffer sb1 = new StringBuffer(100);
System.out.println(sb1.capacity()); // 100
StringBuffer sb2 = new StringBuffer("Java");
System.out.println("The length of \"" + sb2 + "\" is " + sb2.length()); // 4
System.out.println("The character at index 2 is '" + sb2.charAt(2) + "'"); // 'v'
sb2.append(" tech");
System.out.println(sb2); // Java tech
StringBuffer sb3 = new StringBuffer("java");
sb3.append(" tech");
sb3.append(100); // valid
sb3.append(true); // valid
sb3.append(500.00); // valid
sb3.insert(0, "HIBERNATE"); // insert "HIBERNATE" in sb3 from index 2 onwards
sb3.insert(2, "JDBC"); // insert "JDBC" in sb3 from index 0 onwards
System.out.println(sb3); // HIJDBCBERNATEjava tech100true500.0
sb3.delete(0, 12); // delete characters from index 0 to index 11.
System.out.println(sb3); // Ejava tech100true500.0
// we have a reverse() method in case of the StringBuffer object, not there for
// String object.
sb3.reverse();
System.out.println(sb3); // 0.005eurt001hcet avajE
// We can convert a StringBuffer object to a String object using toString()
// method.
String str = sb3.toString();
System.out.println(str); // 0.005eurt001hcet avajE
StringBuffer sb4 = new StringBuffer();
// we can chain methods like this:
sb4.append("java").append(" tech").append(100).append(true).deleteCharAt(5).insert(12, "JDBC");
System.out.println(sb4); // java ech100tJDBCrue
// Both StringBuilder and StringBuffer classes are used interchangeably because
// both use the same methods
// both of the class' objects are mutable. The only difference between
// StringBuffer and StringBuilder classes
// is that, StringBuffer is Thread Safe and StringBuilder is Thread Unsafe,
// meaning, we can use StringBuffer
// class for multithreading purposes which decreases the performance of
// StringBuffer object, whereas StringBuilder
// class' objects cannot be used for multithreading purposes.
StringBuilder s1 = new StringBuilder();
s1.append("java").append(" tech").append(100).append(true).deleteCharAt(5).insert(12, "JDBC");
System.out.println(s1); // java ech100tJDBCrue
}
} |
package CartelRecordView;
import BookView.BookFindingView;
import BookView.BuyBookView;
import CartelView.CartelRegistrationView;
import ClientView.ClientFindingView;
import EmployeesView.FindEmployeeView;
import LibraryManagementFunctionFactory.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import model.Book;
import model.Cartel;
import model.CartelRecord;
import model.Employee;
import views.HomeView;
import views.PaymentTypeView;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class CartelRecordRegistrationView {
private Employee currentUser;
private Book currentBook;
private Cartel currentCartel;
public CartelRecordRegistrationView(Cartel currentCartel) {
this.currentCartel = currentCartel;
}
public CartelRecordRegistrationView() {
}
public Scene execute(Stage stage) {
GridPane root1 = new GridPane();
root1.setHgap(10);
root1.setVgap(10);
root1.setPadding(new Insets(10, 10, 10, 10));
root1.setAlignment(Pos.TOP_CENTER);
Menu userMenu = new Menu("User Control");
// userMenu.setStyle("-fx-font-weight: bold;");
// Label priceLabel = new Label("Price: ");
// priceLabel.setTextFill(Color.web("white"));
// priceLabel.setStyle("-fx-font-weight: bold;");
// root1.add(quantityLabel, 1, 7);
// root1.add(spinner2,2,7);
// TextField priceField = new TextField();
// root1.add(priceField, 2, 8);
Spinner<Integer> spinner1 = new Spinner<>(1, 3000, 2021);
Spinner<Integer> spinner2 = new Spinner<>(1, 12, 1);
Spinner<Integer> spinner3 = new Spinner<>(1, 31, 1);
Spinner<Integer> spinner4 = new Spinner<>(1, 23, 0);
Spinner<Integer> spinner5 = new Spinner<>(1, 59, 0);
Spinner<Integer> spinner6 = new Spinner<>(1, 2000, 1);
Spinner<Integer> spinner7 = new Spinner<>(1, 2000, 1);
Label yearLabel = new Label("Return Year:");
yearLabel.setTextFill(Color.DEEPSKYBLUE);
yearLabel.setStyle("-fx-font-weight: bold;");
root1.add(yearLabel, 1, 1);
root1.add(spinner1, 2, 1);
Label returnMonthLabel = new Label("Return Month:");
returnMonthLabel.setTextFill(Color.DEEPSKYBLUE);
returnMonthLabel.setStyle("-fx-font-weight: bold;");
root1.add(returnMonthLabel, 1, 2);
root1.add(spinner2, 2, 2);
Label returnDayLabel = new Label("Return Day:");
returnDayLabel.setTextFill(Color.DEEPSKYBLUE);
returnDayLabel.setStyle("-fx-font-weight: bold;");
root1.add(returnDayLabel, 1, 3);
root1.add(spinner3, 2, 3);
Label returnHourLabel = new Label("Hour:");
returnHourLabel.setTextFill(Color.DEEPSKYBLUE);
returnHourLabel.setStyle("-fx-font-weight: bold;");
root1.add(returnHourLabel, 1, 4);
root1.add(spinner4, 2, 4);
Label returnMinuteLabel = new Label("Minute:");
returnMinuteLabel.setTextFill(Color.DEEPSKYBLUE);
returnMinuteLabel.setStyle("-fx-font-weight: bold;");
root1.add(returnMinuteLabel, 1, 5);
root1.add(spinner5, 2, 5);
Label bookIDLabel = new Label("Book ID: ");
bookIDLabel.setTextFill(Color.DEEPSKYBLUE);
bookIDLabel.setStyle("-fx-font-weight: bold;");
root1.add(bookIDLabel, 1, 6);
root1.add(spinner6, 2, 6);
Label clientID=new Label("Cartel ID (ID of Last Cartel): ");
clientID.setTextFill(Color.DEEPSKYBLUE);
clientID.setStyle("-fx-font-weight: bold;");
root1.add(clientID,1,7);
root1.add(spinner7,2,7);
Label createdOnLabel = new Label("Created On (Auto Calc Now): ");
createdOnLabel.setTextFill(Color.DEEPSKYBLUE);
createdOnLabel.setStyle("-fx-font-weight: bold;");
TextField createdOnField = new TextField();
root1.add(createdOnLabel, 1, 8);
root1.add(createdOnField, 2, 8);
Button createCartelButton = new Button("-Cartel Record Registration-");
createCartelButton.setStyle("-fx-font-weight: bold;"); //letters are written in bold type
createCartelButton.setTextFill(Color.DEEPSKYBLUE); //Letters of findButton is LIGHTBLUE
createCartelButton.setId("createCartelButton-button");
createCartelButton.setStyle("-fx-background-color:#000000;"); //Background is Black
HBox h1 = new HBox(); //Declare h box
h1.getChildren().add(createCartelButton); //Adding button inside the hBox
root1.add(createCartelButton, 2, 9);
createCartelButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
//String description = descriptionArea.getText();
// boolean isRememberMe = remember.isSelected();
CartelFactory cartelFactory = new CartelFactory();
CartelRecordFactory cartelRecordFactory = new CartelRecordFactory();
ClientFactory clientFactory = new ClientFactory();
BookFactory bookFactory = new BookFactory();
EmployeeFactory employeeFactory = new EmployeeFactory();
CartelRecord cartelRecord = new CartelRecord();
LocalDateTime dataStarted = LocalDateTime.now();
cartelRecord.setDataStarted(dataStarted);
Integer returnYear = spinner1.getValue();
Integer returnMonth = spinner2.getValue();
Integer returnDay = spinner3.getValue();
Integer returnHour = spinner4.getValue();
Integer returnMinute = spinner5.getValue();
cartelRecord.setEndData(LocalDateTime.of(returnYear, returnMonth, returnDay, returnHour, returnMinute));
Integer bookID = spinner6.getValue();
cartelRecord.setBook(bookFactory.findBookByID(bookID));
Integer cartelID = spinner7.getValue();
cartelRecord.setCartel(cartelFactory.findCartelsByID(cartelID));
// cartelRecord.setCartel(currentCartel);
//
// cartelRecord.setBook(currentBook);
LocalDateTime createdOn = LocalDateTime.now();
cartelRecord.setCreatedOn(createdOn);
cartelRecordFactory.createCartelRecord(cartelRecord);
if (currentBook == null && currentCartel == null) {
Alert errorAlert = new Alert(Alert.AlertType.ERROR);
errorAlert.setHeaderText("There was an error");
errorAlert.setContentText("Register Book With It's ID At Buy Book Section! " + "\n"
+ "Register Cartel At Cartel Registration Section! ");
errorAlert.showAndWait();
} else {
//Employee currentEmployee=new Employee();
Alert successAlert = new Alert(Alert.AlertType.CONFIRMATION);
successAlert.setHeaderText("The Cartel Record was registered successfully");
successAlert.showAndWait();
stage.setScene(new HomeView(currentUser).execute(stage));
successAlert.close();
}
}
});
BorderPane mainPane = new BorderPane();
MenuBar menuBar = new MenuBar();
Label backLabel = new Label("Back");
backLabel.setStyle("-fx-font-weight: bold;");
Menu back = new Menu("", backLabel);
backLabel.setOnMouseClicked(e -> {
CartelRegistrationView cartelRegistrationView = new CartelRegistrationView(currentBook);
stage.setScene(cartelRegistrationView.execute(stage));
});
menuBar.getMenus().add(back);
mainPane.setTop(menuBar);
Label buyBookView1 = new Label("Buy Book View");
// buyBookView1.setStyle("-fx-font-weight: bold;");
Menu buyBook = new Menu("", buyBookView1);
buyBookView1.setOnMouseClicked(e -> {
BuyBookView buyBookView = new BuyBookView(currentUser);
stage.setScene(buyBookView.execute(stage));
});
menuBar.getMenus().add(buyBook);
mainPane.setTop(menuBar);
Label homeViewLabel = new Label("Home View");
// homeViewLabel.setStyle("-fx-font-weight: bold;");
Menu homeview = new Menu("", homeViewLabel);
homeViewLabel.setOnMouseClicked(e -> {
HomeView homeView = new HomeView(currentUser);
stage.setScene(homeView.execute(stage));
});
menuBar.getMenus().add(homeview);
mainPane.setTop(menuBar);
Label findBookByIDLabel = new Label("Find Book ID");
// findEmployeeViewLabel.setStyle("-fx-font-weight: bold;");
Menu findBookID = new Menu("", findBookByIDLabel);
findBookByIDLabel.setOnMouseClicked(e -> {
BookFindingView findBookView = new BookFindingView(currentBook);
stage.setScene(findBookView.execute(stage));
});
menuBar.getMenus().add(findBookID);
mainPane.setTop(menuBar);
MenuItem getAllCartels = new MenuItem("-Get All Cartel Info-");
getAllCartels.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
CartelFactory cartelFactory = new CartelFactory();
Alert successAlert = new Alert(Alert.AlertType.CONFIRMATION);
successAlert.setHeaderText("All Cartels Information");
successAlert.setContentText(cartelFactory.findAllCartels());
successAlert.showAndWait();
System.out.println("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_--_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-");
}
});
userMenu.getItems().addAll(getAllCartels);
mainPane.setTop(menuBar);
menuBar.getMenus().add(userMenu);
mainPane.setTop(menuBar);
//
// Label findClientViewLabel=new Label("Find Client ID");
// findClientViewLabel.setStyle("-fx-font-weight: bold;");
// Menu findClientID=new Menu("", findClientViewLabel);
// findClientViewLabel.setOnMouseClicked(e->{
// FindClient findEmployeeView1= new FindEmployeeView(currentUser);
// stage.setScene(findEmployeeView1.execute(stage));
// });
//
// menuBar.getMenus().add(findClientID);
// mainPane.setTop(menuBar);
root1.setStyle("-fx-background-image: url('img_17.png')");
mainPane.setCenter(root1);
Scene scene = new Scene(mainPane, 960, 350);
scene.getStylesheets().add("style.css");
stage.setScene(scene);
stage.setTitle("Register Cartel Records");
stage.show();
return scene;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.jdbc;
import org.junit.jupiter.api.Test;
import org.mockito.BDDMockito;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationConfigurationException;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.jdbc.SqlConfig.TransactionMode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Unit tests for {@link SqlScriptsTestExecutionListener}.
*
* @author Sam Brannen
* @since 4.1
*/
class SqlScriptsTestExecutionListenerTests {
private final SqlScriptsTestExecutionListener listener = new SqlScriptsTestExecutionListener();
private final TestContext testContext = mock();
@Test
void missingValueAndScriptsAndStatementsAtClassLevel() throws Exception {
Class<?> clazz = MissingValueAndScriptsAndStatementsAtClassLevel.class;
BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("foo"));
assertExceptionContains(clazz.getSimpleName() + ".sql");
}
@Test
void missingValueAndScriptsAndStatementsAtMethodLevel() throws Exception {
Class<?> clazz = MissingValueAndScriptsAndStatementsAtMethodLevel.class;
BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("foo"));
assertExceptionContains(clazz.getSimpleName() + ".foo" + ".sql");
}
@Test
void valueAndScriptsDeclared() throws Exception {
Class<?> clazz = ValueAndScriptsDeclared.class;
BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("foo"));
assertThatExceptionOfType(AnnotationConfigurationException.class).isThrownBy(() ->
listener.beforeTestMethod(testContext))
.withMessageContaining("Different @AliasFor mirror values")
.withMessageContaining("attribute 'scripts' and its alias 'value'")
.withMessageContaining("values of [{bar}] and [{foo}]");
}
@Test
void isolatedTxModeDeclaredWithoutTxMgr() throws Exception {
ApplicationContext ctx = mock();
given(ctx.getResource(anyString())).willReturn(mock());
given(ctx.getAutowireCapableBeanFactory()).willReturn(mock());
Class<?> clazz = IsolatedWithoutTxMgr.class;
BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("foo"));
given(testContext.getApplicationContext()).willReturn(ctx);
assertExceptionContains("cannot execute SQL scripts using Transaction Mode [ISOLATED] without a PlatformTransactionManager");
}
@Test
void missingDataSourceAndTxMgr() throws Exception {
ApplicationContext ctx = mock();
given(ctx.getResource(anyString())).willReturn(mock());
given(ctx.getAutowireCapableBeanFactory()).willReturn(mock());
Class<?> clazz = MissingDataSourceAndTxMgr.class;
BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("foo"));
given(testContext.getApplicationContext()).willReturn(ctx);
assertExceptionContains("supply at least a DataSource or PlatformTransactionManager");
}
private void assertExceptionContains(String msg) throws Exception {
assertThatIllegalStateException().isThrownBy(() ->
listener.beforeTestMethod(testContext))
.withMessageContaining(msg);
}
// -------------------------------------------------------------------------
@Sql
static class MissingValueAndScriptsAndStatementsAtClassLevel {
public void foo() {
}
}
static class MissingValueAndScriptsAndStatementsAtMethodLevel {
@Sql
public void foo() {
}
}
static class ValueAndScriptsDeclared {
@Sql(value = "foo", scripts = "bar")
public void foo() {
}
}
static class IsolatedWithoutTxMgr {
@Sql(scripts = "foo.sql", config = @SqlConfig(transactionMode = TransactionMode.ISOLATED))
public void foo() {
}
}
static class MissingDataSourceAndTxMgr {
@Sql("foo.sql")
public void foo() {
}
}
}
|
package entities;
import graphics.Sprite;
public class Portal extends Item {
public Portal(double x, double y, Sprite sprite, String ability) {
super(x, y, sprite, ability);
}
@Override
public void update() {
}
}
|
package com.nsi.clonebin.service;
import com.nsi.clonebin.model.dto.CreateOrEditPasteDTO;
import com.nsi.clonebin.model.dto.MyClonebinPasteDTO;
import com.nsi.clonebin.model.entity.Folder;
import com.nsi.clonebin.model.entity.Paste;
import com.nsi.clonebin.model.entity.UserAccount;
import com.nsi.clonebin.repository.PasteRepository;
import com.nsi.clonebin.security.CurrentUserService;
import com.nsi.clonebin.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
public class PasteService {
private final PasteRepository pasteRepository;
private final CurrentUserService currentUserService;
private final FolderService folderService;
@Autowired
public PasteService(PasteRepository pasteRepository, CurrentUserService currentUserService,
FolderService folderService) {
this.pasteRepository = pasteRepository;
this.currentUserService = currentUserService;
this.folderService = folderService;
}
@Transactional(readOnly = true)
public Paste getById(UUID id) {
return pasteRepository.getOne(id);
}
@Transactional(readOnly = true)
public List<MyClonebinPasteDTO> getByUserId(UUID userId) {
List<Paste> pastes = pasteRepository.findAllByUserId(userId);
if (CollectionUtils.isEmpty(pastes)) {
return new ArrayList<>();
}
return pastes.stream().map(MyClonebinPasteDTO::new).collect(Collectors.toList());
}
public List<MyClonebinPasteDTO> getByFolderId(UUID folderId) {
List<Paste> pastes = pasteRepository.findAllByFolderId(folderId);
if (CollectionUtils.isEmpty(pastes)) {
return new ArrayList<>();
}
return pastes.stream().map(MyClonebinPasteDTO::new).collect(Collectors.toList());
}
@Transactional
public Paste save(CreateOrEditPasteDTO createOrEditPasteDTO) {
return createOrEditPasteDTO.getId() == null ? createPaste(createOrEditPasteDTO) : updatePaste(createOrEditPasteDTO);
}
@Transactional
public void delete(UUID id) {
Paste paste = pasteRepository.getOne(id);
UserAccount currentUser = currentUserService.getCurrentUser();
if (currentUser == null) {
//TODO: throw forbidden exception
throw new RuntimeException();
} else if (!paste.getUserId().equals(currentUser.getId())) {
throw new RuntimeException();
}
pasteRepository.delete(paste);
}
private Paste createPaste(CreateOrEditPasteDTO pasteDTO) {
UserAccount currentUser = currentUserService.getCurrentUser();
Paste paste = new Paste();
paste.setUserId(currentUser.getId());
if (StringUtils.hasText(pasteDTO.getTitle())) {
paste.setTitle(pasteDTO.getTitle());
} else {
paste.setTitle("Untitled");
}
paste.setContent(pasteDTO.getContent());
paste.setFolderId(pasteDTO.getFolderId());
paste.setCreatedAt(LocalDateTime.now());
paste.setExpiresAt(DateTimeUtil.calucateExpiresAt(pasteDTO.getExpiringEnum()));
if (StringUtils.hasText(pasteDTO.getNewFolderName())) {
Folder folder = folderService.save(pasteDTO.getNewFolderName());
paste.setFolderId(folder.getId());
}
return pasteRepository.save(paste);
}
private Paste updatePaste(CreateOrEditPasteDTO pasteDTO) {
Optional<Paste> pasteOptional = pasteRepository.findById(pasteDTO.getId());
if (pasteOptional.isPresent()) {
Paste paste = pasteOptional.get();
paste.setContent(pasteDTO.getContent());
if (StringUtils.hasText(pasteDTO.getTitle())) {
paste.setTitle(pasteDTO.getTitle());
} else {
paste.setTitle("Untitled");
}
paste.setFolderId(pasteDTO.getFolderId());
if (pasteDTO.isChangeExpiresAt()) {
paste.setExpiresAt(DateTimeUtil.calucateExpiresAt(pasteDTO.getExpiringEnum()));
}
if (StringUtils.hasText(pasteDTO.getNewFolderName())) {
Folder folder = folderService.save(pasteDTO.getNewFolderName());
paste.setFolderId(folder.getId());
}
return pasteRepository.save(paste);
} else {
return createPaste(pasteDTO);
}
}
}
|
package com.esum.ebms.v2.msh;
import com.esum.ebms.v2.ProcessorException;
/**
* MSH Process를 처리할 때 발생하는 Exception을 다루는 클래스
*
* Copyright(c) eSum Technologies, Inc. All rights reserved.
*/
public class MSHException extends ProcessorException {
/** HttpMessageSender 인스턴스를 생성하는 중에 발생하는 에러 */
public static final String ERROR_HTTP_MESSAGE_SENDER_INSTANCE = "MSH080";
/** 정의되지 않은 메시지 형식을 수신한 경우 발생하는 에러 */
public static final String EERROR_NOT_DEFINED_MESSAGE_TYPE = "MSH081";
/** HTTP 응답 상태 값이 200(OK), 204(NO CONTENT)이 아닌 다른 값을 수신하는 경우 발생하는 에러 */
public static final String EERROR_HTTP_RESPONSE = "MSH082";
/** 파트너 MSH URL 값에 오류가 있는 경우 발생하는 에러 */
public static final String EERROR_HTTP_URL = "MSH083";
/** HTTP를 통한 메시지 송신 중에 오류가 발생하는 경우 발생하는 에러 */
public static final String EERROR_HTTP_CLIENT = "MSH084";
/** HTTP를 통한 메시지 송신 후 Acknowledgment을 수신하지 못하는 경우 발생하는 에러 */
public static final String EERROR_RETRY_TIMEOUT = "MSH085";
/** 수신 받은 HTTP Response로 부터 Body를 추출하는 중에 오류가 발생하는 경우 발생하는 에러 */
public static final String EERROR_HTTP_RESPONE_BODY = "MSH086";
public MSHException(String code, String location, Throwable exception) {
super(code, location, exception);
}
}
|
/*
Copyright (c) 2016 Eron Gjoni
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package math.doubleV;
import asj.CanLoad;
import asj.data.JSONObject;
import math.floatV.SGVec_3f;
import math.floatV.Vec3f;
/**
* @author Eron Gjoni
*
*/
public class sgRayd implements CanLoad {
public static final int X=0, Y=1, Z=2;
protected Vec3d<?> p1;
protected Vec3d<?> p2;
public sgRayd() {
workingVector = new SGVec_3d();
//this.p1 = new SGVec_3d();
}
public sgRayd(Vec3d<?> origin) {
this.workingVector = origin.copy();
this.p1 = origin.copy();
}
public sgRayd(Vec3d<?> p1, Vec3d<?> p2) {
this.workingVector = p1.copy();
this.p1 = p1.copy();
if(p2 != null)
this.p2 = p2.copy();
}
public <V extends Vec3d<?>> double distTo(V point) {
Vec3d<?> inPoint = point.copy();
inPoint.sub(this.p1);
Vec3d<?> heading = this.heading();
double scale = (inPoint.dot(heading)/(heading.mag()*inPoint.mag()))*(inPoint.mag()/heading.mag());
return point.dist(this.getRayScaledBy(scale).p2);
}
/**
* returns the distance between the input point and the point on this ray (treated as a lineSegment) to which the input is closest.
* @param point
* @return
*/
public <V extends Vec3d<?>> double distToStrict(V point) {
Vec3d<?> inPoint = point.copy();
inPoint.sub(this.p1);
Vec3d<?> heading = this.heading();
double scale = (inPoint.dot(heading)/(heading.mag()*inPoint.mag()))*(inPoint.mag()/heading.mag());
if(scale < 0) {
return point.dist(this.p1);
} else if (scale > 1) {
return point.dist(this.p2);
} else {
return point.dist(this.getRayScaledBy(scale).p2);
}
}
/**
* returns the distance between this ray treated as a line and the input ray treated as a line.
* @param r
* @return
*/
public double distTo(sgRayd r) {
Vec3d<?> closestOnThis = this.closestPointToRay3D(r);
return r.distTo(closestOnThis);
}
/**
* returns the distance between this ray as a line segment, and the input ray treated as a line segment
*/
public double distToStrict(sgRayd r) {
Vec3d<?> closestOnThis = this.closestPointToSegment3D(r);
return closestOnThis.dist(r.closestPointToStrict(closestOnThis));
}
/**
* returns the point on this sgRay which is closest to the input point
* @param point
* @return
*/
public <V extends Vec3d<?>> V closestPointTo(V point) {
workingVector.set(point);
workingVector.sub(this.p1);
Vec3d<?> heading = this.heading();
heading.mag();
workingVector.mag();
//workingVector.normalize();
heading.normalize();
double scale = workingVector.dot(heading);
return (V) this.getScaledTo(scale);
}
public <V extends Vec3d<?>> Vec3d<?> closestPointToStrict(V point) {
V inPoint = (V) point.copy();
inPoint.sub(this.p1);
V heading = (V) this.heading();
double scale = (inPoint.dot(heading)/(heading.mag()*inPoint.mag()))*(inPoint.mag()/heading.mag());
if(scale <= 0)
return this.p1;
else if (scale >= 1)
return this.p2;
else
return this.getMultipledBy(scale);
}
public Vec3d<?> heading(){
if(this.p2 == null) {
if(p1 == null) p1 = new SGVec_3d();
p2 = p1.copy();
p2.set(0d,0d,0d);
return p2;
}
else {
workingVector.set(p2);
return workingVector.subCopy(p1);
}
}
/**
* manually sets the raw variables of this
* ray to be equivalent to the raw variables of the
* target ray. Such that the two rays align without
* creating a new variable.
* @param target
*/
public void alignTo(sgRayd target) {
p1.set(target.p1);
p2.set(target.p2);
}
public void heading(double[] newHead){
if(p2 == null) p2 = p1.copy();
p2.set(newHead);
p2.set(p1);
}
public <V extends Vec3d<?>> void heading(V newHead){
if(p2 == null) p2 = p1.copy();
p2.set(p1);
p2.add(newHead);
}
public void heading(SGVec_3f newHead){
if(p2 == null) p2 = p1.copy();
p2.set(p1);
p2.add(newHead);
}
/**
* sets the input vector equal to this sgRay's heading.
* @param setTo
*/
public void getHeading(SGVec_3d setTo){
setTo.set(p2);
setTo.sub(this.p1);
}
/**
* @return a copy of this ray with its z-component set to 0;
*/
public sgRayd get2DCopy() {
return this.get2DCopy(sgRayd.Z);
}
/**
* gets a copy of this ray, with the component specified by
* collapseOnAxis set to 0.
* @param collapseOnAxis the axis on which to collapse the ray.
* @return
*/
public sgRayd get2DCopy(int collapseOnAxis) {
sgRayd result = this.copy();
if(collapseOnAxis == sgRayd.X) {
result.p1.setX_(0);
result.p2.setX_(0);
}
if(collapseOnAxis == sgRayd.Y) {
result.p1.setY_(0);
result.p2.setY_(0);
}
if(collapseOnAxis == sgRayd.Z) {
result.p1.setZ_(0);
result.p2.setZ_(0);
}
return result;
}
public Vec3d<?> origin(){
return p1.copy();
}
public double mag() {
workingVector.set(p2);
return (workingVector.sub(p1)).mag();
}
public void mag(double newMag) {
workingVector.set(p2);
Vec3d<?> dir = workingVector.sub(p1);
dir.setMag(newMag);
this.heading(dir);
}
/**
* Returns the scalar projection of the input vector on this
* ray. In other words, if this ray goes from (5, 0) to (10, 0),
* and the input vector is (7.5, 7), this function
* would output 0.5. Because that is amount the ray would need
* to be scaled by so that its tip is where the vector would project onto
* this ray.
*
* Due to floating point errors, the intended properties of this function might
* not be entirely consistent with its output under summation.
*
* To help spare programmer cognitive cycles debugging in such circumstances, the intended properties
* are listed for reference here (despite their being easily inferred).
*
* 1. calling scaledProjection(someVector) should return the same value as calling
* scaledProjection(closestPointTo(someVector).
* 2. calling getMultipliedBy(scaledProjection(someVector)) should return the same
* vector as calling closestPointTo(someVector)
*
*
* @param input a vector to project onto this ray
*/
public double scaledProjection(SGVec_3d input) {
workingVector.set(input);
workingVector.sub(this.p1);
Vec3d<?> heading = this.heading();
double headingMag = heading.mag();
double workingVectorMag = workingVector.mag();
if(workingVectorMag == 0 || headingMag == 0)
return 0;
else
return (workingVector.dot(heading)/(headingMag*workingVectorMag))*(workingVectorMag/headingMag);
}
protected Vec3d<?> workingVector;
/**
* divides the ray by the amount specified by divisor, such that the
* base of the ray remains where it is, and the tip
* is scaled accordinly.
* @param divisor
*/
public void div(double divisor) {
p2.sub(p1);
p2.div(divisor);
p2.add(p1);
}
/**
* multiples the ray by the amount specified by scalar, such that the
* base of the ray remains where it is, and the tip
* is scaled accordinly.
* @param divisor
*/
public void mult(double scalar) {
p2.sub(p1);
p2.mult(scalar);
p2.add(p1);
}
/**
* Returns a SGVec_3d representing where the tip
* of this ray would be if mult() was called on the ray
* with scalar as the parameter.
* @param scalar
* @return
*/
public Vec3d<?> getMultipledBy(double scalar) {
Vec3d<?> result = this.heading();
result.mult(scalar);
result.add(p1);
return result;
}
/**
* Returns a SGVec_3d representing where the tip
* of this ray would be if div() was called on the ray
* with scalar as the parameter.
* @param scalar
* @return
*/
public Vec3d<?> getDivideddBy(double divisor) {
Vec3d<?> result = this.heading().copy();
result.mult(divisor);
result.add(p1);
return result;
}
/**
* Returns a SGVec_3d representing where the tip
* of this ray would be if mag(scale) was called on the ray
* with scalar as the parameter.
* @param scalar
* @return
*/
public Vec3d<?> getScaledTo(double scale) {
Vec3d<?> result = this.heading().copy();
result.normalize();
result.mult(scale);
result.add(p1);
return result;
}
/**
* adds the specified length to the ray in both directions.
*/
public void elongate(float amt) {
Vec3d midPoint = p1.addCopy(p2).multCopy(0.5d);
Vec3d p1Heading = p1.subCopy(midPoint);
Vec3d p2Heading = p2.subCopy(midPoint);
Vec3d p1Add = (Vec3d) p1Heading.copy().normalize().mult(amt);
Vec3d p2Add = (Vec3d) p2Heading.copy().normalize().mult(amt);
this.p1.set((Vec3d)p1Heading.addCopy(p1Add).addCopy(midPoint));
this.p2.set((Vec3d)p2Heading.addCopy(p2Add).addCopy(midPoint));
}
public sgRayd copy() {
return new sgRayd(this.p1, this.p2);
}
public void reverse() {
Vec3d<?> temp = this.p1;
this.p1 = this.p2;
this.p2 = temp;
}
public sgRayd getReversed() {
return new sgRayd(this.p2, this.p1);
}
public sgRayd getRayScaledTo(double scalar) {
return new sgRayd(p1, this.getScaledTo(scalar));
}
/*
* reverses this ray's direction so that it
* has a positive dot product with the heading of r
* if dot product is already positive, does nothing.
*/
public void pointWith(sgRayd r) {
if(this.heading().dot(r.heading()) < 0) this.reverse();
}
public void pointWith(SGVec_3d heading) {
if(this.heading().dot(heading) < 0) this.reverse();
}
public sgRayd getRayScaledBy(double scalar) {
return new sgRayd(p1, this.getMultipledBy(scalar));
}
/**
* sets the values of the given vector to where the
* tip of this Ray would be if the ray were inverted
* @param vec
* @return the vector that was passed in after modification (for chaining)
*/
public Vec3d<?> setToInvertedTip(Vec3d<?> vec) {
vec.x = (p1.x - p2.x)+p1.x;
vec.y = (p1.y - p2.y)+p1.y;
vec.z = (p1.z - p2.z)+p1.z;
return vec;
}
public void contractTo(double percent) {
//contracts both ends of a ray toward its center such that the total length of the ray
//is the percent % of its current length;
double halfPercent = 1-((1-percent)/2f);
p1 = p1.lerp(p2, halfPercent);//)new SGVec_3d(p1Tempx, p1Tempy, p1Tempz);
p2 = p2.lerp(p1, halfPercent);//new SGVec_3d(p2Tempx, p2Tempy, p2Tempz);
}
public void translateTo(SGVec_3d newLocation) {
workingVector.set(p2);
workingVector.sub(p1);
workingVector.add(newLocation);
p2.set(workingVector);
p1.set(newLocation);
}
public void translateTipTo(SGVec_3d newLocation) {
workingVector.set(newLocation);
Vec3d<?> transBy = workingVector.sub(p2);
this.translateBy(transBy);
}
public <V extends Vec3d<?>> void translateBy(V toAdd) {
p1.add(toAdd);
p2.add(toAdd);
}
public void normalize() {
this.mag(1);
}
public Vec3d<?> intercepts2D (sgRayd r) {
Vec3d<?> result = p1.copy();
double p0_x = this.p1.x;
double p0_y = this.p1.y;
double p1_x = this.p2.x;
double p1_y = this.p2.y;
double p2_x = r.p1.x;
double p2_y = r.p1.y;
double p3_x = r.p2.x;
double p3_y = r.p2.y;
double s1_x, s1_y, s2_x, s2_y;
s1_x = p1_x - p0_x; s1_y = p1_y - p0_y;
s2_x = p3_x - p2_x; s2_y = p3_y - p2_y;
double t;
t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);
//if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
// Collision detected
return result.set(p0_x + (t * s1_x), p0_y + (t * s1_y), 0d);
// }
//return null; // No collision
}
/*public Vec3d<?> intercepts2D(sgRay r) {
SGVec_3d result = new SGVec_3d();
double a1 = p2.y - p1.y;
double b1 = p1.x - p2.x;
double c1 = a1*p1.x + b1*p1.y;
double a2 = r.p2.y - r.p1.y;
double b2 = r.p1.x - r.p2.y;
double c2 = a2* + b2* r.p1.y;
double det = a1*b2 - a2*b1;
if(det == 0){
// Lines are parallel
return null;
}
else {
result.x = (b2*c1 - b1*c2)/det;
result.y = (a1*c2 - a2*c1)/det;
}
return result;
}*/
/**
* If the closest point to this sgRay on the input sgRay lies
* beyond the bounds of that input sgRay, this returns closest point
* to the input Rays bound;
* @param r
* @return
*/
public Vec3d<?> closestPointToSegment3D(sgRayd r) {
Vec3d<?> closestToThis = r.closestPointToRay3DStrict(this);
return this.closestPointTo(closestToThis);
}
/*public Vec3d<?> closestPointToSegment3DStrict(sgRay r) {
}*/
/**
* returns the point on this ray which is closest to the input ray
* @param r
* @return
*/
public Vec3d<?> closestPointToRay3D(sgRayd r) {
Vec3d<?> result = null;
workingVector.set(p2);
Vec3d<?> u = workingVector.sub(this.p1);
workingVector.set(r.p2);
Vec3d<?> v = workingVector.sub(r.p1);
workingVector.set(this.p1);
Vec3d<?> w = workingVector.sub(r.p1);
double a = u.dot(u); // always >= 0
double b = u.dot(v);
double c = v.dot(v); // always >= 0
double d = u.dot(w);
double e = v.dot(w);
double D = a*c - b*b; // always >= 0
double sc; //tc
// compute the line parameters of the two closest points
if (D < Double.MIN_VALUE) { // the lines are almost parallel
sc = 0.0;
//tc = (b>c ? d/b : e/c); // use the largest denominator
}
else {
sc = (b*e - c*d) / D;
//tc = (a*e - b*d) / D;
}
result = this.getRayScaledBy(sc).p2;
return result;
}
public Vec3d<?> closestPointToRay3DStrict(sgRayd r) {
Vec3d<?> result = null;
workingVector.set(p2);
Vec3d<?> u = workingVector.sub(this.p1);
workingVector.set(r.p2);
Vec3d<?> v = workingVector.sub(r.p1);
workingVector.set(this.p1);
Vec3d<?> w = workingVector.sub(r.p1);
double a = u.dot(u); // always >= 0
double b = u.dot(v);
double c = v.dot(v); // always >= 0
double d = u.dot(w);
double e = v.dot(w);
double D = a*c - b*b; // always >= 0
double sc; //tc
// compute the line parameters of the two closest points
if (D < Double.MIN_VALUE) { // the lines are almost parallel
sc = 0.0;
//tc = (b>c ? d/b : e/c); // use the largest denominator
}
else {
sc = (b*e - c*d) / D;
//tc = (a*e - b*d) / D;
}
if(sc < 0 ) result = this.p1;
else if (sc > 1) result = this.p2;
else result = this.getRayScaledBy(sc).p2;
return result;
}
/**
* returns the point on this ray which is closest to
* the input sgRay. If that point lies outside of the bounds
* of this ray, returns null.
* @param r
* @return
*/
public Vec3d<?> closestPointToRay3DBounded(sgRayd r) {
Vec3d<?> result = null;
workingVector.set(p2);
Vec3d<?> u = workingVector.sub(this.p1);
workingVector.set(r.p2);
Vec3d<?> v = workingVector.sub(r.p1);
workingVector.set(this.p1);
Vec3d<?> w = workingVector.sub(r.p1);
double a = u.dot(u); // always >= 0
double b = u.dot(v);
double c = v.dot(v); // always >= 0
double d = u.dot(w);
double e = v.dot(w);
double D = a*c - b*b; // always >= 0
double sc; //tc
// compute the line parameters of the two closest points
if (D < Double.MIN_VALUE) { // the lines are almost parallel
sc = 0.0;
//tc = (b>c ? d/b : e/c); // use the largest denominator
}
else {
sc = (b*e - c*d) / D;
//tc = (a*e - b*d) / D;
}
if(sc < 0 ) result = null;
else if (sc > 1) result = null;
else result = this.getRayScaledBy(sc).p2;
return result;
}
//returns a ray perpendicular to this ray on the XY plane;
public sgRayd getPerpendicular2D() {
Vec3d<?> heading = this.heading();
workingVector.set(heading.x-1d, heading.x, 0d);
return new sgRayd(this.p1, workingVector.add(this.p1));
}
public Vec3d<?> intercepts2DStrict(sgRayd r) {
//will also return null if the intersection does not occur on the
//line segment specified by the ray.
Vec3d<?> result = p1.copy();
//boolean over = false;
double a1 = p2.y - p1.y;
double b1 = p1.x - p2.x;
double c1 = a1*p1.x + b1*p1.y;
double a2 = r.p2.y - r.p1.y;
double b2 = r.p1.x - r.p2.y;
double c2 = a2* + b2* r.p1.y;
double det = a1*b2 - a2*b1;
if(det == 0){
// Lines are parallel
return null;
}
else {
result.setX_((b2*c1 - b1*c2)/det);
result.setY_((a1*c2 - a2*c1)/det);
}
double position = result.dot(this.heading());
if (position > 1 || position < 0) return null;
return result;
}
/**
* Given two planes specified by a1,a2,a3 and b1,b2,b3 returns a
* ray representing the line along which the two planes intersect
*
* @param a1 the first vertex of a triangle on the first plane
* @param a2 the second vertex of a triangle on the first plane
* @param a3 the third vertex od a triangle on the first plane
* @param b1 the first vertex of a triangle on the second plane
* @param b2 the second vertex of a triangle on the second plane
* @param b3 the third vertex od a triangle on the second plane
* @return a sgRay along the line of intersection of these two planes, or null if inputs are coplanar
*/
public static <V extends Vec3d<?>> sgRayd planePlaneIntersect(V a1, V a2, V a3, V b1, V b2, V b3) {
sgRayd a1a2 = new sgRayd(a1,a2);
sgRayd a1a3 = new sgRayd(a1,a3);
sgRayd a2a3 = new sgRayd(a2,a3);
Vec3d<?> interceptsa1a2 = a1a2.intersectsPlane(b1, b2, b3);
Vec3d<?> interceptsa1a3 = a1a3.intersectsPlane(b1, b2, b3);
Vec3d<?> interceptsa2a3 = a2a3.intersectsPlane(b1, b2, b3);
Vec3d<?>[] notNullCandidates = {interceptsa1a2, interceptsa1a3, interceptsa2a3};
Vec3d<?> notNull1 = null;
Vec3d<?> notNull2 = null;
for(int i=0; i<notNullCandidates.length; i++) {
if(notNullCandidates[i] != null) {
if(notNull1 == null)
notNull1 = notNullCandidates[i];
else {
notNull2 = notNullCandidates[i];
break;
}
}
}
if(notNull1 != null && notNull2 != null)
return new sgRayd(notNull1, notNull2);
else
return null;
}
/**
* @param ta the first vertex of a triangle on the plane
* @param tb the second vertex of a triangle on the plane
* @param tc the third vertex of a triangle on the plane
* @return the point where this ray intersects the plane specified by the triangle ta,tb,tc.
*/
public <V extends Vec3d<?>> Vec3d<?> intersectsPlane(V ta, V tb, V tc) {
double[] uvw = new double[3];
return intersectsPlane(ta, tb, tc, uvw);
}
Vec3d<?> tta, ttb, ttc;
public <V extends Vec3d<?>> Vec3d<?> intersectsPlane(V ta, V tb, V tc, double[] uvw) {
if(tta == null) {
tta = ta.copy(); ttb = tb.copy(); ttc = tc.copy();
} else {
tta.set(ta); ttb.set(tb); ttc.set(tc);
}
tta.sub(p1);
ttb.sub(p1);
ttc.sub(p1);
Vec3d<?> result = (V) planeIntersectTest(tta, ttb, ttc, uvw).copy();
return result.add(this.p1);
}
/**
* @param ta the first vertex of a triangle on the plane
* @param tb the second vertex of a triangle on the plane
* @param tc the third vertex of a triangle on the plane
* @param result the variable in which to hold the result
*/
public void intersectsPlane(Vec3d<?> ta, Vec3d<?> tb, Vec3d<?> tc, Vec3d<?> result) {
double[] uvw = new double[3];
result.set(intersectsPlane(ta, tb, tc, uvw));
}
/**
* Similar to intersectsPlane, but returns false if intersection does not occur on the triangle strictly defined by ta, tb, and tc
* @param ta the first vertex of a triangle on the plane
* @param tb the second vertex of a triangle on the plane
* @param tc the third vertex of a triangle on the plane
* @param result the variable in which to hold the result
*/
public <V extends Vec3d<?>>boolean intersectsTriangle(V ta, V tb, V tc, V result) {
double[] uvw = new double[3];
result.set(intersectsPlane(ta, tb, tc, uvw));
if(Double.isNaN(uvw[0]) || Double.isNaN(uvw[1]) || Double.isNaN(uvw[2]) || uvw[0] < 0 || uvw[1] < 0 || uvw[2] < 0)
return false;
else
return true;
}
Vec3d<?> I,u,v,n,dir,w0;
boolean inUse = false;
private <V extends Vec3d<?>> V planeIntersectTest(V ta, V tb, V tc, double[] uvw) {
if(u== null) {
u = tb.copy();
v = tc.copy();
dir = this.heading();
w0 = p1.copy(); w0.set(0,0,0);
I = p1.copy();
} else {
u.set(tb);
v.set(tc);
n.set(0,0,0);
dir.set(this.heading());
w0.set(0,0,0);
}
//SGVec_3d w = new SGVec_3d();
double r, a, b;
u.sub(ta);
v.sub(ta);
n = u.crossCopy(v);
w0.sub(ta);
a = -(n.dot(w0));
b = n.dot(dir);
r = a / b;
I.set(0,0,0);
I.set(dir);
I.mult(r);
//double[] barycentric = new double[3];
barycentric(ta, tb, tc, I, uvw);
return (V) I.copy();
}
/* Find where this ray intersects a sphere
* @param SGVec_3d the center of the sphere to test against.
* @param radius radius of the sphere
* @param S1 reference to variable in which the first intersection will be placed
* @param S2 reference to variable in which the second intersection will be placed
* @return number of intersections found;
*/
public <V extends Vec3d<?>> int intersectsSphere(V sphereCenter, double radius, V S1, V S2) {
Vec3d<?> tp1 = p1.subCopy(sphereCenter);
Vec3d<?> tp2 = p2.subCopy(sphereCenter);
int result = intersectsSphere(tp1, tp2, radius, S1, S2);
S1.add(sphereCenter); S2.add(sphereCenter);
return result;
}
/* Find where this ray intersects a sphere
* @param radius radius of the sphere
* @param S1 reference to variable in which the first intersection will be placed
* @param S2 reference to variable in which the second intersection will be placed
* @return number of intersections found;
*/
public <V extends Vec3d<?>> int intersectsSphere(V rp1, V rp2, double radius, V S1, V S2) {
V direction = (V) rp2.subCopy(rp1);
V e = (V) direction.copy(); // e=ray.dir
e.normalize(); // e=g/|g|
V h = (V) p1.copy();
h.set(0d,0d,0d);
h = (V) h.sub(rp1); // h=r.o-c.M
double lf = e.dot(h); // lf=e.h
double radpow = radius*radius;
double hdh = h.magSq();
double lfpow = lf*lf;
double s = radpow-hdh+lfpow; // s=r^2-h^2+lf^2
if (s < 0.0) return 0; // no intersection points ?
s = Math.sqrt(s); // s=sqrt(r^2-h^2+lf^2)
int result = 0;
if (lf < s) { // S1 behind A ?
if (lf+s >= 0) { // S2 before A ?}
s = -s; // swap S1 <-> S2}
result = 1; // one intersection point
}
}else result = 2; // 2 intersection points
S1.set(e.multCopy(lf-s));
S1.add(rp1); // S1=A+e*(lf-s)
S2.set(e.multCopy(lf+s));
S2.add(rp1); // S2=A+e*(lf+s)
// only for testing
return result;
}
Vec3d<?> m, at, bt, ct, pt;;
Vec3d<?> bc, ca, ac;
public <V extends Vec3d<?>> void barycentric(V a, V b, V c, V p, double[] uvw) {
if(m == null) {
//m=a.copy();
//m.set(0d,0d,0d);
bc = b.copy();
ca = c.copy();
at = a.copy();
bt = b.copy();
ct = c.copy();
pt = p.copy();
} else {
bc.set(b);
ca.set(a);
at.set(a);
bt.set(b);
ct.set(c);
pt.set(p);
}
m = new SGVec_3d(((SGVec_3d)bc.subCopy(ct)).crossCopy((SGVec_3d)ca.subCopy(at)));
double nu;
double nv;
double ood;
double x = Math.abs(m.x);
double y = Math.abs(m.y);
double z = Math.abs(m.z);
if (x >= y && x >= z) {
nu = triArea2D(pt.y, pt.z, bt.y, bt.z, ct.y, ct.z);
nv = triArea2D(pt.y, pt.z, ct.y, ct.z, at.y, at.z);
ood = 1.0f / m.x;
}
else if (y >= x && y >= z) {
nu = triArea2D(pt.x, pt.z, bt.x, bt.z, ct.x, ct.z);
nv = triArea2D(pt.x, pt.z, ct.x, ct.z, at.x, at.z);
ood = 1.0f / -m.y;
}
else {
nu = triArea2D(pt.x, pt.y, bt.x, bt.y, ct.x, ct.y);
nv = triArea2D(pt.x, pt.y, ct.x, ct.y, at.x, at.y);
ood = 1.0f / m.z;
}
uvw[0] = nu * ood;
uvw[1] = nv * ood;
uvw[2] = 1.0f - uvw[0] - uvw[1];
}
@Override
public String toString() {
String result = "sgRay " + System.identityHashCode(this) + "\n"
+"("+(float)this.p1.x +" -> " +(float)this.p2.x + ") \n "
+"("+(float)this.p1.y +" -> " +(float)this.p2.y + ") \n "
+"("+(float)this.p1.z +" -> " +(float)this.p2.z+ ") \n ";
return result;
}
public static double triArea2D(double x1, double y1, double x2, double y2, double x3, double y3) {
return (x1 - x2) * (y2 - y3) - (x2 - x3) * (y1 - y2);
}
public <V extends Vec3d<?>> void p1(V in) {
this.p1 = in.copy();
}
public <V extends Vec3d<?>> void p2(V in) {
this.p2 = in.copy();
}
public double lerp(double a, double b, double t) {
return (1-t)*a + t*b;
}
public Vec3d<?> p2() {
return p2;
}
public <R extends sgRayd>void set(R r) {
this.p1.set(r.p1);
this.p2.set(r.p2);
}
public <V extends Vec3d<?>> void setP2(V p2) {
this.p2 = p2;
}
public Vec3d<?> p1() {
return p1;
}
public <V extends Vec3d<?>> void setP1(V p1) {
this.p1 = p1;
}
@Override
public CanLoad populateSelfFromJSON(JSONObject j) {
if(this.p1 != null) this.p2 = this.p1.copy();
if(this.p2 != null) this.p1 = this.p2.copy();
if(this.p1 == null)
this.p1 = new SGVec_3d(j.getJSONObject("p1"));
else {
this.p1.set(new SGVec_3d(j.getJSONObject("p1")));
}
if(this.p2 == null)
this.p2 = new SGVec_3d(j.getJSONObject("p2"));
else
this.p2.set(new SGVec_3d(j.getJSONObject("p2")));
return this;
}
@Override
public JSONObject toJSONObject() {
JSONObject result = new JSONObject();
result.setJSONObject("p1", p1.toJSONObject());
result.setJSONObject("p2", p2.toJSONObject());
return result;
}
}
|
package plin.net.br.plin.util;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.NotificationCompat;
import plin.net.br.plin.R;
/**
* Created by sandeco on 10/05/16.
*/
public class Notifier {
private static int NOTIFICATION_ID = 120;
public static void notify(String title, String message) {
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(App.getContext())
.setSmallIcon(R.drawable.plin_notify)
.setContentTitle(title)
.setContentText(message)
.setLargeIcon(BitmapFactory.decodeResource(App.getContext().getResources(), R.drawable.plin_notify))
.setAutoCancel(true)
.setLights(Color.WHITE, 1000, 2000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
builder.setVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager notifyManager =
(NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notifyManager.notify(NOTIFICATION_ID, builder.build());
}
}
|
package com.kmdc.mdu.utils;
import android.content.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class FileUtils {
public static File saveFile(Context context, String content) {
return saveFile(context, content.getBytes(StandardCharsets.UTF_8));
}
public static File saveFile(Context context, byte[] stream) {
File localFile = null;
FileOutputStream fos = null;
String fileName = "deviceInfo.txt";
try {
localFile = new File(context.getFilesDir() + File.separator + fileName);
fos = new FileOutputStream(localFile);
fos.write(stream);
fos.flush();
return localFile;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return localFile;
}
public static boolean createOrExistsDir(File file) {
if (file != null) {
return file.exists() ? file.isDirectory() : file.mkdirs();
}
return false;
}
public static boolean createOrExistsDir(String dirPath) {
return createOrExistsDir(getFileByPath(dirPath));
}
public static boolean createOrExistsFile(File file) {
if (file == null) {
return false;
}
if (file.exists()) {
return file.isFile();
}
if (!createOrExistsDir(file.getParentFile())) {
return false;
}
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static void deleteFile(File file) {
if (file != null) {
file.delete();
}
}
public static File getFileByPath(String filePath) {
return isSpace(filePath) ? null : new File(filePath);
}
public static boolean isFileExists(File file) {
return file != null && (file.exists());
}
private static boolean isSpace(String s) {
if (s == null) {
return true;
}
int i = 0;
int len = s.length();
while (i < len) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
++i;
}
return true;
}
}
|
package com.aidigame.hisun.imengstar.widget.fragment;
import java.util.ArrayList;
import net.simonvt.numberpicker.NumberPicker;
import net.simonvt.numberpicker.NumberPicker.OnValueChangeListener;
import com.aidigame.hisun.imengstar.constant.AddressData;
import com.aidigame.hisun.imengstar.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
/**
* 选择种族
* @author admin
*
*/
public class RaceDialog {
NumberPicker starsPicker;
NumberPicker racePicker;
ArrayList<String> starsList;
ArrayList<String> raceList;
int starValue=0;
int raceValue=0;
String stars;
String race;
TextView provinceTV;
Context context;
View view;
public RaceDialog(Context context){
this.context=context;
view=LayoutInflater.from(context).inflate(R.layout.widget_address_picker, null);
starsPicker=(NumberPicker)view.findViewById(R.id.numberpicker1);
racePicker=(NumberPicker)view.findViewById(R.id.numberpicker2);
provinceTV=(TextView)view.findViewById(R.id.province_tv);
String[] array=context.getResources().getStringArray(R.array.stars);
starsList=new ArrayList<String>();
for(int i=0;i<array.length;i++){
starsList.add(array[i]);
}
starsPicker.setDisplayedValues(array);
starsPicker.setMaxValue(array.length-1);
raceList=new ArrayList<String>();
starsPicker.setMinValue(0);
starsPicker.setOnValueChangedListener(new OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// TODO Auto-generated method stub
racePicker.setValue(0);
starValue=newVal;
stars=starsList.get(newVal);
String[] array=null;
switch (newVal) {
case 0:
array=RaceDialog.this.context.getResources().getStringArray(R.array.cat_race);
break;
case 1:
array=RaceDialog.this.context.getResources().getStringArray(R.array.dog_race);
break;
case 2:
array=RaceDialog.this.context.getResources().getStringArray(R.array.other_race);
break;
}
raceList=new ArrayList<String>();
for(int i=0;i<array.length;i++){
raceList.add(array[i]);
}
racePicker.setDisplayedValues(array);
racePicker.setMaxValue(array.length-1);
racePicker.setMinValue(0);
race=array[0];
provinceTV.setText(stars);
}
});
array=context.getResources().getStringArray(R.array.cat_race);
for(int i=0;i<array.length;i++){
raceList.add(array[i]);
}
racePicker.setDisplayedValues(array);
racePicker.setMaxValue(array.length-1);
racePicker.setMinValue(0);
racePicker.setOnValueChangedListener(new OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// TODO Auto-generated method stub
raceValue=newVal;
race=raceList.get(newVal);
}
});
stars=starsList.get(0);
race=raceList.get(0);
provinceTV.setText(stars);
}
public View getView(){
return view;
}
public String getRace(){
return stars=raceList.get(raceValue);
}
public String getRaceCode(){
String string="";
if(starValue==0){
string=""+(101+raceValue);
}else if(starValue==1){
string=""+(201+raceValue);
}else if(starValue==2){
string=""+(301+raceValue);
}
return string;
}
}
|
package TST_teamproject.main.service;
import java.util.List;
import TST_teamproject.main.model.MainVo;
public interface MainService {
public List<MainVo> test();
}
|
package nyc.c4q.android.ui;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import nyc.c4q.android.R;
import nyc.c4q.android.model.Email;
public class EmailDetailFragment extends Fragment {
private Email email;
private static final DateFormat formatter = SimpleDateFormat.getDateInstance(DateFormat.SHORT);
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
email = (Email) getArguments().getSerializable("email");
}
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_email_detail, container, false);
// #14 TODO - get references to views
// #15 TODO - replace nulls
Picasso.with(getActivity()).load((String) null).into((ImageView) null);
// #16 TODO - bind email data to views
return view;
}
public static EmailDetailFragment newInstance(Email email) {
// #17 TODO - implement this factory method
// create fragment, set up its only argument (the email) and return it
// hint
//args.putSerializable("email", email);
return null;
}
}
|
package Utilities;
import GameControls.GameInfo;
public class EnemyUtilities extends NuetralUtilities{
}
|
package cogbog.dao;
import cogbog.dao.impl.GenericDaoImpl;
import cogbog.model.Bonus;
import cogbog.model.Profile;
import cogbog.model.Skill;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ProfileDaoImplTests {
private static GenericDao<Integer, Profile> profileDao;
private static GenericDao<Integer, Bonus> bonusDao;
private static GenericDao<Integer, Skill> skillDao;
@BeforeClass
public static void init() {
// profileDao = new ProfileDaoImpl();
// bonusDao = new BonusDaoImpl();
// skillDao = new SkillDaoImpl();
profileDao = new GenericDaoImpl<>(Profile.class);
bonusDao = new GenericDaoImpl<>(Bonus.class);
skillDao = new GenericDaoImpl<>(Skill.class);
}
@Test
public void canCreate() throws Exception {
Profile profile = new Profile();
int id = profileDao.create(profile);
}
@Test
public void canFindAfterCreate() throws Exception {
Profile profile = new Profile();
int id = profileDao.create(profile);
profileDao.find(id);
}
@Test
public void canUpdateAfterCreate() throws Exception {
Profile profile = new Profile();
int id = profileDao.create(profile);
profile.setCharacterClass("bard");
profileDao.update(id, profile);
}
@Test
public void canDeleteAfterCreate() throws Exception {
Profile profile = new Profile();
int id = profileDao.create(profile);
profileDao.delete(id);
}
@Test
public void findIdempotent() throws Exception {
Profile profile = new Profile();
profile.setCharacterClass("Investigator");
int id = profileDao.create(profile);
Profile find1 = profileDao.find(id);
Profile find2 = profileDao.find(id);
Assert.assertEquals(find1.toString(), find2.toString());
}
@Test(expected = Exception.class)
public void findFailsAfterDelete() throws Exception {
Profile profile = new Profile();
int id = profileDao.create(profile);
profileDao.delete(id);
profileDao.find(id);
Assert.fail();
}
@Test(expected = Exception.class)
public void updateFailsAfterDelete() throws Exception {
Profile profile = new Profile();
int id = profileDao.create(profile);
profileDao.delete(id);
profileDao.update(id, profile);
}
@Test
public void canFindAfterUpdate() throws Exception {
Profile profile = new Profile();
int id = profileDao.create(profile);
profile.setCharacterName("Toby");
profileDao.update(id, profile);
profileDao.find(id);
}
@Test
public void updateIdempotent() throws Exception {
Profile profile = new Profile();
int id = profileDao.create(profile);
profile.setCharacterClass("bard");
profileDao.update(id, profile);
Profile updatedOnce = profileDao.find(id);
profileDao.update(id, profile);
Profile updatedTwice = profileDao.find(id);
Assert.assertEquals(updatedOnce.toString(), updatedTwice.toString());
}
@Test(expected = Exception.class)
public void cannotDeleteTwice() throws Exception {
Profile profile = new Profile();
int id = profileDao.create(profile);
profileDao.delete(id);
profileDao.delete(id);
}
@Test
public void findTurnsUpLinkedSkills() throws Exception {
Profile profile = new Profile();
int id = profileDao.create(profile);
Skill skill = new Skill();
skill.setOwner(id);
skillDao.create(skill);
Assert.assertNull(profile.getSkills());
profile = profileDao.find(id);
Assert.assertNotNull(profile.getSkills());
Assert.assertTrue(profile.getSkills().contains(skill));
}
@Test
public void findTurnsUpLinkedBonuses() throws Exception {
Profile profile = new Profile();
int id = profileDao.create(profile);
Bonus bonus = new Bonus();
bonus.setOwner(id);
bonusDao.create(bonus);
Assert.assertNull(profile.getBonuses());
profile = profileDao.find(id);
Assert.assertNotNull(profile.getBonuses());
Assert.assertTrue(profile.getBonuses().contains(bonus));
}
} |
package textanalysis.dbutils;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import textanalysis.wikipediaindex.Article;
import utils.Utils;
import dataset.DatasetDocument;
import dataset.Datasets;
public class DBUtils {
private static String HOST, USERNAME, PASSWORD, DATABASE;
private Connection dbConnection;
public DBUtils() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Scanner sc = new Scanner(new File("config/dbconfig"));
HOST = sc.nextLine().split("\\t")[1];
USERNAME = sc.nextLine().split("\\t")[1];
PASSWORD = sc.nextLine().split("\\t")[1];
DATABASE = sc.nextLine().split("\\t")[1];
dbConnection = DriverManager.getConnection("jdbc:mysql://" + HOST
+ "/" + DATABASE
+ "?useUnicode=true&characterEncoding=utf8", USERNAME,
PASSWORD);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
private PreparedStatement addDocStmt;
public void addDocument(DatasetDocument doc) throws SQLException {
//
if (addDocStmt == null) {
addDocStmt = dbConnection
.prepareStatement("insert into document (title, dataset_id, category) values (?, ?, ?)");
}
// title, dataset_id, category, index_name, index_id
addDocStmt.setString(1, doc.getTitle());
addDocStmt.setInt(2, doc.getDataset().datasetId);
addDocStmt.setString(3, doc.getCategory());
addDocStmt.executeUpdate();
}
public List<Integer> getDatasetDocs(Datasets dataset) throws SQLException {
List<Integer> ids = new ArrayList<Integer>();
ResultSet rs = dbConnection.createStatement().executeQuery(
"SELECT id FROM document where dataset_id = "
+ dataset.datasetId);
while (rs.next()) {
ids.add(rs.getInt("id"));
}
return ids;
}
private PreparedStatement getWikipediaConcept;
public Article getWikipediaConcept(int conceptId) throws SQLException {
if (getWikipediaConcept == null)
getWikipediaConcept = dbConnection
.prepareStatement("SELECT name, url, tags FROM wikipedia_concept where id = ?");
getWikipediaConcept.setInt(1, conceptId);
ResultSet rs = getWikipediaConcept.executeQuery();
if (!rs.next())
return null;
Article article = new Article();
article.name = rs.getString("name");
article.url = rs.getString("url");
article.tags = rs.getString("tags").split("|");
article.indexId = conceptId;
return article;
}
private PreparedStatement insertWikipediaConceptStmt;
public void addWikipediaConcept(Article concept) throws SQLException {
if (insertWikipediaConceptStmt == null)
insertWikipediaConceptStmt = dbConnection
.prepareStatement("insert into wikipedia_concept (id, name, url, tags) values (?, ?, ?, ?)");
insertWikipediaConceptStmt.setInt(1, concept.indexId);
insertWikipediaConceptStmt.setString(2, concept.name);
insertWikipediaConceptStmt.setString(3, concept.url);
insertWikipediaConceptStmt.setString(4,
Utils.implode(concept.tags, "|"));
insertWikipediaConceptStmt.executeUpdate();
}
private PreparedStatement getTermAnnotations;
public Map<String, Float> getTermAnnotations(int docId, int method)
throws SQLException {
if (getTermAnnotations == null)
getTermAnnotations = dbConnection
.prepareStatement("SELECT term, weight FROM term_annotation where doc_id = ? and method = ?");
getTermAnnotations.setInt(1, docId);
getTermAnnotations.setInt(2, method);
ResultSet rs = getTermAnnotations.executeQuery();
Map<String, Float> annotations = new HashMap<String, Float>();
while (rs.next()) {
annotations.put(rs.getString("term"), rs.getFloat("weight"));
}
return annotations;
}
private PreparedStatement insertTermAnnotationsStmt;
public void addTermAnnotations(Map<String, Float> annotations, int docId,
int method) throws SQLException {
if (insertTermAnnotationsStmt == null)
insertTermAnnotationsStmt = dbConnection
.prepareStatement("insert into term_annotation (doc_id, term, weight, method) values (?,?,?,?)");
for (Entry<String, Float> term : annotations.entrySet()) {
insertTermAnnotationsStmt.setInt(1, docId);
insertTermAnnotationsStmt.setString(2, term.getKey());
insertTermAnnotationsStmt.setFloat(3, term.getValue());
insertTermAnnotationsStmt.setInt(4, method);
insertTermAnnotationsStmt.executeUpdate();
}
}
private PreparedStatement getConceptAnnotations;
public Map<String, Float> getConceptAnnotations(int docId, int method)
throws SQLException {
if (getConceptAnnotations == null)
getConceptAnnotations = dbConnection
.prepareStatement("SELECT concept_id, weight FROM semantic_annotation where document = ? and method = ?");
getConceptAnnotations.setInt(1, docId);
getConceptAnnotations.setInt(2, method);
ResultSet rs = getConceptAnnotations.executeQuery();
Map<String, Float> annotations = new HashMap<String, Float>();
while (rs.next()) {
annotations
.put(rs.getInt("concept_id") + "", rs.getFloat("weight"));
}
return annotations;
}
private PreparedStatement insertSemanticsStmt;
public void addConceptAnnotations(Map<Integer, Float> annotations,
int docId, int method) throws SQLException {
if (insertSemanticsStmt == null)
insertSemanticsStmt = dbConnection
.prepareStatement("insert into semantic_annotation (document, concept_id, weight, method) values (?, ?, ?, ?)");
for (Entry<Integer, Float> concept : annotations.entrySet()) {
insertSemanticsStmt.setInt(1, docId);
insertSemanticsStmt.setInt(2, concept.getKey());
insertSemanticsStmt.setFloat(3, concept.getValue());
insertSemanticsStmt.setInt(4, method);
insertSemanticsStmt.executeUpdate();
}
}
private PreparedStatement getCatDocsStmt;
public List<Integer> getCategoryDocuments(Datasets dataset, String category)
throws SQLException {
if (getCatDocsStmt == null)
getCatDocsStmt = dbConnection
.prepareStatement("SELECT id FROM document where dataset_id = ? and category = ?");
getCatDocsStmt.setInt(1, dataset.datasetId);
getCatDocsStmt.setString(2, category);
ResultSet rs = getCatDocsStmt.executeQuery();
List<Integer> docs = new ArrayList<Integer>();
while (rs.next()) {
docs.add(rs.getInt("id"));
}
return docs;
}
private PreparedStatement getDsCatsStmt;
public List<String> getDatasetCategories(Datasets dataset)
throws SQLException {
if (getDsCatsStmt == null)
getDsCatsStmt = dbConnection
.prepareStatement("SELECT distinct category FROM document where dataset_id = ?");
getDsCatsStmt.setInt(1, dataset.datasetId);
ResultSet rs = getDsCatsStmt.executeQuery();
List<String> cats = new ArrayList<String>();
while (rs.next()) {
cats.add(rs.getString("category"));
}
return cats;
}
private PreparedStatement getDocCatStmt;
public String getDocumentCategory(int docId) throws SQLException {
if (getDocCatStmt == null)
getDocCatStmt = dbConnection
.prepareStatement("SELECT category FROM document where id = ?");
getDocCatStmt.setInt(1, docId);
ResultSet rs = getDocCatStmt.executeQuery();
if (!rs.next())
return null;
return rs.getString("category");
}
}
|
//file: Problem_2_1.java
//author: Victoria Cameron
//course: CMPT 220
//assignment: Lab 1
//due date: January 26, 2017
//version: 1.0
import java.util.Scanner;
public class Problem_2_1{
public static void main(String[] args){
//display welcome
System.out.println ("Welcome to the Celsius to Fahrenheit converter");
//receive temp
Scanner input = new Scanner (System.in);
System.out.print("Enter a temprature to convert to Fahrenheit");
double celsius = input.nextDouble();
// convert temp
double fahrenheit = (9.0 / 5.0) * celsius + 32;
//show new temp
System.out.println(celsius + "Celsius is" + fahrenheit + "Fahrenheit");
}
} |
/*
* Copyright © 2020-2022 ForgeRock AS (obst@forgerock.com)
*
* 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 uk.org.openbanking.datamodel.service.converter.payment;
import uk.org.openbanking.datamodel.payment.OBDomesticStandingOrder1;
import uk.org.openbanking.datamodel.payment.OBDomesticStandingOrder2;
import uk.org.openbanking.datamodel.payment.OBDomesticStandingOrder3;
import uk.org.openbanking.datamodel.payment.OBWriteDomesticStandingOrder3DataInitiation;
import static uk.org.openbanking.datamodel.service.converter.payment.OBAccountConverter.*;
import static uk.org.openbanking.datamodel.service.converter.payment.OBAmountConverter.*;
public class OBDomesticStandingOrderConverter {
public static OBDomesticStandingOrder1 toOBDomesticStandingOrder1(OBDomesticStandingOrder2 obDomesticStandingOrder2) {
return obDomesticStandingOrder2 == null ? null : (new OBDomesticStandingOrder1())
.frequency(obDomesticStandingOrder2.getFrequency())
.reference(obDomesticStandingOrder2.getReference())
.numberOfPayments(obDomesticStandingOrder2.getNumberOfPayments())
.firstPaymentDateTime(obDomesticStandingOrder2.getFirstPaymentDateTime())
.recurringPaymentDateTime(obDomesticStandingOrder2.getRecurringPaymentDateTime())
.finalPaymentDateTime(obDomesticStandingOrder2.getFinalPaymentDateTime())
.firstPaymentAmount(obDomesticStandingOrder2.getFirstPaymentAmount())
.recurringPaymentAmount(obDomesticStandingOrder2.getRecurringPaymentAmount())
.finalPaymentAmount(obDomesticStandingOrder2.getFinalPaymentAmount())
.debtorAccount(obDomesticStandingOrder2.getDebtorAccount())
.creditorAccount(obDomesticStandingOrder2.getCreditorAccount());
}
public static OBDomesticStandingOrder1 toOBDomesticStandingOrder1(OBDomesticStandingOrder3 obDomesticStandingOrder3) {
return obDomesticStandingOrder3 == null ? null : (new OBDomesticStandingOrder1())
.frequency(obDomesticStandingOrder3.getFrequency())
.reference(obDomesticStandingOrder3.getReference())
.numberOfPayments(obDomesticStandingOrder3.getNumberOfPayments())
.firstPaymentDateTime(obDomesticStandingOrder3.getFirstPaymentDateTime())
.recurringPaymentDateTime(obDomesticStandingOrder3.getRecurringPaymentDateTime())
.finalPaymentDateTime(obDomesticStandingOrder3.getFinalPaymentDateTime())
.firstPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(obDomesticStandingOrder3.getFirstPaymentAmount()))
.recurringPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(obDomesticStandingOrder3.getRecurringPaymentAmount()))
.finalPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(obDomesticStandingOrder3.getFinalPaymentAmount()))
.debtorAccount(toOBCashAccount3(obDomesticStandingOrder3.getDebtorAccount()))
.creditorAccount(toOBCashAccount3(obDomesticStandingOrder3.getCreditorAccount()));
}
public static OBDomesticStandingOrder1 toOBDomesticStandingOrder1(OBWriteDomesticStandingOrder3DataInitiation initiation) {
return initiation == null ? null : (new OBDomesticStandingOrder1())
.frequency(initiation.getFrequency())
.reference(initiation.getReference())
.numberOfPayments(initiation.getNumberOfPayments())
.firstPaymentDateTime(initiation.getFirstPaymentDateTime())
.recurringPaymentDateTime(initiation.getRecurringPaymentDateTime())
.finalPaymentDateTime(initiation.getFinalPaymentDateTime())
.firstPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(initiation.getFirstPaymentAmount()))
.recurringPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(initiation.getRecurringPaymentAmount()))
.finalPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(initiation.getFinalPaymentAmount()))
.debtorAccount(OBAccountConverter.toOBCashAccount3(initiation.getDebtorAccount()))
.creditorAccount(toOBCashAccount3(initiation.getCreditorAccount()));
}
public static OBDomesticStandingOrder2 toOBDomesticStandingOrder2(OBWriteDomesticStandingOrder3DataInitiation initiation) {
return initiation == null ? null : (new OBDomesticStandingOrder2())
.frequency(initiation.getFrequency())
.reference(initiation.getReference())
.numberOfPayments(initiation.getNumberOfPayments())
.firstPaymentDateTime(initiation.getFirstPaymentDateTime())
.recurringPaymentDateTime(initiation.getRecurringPaymentDateTime())
.finalPaymentDateTime(initiation.getFinalPaymentDateTime())
.firstPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(initiation.getFirstPaymentAmount()))
.recurringPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(initiation.getRecurringPaymentAmount()))
.finalPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(initiation.getFinalPaymentAmount()))
.debtorAccount(OBAccountConverter.toOBCashAccount3(initiation.getDebtorAccount()))
.creditorAccount(toOBCashAccount3(initiation.getCreditorAccount()))
.supplementaryData(initiation.getSupplementaryData());
}
public static OBDomesticStandingOrder2 toOBDomesticStandingOrder2(OBDomesticStandingOrder1 obDomesticStandingOrder1) {
return obDomesticStandingOrder1 == null ? null : (new OBDomesticStandingOrder2())
.frequency(obDomesticStandingOrder1.getFrequency())
.reference(obDomesticStandingOrder1.getReference())
.numberOfPayments(obDomesticStandingOrder1.getNumberOfPayments())
.firstPaymentDateTime(obDomesticStandingOrder1.getFirstPaymentDateTime())
.recurringPaymentDateTime(obDomesticStandingOrder1.getRecurringPaymentDateTime())
.finalPaymentDateTime(obDomesticStandingOrder1.getFinalPaymentDateTime())
.firstPaymentAmount(obDomesticStandingOrder1.getFirstPaymentAmount())
.recurringPaymentAmount(obDomesticStandingOrder1.getRecurringPaymentAmount())
.finalPaymentAmount(obDomesticStandingOrder1.getFinalPaymentAmount())
.debtorAccount(obDomesticStandingOrder1.getDebtorAccount())
.creditorAccount(obDomesticStandingOrder1.getCreditorAccount())
.supplementaryData(null);
}
public static OBDomesticStandingOrder2 toOBDomesticStandingOrder2(OBDomesticStandingOrder3 obDomesticStandingOrder3) {
return obDomesticStandingOrder3 == null ? null : (new OBDomesticStandingOrder2())
.frequency(obDomesticStandingOrder3.getFrequency())
.reference(obDomesticStandingOrder3.getReference())
.numberOfPayments(obDomesticStandingOrder3.getNumberOfPayments())
.firstPaymentDateTime(obDomesticStandingOrder3.getFirstPaymentDateTime())
.recurringPaymentDateTime(obDomesticStandingOrder3.getRecurringPaymentDateTime())
.finalPaymentDateTime(obDomesticStandingOrder3.getFinalPaymentDateTime())
.firstPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(obDomesticStandingOrder3.getFirstPaymentAmount()))
.recurringPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(obDomesticStandingOrder3.getRecurringPaymentAmount()))
.finalPaymentAmount(toOBActiveOrHistoricCurrencyAndAmount(obDomesticStandingOrder3.getFinalPaymentAmount()))
.debtorAccount(toOBCashAccount3(obDomesticStandingOrder3.getDebtorAccount()))
.creditorAccount(toOBCashAccount3(obDomesticStandingOrder3.getCreditorAccount()))
.supplementaryData(obDomesticStandingOrder3.getSupplementaryData());
}
public static OBDomesticStandingOrder3 toOBDomesticStandingOrder3(OBDomesticStandingOrder1 obDomesticStandingOrder1) {
return obDomesticStandingOrder1 == null ? null : (new OBDomesticStandingOrder3())
.frequency(obDomesticStandingOrder1.getFrequency())
.reference(obDomesticStandingOrder1.getReference())
.numberOfPayments(obDomesticStandingOrder1.getNumberOfPayments())
.firstPaymentDateTime(obDomesticStandingOrder1.getFirstPaymentDateTime())
.recurringPaymentDateTime(obDomesticStandingOrder1.getRecurringPaymentDateTime())
.finalPaymentDateTime(obDomesticStandingOrder1.getFinalPaymentDateTime())
.firstPaymentAmount(toOBDomesticStandingOrder3FirstPaymentAmount(obDomesticStandingOrder1.getFirstPaymentAmount()))
.recurringPaymentAmount(toOBDomesticStandingOrder3RecurringPaymentAmount(obDomesticStandingOrder1.getRecurringPaymentAmount()))
.finalPaymentAmount(toOBDomesticStandingOrder3FinalPaymentAmount(obDomesticStandingOrder1.getFinalPaymentAmount()))
.debtorAccount(toOBCashAccountDebtor4(obDomesticStandingOrder1.getDebtorAccount()))
.creditorAccount(toOBCashAccountCreditor3(obDomesticStandingOrder1.getCreditorAccount()))
.supplementaryData(null);
}
public static OBDomesticStandingOrder3 toOBDomesticStandingOrder3(OBDomesticStandingOrder2 obDomesticStandingOrder2) {
return obDomesticStandingOrder2 == null ? null : (new OBDomesticStandingOrder3())
.frequency(obDomesticStandingOrder2.getFrequency())
.reference(obDomesticStandingOrder2.getReference())
.numberOfPayments(obDomesticStandingOrder2.getNumberOfPayments())
.firstPaymentDateTime(obDomesticStandingOrder2.getFirstPaymentDateTime())
.recurringPaymentDateTime(obDomesticStandingOrder2.getRecurringPaymentDateTime())
.finalPaymentDateTime(obDomesticStandingOrder2.getFinalPaymentDateTime())
.firstPaymentAmount(toOBDomesticStandingOrder3FirstPaymentAmount(obDomesticStandingOrder2.getFirstPaymentAmount()))
.recurringPaymentAmount(toOBDomesticStandingOrder3RecurringPaymentAmount(obDomesticStandingOrder2.getRecurringPaymentAmount()))
.finalPaymentAmount(toOBDomesticStandingOrder3FinalPaymentAmount(obDomesticStandingOrder2.getFinalPaymentAmount()))
.debtorAccount(toOBCashAccountDebtor4(obDomesticStandingOrder2.getDebtorAccount()))
.creditorAccount(toOBCashAccountCreditor3(obDomesticStandingOrder2.getCreditorAccount()))
.supplementaryData(obDomesticStandingOrder2.getSupplementaryData());
}
public static OBDomesticStandingOrder3 toOBDomesticStandingOrder3(OBWriteDomesticStandingOrder3DataInitiation initiation) {
return initiation == null ? null : (new OBDomesticStandingOrder3())
.frequency(initiation.getFrequency())
.reference(initiation.getReference())
.numberOfPayments(initiation.getNumberOfPayments())
.firstPaymentDateTime(initiation.getFirstPaymentDateTime())
.recurringPaymentDateTime(initiation.getRecurringPaymentDateTime())
.finalPaymentDateTime(initiation.getFinalPaymentDateTime())
.firstPaymentAmount(toOBDomesticStandingOrder3FirstPaymentAmount(initiation.getFirstPaymentAmount()))
.recurringPaymentAmount(toOBDomesticStandingOrder3RecurringPaymentAmount(initiation.getRecurringPaymentAmount()))
.finalPaymentAmount(toOBDomesticStandingOrder3FinalPaymentAmount(initiation.getFinalPaymentAmount()))
.debtorAccount(toOBCashAccountDebtor4(initiation.getDebtorAccount()))
.creditorAccount(toOBCashAccountCreditor3(initiation.getCreditorAccount()))
.supplementaryData(initiation.getSupplementaryData());
}
public static OBWriteDomesticStandingOrder3DataInitiation toOBWriteDomesticStandingOrder3DataInitiation(OBDomesticStandingOrder1 initiation) {
return initiation == null ? null : (new OBWriteDomesticStandingOrder3DataInitiation())
.frequency(initiation.getFrequency())
.reference(initiation.getReference())
.numberOfPayments(initiation.getNumberOfPayments())
.firstPaymentDateTime(initiation.getFirstPaymentDateTime())
.recurringPaymentDateTime(initiation.getRecurringPaymentDateTime())
.finalPaymentDateTime(initiation.getFinalPaymentDateTime())
.firstPaymentAmount(toOBWriteDomesticStandingOrder3DataInitiationFirstPaymentAmount(initiation.getFirstPaymentAmount()))
.recurringPaymentAmount(toOBWriteDomesticStandingOrder3DataInitiationRecurringPaymentAmount(initiation.getRecurringPaymentAmount()))
.finalPaymentAmount(toOBWriteDomesticStandingOrder3DataInitiationFinalPaymentAmount(initiation.getFinalPaymentAmount()))
.debtorAccount(toOBWriteDomesticStandingOrder3DataInitiationDebtorAccount(initiation.getDebtorAccount()))
.creditorAccount(toOBWriteDomesticStandingOrder3DataInitiationCreditorAccount(initiation.getCreditorAccount()))
.supplementaryData(null);
}
public static OBWriteDomesticStandingOrder3DataInitiation toOBWriteDomesticStandingOrder3DataInitiation(OBDomesticStandingOrder2 initiation) {
return initiation == null ? null : (new OBWriteDomesticStandingOrder3DataInitiation())
.frequency(initiation.getFrequency())
.reference(initiation.getReference())
.numberOfPayments(initiation.getNumberOfPayments())
.firstPaymentDateTime(initiation.getFirstPaymentDateTime())
.recurringPaymentDateTime(initiation.getRecurringPaymentDateTime())
.finalPaymentDateTime(initiation.getFinalPaymentDateTime())
.firstPaymentAmount(toOBWriteDomesticStandingOrder3DataInitiationFirstPaymentAmount(initiation.getFirstPaymentAmount()))
.recurringPaymentAmount(toOBWriteDomesticStandingOrder3DataInitiationRecurringPaymentAmount(initiation.getRecurringPaymentAmount()))
.finalPaymentAmount(toOBWriteDomesticStandingOrder3DataInitiationFinalPaymentAmount(initiation.getFinalPaymentAmount()))
.debtorAccount(toOBWriteDomesticStandingOrder3DataInitiationDebtorAccount(initiation.getDebtorAccount()))
.creditorAccount(toOBWriteDomesticStandingOrder3DataInitiationCreditorAccount(initiation.getCreditorAccount()))
.supplementaryData(initiation.getSupplementaryData());
}
public static OBWriteDomesticStandingOrder3DataInitiation toOBWriteDomesticStandingOrder3DataInitiation(OBDomesticStandingOrder3 obDomesticStandingOrder3) {
return obDomesticStandingOrder3 == null ? null : (new OBWriteDomesticStandingOrder3DataInitiation())
.frequency(obDomesticStandingOrder3.getFrequency())
.reference(obDomesticStandingOrder3.getReference())
.numberOfPayments(obDomesticStandingOrder3.getNumberOfPayments())
.firstPaymentDateTime(obDomesticStandingOrder3.getFirstPaymentDateTime())
.recurringPaymentDateTime(obDomesticStandingOrder3.getRecurringPaymentDateTime())
.finalPaymentDateTime(obDomesticStandingOrder3.getFinalPaymentDateTime())
.firstPaymentAmount(toOBWriteDomesticStandingOrder3DataInitiationFirstPaymentAmount(obDomesticStandingOrder3.getFirstPaymentAmount()))
.recurringPaymentAmount(toOBWriteDomesticStandingOrder3DataInitiationRecurringPaymentAmount(obDomesticStandingOrder3.getRecurringPaymentAmount()))
.finalPaymentAmount(toOBWriteDomesticStandingOrder3DataInitiationFinalPaymentAmount(obDomesticStandingOrder3.getFinalPaymentAmount()))
.debtorAccount(toOBWriteDomesticStandingOrder3DataInitiationDebtorAccount(obDomesticStandingOrder3.getDebtorAccount()))
.creditorAccount(toOBWriteDomesticStandingOrder3DataInitiationCreditorAccount(obDomesticStandingOrder3.getCreditorAccount()))
.supplementaryData(obDomesticStandingOrder3.getSupplementaryData());
}
}
|
package cn.jaychang.scstudy.account.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* @author zhangjie
* @package cn.jaychang.scstudy.account.dto
* @description 账户DTO
* @create 2018-10-07 10:06
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AccountDTO implements Serializable{
private static final long serialVersionUID = -3740202802087575413L;
/**
* 账户id
*/
private Long id;
/**
* 账号
*/
private String userId;
/**
* 用户余额
*/
private BigDecimal balance;
/**
* 冻结金额,扣款暂存余额
*/
private BigDecimal freezeAmount;
}
|
package com.geetuargo;
import java.util.*;
public class StreamAPI {
public static void main(String[] args) {
List<Integer> values = new ArrayList();
for(int i=1; i<=10; i++ )
{
values.add(i);
}
values.forEach(a -> System.out.println(a));
}
}
|
package enshud.s4.ilgenerator.visitors;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import enshud.interlanguage.iloperand.ILIndexedVariableOperand;
import enshud.interlanguage.iloperand.ILSimpleVariableOperand;
import enshud.interlanguage.ilstatement.ILCopyStatement;
import enshud.s3.checker.CheckerException;
import enshud.s3.checker.TypeExpressionMap;
import enshud.s4.ilgenerator.ILCodeBlock;
import enshud.s4.ilgenerator.TempVariablePool;
import enshud.symboltable.SymbolTable;
import enshud.symboltable.SymbolTableStack;
import enshud.syntaxtree.AbstractSyntaxNode;
import enshud.syntaxtree.AbstractVisitor;
import enshud.syntaxtree.SyntaxNodeStack;
public class AssignStatementILCodeGenerator extends AbstractVisitor {
private HashMap<AbstractSyntaxNode, String> variableMap;
private HashMap<AbstractSyntaxNode, ILCodeBlock> ilCodeBlocks;
private TempVariablePool tempVariablePool;
public AssignStatementILCodeGenerator(
HashMap<AbstractSyntaxNode, String> variableMap,
HashMap<AbstractSyntaxNode, ILCodeBlock> ilCodeBlocks,
TempVariablePool tempVariablePool) {
this.variableMap = variableMap;
this.ilCodeBlocks = ilCodeBlocks;
this.tempVariablePool = tempVariablePool;
}
@Override
public void postorder(
TypeExpressionMap typeExpressions,
Map<AbstractSyntaxNode, SymbolTable> symbolTables,
SyntaxNodeStack syntaxNodeStack,
SymbolTableStack symbolTableStack
) throws CheckerException {
// 直近のILコードブロックを取得
var ilCodeBlock = ilCodeBlocks.get(syntaxNodeStack.getLastVariable("CompoundStatements"));
String leftVariableName = variableMap.get(syntaxNodeStack.getLast().get(0));
String rightVariableName = variableMap.get(syntaxNodeStack.getLast().get(2));
// 右辺が一時変数なら解放
tempVariablePool.free(rightVariableName);
// 左辺が添え字付き引数なら,添え字を解放
var pattern = Pattern.compile("(?<=\\[).+(?=\\])");
var match = pattern.matcher(leftVariableName);
if(match.find()) {
// 左辺が添え字付き引数
String arrayName = leftVariableName.split("\\[")[0];
String indexName = match.group();
tempVariablePool.free(indexName);
ilCodeBlock.add(new ILCopyStatement(
new ILIndexedVariableOperand(arrayName, indexName),
new ILSimpleVariableOperand(rightVariableName),
typeExpressions.get(syntaxNodeStack.getLast().get(0))
));
} else {
ilCodeBlock.add(new ILCopyStatement(
new ILSimpleVariableOperand(leftVariableName),
new ILSimpleVariableOperand(rightVariableName),
typeExpressions.get(syntaxNodeStack.getLast().get(0))
));
}
}
}
|
package br.com.zup.ecommerce.categoria;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
import org.springframework.util.Assert;
import br.com.zup.ecommerce.compartilhado.ExistsId;
import br.com.zup.ecommerce.compartilhado.UniqueValue;
public class CategoriaRequest {
@NotBlank
@UniqueValue(domainClass=Categoria.class, fieldName="nome", message="Categoria ja esta cadastrado")
private String nome;
@Positive
@ExistsId(domainClass = Categoria.class, fieldName = "id")
private Long idCategoriaMae;
public void setNome(String nome) {
this.nome = nome;
}
public void setIdCategoriaMae(Long idCategoriaMae) {
this.idCategoriaMae = idCategoriaMae;
}
@Override
public String toString() {
return "CategoriaRequest [nome=" + nome + ", idCategoriaMae=" + idCategoriaMae + "]";
}
public Categoria toModel(CategoriaRepository categoriaRepository) {
Categoria categoria = new Categoria(nome);
if(idCategoriaMae !=null) {
Categoria categoriaMae = categoriaRepository.getOne(idCategoriaMae);
Assert.notNull(categoriaMae, "O ID da categoria mae prcisa ser válido");
categoria.setCategoriaMae(categoriaMae);
}
return categoria;
}
}
|
package com.esum.framework.core.management.mbean.as2;
import java.util.List;
import com.esum.framework.core.component.ComponentStatus;
import com.esum.framework.core.exception.SystemException;
import com.esum.framework.core.management.mbean.TransactionStatus;
/**
* AS2 Control.
*/
public interface AS2ControlMBean {
/**
* Reloading the specified partner name.
*/
public void reloadPartnerInfo(String partnerName) throws SystemException;
/**
* Reloading the specified routing.
*/
public void reloadRoutingInfo(String routingId) throws SystemException;
/**
* Get the specified value of key.
*/
public String getProperty(String key) throws SystemException;
public List<ComponentStatus> getComponentListStatus() throws SystemException;
/**
* Returns the shared tomcat or not.
*/
public String getTomcatShareUse(String nodeid) throws SystemException;
/**
* Transaction Status.
*/
public List<TransactionStatus> getTransactionStatus() throws SystemException;
/**
* Purge the specified Channel.
*/
public boolean purgeTransaction(String channelName) throws SystemException;
/**
* Restart the transaction handler.
*/
public boolean restartTransaction(String channelName) throws SystemException;
}
|
package com.zeyad.grability.utilities;
/**
* Created by ZIaDo on 12/4/15.
*/
public class Config {
public static String URL = "https://itunes.apple.com/us/rss/topfreeapplications/limit=20", FILENAME;
public String getURL() {
return URL;
}
public void setURL(String url) {
URL = url;
}
} |
package com.sims.model;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
*
* @author dward
*
*/
@Entity
@Table(name = "physicalinventorydetails", schema = "sims")
public class PhysicalInventoryDetails implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private PhysicalInventory physicalInventory;
private Item item;
private Integer systemQty;
private Integer physicalCount;
private Integer qtyVariance;
private String variance;
private Integer createdBy;
private Timestamp createdOn;
private Integer modifiedBy;
private Timestamp modifiedOn;
private Integer version;
private Boolean active;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "physicalInventoryDetailsId_generator")
@SequenceGenerator(name="physicalInventoryDetailsId_generator", sequenceName = "sims.physicalinventorydetailsseq", allocationSize=1)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "physicalinventoryid", nullable = false)
public PhysicalInventory getPhysicalInventory() {
return physicalInventory;
}
public void setPhysicalInventory(PhysicalInventory physicalInventory) {
this.physicalInventory = physicalInventory;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "itemid", nullable = false)
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
@Column(name = "systemqty")
public Integer getSystemQty() {
return systemQty;
}
public void setSystemQty(Integer systemQty) {
this.systemQty = systemQty;
}
@Column(name = "physicalcount")
public Integer getPhysicalCount() {
return physicalCount;
}
public void setPhysicalCount(Integer physicalCount) {
this.physicalCount = physicalCount;
}
@Column(name = "qtyvariance")
public Integer getQtyVariance() {
return qtyVariance;
}
public void setQtyVariance(Integer qtyVariance) {
this.qtyVariance = qtyVariance;
}
@Column(name = "variance", length = 10)
public String getVariance() {
return variance;
}
public void setVariance(String variance) {
this.variance = variance;
}
@Column(name = "createdby")
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
@Column(name = "createdon")
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
@Column(name = "modifiedby")
public Integer getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(Integer modifiedBy) {
this.modifiedBy = modifiedBy;
}
@Column(name = "modifiedon")
public Timestamp getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(Timestamp modifiedOn) {
this.modifiedOn = modifiedOn;
}
@Column(name = "version")
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
@Column(name = "active")
public Boolean isActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
@Override
public String toString() {
return "PhysicalInventoryDetails [id=" + id + ", physicalInventory="
+ (physicalInventory!=null ? physicalInventory.getId() : "0") + ", item=" + (item!=null ? item.getId() : "0") + ", systemQty="
+ systemQty + ", physicalCount=" + physicalCount
+ ", qtyVariance=" + qtyVariance + ", variance=" + variance
+ ", createdBy=" + createdBy
+ ", createdOn=" + createdOn + ", modifiedBy=" + modifiedBy
+ ", modifiedOn=" + modifiedOn + ", version=" + version
+ ", active=" + active + "]";
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.result;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrlPattern;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrlTemplate;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlTemplate;
/**
* Unit tests for {@link MockMvcResultMatchers}.
*
* @author Brian Clozel
* @author Sam Brannen
*/
public class MockMvcResultMatchersTests {
@Test
public void redirect() throws Exception {
assertThatCode(() -> redirectedUrl("/resource/1").match(redirectedUrlStub("/resource/1")))
.doesNotThrowAnyException();
}
@Test
public void redirectNonMatching() throws Exception {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> redirectedUrl("/resource/2").match(redirectedUrlStub("/resource/1")))
.withMessageEndingWith("expected:</resource/2> but was:</resource/1>");
}
@Test
public void redirectNonMatchingBecauseNotRedirect() throws Exception {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> redirectedUrl("/resource/1").match(forwardedUrlStub("/resource/1")))
.withMessageEndingWith("expected:</resource/1> but was:<null>");
}
@Test
public void redirectWithUrlTemplate() throws Exception {
assertThatCode(() -> redirectedUrlTemplate("/orders/{orderId}/items/{itemId}", 1, 2).match(redirectedUrlStub("/orders/1/items/2")))
.doesNotThrowAnyException();
}
@Test
public void redirectWithMatchingPattern() throws Exception {
assertThatCode(() -> redirectedUrlPattern("/resource/*").match(redirectedUrlStub("/resource/1")))
.doesNotThrowAnyException();
}
@Test
public void redirectWithNonMatchingPattern() throws Exception {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> redirectedUrlPattern("/resource/").match(redirectedUrlStub("/resource/1")))
.withMessage("'/resource/' is not an Ant-style path pattern");
}
@Test
public void redirectWithNonMatchingPatternBecauseNotRedirect() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> redirectedUrlPattern("/resource/*").match(forwardedUrlStub("/resource/1")))
.withMessage("Redirected URL 'null' does not match the expected URL pattern '/resource/*'");
}
@Test
public void forward() throws Exception {
assertThatCode(() -> forwardedUrl("/api/resource/1").match(forwardedUrlStub("/api/resource/1")))
.doesNotThrowAnyException();
}
@Test
public void forwardNonMatching() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> forwardedUrlPattern("api/resource/2").match(forwardedUrlStub("api/resource/1")))
.withMessage("'api/resource/2' is not an Ant-style path pattern");
}
@Test
public void forwardNonMatchingBecauseNotForward() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> forwardedUrlPattern("/resource/*").match(redirectedUrlStub("/resource/1")))
.withMessage("Forwarded URL 'null' does not match the expected URL pattern '/resource/*'");
}
@Test
public void forwardWithQueryString() throws Exception {
assertThatCode(() -> forwardedUrl("/api/resource/1?arg=value").match(forwardedUrlStub("/api/resource/1?arg=value")))
.doesNotThrowAnyException();
}
@Test
public void forwardWithUrlTemplate() throws Exception {
assertThatCode(() -> forwardedUrlTemplate("/orders/{orderId}/items/{itemId}", 1, 2).match(forwardedUrlStub("/orders/1/items/2")))
.doesNotThrowAnyException();
}
@Test
public void forwardWithMatchingPattern() throws Exception {
assertThatCode(() -> forwardedUrlPattern("/api/**/?").match(forwardedUrlStub("/api/resource/1")))
.doesNotThrowAnyException();
}
@Test
public void forwardWithNonMatchingPattern() throws Exception {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> forwardedUrlPattern("/resource/").match(forwardedUrlStub("/resource/1")))
.withMessage("'/resource/' is not an Ant-style path pattern");
}
@Test
public void forwardWithNonMatchingPatternBecauseNotForward() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> forwardedUrlPattern("/resource/*").match(redirectedUrlStub("/resource/1")))
.withMessage("Forwarded URL 'null' does not match the expected URL pattern '/resource/*'");
}
private StubMvcResult redirectedUrlStub(String redirectUrl) throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
response.sendRedirect(redirectUrl);
return new StubMvcResult(null, null, null, null, null, null, response);
}
private StubMvcResult forwardedUrlStub(String forwardedUrl) {
MockHttpServletResponse response = new MockHttpServletResponse();
response.setForwardedUrl(forwardedUrl);
return new StubMvcResult(null, null, null, null, null, null, response);
}
}
|
package com.multivision.ehrms.action;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import com.multivision.ehrms.action.form.ResourceForm;
import com.multivision.ehrms.business.Resource;
import com.multivision.ehrms.business.Project;
import com.multivision.ehrms.exception.DataSourceConnectivityFailedException;
import com.multivision.ehrms.exception.DuplicateRecordException;
import com.multivision.ehrms.service.business.BusinessServiceFactory;
import com.multivision.ehrms.service.business.interfaces.IResourceBusinessService;
import com.multivision.ehrms.service.business.interfaces.IProjectBusinessService;
public class ResourceAction extends BaseDispatchAction {
private Logger logger = Logger.getRootLogger();
BusinessServiceFactory bsFactory;
public BusinessServiceFactory getBsFactory() {
return bsFactory;
}
public void setBsFactory(BusinessServiceFactory bsFactory) {
this.bsFactory = bsFactory;
}
@Override
protected ActionForward perform(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
if (request.getParameter("method") != null) {
String parameter = request.getParameter("method");
if (parameter.equalsIgnoreCase("list")) {
forward = list(mapping, form, request, response);
} else if (parameter.equalsIgnoreCase("add")) {
forward = add(mapping, form, request, response);
} else if (parameter.equalsIgnoreCase("save")) {
forward = save(mapping, form, request, response);
} else if (parameter.equalsIgnoreCase("edit")) {
forward = edit(mapping, form, request, response);
} else if (parameter.equalsIgnoreCase("view")) {
forward = view(mapping, form, request, response);
}
}
return forward;
}
public ActionForward list(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.info("Listing resource information");
ActionForward forward = null;
List<Resource> resources = getResources();
request.setAttribute("RESOURCES", resources);
forward = mapping.findForward("list");
return forward;
}
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.info("Displaying add screen to add resource details");
ActionForward forward = null;
ResourceForm resourceForm = (ResourceForm) form;
resourceForm.setAction("add");
clearFormValues(resourceForm);
request.getSession(false).setAttribute("PROJECTS", fetchProjects());
forward = mapping.findForward("add");
return forward;
}
public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.info("Displaying edit screen to edit resource details");
ActionForward forward = null;
ResourceForm resourceForm = (ResourceForm) form;
Long Id = null;
if (request.getParameter("id") != null
&& request.getParameter("id").length() > 0) {
Id = Long.valueOf(request.getParameter("id"));
}
Resource resource = fetchResource(Id);
request.getSession(false).setAttribute("PROJECTS", fetchProjects());
resourceForm.setAction("edit");
setFormValues(resourceForm, resource);
forward = mapping.findForward("edit");
return forward;
}
public ActionForward view(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.info("Displaying view screen to display resource details");
ActionForward forward = null;
ResourceForm resourceForm = (ResourceForm) form;
Long Id = null;
if (request.getParameter("id") != null
&& request.getParameter("id").length() > 0) {
Id = Long.valueOf(request.getParameter("id"));
}
Resource resource = fetchResource(Id);
setFormValues(resourceForm, resource);
forward = mapping.findForward("view");
return forward;
}
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.info("Trying to save the resource details");
ActionForward forward = null;
ActionMessages messages = new ActionMessages();
forward = mapping.findForward("save");
ResourceForm resourceForm = (ResourceForm) form;
try {
saveValues(resourceForm);
messages.add("project_add_status", new ActionMessage(
"project.data.added.success"));
saveMessages(request, messages);
resourceForm.setAction("save");
logger.info("Saved the employee details");
} catch (DataSourceConnectivityFailedException dscfException) {
logger.debug(dscfException);
messages.add("project_add_status", new ActionMessage(
"global.db.connectivity.failure"));
saveMessages(request, messages);
} catch (DuplicateRecordException drException) {
logger.debug(drException);
messages.add("project_add_status", new ActionMessage(
"project.data.added.duplicate.failed"));
saveMessages(request, messages);
} catch (Exception exception) {
logger.debug(exception);
messages.add("project_add_status",
new ActionMessage("project.data.added.general.failure",
exception.getMessage()));
saveMessages(request, messages);
}
return forward;
}
private List<Resource> getResources() throws Exception {
List<Resource> resources = new ArrayList<Resource>();
IResourceBusinessService projectService = (IResourceBusinessService) getBsFactory()
.getFactory().getBean("resourceBS");
resources = projectService.getResources();
return resources;
}
private void clearFormValues(ResourceForm ResourceForm) {
ResourceForm.setName("");
ResourceForm.setCost(0.0);
ResourceForm.setResourceId(null);
ResourceForm.setProject(new Project());
}
private void setFormValues(ResourceForm resourceForm, Resource resource) {
resourceForm.setId(resource.getId());
resourceForm.setResourceId(resource.getResourceId());
resourceForm.setName(resource.getName());
resourceForm.setCost(resource.getCost());
resourceForm.setProject(resource.getProject());
resourceForm.getProject().setId(
resource.getProject().getId());
resourceForm.getProject().setName(
resource.getProject().getName());
}
private void saveValues(ResourceForm resourceForm) throws Exception {
Resource resource = saveFormValues(resourceForm);
logger.info("1a");
IResourceBusinessService resourceService = (IResourceBusinessService) getBsFactory()
.getFactory().getBean("resourceBS");
logger.info("1b");
resourceService.saveResource(resource);
}
private Resource saveFormValues(ResourceForm resourceForm) throws Exception {
logger.info("1c");
Resource resource = new Resource();
logger.info("1d");
if (!resourceForm.getAction().equalsIgnoreCase("add")) {
resource.setId(resourceForm.getId());
}
logger.info("1d");
resource.setResourceId(resourceForm.getResourceId());
logger.info("1e");
resource.setName(resourceForm.getName());
logger.info("1f");
resource.setCost(resourceForm.getCost());
logger.info("1g");
resource.setProject(resourceForm.getProject());
logger.info("1h");
resource.getProject().setId(
resourceForm.getProject().getId());
logger.info("1i");
resource.getProject().setName(
resourceForm.getProject().getName());
logger.info("1j");
return resource;
}
private List<Project> fetchProjects() throws Exception {
List<Project> projects = new ArrayList<Project>();
IProjectBusinessService projectService = (IProjectBusinessService) getBsFactory()
.getFactory().getBean("projectBS");
projects = projectService.getProjects();
return projects;
}
private Resource fetchResource(Long Id) throws Exception {
Resource resource = null;
IResourceBusinessService resourceService = (IResourceBusinessService) getBsFactory()
.getFactory().getBean("resourceBS");
resource = resourceService.getResource(Id);
return resource;
}
}
|
/*
Riley Denoon
SuperString
April 17th 2020
*/
package SuperString;
/**
*
* @author melanie
*/
public class SuperStringFrame extends javax.swing.JPanel {
/**
* Creates new form SuperStringFrame
*/
public SuperStringFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
txtValueEnteredLength = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
btnLength = new javax.swing.JButton();
lblLength = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtEnteredLowercase = new javax.swing.JTextField();
btnToUppercase = new javax.swing.JButton();
lblUppercase = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtEnteredFourth = new javax.swing.JTextField();
btnFourthSpot = new javax.swing.JButton();
lblFourthSpot = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txtFirstNumberEntered = new javax.swing.JTextField();
txtSecondNumberEntered = new javax.swing.JTextField();
btnIdentical = new javax.swing.JButton();
lblIdentical = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
txtString = new javax.swing.JTextField();
txtLetter = new javax.swing.JTextField();
btnLetterFound = new javax.swing.JButton();
lblLetterFound = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
txtStringEntered = new javax.swing.JTextField();
btnFourToSix = new javax.swing.JButton();
lblFourToSix = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
txtStringWithA = new javax.swing.JTextField();
btnAToX = new javax.swing.JButton();
lblAToX = new javax.swing.JLabel();
jTextField1.setText("jTextField1");
txtValueEnteredLength.setText("Type here");
txtValueEnteredLength.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtValueEnteredLengthActionPerformed(evt);
}
});
jLabel1.setText("Super String Software");
btnLength.setText("Find Length");
btnLength.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLengthActionPerformed(evt);
}
});
lblLength.setText(".........");
jLabel2.setText("Enter a string, the program will output the number of characters in the string.");
jLabel3.setText("Enter a string in lowercase, the program will output the characters in all capital letters. ");
txtEnteredLowercase.setText("Type here");
txtEnteredLowercase.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtEnteredLowercaseActionPerformed(evt);
}
});
btnToUppercase.setText("ALL CAPS");
btnToUppercase.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnToUppercaseActionPerformed(evt);
}
});
lblUppercase.setText("........");
jLabel4.setText("Enter a string, the program will output the character at the 4th spot. ");
txtEnteredFourth.setText("Type Here");
btnFourthSpot.setText("Fourth Spot ");
btnFourthSpot.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFourthSpotActionPerformed(evt);
}
});
lblFourthSpot.setText(".........");
jLabel5.setText("Enter two strings, the program will output whether or not they are identical.");
txtFirstNumberEntered.setText("Type Here");
txtSecondNumberEntered.setText("Type Here");
btnIdentical.setText("Identical?");
btnIdentical.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnIdenticalActionPerformed(evt);
}
});
lblIdentical.setText("..........");
jLabel6.setText("Enter a string and a letter, the program will output if the letter is in the string. ");
txtString.setText("String Here");
txtLetter.setText("Letter Here");
btnLetterFound.setText("Letter Found?");
btnLetterFound.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLetterFoundActionPerformed(evt);
}
});
lblLetterFound.setText("..........");
jLabel7.setText("Enter a String that is at least 8 characters long. The program will output characters 4 to 6.");
txtStringEntered.setText("String Here");
btnFourToSix.setText("Char 4 to 6");
btnFourToSix.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFourToSixActionPerformed(evt);
}
});
lblFourToSix.setText(".........");
jLabel8.setText("Enter a string that contains at least one \"a\", the program will replace all of the \"a'''s ");
txtStringWithA.setText("String Here");
btnAToX.setText("Replace \"a\"");
btnAToX.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAToXActionPerformed(evt);
}
});
lblAToX.setText(".........");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(txtString, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtLetter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnLetterFound))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 592, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(txtStringEntered, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(107, 107, 107)
.addComponent(btnFourToSix)))))
.addContainerGap(25, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(txtValueEnteredLength, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(91, 91, 91)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(btnLength)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblLength)
.addGap(63, 63, 63))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(63, 63, 63))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(txtEnteredLowercase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(92, 92, 92)
.addComponent(btnToUppercase)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblUppercase)
.addGap(59, 59, 59))
.addGroup(layout.createSequentialGroup()
.addComponent(txtEnteredFourth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(92, 92, 92)
.addComponent(btnFourthSpot)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblFourthSpot)
.addGap(49, 49, 49))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(txtFirstNumberEntered, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtSecondNumberEntered, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(btnIdentical)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblIdentical))
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblFourToSix)
.addComponent(lblLetterFound))))
.addGap(46, 46, 46))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 514, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 589, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 540, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, 611, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(txtStringWithA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(117, 117, 117)
.addComponent(btnAToX)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblAToX)
.addGap(48, 48, 48))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnLength)
.addComponent(txtValueEnteredLength, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblLength))
.addGap(18, 18, 18)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtEnteredLowercase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnToUppercase)
.addComponent(lblUppercase))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtEnteredFourth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnFourthSpot)
.addComponent(lblFourthSpot))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtFirstNumberEntered, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtSecondNumberEntered, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnIdentical)
.addComponent(lblIdentical))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtString, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtLetter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnLetterFound)
.addComponent(lblLetterFound))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtStringEntered, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnFourToSix)
.addComponent(lblFourToSix))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtStringWithA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnAToX)
.addComponent(lblAToX))
.addContainerGap(52, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void txtValueEnteredLengthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtValueEnteredLengthActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtValueEnteredLengthActionPerformed
private void btnLengthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLengthActionPerformed
//Declare variables
String valueEnteredLength;
int length;
//Use the getText(); function to retrieve the word the user inputs
valueEnteredLength = txtValueEnteredLength.getText();
//Use the method of length(); to find the length of the word the user enters into the text interface
length = valueEnteredLength.length();
//Display the length of the word into lblLength, and use the string value of 'length'
lblLength.setText(String.valueOf(length));
}//GEN-LAST:event_btnLengthActionPerformed
private void btnToUppercaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnToUppercaseActionPerformed
//Declare variables
String enteredLowercase;
String uppercase;
//use the getText(); function to retrieve the word the user inputs
enteredLowercase = txtEnteredLowercase.getText();
//Use the method toUpperCase(); to change the word into all upercase letters.
uppercase = enteredLowercase.toUpperCase();
//Display the length of the word into lblUppercase
lblUppercase.setText(uppercase);
}//GEN-LAST:event_btnToUppercaseActionPerformed
private void txtEnteredLowercaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtEnteredLowercaseActionPerformed
}//GEN-LAST:event_txtEnteredLowercaseActionPerformed
private void btnFourthSpotActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFourthSpotActionPerformed
//Declare Variables
String enteredValueFourth;
int fourthSpot;
//Use the getText(); function to use the word the user inputs.
enteredValueFourth = txtEnteredFourth.getText();
//Use the method charAt(); to find the character at the fourth spot.
fourthSpot = enteredValueFourth.charAt(4);
//Display the fourth character as a string value into lblfourthSpot
lblFourthSpot.setText(String.valueOf(fourthSpot));
}//GEN-LAST:event_btnFourthSpotActionPerformed
private void btnIdenticalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIdenticalActionPerformed
//Declare Variables
String firstNumber;
String secondNumber;
String identical;
//Use the getText(); function to retrieve the words the users input.
firstNumber = txtFirstNumberEntered.getText();
secondNumber = txtSecondNumberEntered.getText();
//use an if statement to determine if both strings are identical using equals
if (firstNumber.equals(secondNumber)) {
identical = "These are identical";
}
else {
identical = "These aren't identical";
}
//Display if the two string are equal by setting lblIdentical to what the answer is given from the if statement.
lblIdentical.setText(identical);
}//GEN-LAST:event_btnIdenticalActionPerformed
private void btnLetterFoundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLetterFoundActionPerformed
//Declare variables
String wordEntered;
String letterEntered;
String inWord;
//Use the getText(); function to retrieve the word and letter form the text box.
wordEntered = txtString.getText();
letterEntered = txtLetter.getText();
//Use an if statement to display if the letter is in the word
if (wordEntered.contains(letterEntered)) {
//if the letter is in the word then inWord changes to 'The letter is in the word'
inWord = "The letter is in the word";
//Set lblLetterFound to display inWord
lblLetterFound.setText(String.valueOf(inWord));
}
else
{
inWord = "The letter is not in the word";
lblLetterFound.setText(String.valueOf(inWord));
}
//Use the contains(); method to determine if the letter is in the word, set as a string value
//inWord = String.valueOf(wordEntered.contains(letterEntered));
//Display the letter contained
//lblLetterFound.setText(String.valueOf(inWord));
}//GEN-LAST:event_btnLetterFoundActionPerformed
private void btnFourToSixActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFourToSixActionPerformed
//Declare variables
String wordInput;
String four;
String five;
String six;
int num4 = 3;
int num5 = 4;
int num6 = 5;
//Use the getText(); function to get the word.
wordInput = txtStringEntered.getText();
//Use the method charAt(); to get the characters at that point.
four = String.valueOf(wordInput.charAt(num4));
five = String.valueOf(wordInput.charAt(num5));
six = String.valueOf(wordInput.charAt(num6));
//set the label to the letters at position 4,5,6.
lblFourToSix.setText(four+five+six);
}//GEN-LAST:event_btnFourToSixActionPerformed
private void btnAToXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAToXActionPerformed
//Decleare variables
String wordEntered;
//Use the getText(); function to get the word.
wordEntered = txtStringWithA.getText();
//Using the replace(); method replace all the a's with x's.
wordEntered = wordEntered.replace("a","x");
//Set the label to the modified word.
lblAToX.setText(wordEntered);
}//GEN-LAST:event_btnAToXActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAToX;
private javax.swing.JButton btnFourToSix;
private javax.swing.JButton btnFourthSpot;
private javax.swing.JButton btnIdentical;
private javax.swing.JButton btnLength;
private javax.swing.JButton btnLetterFound;
private javax.swing.JButton btnToUppercase;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JTextField jTextField1;
private javax.swing.JLabel lblAToX;
private javax.swing.JLabel lblFourToSix;
private javax.swing.JLabel lblFourthSpot;
private javax.swing.JLabel lblIdentical;
private javax.swing.JLabel lblLength;
private javax.swing.JLabel lblLetterFound;
private javax.swing.JLabel lblUppercase;
private javax.swing.JTextField txtEnteredFourth;
private javax.swing.JTextField txtEnteredLowercase;
private javax.swing.JTextField txtFirstNumberEntered;
private javax.swing.JTextField txtLetter;
private javax.swing.JTextField txtSecondNumberEntered;
private javax.swing.JTextField txtString;
private javax.swing.JTextField txtStringEntered;
private javax.swing.JTextField txtStringWithA;
private javax.swing.JTextField txtValueEnteredLength;
// End of variables declaration//GEN-END:variables
}
|
package net.nowtryz.mcutils.command.execution;
import net.nowtryz.mcutils.command.contexts.CompletionContext;
import java.util.List;
public interface Completer extends Execution {
List<String> complete(CompletionContext context);
}
|
package com.pda.pda_android.activity.apps.detail;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.pda.pda_android.R;
import com.pda.pda_android.adapter.ssxx.SsxxDetailAdapter;
import com.pda.pda_android.base.BaseActivity;
import com.pda.pda_android.base.network.LoadCallBack;
import com.pda.pda_android.base.network.OkHttpManager;
import com.pda.pda_android.base.others.ContentUrl;
import com.pda.pda_android.base.utils.LogUtils;
import com.pda.pda_android.bean.FlagBean;
import com.pda.pda_android.bean.LoginBeanFail;
import com.pda.pda_android.bean.SsxxDetailBean;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Response;
/**
* 梁佳霖创建于:2018/10/31 09:33
* 功能:手术信息详情页面
*/
public class SsxxInfomationDetailActivity extends BaseActivity {
private ImageView iv_top_back;
private TextView username_badnum,ops_num,ops_staue,bxbh,ops_name,ops_dj,ops_bm,docter,
yy_time,dj_time,end_time,sq_code,out_ops_time,inpacu_time,outpacu_time,operdiag_after,
mzys_name,mzfs,xhhs_code,sequence_no,oper_roomno,tv_top_sure,ops_time;
private String name,id;
private SsxxDetailBean ssxxBeanListBean;
@Override
public int setLayoutId() {
return R.layout.activity_ssxxinfomationdetail;
}
@Override
public void initView() {
id = getIntent().getStringExtra("id");
name=getIntent().getStringExtra("name");
iv_top_back = findViewById(R.id.iv_top_back);
username_badnum = findViewById(R.id.tv_top_title);
tv_top_sure=findViewById(R.id.tv_top_sure);
ops_num=findViewById(R.id.ops_num);
ops_staue=findViewById(R.id.ops_staue);
bxbh=findViewById(R.id.bxbh);
ops_name=findViewById(R.id.ops_name);
ops_dj=findViewById(R.id.ops_dj);
ops_bm=findViewById(R.id.ops_bm);
docter=findViewById(R.id.docter);
yy_time=findViewById(R.id.yy_time);
dj_time=findViewById(R.id.dj_time);
end_time=findViewById(R.id.end_time);
sq_code=findViewById(R.id.sq_code);
out_ops_time=findViewById(R.id.out_ops_time);
inpacu_time=findViewById(R.id.inpacu_time);
outpacu_time=findViewById(R.id.outpacu_time);
mzfs=findViewById(R.id.mzfs);
mzys_name=findViewById(R.id.mzys_name);
operdiag_after=findViewById(R.id.operdiag_after);
xhhs_code=findViewById(R.id.xhhs_code);
sequence_no=findViewById(R.id.sequence_no);
oper_roomno=findViewById(R.id.oper_roomno);
ops_time=findViewById(R.id.ops_time);
tv_top_sure.setVisibility(View.GONE);
iv_top_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SsxxInfomationDetailActivity.this.finish();
}
});
username_badnum.setText(name);
}
@Override
public void initData() {
PostData();
}
public void PostData(){
Map<String, String> params = new HashMap<>(); //提交数据包
params.put("oper_id", id);
OkHttpManager.getInstance().postRequest(this, ContentUrl.TestUrl_local + ContentUrl.getUsersSsxxDetail, new LoadCallBack<String>(this) {
@Override
protected void onEror(Call call, int statusCode, Exception e) {
super.onEror(call, statusCode, e);
showCenterToastCenter("请求失败,请稍后重试");
}
@Override
protected void onSuccess(Call call, Response response, String s) {
Gson gson = new Gson();
if (s.contains("\"response\": \"ok\"")){
LogUtils.showLog(s.toString());
ssxxBeanListBean=gson.fromJson(s.toString(),SsxxDetailBean.class);
if (null!=ssxxBeanListBean.getData().getOperxh()){
ops_num.setText(ssxxBeanListBean.getData().getOperxh());
}
if (null!=ssxxBeanListBean.getData().getOper_code()){
ops_bm.setText(ssxxBeanListBean.getData().getOper_code());
}
if (null!=ssxxBeanListBean.getData().getOperscale()){
ops_dj.setText(ssxxBeanListBean.getData().getOperscale());
}
if (null!=ssxxBeanListBean.getData().getOper_name()){
ops_name.setText(ssxxBeanListBean.getData().getOper_name());
}
if (null!=ssxxBeanListBean.getData().getOperstate()){
ops_staue.setText(ssxxBeanListBean.getData().getOperstate());
}
if (null!=ssxxBeanListBean.getData().getWard_code()){
bxbh.setText(ssxxBeanListBean.getData().getWard_code());
}
if (null!=ssxxBeanListBean.getData().getSurgeon_name()){
docter.setText(ssxxBeanListBean.getData().getSurgeon_name());
}
if (null!=ssxxBeanListBean.getData().getYytime()){
yy_time.setText(ssxxBeanListBean.getData().getYytime());
}
if (null!=ssxxBeanListBean.getData().getDjtime()){
dj_time.setText(ssxxBeanListBean.getData().getDjtime());
}
if (null!=ssxxBeanListBean.getData().getEndoper_time()){
end_time.setText(ssxxBeanListBean.getData().getEndoper_time());
}
if (null!=ssxxBeanListBean.getData().getHisappform()){
sq_code.setText(ssxxBeanListBean.getData().getHisappform());
}
if (null!=ssxxBeanListBean.getData().getOutoper_time()){
out_ops_time.setText(ssxxBeanListBean.getData().getOutoper_time());
}
if (null!=ssxxBeanListBean.getData().getInpacu_time()){
inpacu_time.setText(ssxxBeanListBean.getData().getInpacu_time());
}
if (null!=ssxxBeanListBean.getData().getOutpacu_time()){
outpacu_time.setText(ssxxBeanListBean.getData().getOutpacu_time());
}
if (null!=ssxxBeanListBean.getData().getMzfs()){
mzfs.setText(ssxxBeanListBean.getData().getMzfs());
}
if (null!=ssxxBeanListBean.getData().getMzys_name()){
mzys_name.setText(ssxxBeanListBean.getData().getMzys_name());
}
if (null!=ssxxBeanListBean.getData().getOperdiag_after()){
operdiag_after.setText(ssxxBeanListBean.getData().getOperdiag_after());
}
if (null!=ssxxBeanListBean.getData().getXhhs_name()){
xhhs_code.setText(ssxxBeanListBean.getData().getXhhs_name());
}
if (null!=ssxxBeanListBean.getData().getSequence_no()){
sequence_no.setText(ssxxBeanListBean.getData().getSequence_no());
}
if (null!=ssxxBeanListBean.getData().getOper_roomno()){
oper_roomno.setText(ssxxBeanListBean.getData().getOper_roomno());
}
if (null!=ssxxBeanListBean.getData().getInoper_time()){
ops_time.setText(ssxxBeanListBean.getData().getInoper_time());
}
}else {
LoginBeanFail loginBeanFail = gson.fromJson(s,LoginBeanFail.class);
showCenterToastCenter(loginBeanFail.getMessage());
}
}
},params);
}
}
|
package me.walkerknapp.cfi.structs;
import com.dslplatform.json.CompiledJson;
import com.dslplatform.json.JsonAttribute;
import java.util.List;
@CompiledJson
public class CMakeFiles implements CFIObject {
@JsonAttribute(mandatory = true)
public Paths paths;
@JsonAttribute(mandatory = true)
public List<Input> inputs;
@CompiledJson
public static class Paths {
@JsonAttribute(mandatory = true)
public String source;
@JsonAttribute(mandatory = true)
public String build;
}
@CompiledJson
public static class Input {
@JsonAttribute(mandatory = true)
public String path;
@JsonAttribute
public boolean isGenerated;
@JsonAttribute
public boolean isExternal;
@JsonAttribute
public boolean isCMake;
}
}
|
package org.squonk.execution.steps.impl;
import org.squonk.types.BasicObject;
import org.squonk.types.TypesUtils;
import org.squonk.execution.steps.AbstractStep;
import org.squonk.execution.steps.StepDefinitionConstants;
import org.squonk.execution.variable.VariableManager;
import org.squonk.types.MoleculeObject;
import org.squonk.dataset.Dataset;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.camel.CamelContext;
/**
* Converts a Dataset<BasicObject> to a Dataset<MoleculeObject>
* given a specified field name that contains the structure. A default name of
* "structure" is used if option is not specified. The field name is handled in
* a case insensitive manner.
*
* NOTE: if a field with that name is not found MoleculeObjects with an empty
* structure is generated.
*
* NOTE: does not perform any validation of the structure - if bad structures
* are present errors will occur later when these are parsed.
*
* NOTE: This step generates a new Stream that contains the functions necessary
* to convert the BasicObjects to the MoleculeObjects and creates a new Dataset
* with that new Stream, but it does NOT call a terminal operation on the Stream
* to actually do the conversions. You are responsible for providing that
* terminal operation on the output Dataset.
*
* @author timbo
*/
public class BasicObjectToMoleculeObjectStep extends AbstractStep {
private static final Logger LOG = Logger.getLogger(BasicObjectToMoleculeObjectStep.class.getName());
public static final String OPTION_STRUCTURE_FIELD_NAME = StepDefinitionConstants.ConvertBasicToMoleculeObject.OPTION_STRUCTURE_FIELD_NAME;
public static final String OPTION_STRUCTURE_FORMAT = StepDefinitionConstants.ConvertBasicToMoleculeObject.OPTION_STRUCTURE_FORMAT;
public static final String OPTION_PRESERVE_UUID = StepDefinitionConstants.ConvertBasicToMoleculeObject.OPTION_PRESERVE_UUID;
public static String DEFAULT_STRUCTURE_FIELD_NAME = "structure";
@Override
public void execute(VariableManager varman, CamelContext context) throws Exception {
statusMessage = MSG_PREPARING_INPUT;
String structureFieldName = getOption(OPTION_STRUCTURE_FIELD_NAME, String.class, DEFAULT_STRUCTURE_FIELD_NAME);
String structureFormat = getOption(OPTION_STRUCTURE_FORMAT, String.class);
boolean preserveUuid = getOption(OPTION_PRESERVE_UUID, Boolean.class, true);
Dataset<BasicObject> input = fetchMappedInput("input", Dataset.class, varman);
if (input == null) {
throw new IllegalStateException("No input found");
} else if (LOG.isLoggable(Level.FINE) && input.getMetadata() != null) {
LOG.fine("Input has " + input.getSize() + " items");
}
statusMessage = "Applying conversions ...";
Dataset<MoleculeObject> results = TypesUtils.convertBasicObjectDatasetToMoleculeObjectDataset(input, structureFieldName, structureFormat, preserveUuid);
createMappedOutput("output", Dataset.class, results, varman);
statusMessage = generateStatusMessage(input.getSize(), results.getSize(), -1);
LOG.info("Results: " + results.getMetadata());
}
}
|
package com.cs.game;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author Omid Alaepour
*/
@Repository
public interface GameRepository extends JpaRepository<Game, String>, QueryDslPredicateExecutor<Game> {
@Query("select g from Game g left join fetch g.gameInfos")
List<Game> findAllWithInfos();
}
|
package com.cinema.common.service;
import java.util.List;
import com.cinema.sys.model.TreeNode;
public interface TreeService {
/**模拟器系统树*/
List<TreeNode> getSimulatorTree(String simulatorId);
/**产品类别树*/
List<TreeNode> getTypeTree(String typeId);
}
|
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.appcloud.provisioning.runtime.test;
import io.fabric8.kubernetes.api.KubernetesHelper;
import io.fabric8.kubernetes.api.model.ContainerBuilder;
import io.fabric8.kubernetes.api.model.ContainerPortBuilder;
import io.fabric8.kubernetes.api.model.IntOrString;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodList;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceBuilder;
import io.fabric8.kubernetes.api.model.ServicePortBuilder;
import io.fabric8.kubernetes.api.model.extensions.Deployment;
import io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder;
import io.fabric8.kubernetes.client.AutoAdaptableKubernetesClient;
import org.wso2.appcloud.provisioning.runtime.Utils.KubernetesProvisioningUtils;
import org.wso2.appcloud.provisioning.runtime.KubernetesPovisioningConstants;
import org.wso2.appcloud.provisioning.runtime.beans.ApplicationContext;
import org.wso2.appcloud.provisioning.runtime.beans.TenantInfo;
import java.util.HashMap;
import java.util.Map;
public class TestUtils {
private ApplicationContext appCtx;
private AutoAdaptableKubernetesClient kube;
public TestUtils() {
setAppCtx(getApplicationContext());
kube = KubernetesProvisioningUtils.getFabric8KubernetesClient();
}
public Namespace createNamespace() {
kube.namespaces().create(KubernetesProvisioningUtils.getNameSpace(getAppCtx()));
return KubernetesProvisioningUtils.getNameSpace(getAppCtx());
}
public void createService() {
Map<String, String> labelsMap = new HashMap<String, String>();
labelsMap.put("app", getAppCtx().getId());
labelsMap.put("version", getAppCtx().getVersion());
Service service = new ServiceBuilder()
.withKind(KubernetesPovisioningConstants.KIND_SERVICE)
.withNewMetadata()
.withName((getAppCtx().getId() + "-" + getAppCtx().getVersion().replace(".","-")).toLowerCase())
.withLabels(labelsMap)
.endMetadata()
.withNewSpec()
.withPorts(
new ServicePortBuilder().withPort(80).withProtocol("TCP").withTargetPort(new IntOrString(8080))
.build())
.withType("NodePort")
.withSelector(labelsMap)
.endSpec()
.build();
kube.services().inNamespace(KubernetesProvisioningUtils.getNameSpace(getAppCtx()).getMetadata().getName())
.create(service);
}
public Deployment createDeployment() {
Map<String, String> labelsMap = new HashMap<String, String>();
labelsMap.put("app", getAppCtx().getId());
labelsMap.put("version", getAppCtx().getVersion());
Deployment deployment = new DeploymentBuilder()
.withKind("Deployment")
.withNewMetadata()
.withName((getAppCtx().getId() + "-" + getAppCtx().getVersion().replace(".","-")).toLowerCase())
.endMetadata()
.withNewSpec()
.withReplicas(2)
.withNewTemplate()
.withNewMetadata()
.withLabels(labelsMap)
.endMetadata()
.withNewSpec()
.withContainers(new ContainerBuilder().withName("tomcat").withImage("tomcat:latest")
.withPorts(new ContainerPortBuilder().withContainerPort(80).build()).build())
.endSpec()
.endTemplate()
.endSpec()
.build();
kube.extensions().deployments()
.inNamespace(KubernetesProvisioningUtils.getNameSpace(getAppCtx()).getMetadata().getName())
.create(deployment);
return deployment;
}
public boolean getPodStatus(Namespace namespace, Map<String, String> selector) {
PodList podss = kube.inNamespace(namespace.getMetadata().getName()).pods().withLabels(selector).list();
if (podss.getItems().size() == 0) {
return false;
} else {
for (Pod pod : podss.getItems()) {
String status = KubernetesHelper.getPodStatusText(pod);
if (!"Running".equals(status)) {
return false;
}
}
}
return true;
}
private ApplicationContext getApplicationContext() {
ApplicationContext applicationCtx = new ApplicationContext();
applicationCtx.setVersion("1.0.0");
TenantInfo tenant = new TenantInfo();
tenant.setTenantId(5);
tenant.setTenantDomain("wso2.org");
applicationCtx.setTenantInfo(tenant);
applicationCtx.setId("My-JAXRS");
return applicationCtx;
}
public void deleteNamespace(){
kube.namespaces().delete(KubernetesProvisioningUtils.getNameSpace(getAppCtx()));
}
public ApplicationContext getAppCtx() {
return appCtx;
}
public void setAppCtx(ApplicationContext appCtx) {
this.appCtx = appCtx;
}
}
|
package com.company;
public class Main {
public static void main(String[] args) {
//Startup operations
boolean directoryCheck = FileHandling.createDirectory();
boolean bootHistoryCheck = FileHandling.createSIHistory();
Menu.mainMenu();
}
}
|
package DSA.udemy.stack;
import DSA.udemy.arrays.MyArray;
public class MyStackArray<E> implements MyStack<E> {
private E top;
private E bottom;
private final MyArray<E> array;
public MyStackArray() {
this.array = new MyArray<>();
}
@Override
public E push(E element) {
if(this.array.length == 0) this.top = this.bottom = element;
this.top = this.array.push(element);
return this.top;
}
@Override
public E pop() {
if(this.array.length == 1) {
this.top = this.bottom = null;
return this.array.pop();
}
E popped = this.array.pop();
this.top = this.array.get(this.array.length - 1);
return popped;
}
@Override
public E peek() {
return this.top;
}
@Override
public int size() {
return this.array.length;
}
@Override
public boolean isEmpty() {
return this.array.length == 0;
}
}
|
package com.cmeTask.InternTask.api;
import com.cmeTask.InternTask.model.RestVisit;
import com.cmeTask.InternTask.model.Visit;
import com.cmeTask.InternTask.service.VisitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RequestMapping("/api/v1/visit")
@RestController
@CrossOrigin("*")
public class VisitController {
private final VisitService visitService;
@Autowired
public VisitController(VisitService visitService) {
this.visitService = visitService;
}
@PostMapping
public void addVisit(@Valid @NonNull @RequestBody Visit visit){
visitService.addVisit(visit);
}
@GetMapping(path = "{id}")
public List<RestVisit> getVisitUser(@PathVariable("id") String person_id){
return visitService.getVisitUser(person_id);
}
}
|
package ru.job4j.ui;
/**
* Класс MenuOutException реализует сущность Исключение "Выход за пределы меню".
*
* @author Goureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 2017-04-24
* @since 2017-04-24
*/
public class MenuOutException extends RuntimeException {
/**
* Конструктор.
* @param msg сообщение об ошибке.
*/
public MenuOutException(String msg) {
super(msg);
}
}
|
package com.gxtc.huchuan.ui.mine.incomedetail.profit.circle;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gxtc.commlibrary.base.BaseRecyclerAdapter;
import com.gxtc.commlibrary.base.BaseTitleFragment;
import com.gxtc.commlibrary.recyclerview.RecyclerView;
import com.gxtc.commlibrary.recyclerview.wrapper.LoadMoreWrapper;
import com.gxtc.commlibrary.utils.GotoUtil;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.adapter.DistributionAdapter;
import com.gxtc.huchuan.bean.DistributionBean;
import com.gxtc.huchuan.bean.DistributionCountBean;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.pop.PopPosition;
import com.gxtc.huchuan.ui.circle.homePage.CircleMainActivity;
import com.gxtc.huchuan.ui.mine.incomedetail.profit.classroom.ProfitContract;
import com.gxtc.huchuan.ui.mine.incomedetail.profit.classroom.ProfitPresenter;
import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity;
import com.gxtc.huchuan.widget.DividerItemDecoration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import cn.carbswang.android.numberpickerview.library.NumberPickerView;
/**
* Describe:圈子分销
* Created by ALing on 2017/5/16 .
*/
public class CircleDistributionFragment extends BaseTitleFragment implements ProfitContract.View, BaseRecyclerAdapter.OnReItemOnClickListener,View.OnClickListener{
@BindView(R.id.rc_list) RecyclerView mRcList;
@BindView(R.id.swipe_layout) SwipeRefreshLayout mSwipeLayout;
private ProfitContract.Presenter mPresenter;
private List<DistributionBean> distributionList;
private String type = "2"; //显示类型。默认1 1:课堂 2:圈子
private DistributionAdapter adapter;
private PopPosition mPopPosition;
private HashMap<String,String> map;
private int dateType; //日期类型。 0:本日,1:本周,2:本月,3:本年,4:全部
private TextView mTvShareCount;
private TextView mTvAllCount;
private TextView mTvDate;
@Override
public View initView(LayoutInflater inflater, ViewGroup container) {
View view = inflater.inflate(R.layout.activity_share_profit_list, container, false);
return view;
}
@Override
public void initData() {
super.initData();
new ProfitPresenter(this);
map = new HashMap<>();
getDistributionCircle();
initRecyclerView();
}
private void getDistributionCircle() {
mPresenter.getDistributionCount(UserManager.getInstance().getToken(),type,dateType+"");
mPresenter.getDistributionList(type,dateType+"",false);
map.put("token",UserManager.getInstance().getToken());
map.put("dateType", String.valueOf(dateType));
map.put("type",type); //1 课堂 2 圈子
map.put("showType","1"); //1 分销 2 圈子
mPresenter.getIncomeStatistics(map);
}
@Override
public void initListener() {
super.initListener();
mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mPresenter.getDistributionCount(UserManager.getInstance().getToken(),type,dateType+"");
mPresenter.getDistributionList(type,dateType+"",true); //刷新重新获取数据
mRcList.reLoadFinish();
}
});
mRcList.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
@Override
public void onLoadMoreRequested() {
mPresenter.loadMoreDistribution(type,dateType+""); //加载更多
}
});
}
private void initRecyclerView() {
mSwipeLayout.setColorSchemeResources(R.color.refresh_color1,
R.color.refresh_color2,
R.color.refresh_color3,
R.color.refresh_color4);
View view =LayoutInflater.from(getActivity()).inflate(R.layout.activity_share_profit_list_header,null);
mTvShareCount = (TextView) view.findViewById(R.id.tv_share_count);
mTvAllCount = (TextView) view.findViewById(R.id.tv_all_count);
mTvDate = (TextView) view.findViewById(R.id.tv_date);
mRcList.addHeadView(view);
mTvDate.setOnClickListener(this);
mRcList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayout.VERTICAL, false));
mRcList.addItemDecoration(new DividerItemDecoration(getActivity(),
DividerItemDecoration.HORIZONTAL_LIST, 20,
getResources().getColor(R.color.module_divide_line)));
mRcList.setLoadMoreView(R.layout.model_footview_loadmore);
distributionList = new ArrayList<>();
adapter = new DistributionAdapter(getActivity(), distributionList, R.layout.item_list_income);
adapter.setOnReItemOnClickListener(this);
mRcList.setAdapter(adapter);
adapter.setOnReItemOnClickListener(new BaseRecyclerAdapter.OnReItemOnClickListener() {
@Override
public void onItemClick(View v, int position) {
if(!TextUtils.isEmpty(adapter.getList().get(position).getId().trim())){
Intent intent = new Intent(getContext(), CircleMainActivity.class);
intent.putExtra("groupId",Integer.parseInt(adapter.getList().get(position).getId()));
startActivity(intent);
}
}
});
}
public void onClick(View view){
switch (view.getId()){
case R.id.tv_date:
showDatePop();
break;
}
}
/**
* 选择时间
*/
private void showDatePop() {
final String[] dateaArr = getResources().getStringArray(R.array.mine_income_detail);
if (mPopPosition == null) {
mPopPosition = new PopPosition(getActivity(), R.layout.pop_ts_position);
if (dateaArr.length != 0){
mPopPosition.setData(dateaArr);
mPopPosition.setTitle("选择日期");
mPopPosition.setOnValueChangeListener(new NumberPickerView.OnValueChangeListener() {
@Override
public void onValueChange(NumberPickerView picker, int oldVal, int newVal) {
mTvDate.setText(dateaArr[newVal]);
dateType = newVal/* + 1*/;
Log.d("dateType", "onValueChange: "+dateType);
getDistributionCircle();
}
});
}
}
mPopPosition.showPopOnRootView(getActivity());
}
@Override
public void tokenOverdue() {
GotoUtil.goToActivity(this, LoginAndRegisteActivity.class);
}
@Override
public void showDistributList(List<DistributionBean> datas) {
mSwipeLayout.setRefreshing(false);
mRcList.notifyChangeData(datas,adapter);
}
@Override
public void showProfitList(List<DistributionBean> datas) {}
@Override
public void showDistributionCount(DistributionCountBean bean) {
mTvShareCount.setText("共有"+bean.getCount()+"条分享记录 佣金总计:");
}
@Override
public void showIncomeStatistics(DistributionCountBean bean) {
mTvAllCount.setText("¥"+bean.getIncomeMoney());
}
@Override
public void showRefreshFinish(List<DistributionBean> datas) {
mRcList.notifyChangeData(datas,adapter);
}
@Override
public void showLoadMoreProfit(List<DistributionBean> datas) {}
@Override
public void showLoadMoreDistribution(List<DistributionBean> datas) {
mRcList.changeData(datas,adapter);
}
@Override
public void showNoMore() {
mRcList.loadFinish();
}
@Override
public void setPresenter(ProfitContract.Presenter presenter) {
this.mPresenter = presenter;
}
@Override
public void showLoad() {
getBaseLoadingView().showLoading();
}
@Override
public void showLoadFinish() {
mSwipeLayout.setRefreshing(false);
getBaseLoadingView().hideLoading();
}
@Override
public void showEmpty() {
mSwipeLayout.setRefreshing(false);
distributionList.removeAll(distributionList);
mRcList.notifyChangeData(distributionList,adapter);
// getBaseEmptyView().showEmptyContent();
}
@Override
public void showReLoad() {
mPresenter.getDistributionList(type,dateType+"",false);
}
@Override
public void showError(String info) {
mSwipeLayout.setRefreshing(false);
getBaseEmptyView().showEmptyContent(info);
}
@Override
public void showNetError() {
getBaseEmptyView().showNetWorkView(new View.OnClickListener() {
@Override
public void onClick(View v) {
showReLoad();
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
mPresenter.destroy();
}
@Override
public void onItemClick(View v, int position) {
}
}
|
package com.example.demo.dominio;
public @interface NoArgsConstrutctor {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.