text
stringlengths 10
2.72M
|
|---|
package com.google.android.libraries.photoeditor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Rect;
import android.util.FloatMath;
import android.util.Log;
import com.google.android.libraries.photoeditor.RenderFilterInterface.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
public class TilesProvider implements DataSource {
private static final String LOG_TAG = "TilesProvider";
private static final int PREVIEW_TEXTURE_MAX_SIZE = 512;
public static final int PREVIEW_TILE_SIZE = 1024;
private static final float STYLE_IMAGE_SIZE = 128.0f;
private static final List<Integer> texturesToClean = new ArrayList();
private boolean isExportTilesProvider;
private final ReentrantLock lock = new ReentrantLock();
private int previewHeight;
private Bitmap previewSourceImage;
private int previewTexture = -1;
private int previewWidth;
private int scaledHeight = 0;
private int scaledWidth = 0;
private Bitmap screenSourceImage;
private Bitmap sourceImage;
private Bitmap styleSourceImage;
private int tileSize;
private final List<Tile> tiles = new ArrayList();
private float zoom = -1.0f;
public TilesProvider(Bitmap sourceImage, Bitmap screenImage, int tileSize, boolean isExportTilesProvider) {
if (sourceImage.getConfig() != Config.ARGB_8888) {
throw new IllegalArgumentException("Invalid source pixel format");
}
this.sourceImage = sourceImage;
this.screenSourceImage = screenImage;
this.isExportTilesProvider = isExportTilesProvider;
this.tileSize = tileSize;
int sourceWidth = sourceImage.getWidth();
int sourceHeight = sourceImage.getHeight();
if (!this.isExportTilesProvider) {
float scale = Math.max(((float) sourceWidth) / 512.0f, ((float) sourceHeight) / 512.0f);
this.previewWidth = Math.min(Math.round(((float) sourceWidth) / scale), PREVIEW_TEXTURE_MAX_SIZE);
this.previewHeight = Math.min(Math.round(((float) sourceHeight) / scale), PREVIEW_TEXTURE_MAX_SIZE);
if (this.previewWidth > sourceWidth) {
this.previewWidth = sourceWidth;
}
if (this.previewHeight > sourceHeight) {
this.previewHeight = sourceHeight;
}
this.previewSourceImage = Bitmap.createBitmap(this.previewWidth, this.previewHeight, Config.ARGB_8888);
NativeCore.scaleImage(this.sourceImage, this.previewSourceImage);
if (this.previewSourceImage == this.sourceImage) {
this.previewSourceImage = this.sourceImage.copy(Config.ARGB_8888, false);
}
}
}
public void cleanup() {
if (!this.isExportTilesProvider) {
if (!(this.previewSourceImage == null || this.previewSourceImage == this.sourceImage || this.previewSourceImage.isRecycled())) {
this.previewSourceImage.recycle();
}
if (!(this.sourceImage == null || this.sourceImage.isRecycled())) {
this.sourceImage.recycle();
}
}
cleanupTiles(false);
cleanupPreviewTexture();
this.previewSourceImage = null;
this.sourceImage = null;
this.styleSourceImage = null;
this.screenSourceImage = null;
}
public void cleanupGL() {
cleanupTiles(true);
cleanupPreviewTexture();
}
private void cleanupPreviewTexture() {
if (this.previewTexture >= 0) {
addTextureToClean(this.previewTexture);
this.previewTexture = -1;
}
}
private void cleanupTiles(boolean cleanTexturesOnly) {
lock();
for (Tile tile : this.tiles) {
tile.deleteTexture();
}
if (!cleanTexturesOnly) {
this.tiles.clear();
this.scaledWidth = 0;
this.scaledHeight = 0;
}
unlock();
}
private Bitmap createStyleImage() {
float scale = Math.max(((float) getPreviewWidth()) / STYLE_IMAGE_SIZE, ((float) getPreviewHeight()) / STYLE_IMAGE_SIZE);
return Bitmap.createScaledBitmap(this.previewSourceImage, Math.round(((float) getPreviewWidth()) / scale), Math.round(((float) getPreviewHeight()) / scale), true);
}
public void lock() {
this.lock.lock();
}
public void unlock() {
this.lock.unlock();
}
public boolean setZoomScale(float zoomScale) {
if (zoomScale > 1.0f) {
zoomScale = 1.0f;
}
return Math.abs(zoomScale - this.zoom) >= 0.001f && setZoomSize(Math.round(((float) this.sourceImage.getWidth()) * zoomScale), Math.round(((float) this.sourceImage.getHeight()) * zoomScale));
}
public boolean setZoomSize(int newScaledWidth, int newScaledHeight) {
if (newScaledWidth == this.scaledWidth && newScaledHeight == this.scaledHeight) {
return false;
}
lock();
cleanupTiles(false);
int imageWidth = this.sourceImage.getWidth();
int imageHeight = this.sourceImage.getHeight();
this.zoom = Math.min(((float) newScaledWidth) / ((float) imageWidth), ((float) newScaledHeight) / ((float) imageHeight));
int xCount = Math.max((int)Math.ceil(((float) newScaledWidth) / ((float) this.tileSize)), 1);
int yCount = Math.max((int) Math.ceil(((float) newScaledHeight) / ((float) this.tileSize)), 1);
int yScaledPos = 0;
int y100Pos = 0;
int sourceTileSize = Math.round(((float) this.tileSize) / this.zoom);
for (int yIndex = 0; yIndex < yCount; yIndex++) {
int xScaledPos = 0;
int x100Pos = 0;
Rect scaledRect = null;
Rect hundredRect = null;
for (int xIndex = 0; xIndex < xCount; xIndex++) {
scaledRect = new Rect(xScaledPos, yScaledPos, this.tileSize + xScaledPos, this.tileSize + yScaledPos);
if (scaledRect.right > newScaledWidth) {
scaledRect.right = scaledRect.left + (newScaledWidth - xScaledPos);
}
if (scaledRect.bottom > newScaledHeight) {
scaledRect.bottom = scaledRect.top + (newScaledHeight - yScaledPos);
}
hundredRect = new Rect(x100Pos, y100Pos, x100Pos + sourceTileSize, y100Pos + sourceTileSize);
if (hundredRect.right > imageWidth) {
hundredRect.right = hundredRect.left + (imageWidth - x100Pos);
}
if (hundredRect.bottom > imageHeight) {
hundredRect.bottom = hundredRect.top + (imageHeight - y100Pos);
}
if (scaledRect.width() <= 0 || scaledRect.height() <= 0) {
throw new IllegalStateException("Invalid scaled tile rectangle");
}
Tile tile = new Tile(hundredRect, scaledRect, xIndex, yIndex);
this.tiles.add(tile);
this.scaledWidth = Math.max(tile.scaledPosition.right, this.scaledWidth);
this.scaledHeight = Math.max(tile.scaledPosition.bottom, this.scaledHeight);
xScaledPos = scaledRect.right;
x100Pos = hundredRect.right;
}
if (scaledRect != null) {
yScaledPos = scaledRect.bottom;
}
if (hundredRect != null) {
y100Pos = hundredRect.bottom;
}
}
unlock();
return true;
}
public float getZoom() {
return this.zoom;
}
public Bitmap getScreenSourceImage() {
return this.screenSourceImage;
}
public Bitmap getSourceImage() {
return this.sourceImage;
}
public void setSourceImage(Bitmap bitmap) {
this.sourceImage = bitmap;
}
public Bitmap getPreviewSourceImage() {
return this.previewSourceImage;
}
public Bitmap getStyleSourceImage() {
if (this.styleSourceImage == null) {
this.styleSourceImage = createStyleImage();
}
return this.styleSourceImage;
}
public int getHundredPercentWidth() {
return this.sourceImage.getWidth();
}
public int getHundredPercentHeight() {
return this.sourceImage.getHeight();
}
public int getScaledWidth() {
return this.scaledWidth;
}
public int getScaledHeight() {
return this.scaledHeight;
}
public int getTileSize() {
return this.tileSize;
}
public int getPreviewWidth() {
return this.previewWidth;
}
public int getPreviewHeight() {
return this.previewHeight;
}
public int getPreviewSrcTexture() {
return this.previewTexture;
}
public void createPreviewTexture() {
if (this.previewTexture < 0) {
this.previewTexture = NativeCore.createRGBX8TextureFromBitmap(9729, 6408, 33071, this.previewSourceImage);
}
}
public boolean needsCreateSourceTextures() {
lock();
boolean texturesNeeded = false;
for (Tile tile : this.tiles) {
if (tile.srcTexture == -1) {
texturesNeeded = true;
break;
}
}
unlock();
return texturesNeeded;
}
public void createSourceTileTextures() {
if (needsCreateSourceTextures()) {
lock();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(this.sourceImage, this.scaledWidth, this.scaledHeight, true);
if (scaledBitmap.getConfig() != Config.ARGB_8888) {
Bitmap newBitmap = scaledBitmap.copy(Config.ARGB_8888, false);
scaledBitmap.recycle();
scaledBitmap = newBitmap;
}
if (this.tiles.size() == 1 && ((Tile) this.tiles.get(0)).getScaledWidth() == this.scaledWidth && ((Tile) this.tiles.get(0)).getScaledHeight() == this.scaledHeight) {
((Tile) this.tiles.get(0)).srcTexture = NativeCore.createRGBX8TextureFromBitmap(9728, 6408, 33071, scaledBitmap);
} else {
for (Tile tile : this.tiles) {
tile.createTexture(scaledBitmap);
}
}
if (scaledBitmap != this.sourceImage) {
scaledBitmap.recycle();
}
unlock();
}
}
public List<Tile> getTiles() {
return this.tiles;
}
public static void addTextureToClean(int texture) {
texturesToClean.add(Integer.valueOf(texture));
}
public static void cleanTexturesToClean() {
for (Integer texture : texturesToClean) {
NativeCore.deleteTexture(texture.intValue());
}
texturesToClean.clear();
}
private void dump() {
Log.v(LOG_TAG, String.format("xxx TilesProvider::dump - zoom:%f xxx", new Object[]{Float.valueOf(this.zoom)}));
Log.v(LOG_TAG, String.format("xxx TilesProvider::dump hundredPercentSize - w:%d h:%d xxx", new Object[]{Integer.valueOf(this.sourceImage.getWidth()), Integer.valueOf(this.sourceImage.getHeight())}));
Log.v(LOG_TAG, String.format("xxx TilesProvider::dump scaledSize - w:%d h:%d xxx", new Object[]{Integer.valueOf(this.scaledWidth), Integer.valueOf(this.scaledHeight)}));
for (Tile tile : this.tiles) {
Log.v(LOG_TAG, String.format("Tile: %d %d", new Object[]{Integer.valueOf(tile.x), Integer.valueOf(tile.y)}));
Log.v(LOG_TAG, String.format("Tile sourcePosition: %d %d %d %d", new Object[]{Integer.valueOf(tile.sourcePosition.left), Integer.valueOf(tile.sourcePosition.top), Integer.valueOf(tile.sourcePosition.width()), Integer.valueOf(tile.sourcePosition.height())}));
Log.v(LOG_TAG, String.format("Tile scaledPosition: %d %d %d %d", new Object[]{Integer.valueOf(tile.scaledPosition.left), Integer.valueOf(tile.scaledPosition.top), Integer.valueOf(tile.scaledPosition.width()), Integer.valueOf(tile.scaledPosition.height())}));
}
}
public static int getExportTileSize(int filterType) {
return filterType == 3 ? PREVIEW_TEXTURE_MAX_SIZE : 1024;
}
}
|
package com.proyecto.kernel.dao.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.reflect.FieldUtils;
import org.apache.commons.lang.reflect.MethodUtils;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.proxy.HibernateProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.proyecto.common.exception.FrameworkTechnicalException;
import com.proyecto.common.search.util.SearchUtil;
import com.proyecto.common.util.ValidateRule;
import com.proyecto.dom.AbstractEntity;
import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.types.CollectionExpression;
import com.mysema.query.types.EntityPath;
import com.mysema.query.types.Path;
import com.mysema.query.types.PathMetadata;
import com.mysema.query.types.PathType;
import com.mysema.query.types.path.CollectionPathBase;
import com.mysema.query.types.path.EntityPathBase;
/**
* Utility class to help the initialization of the Hibernate proxies using JPAQuery or using Hibernate Criteria.
*
*
*/
public final class ProxyResolver {
private static final String UNCHECKED = "unchecked";
private static final String EL_CRITERIA_SOBRE_EL_QUE_SE_VA_A_BUSCAR_NO_PUEDE_SER_NULO = "El criteria sobre el que se va a buscar no puede ser nulo.";
private static final String LA_CLASE_SOBRE_LA_QUE_SE_VA_A_BUSCAR_NO_PUEDE_SER_NULA = "La clase sobre la que se va a buscar no puede ser nula.";
private static Logger logger = LoggerFactory.getLogger(ProxyResolver.class);
/**
* We make this class not instantiable.
*/
private ProxyResolver() {
}
/****************************************************************************************************
* METODOS PARA RESOLVER PROBLEMAS DE PROXIES. *
****************************************************************************************************/
/**
* Metodo que dada una clase, un criteria y unos relationsToFetch devuelve un objeto con los proxies inicializados.
*
* @param persistentClass
* Clase que devolveremos. La utilizaremos para comprobar que tiene algunas de las propiedades que pasamos en los relationsToFetch
* @param relationsToFetch
* Lista de Strings que nos indicara que objetos queremos inicializar. Cada String contendra, separados por puntos, los nombres de los
* atributos de la clase que queremos inicializar en el objeto raiz. Por ejemplo si queremos obtener un objeto de la clase Usuario que
* tiene un atributo de tipo Prefesional denominado profesional, el String que lo iniciario seria "profesional". Si quisieramos
* inicializar un objeto que cuelga de profesional, por ejemplo centro, en lugar de Usuario el String seria "profesional.centro". El
* segundo ejemplo nos iniciaria tanto el profesional como el centro.
* @param criteria
* Criteria sobre el que le indicaremos los objetos a inicializar.
*
* @return T Devolvera el objeto devuelto por el criteria con, los objetos indicados, inicializados.
*/
@SuppressWarnings({ UNCHECKED })
public static <T extends AbstractEntity> T criteriaUniqueResultWithProxiesSolved(final Class<T> persistentClass, final Criteria criteria,
final List<? extends Path<?>> relationsToFetch, final List<String> aliasCreated) {
validateCriteriaUniqueResultWithProxiesSolved(persistentClass, criteria);
final List<String> listaAIniciarConJOIN = getListaRelationsToFetchAIniciarConJOIN(persistentClass, relationsToFetch, false);
final List<String> listaAIniciarConNuevaConsulta = getListaRelationsToFetchAIniciarConNuevaConsulta(persistentClass, relationsToFetch);
agregarRelationsToFetch(criteria, listaAIniciarConJOIN, aliasCreated);
final T resultado = (T) criteria.uniqueResult();
resolverProxyRelations(resultado, listaAIniciarConNuevaConsulta);
return resultado;
}
/**
* Metodo que dada una clase, un criteria y unos relationsToFetch devuelve un objeto con los proxies inicializados.
*
* @param persistentClass
* Clase que devolveremos. La utilizaremos para comprobar que tiene algunas de las propiedades que pasamos en los relationsToFetch
* @param relationsToFetch
* Lista de Strings que nos indicara que objetos queremos inicializar. Cada String contendra, separados por puntos, los nombres de los
* atributos de la clase que queremos inicializar en el objeto raiz. Por ejemplo si queremos obtener un objeto de la clase Usuario que
* tiene un atributo de tipo Prefesional denominado profesional, el String que lo iniciario seria "profesional". Si quisieramos
* inicializar un objeto que cuelga de profesional, por ejemplo centro, en lugar de Usuario el String seria "profesional.centro". El
* segundo ejemplo nos iniciaria tanto el profesional como el centro.
* @param criteria
* Criteria sobre el que le indicaremos los objetos a inicializar.
*
* @return T Devolvera el objeto devuelto por el criteria con, los objetos indicados, inicializados.
*/
public static <T extends AbstractEntity> T criteriaUniqueResultWithProxiesSolved(final Class<T> persistentClass, final Criteria criteria,
final List<? extends Path<?>> relationsToFetch) {
return criteriaUniqueResultWithProxiesSolved(persistentClass, criteria, relationsToFetch, null);
}
/**
* Metodo que dada una clase, un criteria y unos relationsToFetch devuelve una lista de objetos con los proxies inicializados.
*
* @param persistentClass
* Clase de la que devolveremos una lista. La utilizaremos para comprobar que tiene algunas de las propiedades que pasamos en los
* relationsToFetch.
* @param relationsToFetch
* Lista de Strings que nos indicara que objetos queremos inicializar. Cada String contendra, separados por puntos, los nombres de los
* atributos de la clase que queremos inicializar en el objeto raiz. Por ejemplo si queremos obtener un objeto de la clase Usuario que
* tiene un atributo de tipo Prefesional denominado profesional, el String que lo iniciario seria "profesional". Si quisieramos
* inicializar un objeto que cuelga de profesional, por ejemplo centro, en lugar de Usuario el String seria "profesional.centro". El
* segundo ejemplo nos iniciaria tanto el profesional como el centro.
* @param criteria
* Criteria sobre el que le indicaremos los objetos a inicializar.
* @return List<T> Devolvera una lista de objetos devueltos por el criteria con, los objetos indicados, inicializados.
*/
@SuppressWarnings({ UNCHECKED })
public static <T extends AbstractEntity> List<T> criteriaListWithProxiesSolved(final Class<T> persistentClass, final Criteria criteria,
final List<? extends Path<?>> relationsToFetch, final List<String> aliasCreated) {
validateCriteriaListWithProxiesSolved(persistentClass, criteria);
final List<String> listaAIniciarConJOIN = getListaRelationsToFetchAIniciarConJOIN(persistentClass, relationsToFetch, true);
agregarRelationsToFetch(criteria, listaAIniciarConJOIN, aliasCreated);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
return criteria.list();
}
/**
* Metodo que dada una clase, un criteria y unos relationsToFetch devuelve una lista de objetos con los proxies inicializados.
*
* @param persistentClass
* Clase de la que devolveremos una lista. La utilizaremos para comprobar que tiene algunas de las propiedades que pasamos en los
* relationsToFetch.
* @param relationsToFetch
* Lista de Strings que nos indicara que objetos queremos inicializar. Cada String contendra, separados por puntos, los nombres de los
* atributos de la clase que queremos inicializar en el objeto raiz. Por ejemplo si queremos obtener un objeto de la clase Usuario que
* tiene un atributo de tipo Prefesional denominado profesional, el String que lo iniciario seria "profesional". Si quisieramos
* inicializar un objeto que cuelga de profesional, por ejemplo centro, en lugar de Usuario el String seria "profesional.centro". El
* segundo ejemplo nos iniciaria tanto el profesional como el centro.
* @param criteria
* Criteria sobre el que le indicaremos los objetos a inicializar.
* @return List<T> Devolvera una lista de objetos devueltos por el criteria con, los objetos indicados, inicializados.
*/
public static <T extends AbstractEntity> List<T> criteriaListWithProxiesSolved(final Class<T> persistentClass, final Criteria criteria,
final List<? extends Path<?>> relationsToFetch) {
return criteriaListWithProxiesSolved(persistentClass, criteria, relationsToFetch, null);
}
/**
* Comprueba si el objeto pasado como parámetro es de tipo </code>EntityPath</code> o <code>CollectionPathBase</code>
*
* @param fetch
* Object.
*/
private static void validateFetch(final Path<?> fetch) {
final boolean registroValido = (fetch instanceof EntityPath || fetch instanceof CollectionPathBase);
ValidateRule.isTrue(registroValido, "Error: Path no válido", new ArrayList<Object>());
}
/**
* Obtener lista de relaciones a iniciar con JOINs.
*
* @param persistentClass
* .
* @param List
* <Path> relationsToFetch.
* @param Boolean
* forceJoin.
* @return List<String> listaAIniciarConJOIN.
*/
private static <T extends AbstractEntity> List<String> getListaRelationsToFetchAIniciarConJOIN(final Class<T> persistentClass,
final List<? extends Path<?>> relationsToFetch, final Boolean forceJoin) {
final List<String> listaAIniciarConJOIN = new ArrayList<String>();
// Si nos llega un relationsToFetch lo recorremos
if (relationsToFetch != null) {
for (final Path<?> fetch : relationsToFetch) {
validateFetch(fetch);
if (forceJoin || shouldInitializeWithJoin(fetch, persistentClass)) {
final String relacion = SearchUtil.path2HibernateString(fetch);
listaAIniciarConJOIN.add(relacion);
}
}
}
return listaAIniciarConJOIN;
}
private static boolean shouldInitializeWithJoin(final Path<?> fetch, final Class<? extends AbstractEntity> persistentClass) {
boolean initializeWithJoin = false;
validateFetch(fetch);
final String relacion = SearchUtil.path2HibernateString(fetch);
// If the relation is of one of our childs, maybe we must initialize
// with joins or with a new select.
if (relacion.indexOf('.') == -1) {
final Field campoAIniciar = getCampoByNombre(persistentClass, relacion);
// Es un objeto con una relacion 1 a 1 desde mi parte, con
// lo que lo iniciamos con JOIN
if (Collection.class.isAssignableFrom(campoAIniciar.getType())) {
if (logger.isDebugEnabled()) {
logger.debug("This relation " + relacion + ", of type " + campoAIniciar.getType() + " in the object " + persistentClass.getName()
+ " should be initialized with JOIN (should be of type Collection).");
}
initializeWithJoin = true;
}
} else {
// Otherwise if the relation that we would like to initialize
// is not a direct relation with us, we shold be a join
if (logger.isDebugEnabled()) {
logger.debug("This relation " + relacion + ", in the object " + persistentClass.getName()
+ " should be initialized with JOIN due it's not a direct relation.");
}
initializeWithJoin = true;
}
return initializeWithJoin;
}
/**
* Obtener campo por el nombre.
*
* @param AbstractEntity
* persistentClass.
* @param String
* relacion.
* @return Field campoAIniciar.
*/
private static Field getCampoByNombre(final Class<? extends AbstractEntity> persistentClass, final String relacion) {
Field campoAIniciar;
try {
campoAIniciar = persistentClass.getDeclaredField(relacion);
} catch (final SecurityException e) {
final String infoErrorMessage = "Error al obtener el atributo " + relacion + " de la clase " + persistentClass
+ " en el metodo obtenerListasAInicializar";
logger.error(infoErrorMessage, e);
throw new FrameworkTechnicalException(infoErrorMessage, e);
} catch (final NoSuchFieldException e) {
// Segunda oportunidad
campoAIniciar = getInheritedPrivateField(relacion, persistentClass);
if (campoAIniciar == null) {
final String infoErrorMessage = "Error al obtener el atributo " + relacion + " de la clase " + persistentClass
+ " en el metodo obtenerListasAInicializar";
logger.error(infoErrorMessage, e);
throw new FrameworkTechnicalException(infoErrorMessage, e);
}
}
return campoAIniciar;
}
/**
* @param campo
* @param type
* @return campo
*/
private static Field getInheritedPrivateField(final String campo, final Class<? extends AbstractEntity> type) {
Field result = null;
Class<?> i = type;
while (i != null && i != AbstractEntity.class) {
final Field[] declaredFields = i.getDeclaredFields();
final List<Field> asList = Arrays.asList(declaredFields);
for (final Field field : asList) {
if (field.getName().equals(campo)) {
result = field;
break;
}
}
i = i.getSuperclass();
}
return result;
}
/**
* Obtener lista de relaciones para iniciar con nueva consulta.
*
* @param persistentClass
*
* @param relationsToFetch
*
* @return List<String> listaAIniciarConNuevaConsulta.
*/
private static <T extends AbstractEntity> List<String> getListaRelationsToFetchAIniciarConNuevaConsulta(final Class<T> persistentClass,
final List<? extends Path<?>> relationsToFetch) {
final List<String> listaAIniciarConNuevaConsulta = new ArrayList<String>();
// Si nos llega un relationsToFetch lo recorremos
if (relationsToFetch != null) {
for (final Path<?> fetch : relationsToFetch) {
validateFetch(fetch);
if (!shouldInitializeWithJoin(fetch, persistentClass)) {
final String relacion = SearchUtil.path2HibernateString(fetch);
listaAIniciarConNuevaConsulta.add(relacion);
}
}
}
return listaAIniciarConNuevaConsulta;
}
/**
* Incluye la relacion con las entidades que se van a necesitar inmediatamente para resolver la relacion LAZY mediante un JOIN.
*
* @param clazz
* Clase sobre la que vamos a inicializar las propiedades
* @param criteria
* Criteria al que anyadir el fetch mode
* @param listaAIniciarConJOIN
* Lista de propiedades a inicializar con un JOIN
*/
@SuppressWarnings("deprecation")
private static <T extends AbstractEntity> void agregarRelationsToFetch(final Criteria criteria, final List<String> listaAIniciarConJOIN,
final List<String> aliasCreated) {
final Map<String, String> aliases = obtainAliases(listaAIniciarConJOIN, aliasCreated);
// Ahora creamos los alias en el criteria
if (aliases != null) {
for (final Map.Entry<String, String> aliasEntry : aliases.entrySet()) {
final String alias = aliasEntry.getKey();
final String nombreAlias = aliases.get(alias);
criteria.createAlias(alias, nombreAlias, Criteria.LEFT_JOIN);
}
}
}
/**
* We obtain all the aliases for this relationsToFetch
*
* @param listaAIniciarConJOIN
* @return all the aliases for this relationsToFetch
*/
private static Map<String, String> obtainAliases(final List<String> listaAIniciarConJOIN, final List<String> aliasCreated) {
// Map with all the alias needed for the query
final Map<String, String> aliases = new HashMap<String, String>();
if (listaAIniciarConJOIN != null) {
for (final String relationsToFetch : listaAIniciarConJOIN) {
final Collection<String> c = getAliasesFromRelationsToFetch(relationsToFetch);
// Para cada alias necesario para este projection...
if (c != null) {
for (final String alias : c) {
final String nombreAlias = SearchUtil.createAlias(alias);
if (aliasCreated == null || !aliasCreated.contains(alias)) {
aliases.put(alias, nombreAlias);
}
}
}
}
}
return aliases;
}
private static Collection<String> getAliasesFromRelationsToFetch(final String relationsToFetch) {
final StringTokenizer st = new StringTokenizer(relationsToFetch, ".");
final Set<String> aliases = new TreeSet<String>();
String lastAlias = "";
while (st.hasMoreElements()) {
final String alias = (String) st.nextElement();
final String completeAlias = lastAlias + alias;
aliases.add(completeAlias);
lastAlias = SearchUtil.createAlias(completeAlias) + ".";
}
return aliases;
}
/**
* Inicializa los proxies de las propiedades que se indican en el parametro listaAIniciarConNuevaConsulta. La inicializacion la hara con una nueva
* consulta a la BBDD y solo tendra sentido hacerlo asi en caso de recuperar un unico objeto en la consulta.
*
* @param bean
* Objeto con los proxies a inicializar
* @listaAIniciarConNuevaConsulta Lista de Strings con los atributos a inicializar
*/
private static <T extends AbstractEntity> void resolverProxyRelations(final T bean, final List<String> listaAIniciarConNuevaConsulta) {
if (listaAIniciarConNuevaConsulta != null && bean != null) {
// Para cada relacion accedemos a la propiedad que queremos
for (final String relacion : listaAIniciarConNuevaConsulta) {
try {
initializeAndUnproxy(bean, relacion);
} catch (final Exception e) {
logger.error("An exception has ocurred trying to initialize a Hibernate proxy in the ProxyResolver utility. We ignore it.", e);
}
}
}
}
/****************************************************************************************************
* FIN METODOS PARA RESOLVER PROBLEMAS DE PROXIES *
****************************************************************************************************/
/****************************************************************************************************
* METODOS DE VALIDACION *
****************************************************************************************************/
/**
* Metodo que validara que los parametros del metodo criteriaUniqueResultWithProxiesSolved sean correctos
*/
private static <T extends AbstractEntity> void validateCriteriaUniqueResultWithProxiesSolved(final Class<T> persistentClass,
final Criteria criteria) {
Validate.notNull(persistentClass, LA_CLASE_SOBRE_LA_QUE_SE_VA_A_BUSCAR_NO_PUEDE_SER_NULA);
Validate.notNull(criteria, EL_CRITERIA_SOBRE_EL_QUE_SE_VA_A_BUSCAR_NO_PUEDE_SER_NULO);
}
/**
* Metodo que validara que los parametros del metodo criteriaListWithProxiesSolved sean correctos
*/
private static <T extends AbstractEntity> void validateCriteriaListWithProxiesSolved(final Class<T> persistentClass, final Criteria criteria) {
Validate.notNull(persistentClass, LA_CLASE_SOBRE_LA_QUE_SE_VA_A_BUSCAR_NO_PUEDE_SER_NULA);
Validate.notNull(criteria, EL_CRITERIA_SOBRE_EL_QUE_SE_VA_A_BUSCAR_NO_PUEDE_SER_NULO);
}
/**
* Metodo que validara que los parametros del metodo jpaQueryListWithProxiesSolved sean correctos
*/
private static <T extends AbstractEntity> void validateQueryListWithProxiesSolved(final Class<T> persistentClass, final JPAQuery query) {
Validate.notNull(persistentClass, LA_CLASE_SOBRE_LA_QUE_SE_VA_A_BUSCAR_NO_PUEDE_SER_NULA);
Validate.notNull(query, "La JPAQuery sobre la que se va a buscar no puede ser nula.");
}
/**
* Metodo que validara que los parametros del metodo jpaQueryUniqueResultWithProxiesSolved sean correctos
*/
private static <T extends AbstractEntity> void validateQueryUniqueResultWithProxiesSolved(final Class<T> persistentClass, final JPAQuery query) {
Validate.notNull(persistentClass, LA_CLASE_SOBRE_LA_QUE_SE_VA_A_BUSCAR_NO_PUEDE_SER_NULA);
Validate.notNull(query, "a JPAQuery sobre la que se va a buscar no puede ser nula.");
}
/****************************************************************************************************
* FIN METODOS DE VALIDACION *
****************************************************************************************************/
/****************************************************************************************************
* METODOS DE JPAQUERY *
****************************************************************************************************/
/**
* Metodo que dada una clase, un criteria y unos relationsToFetch devuelve una lista de objetos con los proxies inicializados.
*
* @param persistentClass
* Clase de la que devolveremos una lista. La utilizaremos para comprobar que tiene algunas de las propiedades que pasamos en los
* relationsToFetch.
* @param relationsToFetch
* Lista de Strings que nos indicara que objetos queremos inicializar. Cada String contendra, separados por puntos, los nombres de los
* atributos de la clase que queremos inicializar en el objeto raiz. Por ejemplo si queremos obtener un objeto de la clase Usuario que
* tiene un atributo de tipo Prefesional denominado profesional, el String que lo iniciario seria "profesional". Si quisieramos
* inicializar un objeto que cuelga de profesional, por ejemplo centro, en lugar de Usuario el String seria "profesional.centro". El
* segundo ejemplo nos iniciaria tanto el profesional como el centro.
* @param query
* JPAQuery sobre la que le indicaremos los objetos a inicializar.
* @return List<T> Devolvera una lista de objetos devueltos por el criteria con, los objetos indicados, inicializados.
* @throws Exception
*/
@SuppressWarnings({ UNCHECKED })
public static <T extends AbstractEntity> List<T> jpaQueryListWithProxiesSolved(final Class<T> persistentClass, final JPAQuery query,
final List<? extends Path<?>> relationsToFetch, final EntityPathBase<? extends AbstractEntity> entityBase) throws Exception {
validateQueryListWithProxiesSolved(persistentClass, query);
agregarRelationsToFetch(query, relationsToFetch);
return (List<T>) query.distinct().list(entityBase);
}
/**
* Metodo que dada una clase, un criteria y unos relationsToFetch devuelve un objeto con los proxies inicializados.
*
* @param persistentClass
* Clase que devolveremos. La utilizaremos para comprobar que tiene algunas de las propiedades que pasamos en los relationsToFetch
* @param relationsToFetch
* Lista de Strings que nos indicara que objetos queremos inicializar. Cada String contendra, separados por puntos, los nombres de los
* atributos de la clase que queremos inicializar en el objeto raiz. Por ejemplo si queremos obtener un objeto de la clase Usuario que
* tiene un atributo de tipo Prefesional denominado profesional, el String que lo iniciario seria "profesional". Si quisieramos
* inicializar un objeto que cuelga de profesional, por ejemplo centro, en lugar de Usuario el String seria "profesional.centro". El
* segundo ejemplo nos iniciaria tanto el profesional como el centro.
* @param query
* JPAQuery sobre el que le indicaremos los objetos a inicializar.
*
* @return T Devolvera el objeto devuelto por el criteria con, los objetos indicados, inicializados.
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
*/
@SuppressWarnings({ UNCHECKED })
public static <T extends AbstractEntity, P extends Path<?>> T jpaQueryUniqueResultWithProxiesSolved(final Class<T> persistentClass,
final JPAQuery query, final List<P> relationsToFetch, final EntityPathBase<? extends AbstractEntity> entityBase)
throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
validateQueryUniqueResultWithProxiesSolved(persistentClass, query);
final List<P> listaAIniciarConJOIN = getListaEntityPathBaseAIniciarConJOIN(persistentClass, relationsToFetch, false);
final List<String> listaAIniciarConNuevaConsulta = getListaRelationsToFetchAIniciarConNuevaConsulta(persistentClass, relationsToFetch);
agregarRelationsToFetch(query, listaAIniciarConJOIN);
final T resultado = (T) query.uniqueResult(entityBase);
resolverProxyRelations(resultado, listaAIniciarConNuevaConsulta);
return resultado;
}
/**
* Incluye la relacion con las entidades que se van a necesitar inmediatamente para resolver la relacion LAZY mediante un JOIN.
*
* @param query
* JPAQuery al que anyadir el fetch mode
* @param relationsToFetch
* Lista de propiedades a inicializar con un JOIN
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
*/
@SuppressWarnings({ "rawtypes", UNCHECKED })
private static <T extends Path<?>> void agregarRelationsToFetch(final JPAQuery query, final List<T> relationsToFetch)
throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
final Map<String, Path<?>> aliases = (obtainQAliases(relationsToFetch));
// Now we create the alias in the JPAQuery
if (aliases != null) {
for (final Entry<String, Path<?>> aliasEntry : aliases.entrySet()) {
final String strAlias = aliasEntry.getKey();
final T path = (T) aliases.get(strAlias);
final EntityPathBase alias = (EntityPathBase) SearchUtil.obtainAliasedPath(path, strAlias);
if (path instanceof CollectionExpression) {
query.leftJoin((CollectionExpression<?, T>) path, alias).fetch();
} else {
query.leftJoin((EntityPath<T>) path, (EntityPath) alias).fetch();
}
}
}
}
/**
* We obtain all the aliases for this relationsToFetch
*
* @param listaAIniciarConJOIN
* @return all the aliases for this relationsToFetch
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
private static <T extends Path<?>> Map<String, Path<?>> obtainQAliases(final List<T> relationsToFetch) throws InstantiationException,
IllegalAccessException, InvocationTargetException, NoSuchMethodException {
final Map<String, Path<?>> aliases = new TreeMap<String, Path<?>>();
if (relationsToFetch != null) {
for (final Path<?> path : relationsToFetch) {
aliases.putAll(obtainPathAlias(path));
}
}
return aliases;
}
private static Map<String, Path<?>> obtainPathAlias(final Path<?> path) throws InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
validateFetch(path);
// se crea un mapa invertido. (para que no utilice un alias que no se ha
// creado)
final Map<String, Path<?>> aliasesGrouped = new TreeMap<String, Path<?>>(Collections.reverseOrder());
Path<?> pathAux = path;
PathMetadata<?> metadataPath = path.getMetadata();
Path<?> parentPathAux = metadataPath.getParent();
while (metadataPath.getParent() != null) {
if (!PathType.COLLECTION_ANY.equals(metadataPath.getPathType())) {
aliasesGrouped.put(SearchUtil.createAlias(pathAux), obtainAliasedPath(metadataPath, parentPathAux));
}
pathAux = parentPathAux;
metadataPath = pathAux.getMetadata();
parentPathAux = metadataPath.getParent();
}
return aliasesGrouped;
}
private static Path<?> obtainAliasedPath(final PathMetadata<?> metadataPath, final Path<?> parentPathAux) throws IllegalAccessException,
InvocationTargetException, NoSuchMethodException, InstantiationException {
final Path<?> aliasedPath = SearchUtil.obtainAliasedPath(parentPathAux, SearchUtil.createAlias(parentPathAux));
// First we try to access to the field, if this field is null, we access to the method
final String propertyName = metadataPath.getName();
Object aliasedPathAux = FieldUtils.readDeclaredField(aliasedPath, propertyName, true);
if (aliasedPathAux == null) {
aliasedPathAux = MethodUtils.invokeExactMethod(aliasedPath, propertyName, null);
}
return (Path<?>) aliasedPathAux;
}
/**
* Obtener lista <code>EntityPathBase</code> a iniciar con Join's.
*
* @param Class
* <T> persistentClass.
* @param List
* <P>
* relationsToFetch.
* @param Boolean
* forceJoin.
* @return lista entity path base
*/
private static <T extends AbstractEntity, P extends Path<?>> List<P> getListaEntityPathBaseAIniciarConJOIN(final Class<T> persistentClass,
final List<P> relationsToFetch, final Boolean forceJoin) {
final List<P> listaAIniciarConJOIN = new ArrayList<P>();
// Si nos llega un relationsToFetch lo recorremos
if (relationsToFetch != null) {
for (final P fetch : relationsToFetch) {
validateFetch(fetch);
if (forceJoin || shouldInitializeWithJoin(fetch, persistentClass)) {
listaAIniciarConJOIN.add(fetch);
}
}
}
return listaAIniciarConJOIN;
}
/**
* This method force to unproxy a entity
*
* @param bean
* Object contains the relation
* @param relationName
* Name of relation to be initialized
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
*/
private static void initializeAndUnproxy(final Object bean, final String relationName) throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
// Accedemos a la propiedad para que resuelva el proxy
Object proxy = PropertyUtils.getSimpleProperty(bean, relationName);
if (proxy != null) {
// Tratamos de inicializar el proxy
Hibernate.initialize(proxy);
// Si todavia tenemos un objeto del tipo proxy lo inicializamos
if (proxy instanceof HibernateProxy) {
proxy = ((HibernateProxy) proxy).getHibernateLazyInitializer().getImplementation();
// Seteamos el objeto inicilizado
PropertyUtils.setSimpleProperty(bean, relationName, proxy);
}
}
}
/****************************************************************************************************
* FIN METODOS DE JPAQUERY *
****************************************************************************************************/
}
|
package model;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Chamado {
private IntegerProperty remetente = new SimpleIntegerProperty(0);
private IntegerProperty destinatario = new SimpleIntegerProperty(0);
private StringProperty descricao = new SimpleStringProperty("");
private StringProperty urgencia = new SimpleStringProperty("");
private StringProperty dataCriacao = new SimpleStringProperty("");
private IntegerProperty id = new SimpleIntegerProperty(0);
private BooleanProperty status = new SimpleBooleanProperty(false);
private StringProperty statusStr = new SimpleStringProperty("");
private StringProperty remetenteNome = new SimpleStringProperty("");
private StringProperty destinatarioNome = new SimpleStringProperty("");
public final StringProperty descricaoProperty() {
return this.descricao;
}
public final String getDescricao() {
return this.descricaoProperty().get();
}
public final void setDescricao(final String descricao) {
this.descricaoProperty().set(descricao);
}
public final StringProperty urgenciaProperty() {
return this.urgencia;
}
public final String getUrgencia() {
return this.urgenciaProperty().get();
}
public final void setUrgencia(final String urgencia) {
this.urgenciaProperty().set(urgencia);
}
public final StringProperty dataCriacaoProperty() {
return this.dataCriacao;
}
public final String getDataCriacao() {
return this.dataCriacaoProperty().get();
}
public final void setDataCriacao(String date) {
this.dataCriacaoProperty().set(date);
}
public final IntegerProperty idProperty() {
return this.id;
}
public final int getId() {
return this.idProperty().get();
}
public final void setId(final int id) {
this.idProperty().set(id);
}
public final BooleanProperty statusProperty() {
return this.status;
}
public final boolean isStatus() {
return this.statusProperty().get();
}
public final void setStatus(final boolean status) {
this.statusProperty().set(status);
}
public final StringProperty statusStrProperty() {
return this.statusStr;
}
public final String getStatusStr() {
return this.statusStrProperty().get();
}
public final void setStatusStr(final String statusStr) {
this.statusStrProperty().set(statusStr);
}
public Chamado() {
if(!isStatus()) {
setStatusStr("Nao resolvido");
}else {
setStatusStr("Resolvido");
}
//setRemetenteNome(ChamadoModel.buscarNomePorId());
}
public final IntegerProperty remetenteProperty() {
return this.remetente;
}
public final int getRemetente() {
return this.remetenteProperty().get();
}
public final void setRemetente(final int remetente) {
this.remetenteProperty().set(remetente);
}
public final StringProperty remetenteNomeProperty() {
return this.remetenteNome;
}
public final String getRemetenteNome() {
return this.remetenteNomeProperty().get();
}
public final void setRemetenteNome(final String remetenteNome) {
this.remetenteNomeProperty().set(remetenteNome);
}
public final IntegerProperty destinatarioProperty() {
return this.destinatario;
}
public final int getDestinatario() {
return this.destinatarioProperty().get();
}
public final void setDestinatario(final int destinatario) {
this.destinatarioProperty().set(destinatario);
}
public final StringProperty destinatarioNomeProperty() {
return this.destinatarioNome;
}
public final String getDestinatarioNome() {
return this.destinatarioNomeProperty().get();
}
public final void setDestinatarioNome(final String destinatarioNome) {
this.destinatarioNomeProperty().set(destinatarioNome);
}
}
|
package com.zhangdxchn.lib.weixin.bean.menu;
import java.util.ArrayList;
import java.util.List;
public class ComplexButton extends Button {
private List<Button> sub_button;
public List<Button> getSub_button() {
return sub_button;
}
public void addSubButton(Button btn) {
if (sub_button == null) {
sub_button = new ArrayList<Button>();
}
sub_button.add(btn);
}
}
|
package com.xmzj.common.util;
import java.security.Key;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.AesCipherService;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
public class EncryptUtils {
private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
private static String algorithmName = "md5";
private static int hashIterations = 2;
public static String getAlgorithmName() {
return algorithmName;
}
public static int getHashIterations() {
return hashIterations;
}
private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
"e", "f" };
/**
* encode
*
* @param originString
* @return
*/
public static String md5(String originString) {
if (originString != null) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] results = md.digest(originString.getBytes());
String resultString = byteArrayToHexString(results);
return resultString.toLowerCase();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* change the Byte[] to hex string
*
* @param b
* @return
*/
private static String byteArrayToHexString(byte[] b) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
/**
* change a byte to hex string
*
* @param b
* @return
*/
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
/**
* base64进制加密
*
* @param password
* @return
*/
public static String encrytBase64(String password) {
byte[] bytes = password.getBytes();
return Base64.encodeToString(bytes);
}
/**
* base64进制解密
*
* @param cipherText
* @return
*/
public static String decryptBase64(String cipherText) {
return Base64.decodeToString(cipherText);
}
/**
* 16进制加密
*
* @param password
* @return
*/
public static String encrytHex(String password) {
byte[] bytes = password.getBytes();
return Hex.encodeToString(bytes);
}
/**
* 16进制解密
*
* @param cipherText
* @return
*/
public static String decryptHex(String cipherText) {
return new String(Hex.decode(cipherText));
}
public static String generateKey() {
AesCipherService aesCipherService = new AesCipherService();
Key key = aesCipherService.generateNewKey();
return Base64.encodeToString(key.getEncoded());
}
public static Map generatePassword(String password)
{
String salt = randomNumberGenerator.nextBytes().toHex();
String newPassword = generatePassword(password,salt);
Map result = new HashMap();
result.put("salt", salt);
result.put("password", newPassword);
return result;
}
/**
*
* @Title: generatePassword
* @Description: 生成密码
* @param password 密码明文
* @param salt 密码加密的salt
* @return 参数 返回加密后的密码
*/
public static String generatePassword(String password, String salt) {
// 组合username,两次迭代,对密码进行加密
String password_cipherText = new Md5Hash(password, salt, 2).toBase64();
System.out.println("password:" + password_cipherText);
System.out.println("salt:" + salt);
return password_cipherText;
}
public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
this.randomNumberGenerator = randomNumberGenerator;
}
public void setAlgorithmName(String algorithmName) {
this.algorithmName = algorithmName;
}
public void setHashIterations(int hashIterations) {
this.hashIterations = hashIterations;
}
public static String getRanSalt() {
return randomNumberGenerator.nextBytes().toHex();
}
public static void main(String[] args) {
// String password = "admin";
// String cipherText = encrytHex(password);
// System.out.println(password + "hex加密之后的密文是:" + cipherText);
// String decrptPassword = decryptHex(cipherText);
// System.out.println(cipherText + "hex解密之后的密码是:" + decrptPassword);
// String cipherText_base64 = encrytBase64(password);
// System.out.println(password + "base64加密之后的密文是:" + cipherText_base64);
// String decrptPassword_base64 = decryptBase64(cipherText_base64);
// System.out.println(cipherText_base64 + "base64解密之后的密码是:" +
// decrptPassword_base64);
// String h64 = H64.encodeToString(password.getBytes());
// System.out.println(h64);
// String salt = "7road";
// String cipherText_md5 = new Md5Hash(password, salt, 4).toHex();
// System.out.println(password + "通过md5加密之后的密文是:" + cipherText_md5);
// System.out.println(generateKey());
// System.out.println("==========================================================");
// AesCipherService aesCipherService = new AesCipherService();
// aesCipherService.setKeySize(128);
// Key key = aesCipherService.generateNewKey();
// String aes_cipherText = aesCipherService.encrypt(password.getBytes(),
// key.getEncoded()).toHex();
// System.out.println(password + " aes加密的密文是:" + aes_cipherText);
// String aes_mingwen = new String(
// aesCipherService.decrypt(Hex.decode(aes_cipherText),
// key.getEncoded()).getBytes());
// System.out.println(aes_cipherText + " aes解密的明文是:" + aes_mingwen);
}
}
|
package heylichen.leetcode;
import java.util.*;
public class BSTLevelOrder {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return Collections.emptyList();
}
List<List<Integer>> result = init(root);
Queue<TreeNode> queue = new LinkedList();
queue.add(root);
queue.add(null);
int levelIndex = 0;
while (!queue.isEmpty()) {
//process all nodes of the same level
List<Integer> currentLevel = result.get(levelIndex);
while (!queue.isEmpty()) {
TreeNode node = queue.remove();
if (node == null) {
break;
} else {
currentLevel.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
if (queue.isEmpty()) {
break;
}
queue.add(null);
levelIndex++;
}
return result;
}
private List<List<Integer>> init(TreeNode root) {
int height = getTreeHeight(root);
List<List<Integer>> result = new ArrayList<>(height);
for (int i = 0; i < height; i++) {
result.add(new ArrayList<>());
}
return result;
}
private int getTreeHeight(TreeNode node) {
if (node == null) {
return 0;
}
if (node.left == null && node.right == null) {
return 1;
}
int left = getTreeHeight(node.left);
int right = getTreeHeight(node.right);
return 1 + Math.max(left, right);
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.fileimporters;
import net.datacrow.core.modules.DcModule;
import net.datacrow.core.objects.DcObject;
import net.datacrow.core.services.Region;
import net.datacrow.core.services.SearchMode;
import net.datacrow.core.services.plugin.IServer;
/**
* This client can be updated on events and results form a file import process.
*
* @see FileImporter
* @author Robert Jan van der Waals
*/
public interface IFileImportClient {
/**
* Adds a messages.
* @param message
*/
public void addMessage(String message);
/**
* Adds an error.
* @param e
*/
public void addError(Throwable e);
/**
* Sets the expected result count.
* @param max
*/
public void initProgressBar(int max);
/**
* Updates the progress bar to the specified value.
* @param value
*/
public void updateProgressBar(int value);
/**
* Indicates the process has been canceled.
*/
public boolean cancelled();
/**
* Indicates if online services should be used.
*/
public boolean useOnlineServices();
/**
* Indicate the process has finished.
*/
public void finish();
/**
* The used search mode.
* @return The search mode or null.
*/
public SearchMode getSearchMode();
/**
* The used server.
*/
public IServer getServer();
/**
* The used region.
* @return The region or null.
*/
public Region getRegion();
/**
* The container to which the resulted items are added.
* @return A container or null.
*/
public DcObject getDcContainer();
/**
* The storage medium to apply on the resulted items.
* @return A storage medium or null.
*/
public DcObject getStorageMedium();
/**
* The directory usage implementation (free form).
*/
public int getDirectoryUsage();
public DcModule getModule();
}
|
package com.newlec.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.newlec.domain.LoginDTO;
import com.newlec.domain.MemberVO;
import com.newlec.service.UserServiceImpl;
public class LoginProcController implements Controller {
@Override
public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("LoginProcController");
MemberVO memberVO = new MemberVO();
LoginDTO loginDTO = new LoginDTO();
UserServiceImpl userServiceImpl = new UserServiceImpl();
memberVO.setId(request.getParameter("UserName"));
memberVO.setPassword(request.getParameter("Password"));
System.out.println(memberVO.toString());
try {
loginDTO = userServiceImpl.loginUser(memberVO);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("loginDTO.toString():"+loginDTO.toString());
if(null != loginDTO.getUserName()) {
System.out.println("로그인 성공");
HttpSession session = request.getSession(true);
session.setAttribute("loginDTO", loginDTO);
return "sendRedirect:/newlec/index.yjc";
} else {
System.out.println("로그인 실패");
return "dispatcher:/joinus/login.jsp";
}
}
}
|
package services;
import java.util.ArrayList;
import entities.Client;
import entities.Trajet;
public interface IClientService {
public ArrayList<Client> getAllClient();
public void deletedClient(int ClientID);
public void addClient(Client client);
public void updateClient(Client client);
}
|
/*
* 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 util;
/**
* @author Raphaël
**/
public abstract class MoreGenericity
{
public static <T> T checkNullArg(T arg, String fieldName)
{
if(arg == null)
{
throw new IllegalArgumentException(fieldName+" can't be null.");
}
else
{
return arg;
}
}
/*public static <T extends Number> T checkNegArg(T arg, String fieldName)
{
if(arg.doubleValue() < 0)
{
throw new IllegalArgumentException(fieldName+" can't be negative.");
}
else
{
return arg;
}
}*/
public static double checkNegArg(double arg, String fieldName)
{
if(arg < 0)
{
throw new IllegalArgumentException(fieldName+" can't be negative.");
}
else
{
return arg;
}
}
public static int checkNegArg(int arg, String fieldName)
{
if(arg < 0)
{
throw new IllegalArgumentException(fieldName+" can't be negative.");
}
else
{
return arg;
}
}
}
|
package cn.tedu.file;
import java.io.*;
import java.util.Scanner;
//本类用于练习文件复制综合案例
public class TestCopyFile {
public static void main(String[] args) {
//提示并接收用户输入的两个路径
System.out.println("请输入源文件路径:");//--被复制的那个
String f=new Scanner(System.in).nextLine();
System.out.println("请输入新文件路径:");//--复制好的新文件
String t=new Scanner(System.in).nextLine();
//2.调用创建好的自定义方法文成文件复制
// ZFCopy(f,t);//字符流文件的复制
ZJcopy(f,t);//字节流文件的复制
}
private static void ZJcopy(String f, String t) {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
out = new BufferedOutputStream(new FileOutputStream(t));
int b;
while((b=in.read())!=-1){
out.write(b);
}
System.out.println("恭喜您,文件复制成功");
} catch (Exception e) {
System.out.println("很抱歉,文件复制失败");
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void ZFCopy(String f, String t) {
Reader in = null;
Writer out = null;
try {
in=new BufferedReader(new FileReader(f));
out = new BufferedWriter(new FileWriter(t));
int b;
while((b=in.read())!=-1){
out.write(b);
}
System.out.println("恭喜您,文件复制成功");
} catch (Exception e) {
System.out.println("很抱歉,文件复制失败");
e.printStackTrace();
}finally {
/*关流是有顺序的,如果有多个流最后创建的流最先关
* 多条关流语需要各自try-catc*/
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
package com.xh.repairapk;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TextView;
import com.xh.annotation.ViewAnnotation;
import com.xh.base.BaseFragment;
import com.xh.base.BasePluginFragmentActivity;
/**
* @version 创建时间:2017-12-23 下午4:38:58 项目:repairText 包名:com.xh.repairapk
* 文件名:XhFragmentActivity.java 作者:lhl 说明:
*/
@SuppressLint("NewApi")
public class XhFragmentActivity extends BasePluginFragmentActivity {
@Override
protected String layoutName() {
// TODO Auto-generated method stub
return "fragment";
}
@Override
protected int groupId() {
// TODO Auto-generated method stub
return R.id.frame_layout;
}
@Override
protected List<? extends Fragment> fragments() {
// TODO Auto-generated method stub
List<Fragment> fragments = new ArrayList<Fragment>();
fragments.add(new Myfragment());
return fragments;
}
private class Myfragment extends BaseFragment {
@ViewAnnotation(id = R.id.jiemian1, clickMethodName = "jiemian1")
TextView jiemian1;
@ViewAnnotation(id = R.id.jiemian2, clickMethodName = "jiemian2")
TextView jiemian2;
@ViewAnnotation(id = R.id.jiemian3, clickMethodName = "jiemian3")
TextView jiemian3;
@Override
public String layoutName() {
// TODO Auto-generated method stub
return "activity12";
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
private void jiemian1() {
baseActivity.startActivity(new Intent(baseActivity,
XhViewpacage.class));
// Toast.makeText(getActivity(), "jiemian1", 0).show();
}
private void jiemian2() {
// Toast.makeText(getActivity(), "jiemian2", 0).show();
// Picture picture = SVGParser.getSVGFromResource(getResources(),
// R.raw.back).getPicture();
// Drawable drawable = new PictureDrawable(picture);
// Bitmap bitmap = XhImageUtile.drawable2bitmap(drawable,
// jiemian3.getWidth(), jiemian3.getHeight());
// XhLog.e("==",
// "Height=" + bitmap.getHeight() + " Width="
// + bitmap.getWidth());
// jiemian3.setBackground(XhImageUtile.bitmap2drawable(bitmap));
// imageManager
// .loadBackground(
// jiemian3,
// "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1602552054,373587514&fm=27&gp=0.jpg");
}
private void jiemian3() {
// Toast.makeText(getActivity(), "jiemian3", 0).show();
Class cls = null;
try {
cls = Class.forName("com.xh.repairtest.MainActivity");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
if (cls != null)
baseActivity.startActivity(new Intent(baseActivity, cls));
}
}
@Override
protected int color() {
// TODO Auto-generated method stub
return Color.RED;
}
}
|
package com.predix.feedback.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.predix.feedback.dto.FeedbackRequestDto;
import com.predix.feedback.dto.FeedbackResponseDto;
import com.predix.feedback.service.IFeedbackService;
@RestController
@RequestMapping("/feedback")
public class FeedbackController {
@Autowired
IFeedbackService feedbackService;
@RequestMapping(value = "/add",method = RequestMethod.POST,consumes = {"application/JSON"}, produces = {"application/JSON"})
public ResponseEntity<FeedbackResponseDto> addUser(@RequestBody FeedbackRequestDto userFeedback){
if(userFeedback==null || userFeedback.getUserId()==null || userFeedback.getFeedback()==null || StringUtils.isEmpty(userFeedback.getFeedback())) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
FeedbackResponseDto feed = feedbackService.addFeedback(userFeedback);
//feed.setFeedbackResponse("success");
return new ResponseEntity<FeedbackResponseDto>(feed, HttpStatus.OK);
}
}
|
package com.krish.array;
public class FindMultiMissingInSortedArray {
public static void main(String[] args) {
int[] arr = {-3, 0, 1, 2, 3, 4, 5, 6};
for(int value: findMissing(arr)) {
System.out.println(value);
}
}
private static final int[] findMissing(int[] data) {
if (data == null || data.length <= 1) {
return new int[0];
}
int first = data[0];
int last = data[data.length - 1];
int[] missing = new int[last - first - data.length + 1];
int missingCursor = 0;
int expect = first;
for (int value : data) {
while (expect < value) {
missing[missingCursor] = expect;
missingCursor++;
expect++;
}
expect++;
}
return missing;
}
}
|
package com.cts.spring.qualifier;
public interface MessageProcessor {
public void processMessage(String msg);
}
|
package Problem_14502;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
/* 모든 경우의 수에 대해서 BFS 적용 */
class data{
int x;
int y;
public data(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Main {
static int[][] temp;
static int[][] map;
static int[] dx = {0,1,0,-1};
static int[] dy = {1,0,-1,0};
static int M;
static int N;
public static void reset() {
for(int i = 0; i < temp.length; i++) {
for(int j = 0; j <temp[0].length; j++ ) {
map[i][j] = temp[i][j];
}
}
}
public static void bfs() {
data d1, d2, d3;
reset();
int max = Integer.MIN_VALUE;
for(int i1=0; i1<M;i1++) {
for(int j1=0;j1<N;j1++) {
if(map[i1][j1] != 0) continue;
for(int i2=0; i2<M;i2++) {
for(int j2=0;j2<N;j2++) {
if(i1==i2 && j1==j2) continue;
if(map[i2][j2] !=0) continue;
for(int i3=0; i3<M;i3++) {
for(int j3=0;j3<N;j3++) {
// 3 좌표가 다 다르고, 벽이 아닌경우
if(i1==i2 && j1==j2) continue;
if(i1==i3 && j1==j3) continue;
if(i2==i3 && j2==j3) continue;
if(map[i3][j3] !=0) continue;
for(int i = 0; i < M ; i++) {
for(int j = 0; j<N; j++) {
if(map[i][j] == 2) {
// 벽을 세우고, bfs 진행 : 바이러스 퍼짐
map[i1][j1] = 1;
map[i2][j2] = 1;
map[i3][j3] = 1;
Queue<data> q = new LinkedList<data>();
q.add(new data(i,j));
while(!q.isEmpty()) {
data d = q.poll();
for(int k = 0 ; k < 4; k++) {
int x_ = d.x + dx[k];
int y_ = d.y + dy[k];
if( x_<0 || x_>=M || y_<0 || y_>=N) continue;
if(map[x_][y_] == 1 || map[x_][y_] == 2) continue;
q.add(new data(x_,y_));
map[x_][y_] = 2;
}
}
}
}
}
int cnt = 0;
// 안전영역 카운트 : 0은 안전영역, 2는 감염구역
for(int i = 0 ; i < M; i++) {
for(int j = 0 ; j < N; j++) {
if(map[i][j] == 0) cnt++;
}
}
max = Math.max(max, cnt);
reset();
}
}
}
}
}
}
System.out.println(max);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
M = Integer.parseInt(str[0]);
N = Integer.parseInt(str[1]);
temp = new int[M][N];
map = new int[M][N];
for(int i = 0; i < M; i++) {
String s = br.readLine();
for(int j = 0; j <N; j++ ) {
temp[i][j] = s.charAt(2*j) - '0';
}
}
bfs();
}
}
|
/**
* Copyright © Arrow Software 2011
*/
package com.dabis.trimsalon.services;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import com.dabis.trimsalon.dao.IBoekhoudingDao;
import com.dabis.trimsalon.dao.base.IGenericDao;
import com.dabis.trimsalon.beans.Boekhouding;
/**
* @author Tom
*
*/
public class BoekhoudingManager {
static Logger logger = Logger.getLogger(BoekhoudingManager.class);
@SuppressWarnings("rawtypes")
private Map<String,IGenericDao> daos;
public BoekhoudingManager() { }
@SuppressWarnings("rawtypes")
public BoekhoudingManager( Map<String, IGenericDao> daos ) {
this.daos = daos;
}
/**
* Retrieve all Boekhouding from database.
*
* @return
* List of Boekhouding objects
*/
@Transactional(readOnly=true)
public List<Boekhouding> getAllBoekhoudingen() {
logger.info("GetAllBoekhoudingen");
List<Boekhouding> agegroups = ((IBoekhoudingDao)daos.get("BoekhoudingDao")).findAll();
return agegroups;
}
/**
* Retrieve one Boekhouding from database by its id.
*
* @param id
* the id of the Boekhouding to get
* @return
* the Boekhouding object from database
*/
@Transactional(readOnly=true)
public Boekhouding getBoekhoudingById(long id) {
logger.info("GetBoekhoudingById: "+id);
Boekhouding agegroup = ((IBoekhoudingDao)daos.get("BoekhoudingDao")).read(id);
return agegroup;
}
/**
* Add a new Boekhouding to the database.
*
* @param boekhouding
* the Boekhouding object to add to the database
*/
@Transactional
public long createBoekhouding(Boekhouding boekhouding) {
logger.info("CreateBoekhouding");
return ((IBoekhoudingDao)daos.get("BoekhoudingDao")).create(boekhouding);
}
/**
* Update the database with the given Boekhouding object.
*
* @param boekhouding
* the Boekhouding object to be updated
*/
@Transactional
public void updateBoekhouding (Boekhouding boekhouding) {
logger.info("UpdateBoekhouding: Id="+boekhouding.getId());
((IBoekhoudingDao)daos.get("BoekhoudingDao")).update(boekhouding);
}
/**
* Remove the given Boekhouding from the database.
*
* @param agegroup
* the Boekhouding object to be removed
*/
@Transactional
public void deleteBoekhouding (Boekhouding boekhouding) {
logger.info("DeleteBoekhouding: name="+boekhouding.getId());
((IBoekhoudingDao)daos.get("BoekhoudingDao")).delete(boekhouding);
}
}
|
package com.uchain.plugin;
import akka.actor.ActorRef;
import com.uchain.plugin.notifymessage.NotifyMessage;
import java.util.ArrayList;
import java.util.List;
public class Notification {
private List<ActorRef> listeners = new ArrayList<>();
public void register(ActorRef actorRef) {
listeners.add(actorRef);
}
public void send(NotifyMessage notifyMessage, ActorRef sender) {
listeners.forEach(actorRef -> actorRef.tell(notifyMessage, sender));
}
}
|
/*
* Classe amb la informació d'una estació.
*/
package at.project.stations;
public class Station {
private int station_id;
private int num_bikes_available;
private int num_docks_available;
private long last_reported;
private boolean is_charging_station;
private String status;
public Station() {
super();
}
public Station(int station_id, int num_bikes_available, int num_docks_available, long last_reported,
boolean is_charging_station, String status) {
super();
this.station_id = station_id;
this.num_bikes_available = num_bikes_available;
this.num_docks_available = num_docks_available;
this.last_reported = last_reported;
this.is_charging_station = is_charging_station;
this.status = status;
}
public int getStation_id() {
return station_id;
}
public void setStation_id(int station_id) {
this.station_id = station_id;
}
public int getNum_bikes_available() {
return num_bikes_available;
}
public void setNum_bikes_available(int num_bikes_available) {
this.num_bikes_available = num_bikes_available;
}
public int getNum_docks_available() {
return num_docks_available;
}
public void setNum_docks_available(int num_docks_available) {
this.num_docks_available = num_docks_available;
}
public long getLast_reported() {
return last_reported;
}
public void setLast_reported(long last_reported) {
this.last_reported = last_reported;
}
public boolean isIs_charging_station() {
return is_charging_station;
}
public void setIs_charging_station(boolean is_charging_station) {
this.is_charging_station = is_charging_station;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return "Station [station_id=" + station_id + ", num_bikes_available=" + num_bikes_available
+ ", num_docks_available=" + num_docks_available + ", last_reported=" + last_reported
+ ", is_charging_station=" + is_charging_station + ", status=" + status + "]";
}
/*
* Mčtode que torna la informació més important d'una estació:
* id, num_bikes_available i num_docks_available.
*/
public String essentialInfo() {
return "Station Info [ID Estació = " + station_id + ", Bicicletes disponibles = " + num_bikes_available
+ ", Espais disponibles = " + num_docks_available + "]\n";
}
}
|
package com.fudanscetool.springboot.dao;
import com.fudanscetool.springboot.pojo.Stage3;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface Stage3DAO {
@Insert("INSERT INTO stage3 VALUES(#{projectID}, #{size}, #{RELY}, #{DATA}, #{DOCU}, #{CPLX}, #{RUSE}, #{ACAP}, #{AEXP}, #{PCAP}, #{PEXP}, #{LTEX}, #{PCON}, #{TIME}, #{STOR}, #{PVOL}, #{TOOL}, #{SCED}, #{SITE}, #{estimateLoad})")
int insertStage3(Stage3 stage3);
@Select("SELECT * FROM stage3 WHERE projectID=#{projectID}")
Stage3 searchStage3(String projectID);
@Delete("DELETE FROM stage3 WHERE projectID=#{projectID}")
int deleteStage3(String projectID);
@Update("UPDATE stage3 SET size=#{size}, RELY=#{RELY}, DATA=#{DATA}, DOCU=#{DOCU}, CPLX=#{CPLX}, RUSE=#{RUSE}, ACAP=#{ACAP}, AEXP=#{AEXP}, PCAP=#{PCAP}, PEXP=#{PEXP}, LTEX=#{LTEX}, PCON=#{PCON}, TIME=#{TIME}, STOR=#{STOR}, PVOL=#{PVOL}, TOOL=#{TOOL}, SCED=#{SCED}, SITE=#{SITE}, estimateLoad=#{estimateLoad} WHERE projectID=#{projectID}")
int updateStage3(Stage3 stage3);
}
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.captcha.connector;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* reCaptcha pre validation response.
*/
public class CaptchaPreValidationResponse {
private boolean captchaValidationRequired;
private boolean maxFailedLimitReached;
private boolean enableCaptchaForRequestPath;
private Map<String, String> captchaAttributes;
private boolean postValidationRequired;
private List<String> onCaptchaFailRedirectUrls;
private HttpServletRequest wrappedHttpServletRequest;
public boolean isCaptchaValidationRequired() {
return captchaValidationRequired;
}
public void setCaptchaValidationRequired(boolean captchaValidationRequired) {
this.captchaValidationRequired = captchaValidationRequired;
}
public boolean isMaxFailedLimitReached() {
return maxFailedLimitReached;
}
public void setMaxFailedLimitReached(boolean maxFailedLimitReached) {
this.maxFailedLimitReached = maxFailedLimitReached;
}
public boolean isEnableCaptchaForRequestPath() {
return enableCaptchaForRequestPath;
}
public void setEnableCaptchaForRequestPath(boolean enableCaptchaForRequestPath) {
this.enableCaptchaForRequestPath = enableCaptchaForRequestPath;
}
public boolean isPostValidationRequired() {
return postValidationRequired;
}
public void setPostValidationRequired(boolean postValidationRequired) {
this.postValidationRequired = postValidationRequired;
}
public Map<String, String> getCaptchaAttributes() {
if (captchaAttributes == null) {
return Collections.emptyMap();
}
return captchaAttributes;
}
public void setCaptchaAttributes(Map<String, String> captchaAttributes) {
this.captchaAttributes = captchaAttributes;
}
public List<String> getOnCaptchaFailRedirectUrls() {
if (onCaptchaFailRedirectUrls == null) {
return Collections.emptyList();
}
return onCaptchaFailRedirectUrls;
}
public void setOnCaptchaFailRedirectUrls(List<String> onCaptchaFailRedirectUrls) {
this.onCaptchaFailRedirectUrls = onCaptchaFailRedirectUrls;
}
public HttpServletRequest getWrappedHttpServletRequest() {
return wrappedHttpServletRequest;
}
public void setWrappedHttpServletRequest(HttpServletRequest wrappedHttpServletRequest) {
this.wrappedHttpServletRequest = wrappedHttpServletRequest;
}
}
|
package com.cloudinte.modules.xingzhengguanli.entity;
import com.thinkgem.jeesite.modules.sys.entity.User;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import com.thinkgem.jeesite.common.persistence.DataEntity;
import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField;
/**
* 项目支出绩效目标申报Entity
* @author dcl
* @version 2019-12-16
*/
public class EducationProjectPerformance extends DataEntity<EducationProjectPerformance> {
private static final long serialVersionUID = 1L;
private User user; // 申报人id
private String year; // 年份
private String projectName; // 项目名称
private String projectCode; // 主管部门及代码
private String projectUnit; // 实施单位
private String projectCategory; // 项目属性
private String projectCycle; // 项目周期
private Double metaphaseMoney; // 中期资金总额
private Double metaphaseOtherMoney; // 中期其他资金
private Double metaphaseFinanceMoney; // 中期财政拨款
private Double shortTermMoney; // 年度资金总额
private Double shortTermOtherMoney; // 年度其他资金
private Double shortTermFinanceMoney; // 年度财政拨款
private String shortTermFirstTarget; // 一级指标
private String shortTermFirstTargetName; // 一级指标名称
private String metaphaseContent; // 中期目标
private String shortTermContent; // 年度目标
private String shortTermTargetType; // 短期二级指标类型
private String shortTermSecondTargetName; // 短期二级指标名称
private String shortTermThirdTargetName; // 短期三级指标
private String shortTermTargetValue; // 短期三级指标
private String metaphaseTargetType; // 中期二级指标类型
private String metaphaseSecondTargetName; // 中期二级指标名称
private String metaphaseThirdTargetName; // 中期三级指标
private String metaphaseTargetValue; // 中期三级指标
private String quantityUnit; // 单位
//
private String[] ids;
public String[] getIds() {
return ids;
}
public void setIds(String[] ids) {
this.ids = ids;
}
@Override
public void processEmptyArrayParam() {
if (ids != null && ids.length < 1) {
ids = null;
}
}
/**
* 项目支出绩效目标申报
*/
public EducationProjectPerformance() {
super();
}
/**
* 项目支出绩效目标申报
* @param id
*/
public EducationProjectPerformance(String id){
super(id);
}
@NotNull(message="申报人id不能为空")
@ExcelField(title="申报人id", align=2, sort=1 )
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Length(min=0, max=255, message="年份长度必须介于 0 和 255 之间")
@ExcelField(title="年份", align=2, sort=2 )
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
@Length(min=0, max=255, message="项目名称长度必须介于 0 和 255 之间")
@ExcelField(title="项目名称", align=2, sort=3 )
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
@Length(min=0, max=255, message="主管部门及代码长度必须介于 0 和 255 之间")
@ExcelField(title="主管部门及代码", align=2, sort=4 )
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
@Length(min=0, max=255, message="实施单位长度必须介于 0 和 255 之间")
@ExcelField(title="实施单位", align=2, sort=5 )
public String getProjectUnit() {
return projectUnit;
}
public void setProjectUnit(String projectUnit) {
this.projectUnit = projectUnit;
}
@Length(min=0, max=255, message="项目属性长度必须介于 0 和 255 之间")
@ExcelField(title="项目属性", align=2, sort=6 )
public String getProjectCategory() {
return projectCategory;
}
public void setProjectCategory(String projectCategory) {
this.projectCategory = projectCategory;
}
@Length(min=0, max=255, message="项目周期长度必须介于 0 和 255 之间")
@ExcelField(title="项目周期", align=2, sort=7 )
public String getProjectCycle() {
return projectCycle;
}
public void setProjectCycle(String projectCycle) {
this.projectCycle = projectCycle;
}
@ExcelField(title="中期资金总额", align=2, sort=8 )
public Double getMetaphaseMoney() {
return metaphaseMoney;
}
public void setMetaphaseMoney(Double metaphaseMoney) {
this.metaphaseMoney = metaphaseMoney;
}
@ExcelField(title="中期其他资金", align=2, sort=9 )
public Double getMetaphaseOtherMoney() {
return metaphaseOtherMoney;
}
public void setMetaphaseOtherMoney(Double metaphaseOtherMoney) {
this.metaphaseOtherMoney = metaphaseOtherMoney;
}
@ExcelField(title="中期财政拨款", align=2, sort=10 )
public Double getMetaphaseFinanceMoney() {
return metaphaseFinanceMoney;
}
public void setMetaphaseFinanceMoney(Double metaphaseFinanceMoney) {
this.metaphaseFinanceMoney = metaphaseFinanceMoney;
}
@ExcelField(title="年度资金总额", align=2, sort=11 )
public Double getShortTermMoney() {
return shortTermMoney;
}
public void setShortTermMoney(Double shortTermMoney) {
this.shortTermMoney = shortTermMoney;
}
@ExcelField(title="年度其他资金", align=2, sort=12 )
public Double getShortTermOtherMoney() {
return shortTermOtherMoney;
}
public void setShortTermOtherMoney(Double shortTermOtherMoney) {
this.shortTermOtherMoney = shortTermOtherMoney;
}
@ExcelField(title="年度财政拨款", align=2, sort=13 )
public Double getShortTermFinanceMoney() {
return shortTermFinanceMoney;
}
public void setShortTermFinanceMoney(Double shortTermFinanceMoney) {
this.shortTermFinanceMoney = shortTermFinanceMoney;
}
@Length(min=0, max=3, message="一级指标长度必须介于 0 和 3 之间")
@ExcelField(title="一级指标", align=2, sort=14 ,dictType="first_target")
public String getShortTermFirstTarget() {
return shortTermFirstTarget;
}
public void setShortTermFirstTarget(String shortTermFirstTarget) {
this.shortTermFirstTarget = shortTermFirstTarget;
}
@Length(min=0, max=64, message="一级指标名称长度必须介于 0 和 64 之间")
@ExcelField(title="一级指标名称", align=2, sort=15 )
public String getShortTermFirstTargetName() {
return shortTermFirstTargetName;
}
public void setShortTermFirstTargetName(String shortTermFirstTargetName) {
this.shortTermFirstTargetName = shortTermFirstTargetName;
}
@ExcelField(title="中期目标", align=2, sort=16 )
public String getMetaphaseContent() {
return metaphaseContent;
}
public void setMetaphaseContent(String metaphaseContent) {
this.metaphaseContent = metaphaseContent;
}
@ExcelField(title="年度目标", align=2, sort=17 )
public String getShortTermContent() {
return shortTermContent;
}
public void setShortTermContent(String shortTermContent) {
this.shortTermContent = shortTermContent;
}
@Length(min=0, max=3, message="短期二级指标类型长度必须介于 0 和 3 之间")
@ExcelField(title="短期二级指标类型", align=2, sort=18 ,dictType="target_type")
public String getShortTermTargetType() {
return shortTermTargetType;
}
public void setShortTermTargetType(String shortTermTargetType) {
this.shortTermTargetType = shortTermTargetType;
}
@Length(min=0, max=64, message="短期二级指标名称长度必须介于 0 和 64 之间")
@ExcelField(title="短期二级指标名称", align=2, sort=19 )
public String getShortTermSecondTargetName() {
return shortTermSecondTargetName;
}
public void setShortTermSecondTargetName(String shortTermSecondTargetName) {
this.shortTermSecondTargetName = shortTermSecondTargetName;
}
@Length(min=0, max=255, message="短期三级指标长度必须介于 0 和 255 之间")
@ExcelField(title="短期三级指标", align=2, sort=20 )
public String getShortTermThirdTargetName() {
return shortTermThirdTargetName;
}
public void setShortTermThirdTargetName(String shortTermThirdTargetName) {
this.shortTermThirdTargetName = shortTermThirdTargetName;
}
@Length(min=0, max=255, message="短期三级指标长度必须介于 0 和 255 之间")
@ExcelField(title="短期三级指标", align=2, sort=21 )
public String getShortTermTargetValue() {
return shortTermTargetValue;
}
public void setShortTermTargetValue(String shortTermTargetValue) {
this.shortTermTargetValue = shortTermTargetValue;
}
@Length(min=0, max=3, message="中期二级指标类型长度必须介于 0 和 3 之间")
@ExcelField(title="中期二级指标类型", align=2, sort=22 ,dictType="target_type")
public String getMetaphaseTargetType() {
return metaphaseTargetType;
}
public void setMetaphaseTargetType(String metaphaseTargetType) {
this.metaphaseTargetType = metaphaseTargetType;
}
@Length(min=0, max=64, message="中期二级指标名称长度必须介于 0 和 64 之间")
@ExcelField(title="中期二级指标名称", align=2, sort=23 )
public String getMetaphaseSecondTargetName() {
return metaphaseSecondTargetName;
}
public void setMetaphaseSecondTargetName(String metaphaseSecondTargetName) {
this.metaphaseSecondTargetName = metaphaseSecondTargetName;
}
@Length(min=0, max=255, message="中期三级指标长度必须介于 0 和 255 之间")
@ExcelField(title="中期三级指标", align=2, sort=24 )
public String getMetaphaseThirdTargetName() {
return metaphaseThirdTargetName;
}
public void setMetaphaseThirdTargetName(String metaphaseThirdTargetName) {
this.metaphaseThirdTargetName = metaphaseThirdTargetName;
}
@Length(min=0, max=255, message="中期三级指标长度必须介于 0 和 255 之间")
@ExcelField(title="中期三级指标", align=2, sort=25 )
public String getMetaphaseTargetValue() {
return metaphaseTargetValue;
}
public void setMetaphaseTargetValue(String metaphaseTargetValue) {
this.metaphaseTargetValue = metaphaseTargetValue;
}
@Length(min=0, max=255, message="单位长度必须介于 0 和 255 之间")
@ExcelField(title="单位", align=2, sort=26 ,dictType="quantity_unit")
public String getQuantityUnit() {
return quantityUnit;
}
public void setQuantityUnit(String quantityUnit) {
this.quantityUnit = quantityUnit;
}
}
|
package DesignPatterns.AbstractFactoryPattern;
public interface ProductA {
public void aaa();
}
|
package com.rengu.operationsoanagementsuite.Repository;
import com.rengu.operationsoanagementsuite.Entity.DeploymentDesignDetailEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface DeploymentDesignDetailRepository extends JpaRepository<DeploymentDesignDetailEntity, String>, JpaSpecificationExecutor<DeploymentDesignDetailEntity> {
List<DeploymentDesignDetailEntity> findByDeploymentDesignEntityId(String deploymentDesignId);
List<DeploymentDesignDetailEntity> findByDeviceEntityId(String deviceId);
List<DeploymentDesignDetailEntity> findByDeploymentDesignEntityIdAndDeviceEntityId(String deploymentDesignId, String deviceId);
List<DeploymentDesignDetailEntity> findByDeploymentDesignEntityIdAndComponentEntityId(String deploymentDesignId, String componentId);
List<DeploymentDesignDetailEntity> findByDeploymentDesignEntityIdAndDeviceEntityIdAndComponentEntityId(String deploymentDesignId, String deviceId, String componentId);
}
|
package com.beike.action.pay;
import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.beike.action.pay.hessianclient.TrxHessianServiceGateWay;
import com.beike.common.bean.trx.AlipayWapParams;
import com.beike.common.bean.trx.PaymentInfoGeneratorAlipaySecure;
import com.beike.common.bean.trx.PaymentInfoGeneratorAlipayWap;
import com.beike.util.XMapUtil;
/**
* @title: PayCallBackAction.java
* @package com.beike.action.pay
* @description: 支付宝安全支付和WAP支付回调
* @author jianjun.huo
* @date 2012-6-25 下午06:12:46
* @version v1.0
*
*/
@Controller
public class PayCallBackAction
{
private final Log logger = LogFactory.getLog(PayCallBackAction.class);
@Resource(name = "webClient.trxHessianServiceGateWay")
private TrxHessianServiceGateWay trxHessianServiceGateWay;
/**
* 支付宝Wap : 回调接口
*
* @param request
* @param response
* @throws Exception
* @throws Exception
*/
@SuppressWarnings("unchecked")
@RequestMapping("/pay/alipayWapPayCallBackAlipay.do")
public void alipayWapCallbackNotify(HttpServletRequest request, HttpServletResponse response)
{
try
{
logger.info("+++++++Wap++alipayWapCallbackNotify++begin**************************++++++++++++");
boolean verified = false;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// 获得通知参数
Map map = request.getParameterMap();
// 获得通知签名
String sign = (String) ((Object[]) map.get("sign"))[0];
// 获得通知数据
String notify_data = (String) ((Object[]) map.get("notify_data"))[0];
// 验签名
verified = PaymentInfoGeneratorAlipayWap.checkAlipayWapSign(map, sign);
logger.info("++WAP+alipayWapCallbackNotify+++verified=" + verified + "++++++++++++++");
// 获取参数内容
XMapUtil.register(AlipayWapParams.class);
AlipayWapParams alipayWapParams = (AlipayWapParams) XMapUtil.load(new ByteArrayInputStream(notify_data.getBytes("UTF-8")));
String tradeStatus = alipayWapParams.getTradeStatus();
logger.info("++WAP+alipayWapCallbackNotify+++tradeStatus=" + tradeStatus + "++++++++++++++");
// 封装 hessian数据
Map<String, String> sourceMap = new HashMap<String, String>();
sourceMap.put("payRequestId", alipayWapParams.getOutTradeNo());
sourceMap.put("proExternallId", alipayWapParams.getTradeNo());
sourceMap.put("sucTrxAmount", alipayWapParams.getTotalFee());
sourceMap.put("reqChannel", "MC");
// 回调
if (verified && ("TRADE_FINISHED".equals(tradeStatus) || "TRADE_SUCCESS".equals(tradeStatus)))
{
Map<String, String> rspMap = trxHessianServiceGateWay.complateTrx(sourceMap);
if (null != rspMap && "1".equals(rspMap.get("rspCode")))
{
logger.info("++WAP+alipayWapCallbackNotify++++payRequestId:" + alipayWapParams.getOutTradeNo() + "->rspCode:" + rspMap.get("rspCode") + "++++++payBackSuccess+++++");
out.print("success");
}
}
logger.info("++WAP+alipayWapCallbackNotify++++payRequestId:" + alipayWapParams.getOutTradeNo() + "+++verified:" + verified + "++++payBackFailed+++++");
out.flush();
out.close();
logger.error("+++++WAP+alipayWapCallbackNotify++++++END+++++++++++");
} catch (Exception e)
{
logger.debug(e.getMessage());
e.printStackTrace();
}
}
/**
* 支付宝安全支付回调接口
*
* @param request
* @param response
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
@RequestMapping("/pay/alipaySecurePayCallBackAlipay.do")
public void alipaySecureCallbackNotify(HttpServletRequest request, HttpServletResponse response)
{
try
{
logger.info("+++++++MC+alipaySecureCallbackNotify++begin**************************++++++++++++");
boolean verified = false;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// 获得通知参数
Map map = request.getParameterMap();
// 获得通知签名
String sign = (String) ((Object[]) map.get("sign"))[0];
// 获得待验签名的数据
String notify_data = (String) ((Object[]) map.get("notify_data"))[0];
logger.info("++MC+alipaySecureCallbackNotify+++sign=" + sign + "+++notify_data=" + notify_data + "+++++++++++++");
// 验签
verified = PaymentInfoGeneratorAlipaySecure.checkAlipaySecureSign("notify_data=" + notify_data, sign);
logger.info("++MC+alipaySecureCallbackNotify+++verified=" + verified + "++++++++++++++");
// 获取支付宝参数内容
XMapUtil.register(AlipayWapParams.class);
AlipayWapParams alipayWapParams = (AlipayWapParams) XMapUtil.load(new ByteArrayInputStream(notify_data.getBytes("UTF-8")));
String tradeStatus = alipayWapParams.getTradeStatus();
logger.info("++MC+alipaySecureCallbackNotify+++tradeStatus=" + tradeStatus + "++++++++++++++");
// 封装 hessian数据
Map<String, String> sourceMap = new HashMap<String, String>();
sourceMap.put("payRequestId", alipayWapParams.getOutTradeNo());
sourceMap.put("proExternallId", alipayWapParams.getTradeNo());
sourceMap.put("sucTrxAmount", alipayWapParams.getTotalFee());
sourceMap.put("reqChannel", "MC");
logger.info("+MC++alipaySecureCallbackNotify+++payRequestId=" + alipayWapParams.getOutTradeNo() + "+++proExternallId=" + alipayWapParams.getTradeNo() + "+++sucTrxAmount=" + alipayWapParams.getTotalFee() + "++++++++");
// 回调
if (verified && ("TRADE_FINISHED".equals(tradeStatus) || "TRADE_SUCCESS".equals(tradeStatus)))
{
Map<String, String> rspMap = trxHessianServiceGateWay.complateTrx(sourceMap);
if (null != rspMap && "1".equals(rspMap.get("rspCode")))
{
logger.info("++MC+alipaySecurePayCallBackAlipay+payRequestId:" + alipayWapParams.getOutTradeNo() + "->rspCode:" + rspMap.get("rspCode") + "++++++payBackSuccess+++++");
out.print("success");
}
}
logger.info("++MC+alipaySecurePayCallBackAlipay++payRequestId:" + alipayWapParams.getOutTradeNo() + "+++verified:" + verified + "++++++payBackFailed!+++++");
out.flush();
out.close();
logger.info("++++++MC+alipaySecureCallbackNotify++end**************************++++++++++++");
} catch (Exception e)
{
logger.debug(e.getMessage());
e.printStackTrace();
}
}
}
|
package exceptions;
@SuppressWarnings("serial")
public class DBCloseException extends DBException {
}
|
import java.awt.*;
import javax.swing.*;
public class TestSwing1 {
public static void main (String[] arv)
{
JFrame f = new JFrame();
f.setSize (2000, 1000);
f.setVisible(true);
}
}
|
package de.scads.gradoop_service.server;
import de.scads.gradoop_service.server.helper.GraphHelper;
import de.scads.gradoop_service.server.helper.PatternMatchingHelper;
import de.scads.gradoop_service.server.helper.ServiceHelper;
import de.scads.gradoop_service.server.helper.filtering.FilteringHelper;
import de.scads.gradoop_service.server.helper.linking.LinkingHelper;
import org.gradoop.common.model.impl.pojo.Edge;
import org.gradoop.flink.io.impl.json.JSONDataSource;
import org.gradoop.flink.model.api.epgm.LogicalGraph;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import java.util.List;
public class PatterMatchTest {
String pattern= "{\r\n\t\"types\": [\r\n\t\t{\r\n\t\t\t\"uri\": \"Person\",\r\n\t\t\t\"id\": \"5\",\r\n\t\t\t\"included\": true,\r\n\t\t\t\"propFilter\": [\r\n\t\t\t\t{\r\n\t\t\t\t\t\"prop\": \"name\",\r\n\t\t\t\t\t\"comparison\": \"equal\",\r\n\t\t\t\t\t\"value\": \"Eve\"\r\n\t\t\t\t}\r\n\t\t\t]\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"uri\": \"Tag\",\r\n\t\t\t\"id\": \"4\",\r\n\t\t\t\"included\": false,\r\n\t\t\t\"propFilter\": [\r\n\t\t\t\t{\r\n\t\t\t\t\t\"prop\": \"name\",\r\n\t\t\t\t\t\"comparison\": \"equal\",\r\n\t\t\t\t\t\"value\": \"Databases\"\r\n\t\t\t\t}\r\n\t\t\t]\r\n\t\t}\r\n\t],\r\n\t\"edges\": [\r\n\t\t{\r\n\t\t\t\"auri\": \"Person\",\r\n\t\t\t\"uri\": \"hasInterest\",\r\n\t\t\t\"buri\": \"Tag\"\r\n\t\t}\r\n\t]\r\n}\r\n";
@Test
public void test() throws Exception {
ServiceHelper.getConfig().getExecutionEnvironment().setParallelism(1);
String file = PatterMatchTest.class.getResource("/data/testdata").getFile();
JSONDataSource source = new JSONDataSource(file, ServiceHelper.getConfig());
LogicalGraph graph = source.getLogicalGraph();
LogicalGraph result= PatternMatchingHelper.runPatternMatching(graph, pattern);
System.out.println( result.getVertices().count());
}
/**
* Test with comparision
*/
String pattern2 = "{\r\n\t\"types\": [\r\n\t\t{\r\n\t\t\t\"uri\": \"Person\",\r\n\t\t\t\"id\": \"1\",\r\n\t\t\t\"included\": true,\r\n\t\t\t\"propFilter\": [\r\n\t\t\t\t{\r\n\t\t\t\t\t\"prop\": \"age\",\r\n\t\t\t\t\t\"comparison\": \"expression\",\r\n\t\t\t\t\t\"value\": \">10\"\r\n\t\t\t\t}\r\n\t\t\t]\r\n\t\t}\r\n\t],\r\n\t\"edges\": []\r\n}";
@Test
public void testComparison() throws Exception {
ServiceHelper.setLocalExecution();
ServiceHelper.getConfig().getExecutionEnvironment().setParallelism(1);
String file = PatterMatchTest.class.getResource("/data/testdata").getFile();
JSONDataSource source = new JSONDataSource(file, ServiceHelper.getConfig());
LogicalGraph graph = source.getLogicalGraph();
LogicalGraph result= PatternMatchingHelper.runPatternMatching(graph, pattern2);
System.out.println( result.getVertices().count());
}
String pattern3="{\r\n\t\"types\": [\r\n\t\t{\r\n\t\t\t\"uri\": \"Person\",\r\n\t\t\t\"id\": \"1\",\r\n\t\t\t\"included\": true,\r\n\t\t\t\"propFilter\": [\r\n\t\t\t\t{\r\n\t\t\t\t\t\"prop\": \"age\",\r\n\t\t\t\t\t\"comparison\": \"expression\",\r\n\t\t\t\t\t\"value\": \">=10\"\r\n\t\t\t\t}\r\n\t\t\t]\r\n\t\t}\r\n\t],\r\n\t\"edges\": []\r\n}";
@Test
public void testComparisonGreaterEqual() throws Exception {
ServiceHelper.setLocalExecution();
ServiceHelper.getConfig().getExecutionEnvironment().setParallelism(1);
String file = PatterMatchTest.class.getResource("/data/testdata").getFile();
JSONDataSource source = new JSONDataSource(file, ServiceHelper.getConfig());
LogicalGraph graph = source.getLogicalGraph();
LogicalGraph result= PatternMatchingHelper.runPatternMatching(graph, pattern3);
System.out.println( result.getVertices().count());
}
/**
* multiple attributes..
*/
String pattern4="{\r\n\t\"types\": [\r\n\t\t{\r\n\t\t\t\"uri\": \"Person\",\r\n\t\t\t\"id\": \"3\",\r\n\t\t\t\"included\": true,\r\n\t\t\t\"propFilter\": [\r\n\t\t\t\t{\r\n\t\t\t\t\t\"prop\": \"age\",\r\n\t\t\t\t\t\"comparison\": \"expression\",\r\n\t\t\t\t\t\"value\": \">21\"\r\n\t\t\t\t},\r\n\t\t\t\t{\r\n\t\t\t\t\t\"prop\": \"gender\",\r\n\t\t\t\t\t\"comparison\": \"equal\",\r\n\t\t\t\t\t\"value\": \"f\"\r\n\t\t\t\t}\r\n\t\t\t]\r\n\t\t}\r\n\t],\r\n\t\"edges\": []\r\n}";
@Test
public void testComparisoMulitpleAttributes() throws Exception {
ServiceHelper.setLocalExecution();
ServiceHelper.getConfig().getExecutionEnvironment().setParallelism(1);
String file = PatterMatchTest.class.getResource("/data/testdata").getFile();
JSONDataSource source = new JSONDataSource(file, ServiceHelper.getConfig());
LogicalGraph graph = source.getLogicalGraph();
LogicalGraph result= PatternMatchingHelper.runPatternMatching(graph, pattern4);
long resultCount = result.getVertices().count();
assertTrue(resultCount==2);
System.out.println( resultCount);
}
@Test
public void testCypherExecute() throws Exception{
ServiceHelper.getConfig().getExecutionEnvironment().setParallelism(1);
String file = PatterMatchTest.class.getResource("/data/testdata").getFile();
JSONDataSource source = new JSONDataSource(file, ServiceHelper.getConfig());
LogicalGraph graph = source.getLogicalGraph();
String query= "MATCH (Person:Person)-[:hasInterest]->(Tag:Tag) (Forum:Forum)-[:hasTag]->(Tag:Tag) WHERE Person.name=\"Eve\"";
LogicalGraph result= PatternMatchingHelper.runCyperQuery(graph, query);
System.out.println( result.getVertices().count());
}
}
|
package fileOperations;
import java.io.File;
public class FileOperations {
/* Class used to define Special File/DIrectory Related Operations */
public static boolean exists(String path) {
File justChecking = new File(path);
return justChecking.exists();
}
}
|
package me.matyyy.score.basic.utils;
import java.util.ArrayList;
import java.util.List;
import me.matyyy.score.basic.SuserBoard;
public class UtilsSboard {
public static List<SuserBoard> boards = new ArrayList<>();
public static List<SuserBoard> getBoards() {
return new ArrayList<SuserBoard>(boards);
}
public static void add(SuserBoard b) {
if(!boards.contains(b)) boards.add(b);
}
public static void remove(SuserBoard b) {
if(boards.contains(b)) boards.remove(b);
}
}
|
/*
* 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 fourinline;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
/**
*
* @author alex
*/
public class GUI2 extends javax.swing.JFrame
{
static Sender2 s;
static int[][] board = new int[6][7];
/**
* Creates new form GUI
*/
public GUI2()
{
initComponents();
setBoard();
try
{
Listener2 l = new Listener2("gui2", 8882);
l.start();
} catch (SocketException ex)
{
Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnknownHostException ex)
{
Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* 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()
{
jButtonNewGame = new javax.swing.JButton();
jButtonCancel = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jButton0 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
menuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
openMenuItem = new javax.swing.JMenuItem();
saveMenuItem = new javax.swing.JMenuItem();
saveAsMenuItem = new javax.swing.JMenuItem();
exitMenuItem = new javax.swing.JMenuItem();
editMenu = new javax.swing.JMenu();
cutMenuItem = new javax.swing.JMenuItem();
copyMenuItem = new javax.swing.JMenuItem();
pasteMenuItem = new javax.swing.JMenuItem();
deleteMenuItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
contentsMenuItem = new javax.swing.JMenuItem();
aboutMenuItem = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("GUI2");
setMaximumSize(new java.awt.Dimension(425, 560));
setMinimumSize(new java.awt.Dimension(425, 560));
setPreferredSize(new java.awt.Dimension(425, 560));
jButtonNewGame.setBackground(new java.awt.Color(102, 204, 255));
jButtonNewGame.setText("New Game");
jButtonNewGame.setToolTipText("");
jButtonNewGame.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButtonNewGameActionPerformed(evt);
}
});
jButtonCancel.setBackground(new java.awt.Color(102, 204, 255));
jButtonCancel.setText("Cancel");
jButtonCancel.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButtonCancelActionPerformed(evt);
}
});
GUI2.jPanel2.setVisible(false);
jButton0.setBackground(new java.awt.Color(102, 204, 255));
jButton0.setText("0");
jButton0.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton0ActionPerformed(evt);
}
});
jButton1.setBackground(new java.awt.Color(102, 204, 255));
jButton1.setText("1");
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton1ActionPerformed(evt);
}
});
jButton2.setBackground(new java.awt.Color(102, 204, 255));
jButton2.setText("2");
jButton2.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton2ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(102, 204, 255));
jButton3.setText("3");
jButton3.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton3ActionPerformed(evt);
}
});
jButton4.setBackground(new java.awt.Color(102, 204, 255));
jButton4.setText("4");
jButton4.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton4ActionPerformed(evt);
}
});
jButton5.setBackground(new java.awt.Color(102, 204, 255));
jButton5.setText("5");
jButton5.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton5ActionPerformed(evt);
}
});
jButton6.setBackground(new java.awt.Color(102, 204, 255));
jButton6.setText("6");
jButton6.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton6ActionPerformed(evt);
}
});
jPanel1.setBackground(new java.awt.Color(102, 204, 255));
jPanel1.setForeground(new java.awt.Color(255, 153, 153));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 323, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 310, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jButton0)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton6)))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton0)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4)
.addComponent(jButton5)
.addComponent(jButton6))
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
fileMenu.setMnemonic('f');
fileMenu.setText("File");
openMenuItem.setMnemonic('o');
openMenuItem.setText("Open");
fileMenu.add(openMenuItem);
saveMenuItem.setMnemonic('s');
saveMenuItem.setText("Save");
fileMenu.add(saveMenuItem);
saveAsMenuItem.setMnemonic('a');
saveAsMenuItem.setText("Save As ...");
saveAsMenuItem.setDisplayedMnemonicIndex(5);
fileMenu.add(saveAsMenuItem);
exitMenuItem.setMnemonic('x');
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
exitMenuItemActionPerformed(evt);
}
});
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
editMenu.setMnemonic('e');
editMenu.setText("Edit");
cutMenuItem.setMnemonic('t');
cutMenuItem.setText("Cut");
editMenu.add(cutMenuItem);
copyMenuItem.setMnemonic('y');
copyMenuItem.setText("Copy");
editMenu.add(copyMenuItem);
pasteMenuItem.setMnemonic('p');
pasteMenuItem.setText("Paste");
editMenu.add(pasteMenuItem);
deleteMenuItem.setMnemonic('d');
deleteMenuItem.setText("Delete");
editMenu.add(deleteMenuItem);
menuBar.add(editMenu);
helpMenu.setMnemonic('h');
helpMenu.setText("Help");
contentsMenuItem.setMnemonic('c');
contentsMenuItem.setText("Contents");
helpMenu.add(contentsMenuItem);
aboutMenuItem.setMnemonic('a');
aboutMenuItem.setText("About");
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jButtonNewGame)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(57, 57, 57))
.addGroup(layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(37, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonCancel)
.addComponent(jButtonNewGame))
.addContainerGap(35, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
System.exit(0);
}//GEN-LAST:event_exitMenuItemActionPerformed
private void jButton0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton0ActionPerformed
// TODO add your handling code here:
setX(0, 2);
sendMove(0);
setInactiveBtns(false);
}//GEN-LAST:event_jButton0ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
setX(1, 2);
sendMove(1);
setInactiveBtns(false);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButtonNewGameActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonNewGameActionPerformed
{//GEN-HEADEREND:event_jButtonNewGameActionPerformed
// TODO add your handling code here:
Sender2 s = null;
try
{
s = new Sender2("setX in gui1", "NewGame", 8881);
} catch (SocketException ex)
{
Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnknownHostException ex)
{
Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
}
s.start();
}//GEN-LAST:event_jButtonNewGameActionPerformed
private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonCancelActionPerformed
{//GEN-HEADEREND:event_jButtonCancelActionPerformed
// TODO add your handling code here:
Sender2 s = null;
try
{
s = new Sender2("setX in gui1", "EndGame", 8881);
} catch (SocketException ex)
{
Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnknownHostException ex)
{
Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
}
s.start();
System.exit(0);
}//GEN-LAST:event_jButtonCancelActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton2ActionPerformed
{//GEN-HEADEREND:event_jButton2ActionPerformed
// TODO add your handling code here:
setX(2, 2);
sendMove(2);
setInactiveBtns(false);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton3ActionPerformed
{//GEN-HEADEREND:event_jButton3ActionPerformed
// TODO add your handling code here:
setX(3, 2);
sendMove(3);
setInactiveBtns(false);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton4ActionPerformed
{//GEN-HEADEREND:event_jButton4ActionPerformed
// TODO add your handling code here:
setX(4, 2);
sendMove(4);
setInactiveBtns(false);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton5ActionPerformed
{//GEN-HEADEREND:event_jButton5ActionPerformed
// TODO add your handling code here:
setX(5, 2);
sendMove(5);
setInactiveBtns(false);
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton6ActionPerformed
{//GEN-HEADEREND:event_jButton6ActionPerformed
// TODO add your handling code here:
setX(6, 2);
sendMove(6);
setInactiveBtns(false);
}//GEN-LAST:event_jButton6ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(GUI2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(GUI2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(GUI2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(GUI2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new GUI2().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem aboutMenuItem;
private javax.swing.JMenuItem contentsMenuItem;
private javax.swing.JMenuItem copyMenuItem;
private javax.swing.JMenuItem cutMenuItem;
private javax.swing.JMenuItem deleteMenuItem;
private javax.swing.JMenu editMenu;
private javax.swing.JMenuItem exitMenuItem;
private javax.swing.JMenu fileMenu;
private javax.swing.JMenu helpMenu;
private static javax.swing.JButton jButton0;
private static javax.swing.JButton jButton1;
private static javax.swing.JButton jButton2;
private static javax.swing.JButton jButton3;
private static javax.swing.JButton jButton4;
private static javax.swing.JButton jButton5;
private static javax.swing.JButton jButton6;
private javax.swing.JButton jButtonCancel;
private javax.swing.JButton jButtonNewGame;
private static javax.swing.JPanel jPanel1;
public static javax.swing.JPanel jPanel2;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenuItem openMenuItem;
private javax.swing.JMenuItem pasteMenuItem;
private javax.swing.JMenuItem saveAsMenuItem;
private javax.swing.JMenuItem saveMenuItem;
// End of variables declaration//GEN-END:variables
public static void setBoard()
{
jPanel1.setLayout(new GridLayout(6, 7));
jPanel1.setSize(new Dimension(323, 303));
for (int i = 0; i < board.length; i++)
{
int[] board1 = board[i];
for (int j = 0; j < board1.length; j++)
{
int c = board1[j];
JLabel jl;
jl = new JLabel(" 0 ");
jl.setFont(new java.awt.Font("Tahoma", 0, 38));
jPanel1.add(jl);
board[i][j] = 0;
}
}
}
public static void setX(int col, int player)
{
boolean somebodyWon = false;
boolean isColumnFull = true;
for (int i = board.length - 1; i >= 0; i--)
{
if (board[i][col] == 0)
{
board[i][col] = player;
isColumnFull = false;
if (checkWin(i, col, player))
{
try
{
s = new Sender2("Winner in gui2", "Player2 won!", 8881);
s.start();
JOptionPane.showMessageDialog(GUI2.getWindows()[0], "Congratulations! You won! :D");
GUI2.jPanel2.setVisible(false);
somebodyWon = true;
} catch (SocketException ex)
{
Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnknownHostException ex)
{
Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
}
}
break;
}
}
if (isColumnFull)
{
JOptionPane.showMessageDialog(GUI2.getWindows()[0], "That column is full. Another must be chosen!");
} else
{
updateBoardGUI();
if (somebodyWon == false)
{
if (checkIfIsFull(board))
{
try
{
s = new Sender2("Board is full", "NoWinner", 8881);
} catch (SocketException ex)
{
Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnknownHostException ex)
{
Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
}
s.start();
JOptionPane.showMessageDialog(GUI2.getWindows()[0], "Board is full, nobody won.");
GUI2.jPanel2.setVisible(false);
}
}
}
}
private static boolean checkIfIsFull(int[][] board)
{
for (int i = 0; i < board.length; i++)
{
int[] board1 = board[i];
for (int j = 0; j < board1.length; j++)
{
if (board1[j] == 0)
{
return false;
}
}
}
return true;
}
private static void sendMove(int col)
{
try
{
s = new Sender2("setX in gui2", " " + col, 8881);
s.start();
} catch (Exception ex)
{
Logger.getLogger(GUI2.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void updateBoardGUI()
{
jPanel1.removeAll();
jPanel1.setLayout(new GridLayout(6, 7));
jPanel1.setSize(new Dimension(323, 303));
for (int i = 0; i < board.length; i++)
{
int[] board1 = board[i];
for (int j = 0; j < board1.length; j++)
{
int c = board1[j];
JLabel jl = new JLabel(" " + c + " ");
jl.setFont(new java.awt.Font("Tahoma", 0, 38));
jPanel1.add(jl);
}
}
jPanel1.setVisible(false);
jPanel1.setVisible(true);
}
private static boolean checkWin(int R, int C, int player)
{
// diagonal (NW --> SE)
if (checkFour(R - 3, R + 4, C - 3, C + 4, player))
{
return true;
} else // diagonal (SW --> NE)
if (checkFour(R + 3, R - 4, C - 3, C + 4, player))
{
return true;
} else // straight across (W --> E)
if (checkFour(R, R, C - 3, C + 4, player))
{
return true;
} else // straight down (N --> S)
if (checkFour(R - 3, R + 4, C, C, player))
{
return true;
}
return false;
}
private static boolean checkFour(int startRow, int endRow, int startCol, int endCol,
int player)
{
int rowStep = (startRow > endRow ? -1 : (startRow < endRow ? 1 : 0));
int colStep = (startCol > endCol ? -1 : (startCol < endCol ? 1 : 0));
int count = 0;
int row = startRow;
int col = startCol;
for (; row != endRow || col != endCol; row += rowStep, col += colStep)
{
// check bounds
if (row < 0 || col < 0 || row >= 6 || col >= 7)
{
continue;
}
if (board[row][col] == player)
{
count++; // counting the continuous player pieces
} else
{
count = 0; // discontinuous sequence -- must reset count
}
if (count == 4)
{
break; // four-in-a-row found
}
}
return (count == 4);
}
public static void setInactiveBtns(boolean inactive)
{
jButton0.setEnabled(inactive);
jButton1.setEnabled(inactive);
jButton2.setEnabled(inactive);
jButton3.setEnabled(inactive);
jButton4.setEnabled(inactive);
jButton5.setEnabled(inactive);
jButton6.setEnabled(inactive);
}
}
|
package vnfoss2010.smartshop.serverside.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vnfoss2010.smartshop.serverside.database.entity.UserInfo;
import vnfoss2010.smartshop.serverside.test.SampleDataNghia;
public class AccountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doGet(req, resp);
process(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doPost(req, resp);
doRegister(req, resp);
// process(req, resp);
}
private void process(HttpServletRequest req, HttpServletResponse resp) throws IOException{
PrintWriter out = resp.getWriter();
out.print("Hello");
out.close();
}
private void doRegister(HttpServletRequest req, HttpServletResponse resp) {
//String username, String password, String firstName,
// String lastName, String phone, String email, Date birthday,
// String address, double lat, double lng
ArrayList<UserInfo> userInfos = SampleDataNghia.getSampleListUserInfos();
try {
resp.getWriter().print("In do register");
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package main;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.awt.CardLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import Utility.Utility;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Inventory extends JFrame {
/**
*
*/
private static final long serialVersionUID = 3035309723810078113L;
private JPanel contentPane,userMainPagePane;
private JPanel infoPanel;
private JTextField uName;
private JPasswordField pswrd;
private JPanel loginPanel;
private String first_name;
private String last_name;
private Connection connect = null;
private Statement statement = null;
private ResultSet resultSet = null;
private JPanel registerPanel, forgotUsernamePanel;
private JPanel mainPane;
private CardLayout cl = new CardLayout();
private UserMainPage mainPage = null;
private String dbQuery;
private String username;
private String psswd;
/**
* Create the frame.
*/
public Inventory(MainInventory m) {
this.dbQuery = m.getDBQuery();
this.username = m.getDBUsername();
this.psswd = m.getDBPassword();
mainPane = new JPanel();
contentPane = new JPanel();
userMainPagePane = new JPanel();
connect = Utility.makeDBConnection(dbQuery,username,psswd);
setTitle("Microbial Matrix Inventory Tracker");
setSize(1024, 768);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 703, 396);
mainPane.setLayout(cl);
setLoginPane();
setUserMainPage(userMainPagePane);
setContentPane(mainPane);
mainPane.add(contentPane, "login");
mainPane.add(userMainPagePane,"user");
cl.show(mainPane, "login");
}
/**
*
*/
private void setLoginPane() {
contentPane.setLayout(new GridLayout(3, 1));
infoPanel = new JPanel();
infoPanel.setLayout(new GridLayout(2, 2));
infoPanel.setBorder(new TitledBorder("Login"));
contentPane.add(infoPanel);
infoPanel.add(new JLabel("Username"));
uName = new JTextField();
infoPanel.add(uName);
uName.setColumns(10);
JLabel lblNewLabel = new JLabel("Password");
infoPanel.add(lblNewLabel);
pswrd = new JPasswordField();
infoPanel.add(pswrd);
pswrd.setColumns(10);
loginPanel = new JPanel();
loginPanel.setLayout(new GridLayout(1, 2));
contentPane.add(loginPanel);
JButton loginB = new JButton("Login");
loginB.addActionListener(new ActionListener() {
@SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent arg0) {
if (checkLogin(uName.getText(), pswrd.getText())) {
JOptionPane.showMessageDialog(contentPane, "Welcome "
+ first_name + " " + last_name + "!");
mainPage.setUserDetail(uName.getText(),first_name,last_name,pswrd.getText());
cl.show(mainPane, "user");
} else {
JOptionPane.showMessageDialog(contentPane,
"Invalid login and password");
}
}
});
JButton registerB = new JButton("Register Account");
registerPanel = new JPanel();
registerPanel.setLayout(new GridLayout(5, 2));
final JTextField newUName = new JTextField();
newUName.setColumns(10);
final JTextField newPswrd = new JTextField();
newPswrd.setColumns(10);
final JTextField newFName = new JTextField();
newFName.setColumns(10);
final JTextField newLName = new JTextField();
newLName.setColumns(10);
final JTextField newEmail = new JTextField();
newEmail.setColumns(50);
registerPanel.add(new JLabel("Enter Username"));
registerPanel.add(newUName);
registerPanel.add(new JLabel("Enter Password"));
registerPanel.add(newPswrd);
registerPanel.add(new JLabel("Enter First Name"));
registerPanel.add(newFName);
registerPanel.add(new JLabel("Enter Last Name"));
registerPanel.add(newLName);
registerPanel.add(new JLabel("Enter email id"));
registerPanel.add(newEmail);
registerB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int result = JOptionPane.showConfirmDialog(null, registerPanel,
"Please enter your information",
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
addNewUser(newUName.getText(), newPswrd.getText(),
newFName.getText(), newLName.getText(),
newEmail.getText());
}
}
});
forgotUsernamePanel = new JPanel();
forgotUsernamePanel.setLayout(new GridLayout(5, 2));
final JTextField emailAdd = new JTextField();
emailAdd.setColumns(10);
final JTextField firstName = new JTextField();
firstName.setColumns(10);
final JTextField lastName = new JTextField();
lastName.setColumns(10);
forgotUsernamePanel.add(new JLabel("Enter email address"));
forgotUsernamePanel.add(emailAdd);
forgotUsernamePanel.add(new JLabel("Enter First Name"));
forgotUsernamePanel.add(firstName);
forgotUsernamePanel.add(new JLabel("Enter Last Name"));
forgotUsernamePanel.add(lastName);
JButton forgotB = new JButton("Forgot username/password");
forgotB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int result = JOptionPane.showConfirmDialog(null,
forgotUsernamePanel, "Forgot username or password",
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
getLogonInfo(forgotUsernamePanel, firstName.getText(),
lastName.getText(), emailAdd.getText());
}
}
});
loginPanel.add(loginB);
loginPanel.add(registerB);
loginPanel.add(forgotB);
}
private boolean checkLogin(String uName, String pswrd) {
try {
statement = connect.createStatement();
resultSet = statement
.executeQuery("select count(*) as rowcount, firstname,lastname from login where username=\""
+ uName + "\" and password = \"" + pswrd + "\"");
int count = 0;
if (resultSet.next()) {
count = resultSet.getInt("rowcount");
first_name = resultSet.getString("firstname");
last_name = resultSet.getString("lastname");
}
return !(count == 0);
} catch (SQLException e) {
MainInventory.logger.severe(e.getMessage());
}
return false;
}
private void addNewUser(String uName, String pswrd, String fName,
String lName, String email) {
PreparedStatement preparedStatement;
try {
preparedStatement = connect
.prepareStatement("insert into inventory.login values (default, ?, ?, ?, ? , ?)");
preparedStatement.setString(1, uName);
preparedStatement.setString(2, pswrd);
preparedStatement.setString(3, email);
preparedStatement.setString(4, fName);
preparedStatement.setString(5, lName);
preparedStatement.executeUpdate();
} catch (SQLException e) {
MainInventory.logger.severe(e.getMessage());
}
}
private void getLogonInfo(JPanel panel, String fName, String lName,
String email) {
try {
statement = connect.createStatement();
resultSet = statement
.executeQuery("select username,password from login where firstname=\""
+ fName
+ "\" and lastname = \""
+ lName
+ "\" and email = \"" + email + "\";");
String uName = "";
String pswrd = "";
if (resultSet.next()) {
uName = resultSet.getString("username");
pswrd = resultSet.getString("password");
}
if (uName.isEmpty()) {
JOptionPane.showMessageDialog(panel,
"Sorry we couldn't find you in the system");
} else {
JOptionPane.showMessageDialog(panel, "Your username is:"
+ uName + " and your password is:" + pswrd);
}
} catch (SQLException e) {
MainInventory.logger.severe(e.getMessage());
}
}
private void setUserMainPage(JPanel userMainPage){
mainPage = new UserMainPage(userMainPage,connect,this);
}
public void resetDetails(){
cl.show(mainPane, "login");
uName.setText("");
pswrd.setText("");
}
}
|
package gina.nikol.qnr.demo.dao;
import java.util.List;
import gina.nikol.qnr.demo.entity.Location;
public interface LocationDAO {
public List<Location> getLocations();
public Location getLocation(int locId);
}
|
package com.javarush.task.task05.task0507;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
/*
Среднее арифметическое
*/
public class Solution {
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
Reader reader = new InputStreamReader(inputStream);
BufferedReader bf = new BufferedReader(reader);
int sum = 0;
double count = 0;
while(true){
String s = bf.readLine();
int number = Integer.parseInt(s);
if(number == -1){
break;
}
sum += number;
count++;
}
System.out.println(sum / count);
}
}
|
package com.example.gauravbharti.garagebluetooth;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by gauravbharti on 11/03/17.
*/
public class BluetoothAddressAdapter extends BaseAdapter{
ArrayList<Details> detailsArrayList=new ArrayList<Details>();
Context context;
SharedPreferences pref;
LayoutInflater layoutInflater;
MainActivity mainActivity;
edit_passwordFragment edit_passwordFragments;
String connected_address;
public BluetoothAddressAdapter(Context context,ArrayList<Details> detailsArrayList,String connected_address)
{ super();
this.context=context;
layoutInflater=LayoutInflater.from(context);
this.detailsArrayList=detailsArrayList;
this.connected_address=connected_address;
}
@Override
public int getCount() {
return this.detailsArrayList.size();
}
@Override
public Object getItem(int position) {
return detailsArrayList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{ if(convertView == null)
{ convertView=layoutInflater.inflate(R.layout.bluetooth_card,parent,false);
}
final Details details=this.detailsArrayList.get(position);
mainActivity=(MainActivity) GarageBluetoothApplication.getInstance().getCurrentActivity();
TextView name=(TextView)convertView.findViewById(R.id.name);
TextView type=(TextView)convertView.findViewById(R.id.type);
TextView password=(TextView)convertView.findViewById(R.id.password);
TextView address=(TextView)convertView.findViewById(R.id.address);
name.setText(details.getName());
type.setText(details.getType());
password.setText(details.getPassword());
address.setText(details.getAddress());
((ImageButton)convertView.findViewById(R.id.password_edit_btn)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pref = PreferenceManager.getDefaultSharedPreferences(mainActivity.getApplicationContext());
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
try
{ jsonArray=new JSONArray(pref.getString("current","[]"));
jsonObject=jsonArray.getJSONObject(0);
if(jsonObject.getString("address").equals(details.getAddress()))
{ edit_passwordFragments=edit_passwordFragment.newInstance(details.getPassword(),details.getAddress(),details.getName());
mainActivity.switchFragment(edit_passwordFragments);
}
else
{ Toast.makeText(mainActivity,"Not Connected to this device",Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{ Toast.makeText(mainActivity,"Not Connected to this device",Toast.LENGTH_SHORT).show();
}
}
});
return convertView;
}
}
|
package io.github.henryssondaniel.teacup.engine.junit;
import io.github.henryssondaniel.teacup.engine.Executor;
import io.github.henryssondaniel.teacup.engine.ExecutorFactory;
enum ExecutorHolder {
;
private static final Executor EXECUTOR = ExecutorFactory.create();
static Executor getExecutor() {
return EXECUTOR;
}
}
|
package ru.job4j.array;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class CheckArrayCharTest {
@Test
public void whenLookForHellInWordHelloThanFind() {
CheckArrayChar check = new CheckArrayChar();
boolean result = check.contains("Hello", "Hell");
assertThat(result, is(true));
}
@Test
public void whenLookForDenceInWordDancingThanNotFind() {
CheckArrayChar check = new CheckArrayChar();
boolean result = check.contains("Dancing", "Dence");
assertThat(result, is(false));
}
}
|
package cl.cehd.ocr.algorithm.usecase;
import cl.cehd.ocr.algorithm.entity.AccountDigit;
import cl.cehd.ocr.algorithm.entity.IndividualDigitIdentifier;
import java.util.List;
import java.util.stream.Collectors;
public class AccountNumberIdentifier {
private final IndividualDigitIdentifier individualDigitIdentifier;
public AccountNumberIdentifier(IndividualDigitIdentifier individualDigitIdentifier) {
this.individualDigitIdentifier = individualDigitIdentifier;
}
public String identifyAccountNumber(List<AccountDigit> accountDigits) {
return accountDigits
.stream()
.map(individualDigitIdentifier::readDigitValue)
.collect(Collectors.joining());
}
}
|
import java.util.Arrays;
import java.util.List;
public class UnsuportedException {
public static void main(String[] args) {
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
List<String> flowerList = Arrays.asList(flowers);
flowerList.add("Celosia");
}
}
|
package com.example.holdempub;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
public class TradePage extends AppCompatActivity {
RecyclerView tradeRc;
TradeRecyclerAdapter tradeAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trade_page);
init();
initDB();
}
void init(){
tradeRc = findViewById(R.id.tradeRc);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
tradeRc.setLayoutManager(linearLayoutManager);
tradeAdapter = new TradeRecyclerAdapter();
tradeRc.setAdapter(tradeAdapter);
}
public void initDB(){
Trade trade1 = new Trade("jsw7027", "KSOP 팔아요", "KSOP", 100000, 1, "직거래");
Trade trade2 = new Trade("jsw7027", "BPP 팔아요", "BPP", 120000, 1, "직거래");
Trade trade3 = new Trade("jsw7027", "HPL 팔아요", "HPL", 80000, 1, "직거래");
Trade trade4 = new Trade("jsw7027", "APL 팔아요", "APL", 90000, 1, "직거래");
tradeAdapter.addItem(trade1);
tradeAdapter.addItem(trade2);
tradeAdapter.addItem(trade3);
tradeAdapter.addItem(trade4);
}
}
|
package com.gmail.filoghost.holographicdisplays.commands.main;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import com.gmail.filoghost.holographicdisplays.HolographicDisplays;
import com.gmail.filoghost.holographicdisplays.commands.Colors;
import com.gmail.filoghost.holographicdisplays.commands.Strings;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.AddlineCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.AlignCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.CopyCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.CreateCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.DeleteCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.EditCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.FixCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.HelpCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.InfoCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.InsertlineCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.ListCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.MovehereCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.NearCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.ReadimageCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.ReadtextCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.ReloadCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.RemovelineCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.SetlineCommand;
import com.gmail.filoghost.holographicdisplays.commands.main.subs.TeleportCommand;
import com.gmail.filoghost.holographicdisplays.exception.CommandException;
import com.gmail.filoghost.holographicdisplays.util.Utils;
public class HologramsCommandHandler implements CommandExecutor {
private List<HologramSubCommand> subCommands;
public HologramsCommandHandler() {
subCommands = Utils.newList();
registerSubCommand(new AddlineCommand());
registerSubCommand(new CreateCommand());
registerSubCommand(new DeleteCommand());
registerSubCommand(new EditCommand(this));
registerSubCommand(new ListCommand());
registerSubCommand(new NearCommand());
registerSubCommand(new TeleportCommand());
registerSubCommand(new MovehereCommand());
registerSubCommand(new AlignCommand());
registerSubCommand(new CopyCommand());
registerSubCommand(new ReloadCommand());
registerSubCommand(new FixCommand());
registerSubCommand(new RemovelineCommand());
registerSubCommand(new SetlineCommand());
registerSubCommand(new InsertlineCommand());
registerSubCommand(new ReadtextCommand());
registerSubCommand(new ReadimageCommand());
registerSubCommand(new InfoCommand());
registerSubCommand(new HelpCommand(this));
}
public void registerSubCommand(HologramSubCommand subCommand) {
subCommands.add(subCommand);
}
public List<HologramSubCommand> getSubCommands() {
return new ArrayList<HologramSubCommand>(subCommands);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length == 0) {
sender.sendMessage(Colors.PRIMARY_SHADOW + "Server is running " + Colors.PRIMARY + "Holographic Displays " + Colors.PRIMARY_SHADOW + "v" + HolographicDisplays.getInstance().getDescription().getVersion() + " by " + Colors.PRIMARY + "filoghost");
if (sender.hasPermission(Strings.BASE_PERM + "help")) {
sender.sendMessage(Colors.PRIMARY_SHADOW + "Commands: " + Colors.PRIMARY + "/" + label + " help");
}
return true;
}
for (HologramSubCommand subCommand : subCommands) {
if (subCommand.isValidTrigger(args[0])) {
if (!subCommand.hasPermission(sender)) {
sender.sendMessage(Colors.ERROR + "You don't have permission.");
return true;
}
if (args.length - 1 >= subCommand.getMinimumArguments()) {
try {
subCommand.execute(sender, label, Arrays.copyOfRange(args, 1, args.length));
} catch (CommandException e) {
sender.sendMessage(Colors.ERROR + e.getMessage());
}
} else {
sender.sendMessage(Colors.ERROR + "Usage: /" + label + " " + subCommand.getName() + " " + subCommand.getPossibleArguments());
}
return true;
}
}
sender.sendMessage(Colors.ERROR + "Unknown sub-command. Type \"/" + label + " help\" for a list of commands.");
return true;
}
}
|
package travel.api.config.response;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author Administrator
*/
@Controller
public class CommonReturnController {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
*
* @param response
*/
protected void commonResponse(HttpServletResponse response, WorkResponse workResponse) {
try {
response.setContentType("application/json;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
JSONObject jsonObject = JSONObject.fromObject(workResponse);
String json = jsonObject.toString();
logger.info("response data : " + json);
response.getWriter().println(json);
} catch (IOException e) {
logger.error(String.valueOf(e));
return;
}
}
}
|
package ir.ac.kntu;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.ParallelCamera;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
/**
* @author Sepehr Ghaseminejad
*/
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Scene scene = new Scene(root, 800, 500, Color.WHEAT);
primaryStage.setScene(scene);
primaryStage.setTitle("Pong");
primaryStage.setResizable(false);
primaryStage.show();
ParallelCamera camera = new ParallelCamera();
// camera.setScaleX(1);
// camera.setScaleY(1);
scene.setCamera(camera);
int scoreA = 0;
Text text1 = new Text("Player A: " + scoreA);
text1.setX(220);
text1.setY(15);
text1.setFont(new Font(15));
text1.setStroke(Color.BURLYWOOD);
text1.setFill(Color.BURLYWOOD);
Text textA = new Text("Use space to change your wall");
textA.setX(0);
textA.setY(15);
textA.setFont(new Font(15));
textA.setFill(Color.CYAN);
textA.setStroke(Color.CYAN);
final int[] scoreB = {0};
Text text2 = new Text("Player B: " + scoreB[0]);
text2.setX(500);
text2.setY(15);
text2.setFont(new Font(15));
text2.setStroke(Color.BURLYWOOD);
text2.setFill(Color.BURLYWOOD);
Text textB = new Text("Use shift to change your wall");
textB.setX(600);
textB.setY(15);
textB.setFont(new Font(15));
textB.setStroke(Color.CYAN);
textB.setFill(Color.CYAN);
Line line1 = new Line(0,20,800,20);
line1.setStroke(Color.WHITE);
Line line2 = new Line(400,20,400,500);
line2.setStroke(Color.WHITE);
Line line3 = new Line(0,500,800,500);
line3.setStroke(Color.WHITE);
Circle circle1 = new Circle(50,Color.WHITE);
circle1.setCenterX(400);
circle1.setCenterY(260);
Rectangle rectangleA = new Rectangle(10,50,Color.YELLOW);
rectangleA.setX(0);
rectangleA.setY(230);
Rectangle rectangleB = new Rectangle(10,50,Color.YELLOW);
rectangleB.setX(790);
rectangleB.setY(230);
Circle ball = new Circle(10,Ball.RED.getColor());
if(Math.random() < 0.5) {
ball.setFill(Ball.PURPLE.getColor());
}
ball.setCenterX(400);
ball.setCenterY(260);
final int[] t = {0};
final Wall[] wallA = {new YellowWall()};
final Wall[] wallB = {new YellowWall()};
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent){
YellowWall yellowWall = new YellowWall();
BlueWall blueWall = new BlueWall();
if(keyEvent.getCode() == KeyCode.S){
if(rectangleA.getY() < 450) {
rectangleA.setY(rectangleA.getY() + wallA[0].getSpeed());
}
}else if(keyEvent.getCode() == KeyCode.W){
if(rectangleA.getY() > 20) {
rectangleA.setY(rectangleA.getY() - wallA[0].getSpeed());
}
}
if(keyEvent.getCode() == KeyCode.DOWN){
if(rectangleB.getY() < 450) {
rectangleB.setY(rectangleB.getY() + wallB[0].getSpeed());
}
}else if(keyEvent.getCode() == KeyCode.UP){
if(rectangleB.getY() > 20) {
rectangleB.setY(rectangleB.getY() - wallB[0].getSpeed());
}
}else if(keyEvent.getCode() == KeyCode.SPACE){
if(wallA[0].getColor() == Color.YELLOW){
wallA[0] = blueWall;
}else{
wallA[0] = yellowWall;
}
rectangleA.setHeight(wallA[0].getY());
rectangleA.setFill(wallA[0].getColor());
}else if(keyEvent.getCode() == KeyCode.SHIFT){
if(wallB[0].getColor() == Color.YELLOW){
wallB[0] = blueWall;
}else{
wallB[0] = yellowWall;
}
rectangleB.setHeight(wallB[0].getY());
rectangleB.setFill(wallB[0].getColor());
}
}
});
int k;
if(ball.getFill() == Color.RED){
k = Ball.RED.getvX();
}else{
k = Ball.PURPLE.getvX();
}
new AnimationTimer() {
private int valueX = k;
private int valueY = 3;
private boolean goal = false;
private int sA = 0;
private int sB = 0;
@Override
public void handle(long l) {
if (ball.getCenterY() > 20 && ball.getCenterY() < 490) {
if(ball.getCenterX() < 10){
if(rectangleA.getY() > ball.getCenterY() || rectangleA.getY() + rectangleA.getHeight() < ball.getCenterY()){
goal = true;
sB += 1;
text2.setText("Player B: " + sB);
}else{
valueX *= -1;
}
}else if(ball.getCenterX() > 790){
if(rectangleB.getY() > ball.getCenterY() || rectangleB.getY() + rectangleB.getHeight() < ball.getCenterY()){
goal = true;
sA += 1;
text1.setText("Player A: " + sA);
}else{
valueX *= -1;
}
}
}else{
valueY *= -1;
}
if(goal){
ball.setCenterY(260);
ball.setCenterX(400);
valueX *= -1;
}else {
ball.setCenterY(ball.getCenterY() + valueY);
ball.setCenterX(ball.getCenterX() + valueX);
}
goal = false;
scene.setFill(Color.rgb(57,125,10));
camera.setLayoutX(ball.getCenterX() - 800 / 2);
camera.setLayoutY(ball.getCenterY() - 500 / 2);
}
}.start();
root.getChildren().add(text1);
root.getChildren().add(text2);
root.getChildren().add(textA);
root.getChildren().add(textB);
root.getChildren().add(rectangleA);
root.getChildren().add(rectangleB);
root.getChildren().add(line1);
root.getChildren().add(line2);
root.getChildren().add(line3);
root.getChildren().add(circle1);
root.getChildren().add(ball);
}
@Override
public void init() {
System.out.println("Initializing...");
}
@Override
public void stop() {
System.out.println("Closing....");
}
public static void main(String[] args) {
launch(args);
}
}
|
package com.citibank.ods.modules.product.broker.functionality.valueobject;
/**
*
* @author Hamilton Matos,Jul 22, 2007
*/
public class BrokerListFncVO extends BaseBrokerListFncVO
{
}
|
package com.example.vehiclehirebookingsystem.http;
import com.example.vehiclehirebookingsystem.VehicleService;
import com.example.vehiclehirebookingsystem.model.Vehicle;
import com.example.vehiclehirebookingsystem.repository.VehicleNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.Collection;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@RequiredArgsConstructor
@RestController
public class VehicleController {
private final VehicleService service;
@GetMapping(value = "vehicles", produces = APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<Vehicle> getVehicles(@RequestParam(value = "filter", required = false) String filter) {
return service.getVehicles("available".equals(filter));
}
@GetMapping(value = "vehicles/{id}/cost-of-hire", produces = APPLICATION_JSON_VALUE)
public ResponseEntity<GetCostOfHireResponse> getCostOfHire(@PathVariable("id") long id,
@RequestParam("from_date") @DateTimeFormat(iso = ISO.DATE) LocalDate from,
@RequestParam("to_date") @DateTimeFormat(iso = ISO.DATE) LocalDate to) {
if (!from.isBefore(to)) {
return new ResponseEntity<>(BAD_REQUEST);
}
long cost = service.calculateCostOfHire(id, from, to);
return new ResponseEntity<>(new GetCostOfHireResponse(cost), OK);
}
@ExceptionHandler(VehicleNotFoundException.class)
@ResponseStatus(NOT_FOUND)
public void vehicleNotFoundExceptionHandler(VehicleNotFoundException exception) {
}
}
|
package by.cdptr.javabasics.l4_2;
import java.util.Random;
import java.util.Scanner;
public class MassivKratnyyK {
public static int enterNumber() {
Scanner scan = new Scanner(System.in);
while (!scan.hasNextInt()) {
System.out.println("Введено невалидное число! Попробуйте снова");
scan.next();
}
return scan.nextInt();
}
public static int noZerosAllowed(int i) {
while (i <= 0) {
System.out.println("Число не может быть меньше нуля либо равно ему! Попробуйте снова");
i = enterNumber();
}
return i;
}
public static int[] fillArrayWithRandomNumber(int x) {
int[] arr = new int[x];
Random rand = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(100);
}
return arr;
}
public static int summaKratnyh(int[] arr, int k) {
int result = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % k == 0) {
result += arr[i];
}
}
return result;
}
}
|
package formularios;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Color;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import javax.swing.ImageIcon;
import java.awt.SystemColor;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import java.awt.Component;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import javax.swing.Box;
import javax.swing.SwingConstants;
import primerconteo.primer;
import javax.swing.JCheckBox;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
public class generarmarbete extends JFrame {
static Date date = new Date();
static DateFormat hourFormat = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
public static LinkedList contenedor=new LinkedList();
private JPanel contentPane;
//la pao
//dhadkjhdsfkjahfkjsdhfkahsf
String almacenes="";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
generarmarbete frame = new generarmarbete();
frame.setVisible(true);
frame.setIconImage(new ImageIcon(getClass().getResource("/imagenes/4e.jpg")).getImage());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public generarmarbete() {
setResizable(false);
setBackground(SystemColor.inactiveCaption);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 871, 468);
contentPane = new JPanel();
contentPane.setBackground(SystemColor.inactiveCaption);
contentPane.setForeground(SystemColor.inactiveCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JMenuBar menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 855, 21);
contentPane.add(menuBar);
JMenu mnArchivo = new JMenu("Archivo");
mnArchivo.setFont(new Font("Candara", Font.PLAIN, 14));
menuBar.add(mnArchivo);
JMenuItem mntmRegresar = new JMenuItem("Regresar");
mntmRegresar.setIcon(new ImageIcon(generarmarbete.class.getResource("/imagenes/regresar.png")));
mntmRegresar.setFont(new Font("Candara", Font.PLAIN, 12));
mntmRegresar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
formularios.inicio inicio= new formularios.inicio();
inicio.setVisible(true);
}
});
mnArchivo.add(mntmRegresar);
JMenuItem mntmSalir = new JMenuItem("Salir");
mntmSalir.setIcon(new ImageIcon(generarmarbete.class.getResource("/imagenes/salir.png")));
mntmSalir.setFont(new Font("Candara", Font.PLAIN, 12));
mntmSalir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
mnArchivo.add(mntmSalir);
JLabel lblNewLabel = new JLabel("Generar Marbetes");
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBackground(Color.WHITE);
JButton btnGenerarMarbete = new JButton("Generar PDF");
final JCheckBox brandsEUA_chbx = new JCheckBox("4E BRANDS EUA");
brandsEUA_chbx.setBackground(Color.BLACK);
brandsEUA_chbx.setForeground(Color.WHITE);
final JCheckBox etiquetas_chbx = new JCheckBox("4G_1D ETIQUETAS");
etiquetas_chbx.setBackground(Color.BLACK);
etiquetas_chbx.setForeground(Color.WHITE);
final JCheckBox mp_chbx = new JCheckBox("4G_1D MP");
mp_chbx.setBackground(Color.BLACK);
mp_chbx.setForeground(Color.WHITE);
final JCheckBox quimicos_chbx = new JCheckBox("4G_1F QUIMICOS");
quimicos_chbx.setBackground(Color.BLACK);
quimicos_chbx.setForeground(Color.WHITE);
final JCheckBox smoMP_chbx = new JCheckBox("SMO_MATERIA PRIMA");
smoMP_chbx.setBackground(Color.BLACK);
smoMP_chbx.setForeground(Color.WHITE);
final JCheckBox c5_chbx = new JCheckBox("PRINCIPAL_C5");
c5_chbx.setBackground(Color.BLACK);
c5_chbx.setForeground(Color.WHITE);
final JCheckBox mpPlanta_chbx = new JCheckBox("MP_PLANTA 2C");
mpPlanta_chbx.setBackground(Color.BLACK);
mpPlanta_chbx.setForeground(Color.WHITE);
final JCheckBox mpPlanta_chbxB = new JCheckBox("MP_PLANTA 2B");
mpPlanta_chbxB.setBackground(Color.BLACK);
mpPlanta_chbxB.setForeground(Color.WHITE);
final JCheckBox smoPT_chbx = new JCheckBox("SMO_J1_PT");
smoPT_chbx.setBackground(Color.BLACK);
smoPT_chbx.setForeground(Color.WHITE);
JLabel lblNewLabel_5 = new JLabel("");
lblNewLabel_5.setForeground(Color.WHITE);
brandsEUA_chbx.setFont(new Font("Dialog", Font.BOLD, 14));
etiquetas_chbx.setFont(new Font("Dialog", Font.BOLD, 14));
mp_chbx.setFont(new Font("Dialog", Font.BOLD, 14));
quimicos_chbx.setFont(new Font("Dialog", Font.BOLD, 14));
smoMP_chbx.setFont(new Font("Dialog", Font.BOLD, 14));
c5_chbx.setFont(new Font("Dialog", Font.BOLD, 14));
mpPlanta_chbx.setFont(new Font("Dialog", Font.BOLD, 14));
mpPlanta_chbxB.setFont(new Font("Dialog", Font.BOLD, 14));
smoPT_chbx.setFont(new Font("Dialog", Font.BOLD, 14));
lblNewLabel.setFont(new Font("Dialog", Font.BOLD, 30));
btnGenerarMarbete.setFont(new Font("Candara", Font.PLAIN, 14));
brandsEUA_chbx.setBounds(48, 96, 210, 23);
etiquetas_chbx.setBounds(48, 142, 210, 23);
mp_chbx.setBounds(48, 188, 210, 23);
quimicos_chbx.setBounds(48, 235, 210, 23);
mpPlanta_chbxB.setBounds(48, 274, 210, 23);
smoMP_chbx.setBounds(453, 235, 210, 23);
c5_chbx.setBounds(453, 142, 210, 23);
mpPlanta_chbx.setBounds(453, 96, 210, 23);
smoPT_chbx.setBounds(453, 188, 210, 23);
lblNewLabel.setBounds(0, 32, 855, 39);
btnGenerarMarbete.setBounds(624, 367, 155, 23);
lblNewLabel_5.setBounds(0, 0, 855, 429);
btnGenerarMarbete.setVerticalAlignment(SwingConstants.TOP);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setVerticalAlignment(SwingConstants.TOP);
lblNewLabel_5.setIcon(new ImageIcon(generarmarbete.class.getResource("/imagenes/fondo.jpg")));
contentPane.add(btnGenerarMarbete);
contentPane.add(brandsEUA_chbx);
contentPane.add(etiquetas_chbx);
contentPane.add(mp_chbx);
contentPane.add(quimicos_chbx);
contentPane.add(smoMP_chbx);
contentPane.add(c5_chbx);
contentPane.add(mpPlanta_chbx);
contentPane.add(mpPlanta_chbxB);
contentPane.add(smoPT_chbx);
contentPane.add(lblNewLabel);
contentPane.add(lblNewLabel_5);
btnGenerarMarbete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(smoPT_chbx.isSelected() || mpPlanta_chbx.isSelected() || c5_chbx.isSelected()
|| smoMP_chbx.isSelected() || quimicos_chbx.isSelected() ||mpPlanta_chbxB.isSelected()
|| mp_chbx.isSelected() || etiquetas_chbx.isSelected() || brandsEUA_chbx.isSelected())
{
if(smoPT_chbx.isSelected())
almacenes = almacenes + "|" + smoPT_chbx.getText();
if(mpPlanta_chbx.isSelected())
almacenes = almacenes + "|" + mpPlanta_chbx.getText();
if(mpPlanta_chbxB.isSelected())
almacenes = almacenes + "|" + mpPlanta_chbxB.getText();
if(c5_chbx.isSelected())
almacenes = almacenes + "|" + c5_chbx.getText();
if(smoMP_chbx.isSelected())
almacenes = almacenes + "|" + smoMP_chbx.getText();
if(quimicos_chbx.isSelected())
almacenes = almacenes + "|" + quimicos_chbx.getText();
if(mp_chbx.isSelected())
almacenes = almacenes + "|" + mp_chbx.getText();
if(etiquetas_chbx.isSelected())
almacenes = almacenes + "|" + etiquetas_chbx.getText();
if(brandsEUA_chbx.isSelected())
almacenes = almacenes + "|" + brandsEUA_chbx.getText();
System.out.println(almacenes);
if(almacenes.charAt(0)=='|')
almacenes=""+almacenes.substring(1, almacenes.length())+"";
System.out.println(almacenes);
boolean listo = generarMarbete(almacenes);
almacenes="";
if(listo)
JOptionPane.showMessageDialog(contentPane, "Archivo generado satisfactoriamente");
//SISI
System.out.println("ARCHIVO GENERADO");
}
else
{
//Mensaje para seleccionar algo
JOptionPane.showMessageDialog(contentPane, "Selecciona al menos un almacén");
}
}
});
}
private boolean generarMarbete(String almacenes)
{
System.out.println(almacenes);
boolean listo = false;
try
{
System.out.println("Se inicia conexion a bd");
Class.forName("org.postgresql.Driver");
Connection conexion = DriverManager.getConnection("jdbc:postgresql://10.1.250.24:5932/inventarios", "postgres", "s3st2m1s4e");
//Connection conexion = DriverManager.getConnection("jdbc:postgresql://201.149.89.163:5932/openbravo", "postgres", "s3st2m1s4e");
System.out.println("Se finaliza la prueba de conexion a postgresql");
System.out.println("Se inicia la solicitud del reporte");
Map<String,Object> parameters = new HashMap<String,Object>();
parameters.put("almacenes",new String(almacenes));
System.out.println(parameters.put("almacenes",new String(almacenes)));
parameters.put("IMG_DIR",new String("/INFORMES/imagenes/"));
System.out.println(parameters.put("IMG_DIR",new String("/INFORMES/imagenes/")));
JasperReport reporte = (JasperReport)JRLoader.loadObjectFromFile("/INFORMES/reportes/marbete.jasper");
System.out.println(reporte);
System.out.println(parameters);
System.out.println(conexion);
JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parameters, conexion);
System.out.println("Se solicita la impresion del reporte");
JRExporter exporter = new JRPdfExporter();
System.out.println("Imprime reporte");
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new File("/INFORMES/"+"Marbetes"+almacenes+hourFormat.format(date)+".pdf"));
exporter.exportReport();
System.out.println("Termina ejecucion");
listo = true;
conexion.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception ex) {
// TODO: handle exception
ex.printStackTrace();
}
return listo;
}
}
|
package com.spring.scrapper.vboard;
import java.util.List;
import com.spring.scrapper.vboard.vo.VBoardVO;
public interface VBoardDAO {
public VBoardVO selectVBoard(VBoardVO vo) throws Exception;
public List<VBoardVO> selectVBoardList(VBoardVO vo) throws Exception;
public boolean insertVBoard(VBoardVO vo) throws Exception;
public boolean updateVBoard(VBoardVO vo) throws Exception;
public boolean deleteVBoard(VBoardVO vo) throws Exception;
}
|
package com.quickly.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.quickly.R;
import com.zhouwei.mzbanner.holder.MZViewHolder;
public class HomeBannerViewHolder implements MZViewHolder<String> {
private ImageView mImageView;
@Override
public View createView(Context context) {
View inflate = LayoutInflater.from(context).inflate(R.layout.home_banner_item, null);
mImageView = inflate.findViewById(R.id.banner_image);
return inflate;
}
@Override
public void onBind(Context context, int i, String s) {
Glide.with(context).load(s).into(mImageView);
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.util;
/**
* 提供一些简单的PB编码相关方法.
*
* @author 小流氓[176543888@qq.com]
* @since 3.0
*/
public class ProtobufUtils {
private static final int MAX_VALUE = 0XFFFFFFFF;
/**
* 一个字节真实长度,7位
*/
private static final int ONE_BYTE_LENGTH = 7;
/**
* 2个字节真实长度,14位
*/
private static final int TWO_BYTE_LENGTH = ONE_BYTE_LENGTH * 2;
/**
* 3个字节真实长度,21位
*/
private static final int THREE_BYTE_LENGTH = ONE_BYTE_LENGTH * 3;
/**
* 4个字节真实长度,28位
*/
private static final int FOUR_BYTE_LENGTH = ONE_BYTE_LENGTH * 4;
/**
* Computes size of protobuf varint32 after encoding.
*
* @param value which is to be encoded.
* @return size of value encoded as protobuf varint32.
*/
public static int computeRawVarint32Size(final int value) {
if ((value & (MAX_VALUE << ONE_BYTE_LENGTH)) == 0) {
return 1;
}
if ((value & (MAX_VALUE << TWO_BYTE_LENGTH)) == 0) {
return 2;
}
if ((value & (MAX_VALUE << THREE_BYTE_LENGTH)) == 0) {
return 3;
}
if ((value & (MAX_VALUE << FOUR_BYTE_LENGTH)) == 0) {
return 4;
}
return 5;
}
/**
* 以varint32的方式编码一个数字.
*
* @param value 数字
* @return 编码后的字节数组.
*/
public static byte[] encodeInt32(int value) {
byte[] result = new byte[computeRawVarint32Size(value)];
for (int i = 0, len = result.length; i < len; i++) {
if ((value & ~0x7F) == 0) {
result[i] = (byte) value;
} else {
result[i] = (byte) ((value & 0x7F) | 0x80);
value >>>= 7;
}
}
return result;
}
}
|
package com.kingnode.gou.dto;
import java.io.Serializable;
/**
* 活动范围表
*
* @author rascal
*/
public class ActivityDto implements Serializable{
private String name; //特卖名称
private String content; //特卖内容
private String startTime; //开始时间
private String endTime; //结束时间
private String activityCode; //特卖类型
private Double discount; //折扣
private int pri;
private String imgPath;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getContent(){
return content;
}
public void setContent(String content){
this.content=content;
}
public String getStartTime(){
return startTime;
}
public void setStartTime(String startTime){
this.startTime=startTime;
}
public String getEndTime(){
return endTime;
}
public void setEndTime(String endTime){
this.endTime=endTime;
}
public String getActivityCode(){
return activityCode;
}
public void setActivityCode(String activityCode){
this.activityCode=activityCode;
}
public Double getDiscount(){
return discount;
}
public void setDiscount(Double discount){
this.discount=discount;
}
public int getPri(){
return pri;
}
public void setPri(int pri){
this.pri=pri;
}
public String getImgPath(){
return imgPath;
}
public void setImgPath(String imgPath){
this.imgPath=imgPath;
}
}
|
package com.wirelesscar.dynafleet.api.types;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Api_UserTO complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Api_UserTO">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="assignedDrivers" type="{http://wirelesscar.com/dynafleet/api/types}Api_LongArrayTO"/>
* <element name="assignedVehicles" type="{http://wirelesscar.com/dynafleet/api/types}Api_LongArrayTO"/>
* <element name="description" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="email" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="emailAlias" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="firstName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="id" type="{http://wirelesscar.com/dynafleet/api/types}Api_UserId"/>
* <element name="isDeleted" type="{http://wirelesscar.com/dynafleet/api/types}Api_Boolean"/>
* <element name="language" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="lastName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="loginname" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="measureType" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="showCommunicationCostWarning" type="{http://wirelesscar.com/dynafleet/api/types}Api_Boolean"/>
* <element name="userRoles" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Api_UserTO", propOrder = {
"assignedDrivers",
"assignedVehicles",
"description",
"email",
"emailAlias",
"firstName",
"id",
"isDeleted",
"language",
"lastName",
"loginname",
"measureType",
"showCommunicationCostWarning",
"userRoles"
})
public class ApiUserTO {
@XmlElement(required = true, nillable = true)
protected ApiLongArrayTO assignedDrivers;
@XmlElement(required = true, nillable = true)
protected ApiLongArrayTO assignedVehicles;
@XmlElement(required = true, nillable = true)
protected String description;
@XmlElement(required = true, nillable = true)
protected String email;
@XmlElement(required = true, nillable = true)
protected String emailAlias;
@XmlElement(required = true, nillable = true)
protected String firstName;
@XmlElement(required = true, nillable = true)
protected ApiUserId id;
@XmlElement(required = true, nillable = true)
protected ApiBoolean isDeleted;
@XmlElement(required = true, nillable = true)
protected String language;
@XmlElement(required = true, nillable = true)
protected String lastName;
@XmlElement(required = true, nillable = true)
protected String loginname;
@XmlElement(required = true, nillable = true)
protected String measureType;
@XmlElement(required = true, nillable = true)
protected ApiBoolean showCommunicationCostWarning;
@XmlElement(nillable = true)
protected List<String> userRoles;
/**
* Gets the value of the assignedDrivers property.
*
* @return
* possible object is
* {@link ApiLongArrayTO }
*
*/
public ApiLongArrayTO getAssignedDrivers() {
return assignedDrivers;
}
/**
* Sets the value of the assignedDrivers property.
*
* @param value
* allowed object is
* {@link ApiLongArrayTO }
*
*/
public void setAssignedDrivers(ApiLongArrayTO value) {
this.assignedDrivers = value;
}
/**
* Gets the value of the assignedVehicles property.
*
* @return
* possible object is
* {@link ApiLongArrayTO }
*
*/
public ApiLongArrayTO getAssignedVehicles() {
return assignedVehicles;
}
/**
* Sets the value of the assignedVehicles property.
*
* @param value
* allowed object is
* {@link ApiLongArrayTO }
*
*/
public void setAssignedVehicles(ApiLongArrayTO value) {
this.assignedVehicles = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the email property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEmail() {
return email;
}
/**
* Sets the value of the email property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEmail(String value) {
this.email = value;
}
/**
* Gets the value of the emailAlias property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEmailAlias() {
return emailAlias;
}
/**
* Sets the value of the emailAlias property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEmailAlias(String value) {
this.emailAlias = value;
}
/**
* Gets the value of the firstName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFirstName() {
return firstName;
}
/**
* Sets the value of the firstName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFirstName(String value) {
this.firstName = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link ApiUserId }
*
*/
public ApiUserId getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link ApiUserId }
*
*/
public void setId(ApiUserId value) {
this.id = value;
}
/**
* Gets the value of the isDeleted property.
*
* @return
* possible object is
* {@link ApiBoolean }
*
*/
public ApiBoolean getIsDeleted() {
return isDeleted;
}
/**
* Sets the value of the isDeleted property.
*
* @param value
* allowed object is
* {@link ApiBoolean }
*
*/
public void setIsDeleted(ApiBoolean value) {
this.isDeleted = value;
}
/**
* Gets the value of the language property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLanguage() {
return language;
}
/**
* Sets the value of the language property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLanguage(String value) {
this.language = value;
}
/**
* Gets the value of the lastName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLastName() {
return lastName;
}
/**
* Sets the value of the lastName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLastName(String value) {
this.lastName = value;
}
/**
* Gets the value of the loginname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLoginname() {
return loginname;
}
/**
* Sets the value of the loginname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLoginname(String value) {
this.loginname = value;
}
/**
* Gets the value of the measureType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMeasureType() {
return measureType;
}
/**
* Sets the value of the measureType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMeasureType(String value) {
this.measureType = value;
}
/**
* Gets the value of the showCommunicationCostWarning property.
*
* @return
* possible object is
* {@link ApiBoolean }
*
*/
public ApiBoolean getShowCommunicationCostWarning() {
return showCommunicationCostWarning;
}
/**
* Sets the value of the showCommunicationCostWarning property.
*
* @param value
* allowed object is
* {@link ApiBoolean }
*
*/
public void setShowCommunicationCostWarning(ApiBoolean value) {
this.showCommunicationCostWarning = value;
}
/**
* Gets the value of the userRoles property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the userRoles property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getUserRoles().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getUserRoles() {
if (userRoles == null) {
userRoles = new ArrayList<String>();
}
return this.userRoles;
}
}
|
package com.n2s.miniproject.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.n2s.miniproject.core.databasecon;
/**
* Servlet implementation class LoginAdmin
*/
@WebServlet("/LoginAdmin")
public class LoginAdmin extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginAdmin() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Connection con;
Statement stmt;
ResultSet rs;
String uname = request.getParameter("uname");
String password = request.getParameter("pwd");
con = databasecon.getconnection();
try{
stmt = con.createStatement();
rs = stmt.executeQuery("select name,password from register where name ='"+uname+"' and password = '"+password+"'");
if(rs.next()){
HttpSession sess = request.getSession(true);
sess.setAttribute("uname",uname);
response.sendRedirect("AdminConsole.jsp");
}else{
response.sendRedirect("Login.jsp?msg1=unsucc");
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.izasoft.jcart.web.validators;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.izasoft.jcart.common.service.CatalogService;
import com.izasoft.jcart.domain.Category;
@Component
public class CategoryValidator implements Validator{
@Autowired protected CatalogService catalogService;
@Autowired protected MessageSource messageSource;
public boolean supports(Class<?> clazz) {
return Category.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
Category category = (Category) target;
String name = category.getName();
Category categoryByName = catalogService.getCategoryByName(name);
if(categoryByName != null) {
errors.rejectValue("name", "error.exist", new Object[] {name}, "Category "+ category.getName()+" already exist");
}
}
}
|
package edu.ucsb.cs56.pconrad.parsing.syntax;
public class LessThan extends OperatorScaffold {
// begin constants
public static final LessThan LESSTHAN = new LessThan();
// end constants
public LessThan() {
super("<");
}
}
|
package Problem_15654;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static int N, M;
public static int[] arr;
public static int[] idx;
public static boolean[] tr;
public static StringBuilder sb;
public static void ans(int cnt) {
if (cnt == M) {
for (int i = 0; i < M; i++)
sb.append(arr[idx[i]]).append(" ");
sb.append("\n");
} else {
for (int i = 0; i < N; i++) {
if (!tr[i]) {
idx[cnt] = i;
tr[i] = true;
ans(cnt + 1);
tr[i] = false;
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String buffer = br.readLine();
sb = new StringBuilder();
N = Integer.parseInt(buffer.split(" ")[0]);
M = Integer.parseInt(buffer.split(" ")[1]);
buffer = br.readLine();
StringTokenizer st = new StringTokenizer(buffer, " ");
arr = new int[N];
tr = new boolean[N];
for (int i = 0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
idx = new int[M];
Arrays.sort(arr);
ans(0);
System.out.print(sb.toString());
}
}
|
package com.cxxt.mickys.playwithme.model.bean;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* PWMUser
* 用户的对象数据类
*
* @author huangyz0918
*/
@Data
@EqualsAndHashCode(callSuper=false)
public class PWMUser extends BasePWMBean {
// non null
private String username;
private String phone;
private int sex;
private int age;
private String image;
private String signature;
private String email;
private String address;
private String[] attendCorporation;
private String[] manageCorporation;
private String[] activity;
}
|
class A{
A(){
System.out.println("parent class constructor");
}
}
public class superconstructorcall extends A {
superconstructorcall(){
/* here compiler automatically adds the :super()*/ /* super() is used to call the parent class constructor*/
System.out.println("sub class constructor");
}
public static void main(String args[]){
superconstructorcall obj=new superconstructorcall();
}
}
|
package apascualco.blog.springboot.utils;
import apascualco.blog.springboot.persistence.entidades.*;
import apascualco.blog.springboot.persistence.repositorio.CarroceriaREPO;
import apascualco.blog.springboot.persistence.repositorio.MotorREPO;
import apascualco.blog.springboot.persistence.repositorio.RuedasREPO;
import apascualco.blog.springboot.persistence.repositorio.TapiceriaREPO;
import org.apache.commons.lang.RandomStringUtils;
import java.util.Random;
public class PersistenciaUtils {
public static CocheEntidad generarCocheEntidad(CarroceriaREPO carroceriaREPO, TapiceriaREPO tapiceriaREPO, MotorREPO motorREPO, RuedasREPO ruedasREPO) {
CocheEntidad cocheEntidad = new CocheEntidad();
cocheEntidad.setCarroceria(PersistenciaUtils.generarCarroceriaEntidad(carroceriaREPO));
cocheEntidad.setMotor(PersistenciaUtils.generarMotorEntidad(motorREPO));
cocheEntidad.setRuedas(PersistenciaUtils.generarRuedadEntidad(ruedasREPO));
cocheEntidad.setTapiceria(PersistenciaUtils.generarTapiceriaEntidad(tapiceriaREPO));
return cocheEntidad;
}
public static CarroceriaEntidad generarCarroceriaEntidad(CarroceriaREPO carroceriaREPO) {
CarroceriaEntidad carroceriaEntidad = new CarroceriaEntidad();
carroceriaEntidad.setColor(PersistenciaUtils.generateString());
carroceriaEntidad.setTipo(PersistenciaUtils.generateString());
carroceriaEntidad.setPuertas(PersistenciaUtils.generateInt());
return carroceriaREPO.save(carroceriaEntidad);
}
public static MotorEntidad generarMotorEntidad(MotorREPO motorREPO) {
MotorEntidad motorEntidad = new MotorEntidad();
motorEntidad.setValvulas(PersistenciaUtils.generateInt());
motorEntidad.setFabricante(PersistenciaUtils.generateString());
motorEntidad.setCV(PersistenciaUtils.generateString());
motorEntidad.setTipo(PersistenciaUtils.generateString());
motorEntidad.setConsumo(PersistenciaUtils.generateString());
return motorREPO.save(motorEntidad);
}
public static RuedasEntidad generarRuedadEntidad(RuedasREPO ruedasREPO) {
RuedasEntidad ruedasEntidad = new RuedasEntidad();
ruedasEntidad.setTamanyo(PersistenciaUtils.generateInt());
ruedasEntidad.setPerfil(PersistenciaUtils.generateString());
return ruedasREPO.save(ruedasEntidad);
}
public static TapiceriaEntidad generarTapiceriaEntidad(TapiceriaREPO tapiceriaREPO) {
TapiceriaEntidad tapiceriaEntidad = new TapiceriaEntidad();
tapiceriaEntidad.setMateriall(PersistenciaUtils.generateString());
tapiceriaEntidad.setColor(PersistenciaUtils.generateString());
return tapiceriaREPO.save(tapiceriaEntidad);
}
private static String generateString() {
return RandomStringUtils.randomAlphanumeric(17);
}
private static int generateInt() {
return new Random().nextInt(100);
}
}
|
package demo;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import demo.Client.*;
import demo.Balancer.*;
/**
* @author Luciano Freitas
* @description
*/
public class ElasticLoadBalancer {
public static void main(String[] args) {
final ActorSystem system = ActorSystem.create("system");
final ActorRef client = system.actorOf(Client.createActor(), "client");
final ActorRef lb = system.actorOf(Balancer.createActor(system), "balancer");
MaxSessionMSG msm = new MaxSessionMSG(2);
MyMessage m1 = new MyMessage("Hello1");
MyMessage m2 = new MyMessage("Hello2");
MyMessage m3 = new MyMessage("Hello3");
lb.tell(msm, ActorRef.noSender());
lb.tell(m1, client);
lb.tell(m2, client);
lb.tell(m3, client);
// We wait 5 seconds before ending system (by default)
// But this is not the best solution.
try {
waitBeforeTerminate();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
system.terminate();
}
}
public static void waitBeforeTerminate() throws InterruptedException {
Thread.sleep(5000);
}
}
|
//
// TGServerThread.java
//
// Written by : Priyank Patel <pkpatel@cs.stanford.edu>
//
// Accepts connection requests and processes them
package Chat;
// socket
import java.net.*;
import java.io.*;
// Swing
import javax.swing.JTextArea;
// Crypto
import java.security.*;
import java.util.HashMap;
import javax.crypto.*;
public class TGServerThread extends Thread {
private TGServer _tgs;
private ServerSocket _serverSocket = null;
private int _portNum;
private String _hostName;
private JTextArea _outputArea;
private String tgsKeyStoreFileName;
private String tgsKeyStorePassword;
private static final String kaAlias = "clienta";
private static final String kbAlias = "clientb";
private static final String kaPassword = "passwordA";
private static final String kbPassword = "passwordB";
private static final String kkdcAlias = "kdc";
private static final String kkdcPassword = "passwordKDC";
private HashMap<String,String> passTable;
public TGServerThread(TGServer tgs) {
super("AuthServerThread");
passTable = new HashMap<String, String>();
passTable.put( kaAlias, kaPassword);
passTable.put( kbAlias, kbPassword);
_tgs = tgs;
_portNum = tgs.getPortNumber();
tgsKeyStoreFileName = _tgs.getKeyStoreFileName();
tgsKeyStorePassword = _tgs.getKeyStorePassword();
_outputArea = tgs.getOutputArea();
_serverSocket = null;
try {
InetAddress serverAddr = InetAddress.getByName(null);
_hostName = serverAddr.getHostName();
} catch (UnknownHostException e) {
_hostName = "0.0.0.0";
}
}
// Accept connections and service them one at a time
public void run() {
try {
_serverSocket = new ServerSocket(_portNum);
_outputArea.append("AS waiting on " + _hostName + " port " + _portNum);
while (true) {
Socket socket = _serverSocket.accept();
//
// Got the connection, now do what is required
//
PrintWriter asOut = new PrintWriter(socket.getOutputStream(), true);
BufferedReader asIn = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String kKDC = Utils.getKey(tgsKeyStoreFileName, tgsKeyStorePassword, kkdcAlias, kkdcPassword);
//generate a symmetric key between client a and client b
Key abKey; //the symmetric key
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(rand);
generator.init(128);
abKey = generator.generateKey();
String kAB = Utils.keyToString( abKey);
//read input from the client a
String [] input = asIn.readLine().trim().split(" ");
String idA_tocheck = input[0]; //id of client a (what client a claims)
String idB = input[1]; //id of client b
String TGT = input[2]; //ticket granting ticket
_outputArea.append( idA_tocheck+" sent a request to communacite with "+idB);
String [] TGT_in = Utils.decrypt_aes(kKDC, Constants.IV, TGT).split(" ");
String sA = TGT_in[0]; //session key of client a
String idA = TGT_in[1]; //real id of client a (as authentication server says)
String timestamp = Utils.decrypt_aes(sA, Constants.IV, input[3]);
String kB = Utils.getKey(tgsKeyStoreFileName, tgsKeyStorePassword, idB, passTable.get( idB)); //password of client b
//check if id of client a is and time-stamp are true
if(idA_tocheck.equals( idA) && Utils.checkTimestamp(timestamp)){
asOut.println( Utils.encrypt_aes(sA, Constants.IV, idB+" "+kAB+" "+Utils.encrypt_aes(kB, Constants.IV, idA+" "+kAB)));
_outputArea.append("Response has been sent to "+idA);
}
else{
System.out.println("Your ID is wrong or timestamp is wrong!");
socket.close();
}
}
} catch (Exception e) {
System.out.println("TGS thread error: " + e.getMessage());
e.printStackTrace();
System.exit(-1);
}
}
}
|
package homework_2016_3_10;
/**
* How many days is from a day before to today
* use java api
* @author 151250137
*
*/
public class Homework3_2 {
}
|
package old.Data20180508;
public class SearchinRotatedSortedArrayII {
public static void main(String[] args) {
System.out.println(new SearchinRotatedSortedArrayII().search(new int[]{1, 3, 1, 1, 1}, 3));
}
public boolean search(int[] nums, int target) {
int low = 0, high = nums.length - 1, mid = -1;
while(low <= high){
mid = low + (high - low) / 2;
if(nums[mid] == target)
return true;
if(nums[mid] < nums[high] || nums[mid] < nums[low]){
if(target > nums[mid] && target <= nums[high]){
low = mid + 1;
}else
high = mid - 1;
}else if(nums[mid] > nums[low] || nums[mid] > nums[high]){
if (target < nums[mid] && target >= nums[low]) {
high = mid - 1;
} else {
low = mid + 1;
}
}else{
high--;
}
}
return false;
}
}
|
package nz.co.zufang.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
/**
* Created by Mark on 2/25/2016.
*/
@Entity
@Table(name = "TBL_INFO")
public class Info{
@Id
@Column(name = "ID", unique = true)
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String id;
@Column(name = "TITLE")
private String title;
@Column(name = "CONTENT")
private String content;
@Column(name = "THUMB")
private String thumb;
@Column(name = "KEYWORDS")
private String keywords;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "LINKMAN")
private String linkMan;
@Column(name = "FEE")
private Double fee;
@Column(name = "EMAIL")
private String email;
@Column(name = "QQ")
private String qq;
@Column(name = "PHONE")
private String phone;
@Column(name = "ADDRESS")
private String address;
@Column(name = "MAP_POINT")
private String mapPoint;
@Column(name = "POST_AREA")
private String postArea;
@Column(name = "POST_DATE")
private Date postDate;
@Column(name = "END_DATE")
private Date endDate;
@Column(name = "IP")
private String ip;
@Column(name = "CLICK")
private int click;
@Column(name = "IS_PRO")
private boolean isPro;
@Column(name = "IS_TOP")
private boolean isTop;
@Column(name = "TOP_TYPE")
private String topType;
@Column(name = "IS_CHECK")
private boolean isCheck;
@Column(name = "CITY")
private String city;
@Column(name = "DISTRICT")
private String district;
@Column(name = "SUBURB")
private String suburb;
@Column(name = "DURATION")
private String duration;
@Column(name = "MINPRICE")
private String minprice;
@Column(name = "MAXPRICE")
private String maxprice;
@Column(name = "PRICE")
private double price;
@Column(name = "TYPE")
private String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getThumb() {
return thumb;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLinkMan() {
return linkMan;
}
public void setLinkMan(String linkMan) {
this.linkMan = linkMan;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMapPoint() {
return mapPoint;
}
public void setMapPoint(String mapPoint) {
this.mapPoint = mapPoint;
}
public String getPostArea() {
return postArea;
}
public void setPostArea(String postArea) {
this.postArea = postArea;
}
public Date getPostDate() {
return postDate;
}
public void setPostDate(Date postDate) {
this.postDate = postDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getClick() {
return click;
}
public void setClick(int click) {
this.click = click;
}
public boolean isPro() {
return isPro;
}
public void setPro(boolean pro) {
isPro = pro;
}
public boolean isTop() {
return isTop;
}
public void setTop(boolean top) {
isTop = top;
}
public String getTopType() {
return topType;
}
public void setTopType(String topType) {
this.topType = topType;
}
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean check) {
isCheck = check;
}
public Double getFee() {
return fee;
}
public void setFee(Double fee) {
this.fee = fee;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getSuburb() {
return suburb;
}
public void setSuburb(String suburb) {
this.suburb = suburb;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getMinprice() {
return minprice;
}
public void setMinprice(String minprice) {
this.minprice = minprice;
}
public String getMaxprice() {
return maxprice;
}
public void setMaxprice(String maxprice) {
this.maxprice = maxprice;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
|
package main.com.java.basics.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* @author Heena Hussain
* Example to read the annotation
*/
public class RunTest
{
public static void main(String[] args)
{
Class testExampleClass = TestExample.class;
Annotation[] annotations = testExampleClass.getAnnotations();
TesterInfo testerInfo = null;
for(Annotation annotation : annotations)
{
if(annotation instanceof TesterInfo)
{
testerInfo = (TesterInfo) annotation;
break;
}
}
if(testerInfo != null)
{
System.out.println("createdBy : " + testerInfo.createdBy());
System.out.println("tags : " + Arrays.toString(testerInfo.tags()));
System.out.println("lastModified: " + testerInfo.lastModified());
}
Method[] methods = testExampleClass.getDeclaredMethods(); //Provide only direct annotations
for(Method method : methods)
{
if(method.isAnnotationPresent(TestAnnotation.class))
{
TestAnnotation testAnnotation = method.getAnnotation(TestAnnotation.class);
if(testAnnotation.enabled())
{
try
{
method.invoke(testExampleClass.newInstance());
System.out.println("Executing test: " + method.getName());
} catch(Exception ex)
{
System.out.println("Failed test: " + method.getName());
}
} else
{
System.out.println("Ignored test: " + method.getName());
}
}
}
Field[] fields = testExampleClass.getDeclaredFields(); // to get all fields defined in this calls only - excludes base class fields
for(Field field : fields)
{
Annotation[] fieldAnnotations = field.getAnnotations(); // Provided all annotations
for(Annotation annotation : fieldAnnotations)
{
if( annotation instanceof FieldAnnotation)
{
System.out.println("Field annotation " + field.getName() + " : " + ((FieldAnnotation) annotation).key());
}
}
}
}
}
|
package com.jinglangtech.teamchat.model;
/**
* Created by icebery on 2017/4/25 0025.
*
* 登录用户
*/
public class LoginUser {
public int type;
public String _id;
public String token;
public String name;
public String avatar;
public String account;
public boolean isUpdated;
public boolean notification;
}
|
package Services.Impl;
/**
* Created by Emma on 8/12/2018.
*/
//add
public class HiresServiceImpl {
}
|
package Lesson_5;
import Lesson_5.Services.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
@Controller
@RequestMapping("/books")
public class BookController {
private BookService bookService;
@Autowired
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
@RequestMapping("/list")
public String showAllBooks(Model model) {
List<Book> bookList = bookService.getAllBooks();
model.addAttribute("booksList", bookList);
return "books-list";
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String addBook(Model model) {
model.addAttribute("book", new Book());
return "add-bookform";
}
@RequestMapping(value = "add", method = RequestMethod.POST)
public String addBook(Book book) {
bookService.saveBook(book);
return "redirect:/books/list";
}
}
|
package com.aut.yuxiang.lbs_middleware;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
/**
* Created by yuxiang on 2/02/17.
*/
public class LocationBindingData extends BaseObservable {
private String longitude;
private String latitude;
private String accuracy;
@Bindable
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
notifyPropertyChanged(BR.latitude);
}
@Bindable
public String getAccuracy() {
return accuracy;
}
public void setAccuracy(String accuracy) {
this.accuracy = accuracy;
notifyPropertyChanged(BR.accuracy);
}
@Bindable
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
notifyPropertyChanged(BR.longitude);
}
}
|
package bioskopp;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MojNalogServlet
*/
public class MojNalogServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String korisnickoIme = request.getParameter("korisnickoIme");
String sifra = request.getParameter("sifra");
String uloga = request.getParameter("uloga");
System.out.println(korisnickoIme);
System.out.println(sifra);
System.out.println(uloga);
response.getWriter().println("success");
}
}
|
package com.ebook.admin.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.ebook.admin.domain.Book;
import com.ebook.admin.service.BookService;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
private BookService bookService;
@GetMapping("/add")
public String addBookGet(Model model) {
Book book = new Book();
model.addAttribute("book", book);
return "addBook";
}
@PostMapping("/add")
public String addBookPost(@ModelAttribute("book") Book book) {
bookService.save(book);
MultipartFile bookImage = book.getBookImage();
try {
byte[] bytes = bookImage.getBytes();
String name = book.getId() + ".png";
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(new File("src/main/resources/static/image/book/" + name)));
stream.write(bytes);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:bookList";
}
@GetMapping("/bookList")
public String bookList(Model model) {
List<Book> books = bookService.findAll();
model.addAttribute("books", books);
return "bookList";
}
@GetMapping("/bookInfo")
public String bookInfo(@RequestParam Long id, Model model) {
Book book = bookService.findOne(id);
model.addAttribute("book", book);
return "bookInfo";
}
@GetMapping("/update")
public String updateBookGet(@RequestParam Long id, Model model) {
Book book = bookService.findOne(id);
model.addAttribute("book", book);
return "updateBook";
}
@PostMapping("/update")
public String updateBookPost(@ModelAttribute("book") Book book) {
bookService.save(book);
MultipartFile bookImage = book.getBookImage();
if (!bookImage.isEmpty()) {
try {
byte[] bytes = bookImage.getBytes();
String name = book.getId() + ".png";
Files.delete(Paths.get("src/main/resources/static/image/book/" + name));
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(new File("src/main/resources/static/image/book/" + name)));
stream.write(bytes);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return "redirect:bookList";
}
@GetMapping("/delete")
public String deleteBook(@RequestParam Long id) {
bookService.removeOne(id);
return "redirect:bookList";
}
}
|
package se.mauritzz.kth.inet.http.body;
public class PlainTextResponseBody extends HttpBody {
private String body;
public PlainTextResponseBody(String body) {
super(BodyType.TEXT_PLAIN);
this.body = body;
}
@Override
public String getBody() {
return body;
}
}
|
package org.dajlab.mondialrelayapi.soap;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Classe Java pour anonymous complex type.
*
* <p>
* Le fragment de schéma suivant indique le contenu attendu figurant dans cette
* classe.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Enseigne" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="STAT_ID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Langue" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Security" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "enseigne", "statid", "langue", "security" })
@XmlRootElement(name = "WSI2_STAT_Label")
public class WSI2STATLabel {
@XmlElement(name = "Enseigne")
protected String enseigne;
@XmlElement(name = "STAT_ID")
protected String statid;
@XmlElement(name = "Langue")
protected String langue;
@XmlElement(name = "Security")
protected String security;
/**
* Obtient la valeur de la propriété enseigne.
*
* @return possible object is {@link String }
*
*/
public String getEnseigne() {
return enseigne;
}
/**
* Définit la valeur de la propriété enseigne.
*
* @param value
* allowed object is {@link String }
*
*/
public void setEnseigne(String value) {
this.enseigne = value;
}
/**
* Obtient la valeur de la propriété statid.
*
* @return possible object is {@link String }
*
*/
public String getSTATID() {
return statid;
}
/**
* Définit la valeur de la propriété statid.
*
* @param value
* allowed object is {@link String }
*
*/
public void setSTATID(String value) {
this.statid = value;
}
/**
* Obtient la valeur de la propriété langue.
*
* @return possible object is {@link String }
*
*/
public String getLangue() {
return langue;
}
/**
* Définit la valeur de la propriété langue.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLangue(String value) {
this.langue = value;
}
/**
* Obtient la valeur de la propriété security.
*
* @return possible object is {@link String }
*
*/
public String getSecurity() {
return security;
}
/**
* Définit la valeur de la propriété security.
*
* @param value
* allowed object is {@link String }
*
*/
public void setSecurity(String value) {
this.security = value;
}
}
|
package com.example.demo.security;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.example.demo.dao.PermissionDao;
import com.example.demo.dao.UserDao;
import com.example.demo.domain.Permission;
import com.example.demo.domain.User;
/**
* 自定义UserDetailsService 接口
*/
@Service
public class CustomUserService implements UserDetailsService {
@Autowired
private UserDao userDao;
@Autowired
private PermissionDao permissionDao;
@Override
public UserDetails loadUserByUsername(String username) {
// 重写loadUserByUsername 方法获得 userdetails 类型用户
User user = userDao.findByUserName(username);
if (user == null) {
User mobileUser = userDao.findByMobile(username);
if (mobileUser == null) {
throw new UsernameNotFoundException("用户不存在");
} else {
return new org.springframework.security.core.userdetails.User(mobileUser.getLogin_name(), mobileUser.getPassword(),
getGrantedAuthorities(mobileUser));
}
} else {
return new org.springframework.security.core.userdetails.User(user.getLogin_name(), user.getPassword(), getGrantedAuthorities(user));
}
// List<Permission> permissions = permissionDao.findByAdminUserId(user.getId());
// List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
// for (Permission permission : permissions) {
// if (permission != null && permission.getPermission_name() != null) {
// GrantedAuthority grantedAuthority = new
// SimpleGrantedAuthority(permission.getPermission_name());
// grantedAuthorities.add(grantedAuthority);
// }
// }
}
List<GrantedAuthority> getGrantedAuthorities(User user) {
List<Permission> permissions = permissionDao.findByAdminUserId(user.getId());
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (Permission permission : permissions) {
if (permission != null && permission.getPermission_name() != null) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getPermission_name());
grantedAuthorities.add(grantedAuthority);
}
}
return grantedAuthorities;
}
}
|
package com.example.feeasy.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.example.feeasy.Threads.Connection;
import com.example.feeasy.dataManagement.AppDataManager;
import com.example.feeasy.dataManagement.DataManager;
import com.example.feeasy.R;
import com.example.feeasy.adapters.AdapterHome;
import com.example.feeasy.entities.ActionNames;
import com.example.feeasy.entities.Group;
import com.example.feeasy.entities.GroupMember;
import org.json.JSONObject;
public class HomeActivity extends AppCompatActivity {
RecyclerView recyclerView;
AdapterHome adapter;
Handler groupListHandler = new GroupListHandler(Looper.getMainLooper());
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
View buttonAddGroup = findViewById(R.id.button_addGroup);
buttonAddGroup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddGroupActivity.class);
startActivity(intent);
}
});
adapter = new AdapterHome(this, DataManager.getDataManager().getGroupList());
recyclerView = findViewById(R.id.main_recycler);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
Intent intent;
switch (item.getItemId()){
case R.id.item1:
intent = new Intent(this, ProfileActivity.class);
startActivity(intent);
return true;
case R.id.item2:
intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
default: super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume() {
AppDataManager.getAppDataManager().setCurrentHandler(groupListHandler);
// TODO: could be removed
Connection connection = new Connection();
connection.handleAction(ActionNames.ALL_GROUPS, new JSONObject());
//-------------------------------------------------------------------
adapter.notifyDataSetChanged();
super.onResume();
}
@Override
public void onBackPressed() {
}
private class GroupListHandler extends Handler {
public GroupListHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(@NonNull Message msg) {
if(msg.obj == ActionNames.ALL_GROUPS){
if(msg.arg1 == 0){
runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
}
});
}
}
}
}
}
|
package com.example.demo.mapper;
import com.example.demo.entity.SysMonthlyReportMajor;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zjp
* @since 2021-03-30
*/
public interface SysMonthlyReportMajorMapper extends BaseMapper<SysMonthlyReportMajor> {
}
|
package com.zut.lcy.mybatisplus.util;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.sql.SQLException;
public class MyBatisPlusGenerator {
public static void main(String[] args) throws SQLException {
GlobalConfig config = new GlobalConfig();
config.setActiveRecord(true) // 是否支持AR模式
.setAuthor("刘朝阳") // 作者
.setOutputDir("D:\\SoftWare") // 生成路径
.setFileOverride(true) // 文件覆盖
.setIdType(IdType.AUTO) // 主键策略
.setServiceName("%sService") // 设置生成的service接口的名字的首字母是否为I
// IEmployeeService
.setBaseResultMap(true)//生成基本的resultMap
.setBaseColumnList(true);//生成基本的SQL片段
//2. 数据源配置
DataSourceConfig dsConfig = new DataSourceConfig();
dsConfig.setDbType(DbType.MYSQL) // 设置数据库类型
.setDriverName("com.mysql.jdbc.Driver")
.setUrl("jdbc:mysql://localhost:3306/exam?useSSL=false&useUnicode=true&characterEncoding=utf-8" +
"&allowMultiQueries=true&serverTimezone=UTC")
.setUsername("root")
.setPassword("root");
//3. 策略配置globalConfiguration中
StrategyConfig stConfig = new StrategyConfig();
stConfig.setCapitalMode(true)
.setNaming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略
; // 生成的表
//4. 包名策略配置
PackageConfig pkConfig = new PackageConfig();
pkConfig.setParent("com.zut.lcy.mybatisplus")
.setMapper("mapper")//dao
.setService("service")//servcie
.setController("controller")//controller
.setEntity("entity")
.setXml("mapper");//mapper.xml
//5. 整合配置
AutoGenerator ag = new AutoGenerator();
ag.setGlobalConfig(config)
.setDataSource(dsConfig)
.setStrategy(stConfig)
.setPackageInfo(pkConfig);
ag.execute();
}
}
//本项目中使用的sqk文件
///*
// Navicat Premium Data Transfer
//
// Source Server : localhost
// Source Server Type : MySQL
// Source Server Version : 50727
// Source Host : localhost:3306
// Source Schema : exam
//
// Target Server Type : MySQL
// Target Server Version : 50727
// File Encoding : 65001
//
// Date: 17/12/2019 11:52:43
//*/
//
// SET NAMES utf8mb4;
// SET FOREIGN_KEY_CHECKS = 0;
//
// -- ----------------------------
// -- Table structure for student
// -- ----------------------------
// DROP TABLE IF EXISTS `student`;
// CREATE TABLE `student` (
// `id` int(11) NOT NULL AUTO_INCREMENT,
// `s_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
// `s_age` int(11) NULL DEFAULT NULL,
// `s_gender` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
// `s_address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
// `s_education` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
// `s_major` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
// PRIMARY KEY (`id`) USING BTREE
// ) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
//
// -- ----------------------------
// -- Table structure for user
// -- ----------------------------
// DROP TABLE IF EXISTS `user`;
// CREATE TABLE `user` (
// `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
// `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
// PRIMARY KEY (`username`) USING BTREE
// ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
//
// SET FOREIGN_KEY_CHECKS = 1;
|
/*
* 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.
*/
/**
*
* @author bernice.templeman001
*/
public class Tree {
public Tree()
{
treeCount++;
}
public int getTreeCount()
{
return treeCount;
}
}
|
package com.staniul.teamspeak.modules.adminlists;
public class Servergroup {
private int id;
private int rank;
private String icon;
public Servergroup() {
}
public Servergroup(int id, int rank, String icon) {
this.id = id;
this.rank = rank;
this.icon = icon;
}
public int getId() {
return id;
}
public int getRank() {
return rank;
}
public String getIcon() {
return icon;
}
@Override
public String toString() {
return String.format("%d (%d): %s", id, rank, icon);
}
}
|
package trunk.Control;
import trunk.Model.*;
/**
* With this simulation, the user shall indicate a per annum percentage that each
* equity will decrease. This class implements the FutureSimulation interface, and
* acts as a concrete strategy within the Strategy design pattern.
*/
public class BearMarket implements FutureSimulation {
/**
* The method to run the simulation.
* @param portfolio : A Portfolio object that will run the simulation.
* @param percentage : A double that represents a per annum percentage.
* @param interval : An int that represents a period of time.
* @param steps : An int that represents the number of intervals to run.
* @return : A double representing the equity price after the simulation.
*/
public double[] simulate(Portfolio portfolio, double percentage, int interval, int steps) {
steps += 1;
double[] finalValues = new double[steps];
double initValue = 0;
double finalValue;
double cashValue = 0;
double totChange = 0;
for (int i = 0; i < portfolio.equityList1.size(); i++) {
Equity e = portfolio.equityList1.get(i);
initValue += e.shares * e.acquisitionPrice;
}
for (int i = 0; i < portfolio.cashAccList.size(); i++) {
CashAccount ca = portfolio.cashAccList.get(i);
cashValue += ca.balance;
}
initValue += cashValue;
finalValues[0] = initValue;
double sub = initValue * (percentage / 100);
for (int j = 1; j < steps; j++) {
if (finalValues[j - 1] - sub >= 0)
finalValues[j] = finalValues[j - 1] - sub;
else finalValues[j] = 0;
}
return finalValues;
}
@Override
public double[] simulate(Equity e, double percentage, int interval, int steps) {
double[] vals = new double[steps];
double initValue = e.shares * e.acquisitionPrice;
vals[0] = initValue;
for (int i = 1; i < steps; i++) {
initValue -= initValue * (percentage / 100);
if (initValue >= 0)
vals[i] = initValue;
else vals[i] = 0;
}
return vals;
}
}
|
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.jsf;
import jakarta.faces.application.NavigationHandler;
import jakarta.faces.context.FacesContext;
import org.springframework.lang.Nullable;
/**
* Base class for JSF NavigationHandler implementations that want
* to be capable of decorating an original NavigationHandler.
*
* <p>Supports the standard JSF style of decoration (through a constructor argument)
* as well as an overloaded {@code handleNavigation} method with explicit
* NavigationHandler argument (passing in the original NavigationHandler). Subclasses
* are forced to implement this overloaded {@code handleNavigation} method.
* Standard JSF invocations will automatically delegate to the overloaded method,
* with the constructor-injected NavigationHandler as argument.
*
* @author Juergen Hoeller
* @since 1.2.7
* @see #handleNavigation(jakarta.faces.context.FacesContext, String, String, NavigationHandler)
* @see DelegatingNavigationHandlerProxy
*/
public abstract class DecoratingNavigationHandler extends NavigationHandler {
@Nullable
private NavigationHandler decoratedNavigationHandler;
/**
* Create a DecoratingNavigationHandler without fixed original NavigationHandler.
*/
protected DecoratingNavigationHandler() {
}
/**
* Create a DecoratingNavigationHandler with fixed original NavigationHandler.
* @param originalNavigationHandler the original NavigationHandler to decorate
*/
protected DecoratingNavigationHandler(NavigationHandler originalNavigationHandler) {
this.decoratedNavigationHandler = originalNavigationHandler;
}
/**
* Return the fixed original NavigationHandler decorated by this handler, if any
* (that is, if passed in through the constructor).
*/
@Nullable
public final NavigationHandler getDecoratedNavigationHandler() {
return this.decoratedNavigationHandler;
}
/**
* This implementation of the standard JSF {@code handleNavigation} method
* delegates to the overloaded variant, passing in constructor-injected
* NavigationHandler as argument.
* @see #handleNavigation(jakarta.faces.context.FacesContext, String, String, jakarta.faces.application.NavigationHandler)
*/
@Override
public final void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
handleNavigation(facesContext, fromAction, outcome, this.decoratedNavigationHandler);
}
/**
* Special {@code handleNavigation} variant with explicit NavigationHandler
* argument. Either called directly, by code with an explicit original handler,
* or called from the standard {@code handleNavigation} method, as
* plain JSF-defined NavigationHandler.
* <p>Implementations should invoke {@code callNextHandlerInChain} to
* delegate to the next handler in the chain. This will always call the most
* appropriate next handler (see {@code callNextHandlerInChain} javadoc).
* Alternatively, the decorated NavigationHandler or the passed-in original
* NavigationHandler can also be called directly; however, this is not as
* flexible in terms of reacting to potential positions in the chain.
* @param facesContext the current JSF context
* @param fromAction the action binding expression that was evaluated to retrieve the
* specified outcome, or {@code null} if the outcome was acquired by some other means
* @param outcome the logical outcome returned by a previous invoked application action
* (which may be {@code null})
* @param originalNavigationHandler the original NavigationHandler,
* or {@code null} if none
* @see #callNextHandlerInChain
*/
public abstract void handleNavigation(FacesContext facesContext, @Nullable String fromAction,
@Nullable String outcome, @Nullable NavigationHandler originalNavigationHandler);
/**
* Method to be called by subclasses when intending to delegate to the next
* handler in the NavigationHandler chain. Will always call the most
* appropriate next handler, either the decorated NavigationHandler passed
* in as constructor argument or the original NavigationHandler as passed
* into this method - according to the position of this instance in the chain.
* <p>Will call the decorated NavigationHandler specified as constructor
* argument, if any. In case of a DecoratingNavigationHandler as target, the
* original NavigationHandler as passed into this method will be passed on to
* the next element in the chain: This ensures propagation of the original
* handler that the last element in the handler chain might delegate back to.
* In case of a standard NavigationHandler as target, the original handler
* will simply not get passed on; no delegating back to the original is
* possible further down the chain in that scenario.
* <p>If no decorated NavigationHandler specified as constructor argument,
* this instance is the last element in the chain. Hence, this method will
* call the original NavigationHandler as passed into this method. If no
* original NavigationHandler has been passed in (for example if this
* instance is the last element in a chain with standard NavigationHandlers
* as earlier elements), this method corresponds to a no-op.
* @param facesContext the current JSF context
* @param fromAction the action binding expression that was evaluated to retrieve the
* specified outcome, or {@code null} if the outcome was acquired by some other means
* @param outcome the logical outcome returned by a previous invoked application action
* (which may be {@code null})
* @param originalNavigationHandler the original NavigationHandler,
* or {@code null} if none
*/
protected final void callNextHandlerInChain(FacesContext facesContext, @Nullable String fromAction,
@Nullable String outcome, @Nullable NavigationHandler originalNavigationHandler) {
NavigationHandler decoratedNavigationHandler = getDecoratedNavigationHandler();
if (decoratedNavigationHandler instanceof DecoratingNavigationHandler decHandler) {
// DecoratingNavigationHandler specified through constructor argument:
// Call it with original NavigationHandler passed in.
decHandler.handleNavigation(facesContext, fromAction, outcome, originalNavigationHandler);
}
else if (decoratedNavigationHandler != null) {
// Standard NavigationHandler specified through constructor argument:
// Call it through standard API, without original NavigationHandler passed in.
// The called handler will not be able to redirect to the original handler.
decoratedNavigationHandler.handleNavigation(facesContext, fromAction, outcome);
}
else if (originalNavigationHandler != null) {
// No NavigationHandler specified through constructor argument:
// Call original handler, marking the end of this chain.
originalNavigationHandler.handleNavigation(facesContext, fromAction, outcome);
}
}
}
|
package org.maia.mvc.gerenciadorOfertas.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;
import lombok.*;
@SuppressWarnings("serial")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "promocoes")
public class Promocao implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "site_promocao", nullable = false)
private String site;
@Column(name = "title_promocao", nullable = false)
private String titulo;
@Column(name = "link_promocao", nullable = false)
private String linkPromocao;
@Column(name = "descricao", nullable = false)
private String descricao;
@NumberFormat(style = Style.CURRENCY, pattern = "#,##0.00")
@Column(name = "preco_promocao", nullable = false)
private BigDecimal preco;
@Column(name = "link_imagem", nullable = false)
private String linkImage;
@Column(name = "total_likes")
private int likes;
@Column(name = "data_cadastro")
private LocalDateTime dtaCadastroDateTime;
@ManyToOne
@JoinColumn(name = "categoria_fk")
private Categoria categoria;
}
|
package com.sshfortress.common.util.tabletoentity;
public class ColumnAttribute {
//字段名称
private String columnName;
//字段类型
private String columType;
//字段长度
private int length;
//小数点后
private int scale;
//是否为 nullable
private int isNullable;
// 是否为主键
private boolean isPK;
// 属性
private String attributeName;
// 属性类型
private String attributeType;
// 字段说明
private String comment;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getColumType() {
return columType;
}
public void setColumType(String columType) {
this.columType = columType;
}
public int isNullable() {
return isNullable;
}
public void setNullable(int isNullable) {
this.isNullable = isNullable;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getScale() {
return scale;
}
public void setScale(int scale) {
this.scale = scale;
}
public String getAttributeName() {
return attributeName;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public String getAttributeType() {
return attributeType;
}
public void setAttributeType(String attributeType) {
this.attributeType = attributeType;
}
public int getIsNullable() {
return isNullable;
}
public void setIsNullable(int isNullable) {
this.isNullable = isNullable;
}
public boolean isPK() {
return isPK;
}
public void setPK(boolean isPK) {
this.isPK = isPK;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
|
package com.icanit.app_v2.adapter;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import com.icanit.app_v2.R;
import com.icanit.app_v2.entity.CartItem;
import com.icanit.app_v2.entity.MerchantCartItems;
import com.icanit.app_v2.exception.AppException;
import com.icanit.app_v2.ui.InnerListView2;
import com.icanit.app_v2.ui.OuterListView;
import com.icanit.app_v2.util.AppUtil;
public class CartItemListAdapterSub extends MyBaseAdapter {
private Context context;
private LayoutInflater inflater;
private int resId=R.layout.item4lv_cartiteminfo_sub;
// private List<CartItem> itemList;
// private List<MerchantCartItems> dividedItemList;
private TextView totalCost;
private View confirmation,trashButton;
private int subLvItemHeight,subLvMaxHeight;
public CartItemListAdapterSub(Context context,TextView totalCost,View confirmation,View trashButton){
this.context=context;inflater=LayoutInflater.from(context);
this.totalCost=totalCost;this.confirmation=confirmation;this.trashButton=trashButton;
// itemList=AppUtil.appContext.shoppingCartList;
updateTotalCost();updateSubmitButton();
// dividedItemList=AppUtil.appContext.dividedItemList;
LinearLayout ll=((LinearLayout)inflater.inflate(R.layout.item4lv_cartiteminfo_x, null,false));
subLvItemHeight=AppUtil.getMeasuredHeight(ll);
}
public List<MerchantCartItems> getDividedItemList() {
return AppUtil.appContext.dividedItemList;
}
public void updateTotalCost(){
totalCost.setText("×ܽð¶î:£¤"+String.format("%.2f", AppUtil.calculateTotalCost(AppUtil.appContext.shoppingCartList)));
}
public void updateSubmitButton(){
if(AppUtil.appContext.shoppingCartList==null||AppUtil.appContext.shoppingCartList.isEmpty()){
confirmation.setEnabled(false);
trashButton.setEnabled(false);
}else {
confirmation.setEnabled(true);
trashButton.setEnabled(true);
}
}
public int getCount() {
// return 10;
if(AppUtil.appContext.dividedItemList==null) return 0;
return AppUtil.appContext.dividedItemList.size();
}
public Object getItem(int arg0) {
if(AppUtil.appContext.dividedItemList==null) return null;
return AppUtil.appContext.dividedItemList.get(arg0);
}
public long getItemId(int arg0) {
return 0;
}
public View getView(int position, View convertView, ViewGroup container) {
final ViewHolder holder;
final MerchantCartItems mc =
AppUtil.appContext.dividedItemList.get(position);
if(convertView==null){
holder=new ViewHolder();
convertView=inflater.inflate(resId, container,false);
convertView.setTag(holder);
initHolder(holder,convertView,container);
}else{holder=(ViewHolder)convertView.getTag();}
holder.storeName.setText(mc.merchant.merName);
holder.delivery.setChecked(mc.delivery);
holder.pickup.setChecked(!mc.delivery);
int height=AppUtil.calculateListViewHeight(holder.goodsList, subLvItemHeight, mc.items.size());
LayoutParams params=holder.goodsList.getLayoutParams();
params.height=mc.items.size()>3&&position!=AppUtil.appContext.dividedItemList.size()-1?
AppUtil.calculateListViewHeight(holder.goodsList, subLvItemHeight,3):height;
// holder.goodsList.setLayoutParams(params);
holder.postScript.setText(mc.postscript==null||"null".equals(mc.postscript)?"":mc.postscript);
holder.postScript.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean focused) {
if(!focused){
mc.postscript=holder.postScript.getText().toString();
}
}
});
try {
holder.goodsList.setAdapter(new CartItemListAdapterSub_sub(context,mc, this));
} catch (AppException e) {
e.printStackTrace();
}
holder.delivery.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton self, boolean checked) {
mc.delivery=checked;
}
});
return convertView;
}
private void initHolder(ViewHolder holder,View convertView,ViewGroup container){
holder.snap=(ImageButton)convertView.findViewById(R.id.imageButton1);
holder.storeName=(TextView)convertView.findViewById(R.id.textView1);
holder.delivery=(RadioButton)convertView.findViewById(R.id.radio0);
holder.pickup=(RadioButton)convertView.findViewById(R.id.radio1);
holder.goodsList=(InnerListView2)convertView.findViewById(R.id.listView1);
holder.goodsList.setOuterLv((OuterListView)container);
holder.postScript=(EditText)convertView.findViewById(R.id.editText1);
}
class ViewHolder{
public ImageButton snap;
public TextView storeName;
public RadioButton delivery,pickup;
public InnerListView2 goodsList;
public EditText postScript;
}
@Override
public void notifyDataSetChanged() {
updateSubmitButton();updateTotalCost();
super.notifyDataSetChanged();
}
public void clearAllCartItems() throws AppException{
AppUtil.getServiceFactory().getShoppingCartServiceInstance(context).clearAllItems();
notifyDataSetChanged();
}
}
|
/**
*
*/
package com.UBQPageObjectLib;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import com.UBQGenericLib.WebDriverCommonLib;
/**
* @author Basanagouda
*
*/
public class StaffVehicleMapping extends WebDriverCommonLib {
WebDriver driver;
// ----------------------Constructor----------------------//
public StaffVehicleMapping(WebDriver driver) {
this.driver = driver;
}
// ----------------------UI Elements----------------------//
// ---For Select SBU ---//
@FindBy(how = How.XPATH, using = "//select[@id='SBUList']")
private WebElement sbulist;
// ---For Select Vehicle ---//
@FindBy(how = How.XPATH, using = "//select[@id='vehicle']")
private WebElement selectvehicle;
// ---For Select SalesMan ---//
@FindBy(how = How.XPATH, using = "//select[@id='salesMan']")
private WebElement selectsalesman;
// ---For Save Btn ---//
@FindBy(how = How.XPATH, using = "//input[@id='saveButton']")
private WebElement savebtn;
// ---For Clear Btn ---//
@FindBy(how = How.XPATH, using = "//input[@id='clearButton']")
private WebElement clearbtn;
// ---For StaffVehicleListLink ---//
@FindBy(how = How.XPATH, using = "//form[@id='staffVehicleMapForm']/fieldset/table/tbody/tr[4]/td/a")
private WebElement StaffVehicleListLink;
// ---For newWindowElement---//
@FindBy(how = How.TAG_NAME, using = "html")
private WebElement newWindowElement;
// ----------------------Functions----------------------//
// For Select Sbu List
public void selectsbulist(String sbu) {
selectvalue(sbu, sbulist);
}
// For Select Vehicle
public void selectvehicle(String vehicleno) {
selectvalue(vehicleno, selectvehicle);
}
// For Select salesman
public void selectsalesman(String salesman) {
selectvalue(salesman, selectsalesman);
}
// For Click Ok
public void clickSaveBtn() {
buttonClick(savebtn);
}
// For Click Clear
public void clickclearBtn() {
buttonClick(clearbtn);
}
// For Click StaffVehicleListLink
public void clickStaffVehicleListLink() {
buttonClick(StaffVehicleListLink);
}
public int getNumOfRows() {
List<WebElement> size = driver.findElements(By.xpath("//form[@id='staffVehicleMapPreview']/table/tbody/tr"));
// System.out.println(size.size());
return size.size();
}
public String getSBUName() {
WebElement element = driver.findElement(
By.xpath("//*[@id='staffVehicleMapPreview']/table/tbody/tr[" + getNumOfRows() + "]/td[1]"));
highLightElement(driver, element);
return element.getText();
}
public String getSalesmanName() {
WebElement element = driver.findElement(
By.xpath("//*[@id='staffVehicleMapPreview']/table/tbody/tr[" + getNumOfRows() + "]/td[2]"));
highLightElement(driver, element);
return element.getText();
}
public String getVehicleNo() {
WebElement element = driver.findElement(
By.xpath("//*[@id='staffVehicleMapPreview']/table/tbody/tr[" + getNumOfRows() + "]/td[3]"));
highLightElement(driver, element);
return element.getText();
}
public String getVehicleName() {
WebElement element = driver.findElement(
By.xpath("//*[@id='staffVehicleMapPreview']/table/tbody/tr[" + getNumOfRows() + "]/td[4]"));
highLightElement(driver, element);
return element.getText();
}
public int getdatafrommultiplerows(int rnum, int cnum) {
WebElement element = driver
.findElement(By.xpath("//table[@id='batchesTable']/tbody/tr[" + rnum + "]/td[" + cnum + "]"));
highLightElement(driver, element);
int value = Integer.parseInt(element.getText().trim());
// System.out.println(value);
return value;
}
public void closenewwindow() {
newWindowElement.sendKeys(Keys.CONTROL, "W");
}
}
|
package com.alugueaki.project.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.alugueaki.project.domain.Locatario;
public interface LocatarioRepository extends JpaRepository<Locatario, Integer> {
}
|
package com.yokoapps.alarmzeker;
import java.util.ArrayList;
import java.util.Random;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Vibrator;
import androidx.core.app.NotificationCompat;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
ArrayList<AthkarItem> localArrayList;
public ArrayList<AthkarItem> GetData() {
ArrayList<AthkarItem> list = new ArrayList<AthkarItem>();
AthkarItem item = new AthkarItem();
item.setThikrID(1);
item.setSoundID(R.raw.aud1);
item.setThikrName("تباركت يا ذا الجلال والاكرام");
list.add(item);
item = new AthkarItem();
item.setThikrID(2);
item.setSoundID(R.raw.aud2);
item.setThikrName("اشهد ان لا اله الا الله وحده لا شريك له وان محمد عبده ورسوله");
list.add(item);
item = new AthkarItem();
item.setThikrID(3);
item.setSoundID(R.raw.aud3);
item.setThikrName("بسم الله");
list.add(item);
item = new AthkarItem();
item.setThikrID(4);
item.setSoundID(R.raw.aud4);
item.setThikrName("سبحانك اللهم وبحمدك");
list.add(item);
item = new AthkarItem();
item.setThikrID(5);
item.setSoundID(R.raw.aud5);
item.setThikrName("توكلت على الله");
list.add(item);
item = new AthkarItem();
item.setThikrID(6);
item.setSoundID(R.raw.aud6);
item.setThikrName("اللهم افتحلي ابواب رحمتك");
list.add(item);
item = new AthkarItem();
item.setThikrID(7);
item.setSoundID(R.raw.aud7);
item.setThikrName("اللهم انت الملك لا الله الا انت");
list.add(item);
item = new AthkarItem();
item.setThikrID(8);
item.setSoundID(R.raw.aud8);
item.setThikrName("سبحانك اللهم وبحمدك");
list.add(item);
item = new AthkarItem();
item.setThikrID(9);
item.setSoundID(R.raw.aud9);
item.setThikrName("استغفرك واتوب اليك");
list.add(item);
item = new AthkarItem();
item.setThikrID(10);
item.setSoundID(R.raw.aud10);
item.setThikrName("اللهم لك الحمد انت نور السموات والارض ومن في هن");
list.add(item);
item = new AthkarItem();
item.setThikrID(11);
item.setSoundID(R.raw.aud11);
item.setThikrName("انت الاهي لا اله الا انت");
list.add(item);
item = new AthkarItem();
item.setThikrID(12);
item.setSoundID(R.raw.aud12);
item.setThikrName("اللهم لا مانع لما اعطيت وما معطي لما منعت");
list.add(item);
item = new AthkarItem();
item.setThikrID(13);
item.setSoundID(R.raw.aud13);
item.setThikrName("اللهم اهدني في من هديت");
list.add(item);
item = new AthkarItem();
item.setThikrID(14);
item.setSoundID(R.raw.aud14);
item.setThikrName("اللهم اني اعوذ برضاك من سخطك");
list.add(item);
item = new AthkarItem();
item.setThikrID(15);
item.setSoundID(R.raw.aud15);
item.setThikrName("اللهم صلي على محمد وعلى آل ومحمد");
list.add(item);
item = new AthkarItem();
item.setThikrID(16);
item.setSoundID(R.raw.aud16);
item.setThikrName("استغفر الله");
list.add(item);
item = new AthkarItem();
item.setThikrID(17);
item.setSoundID(R.raw.aud17);
item.setThikrName("لا اله الا الله وحده لا شريك له ,له الملك وله الحمد وهو على كل شئ قدير");
list.add(item);
item = new AthkarItem();
item.setThikrID(18);
item.setSoundID(R.raw.aud18);
item.setThikrName("لا حول ولا قوة الا بالله");
list.add(item);
item = new AthkarItem();
item.setThikrID(19);
item.setSoundID(R.raw.aud19);
item.setThikrName("لا اله الا الله ولا نعبد الا اياه");
list.add(item);
item = new AthkarItem();
item.setThikrID(20);
item.setSoundID(R.raw.aud20);
item.setThikrName("اللهم اعني على ذكرك وشكرك وحسن عبادتك");
list.add(item);
item = new AthkarItem();
item.setThikrID(21);
item.setSoundID(R.raw.aud21);
item.setThikrName("سبحان الله وبحمده");
list.add(item);
item = new AthkarItem();
item.setThikrID(22);
item.setSoundID(R.raw.aud22);
item.setThikrName("حسبي الله لا اله الا هو عليه توكلت وهو رب العرش العظيم");
list.add(item);
item = new AthkarItem();
item.setThikrID(23);
item.setSoundID(R.raw.aud23);
item.setThikrName("رضيت بالله ربا وبالاسلام دينا وبمحمد صلى الله عليه وسلم نبيا");
list.add(item);
item = new AthkarItem();
item.setThikrID(24);
item.setSoundID(R.raw.aud24);
item.setThikrName("اللهم اني اسالك علماً نافعا ورزقاً طيبا وعمل متقبلا");
list.add(item);
item = new AthkarItem();
item.setThikrID(25);
item.setSoundID(R.raw.aud25);
item.setThikrName("اللهم صلي وسلم على نبينا محمد");
list.add(item);
item = new AthkarItem();
item.setThikrID(26);
item.setSoundID(R.raw.aud26);
item.setThikrName("اللهم مغفرتك اوسع من ذنوبي");
list.add(item);
item = new AthkarItem();
item.setThikrID(27);
item.setSoundID(R.raw.aud27);
item.setThikrName("الحمدلله كثيراً طيباُ مبارك فيه");
list.add(item);
item = new AthkarItem();
item.setThikrID(28);
item.setSoundID(R.raw.aud28);
item.setThikrName("الحمدلله الذي بنعمته تتم الصالحات");
list.add(item);
item = new AthkarItem();
item.setThikrID(29);
item.setSoundID(R.raw.aud29);
item.setThikrName("لا اله الا الله العظيم الحليم");
list.add(item);
item = new AthkarItem();
item.setThikrID(30);
item.setSoundID(R.raw.aud30);
item.setThikrName("يا حي يا قيوم برحمتك استغيث");
list.add(item);
item = new AthkarItem();
item.setThikrID(31);
item.setSoundID(R.raw.aud31);
item.setThikrName("اعوذ بالله من الشيطان الرجيم");
list.add(item);
item = new AthkarItem();
item.setThikrID(32);
item.setSoundID(R.raw.aud32);
item.setThikrName("اللهم اتنا في الدنيا حسنه وفي الاخرة حسنه وقنا عذاب النار");
list.add(item);
item = new AthkarItem();
item.setThikrID(33);
item.setSoundID(R.raw.aud33);
item.setThikrName("يا مقلب القلوب ثبت قلبي على دينك");
list.add(item);
return list;
}
private MediaPlayer mMediaPlayer;
public void stop() {
if (mMediaPlayer != null) {
if(mMediaPlayer.isPlaying())
mMediaPlayer.stop();
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public void play(Context c, int rid) {
stop();
mMediaPlayer = MediaPlayer.create(c, rid);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
@Override
public void onReceive(Context context, Intent intent) {
try {
localArrayList = GetData();
// Get instance of Vibrator from current Context
Vibrator v1 = (Vibrator) context
.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 300 milliseconds
v1.vibrate(400);
AthkarItem randomStr = localArrayList.get(new Random()
.nextInt(localArrayList.size()));
play(context, randomStr.getSoundID());
Notification(context, randomStr.thikrName);
} catch (Exception e) {
AthkarItem randomStr = localArrayList.get(new Random()
.nextInt(localArrayList.size()-1));
play(context, randomStr.getSoundID());
Notification(context, randomStr.thikrName);
// Get instance of Vibrator from current Context
Vibrator v1 = (Vibrator) context
.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 300 milliseconds
v1.vibrate(400);
}
}
public static final String CHANNEL_ID = "AlarmManagerBroadcastReceiverYokoApps";
public void Notification(Context context, String message) {
String strtitle = "اذكار - منبه صوتي";
// Create an explicit intent for an Activity in your app
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context. NOTIFICATION_SERVICE ) ;
Intent intent = new Intent(context, FullAzkarActivity.class);
intent.putExtra("title", strtitle);
intent.putExtra("text", message);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(strtitle)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true);
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_LOW ;
NotificationChannel notificationChannel = new NotificationChannel( CHANNEL_ID , "AlarmManagerBroadcastReceiverYokoApps" , importance) ;
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel) ;
}
assert notificationManager != null;
notificationManager.notify(1 , builder.build()) ;
}
public void SetAlarm(Context context) {
SharedPreferences pref = context.getSharedPreferences("autoazkaralarm",
0);
int NOTIFY_INTERVAL = 0;
switch (pref.getInt("spinnerSSTIME", 0)) {
case 0:
NOTIFY_INTERVAL = 300 * 1000;
break;
case 1:
NOTIFY_INTERVAL = 600 * 1000;
break;
case 2:
NOTIFY_INTERVAL = 1800 * 1000;
break;
case 3:
NOTIFY_INTERVAL = 3600 * 1000;
break;
case 4:
NOTIFY_INTERVAL = 10800 * 1000;
break;
case 5:
NOTIFY_INTERVAL = 21600 * 1000;
break;
case 6:
NOTIFY_INTERVAL = 43200 * 1000;
break;
case 7:
NOTIFY_INTERVAL = 86400 * 1000;
break;
default:
break;
}
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
// After after 5 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ NOTIFY_INTERVAL, NOTIFY_INTERVAL, pi);
}
public void CancelAlarm(Context context) {
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
|
package org.narl.hrms.visual.rest;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.bson.Document;
import org.narl.hrms.visual.mongo.service.CommondServiceImpl;
import org.narl.hrms.visual.rest.output.EmpCountOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
@Path("employeedatemonth")
public class EmployeeDataByMonthService {
private static final Logger logger = LoggerFactory.getLogger(EmployeeDataByMonthService.class);
private int months=12;
@Autowired
MongoTemplate mongoTemplate;
@Autowired
CommondServiceImpl commondServiceImpl;
String collectionName="ORG_DEPT_EMP_";
/**
* 角色:1,super user
* 組織 : 全選或選一
* 部門:全選
*
* 角色:2,HR
* 組織 : 選一(自己的中心)
* 部門:全選
* by:新增雇用、結束雇用
* */
@POST
@Path("postFindEmpOrgTotal")
@Produces({ MediaType.APPLICATION_JSON })
public List<Document> postFindEmpOrgTotal(@FormParam("year") String yearString, @FormParam("org_id") String org_id) {
logger.info("postFindEmpOrgTotal>> org_id: " +org_id +", yearString: "+yearString );
if (yearString==null )
return new ArrayList<Document>();
String collectName=this.collectionName+yearString;
if (!commondServiceImpl.collectionExisted(collectName))
return new ArrayList<Document>();
List<Document> result=getDefaultDocuments();
for (int mon=1;mon<=this.months; mon++) {
String monthString=String.format("%02d", Integer.valueOf(mon));
String regex=yearString;
if (!monthString.equals("")) {
regex=regex+"/" +monthString +"/";
}
for (Map.Entry<String, String> entry : commondServiceImpl.byMap.entrySet()) {
String whereCond="start_date";
if (entry.getKey().equals("term"))
whereCond="end_date";
else if (entry.getKey().equals("now"))
whereCond="";
Criteria criteriaDefinition = new Criteria();
if (org_id.equals("-1")) {
if (!whereCond.equals(""))
criteriaDefinition.andOperator(Criteria.where(whereCond).regex(regex, "i"));
} else {
if (!whereCond.equals(""))
criteriaDefinition.andOperator(Criteria.where("org_id").is(Integer.valueOf(org_id)), Criteria.where(whereCond).regex(regex, "i"));
else
criteriaDefinition.andOperator(Criteria.where("org_id").is(Integer.valueOf(org_id)));
}
Aggregation aggregation=null;
if (org_id.equals("-1")) {
aggregation=newAggregation(
match(criteriaDefinition),
group().count().as("count")
);
} else {
aggregation=newAggregation(
match(criteriaDefinition),
group("org_name").count().as("count")
);
}
// System.out.println(">>" +aggregation);
AggregationResults groupResults = mongoTemplate.aggregate(
aggregation, collectName, EmpCountOutput.class);
List<EmpCountOutput> aggList = groupResults.getMappedResults();
for (EmpCountOutput a : aggList) {
Document n1=new Document("name", monthString+"月");
n1.append("category", entry.getValue());
n1.append("count", 0);
n1.append("countNow", 0);
if (result.contains(n1)) {
result.remove(n1) ;
}
n1.remove("count");
n1.remove("countNow");
if (entry.getKey().equals("now")) {
n1.append("count", 0);
n1.append("countNow", a.getCount());
} else {
n1.append("countNow", 0);
n1.append("count", a.getCount());
}
result.add(n1);
}
}
}
reBuildDocuments(result);
return result;
}
/**
* 角色:1,2,3
* 部門: 選一個 (角色3為自己所在部門)
* * by:新增雇用、結束雇用
*/
@POST
@Path("postFindEmpDeptTotal")
@Produces({ MediaType.APPLICATION_JSON })
public List<Document> postFindLeaveDeptTotal(@FormParam("year") String yearString, @FormParam("org_id") String org_id,
@FormParam("dept_id") final String dept_id) {
logger.info("postFindEmpDeptTotal>> org_id: " +org_id +", dept_id: " +dept_id +", yearString: "+yearString );
if (yearString==null || dept_id.equals("-1"))
return new ArrayList<Document>();
String collectName=this.collectionName+yearString;
if (!commondServiceImpl.collectionExisted(collectName))
return new ArrayList<Document>();
List<Document> result=getDefaultDocuments();
for (int mon=1;mon<=this.months; mon++) {
String monthString=String.format("%02d", Integer.valueOf(mon));
String regex=yearString;
if (!monthString.equals("")) {
regex=regex+"/" +monthString +"/";
}
for (Map.Entry<String, String> entry : commondServiceImpl.byMap.entrySet()) {
String whereCond="start_date";
if (entry.getKey().equals("term"))
whereCond="end_date";
else if (entry.getKey().equals("now"))
whereCond="";
Criteria criteriaDefinition = new Criteria();
if (whereCond.equals(""))
criteriaDefinition.andOperator( Criteria.where("org_id").is(Integer.valueOf(org_id)),Criteria.where("dept_id").is(Integer.valueOf(dept_id)));
else
criteriaDefinition.andOperator( Criteria.where("org_id").is(Integer.valueOf(org_id)),Criteria.where("dept_id").is(Integer.valueOf(dept_id)), Criteria.where(whereCond).regex(regex, "i"));
Aggregation aggregation =newAggregation(
match(criteriaDefinition),
group("org_name","dept_name").count().as("count")
);
// System.out.println(">>" +aggregation);
AggregationResults groupResults = mongoTemplate.aggregate(
aggregation, collectName, EmpCountOutput.class);
List<EmpCountOutput> aggList = groupResults.getMappedResults();
for (EmpCountOutput a : aggList) {
Document n1=new Document("name",monthString+"月");
n1.append("category", entry.getValue());
n1.append("count", 0);
n1.append("countNow", 0);
if (result.contains(n1)) {
result.remove(n1) ;
}
n1.remove("count");
n1.remove("countNow");
if (entry.getKey().equals("now")) {
n1.append("countNow", a.getCount());
n1.append("count", 0);
} else {
n1.append("countNow", 0);
n1.append("count", a.getCount());
}
result.add(n1);
}
}
}
reBuildDocuments(result);
return result;
}
/**
* make up basic array of documents
* @return
*/
private List<Document> getDefaultDocuments() {
final List<Document> result=new ArrayList<Document>();
for (int mon=1;mon<=this.months; mon++) {
String monthString=String.format("%02d", Integer.valueOf(mon));
for (Map.Entry<String, String> entry : commondServiceImpl.byMap.entrySet()) {
Document n1=new Document("name",monthString+"月");
n1.append("category", entry.getValue());
n1.append("count",0);
n1.append("countNow",0);
result.add(n1);
}
}
return result;
}
/**
* 重整,目前在職人數=目前在職人數CURRENT-新增雇用NEW+結束雇用TERM
* @param result
*/
private void reBuildDocuments(List<Document> result) {
Map<String, Integer> nCount = new HashMap<String, Integer>();
for (Document d : result) {
for (int k=0; k<this.months; k++) {
String monthString=String.format("%02d", Integer.valueOf(k+1));
if (d.get("category").toString().startsWith("C")) {
if (d.get("name").toString().startsWith(monthString+"月")) {
nCount.put(monthString+"月", Integer.valueOf(d.get("countNow").toString()));
}
}
}
}
System.out.println(">>" +nCount);
for (Document d : result) {
for (int k=0; k<this.months; k++) {
String monthString=String.format("%02d", Integer.valueOf(k+1));
if (d.get("category").toString().startsWith("N")) {
if (d.get("name").toString().startsWith(monthString+"月")) {
int count = nCount.get(monthString+"月").intValue()- Integer.valueOf(d.get("count").toString());
nCount.remove(monthString+"月");
nCount.put(monthString+"月", Integer.valueOf(count));
}
}
if (d.get("category").toString().startsWith("T")) {
if (d.get("name").toString().startsWith(monthString+"月")) {
int count = nCount.get(monthString+"月").intValue()+ Integer.valueOf(d.get("count").toString());
nCount.remove(monthString+"月");
nCount.put(monthString+"月", Integer.valueOf(count));
}
}
}
}
// System.out.println(">>" +nCount);
for (Document d : result) {
if (d.get("category").toString().startsWith("C")) {
for (int k=0; k<this.months; k++) {
String monthString=String.format("%02d", Integer.valueOf(k+1));
if (d.get("name").toString().startsWith(monthString+"月")) {
d.remove("countNow");
d.append("countNow", nCount.get(monthString+"月").intValue());
}
}
}
}
// System.out.println(">>" +nCount);
}
}
|
package net.droidlabs.viking.bindings.map.managers;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import java.util.Collection;
public interface IMapEntityManager<T> {
void add(GoogleMap googleMap, T item);
void addItems(GoogleMap googleMap, Collection<T> items);
interface MapResolver {
void resolve(OnMapReadyCallback onMapReadyCallback);
}
}
|
package com.wkrzywiec.spring.library.integration.dao;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import com.wkrzywiec.spring.library.config.LibraryConfig;
import com.wkrzywiec.spring.library.dao.BookDAO;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= LibraryConfig.class)
@WebAppConfiguration("src/main/java")
public class BookDAOIntegrationTest {
@Autowired
private BookDAO bookDAO;
@Test
public void givenAppContext_WhenAutowire_ThenClassesAreAvailble(){
assertNotNull(bookDAO);
}
@Test
@Transactional
public void givenDAO_WhenGetAllReservedBooks_ThenReceiveTotalCount() {
//given
int resultCount = 0;
//when
resultCount = bookDAO.getReservedBooksTotalCount();
//then
assertTrue(resultCount > 0);
}
@Test
@Transactional
public void givenDAO_WhenGetAllBorrowedBooks_ThenReceiveTotalCount() {
//given
int resultCount = 0;
//when
resultCount = bookDAO.getBorrowedBooksTotalCount();
//then
assertTrue(resultCount > 0);
}
@Test
@Transactional
public void givenUserId_whenGetReservedBooksCountForUser_thenReceiveUserReservedBooksTotalCount() {
//given
int userId = 1;
int resultCount = 0;
//when
resultCount = bookDAO.getReservedBooksTotalCountByUser(userId);
//then
assertTrue(resultCount > 0);
}
@Test
@Transactional
public void givenUserId_whenGetBorrowedBooksCountForUser_thenReceiveUserBorrowedBooksTotalCount() {
//given
int userId = 1;
int resultCount = 0;
//when
resultCount = bookDAO.getBorrowedBooksTotalCountByUser(userId);
//then
assertTrue(resultCount > 0);
}
}
|
/** https://codeforces.com/problemset/problem/886/C #greedy #hash-table */
import java.util.HashSet;
import java.util.Scanner;
class PetyaAndCatacombs {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
HashSet<Integer> minuteSet = new HashSet<>();
minuteSet.add(0);
int minute;
for (int i = 1; i < n + 1; i++) {
minute = sc.nextInt();
if (minuteSet.contains(minute)) {
minuteSet.remove(minute);
}
minuteSet.add(i);
}
System.out.println(minuteSet.size());
}
}
|
package generator.util.loop;
import generator.util.Random;
import generator.visitors.AtomicValueType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import java.util.stream.Stream;
public class LoopUtils {
public LoopUtils() {
}
private final ArrayList<String> takenVariableNames = new ArrayList<>();
private final Stack<String> variableNameStack = new Stack<>();
private final AtomicValueType[] VALID_TYPES =
{AtomicValueType.DICTIONARY, AtomicValueType.LIST,
AtomicValueType.STRING, AtomicValueType.SET,
AtomicValueType.TUPLE, AtomicValueType.INT, AtomicValueType.ANY};
private final String[] forEachVarName = {"e", "el", "element", "item"};
private final String[] forInRangeVarName = {"i", "j", "k", "n", "x", "l"};
private LoopType getRandomLoopType() {
return LoopType.values()[Random.randomInt(0, LoopType.values().length - 1)];
}
private LoopType getRandomLoopType(LoopType ... types) {
return types[Random.randomInt(0, types.length - 1)];
}
public LoopDirection getRandomLoopDirection() {
return LoopDirection.values()[Random.randomInt(0, LoopDirection.values().length - 1)];
}
public boolean isValidType(AtomicValueType type) {
return Arrays.asList(VALID_TYPES).contains(type);
}
public LoopStructure getLoopStructure(AtomicValueType type) {
switch(type) {
case LIST:
case ANY:
return LoopStructure.LIST;
case DICTIONARY:
return LoopStructure.DICTIONARY;
case STRING:
return LoopStructure.STRING;
case SET:
return LoopStructure.SET;
case TUPLE:
return LoopStructure.TUPLE;
case INT:
return LoopStructure.INT;
default:
throw new IllegalArgumentException("The AtomicValue type: " + type.toString() + " is not a supported type to be iterated over");
}
}
public Loop generateRandomLoop(String listName, LoopStructure loopStructure) {
switch (loopStructure) {
case LIST:
case STRING:
case TUPLE:
LoopDirection loopDirection = getRandomLoopDirection();
LoopIndices loopIndices = new LoopIndices("len(" + listName + ")", 0, loopDirection);
switch (getRandomLoopType()) {
case FOR_EACH:
return new ForEachLoop(getAvailableForEachName(), listName, loopIndices);
case FOR_IN:
return new ForInRangeLoop(getAvailableForInRangeName(), listName, loopIndices, loopDirection);
case WHILE:
return new WhileLoop(getAvailableForInRangeName(), listName, loopIndices, loopDirection);
}
break;
case INT:
loopDirection = getRandomLoopDirection();
loopIndices = new LoopIndices("" + listName, 0, loopDirection);
switch (getRandomLoopType(LoopType.WHILE, LoopType.FOR_IN)) {
case FOR_IN:
return new ForInRangeLoop(getAvailableForInRangeName(), listName, loopIndices, loopDirection, false);
case WHILE:
return new WhileLoop(getAvailableForInRangeName(), listName, loopIndices, loopDirection, false);
}
case DICTIONARY:
case SET:
return new ForEachLoop(getAvailableForEachName(), listName, null);
}
throw new IllegalStateException("Failed to generate a random loop type");
}
public String getAvailableForEachName() {
for (String name : forEachVarName) {
if (!isVariableNameTaken(name))
return name;
}
throw new ArrayIndexOutOfBoundsException("Could not find any more for each variable names, add more to the pre-defined list!");
}
public String getAvailableForInRangeName() {
for (String name : forInRangeVarName) {
if (!isVariableNameTaken(name))
return name;
}
throw new ArrayIndexOutOfBoundsException("Could not find any more for each variable names, add more to the pre-defined list!");
}
public void addTakenVariableName(String varName) {
takenVariableNames.add(varName);
}
public boolean isVariableNameTaken(String varName) {
return takenVariableNames.contains(varName);
}
public void removeTakenVariableName(String varName) {
takenVariableNames.remove(varName);
}
public String getTakenVariableNames() {
return takenVariableNames.stream().reduce("", (tot, el) -> tot + el + ", ");
}
public String getTopOfVariableNameStack() {
return variableNameStack.peek();
}
public void popVariableNameStack() {
variableNameStack.pop();
}
public void addVariableNameToStack(String varName) {
variableNameStack.push(varName);
}
public boolean inForLoop() {
return !variableNameStack.empty();
}
public String getValidTypesToString() {
return Stream.of(VALID_TYPES).map(AtomicValueType::toString).reduce("", (res, str) -> res.equals("") ? str : res + ", " + str);
}
}
|
package com.tu.mq.kafka;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
/**
* @Description 监听,消费消息
* @Classname Listener
* @Date 2019/5/23 10:40
* @Created by tuyongjian
*/
public class Listener {
private Logger logger = LoggerFactory.getLogger(Listener.class);
@KafkaListener(topics = {"test"})
public void listen(ConsumerRecord<?,?> record){
logger.info("kafka key ---"+record.key());
logger.info("kafka value ---"+record.value());
}
}
|
package com.ahmedonics.apps.ultimateutilitymaster.activities.Others;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.ahmedonics.apps.ultimateutilitymaster.R;
import com.ahmedonics.apps.ultimateutilitymaster.config.Constants;
import com.ahmedonics.apps.ultimateutilitymaster.utils.CommonFunctions;
public class RandomNumberGeneratorActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_number_generator);
setTitle("Random Number Generator");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
SharedPreferences pref = getApplicationContext().getSharedPreferences("appSettings", 0);
boolean check = pref.getBoolean("keep_screen_on_", false);
if (check) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
final EditText et = (EditText) findViewById(R.id.generate_random_number__start_val);
final EditText et2 = (EditText) findViewById(R.id.generate_random_number__end_val);
final EditText et3 = (EditText) findViewById(R.id.generate_random_number__how_many);
et.setText(Constants.random_number_generator_start_min + "");
et2.setText(Constants.random_number_generator_start_max + "");
et3.setText(Constants.random_number_generator_generated_numbers_min + "");
Button btnRandomNumberGeneratorSubmit = (Button) findViewById(R.id.btn_generate_random_number_submit);
btnRandomNumberGeneratorSubmit.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
if (CommonFunctions.isEmptyEditText(et) || CommonFunctions.isEmptyEditText(et2)
|| CommonFunctions.isEmptyEditText(et3) ) {
Toast.makeText(v.getContext(), "You didn't enter required value(s).", Toast.LENGTH_LONG).show();
} else {
int startValue = CommonFunctions.getEditTextAsInt(et);
int endValue = CommonFunctions.getEditTextAsInt(et2);
int howMany = CommonFunctions.getEditTextAsInt(et3);
if (howMany < Constants.random_number_generator_generated_numbers_min || howMany > Constants.random_number_generator_generated_numbers_max) {
Toast.makeText(v.getContext(), "Can't generate this much random numbers.", Toast.LENGTH_LONG).show();
} else if (startValue >= endValue || startValue < Constants.random_number_generator_start_min || startValue > Constants.random_number_generator_start_max) {
Toast.makeText(v.getContext(), "Invalid start value.", Toast.LENGTH_LONG).show();
} else if (endValue <= startValue || endValue < Constants.random_number_generator_start_min || endValue > Constants.random_number_generator_start_max) {
Toast.makeText(v.getContext(), "Invalid end value.", Toast.LENGTH_LONG).show();
} else if (endValue - startValue <= Constants.random_number_generator_start_stop_margin) {
Toast.makeText(v.getContext(), "Start and End value should have min difference of 100.", Toast.LENGTH_LONG).show();
} else {
String text = "Generated Random Numbers:\n\n";
for (int i = 1; i <= howMany; i++) {
if (i > 1) text += ", ";
text += CommonFunctions.generateRandomNumber(startValue, endValue);
}
CommonFunctions.resultSharingDialog(RandomNumberGeneratorActivity.this, text);
}
}
}
});
}
}
|
package com.ex.musicdb.model.binding;
import com.ex.musicdb.model.entities.enums.Genre;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
public class ArticleAddBindingModel {
@NotEmpty
@Size(min = 3, max = 20)
private String title;
@NotEmpty
@Size(min = 5)
private String imageUrl;
@NotNull
private Genre genre;
@NotEmpty
@Size(min = 5)
private String content;
@DateTimeFormat(pattern = "dd-MM-yyyy HH:mm")
private LocalDateTime createdOn;
public ArticleAddBindingModel() {
}
public String getTitle() {
return title;
}
public ArticleAddBindingModel setTitle(String title) {
this.title = title;
return this;
}
public String getImageUrl() {
return imageUrl;
}
public ArticleAddBindingModel setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
return this;
}
public Genre getGenre() {
return genre;
}
public ArticleAddBindingModel setGenre(Genre genre) {
this.genre = genre;
return this;
}
public String getContent() {
return content;
}
public ArticleAddBindingModel setContent(String content) {
this.content = content;
return this;
}
public LocalDateTime getCreatedOn() {
return createdOn;
}
public ArticleAddBindingModel setCreatedOn(LocalDateTime createdOn) {
this.createdOn = createdOn;
return this;
}
}
|
package org.garret.perst.impl;
import org.garret.perst.*;
import org.garret.perst.reflect.*;
import java.util.Date;
class BtreeFieldIndex extends Btree implements FieldIndex {
String className;
String fieldName;
long autoincCount;
transient Type cls;
transient Field fld;
public BtreeFieldIndex() {}
public void writeObject(IOutputStream out) {
super.writeObject(out);
out.writeString(className);
out.writeString(fieldName);
out.writeLong(autoincCount);
}
public void readObject(IInputStream in) {
super.readObject(in);
className = in.readString();
fieldName = in.readString();
autoincCount = in.readLong();
cls = ReflectionProvider.getInstance().getType(className);
locateField();
}
private final void locateField()
{
fld = cls.getField(fieldName);
if (fld == null) {
throw new StorageError(StorageError.INDEXED_FIELD_NOT_FOUND, className + "." + fieldName);
}
}
public Class getIndexedClass() {
return cls.getDescribedClass();
}
public String[] getKeyFields() {
return new String[]{fieldName};
}
BtreeFieldIndex(Class cls, String fieldName, boolean unique) {
this(cls, fieldName, unique, 0);
}
BtreeFieldIndex(Class cls, String fieldName, boolean unique, long autoincCount) {
this.cls = ReflectionProvider.getInstance().getType(cls);
this.unique = unique;
this.fieldName = fieldName;
this.className = cls.getName();
this.autoincCount = autoincCount;
locateField();
type = checkType(Types.getTypeCode(fld.getType()));
}
private Key extractKey(IPersistent obj) {
try {
Field f = fld;
Key key = null;
switch (type) {
case Types.Boolean:
key = new Key(f.getBoolean(obj));
break;
case Types.Byte:
key = new Key(f.getByte(obj));
break;
case Types.Short:
key = new Key(f.getShort(obj));
break;
case Types.Char:
key = new Key(f.getChar(obj));
break;
case Types.Int:
key = new Key(f.getInt(obj));
break;
case Types.Object:
{
IPersistent ptr = (IPersistent)f.get(obj);
if (ptr != null && !ptr.isPersistent())
{
getStorage().makePersistent(ptr);
}
key = new Key(ptr);
break;
}
case Types.Long:
key = new Key(f.getLong(obj));
break;
case Types.Date:
key = new Key((Date)f.get(obj));
break;
case Types.Float:
key = new Key(f.getFloat(obj));
break;
case Types.Double:
key = new Key(f.getDouble(obj));
break;
case Types.String:
{
Object val = f.get(obj);
if (val != null) {
key = new Key((String)val);
}
}
break;
case Types.ArrayOfByte:
{
byte[] arr = (byte[])f.get(obj);
key = new Key(arr, (f.getModifiers() & Modifier.FixedSize) != 0 ? arr.length : 0);
}
break;
default:
Assert.failed("Invalid type");
}
return key;
} catch (Exception x) {
throw new StorageError(StorageError.ACCESS_VIOLATION, x);
}
}
public boolean put(IPersistent obj) {
Key key = extractKey(obj);
return key != null && super.insert(key, obj, false) >= 0;
}
public IPersistent set(IPersistent obj) {
Key key = extractKey(obj);
if (key == null) {
throw new StorageError(StorageError.KEY_IS_NULL);
}
return super.set(key, obj);
}
public void remove(IPersistent obj) {
Key key = extractKey(obj);
if (key != null) {
super.remove(key, obj);
}
}
public boolean containsObject(IPersistent obj) {
Key key = extractKey(obj);
if (key == null) {
return false;
}
if (unique) {
return super.get(key) != null;
} else {
IPersistent[] mbrs = get(key, key);
for (int i = 0; i < mbrs.length; i++) {
if (mbrs[i] == obj) {
return true;
}
}
return false;
}
}
public boolean contains(IPersistent obj) {
Key key = extractKey(obj);
if (key == null) {
return false;
}
if (unique) {
return super.get(key) != null;
} else {
IPersistent[] mbrs = get(key, key);
for (int i = 0; i < mbrs.length; i++) {
if (mbrs[i].equals(obj)) {
return true;
}
}
return false;
}
}
public synchronized void append(IPersistent obj) {
Key key;
try {
switch (type) {
case Types.Int:
key = new Key((int)autoincCount);
fld.setInt(obj, (int)autoincCount);
break;
case Types.Long:
key = new Key(autoincCount);
fld.setLong(obj, autoincCount);
break;
default:
throw new StorageError(StorageError.UNSUPPORTED_INDEX_TYPE, fld.getType());
}
} catch (Exception x) {
throw new StorageError(StorageError.ACCESS_VIOLATION, x);
}
autoincCount += 1;
obj.modify();
super.insert(key, obj, false);
}
public IPersistent[] get(Key from, Key till) {
ArrayList list = new ArrayList();
if (root != 0) {
BtreePage.find((StorageImpl)getStorage(), root, checkKey(from), checkKey(till), this, height, list);
}
return (IPersistent[])list.toArray(new IPersistent[list.size()]);
}
public IPersistent[] toPersistentArray() {
IPersistent[] arr = new IPersistent[nElems];
if (root != 0) {
BtreePage.traverseForward((StorageImpl)getStorage(), root, type, height, arr, 0);
}
return arr;
}
public boolean isCaseInsensitive() {
return false;
}
}
class BtreeCaseInsensitiveFieldIndex extends BtreeFieldIndex {
BtreeCaseInsensitiveFieldIndex() {}
BtreeCaseInsensitiveFieldIndex(Class cls, String fieldName, boolean unique) {
super(cls, fieldName, unique);
}
BtreeCaseInsensitiveFieldIndex(Class cls, String fieldName, boolean unique, long autoincCount) {
super(cls, fieldName, unique, autoincCount);
}
Key checkKey(Key key) {
if (key != null && key.oval instanceof String) {
key = new Key(((String)key.oval).toLowerCase(), key.inclusion != 0);
}
return super.checkKey(key);
}
public boolean isCaseInsensitive() {
return true;
}
}
|
package com.example.seyoung.finalhhproject;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class tab4 extends Activity {
TextView foodtv;//음식에 관한 설명을 적는 텍스트뷰
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab4_frame);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);//갤러리
foodtv=(TextView)findViewById(R.id.foodtv) ;//텍스트뷰
MyGalleryAdapter galAdapter = new MyGalleryAdapter(this);
gallery.setAdapter(galAdapter);
}
public class MyGalleryAdapter extends BaseAdapter {
Context context;
Integer[] posterID = { R.drawable.beef, R.drawable.bibimbap,
R.drawable.chicken, R.drawable.coffee, R.drawable.fish,
R.drawable.hambuger, R.drawable.jajang, R.drawable.kimbab,
R.drawable.pasta, R.drawable.pizza, R.drawable.ramen,
R.drawable.shrimp, R.drawable.sushi, R.drawable.torti,
R.drawable.mandu, R.drawable.noodle };
//음식의 이름과 설명
String[] foodTitle = { "부드러운 소고기 : 280kcal", "맛있는 비빔밥 : 706kcal", "바삭바삭 치킨 : 1700kcal",
"달달한 커피 : 200kcal", "쫄깃한 회 : 100kcal", "동그란 햄버거 : 558kcal", " 맛있는 자장면 : 864kcal",
"영양가득 김밥 : 500kcal", "담백한 파스타 : 400kcal", "맛있는 피자 : 253kcal", "간편한 라면 : 422kcal",
"건강한 새우요리 : 700kcal", "싱싱한 초밥 : 140kcal", "이국적인 토르티야 : 319kcal", "간편한 만두 : 52kcal", "상쾌한 국수 : 374kcal"};
public MyGalleryAdapter(Context c) {
context = c;
}
public int getCount() {
return posterID.length;
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageview = new ImageView(context);
imageview.setLayoutParams(new Gallery.LayoutParams(200, 300));
imageview.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageview.setPadding(5, 5, 5, 5);
imageview.setImageResource(posterID[position]);
final int pos = position;
imageview.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
ImageView ivPoster = (ImageView) findViewById(R.id.ivPoster);
ivPoster.setScaleType(ImageView.ScaleType.FIT_CENTER);
ivPoster.setImageResource(posterID[pos]);
foodtv.setText(foodTitle[pos]);
return false;
}
});
return imageview;
}
}
}
|
package cn.com.xbed.common.util.response;
/**
* 业务返回参数
* @Title: ServiceCode.java
* @Package cn.com.xbed.util.response
* @Description: TODO
* @author porridge
* @date 2015年11月26日 下午1:07:40
* @version V1.0
*/
public class ServiceCode {
public static final int OK = 21020000;
public static final String OK_DEFAULT_MSG = "操作成功";
public static final int DELETE_SUCCESS = 22020001;
public static final String DELETE_SUCCESS_MSG = "删除成功";
public static final int DELETE_FAILURE = 42020002;
public static final String DELETE_FAILURE_MSG = "删除失败";
public static final int UNAUTHORIZED = 42020003;
public static final String UNAUTHORIZED_DEFAULT_MSG = "未授权,或授权过期";
public static final int MISSING_PARAM_CODE = 42020004;
public static final String MISSING_PARAM_CODE_DEFAULT_MSG = "缺少参数";
public static final int PAGE_NOT_FOUND = 42020005;
public static final String PAGE_NOT_FOUND_DEFAULT_MSG = "找不到请求的页面";
public static final int RESOURCE_NOT_FOUND = 42020006;
public static final String RESOURCE_NOT_FOUND_DEFAULT_MSG = "找不到请求的资源";
//无效参数
public static final int INVILD_PARAM_CODE = 42020007;
public static final String INVILD_PARAM_DEFAULT_MSG = "无效参数";
public static final int OTHER_API_ERROR_CODE = 42020008;
public static final String OTHER_API_ERROR_CODE_DEFAULT_MSG = "%s服务发生错误,传递数据:%s 服务返回结果:%s";
public static final int ERROR = 42020000;
public static final String ERROR_DEFAULT_MSG = "操作失败";
public static final int SERVER_ERROR = 52020000;
public static final String SERVER_ERROR_DEFAULT_MSG = "系统异常,请重试";
public static final int SERVER_REPETITION = 62020001;
public static final String SERVER_REPETITION_DEFAULT_MSG = "操作失败,存在重复数据";
public static final int EXIST_PHONE_ERROR = 62020002;
public static final String EXIST_PHONE_ERROR_DEFAULT_MSG = "用户手机号码已存在,不能够重复注册";
public static final int VERIFY_PHONE_CODE_ERROR = 62020003;
public static final String VERIFY_PHONE_CODE_ERROR_DEFAULT_MSG = "短信验证码输入错误或过期";
public static final int CHECKIN_CLEAN_CODE = 72020001;
public static final String CHECKIN_CLEAN_CODE_DEFAULT_MSG = "需要在住清洁评价";
public static final int CHECKIN_CLEAN_TIME_CODE = 72020002;
public static final String CHECKIN_CLEAN_TIME_CODE_DEFAULT_MSG = "可申请在住清洁";
public static final int UNDER_APPLY_CANCEL_CODE = 72020003;
public static final String UNDER_APPLY_CANCEL_CODE_DEFAULT_MSG = "已经申请了在住清洁,再次申请需取消上一单,确定取消吗";
public static final int UNDER_APPLY_CODE = 72020004;
public static final String CUNDER_APPLY_CODE_DEFAULT_MSG = "清洁管家已经出发前往打扫,不能再次申请";
public static final int CHECKINID_VALID_CODE = 72020005;
public static final String CHECKINID_VALID_CODE_DEFAULT_MSG = "该入住单不存在";
public static final int CHECKINTIME_VALID_CODE = 72020006;
public static final String CHECKINTIME_VALID_CODE_DEFAULT_MSG = "申请在住清洁时间超出范围";
public static final int STEP_VALID_CODE = 72020007;
public static final String STEP_VALID_CODE_DEFAULT_MSG = "该入住单不在入住状态";
public static final int CLEAN_TIME_VALID_CODE = 72020008;
public static final String CLEAN_TIME_VALID_CODE_DEFAULT_MSG = "对不起,目前不能申请在住清洁";
public static final int CHECKIN_CLEAN_ERROR = 72029999;
public static final String CHECKIN_CLEAN_ERROR_DEFAULT_MSG = "调用丽佳会检查是否允许申请在住清洁接口发生错误";
public static final String CANCEL_CHECKINORDER_OVER_TIME_MSG = "对不起,已经超过14点,订单不能取消";
public static final String CHECKIN_STATUS_MSG = "已经有人办理了入住,订单不能取消";
public static final int EVALUEATED_CODE = 72020009;
public static final String EVALUEATED_CODE_DEFAULT_MSG = "您已评价过该房间";
public static final int PAY_NEEDED_CLEAN_ORDER = 72020010;
public static final String PAY_NEEDED_CLEAN_ORDER_DEFAULT_MSG = "该请结单需要用户支付";
}
|
package org.zeos.cafe.dao.impl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.zeos.cafe.dao.DishDao;
import org.zeos.cafe.entity.Dish;
import org.zeos.cafe.entity.DishType;
import java.util.List;
/**
* Created by alxev on 09.07.2017.
*/
@Repository
public class DishDaoImpl implements DishDao {
private SessionFactory sessionFactory;
private Session session;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
this.session = this.sessionFactory.openSession();
}
public Dish getById(int id) {
return session.get(Dish.class, id);
}
public void delete(Dish dish) {
session.delete(dish);
}
public void insert(Dish dish) {
session.saveOrUpdate(dish);
}
public List<Dish> getAll() {
return (List<Dish>) session.createQuery(" from Dish").list();
}
public List<Dish> getByType(DishType dishType) {
return (List<Dish>) session.createQuery("from Dish where dishTypeId = :dishTypeId").setParameter("dishTypeId", dishType.getId()).list();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.