text stringlengths 10 2.72M |
|---|
/*
* 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 morpion;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Observable;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author vinotco
*/
public class VueMorpion extends Observable{
private final JFrame window ;
private final JPanel middlePanel;
private final ArrayList <JButton> listeBouttons = new ArrayList<>();
private final JButton classement;
private final JButton pSuivante;
public VueMorpion (String j1, String j2){
window = new JFrame("Morpion");
window.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
// Définit la taille de la fenêtre en pixels
window.setSize(1200, 800);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation(dim.width/2-window.getSize().width/2, dim.height/2-window.getSize().height/2);
JPanel mainPanel = new JPanel(new BorderLayout());
window.add(mainPanel) ;
JPanel topPanel = new JPanel (new GridLayout(2, 5));
mainPanel.add(topPanel, BorderLayout.NORTH);
topPanel.add(new JLabel("Joueur 1 :"));
topPanel.add(new JLabel(j1));
topPanel.add(new JLabel(""));
topPanel.add(new JLabel("Joueur 2 :"));
topPanel.add(new JLabel(j2));
topPanel.add(new JLabel(""));
JLabel image = new JLabel("O");
topPanel.add(image);
topPanel.add(new JLabel(""));
topPanel.add(new JLabel(""));
topPanel.add(new JLabel(""));
JLabel image2 = new JLabel( "X");
topPanel.add(image2);
middlePanel = new JPanel (new GridLayout(3, 3));
mainPanel.add(middlePanel, BorderLayout.CENTER);
JButton zero = new JButton();listeBouttons.add(zero);
zero.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(listeBouttons.indexOf(zero));
clearChanged();
}
});
JButton un = new JButton();listeBouttons.add(un);
un.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(listeBouttons.indexOf(un));
clearChanged();
}
});
JButton deux = new JButton();listeBouttons.add(deux);
deux.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(listeBouttons.indexOf(deux));
clearChanged();
}
});
JButton trois = new JButton();listeBouttons.add(trois);
trois.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(listeBouttons.indexOf(trois));
clearChanged();
}
});
JButton quatre = new JButton();listeBouttons.add(quatre);
quatre.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(listeBouttons.indexOf(quatre));
clearChanged();
}
});
JButton cinq = new JButton();listeBouttons.add(cinq);
cinq.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(listeBouttons.indexOf(cinq));
clearChanged();
}
});
JButton six = new JButton();listeBouttons.add(six);
six.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(listeBouttons.indexOf(six));
clearChanged();
}
});
JButton sept = new JButton();listeBouttons.add(sept);
sept.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(listeBouttons.indexOf(sept));
clearChanged();
}
});
JButton huit = new JButton();listeBouttons.add(huit);
huit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(listeBouttons.indexOf(huit));
clearChanged();
}
});
for( int i = 0; i<=8; i++){
middlePanel.add(listeBouttons.get(i));
}
JPanel bottomPanel = new JPanel (new GridLayout(1, 4));
mainPanel.add(bottomPanel, BorderLayout.SOUTH);
classement = new JButton("Classement");
classement.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(Action.CLASSEMENT);
clearChanged();
}
});
bottomPanel.add(classement);
bottomPanel.add(new JLabel(""));
bottomPanel.add(new JLabel(""));
pSuivante = new JButton("Partie Suivante");
pSuivante.setEnabled(false);
pSuivante.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setChanged();
notifyObservers(Action.NEXT);
clearChanged();
}
});
bottomPanel.add(pSuivante);
}
public JButton getpSuivante() {
return pSuivante;
}
public JPanel getMiddlePanel() {
return middlePanel;
}
public void afficher() {
this.window.setVisible(true);
}
public void close() {
this.window.dispose();
}
public JFrame getWindow() {
return window;
}
public ArrayList <JButton> getListeBouttons() {
return listeBouttons;
}
}
|
package nom.hhx.cache.impl;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import nom.hhx.cache.Key;
public abstract class ObjectCacheAdapter<KEY extends Key, OBJECT> extends CacheAdapter<KEY,OBJECT>
{
public ObjectCacheAdapter( int cachesize )
{
super( cachesize );
cache = new ConcurrentHashMap<KEY,OBJECT>( (int)(cachesize/0.75) );
}
protected Map<KEY,OBJECT> cache;
}
|
import java.util.Scanner;
import java.util.Arrays;
public class exe10 {
public static void main(String[] args) {
Scanner leia = new Scanner (System.in);
int i, total = 0, soma, pessoas, maiorIdade = 0, menorIdade = 0, mulheres = 0, j = 0;
double media=0, menorSalario=0 ;
System.out.println("Insira a quantidade de pessoas:");
pessoas = leia.nextInt();
String sexo[] = new String [pessoas];
int idade[] = new int [pessoas];
double salario[] = new double [pessoas];
for(i=0 ; i<pessoas; i++){
System.out.println("Insira o sexo");
sexo[i] = leia.next();
System.out.println("Insira a idade");
idade[i] = leia.nextInt();
System.out.println("Insira o salário");
salario[i] = leia.nextDouble();
media = media + salario[i] ;
if(maiorIdade == 0) {
maiorIdade = idade[i] ;
}
if(menorIdade == 0) {
menorIdade = idade[i] ;
}
if(maiorIdade < idade[i] ) {
maiorIdade = idade[i] ;
}
if(menorIdade > idade[i] ) {
menorIdade = idade[i] ;
}
if(sexo[i].equals("f")) {
mulheres++;
}
if(menorSalario == 0) {
menorSalario = salario[i] ;
}
if(menorSalario > salario[i] ) {
j = i ;
}
}
media = media / pessoas ;
System.out.println("Média:"+ media);
System.out.println("Maior Idade:"+maiorIdade);
System.out.println("Menor Idade:"+menorIdade);
System.out.println("Número de Mulheres:"+mulheres);
System.out.println("A idade da pessoa que tem o menor salário é:"+idade[j]);
System.out.println("O sexo da pessoa que tem o menor salário:"+sexo[j]);
}
}
|
package com.example.mrmadom2;
import java.util.ArrayList;
import androidx.recyclerview.widget.DiffUtil;
public class ContactDiffCallback extends DiffUtil.Callback {
private ArrayList<Contact> mOldList;
private ArrayList<Contact> mNewList;
public ContactDiffCallback(ArrayList<Contact> oldList, ArrayList<Contact> newList) {
mOldList = oldList;
mNewList = newList;
}
@Override
public int getOldListSize() {
return mOldList.size();
}
@Override
public int getNewListSize() {
return mNewList.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
Contact oldContact = mOldList.get(oldItemPosition);
Contact newContact = mNewList.get(newItemPosition);
return oldContact.getId() == newContact.getId();
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
Contact oldContact = mOldList.get(oldItemPosition);
Contact newContact = mNewList.get(newItemPosition);
return oldContact.getName().equals(newContact.getName());
}
}
|
/*
* Created by Angel Leon (@gubatron), Alden Torres (aldenml)
* Copyright (c) 2011-2014, FrostWire(R). All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.frostwire.gui.library;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JList;
import javax.swing.ListModel;
import com.frostwire.alexandria.Playlist;
import com.frostwire.gui.library.LibraryPlaylists.LibraryPlaylistsListCell;
import com.frostwire.gui.player.MediaPlayer;
import com.frostwire.mplayer.MediaPlaybackState;
import com.limegroup.gnutella.gui.GUIMediator;
/**
*
* @author gubatron
* @author aldenml
*
*/
public class LibraryIconList extends JList<Object> {
private Image speaker;
private Image loading;
public LibraryIconList() {
loadIcons();
}
public LibraryIconList(ListModel<Object> dataModel) {
super(dataModel);
loadIcons();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
MediaPlayer player = MediaPlayer.instance();
if (player.getState() != MediaPlaybackState.Stopped) {
if (player.getCurrentMedia() != null && player.getCurrentPlaylist() != null && player.getPlaylistFilesView() != null) {
int index = getPlaylistIndex(player.getCurrentPlaylist());
if (index != -1) {
paintIcon(g, speaker, index);
}
}
}
paintImportingIcons(g);
}
private void loadIcons() {
speaker = GUIMediator.getThemeImage("speaker").getImage();
loading = GUIMediator.getThemeImage("indeterminate_small_progress").getImage();
}
private void paintIcon(Graphics g, Image image, int index) {
Rectangle rect = getUI().getCellBounds(this, index, index);
Dimension lsize = rect.getSize();
Point llocation = rect.getLocation();
g.drawImage(image, llocation.x + lsize.width - speaker.getWidth(null) - 4, llocation.y + (lsize.height - speaker.getHeight(null)) / 2, null);
}
private int getPlaylistIndex(Playlist playlist) {
int n = getModel().getSize();
for (int i = 0; i < n; i++) {
Object value = getModel().getElementAt(i);
if (value instanceof LibraryPlaylistsListCell) {
Playlist p = ((LibraryPlaylistsListCell) value).getPlaylist();
if (p != null && p.equals(playlist)) {
return i;
}
}
}
return -1;
}
private void paintImportingIcons(Graphics g) {
int n = getModel().getSize();
for (int i = 0; i < n; i++) {
Object value = getModel().getElementAt(i);
if (value instanceof LibraryPlaylistsListCell) {
Playlist p = ((LibraryPlaylistsListCell) value).getPlaylist();
if (LibraryMediator.instance().getLibraryPlaylists().isPlaylistImporting(p)) {
paintIcon(g, loading, i);
}
} else {
return;
}
}
}
}
|
package controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import models.ModelOperaciones;
import views.ViewOperaciones;
/**
*
* @author Lupita
*/
public class ControllerOperaciones {
public ViewOperaciones view_operaciones;
public ModelOperaciones model_operaciones;
public MouseListener mouselistener = new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getSource() == view_operaciones.jb_suma) {
model_operaciones.jb_suma();
} else if (e.getSource() == view_operaciones.jb_resta) {
model_operaciones.jb_resta();
} else if (e.getSource() == view_operaciones.jb_multiplicacion) {
model_operaciones.multiplicacion();
} else if (e.getSource() == view_operaciones.jb_residuo) {
model_operaciones.jb_residuo();
} else {
model_operaciones.divicion();
}
}
@Override
public void mousePressed(MouseEvent e) {
if (e.getSource() == view_operaciones.jb_suma) {
model_operaciones.jb_suma();
} else if (e.getSource() == view_operaciones.jb_resta) {
model_operaciones.jb_resta();
} else if (e.getSource() == view_operaciones.jb_multiplicacion) {
model_operaciones.multiplicacion();
} else if (e.getSource() == view_operaciones.jb_residuo) {
model_operaciones.jb_residuo();
} else {
model_operaciones.divicion();
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getSource() == view_operaciones.jb_suma) {
model_operaciones.jb_suma();
} else if (e.getSource() == view_operaciones.jb_resta) {
model_operaciones.jb_resta();
} else if (e.getSource() == view_operaciones.jb_multiplicacion) {
model_operaciones.multiplicacion();
} else if (e.getSource() ==view_operaciones.jb_residuo) {
model_operaciones.jb_residuo();
} else {
model_operaciones.divicion();
}
}
@Override
public void mouseEntered(MouseEvent e) {
if (e.getSource() == view_operaciones.jb_suma) {
model_operaciones.jb_suma();
} else if (e.getSource() == view_operaciones.jb_resta) {
model_operaciones.jb_resta();
} else if (e.getSource() == view_operaciones.jb_multiplicacion) {
model_operaciones.multiplicacion();
} else if (e.getSource() == view_operaciones.jb_residuo) {
model_operaciones.jb_residuo();
} else {
model_operaciones.divicion();
}
}
@Override
public void mouseExited(MouseEvent e) {
if (e.getSource() == view_operaciones.jb_suma) {
model_operaciones.jb_suma();
} else if (e.getSource() == view_operaciones.jb_resta) {
model_operaciones.jb_resta();
} else if (e.getSource() == view_operaciones.jb_multiplicacion) {
model_operaciones.multiplicacion();
} else if (e.getSource() == view_operaciones.jb_residuo) {
model_operaciones.jb_residuo();
} else {
model_operaciones.divicion();
}
}
};
public ControllerOperaciones(ModelOperaciones modelOperaciones, ViewOperaciones viewOperaciones) {
this.model_operaciones = modelOperaciones;
this.view_operaciones = viewOperaciones;
initView();
this.view_operaciones.jb_suma.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
addButton(e);
}
});
this.view_operaciones.jb_resta.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
jb_restaButton(e);
}
});
this.view_operaciones.jb_residuo.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
jb_residuoButton(e);
}
});
this.view_operaciones.jb_multiplicacion.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
multiplicateButton(e);
}
});
this.view_operaciones.jb_divicion.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
divideButton(e);
}
});
}
public void addButton(ActionEvent e){
double firstValue = Double.parseDouble(this.view_operaciones.jtx_primeroValue.getText());
double secondValue = Double.parseDouble(this.view_operaciones.jtx_segundoValue.getText());
this.model_operaciones.setValues(firstValue, secondValue);
this.view_operaciones.jtx_resultado.setText(""+this.model_operaciones.jb_suma());
}
public void jb_restaButton(ActionEvent e){
double firstValue = Double.parseDouble(this.view_operaciones.jtx_primeroValue.getText());
double secondValue = Double.parseDouble(this.view_operaciones.jtx_segundoValue.getText());
this.model_operaciones.setValues(firstValue, secondValue);
this.view_operaciones.jtx_resultado.setText(""+this.model_operaciones.jb_resta());
}
public void jb_residuoButton(ActionEvent e){
double firstValue = Double.parseDouble(this.view_operaciones.jtx_primeroValue.getText());
double secondValue = Double.parseDouble(this.view_operaciones.jtx_segundoValue.getText());
this.model_operaciones.setValues(firstValue, secondValue);
this.view_operaciones.jtx_resultado.setText(""+this.model_operaciones.jb_residuo());
}
public void multiplicateButton(ActionEvent e){
double firstValue = Double.parseDouble(this.view_operaciones.jtx_primeroValue.getText());
double secondValue = Double.parseDouble(this.view_operaciones.jtx_segundoValue.getText());
this.model_operaciones.setValues(firstValue, secondValue);
this.view_operaciones.jtx_resultado.setText(""+this.model_operaciones.multiplicacion());
}
public void divideButton(ActionEvent e){
double firstValue = Double.parseDouble(this.view_operaciones.jtx_primeroValue.getText());
double secondValue = Double.parseDouble(this.view_operaciones.jtx_segundoValue.getText());
this.model_operaciones.setValues(firstValue, secondValue);
this.view_operaciones.jtx_resultado.setText(""+this.model_operaciones.divicion());
}
public void initView(){
this.view_operaciones.setTitle("Calculadora");
this.view_operaciones.setLocationRelativeTo(null);
this.view_operaciones.setVisible(true);
}
}
|
package com.ferreusveritas.growingtrees.worldgen;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import javax.imageio.ImageIO;
import com.ferreusveritas.growingtrees.util.Circle;
import net.minecraft.world.gen.NoiseGeneratorPerlin;
public class CircleDebug {
public static int scale = 8;
public static void outputCirclesToPng(ArrayList<Circle> circles, int chunkX, int chunkZ, String name){
int width = 48 * scale;
int height = 48 * scale;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Color lightGrey = new Color(186, 189, 182);
Color darkGrey = new Color(136, 138, 133);
for(int gz = 0; gz < 3; gz++){
for(int gx = 0; gx < 3; gx++){
drawRect(img, gx * 16 * scale, gz * 16 * scale, 16 * scale, 16 * scale, ((gz * 3 + gx) % 2) == 0 ? lightGrey : darkGrey);
}
}
for(Circle c: circles){
drawCircle(img, c, (chunkX - 1) * 16, (chunkZ - 1) * 16);
}
if(name.isEmpty()){
name = "unresolved-" + chunkX + ":" + chunkZ;
}
//System.out.println("Writing:" + name + ".png");
try {
ImageIO.write(img, "png", new File("./unsolved/" + name + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void drawCircle(BufferedImage image, Circle circle, int xOffset, int zOffset){
Color green = new Color(115, 210, 22, circle.real ? 192 : 64);
Color red = new Color(204, 0, 0, circle.real ? 192 : 64);
Color col = circle.hasFreeAngles() ? red : green;
int startX = circle.x - circle.radius;
int stopX = circle.x + circle.radius;
int startZ = circle.z - circle.radius;
int stopZ = circle.z + circle.radius;
for(int z = startZ; z <= stopZ; z++){
for(int x = startX; x <= stopX; x++){
if(circle.isInside(x, z)){
drawRect(image, (x - xOffset) * scale, (z - zOffset) * scale, scale, scale, col);
//safeSetRGB(image, x - xOffset, z - zOffset, col);
}
}
}
//Draw arc segments
double radius = circle.radius + 0.5f;
for(int i = 0; i < 32; i++){
boolean isOn = (circle.arc & (1 << i)) != 0;
double x1 = circle.x + 0.5 + Math.cos(Math.PI * 2 * i / 32.0) * radius;
double z1 = circle.z + 0.5 + Math.sin(Math.PI * 2 * i / 32.0) * radius;
double x2 = circle.x + 0.5 + Math.cos(Math.PI * 2 * (i + 1)/ 32.0) * radius;
double z2 = circle.z + 0.5 + Math.sin(Math.PI * 2 * (i + 1) / 32.0) * radius;
drawLine(image, (int)((x1 - xOffset) * scale), (int)((z1 - zOffset) * scale), (int)((x2 - xOffset) * scale), (int)((z2 - zOffset) * scale), (((i & 1) == 0) ? (isOn ? Color.BLACK : Color.PINK) : (isOn ? Color.DARK_GRAY : Color.CYAN)));
}
}
public static void drawLine(BufferedImage image, int x1, int z1, int x2, int z2, Color color){
int w = x2 - x1 ;
int h = z2 - z1 ;
int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ;
if (w<0) dx1 = -1 ; else if (w>0) dx1 = 1 ;
if (h<0) dy1 = -1 ; else if (h>0) dy1 = 1 ;
if (w<0) dx2 = -1 ; else if (w>0) dx2 = 1 ;
int longest = Math.abs(w) ;
int shortest = Math.abs(h) ;
if (!(longest>shortest)) {
longest = Math.abs(h) ;
shortest = Math.abs(w) ;
if (h<0) dy2 = -1 ; else if (h>0) dy2 = 1 ;
dx2 = 0 ;
}
int numerator = longest >> 1 ;
for (int i=0;i<=longest;i++) {
safeSetRGB(image, x1,z1,color) ;
numerator += shortest ;
if (!(numerator<longest)) {
numerator -= longest ;
x1 += dx1 ;
z1 += dy1 ;
} else {
x1 += dx2 ;
z1 += dy2 ;
}
}
}
public static void drawRect(BufferedImage image, int x, int z, int w, int h, Color color){
for(int zi = 0; zi < h; zi++){
for(int xi = 0; xi < w; xi++){
safeSetRGB(image, x + xi, z + zi, color);
}
}
}
public static void safeSetRGB(BufferedImage image, int x, int z, Color color){
if(x >= 0 && z >= 0 && x < image.getWidth() && z < image.getHeight()){
color.getAlpha();
Color dst = new Color(image.getRGB(x, z));
float dr = dst.getRed() / 255f;
float dg = dst.getGreen() / 255f;
float db = dst.getBlue() / 255f;
float sr = color.getRed() / 255f;
float sg = color.getGreen() / 255f;
float sb = color.getBlue() / 255f;
float sa = color.getAlpha() / 255f;
//Simple Alpha blending
image.setRGB(x, z, new Color(sr * sa + dr * (1f - sa), sg * sa + dg * (1f - sa), sb * sa + db * (1f - sa)).getRGB());
}
}
public static void initNoisetest() {
int width = 128;
int height = 128;
NoiseGeneratorPerlin noiseGenerator = new NoiseGeneratorPerlin(new Random(2), 1);
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for(int oct = 0; oct < 7; oct++){
System.out.println("Noise" + oct);
for(int i = 0; i < width; i++) {
for(int j = 0; j < height; j++) {
float noise = (float) ((noiseGenerator.func_151601_a(i / 64.0, j / 64.0) + 1D) / 2.0D);
switch(oct){
case 6: noise += (float) ((noiseGenerator.func_151601_a(i / 1.0, j / 1.0) + 1D) / 2.0D) / 64;
case 5: noise += (float) ((noiseGenerator.func_151601_a(i / 2.0, j / 2.0) + 1D) / 2.0D) / 32;
case 4: noise += (float) ((noiseGenerator.func_151601_a(i / 4.0, j / 4.0) + 1D) / 2.0D) / 16;
case 3: noise += (float) ((noiseGenerator.func_151601_a(i / 8.0, j / 8.0) + 1D) / 2.0D) / 8;
case 2: noise += (float) ((noiseGenerator.func_151601_a(i / 16.0, j / 16.0) + 1D) / 2.0D) / 4;
case 1: noise += (float) ((noiseGenerator.func_151601_a(i / 32.0, j / 32.0) + 1D) / 2.0D) / 2;
}
noise /= 2;
int value = (int) (255 * noise);
img.setRGB(i, j, new Color(value, value, value).getRGB());
}
}
try {
ImageIO.write(img, "png", new File("./" + "noise" + oct + ".png"));
} catch(IOException e) {
e.printStackTrace();
}
}
}
////////////////////////////////////////////////////////////
public static void initCircleTests(){
ArrayList<Circle> circles = new ArrayList<Circle>();
/*
Circle c1 = new Circle(8, 8, 8);//Right in the middle
c1.real = true;
circles.add(c1);
Circle c2 = CircleHelper.findSecondCircle(c1, 7);
c1.real = true;
circles.add(c2);
Circle c3 = CircleHelper.findThirdCircle(c1, c2, 4);
if(c3 != null){
circles.add(c3);
Circle c4 = CircleHelper.findThirdCircle(c1, c3, 6);
if(c4 != null){
circles.add(c4);
}
c4 = CircleHelper.findThirdCircle(c3, c2, 2);
if(c4 != null){
circles.add(c4);
}
}
for(Circle cOut: circles){
for(Circle cIn: circles){
CircleHelper.maskCircles(cOut, cIn);
}
}
outputCirclesToPng(circles, 0, 0, "masking");
int xOffset = -48 * 16;
int zOffset = 44 * 16;
for(int r = 2; r <= 8; r++){
//Test 1 (nonarant test)
circles.clear();
circles.add(new Circle(-8 + xOffset, -8 + zOffset, r));
circles.add(new Circle( 8 + xOffset, -8 + zOffset, r));
circles.add(new Circle(24 + xOffset, -8 + zOffset, r));
circles.add(new Circle(-8 + xOffset, 8 + zOffset, r));
circles.add(new Circle( 8 + xOffset, 8 + zOffset, r));
circles.add(new Circle(24 + xOffset, 8 + zOffset, r));
circles.add(new Circle(-8 + xOffset, 24 + zOffset, r));
circles.add(new Circle( 8 + xOffset, 24 + zOffset, r));
circles.add(new Circle(24 + xOffset, 24 + zOffset, r));
for(Circle c: circles){c.edgeMask(xOffset, zOffset);}
outputCirclesToPng(circles, xOffset >> 4, zOffset >> 4, "test 1r" + r);
//Test 2 (Outside Edge Test)
circles.clear();
circles.add(new Circle(-3 + xOffset, 8 + zOffset, r));
circles.add(new Circle( 18 + xOffset, 8 + zOffset, r));
circles.add(new Circle(8 + xOffset, -3 + zOffset, r));
circles.add(new Circle(8 + xOffset, 18 + zOffset, r));
for(Circle c: circles){c.edgeMask(xOffset, zOffset);}
outputCirclesToPng(circles, xOffset >> 4, zOffset >> 4, "test 2r" + r);
//Test 3 (Inside Edge Test)
circles.clear();
circles.add(new Circle(4 + xOffset, 8 + zOffset, r));
circles.add(new Circle(11 + xOffset, 8 + zOffset, r));
circles.add(new Circle(8 + xOffset, 4 + zOffset, r));
circles.add(new Circle(8 + xOffset, 11 + zOffset, r));
for(Circle c: circles){c.edgeMask(xOffset, zOffset);}
outputCirclesToPng(circles, xOffset >> 4, zOffset >> 4, "test 3r" + r);
//Test 4 (Inside Corner Test)
circles.clear();
circles.add(new Circle(4 + xOffset, 4 + zOffset, r));
circles.add(new Circle(11 + xOffset, 4 + zOffset, r));
circles.add(new Circle(4 + xOffset, 11 + zOffset, r));
circles.add(new Circle(11 + xOffset, 11 + zOffset, r));
for(Circle c: circles){c.edgeMask(xOffset, zOffset);}
outputCirclesToPng(circles, xOffset >> 4, zOffset >> 4, "test 4r" + r);
//Test 5 (Outside Corner Test)
circles.clear();
circles.add(new Circle(-3 + xOffset, -3 + zOffset, r));
circles.add(new Circle(-3 + xOffset, 18 + zOffset, r));
circles.add(new Circle(18 + xOffset, -3 + zOffset, r));
circles.add(new Circle(18 + xOffset, 18 + zOffset, r));
for(Circle c: circles){c.edgeMask(xOffset, zOffset);}
outputCirclesToPng(circles, xOffset >> 4, zOffset >> 4, "test 5r" + r);
//Test 6
circles.clear();
circles.add(new Circle(16 + xOffset, 16 + zOffset, r));
circles.add(new Circle(-1 + xOffset, 16 + zOffset, r));
circles.add(new Circle(16 + xOffset, -1 + zOffset, r));
circles.add(new Circle(-1 + xOffset, -1 + zOffset, r));
for(Circle c: circles){c.edgeMask(xOffset, zOffset);}
outputCirclesToPng(circles, xOffset >> 4, zOffset >> 4, "test 6r" + r);
//Test 7
circles.clear();
circles.add(new Circle(15 + xOffset, 15 + zOffset, r));
circles.add(new Circle(0 + xOffset, 15 + zOffset, r));
circles.add(new Circle(15 + xOffset, 0 + zOffset, r));
circles.add(new Circle(0 + xOffset, 0 + zOffset, r));
for(Circle c: circles){c.edgeMask(xOffset, zOffset);}
outputCirclesToPng(circles, xOffset >> 4, zOffset >> 4, "test 7r" + r);
}
*/
}
////////////////////////////////////////////////////////////
public static void saveImage(BufferedImage img, String directory, String name) throws IOException {
ImageIO.write(img, "png", new File(directory + name + ".png"));
}
public static void setAlpha(BufferedImage img, int alpha) {
for(int i = 0; i < img.getWidth(); i++) {
for(int j = 0; j < img.getHeight(); j++) {
Color currentColor = new Color(img.getRGB(i, j));
Color newColor = new Color(currentColor.getRed(), currentColor.getGreen(), currentColor.getBlue(), alpha);
img.setRGB(i, j, newColor.getRGB());
}
}
}
}
|
package api.algorithm.selection;
import java.util.ArrayList;
import java.util.List;
import api.RandomNumbers;
import api.model.individual.Individual;
public class ProbabilisticTournament extends DeterministicTournament {
public ProbabilisticTournament(int numberOfSelected) {
super(numberOfSelected,2);
}
protected List<Individual> selectRandomContestants(List<Individual> poblation){
List<Individual> res = new ArrayList<>();
for(int i=0; i<2; i++){
res.add(poblation.get((int) (RandomNumbers.getInstance().getRandomNumber()*poblation.size())));
}
return res;
}
protected Individual selectBest(List<Individual> contestants){
double randomNumber = RandomNumbers.getInstance().getRandomNumber();
Individual best = contestants.get(0);
Individual worst = contestants.get(1);
if(best.getFitness() < worst.getFitness()){
Individual aux = worst;
worst = best;
best = aux;
}
if(randomNumber < 0.75 ){
return best;
}else{
return worst;
}
}
}
|
/*
* @(#)$Id: MinimumEscapeHandler.java,v 1.2 2005/09/10 19:07:39 kohsuke Exp $
*/
/*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the "License"). You may not use this file except
* in compliance with the License.
*
* You can obtain a copy of the license at
* https://jwsdp.dev.java.net/CDDLv1.0.html
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* HEADER in each file and include the License file at
* https://jwsdp.dev.java.net/CDDLv1.0.html If applicable,
* add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your
* own identifying information: Portions Copyright [yyyy]
* [name of copyright owner]
*/
package com.sun.xml.bind.marshaller;
import java.io.IOException;
import java.io.Writer;
/**
* Performs no character escaping. Usable only when the output encoding
* is UTF, but this handler gives the maximum performance.
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
public class MinimumEscapeHandler implements CharacterEscapeHandler {
private MinimumEscapeHandler() {} // no instanciation please
public static final CharacterEscapeHandler theInstance = new MinimumEscapeHandler();
public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
// avoid calling the Writerwrite method too much by assuming
// that the escaping occurs rarely.
// profiling revealed that this is faster than the naive code.
int limit = start+length;
for (int i = start; i < limit; i++) {
char c = ch[i];
if( c=='&' || c=='<' || c=='>' || (c=='\"' && isAttVal) ) {
if(i!=start)
out.write(ch,start,i-start);
start = i+1;
switch (ch[i]) {
case '&' :
out.write("&");
break;
case '<' :
out.write("<");
break;
case '>' :
out.write(">");
break;
case '\"' :
out.write(""");
break;
}
}
}
if( start!=limit )
out.write(ch,start,limit-start);
}
}
|
package com.netcracker.repositories;
//import org.springframework.data.repository.CrudRepository;
import com.netcracker.entities.Complain;
import com.netcracker.entities.Group;
import com.netcracker.entities.Route;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.netcracker.entities.User;
import java.util.List;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
User findUserByEmail(String email);
List<User> findAllByRoutes(Route route);
List<User> findAllByGroups(Group group);
User findUserByFio(String username);
User findUserByUserId(Long userId);
@Query("select c from User c where c.numberOfComplaints > 0 order by c.numberOfComplaints desc ")
List<User> findUsers();
/*@PersistenceContext
private EntityManager em;*/
}
|
/**
* @author Michael Avnyin
* THIS IS A GUI APPLICATION OF MY DATABASE
*
* ************IMPORTANT***************
*
* MyDbGui IS A SEPERATE JAVA FILE
* IF YOU WOULD LIKE TO VIEW DATABASE IN GUI PLEASE RUN SEPERATLEY
* ALSO IT IS IMPORTANT TO BUILD A PATH TO THE JAR FILE LABELED "rs2xml" LOCATED IN THE FOLDER
* ONCE YOU HAVE INCLUDED rs2xml JAR file to referenced library you can compile and the GUI WILL SHOW UP
* CLICK "LOAD DATABASE" TO HAVE THE DB APPEAR IN JFRAME
*
* ************IMPORTANT***************
*/
import java.awt.EventQueue;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import java.util.Properties;
import javax.swing.*;
import net.proteanit.sql.DbUtils; // useful and very important to get the infomation to populate
public class MyDbGui {
private JFrame frame;
private JTable table;
private final String userName = "root";
private final String password = "root";
private final String serverName = "localhost";
private final int portNumber = 3306;
private final String dbName = "test";
private final String tableName = "STUDENTS1";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyDbGui window = new MyDbGui(); // create a new window
window.frame.setVisible(true); // set the window visible
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application calls initialize.
* @throws SQLException
*/
public MyDbGui() throws SQLException {
initialize();
}
/**
* getConnection method establishes a connection to database to allow all the functionality
* @return conn sends back the connection
* @throws SQLException
*/
public Connection getConnection() throws SQLException{
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
conn = DriverManager.getConnection("jdbc:mysql://" + this.serverName + ":" + this.portNumber + "/" + this.dbName, connectionProps);
return conn;
}
/**
* Initialize the contents of the frame.
*/
Connection conn = null;
private void initialize() throws SQLException {
conn = this.getConnection(); // create connection
frame = new JFrame(); //
frame.setBounds(100, 100, 700, 400); // sets size of window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // closes when you close window
frame.getContentPane().setLayout(null); //
JButton btnLoadDatabase = new JButton("LOAD DATABASE"); // create our button
btnLoadDatabase.addActionListener(new ActionListener() { // our button linked to action listener which will load our db
public void actionPerformed(ActionEvent e) {
try{
String query = "select * from STUDENTS1"; // query gets all from database
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception ee){
ee.printStackTrace();
}
}
});
btnLoadDatabase.setBounds(272, 6, 150, 40);
frame.getContentPane().add(btnLoadDatabase);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(17, 58, 666, 302);
frame.getContentPane().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
} |
package com.epam.meal.parser.dom;
import com.epam.meal.parser.entity.Meal;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* DOM parser XML-file
*/
public class MenuDOMParser {
/**
* file's name
*/
private static final String FILE_NAME = "menu.xml";
/**
* tags' and attributes' names
*/
private static final String PART = "part";
private static final String CATEGORY = "category";
private static final String MEAL = "meal";
private static final String ID = "id";
private static final String PHOTO = "photo";
private static final String TITLE = "title";
private static final String DESCRIPTION = "description";
private static final String PORTION = "portion";
private static final String PRICE = "price";
/**
* List for adding information from menu
*/
private List<Meal> mealList = new ArrayList<>();
public List<Meal> getMealList() {
return mealList;
}
/**
* parse XML-file
*
* @throws SAXException if problem with parsing
* @throws IOException if problem with file
*/
public void parse() throws SAXException, IOException {
Document document = getDocument();
Element root = document.getDocumentElement();
NodeList partNodes = root.getElementsByTagName(PART);
Meal meal = null;
for (int i = 0; i < partNodes.getLength(); i++) {
meal = new Meal();
Element partElement = (Element) partNodes.item(i);
meal.setCategory(partElement.getAttribute(CATEGORY));
setParameter(meal, partElement);
}
}
/**
* get DOM document
*
* @return document
* @throws SAXException if problem with parsing
* @throws IOException if problem with file
*/
private static Document getDocument() throws SAXException, IOException {
DOMParser parserDOM = new DOMParser();
parserDOM.parse(FILE_NAME);
Document document = parserDOM.getDocument();
return document;
}
/**
* set meals' parameters
*
* @param meal - meal
* @param partElement - element "part" from XML-file
*/
private void setParameter(Meal meal, Element partElement) {
Element mealElement = getChild(partElement, MEAL);
NodeList mealNode = partElement.getElementsByTagName(MEAL);
for (int j = 0; j < mealNode.getLength(); j++) {
meal.setId(mealElement.getAttribute(ID));
meal.setPhoto(getChild(mealElement, PHOTO).getTextContent());
meal.setTitle(getChild(mealElement, TITLE).getTextContent());
meal.setDescription(getChild(mealElement, DESCRIPTION).getTextContent());
meal.setPortion(getChild(mealElement, PORTION).getTextContent());
meal.setPrice(getChild(mealElement, PRICE).getTextContent());
mealList.add(meal);
}
}
/***
* get child element
*
* @param element - from which get a child
* @param childName - child's name
* @return child element
*/
private static Element getChild(Element element, String childName) {
NodeList childList = element.getElementsByTagName(childName);
Element child = (Element) childList.item(0);
return child;
}
}
|
import java.util.Scanner;
public class cMatrix
{
private Scanner scan;
private int matrixA[][];
private int matrixB[][];
private int matrixC[][];
private int size;
public cMatrix()
{
scan = new Scanner(System.in);
System.out.println("Matrix Creation");
System.out.println("\n Wpisz rozmiar macierzy M :");
this.size = scan.nextInt();
matrixA = new int[size][size];
matrixB = new int[size][size];
matrixC = new int[size][size];
}
private void create(int matrix[][], int size)
{
for(int i=0; i<size; i++)
{
for(int j=0; j<size; j++)
{
matrix[i][j] = scan.nextInt();
}
}
}
private void display(int matrix[][]) {
for(int i=0; i<size; i++) {
for(int j=0; j<size; j++) {
System.out.print("\t" + matrix[i][j]);
}
System.out.println();
}
}
private void AddMartix() //fix naming
{
for(int i=0; i<size; i++)
{
for(int j=0; j<size; j++)
{
matrixC[i][j] = matrixA[i][j] + matrixB[i][j];
}
}
}
public void CleanMatrixC()
{
for(int i=0; i<size; i++)
{
for(int j=0; j<size; j++)
{
matrixC[i][j] =0;
}
}
}
private void MultiplyMatrix()
{
int sum = 0;
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
{
for(int l = 0; l < size ; l++)
{
sum += matrixA[i][l] * matrixB[l][j];
}
matrixC[i][j] = sum;
sum = 0;
}
}
}
public void transpose(int matrix[][])
{
matrixC=matrix;
for(int i = 0; i < size; ++i)
{
for(int j = i + 1; j < size; ++j)
{
int temp = matrixC[i][j];
matrixC[i][j] = matrixC[j][i];
matrixC[j][i] = temp;
}
}
}
public void run()
{
System.out.println("Wpisz macierz A:");
create(matrixA, size);
System.out.println("Wpisz macierz B:");
create(matrixB, size);
System.out.println("Macierz A :");
display(matrixA);
System.out.println("Macierz B :");
display(matrixB);
System.out.println("Suma Macierzy A + B :");
AddMartix();
display(matrixC);
CleanMatrixC();
System.out.println("Iloczyn macierzy A + B :");
MultiplyMatrix();
display(matrixC);
CleanMatrixC();
System.out.println("Macierz transponowana dla macierzy A :");
transpose(matrixA);
display(matrixC);
CleanMatrixC();
System.out.println(" Macierz transponowana dla macierz B :");
transpose(matrixB);
display(matrixC);
CleanMatrixC();
}
}
|
package com.unicom.patrolDoor.service;
import com.unicom.patrolDoor.entity.Recommend;
import java.util.List;
import java.util.Map;
/**
* @Author wrk
* @Date 2021/4/13 9:56
*/
public interface RecommendService {
void insertRecommend(Recommend recommend);
Recommend selectByQuestionId(int questionId);
void updateRecommend(Integer id,String recommendTime);
List<Map<String, Object>> selectList();
}
|
package by.epam.kooks.action.post;
import by.epam.kooks.action.constants.Constants;
import by.epam.kooks.action.manager.Action;
import by.epam.kooks.entity.Customer;
import by.epam.kooks.action.get.AbstractBasket;
import by.epam.kooks.action.manager.ActionResult;
import by.epam.kooks.entity.Basket;
import by.epam.kooks.entity.Transaction;
import by.epam.kooks.service.TransactionService;
import by.epam.kooks.entity.BookInfo;
import by.epam.kooks.service.BookService;
import by.epam.kooks.service.exception.ServiceException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Action class , allows customers take a book from basket
*
* @author Eugene Kooks
*/
public class CustomerTakeBookFromBasket extends AbstractBasket implements Action {
private static final Logger log = LogManager.getLogger(CustomerTakeBookFromBasket.class);
@Override
public ActionResult execute(HttpServletRequest req, HttpServletResponse resp) {
TransactionService transactionService = new TransactionService();
BookService bookService = new BookService();
Transaction transaction = new Transaction();
Customer customer = new Customer();
BookInfo bookInfo;
HttpSession session = req.getSession();
Basket basket = getBasket(session);
int id = (int) session.getAttribute(Constants.ATT_CUSTOMER_ID);
int bookInfoId = Integer.parseInt(req.getParameter(Constants.ATT_BOOK_INFO_ID));
int bookId = Integer.parseInt(req.getParameter(Constants.BOOK_ID));
try {
bookInfo = bookService.findBookInfoByBookId(bookId);
customer.setId(id);
transaction.setCustomer(customer);
transaction.setBookInfo(bookInfo);
if (transactionService.isBookInTransactionAlreadyTaken(transaction) || transactionService.countActiveTransaction(transaction) > Constants.MAX_COUNT_BOOKS) {
req.setAttribute(Constants.ATT_TAKE_ERROR, true);
log.debug("Can't past checking for isAlready taken {} and max count book{}", transactionService.isBookInTransactionAlreadyTaken(transaction), transactionService.countActiveTransaction(transaction) > Constants.MAX_COUNT_BOOKS);
return new ActionResult(Constants.BASKET);
} else {
basket.delete(bookInfoId);
transactionService.customerTakeBook(transaction);
log.debug("Book deleted from basket and take book where customer id = {}", customer.getId());
}
} catch (ServiceException e) {
log.warn("Can't book delete from basket and take book where customer id = {}", customer.getId(), e);
}
return new ActionResult(Constants.BASKET, true);
}
}
|
package org.kiworkshop.jdbctemplate;
import org.kiworkshop.dao.MemberDao;
import org.kiworkshop.domain.Member;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import javax.sql.DataSource;
import java.util.List;
import java.util.stream.Collectors;
public class MemberDaoSimpleJdbcInsertImpl implements MemberDao {
private final SimpleJdbcInsert simpleJdbcInsert;
public MemberDaoSimpleJdbcInsertImpl(DataSource dataSource) {
this.simpleJdbcInsert = new SimpleJdbcInsert(dataSource)
.withTableName("member");
}
@Override
public void insert(Member member) {
SqlParameterSource source = new MapSqlParameterSource()
.addValue("id", member.getId())
.addValue("name", member.getName())
.addValue("point", member.getPoint());
simpleJdbcInsert.execute(source);
}
public void insertAll(List<Member> members) {
List<MapSqlParameterSource> sources = members.stream()
.map(member -> new MapSqlParameterSource()
.addValue("id", member.getId())
.addValue("name", member.getName())
.addValue("point", member.getPoint())
).collect(Collectors.toList());
simpleJdbcInsert.executeBatch(sources.toArray(new MapSqlParameterSource[0]));
}
@Override
public void update(Member member) {
}
@Override
public void delete(Member member) {
}
@Override
public void deleteAll() {
}
@Override
public Member findById(Long id) {
return null;
}
@Override
public List<Member> findAll() {
return null;
}
}
|
package com.karya.controller;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.karya.bean.RegistrationBean;
import com.karya.model.Login001MB;
import com.karya.service.IRegistrationService;
@Controller
@RequestMapping(value="Registration")
public class RegistrationController {
@Resource(name="RegistrationService")
private IRegistrationService registrationService;
private @Value("${Registration.SecurityQuestion}") String[] securityQuestionList;
private @Value("${Login.Domain}") String[] domainList;
@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView role(@ModelAttribute("command") RegistrationBean registrationBean,BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("securityQuestionList", securityQuestionList);
model.put("domainList", domainList);
model.put("loginBeanList", prepareListofBean(registrationService.listregisterpages()));
return new ModelAndView("register", model);
}
@RequestMapping(value = "/deleteregisterpage", method = RequestMethod.GET)
public ModelAndView deletepage(@ModelAttribute("command") RegistrationBean registrationBean,
BindingResult result) {
registrationService.deletepage(registrationBean.getId());
Map<String, Object> model = new HashMap<String, Object>();
model.put("securityquestionlists", securityQuestionList);
model.put("domainList", domainList);
model.put("loginBeanList", prepareListofBean(registrationService.listregisterpages()));
registrationBean = new RegistrationBean();
return new ModelAndView("register", model);
}
@RequestMapping(value = "/editregisterpage", method = RequestMethod.GET)
public ModelAndView registerpage(@ModelAttribute("command") RegistrationBean registrationBean,
BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("securityQuestionList", securityQuestionList);
model.put("domainList", domainList);
model.put("loginBean", prepareRegistrationBean(registrationService.getregisterpage(registrationBean.getId())));
model.put("loginBeanList", prepareListofBean(registrationService.listregisterpages()));
return new ModelAndView("register", model);
}
@RequestMapping(value = "/registrationsave")
public ModelAndView registrationsave(@ModelAttribute("command") @Valid RegistrationBean registrationBean,BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("securityQuestionList", securityQuestionList);
model.put("domainList", domainList);
model.put("loginBeanList", prepareListofBean(registrationService.listregisterpages()));
if (result.hasErrors()) {
return new ModelAndView("register", model);
}
registrationService.save(prepareModel(registrationBean));
return new ModelAndView("redirect:/Registration/register", model);
}
@RequestMapping(value = "/changeusername", method = RequestMethod.GET)
public ModelAndView changeusername(@ModelAttribute("command") RegistrationBean registrationBean,BindingResult result,
Principal user) {
Login001MB login001MB = new Login001MB();
Map<String, Object> model = new HashMap<String, Object>();
ModelAndView model1 = new ModelAndView();
if (user != null) {
String usernametemp = user.getName().substring(0, 1).toUpperCase();
String username = usernametemp + user.getName().substring(1);
model1.addObject("msg", username);
}
model.put("loginbean", login001MB);
//return new ModelAndView("changeusername", model);
model1.setViewName("changeusername");
return model1;
}
@RequestMapping(value = "/saveusername")
public ModelAndView saveusername(@ModelAttribute("command") @Valid RegistrationBean registrationBean,
BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
Login001MB login001MB = new Login001MB();
login001MB.setUsername(registrationBean.getUsername());
registrationService.saveusername(registrationBean.getUsername(),registrationBean.getNewusername());
//model.put("loginBean", prepareRegistrationBeanUN(registrationService.saveusername(existingusername, newusername)));
//System.out.println(newusername);
//model.put("loginBean", prepareRegistrationBeanUN(registrationService.saveusername(existingusername, username));
return new ModelAndView("redirect:/Registration/changeusername", model);
}
@RequestMapping(value = "/changepassword", method = RequestMethod.GET)
public ModelAndView changepassword(@ModelAttribute("command") RegistrationBean registrationBean,
BindingResult result,Principal user) {
//Map<String, Object> model = new HashMap<String, Object>();
ModelAndView model1 = new ModelAndView();
if (user != null) {
String usernametemp = user.getName().substring(0, 1).toUpperCase();
String username = usernametemp + user.getName().substring(1);
model1.addObject("msg", username);
}
model1.setViewName("changepassword");
return model1;
}
@RequestMapping(value = "/savepassword")
public ModelAndView savepassword(@ModelAttribute("command") @Valid RegistrationBean registrationBean,
BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
Login001MB login001MB = new Login001MB();
login001MB.setPassword(registrationBean.getPassword());
registrationService.savepassword(registrationBean.getUsername(),registrationBean.getNewpassword());
//model.put("loginBean", prepareRegistrationBeanUN(registrationService.saveusername(existingusername, newusername)));
//System.out.println(newusername);
//model.put("loginBean", prepareRegistrationBeanUN(registrationService.saveusername(existingusername, username));
return new ModelAndView("redirect:/Registration/changepassword", model);
}
private RegistrationBean prepareRegistrationBean(Login001MB login001mb) {
RegistrationBean bean = new RegistrationBean();
bean.setFirstname(login001mb.getFirstname());
bean.setLastname(login001mb.getLastname());
bean.setId(login001mb.getId());
bean.setPassword(login001mb.getPassword());
bean.setDomain(login001mb.getDomain());
bean.setSecurityquestion(login001mb.getSecurityquestion());
bean.setSecurityanswer(login001mb.getSecurityanswer());
bean.setUsername(login001mb.getUsername());
bean.setMessage(login001mb.getMessage());
return bean;
}
private List<RegistrationBean> prepareListofBean(List<Login001MB> login001mblist) {
List<RegistrationBean> beans = null;
if(login001mblist != null && !login001mblist.isEmpty()){
beans = new ArrayList<RegistrationBean>();
RegistrationBean bean = null;
for(Login001MB login001mb : login001mblist){
bean = new RegistrationBean();
bean.setFirstname(login001mb.getFirstname());
bean.setLastname(login001mb.getLastname());
bean.setId(login001mb.getId());
bean.setUsername(login001mb.getUsername());
bean.setPassword(login001mb.getPassword());
bean.setDomain(login001mb.getDomain());
bean.setEnabled(login001mb.isEnabled());
bean.setSecurityquestion(login001mb.getSecurityquestion());
bean.setSecurityanswer(login001mb.getSecurityanswer());
bean.setMessage(login001mb.getMessage());
beans.add(bean);
}
}
return beans;
}
private Login001MB prepareModel(RegistrationBean registrationBean ){
Login001MB login001MB = new Login001MB();
login001MB.setFirstname(registrationBean.getFirstname());
login001MB.setLastname(registrationBean.getLastname());
login001MB.setUsername(registrationBean.getUsername());
login001MB.setPassword(registrationBean.getPassword());
login001MB.setDomain(registrationBean.getDomain());
login001MB.setSecurityquestion(registrationBean.getSecurityquestion());
login001MB.setSecurityanswer(registrationBean.getSecurityanswer());
login001MB.setId(registrationBean.getId());
login001MB.setMessage(registrationBean.getMessage());
return login001MB;
}
}
|
package dto.logs;
public class ErroresDTO {
private String tituloError;
private String mensajeError;
public String getMensajeError() {
return mensajeError;
}
public void setMensajeError(String mensajeError) {
this.mensajeError = mensajeError;
}
public String getTituloError() {
return tituloError;
}
public void setTituloError(String tituloError) {
this.tituloError = tituloError;
}
}
|
package com.gamzat;
/**
* Created by Гамзат on 30.05.2017.
*/
public class Bender {
public static void main (String [] args ){
double Bart;
Bart = 460.128;
System.out.println("Я хочу ");
System.out.println(Bart);
System.out.println("долларов в день!");
}
}
|
/*
* 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 Business.StructuralHealthMonitor;
import Business.Architecture.Architecture;
import java.util.Date;
/**
*
* @author User
*/
public class SensorData {
private int inputForce;
private float outputVoltage;
private String serialNumber;
private String location;
private String status;
private String date;
/**
* @return the inputForce
*/
public int getInputForce() {
return inputForce;
}
/**
* @param inputForce the inputForce to set
*/
public void setInputForce(int inputForce) {
this.inputForce = inputForce;
}
/**
* @return the outputVoltage
*/
public float getOutputVoltage() {
return outputVoltage;
}
/**
* @param outputVoltage the outputVoltage to set
*/
public void setOutputVoltage(int inputForce) {
float out =inputForce/20;
this.outputVoltage = out;
}
/**
* @return the serialNumber
*/
public String getSerialNumber() {
return serialNumber;
}
/**
* @param serialNumber the serialNumber to set
*/
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
/**
* @return the date
*/
/**
* @return the location
*/
public String getLocation() {
return location;
}
/**
* @param location the location to set
*/
public void setLocation(String location) {
this.location = location;
}
/**
* @return the date
*/
public String getDate() {
return date;
}
/**
* @param date the date to set
*/
public void setDate(String date) {
this.date = date;
}
/**
* @return the date
*/
}
|
package com.example.learningspring.controller;
import com.example.learningspring.data.entity.Room;
import com.example.learningspring.data.repository.RoomRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/rooms")
public class RoomController {
private final RoomRepository roomRepository;
public RoomController(RoomRepository roomRepository) {
this.roomRepository = roomRepository;
}
@GetMapping
public Iterable<Room> getRooms() {
return this.roomRepository.findAll();
}
}
|
package examples;
import mdb.Model;
import java.sql.SQLException;
public class Course extends Model {
public static final String table = "courses";
public static final String[] attributes = {"id", "name"};
public Course() {
super();
}
public Course(int id) throws SQLException {
super(id);
}
public String toString() {
return (String) get("name");
}
}
|
package com.health.system.domain.dto;
import com.health.system.domain.SysPost;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 岗位表 sys_post
*
* @author zq
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class SysPostDto extends SysPost {
/**
* 用户是否存在此岗位标识 默认不存在
*/
private boolean flag = false;
}
|
package com.dalong;
import org.springframework.stereotype.Service;
@Service
public class ThirdLogin implements UserLogin{
@Override
public String login(String name, int age) {
return "third";
}
}
|
package com.wxt.designpattern.flyweight.test02.example1;
import java.util.*;
/**
* 供测试用,在内存中模拟数据库中的值
*/
public class TestDB {
/**
* 用来存放单独授权数据的值
*/
public static List<String> colDB = new ArrayList<>();
/**
* 用来存放组合授权数据的值,key为组合数据的id,value为该组合包含的多条授权数据的值
*/
public static Map<String,String[]> mapDB = new HashMap<>();
static{
//通过静态块来填充模拟的数据,增加一个标识来表明是否组合授权数据
colDB.add("张三,人员列表,查看,1");
colDB.add("李四,人员列表,查看,1");
colDB.add("李四,操作薪资数据,,2");
mapDB.put("操作薪资数据",new String[]{"薪资数据,查看","薪资数据,修改"});
//增加更多的授权数据
for(int i=0;i<3;i++){
colDB.add("张三"+i+",人员列表,查看,1");
}
}
}
|
package com.revature.controller;
import javax.servlet.http.HttpServletRequest;
import com.revature.ajax.ClientMessage;
import com.revature.model.Employee;
import com.revature.repository.EmployeeRepositoryjdbc;
import com.revature.service.EmployeeServiceAlpha;
public class EmployeeInformationControllerAlpha implements EmployeeInformationController {
private static EmployeeInformationController informationController = new EmployeeInformationControllerAlpha();
private EmployeeInformationControllerAlpha() {}
public static EmployeeInformationController getInstance() {
return informationController;
}
@Override
public Object registerEmployee(HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object updateEmployee(HttpServletRequest request) {
Employee loggedEmployee = (Employee) request.getSession().getAttribute("loggedEmployee");
if(loggedEmployee == null) {
System.out.println("no this is the one that is printing.");
return "login.html";
}
if (request.getMethod().equals("GET")) {
return "update.html";
}
if(request.getParameter("firstName") == "") {
return new ClientMessage("FAILED");
}
if(request.getParameter("lastName") == "" ) {
return new ClientMessage("FAILED");
}
if(request.getParameter("email") == "") {
return new ClientMessage("FAILED");
}
loggedEmployee.setFirstName(request.getParameter("firstName"));
loggedEmployee.setLastName(request.getParameter("lastName"));
loggedEmployee.setEmail(request.getParameter("email"));
EmployeeServiceAlpha.getInstance().updateEmployeeInformation(loggedEmployee);
return loggedEmployee;
}
@Override
public Object viewEmployeeInformation(HttpServletRequest request) {
Employee loggedEmployee = (Employee) request.getSession().getAttribute("loggedEmployee");
if(loggedEmployee == null) {
return "login.html";
}
if (request.getParameter("fetch") == null) {
return "my-account.html";
}
return loggedEmployee = EmployeeServiceAlpha.getInstance().getEmployeeInformation(loggedEmployee);
}
@Override
public Object viewAllEmployees(HttpServletRequest request) {
Employee loggedEmployee = (Employee) request.getSession().getAttribute("loggedEmployee");
if(loggedEmployee == null) {
return "login.html";
}
if(loggedEmployee.getEmployeeRole().getId() != 2) {
System.out.println(loggedEmployee.getEmployeeRole().getId());
return "oops.html";
}
if (request.getParameter("fetch") == null) {
return "all-employees.html";
}
return EmployeeServiceAlpha.getInstance().getAllEmployeesInformation();
}
@Override
public Object usernameExists(HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}
}
|
package at.fhv.itm14.fhvgis.persistence.dao.interfaces.raw;
import at.fhv.itm14.fhvgis.domain.raw.RawWaypoint;
import at.fhv.itm14.fhvgis.persistence.dao.interfaces.IGenericDao;
import at.fhv.itm14.fhvgis.persistence.exceptions.PersistenceException;
import java.util.List;
import java.util.UUID;
public interface IRawWaypointDao extends IGenericDao<RawWaypoint> {
List<RawWaypoint> findAllRawWaypointsOfTrack(UUID trackid) throws PersistenceException;
}
|
package vangthao.app.introandroiddemo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
public class SimpleBundleDemoActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_bundle_demo);
String initialText = getIntent().getStringExtra("text");
TextView txtDisplayText = findViewById(R.id.txtDisplayText);
if (initialText != null) {
txtDisplayText.setText(initialText);
}
getSupportActionBar().setHomeButtonEnabled(true);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, ActionBarMenuActivity.class);
startActivity(intent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
} |
package com.mattcramblett.primenumbergenerator;
import java.util.Arrays;
import java.util.List;
/**
* Base class for tests to hold useful constants for testing the system
*/
public abstract class AbstractTest {
protected static final List<Integer> SMALL_PRIMES = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101);
}
|
package model;
import lombok.Getter;
public class Category{
@Getter private Integer id;
@Getter private String name;
public Category(){
id = 0;
name = "";
}
public Category(Integer id, String name){
this.id = id;
this.name = name;
}
}
|
package org.rs.core.beans.model;
import org.rs.core.beans.RsStrategyInfo;
public class RsStrategyInfoModel extends RsStrategyInfo{
private String msmc;
public String getMsmc() {
return msmc;
}
public void setMsmc(String msmc) {
this.msmc = msmc;
}
}
|
package old.Data20180408;
import java.util.ArrayList;
import java.util.LinkedList;
import old.DataType.TreeNode;
public class BinaryTreePreorderTraversal {
/**
* 二叉树的先序遍历(迭代)
* @param root
* @return
*/
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
if(root == null)
return list;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
int size = queue.size();
while(size-- > 0) {
TreeNode node = queue.poll();
list.add(node.val);
if(node.right != null)
queue.offerFirst(node.right);
if(node.left != null) {
queue.offerFirst(node.left);
}
}
}
return list;
}
/**
* 二叉树的先序遍历(递归)
*/
private ArrayList<Integer> list = new ArrayList<>();
public ArrayList<Integer> preorderTraversal1(TreeNode root){
preorder(root);
return list;
}
public void preorder(TreeNode root) {
if(root == null)
return;
list.add(root.val);
preorder(root.left);
preorder(root.right);
}
}
|
package online.lahloba.www.lahloba.ui.cart;
import androidx.lifecycle.ViewModelProviders;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.location.Location;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import online.lahloba.www.lahloba.R;
import online.lahloba.www.lahloba.ViewModelProviderFactory;
import online.lahloba.www.lahloba.data.model.AddressItem;
import online.lahloba.www.lahloba.data.model.CartItem;
import online.lahloba.www.lahloba.data.model.OrderItem;
import online.lahloba.www.lahloba.data.model.ProductOption;
import online.lahloba.www.lahloba.data.model.UserItem;
import online.lahloba.www.lahloba.data.model.vm_helper.CartVMHelper;
import online.lahloba.www.lahloba.databinding.CartActivityBinding;
import online.lahloba.www.lahloba.ui.cart.bottom_sheet.AddOrderConfirmBottomSheet;
import online.lahloba.www.lahloba.ui.cart.bottom_sheet.AddressBottomSheet;
import online.lahloba.www.lahloba.ui.cart.bottom_sheet.LogginBottomSheet;
import online.lahloba.www.lahloba.ui.cart.bottom_sheet.ShippingMethodBottomSheet;
import online.lahloba.www.lahloba.ui.login.LoginActivity;
import online.lahloba.www.lahloba.ui.login.LoginViewModel;
import online.lahloba.www.lahloba.utils.Injector;
import online.lahloba.www.lahloba.utils.StatusUtils;
import online.lahloba.www.lahloba.utils.Utils;
import static online.lahloba.www.lahloba.utils.Constants.EXTRA_USER_ID;
public class CartActivity extends AppCompatActivity
implements
LogginBottomSheet.OnLoginSheetClicked,
ShippingMethodBottomSheet.OnShippingMethodClicked,
AddressBottomSheet.SendAddressToCart,
AddOrderConfirmBottomSheet.ConfirmClickListener
{
private LoginViewModel loginViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CartActivityBinding binding = DataBindingUtil.setContentView(this,R.layout.cart_activity);
binding.setLifecycleOwner(this);
/***
* Login View Model in cart activity
*/
ViewModelProviderFactory loginFactory = Injector.getVMFactory(this);
loginViewModel = ViewModelProviders.of(this,loginFactory).get(LoginViewModel.class);
if(savedInstanceState == null){
Intent intent = getIntent();
if(null != intent && intent.hasExtra(EXTRA_USER_ID)){
Bundle bundle = new Bundle();
bundle.putString(EXTRA_USER_ID, intent.getStringExtra(EXTRA_USER_ID));
CartFragment cartFragment = CartFragment.newInstance(bundle);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, cartFragment)
.commitNow();
((CartFragment)getSupportFragmentManager().getFragments().get(0)).setLoginViewModel(loginViewModel);
}
}
}
/**
* Login sheet Item clicked
* @param id the id of button clicked (login method chosen)
*/
@Override
public void onLoginSheetItemClicked(int id) {
((CartFragment)getSupportFragmentManager().getFragments().get(0))
.onLoginSheetItemClicked(id);
}
/**
* Shipping sheet item clicked
* @param id
*/
@Override
public void onShippingMethodClicked(int id) {
((CartFragment)getSupportFragmentManager().getFragments().get(0))
.onShippingMethodClicked(id);
}
/**
* Get selected Address From Adapter to activity
*/
@Override
public void onSendAddressToCart(AddressItem addressItems) {
((CartFragment)getSupportFragmentManager().getFragments().get(0))
.onSendAddressToCart(addressItems);
}
@Override
public void onClickConfirmItem(int id) {
((CartFragment)getSupportFragmentManager().getFragments().get(0))
.onClickConfirmItem(id);
}
}
|
package crecepalabra;
import java.io.*;
public class Palabra {
private static int MAX_LETRAS = 20;
private static char letra = ' '; // Se inicializa a espacio
private char letras[];
private int longitud;
public Palabra() {
letras = new char[MAX_LETRAS];
longitud = 0;
}
private static void saltar_espacios() throws IOException {
while (letra == ' ') {
letra = (char) System.in.read();
}
}
public static Palabra leer() throws IOException {
Palabra palabra = new Palabra();
int pos = 0;
saltar_espacios();
while (letra != '\n') {
palabra.letras[pos] = letra;
pos++;
letra = (char) System.in.read();
}
letra = ' ';
palabra.longitud = pos;
return palabra;
}
public char letra(int posicion) {
return letras[posicion];
}
public boolean rendicion() {
return longitud == 0;
}
public boolean es_igual(Palabra palabra) {
// Si la longitud es distinta son distintas
if (longitud != palabra.longitud) {
return false;
}
// Si hay una letra distinta son distintas
for (int i = 0; i < longitud; ++i) {
if (letras[i] != palabra.letras[i]) {
return false;
}
}
// Son iguales
return true;
}
static boolean son_iguales(Palabra p1, Palabra p2) {
return p1.es_igual(p2);
}
public int LongPalabra() {
return longitud;
}
public boolean longInicial() {
return longitud >= 3;
}
@Override
public String toString() {
String res = "";
for (int i = 0; i < longitud; ++i) {
res += letras[i];
}
return res;
}
}
|
package com.zhongyp.spring.demo.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo {
public static void main(String args[]){
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-demo-annotation-beans.xml");
Person p = (Person) ctx.getBean("person");
p.testPrint();
}
}
|
package EmmaD;
import java.util.*;
import javax.swing.*;
/**
* Created by rodrique on 3/12/2018.
*/
public class RunClientAccount
{
public static void main(String[] args) {
Client fnbClient = new Client();
Account fnbAccount = new Account();
String name = JOptionPane.showInputDialog("***_Enter Client name:_*** ");
fnbClient.setClientName(name);
String sName = JOptionPane.showInputDialog("***_Enter Client surname:_*** ");
fnbClient.setClientSurname(sName);
String num = JOptionPane.showInputDialog("***_Enter Account Number:_*** ");
int accNum = Integer.parseInt(num);
fnbAccount.setAccountNumber(accNum);
String type = JOptionPane.showInputDialog("***_Enter Account Type:_*** ");
fnbAccount.setAccountType(type);
String bal = JOptionPane.showInputDialog("***_Enter Account Balance: R_***");
int accBal = Integer.parseInt(bal);
fnbAccount.setAccountBalance(accBal);
String deposit = JOptionPane.showInputDialog("***_Enter amount to deposit: R_***");
int dep = Integer.parseInt(deposit);
fnbAccount.deposit(dep);
if(accBal > 0)
{
String withraw = JOptionPane.showInputDialog("***_Enter amount to withdraw: R_***");
int wDraw = Integer.parseInt(withraw);
fnbAccount.withdraw(wDraw);
}
fnbClient.setClientAccount(fnbAccount);
JOptionPane.showMessageDialog(null, fnbClient.toString());
}
}
|
package com.ledungcobra.scenes;
import com.ledungcobra.anotations.BackButton;
import com.ledungcobra.applicationcontext.AppContext;
import com.ledungcobra.entites.Course;
import com.ledungcobra.entites.CourseRegistrationSession;
import com.ledungcobra.entites.Semester;
import com.ledungcobra.entites.StudentAccount;
import com.ledungcobra.models.CourseTableModel;
import com.ledungcobra.services.StudentService;
import com.ledungcobra.utils.Navigator;
import lombok.SneakyThrows;
import lombok.val;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import static com.ledungcobra.scenes.LoginScreen.USER_KEY;
public class StudentRegisterCoursesScreen extends Screen
{
// <editor-fold defaultstate="collapsed desc="Field declarations">
private javax.swing.JButton addBtn;
@BackButton
private javax.swing.JButton backBtn;
private javax.swing.JButton editRegisteredCourseListBtn;
private javax.swing.JLabel endDateLbl;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable openedCourseListTable;
private javax.swing.JTable previewCourses;
private javax.swing.JButton registerBtn;
private javax.swing.JButton removeBtn;
private javax.swing.JLabel semesterLbl;
private javax.swing.JLabel startDateLbl;
private HashSet<Course> tempCourseSet;
private HashSet<Course> registeredCourse;
private List<Course> loadedCourseList;
private final StudentService service = AppContext.studentService;
private CourseRegistrationSession currentSession;
private Semester activeSemester;
private HashSet<Course> removedCoursesSet;
private StudentAccount studentAccount;
private JPanel jPanel1;
private JPanel jPanel3;
private JPanel jPanel2;
private JPanel jPanel4;
@SneakyThrows
@Override
public void onCreateView()
{
initComponents();
if (this.data == null) throw new Exception("Data should not be null");
this.studentAccount = (StudentAccount) this.data.get(USER_KEY);
removedCoursesSet = new HashSet<>();
try
{
this.currentSession = service.getValidCourseRegistrationSession();
this.activeSemester = service.getActiveSemester();
this.semesterLbl.setText(this.currentSession.getSemester().toString());
this.startDateLbl.setText(this.currentSession.getStartDate().toString());
this.endDateLbl.setText(this.currentSession.getEndDate().toString());
} catch (Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
finish();
return;
}
loadData();
updateLoadedCourseList();
updateTempCourseList();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents()
{
jScrollPane1 = new javax.swing.JScrollPane();
openedCourseListTable = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
previewCourses = new javax.swing.JTable();
backBtn = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
endDateLbl = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
startDateLbl = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
semesterLbl = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
addBtn = new javax.swing.JButton();
editRegisteredCourseListBtn = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
removeBtn = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
registerBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setViewportView(openedCourseListTable);
jScrollPane2.setViewportView(previewCourses);
backBtn.setText("Back");
jLabel7.setFont(new java.awt.Font("Tahoma", 3, 13)); // NOI18N
jLabel7.setText("Opened Courses ");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Info", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 3, 14))); // NOI18N
endDateLbl.setText("12/12/2001");
jLabel5.setText("End date");
jLabel2.setText("Semester");
startDateLbl.setText("12/12/2001");
jLabel3.setText("Register session:");
semesterLbl.setText("HK1");
jLabel4.setText("Start date");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(semesterLbl)
.addGap(103, 103, 103)
.addComponent(jLabel3)
.addGap(21, 21, 21)
.addComponent(jLabel4)
.addGap(22, 22, 22)
.addComponent(startDateLbl)
.addGap(49, 49, 49)
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addComponent(endDateLbl)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(semesterLbl)
.addComponent(jLabel3))
.addComponent(jLabel2)
.addComponent(startDateLbl)
.addComponent(jLabel4)
.addComponent(endDateLbl)
.addComponent(jLabel5))
.addGap(38, 38, 38))
);
jLabel6.setFont(new java.awt.Font("Tahoma", 3, 13)); // NOI18N
jLabel6.setText("Temporary chose course list");
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Temporary actions", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 3, 14))); // NOI18N
addBtn.setText("Add");
editRegisteredCourseListBtn.setText("Edit registerd course list");
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(editRegisteredCourseListBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(addBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(addBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(editRegisteredCourseListBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Temporary Action", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 3, 14))); // NOI18N
removeBtn.setBackground(new java.awt.Color(255, 0, 0));
removeBtn.setText("Remove");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(removeBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(removeBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Persistent Action", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 3, 14))); // NOI18N
registerBtn.setBackground(new java.awt.Color(51, 255, 51));
registerBtn.setText("Register");
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(registerBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(registerBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 1469, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(backBtn)
.addComponent(jLabel7)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1469, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(backBtn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel6)
.addGap(5, 5, 5)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
pack();
}// </editor-fold>
void loadData()
{
this.registeredCourse = new HashSet<>(service.getRegisteredCourses(activeSemester, this.studentAccount));
this.tempCourseSet = new HashSet<>(this.registeredCourse);
}
private void updateTempCourseList()
{
this.previewCourses.setModel(new CourseTableModel(new ArrayList<>(this.tempCourseSet)));
}
private void updateLoadedCourseList()
{
this.openedCourseListTable.setModel(new CourseTableModel(new ArrayList<>()));
this.loadedCourseList = service.getCoursesOpenedInActiveSemester();
this.openedCourseListTable.setModel(new CourseTableModel(this.loadedCourseList));
}
@Override
protected void finish()
{
AppContext.executorService.submit(() -> {
try
{
Thread.sleep(400);
SwingUtilities.invokeAndWait(super::finish);
} catch (InterruptedException | InvocationTargetException e)
{
JOptionPane.showMessageDialog(null, "An error occur");
}
});
}
@Override
public void addEventListener()
{
addBtn.addActionListener(this::addCourseToTempListActionPerform);
removeBtn.addActionListener(this::removeCourseFromTempListActionPerform);
editRegisteredCourseListBtn.addActionListener(this::onEditCourseListBtnPerform);
registerBtn.addActionListener(this::onRegisterBtnActionPerformed);
}
private void onRegisterBtnActionPerformed(ActionEvent e)
{
try
{
if (checkBeforeSubmit())
{
service.removeCourses(removedCoursesSet, studentAccount, activeSemester);
registeredCourse.forEach(c -> {
tempCourseSet.remove(c);
});
service.registerCourses(tempCourseSet, studentAccount, this.currentSession, activeSemester);
loadData();
updateTempCourseList();
updateLoadedCourseList();
JOptionPane.showMessageDialog(this, "Register success");
} else
{
JOptionPane.showMessageDialog(this, "You have a conflict in time between courses in your temp list");
}
} catch (Exception ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
boolean checkBeforeSubmit()
{
if (tempCourseSet.size() > 8)
{
JOptionPane.showMessageDialog(this, "You are allowed to register maximum 8 course");
return false;
}
val courses = new ArrayList<>(tempCourseSet);
for (int i = 0; i < courses.size(); i++)
{
val currentCourse = courses.get(i);
for (int j = 0; j < courses.size(); j++)
{
if (i != j &&
currentCourse.getShiftToStudyInDay()
.equals(courses.get(j).getShiftToStudyInDay()) &&
currentCourse.getDayToStudyInWeek().equals(courses.get(j).getDayToStudyInWeek())
)
{
return false;
}
}
}
return true;
}
private void onEditCourseListBtnPerform(ActionEvent e)
{
new Navigator<ListAllRegisteredCoursesScreen>().navigate(this.data);
}
private void removeCourseFromTempListActionPerform(ActionEvent e)
{
int[] coursesIndices = previewCourses.getSelectedRows();
if (coursesIndices != null || coursesIndices.length > 0)
{
List<Course> courses = new ArrayList<>(this.tempCourseSet);
Arrays.stream(coursesIndices).forEach(i -> {
this.removedCoursesSet.add(courses.get(i));
this.tempCourseSet.remove(courses.get(i));
});
updateTempCourseList();
} else
{
JOptionPane.showMessageDialog(this, "You have to choose any course to add to your temp course list");
}
}
private void addCourseToTempListActionPerform(ActionEvent e)
{
int[] courseIndices = openedCourseListTable.getSelectedRows();
if (!checkBeforeAddCourse()) return;
if (courseIndices != null || courseIndices.length > 0)
{
Arrays.stream(courseIndices).forEach(i -> {
this.tempCourseSet.add(this.loadedCourseList.get(i));
this.removedCoursesSet.remove(this.loadedCourseList.get(i));
});
updateTempCourseList();
} else
{
JOptionPane.showMessageDialog(this, "You have to choose any course to add to your temp course list");
}
}
private boolean checkBeforeAddCourse()
{
int[] selectedCourseIndices = openedCourseListTable.getSelectedRows();
if (selectedCourseIndices == null || selectedCourseIndices.length == 0) return true;
List<Course> courses = new ArrayList<>(tempCourseSet);
for (int i = 0; i < selectedCourseIndices.length; i++)
{
val currentCourse = loadedCourseList.get(selectedCourseIndices[i]);
for (int j = 0; j < courses.size(); j++)
{
if (currentCourse.getSubject() != null &&
currentCourse.getSubject().equals(courses.get(j).getSubject()))
{
return false;
}
}
}
return true;
}
} |
package com.lab3;
public class demo1 {
public static void main(String[] args) {
int number = 7;
for(int i = 1 ; i<=10;i++) {
System.out.println(number+ " x " + i + "=" +number*i);
}
int j = 1;
while(j<=10) {
System.out.printf("%d x %d = %d %n",number,j,number*j);
j++;
}
int k =1;
do {
System.out.printf("%d x %d = %d %n",number,k,number*k);
k++;
} while (k<=10);
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.junit4.statements;
import org.junit.runners.model.Statement;
import org.springframework.test.context.TestContextManager;
/**
* {@code RunPrepareTestInstanceCallbacks} is a custom JUnit {@link Statement} which
* allows the <em>Spring TestContext Framework</em> to be plugged into the JUnit
* execution chain by calling {@link TestContextManager#prepareTestInstance(Object)
* prepareTestInstance()} on the supplied {@link TestContextManager}.
*
* @author Sam Brannen
* @since 4.2
* @see #evaluate()
*/
public class RunPrepareTestInstanceCallbacks extends Statement {
private final Statement next;
private final Object testInstance;
private final TestContextManager testContextManager;
/**
* Construct a new {@code RunPrepareTestInstanceCallbacks} statement.
* @param next the next {@code Statement} in the execution chain; never {@code null}
* @param testInstance the current test instance; never {@code null}
* @param testContextManager the {@code TestContextManager} upon which to call
* {@code prepareTestInstance()}; never {@code null}
*/
public RunPrepareTestInstanceCallbacks(Statement next, Object testInstance, TestContextManager testContextManager) {
this.next = next;
this.testInstance = testInstance;
this.testContextManager = testContextManager;
}
/**
* Invoke {@link TestContextManager#prepareTestInstance(Object)} and
* then evaluate the next {@link Statement} in the execution chain
* (typically an instance of {@link RunAfterTestMethodCallbacks}).
*/
@Override
public void evaluate() throws Throwable {
this.testContextManager.prepareTestInstance(this.testInstance);
this.next.evaluate();
}
}
|
package ir.sadeghzadeh.mozhdeh.utils;
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build.VERSION;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import ir.sadeghzadeh.mozhdeh.BuildConfig;
import ir.sadeghzadeh.mozhdeh.Const;
import ir.sadeghzadeh.mozhdeh.MainActivity;
import ir.sadeghzadeh.mozhdeh.entity.Item;
public class Util {
private static final Pattern DIR_SEPORATOR;
public static Context context;
public static MainActivity mainActivity;
static class LoginResponseListener implements Response.Listener<String> {
LoginResponseListener() {
}
public void onResponse(String response) {
}
}
static class LoginErrorResponseListener implements Response.ErrorListener {
LoginErrorResponseListener() {
}
public void onErrorResponse(VolleyError error) {
Log.d("Login", error.toString());
}
}
public static void writeToLogFile(String inputText, Object... objects) {
String log = new Date().toString() + " : " + String.format(inputText, objects);
File logFile = new File(getDownloadDirectoryPath() + "/mozhdegani.log");
if (!logFile.exists()) {
logFile.getParentFile().mkdirs();
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (logFile.length() > 500000) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(logFile);
fileOutputStream.write(BuildConfig.FLAVOR.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e2) {
e2.printStackTrace();
} catch (IOException e3) {
e3.printStackTrace();
}
}
try {
FileWriter fileWriter = new FileWriter(logFile, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(log);
bufferedWriter.newLine();
bufferedWriter.flush();
bufferedWriter.close();
fileWriter.close();
} catch (FileNotFoundException e22) {
e22.printStackTrace();
} catch (IOException e32) {
e32.printStackTrace();
}
}
public static String getDownloadDirectoryPath() {
String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
File dir = new File(downloadPath);
if (!dir.exists()) {
dir.mkdirs();
}
return downloadPath;
}
static {
DIR_SEPORATOR = Pattern.compile("/");
}
public static String[] getStorageDirectories() {
Set<String> rv = new HashSet();
String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
if (!TextUtils.isEmpty(rawEmulatedStorageTarget)) {
String rawUserId;
if (VERSION.SDK_INT < 17) {
rawUserId = BuildConfig.FLAVOR;
} else {
String[] folders = DIR_SEPORATOR.split(Environment.getExternalStorageDirectory().getAbsolutePath());
String lastFolder = folders[folders.length - 1];
boolean isDigit = false;
try {
Integer.valueOf(lastFolder);
isDigit = true;
} catch (NumberFormatException e) {
}
rawUserId = isDigit ? lastFolder : BuildConfig.FLAVOR;
}
if (TextUtils.isEmpty(rawUserId)) {
rv.add(rawEmulatedStorageTarget);
} else {
rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
}
} else if (TextUtils.isEmpty(rawExternalStorage)) {
rv.add("/storage/sdcard0");
} else {
rv.add(rawExternalStorage);
}
if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
Collections.addAll(rv, rawSecondaryStoragesStr.split(File.pathSeparator));
}
return (String[]) rv.toArray(new String[rv.size()]);
}
public static String fetchFromPreferences(String key) {
String str = Const.APP_CONFIG;
return context.getSharedPreferences(str, 0).getString(key, null);
}
public static void saveInPreferences(String key, String value) {
String str = Const.APP_CONFIG;
Editor editor = context.getSharedPreferences(str, 0).edit();
editor.putString(key, value);
editor.commit();
}
public static boolean fetchBooleanFromPreferences(String key, boolean defaultValue) {
String str = Const.APP_CONFIG;
return context.getSharedPreferences(str, 0).getBoolean(key, defaultValue);
}
public static void saveBooleanInPreferences(String key, boolean value) {
String str = Const.APP_CONFIG;
Editor editor = context.getSharedPreferences(str, 0).edit();
editor.putBoolean(key, value);
editor.commit();
}
public static void login() {
/*
if (fetchFromPreferences(Const.USERNAME) != null) {
ApplicationController.getInstance().addToRequestQueue(new LoginRequest(1, URL.LOGIN, new LoginResponseListener(), new LoginErrorResponseListener()));
}
*/
}
public static void moveFile(String inputFile, String outputPath) {
InputStream in = null;
OutputStream out = null;
try {
//create output directory if it doesn't exist
File dir = new File(outputPath);
if (!dir.exists()) {
dir.mkdirs();
}
in = new FileInputStream(inputFile);
out = new FileOutputStream(inputFile);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
// write the output file
out.flush();
out.close();
out = null;
// delete the original file
new File(inputFile).delete();
} catch (FileNotFoundException fnfe1) {
Log.e("tag", fnfe1.getMessage());
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
public static Location getLocation() {
Location location=null;
try {
double latitude; // latitude
double longitude; // longitude
LocationManager locationManager = (LocationManager) context
.getSystemService(context.LOCATION_SERVICE);
// getting GPS Status
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network Status
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
// First get location from Network Provider
if (isNetworkEnabled) {
if (locationManager != null) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return null;
}
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public static boolean isUserLogged(){
String token = fetchFromPreferences(Const.TOKEN);
if(token == null || token.isEmpty()){
return false;
}
return true;
}
public static String imageUrlMaker(boolean thumbnail, Item item){
String url = "";
if(thumbnail){
url = Const.SERVER_URL + Const.THUMBNAIL_URL + "/" + item.id + item.ImageExt;
}else {
url = Const.SERVER_URL + Const.FULL_IMAGE_URL + "/" + item.id + item.ImageExt;
}
return url;
}
public static String buildCommaSeperate(List<String> list){
String result = "";
if(list.size() == 0){
return result;
}
for (String row : list){
result += row + ",";
}
result = result.substring(0,result.length()-1); //remove last comma
return result;
}
}
|
package cdp.participacao;
import java.io.Serializable;
/**
* O enum representa os tipos de cargo de um Profissional.
*
* @author Yuri Silva
* @author Tiberio Gadelha
* @author Matheus Henrique
* @author Gustavo Victora
*/
public enum Cargo implements Serializable {
DESENVOLVEDOR("desenvolvedor"),
GERENTE("gerente"),
PESQUISADOR("pesquisador");
private final String cargo;
Cargo(String cargo) {
this.cargo = cargo;
}
public String getCargo() {
return this.cargo;
}
}
|
package com.epam.university.spring.model;
import com.epam.university.spring.domain.Show;
import com.epam.university.spring.domain.User;
public class TenthTicketDiscountStrategy implements DiscountStrategy {
public Long execute(User user, Show show) {
int size = user.getTickets().size();
if (size % 10 == 0 && size > 0) {
return 50L;
} else {
return 0L;
}
}
}
|
package com.javarush.task.task08.task0823;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*
Омовение Рамы
*/
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
//напишите тут ваш код
/*Проверяю строку на вхождение пробела U+0020
* если пробел находится, то возвращаю индекс пробела. Инкрементирую индекс
* Получаю из индекса букву и charAt
* полученную букву переводим в верхний регистр*/
StringBuffer str = new StringBuffer(s);
String space = " ";
char sp = space.charAt(0);
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(0);
c = Character.toUpperCase(c);
str.setCharAt(0, c);
if (str.charAt(i) == sp) {
c = str.charAt(i+1);
c = Character.toUpperCase(c);
str.setCharAt(i+1, c);
}
}
System.out.println(str);
}
}
|
package com.tabs.tabs.database;
// method to set Plant notes
// method to increment droplets by N
// method to decide status
// method to calc days since last water
// method to init new plant (e.g. set notes as "" by default)
import androidx.room.Database;
import androidx.room.RoomDatabase;
@Database(entities = {PlantModel.class}, version = 2)
public abstract class AppDatabase extends RoomDatabase {
public abstract PlantDao PlantDao();
}
/*
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "plant_db").build();
*/ |
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.env;
import java.io.File;
import java.io.IOException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.env.MockPropertySource;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.mock.web.MockServletContext;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.context.support.StandardServletEnvironment;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
import static org.springframework.context.ConfigurableApplicationContext.ENVIRONMENT_BEAN_NAME;
import static org.springframework.core.env.EnvironmentSystemIntegrationTests.Constants.DERIVED_DEV_BEAN_NAME;
import static org.springframework.core.env.EnvironmentSystemIntegrationTests.Constants.DERIVED_DEV_ENV_NAME;
import static org.springframework.core.env.EnvironmentSystemIntegrationTests.Constants.DEV_BEAN_NAME;
import static org.springframework.core.env.EnvironmentSystemIntegrationTests.Constants.DEV_ENV_NAME;
import static org.springframework.core.env.EnvironmentSystemIntegrationTests.Constants.ENVIRONMENT_AWARE_BEAN_NAME;
import static org.springframework.core.env.EnvironmentSystemIntegrationTests.Constants.PROD_BEAN_NAME;
import static org.springframework.core.env.EnvironmentSystemIntegrationTests.Constants.PROD_ENV_NAME;
import static org.springframework.core.env.EnvironmentSystemIntegrationTests.Constants.TRANSITIVE_BEAN_NAME;
import static org.springframework.core.env.EnvironmentSystemIntegrationTests.Constants.XML_PATH;
/**
* System integration tests for container support of the {@link Environment} API.
*
* <p>
* Tests all existing BeanFactory and ApplicationContext implementations to ensure that:
* <ul>
* <li>a standard environment object is always present
* <li>a custom environment object can be set and retrieved against the factory/context
* <li>the {@link EnvironmentAware} interface is respected
* <li>the environment object is registered with the container as a singleton bean (if an
* ApplicationContext)
* <li>bean definition files (if any, and whether XML or @Configuration) are registered
* conditionally based on environment metadata
* </ul>
*
* @author Chris Beams
* @author Sam Brannen
* @see org.springframework.context.support.EnvironmentIntegrationTests
*/
@SuppressWarnings("resource")
public class EnvironmentSystemIntegrationTests {
private final ConfigurableEnvironment prodEnv = new StandardEnvironment();
private final ConfigurableEnvironment devEnv = new StandardEnvironment();
private final ConfigurableEnvironment prodWebEnv = new StandardServletEnvironment();
@BeforeEach
void setUp() {
prodEnv.setActiveProfiles(PROD_ENV_NAME);
devEnv.setActiveProfiles(DEV_ENV_NAME);
prodWebEnv.setActiveProfiles(PROD_ENV_NAME);
}
@Test
void genericApplicationContext_standardEnv() {
ConfigurableApplicationContext ctx = new GenericApplicationContext(newBeanFactoryWithEnvironmentAwareBean());
ctx.refresh();
assertHasStandardEnvironment(ctx);
assertEnvironmentBeanRegistered(ctx);
assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
}
@Test
void genericApplicationContext_customEnv() {
GenericApplicationContext ctx = new GenericApplicationContext(newBeanFactoryWithEnvironmentAwareBean());
ctx.setEnvironment(prodEnv);
ctx.refresh();
assertHasEnvironment(ctx, prodEnv);
assertEnvironmentBeanRegistered(ctx);
assertEnvironmentAwareInvoked(ctx, prodEnv);
}
@Test
void xmlBeanDefinitionReader_inheritsEnvironmentFromEnvironmentCapableBDR() {
GenericApplicationContext ctx = new GenericApplicationContext();
ctx.setEnvironment(prodEnv);
new XmlBeanDefinitionReader(ctx).loadBeanDefinitions(XML_PATH);
ctx.refresh();
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue();
}
@Test
void annotatedBeanDefinitionReader_inheritsEnvironmentFromEnvironmentCapableBDR() {
GenericApplicationContext ctx = new GenericApplicationContext();
ctx.setEnvironment(prodEnv);
new AnnotatedBeanDefinitionReader(ctx).register(Config.class);
ctx.refresh();
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue();
}
@Test
void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedConfigClasses() {
// it's actually ConfigurationClassPostProcessor's Environment that gets the job done here.
GenericApplicationContext ctx = new GenericApplicationContext();
ctx.setEnvironment(prodEnv);
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
scanner.scan("org.springframework.core.env.scan1");
ctx.refresh();
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue();
}
@Test
void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedComponents() {
GenericApplicationContext ctx = new GenericApplicationContext();
ctx.setEnvironment(prodEnv);
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
scanner.scan("org.springframework.core.env.scan2");
ctx.refresh();
assertThat(scanner.getEnvironment()).isEqualTo(ctx.getEnvironment());
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue();
}
@Test
void genericXmlApplicationContext() {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
assertHasStandardEnvironment(ctx);
ctx.setEnvironment(prodEnv);
ctx.load(XML_PATH);
ctx.refresh();
assertHasEnvironment(ctx, prodEnv);
assertEnvironmentBeanRegistered(ctx);
assertEnvironmentAwareInvoked(ctx, prodEnv);
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue();
}
@Test
void classPathXmlApplicationContext() {
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(XML_PATH);
ctx.setEnvironment(prodEnv);
ctx.refresh();
assertEnvironmentBeanRegistered(ctx);
assertHasEnvironment(ctx, prodEnv);
assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue();
}
@Test
void fileSystemXmlApplicationContext() throws IOException {
ClassPathResource xml = new ClassPathResource(XML_PATH);
File tmpFile = File.createTempFile("test", "xml");
FileCopyUtils.copy(xml.getFile(), tmpFile);
// strange - FSXAC strips leading '/' unless prefixed with 'file:'
ConfigurableApplicationContext ctx =
new FileSystemXmlApplicationContext(new String[] {"file:" + tmpFile.getPath()}, false);
ctx.setEnvironment(prodEnv);
ctx.refresh();
assertEnvironmentBeanRegistered(ctx);
assertHasEnvironment(ctx, prodEnv);
assertEnvironmentAwareInvoked(ctx, ctx.getEnvironment());
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue();
}
@Test
void annotationConfigApplicationContext_withPojos() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
assertHasStandardEnvironment(ctx);
ctx.setEnvironment(prodEnv);
ctx.register(EnvironmentAwareBean.class);
ctx.refresh();
assertEnvironmentAwareInvoked(ctx, prodEnv);
}
@Test
void annotationConfigApplicationContext_withProdEnvAndProdConfigClass() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
assertHasStandardEnvironment(ctx);
ctx.setEnvironment(prodEnv);
ctx.register(ProdConfig.class);
ctx.refresh();
assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue();
}
@Test
void annotationConfigApplicationContext_withProdEnvAndDevConfigClass() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
assertHasStandardEnvironment(ctx);
ctx.setEnvironment(prodEnv);
ctx.register(DevConfig.class);
ctx.refresh();
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(TRANSITIVE_BEAN_NAME)).isFalse();
}
@Test
void annotationConfigApplicationContext_withDevEnvAndDevConfigClass() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
assertHasStandardEnvironment(ctx);
ctx.setEnvironment(devEnv);
ctx.register(DevConfig.class);
ctx.refresh();
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isTrue();
assertThat(ctx.containsBean(TRANSITIVE_BEAN_NAME)).isTrue();
}
@Test
void annotationConfigApplicationContext_withImportedConfigClasses() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
assertHasStandardEnvironment(ctx);
ctx.setEnvironment(prodEnv);
ctx.register(Config.class);
ctx.refresh();
assertEnvironmentAwareInvoked(ctx, prodEnv);
assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue();
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(TRANSITIVE_BEAN_NAME)).isFalse();
}
@Test
void mostSpecificDerivedClassDrivesEnvironment_withDerivedDevEnvAndDerivedDevConfigClass() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
StandardEnvironment derivedDevEnv = new StandardEnvironment();
derivedDevEnv.setActiveProfiles(DERIVED_DEV_ENV_NAME);
ctx.setEnvironment(derivedDevEnv);
ctx.register(DerivedDevConfig.class);
ctx.refresh();
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isTrue();
assertThat(ctx.containsBean(DERIVED_DEV_BEAN_NAME)).isTrue();
assertThat(ctx.containsBean(TRANSITIVE_BEAN_NAME)).isTrue();
}
@Test
void mostSpecificDerivedClassDrivesEnvironment_withDevEnvAndDerivedDevConfigClass() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.setEnvironment(devEnv);
ctx.register(DerivedDevConfig.class);
ctx.refresh();
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(DERIVED_DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(TRANSITIVE_BEAN_NAME)).isFalse();
}
@Test
void annotationConfigApplicationContext_withProfileExpressionMatchOr() {
testProfileExpression(true, "p3");
}
@Test
void annotationConfigApplicationContext_withProfileExpressionMatchAnd() {
testProfileExpression(true, "p1", "p2");
}
@Test
void annotationConfigApplicationContext_withProfileExpressionNoMatchAnd() {
testProfileExpression(false, "p1");
}
@Test
void annotationConfigApplicationContext_withProfileExpressionNoMatchNone() {
testProfileExpression(false, "p4");
}
private void testProfileExpression(boolean expected, String... activeProfiles) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
StandardEnvironment environment = new StandardEnvironment();
environment.setActiveProfiles(activeProfiles);
ctx.setEnvironment(environment);
ctx.register(ProfileExpressionConfig.class);
ctx.refresh();
assertThat(ctx.containsBean("expressionBean")).isEqualTo(expected);
}
@Test
void webApplicationContext() {
GenericWebApplicationContext ctx = new GenericWebApplicationContext(newBeanFactoryWithEnvironmentAwareBean());
assertHasStandardServletEnvironment(ctx);
ctx.setEnvironment(prodWebEnv);
ctx.refresh();
assertHasEnvironment(ctx, prodWebEnv);
assertEnvironmentBeanRegistered(ctx);
assertEnvironmentAwareInvoked(ctx, prodWebEnv);
}
@Test
void xmlWebApplicationContext() {
AbstractRefreshableWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setConfigLocation("classpath:" + XML_PATH);
ctx.setEnvironment(prodWebEnv);
ctx.refresh();
assertHasEnvironment(ctx, prodWebEnv);
assertEnvironmentBeanRegistered(ctx);
assertEnvironmentAwareInvoked(ctx, prodWebEnv);
assertThat(ctx.containsBean(DEV_BEAN_NAME)).isFalse();
assertThat(ctx.containsBean(PROD_BEAN_NAME)).isTrue();
}
@Test
void staticApplicationContext() {
StaticApplicationContext ctx = new StaticApplicationContext();
assertHasStandardEnvironment(ctx);
registerEnvironmentBeanDefinition(ctx);
ctx.setEnvironment(prodEnv);
ctx.refresh();
assertHasEnvironment(ctx, prodEnv);
assertEnvironmentBeanRegistered(ctx);
assertEnvironmentAwareInvoked(ctx, prodEnv);
}
@Test
void staticWebApplicationContext() {
StaticWebApplicationContext ctx = new StaticWebApplicationContext();
assertHasStandardServletEnvironment(ctx);
registerEnvironmentBeanDefinition(ctx);
ctx.setEnvironment(prodWebEnv);
ctx.refresh();
assertHasEnvironment(ctx, prodWebEnv);
assertEnvironmentBeanRegistered(ctx);
assertEnvironmentAwareInvoked(ctx, prodWebEnv);
}
@Test
void annotationConfigWebApplicationContext() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.setEnvironment(prodWebEnv);
ctx.setConfigLocation(EnvironmentAwareBean.class.getName());
ctx.refresh();
assertHasEnvironment(ctx, prodWebEnv);
assertEnvironmentBeanRegistered(ctx);
assertEnvironmentAwareInvoked(ctx, prodWebEnv);
}
@Test
void registerServletParamPropertySources_AbstractRefreshableWebApplicationContext() {
MockServletContext servletContext = new MockServletContext();
servletContext.addInitParameter("pCommon", "pCommonContextValue");
servletContext.addInitParameter("pContext1", "pContext1Value");
MockServletConfig servletConfig = new MockServletConfig(servletContext);
servletConfig.addInitParameter("pCommon", "pCommonConfigValue");
servletConfig.addInitParameter("pConfig1", "pConfig1Value");
AbstractRefreshableWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.setConfigLocation(EnvironmentAwareBean.class.getName());
ctx.setServletConfig(servletConfig);
ctx.refresh();
ConfigurableEnvironment environment = ctx.getEnvironment();
assertThat(environment).isInstanceOf(StandardServletEnvironment.class);
MutablePropertySources propertySources = environment.getPropertySources();
assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)).isTrue();
assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)).isTrue();
// ServletConfig gets precedence
assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonConfigValue");
assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)))
.isLessThan(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)));
// but all params are available
assertThat(environment.getProperty("pContext1")).isEqualTo("pContext1Value");
assertThat(environment.getProperty("pConfig1")).isEqualTo("pConfig1Value");
// Servlet* PropertySources have precedence over System* PropertySources
assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)))
.isLessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)));
// Replace system properties with a mock property source for convenience
MockPropertySource mockSystemProperties = new MockPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
mockSystemProperties.setProperty("pCommon", "pCommonSysPropsValue");
mockSystemProperties.setProperty("pSysProps1", "pSysProps1Value");
propertySources.replace(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, mockSystemProperties);
// assert that servletconfig params resolve with higher precedence than sysprops
assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonConfigValue");
assertThat(environment.getProperty("pSysProps1")).isEqualTo("pSysProps1Value");
}
@Test
void registerServletParamPropertySources_GenericWebApplicationContext() {
MockServletContext servletContext = new MockServletContext();
servletContext.addInitParameter("pCommon", "pCommonContextValue");
servletContext.addInitParameter("pContext1", "pContext1Value");
GenericWebApplicationContext ctx = new GenericWebApplicationContext();
ctx.setServletContext(servletContext);
ctx.refresh();
ConfigurableEnvironment environment = ctx.getEnvironment();
assertThat(environment).isInstanceOf(StandardServletEnvironment.class);
MutablePropertySources propertySources = environment.getPropertySources();
assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)).isTrue();
// ServletContext params are available
assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonContextValue");
assertThat(environment.getProperty("pContext1")).isEqualTo("pContext1Value");
// Servlet* PropertySources have precedence over System* PropertySources
assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)))
.isLessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)));
// Replace system properties with a mock property source for convenience
MockPropertySource mockSystemProperties = new MockPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
mockSystemProperties.setProperty("pCommon", "pCommonSysPropsValue");
mockSystemProperties.setProperty("pSysProps1", "pSysProps1Value");
propertySources.replace(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, mockSystemProperties);
// assert that servletcontext init params resolve with higher precedence than sysprops
assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonContextValue");
assertThat(environment.getProperty("pSysProps1")).isEqualTo("pSysProps1Value");
}
@Test
void registerServletParamPropertySources_StaticWebApplicationContext() {
MockServletContext servletContext = new MockServletContext();
servletContext.addInitParameter("pCommon", "pCommonContextValue");
servletContext.addInitParameter("pContext1", "pContext1Value");
MockServletConfig servletConfig = new MockServletConfig(servletContext);
servletConfig.addInitParameter("pCommon", "pCommonConfigValue");
servletConfig.addInitParameter("pConfig1", "pConfig1Value");
StaticWebApplicationContext ctx = new StaticWebApplicationContext();
ctx.setServletConfig(servletConfig);
ctx.refresh();
ConfigurableEnvironment environment = ctx.getEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)).isTrue();
assertThat(propertySources.contains(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)).isTrue();
// ServletConfig gets precedence
assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonConfigValue");
assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)))
.isLessThan(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)));
// but all params are available
assertThat(environment.getProperty("pContext1")).isEqualTo("pContext1Value");
assertThat(environment.getProperty("pConfig1")).isEqualTo("pConfig1Value");
// Servlet* PropertySources have precedence over System* PropertySources
assertThat(propertySources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)))
.isLessThan(propertySources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)));
// Replace system properties with a mock property source for convenience
MockPropertySource mockSystemProperties = new MockPropertySource(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
mockSystemProperties.setProperty("pCommon", "pCommonSysPropsValue");
mockSystemProperties.setProperty("pSysProps1", "pSysProps1Value");
propertySources.replace(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, mockSystemProperties);
// assert that servletconfig params resolve with higher precedence than sysprops
assertThat(environment.getProperty("pCommon")).isEqualTo("pCommonConfigValue");
assertThat(environment.getProperty("pSysProps1")).isEqualTo("pSysProps1Value");
}
@Test
void abstractApplicationContextValidatesRequiredPropertiesOnRefresh() {
{
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.refresh();
}
{
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setRequiredProperties("foo", "bar");
assertThatExceptionOfType(MissingRequiredPropertiesException.class).isThrownBy(
ctx::refresh);
}
{
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setRequiredProperties("foo");
ctx.setEnvironment(new MockEnvironment().withProperty("foo", "fooValue"));
ctx.refresh(); // should succeed
}
}
private DefaultListableBeanFactory newBeanFactoryWithEnvironmentAwareBean() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
registerEnvironmentBeanDefinition(bf);
return bf;
}
private void registerEnvironmentBeanDefinition(BeanDefinitionRegistry registry) {
registry.registerBeanDefinition(ENVIRONMENT_AWARE_BEAN_NAME,
rootBeanDefinition(EnvironmentAwareBean.class).getBeanDefinition());
}
private void assertEnvironmentBeanRegistered(
ConfigurableApplicationContext ctx) {
// ensure environment is registered as a bean
assertThat(ctx.containsBean(ENVIRONMENT_BEAN_NAME)).isTrue();
}
private void assertHasStandardEnvironment(ApplicationContext ctx) {
Environment defaultEnv = ctx.getEnvironment();
assertThat(defaultEnv).isNotNull();
assertThat(defaultEnv).isInstanceOf(StandardEnvironment.class);
}
private void assertHasStandardServletEnvironment(WebApplicationContext ctx) {
// ensure a default servlet environment exists
Environment defaultEnv = ctx.getEnvironment();
assertThat(defaultEnv).isNotNull();
assertThat(defaultEnv).isInstanceOf(StandardServletEnvironment.class);
}
private void assertHasEnvironment(ApplicationContext ctx, Environment expectedEnv) {
// ensure the custom environment took
Environment actualEnv = ctx.getEnvironment();
assertThat(actualEnv).isNotNull();
assertThat(actualEnv).isEqualTo(expectedEnv);
// ensure environment is registered as a bean
assertThat(ctx.containsBean(ENVIRONMENT_BEAN_NAME)).isTrue();
}
private void assertEnvironmentAwareInvoked(ConfigurableApplicationContext ctx, Environment expectedEnv) {
assertThat(ctx.getBean(EnvironmentAwareBean.class).environment).isEqualTo(expectedEnv);
}
private static class EnvironmentAwareBean implements EnvironmentAware {
public Environment environment;
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
/**
* Mirrors the structure of beans and environment-specific config files in
* EnvironmentSystemIntegrationTests-context.xml
*/
@Configuration
@Import({DevConfig.class, ProdConfig.class})
static class Config {
@Bean
public EnvironmentAwareBean envAwareBean() {
return new EnvironmentAwareBean();
}
}
@Profile(DEV_ENV_NAME)
@Configuration
@Import(TransitiveConfig.class)
static class DevConfig {
@Bean
public Object devBean() {
return new Object();
}
}
@Profile(PROD_ENV_NAME)
@Configuration
static class ProdConfig {
@Bean
public Object prodBean() {
return new Object();
}
}
@Configuration
static class TransitiveConfig {
@Bean
public Object transitiveBean() {
return new Object();
}
}
@Profile(DERIVED_DEV_ENV_NAME)
@Configuration
static class DerivedDevConfig extends DevConfig {
@Bean
public Object derivedDevBean() {
return new Object();
}
}
@Profile("(p1 & p2) | p3")
@Configuration
static class ProfileExpressionConfig {
@Bean
public Object expressionBean() {
return new Object();
}
}
/**
* Constants used both locally and in scan* sub-packages
*/
public static class Constants {
public static final String XML_PATH = "org/springframework/core/env/EnvironmentSystemIntegrationTests-context.xml";
public static final String ENVIRONMENT_AWARE_BEAN_NAME = "envAwareBean";
public static final String PROD_BEAN_NAME = "prodBean";
public static final String DEV_BEAN_NAME = "devBean";
public static final String DERIVED_DEV_BEAN_NAME = "derivedDevBean";
public static final String TRANSITIVE_BEAN_NAME = "transitiveBean";
public static final String PROD_ENV_NAME = "prod";
public static final String DEV_ENV_NAME = "dev";
public static final String DERIVED_DEV_ENV_NAME = "derivedDev";
}
}
|
public class WaitNotifyTest
{
public static void main(String[] p)
{
Lock lock = new Lock();
ThreadA ta = new ThreadA("a", lock);
ThreadB tb = new ThreadB("b", lock);
ta.start();
tb.start();
}
}
class Lock
{
}
class ThreadA extends Thread
{
Lock lock;
ThreadA(String name, Lock lock)
{
this.setName(name);
this.lock = lock;
}
@Override
public void run()
{
for (int i = 0; i < 5; i++)
{
synchronized (lock)
{
try
{
lock.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
lock.notify();
}
}
}
}
class ThreadB extends Thread
{
Lock lock;
ThreadB(String name, Lock lock)
{
this.setName(name);
this.lock = lock;
}
@Override
public void run()
{
for (int i = 0; i < 5; i++)
{
synchronized (lock)
{
System.out.println(Thread.currentThread().getName());
lock.notify();
try
{
lock.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
} |
package com.onlinetest.athenahealth;
import java.util.Stack;
public class BracketBalanceCheck {
public static void main(String[] args) {
String values[] = { "{}[]()", "{[}]}" };
String[] res = braces(values);
for (int i = 0; i < res.length; i++) {
System.out.println(res[i]);
}
}
private final static String YES = "YES";
private final static String NO = "NO";
// Complete the braces function below.
static String[] braces(String[] values) {
String[] result = new String[values.length];
for (int i = 0; i < values.length; i++) {
result[i] = isBalanced2(values[i]) ? YES : NO;
}
return result;
}
static boolean isBalanced(String value) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
switch (ch) {
case '{':
case '[':
case '(':
stack.push(ch);
break;
case '}':
if (!stack.isEmpty() && stack.peek() == '{') {
stack.pop();
} else {
return false;
}
break;
case ']':
if (!stack.isEmpty() && stack.peek() == '[') {
stack.pop();
} else {
return false;
}
break;
case ')':
if (!stack.isEmpty() && stack.peek() == '(') {
stack.pop();
} else {
return false;
}
break;
}
}
return stack.isEmpty();
}
static boolean isBalanced2(String value) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
if (ch == '{' || ch == '[' || ch == '(') {
stack.push(ch);
} else {
if (!stack.isEmpty() && isMatch(ch, stack.peek())) {
stack.pop();
} else {
return false;
}
}
}
return stack.isEmpty();
}
private static boolean isMatch(Character curBracket, Character topBracket) {
boolean isMatch = false;
switch(curBracket) {
case '}':
if (topBracket == '{') {
isMatch = true;
}
break;
case ']':
if (topBracket == '[') {
isMatch = true;
}
break;
case ')':
if (topBracket == '(') {
isMatch = true;
}
break;
}
return isMatch;
}
}
|
package revolt.backend.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.NullValueCheckStrategy;
import revolt.backend.dto.MechmodDto;
import revolt.backend.entity.Mechmod;
import java.util.List;
@Mapper(componentModel = "spring", uses = {MechmodMapperResolver.class},
nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
public interface MechmodMapper {
@Mappings({
@Mapping(source = "brand.id", target = "brandId"),
@Mapping(source = "country.id", target = "countryId")})
MechmodDto toDto(Mechmod mechmod);
Mechmod toEntity(MechmodDto mechmodDto);
List<MechmodDto> toDtoList(List<Mechmod> mechmods);
List<Mechmod> toEntityList(List<MechmodDto> mechmodDtos);
} |
package ui;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JPanel;
public class JPanelHelpNext extends JPanel implements Runnable{
private static final long serialVersionUID = 1L;
private JMainFrame jMainFrame;
Point[] points=new Point[]{new Point(34,105),new Point(414,105)};
private int now = 0;
private int next = 0;
private boolean isRight = true;
public JPanelHelpNext(JMainFrame jframe){
this.jMainFrame = jframe;
this.setLayout(null);
this.setBounds(306,98,411,510);
this.setVisible(true);
jMainFrame.getContentPane().add(this);
this.repaint();
}
public void paintComponent(Graphics g){
g.drawImage(jMainFrame.everyImage.IMG_HELP_CONTENTS[now].getImage(), points[0].x, points[1].y,339,400,null);
g.drawImage(jMainFrame.everyImage.IMG_HELP_CONTENTS[next].getImage(), points[1].x, points[1].y,339,400,null);
if(now==0||next==0){
g.drawImage(jMainFrame.everyImage.IMG_HELP_TITLES[now].getImage(), points[0].x-6,39,157,44,null);
g.drawImage(jMainFrame.everyImage.IMG_HELP_TITLES[next].getImage(), points[1].x-6,39,157,44,null);
}else{
g.drawImage(jMainFrame.everyImage.IMG_HELP_TITLES[1].getImage(),28,39,157,44,null);
}
}
public void setDirection(boolean i){
isRight = i;
}
public void run(){
if(isRight){
next++;
points[1].x = 414;
while(points[1].x>34){
points[1].x-=10;
points[0].x-=10;
this.repaint();
jMainFrame.getContentPane().repaint();
try {
Thread.sleep(8);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
points[0].x = 34;
now = next;
}else{
next--;
points[1].x = -344;
while(points[1].x<34){
points[1].x+=10;
points[0].x+=10;
this.repaint();
jMainFrame.getContentPane().repaint();
try {
Thread.sleep(8);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
points[0].x = 34;
now = next;
}
}
}
|
/* Copyright 2015 Esri
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.esri.arcgis.samples.offlineanalysis;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.Toast;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.Layer;
import com.esri.android.map.MapOnTouchListener;
import com.esri.android.map.MapView;
import com.esri.android.map.RasterLayer;
import com.esri.android.map.event.OnZoomListener;
import com.esri.core.analysis.LineOfSight;
import com.esri.core.analysis.Viewshed;
import com.esri.core.geometry.Point;
import com.esri.core.map.Graphic;
import com.esri.core.raster.FileRasterSource;
import com.esri.core.raster.FunctionRasterSource;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol.STYLE;
import java.io.File;
import java.io.FileNotFoundException;
/**
* The Offline Analysis sample shows how to do Line of Sight and Viewshed
* analysis on raster DEM files on device. The sample shows how to extend the
* MapOnTouchListener to customize the apps response to tapping on the map.
*
*/
public class MainActivity extends Activity {
static final String TAG = "OfflineAnalysis";
// offline data
private static File demoDataFile;
private static String offlineDataSDCardDirName;
private static String filename;
// Map objects
MapView mMapView;
FileRasterSource mRasterSource;
private RasterLayer mRasterLayer;
private String mRaster;
private GraphicsLayer mGraphicsLayer;
private LineOfSight mLineOfSight;
private Layer mLosLayer;
private FunctionRasterSource functionRS;
private RasterLayer viewShedLayer;
private Viewshed mViewshed;
// ActionBar menu items
private MenuItem mLOS;
private MenuItem mVSmenu;
private double mObserverZOffset = Double.NaN;
private double mTargetZOffset = Double.NaN;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create the path to local raster file
demoDataFile = Environment.getExternalStorageDirectory();
offlineDataSDCardDirName = this.getResources().getString(
R.string.raster_dir);
filename = this.getResources().getString(R.string.raster_file);
// create the raster path
mRaster = demoDataFile + File.separator + offlineDataSDCardDirName
+ File.separator + filename;
// create the mapview
mMapView = (MapView) findViewById(R.id.map);
try {
// create the raster source
mRasterSource = new FileRasterSource(mRaster);
// create the raster layer
mRasterLayer = new RasterLayer(mRasterSource);
// add the layer
mMapView.addLayer(mRasterLayer);
// zoom to raster source extent
mMapView.setExtent(mRasterSource.getExtent());
} catch (FileNotFoundException | RuntimeException e) {
Log.e(TAG, e.getMessage());
}
// add graphics layer
mGraphicsLayer = new GraphicsLayer();
mMapView.addLayer(mGraphicsLayer);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
// get the analysis menu items
mLOS = menu.getItem(0);
mVSmenu = menu.getItem(1);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// Handle menu item selection
switch (id) {
case R.id.menu_analysis_los:
mLOS.setChecked(true);
Toast toast = Toast.makeText(getApplicationContext(),
"Line of Sight selected", Toast.LENGTH_LONG);
toast.show();
performLOS();
return true;
case R.id.menu_analysis_viewshed:
mVSmenu.setChecked(true);
Toast toast2 = Toast.makeText(getApplicationContext(),
"Viewshed selected", Toast.LENGTH_LONG);
toast2.show();
calculateViewshed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onPause() {
super.onPause();
// Call MapView.pause to suspend map rendering while the activity is
// paused, which can save battery usage.
if (mMapView != null) {
mMapView.pause();
}
}
@Override
protected void onResume() {
super.onResume();
// Call MapView.unpause to resume map rendering when the activity
// returns to the foreground.
if (mMapView != null) {
mMapView.unpause();
}
}
/*
* Remove any analysis layers on map
*/
private void clearFunctionLayers() {
turnOffLayer(mLosLayer);
turnOffLayer(viewShedLayer);
// clear any graphics
if (mGraphicsLayer != null) {
mGraphicsLayer.removeAll();
}
}
/*
* Remove layer and recycle
* Dispose of analysis functions
*/
private void turnOffLayer(Layer layer) {
if (layer != null && !layer.isRecycled()) {
mMapView.removeLayer(layer);
layer.recycle();
if(mViewshed != null){
mViewshed.dispose();
mViewshed = null;
}
if(mLineOfSight != null){
mLineOfSight.dispose();
mLineOfSight = null;
}
}
}
/*
* Line of Sight Analysis
*/
private void performLOS() {
// clear any analysis layers showing
clearFunctionLayers();
try {
mLineOfSight = new LineOfSight(mRaster);
} catch (FileNotFoundException | RuntimeException e) {
e.printStackTrace();
}
if (mLineOfSight != null) {
mLosLayer = mLineOfSight.getOutputLayer();
mMapView.addLayer(mLosLayer);
// set observer features
mLineOfSight.setObserver(mMapView.getCenter());
mLineOfSight.setObserverZOffset(mObserverZOffset);
mLineOfSight.setTargetZOffset(mTargetZOffset);
// Set gesture used to change the position of the observer and
// target.
// When the position of a target is changed, the task will be
// executed and
// the result will be rendered on the map view.
mMapView.setOnTouchListener(new OnTouchListenerLOS(mMapView
.getContext(), mMapView, mLineOfSight));
// Reset the observer to center of map on map zoom
mMapView.setOnZoomListener(new OnZoomListener() {
private static final long serialVersionUID = 1L;
@Override
public void preAction(float pivotX, float pivotY, double factor) {
}
@Override
public void postAction(float pivotX, float pivotY, double factor) {
// set the observer to the center of the map
mLineOfSight.setObserver(mMapView.getCenter());
}
});
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Raster File Not Found", Toast.LENGTH_LONG);
toast.show();
}
}
/*
* Viewshed Analysis
*/
private void calculateViewshed() {
// clear any analysis layers showing
clearFunctionLayers();
// create a viewshed
try {
mViewshed = new Viewshed(mRaster);
} catch (FileNotFoundException | RuntimeException e) {
e.printStackTrace();
}
if (mViewshed != null) {
functionRS = mViewshed.getOutputFunctionRasterSource();
viewShedLayer = new RasterLayer(functionRS);
mMapView.addLayer(viewShedLayer);
mViewshed.setObserverZOffset(mObserverZOffset);
// Set gesture used to change the position of the observer
mMapView.setOnTouchListener(new OnTouchListenerViewshed(mMapView
.getContext(), mMapView, mViewshed));
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Raster File Not Found", Toast.LENGTH_LONG);
toast.show();
}
}
/*
* Override com.esri.android.map.MapOnTouchListener to customize gesture
* used to change the position of the observer and target.
*/
private class OnTouchListenerLOS extends MapOnTouchListener {
MapView mMap;
LineOfSight mTask;
public OnTouchListenerLOS(Context context, MapView map, LineOfSight task) {
super(context, map);
mMap = map;
mTask = task;
}
@Override
public boolean onDragPointerMove(MotionEvent from, MotionEvent to) {
try {
Point p = mMap.toMapPoint(to.getX(), to.getY());
mTask.setTarget(p);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
@Override
public boolean onSingleTap(MotionEvent tap) {
try {
Point p = mMap.toMapPoint(tap.getX(), tap.getY());
mTask.setTarget(p);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/*
* Override method to change the observers position in calculating Line
* of Sight.
*
* @see
* com.esri.android.map.MapOnTouchListener#onLongPress(android.view.
* MotionEvent)
*/
@Override
public void onLongPress(MotionEvent tap) {
Point p = mMap.toMapPoint(tap.getX(), tap.getY());
mTask.setObserver(p);
}
}
/*
* Override com.esri.android.map.MapOnTouchListener to customize gesture
* used to change the position of the observer.
*/
private class OnTouchListenerViewshed extends MapOnTouchListener {
private MapView mMap;
private Viewshed mTask;
public OnTouchListenerViewshed(Context context, MapView map,
Viewshed task) {
super(context, map);
mMap = map;
mTask = task;
}
@Override
public boolean onSingleTap(MotionEvent tap) {
Point mapPoint = mMap.toMapPoint(tap.getX(), tap.getY());
// clear any graphics
mGraphicsLayer.removeAll();
// create a graphic to represent observer position
Graphic graphic = new Graphic(mapPoint, new SimpleMarkerSymbol(
Color.YELLOW, 20, STYLE.CROSS));
// add graphic to map
mGraphicsLayer.addGraphic(graphic);
// set observer on viewshed
mTask.setObserver(mapPoint);
return true;
}
}
} |
/**
* This package provides support for client HTTP
* {@link io.micrometer.observation.Observation}.
*/
@NonNullApi
@NonNullFields
package org.springframework.http.client.observation;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package com.twp.baseline;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BasketTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
@Before
public void setOutContent() {
System.setOut(new PrintStream(outContent));
}
@After
public void cleanUpOutContent() {
System.setOut(System.out);
}
@Test
public void shouldGenerateReceiptShowingTheNameOfItemTheirPriceInclOfTaxesAndTotalCostAndTotalAmount() {
Goods oneGoods = mock(Goods.class);
Goods twoGoods = mock(Goods.class);
List<Goods> goodsList = new ArrayList<>();
goodsList.add(oneGoods);
goodsList.add(twoGoods);
Basket basket = new Basket(goodsList);
when(oneGoods.getName()).thenReturn("Good 1");
when(twoGoods.getName()).thenReturn("Good 2");
when(oneGoods.totalTax()).thenReturn(1.20);
when(twoGoods.totalTax()).thenReturn(0.15);
when(oneGoods.totalPrice()).thenReturn(12.65);
when(twoGoods.totalPrice()).thenReturn(1.15);
basket.receipt();
assertEquals("Good 1:12.65\n" +
"Good 2:1.15\n" +
"Sales Tax:1.3499999999999999\n" +
"Total:13.8\n", outContent.toString());
}
}
|
package com.test.base;
/**
* You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24.
Example 1:
Input: [4, 1, 8, 7]
Output: True
Explanation: (8-4) * (7-1) = 24
Example 2:
Input: [1, 2, 1, 2]
Output: False
Note:
The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.
You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.
* @author YLine
*
* 2018年12月26日 下午5:32:27
*/
public interface Solution
{
public boolean judgePoint24(int[] nums);
}
|
package plugins.fmp.fmpTools;
import java.awt.Color;
import java.util.ArrayList;
import icy.image.IcyBufferedImage;
import plugins.fmp.fmpSequence.SequenceVirtual;
public class ImageOperations {
private SequenceVirtual seq = null;
private ImageOperationsStruct opTransf = new ImageOperationsStruct();
private ImageOperationsStruct opThresh = new ImageOperationsStruct();
private ImageTransformTools imgTransf = new ImageTransformTools();
private ImageThresholdTools imgThresh = new ImageThresholdTools();
public ImageOperations (SequenceVirtual seq) {
setSequence(seq);
}
public void setSequence(SequenceVirtual seq) {
this.seq = seq;
imgTransf.setSequence(seq);
}
public void setTransform (EnumImageOp transformop) {
opTransf.transformop = transformop;
}
public void setThresholdSingle( int threshold) {
opThresh.thresholdtype = EnumThresholdType.SINGLE;
opThresh.simplethreshold = threshold;
imgThresh.setSingleThreshold(threshold);
}
public void setColorArrayThreshold (ArrayList <Color> colorarray, int distanceType, int colorthreshold) {
opThresh.thresholdtype = EnumThresholdType.COLORARRAY;
opThresh.colorarray = colorarray;
opThresh.colordistanceType = distanceType;
opThresh.colorthreshold = colorthreshold;
imgThresh.setColorArrayThreshold(distanceType, colorthreshold, colorarray);
}
public IcyBufferedImage run() {
return run (seq.currentFrame);
}
public IcyBufferedImage run (int frame) {
// step 1
opTransf.fromFrame = frame;
if (!opTransf.isValidTransformCache(seq.cacheTransformOp)) {
seq.cacheTransformedImage = imgTransf.transformImageFromVirtualSequence(frame, opTransf.transformop);
if (seq.cacheTransformedImage == null) {
return null;
}
opTransf.copyTransformOpTo(seq.cacheTransformOp);
seq.cacheThresholdOp.fromFrame = -1;
}
// step 2
opThresh.fromFrame = frame;
if (!opThresh.isValidThresholdCache(seq.cacheThresholdOp)) {
if (opThresh.thresholdtype == EnumThresholdType.COLORARRAY)
seq.cacheThresholdedImage = imgThresh.getBinaryInt_FromColorsThreshold(seq.cacheTransformedImage);
else
seq.cacheThresholdedImage = imgThresh.getBinaryInt_FromThreshold(seq.cacheTransformedImage);
opThresh.copyThresholdOpTo(seq.cacheThresholdOp) ;
}
return seq.cacheThresholdedImage;
}
public IcyBufferedImage run_nocache() {
// step 1
int frame = seq.currentFrame;
IcyBufferedImage transformedImage = imgTransf.transformImageFromVirtualSequence(frame, opTransf.transformop);
if (transformedImage == null)
return null;
// step 2
IcyBufferedImage thresholdedImage;
if (opThresh.thresholdtype == EnumThresholdType.COLORARRAY)
thresholdedImage = imgThresh.getBinaryInt_FromColorsThreshold(transformedImage);
else
thresholdedImage = imgThresh.getBinaryInt_FromThreshold(transformedImage);
return thresholdedImage;
}
public boolean[] convertToBoolean(IcyBufferedImage binaryMap) {
return imgThresh.getBoolMap_FromBinaryInt(binaryMap);
}
}
|
package com.puneragroups.punerainvestmart;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Random;
public class LoginActivity extends AppCompatActivity {
ProgressBar progressbar;
int flags;
EditText editTextMobile;
Button btn_continue;
int randomNumber;
String base;
DatabaseReference mOtpdatabase, mUserDatabase;
String sender_id, message, authorization;
String mobile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextMobile = findViewById(R.id.mobile);
btn_continue = findViewById(R.id.buttonContinue);
progressbar = findViewById(R.id.progressbar);
FirebaseApp.initializeApp(this);
FirebaseDatabase database = FirebaseDatabase.getInstance();
mUserDatabase = database.getReference("Users");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/*mOtpdatabase = database.getReference("Admin").child("OTP");
mOtpdatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
sender_id = dataSnapshot.child("sender_id").getValue().toString();
message = dataSnapshot.child("message").getValue().toString();
authorization = dataSnapshot.child("authorization").getValue().toString();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});*/
btn_continue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressbar.setVisibility(View.VISIBLE);
mobile = editTextMobile.getText().toString().trim();
if (mobile.isEmpty() || mobile.length() < 10) {
progressbar.setVisibility(View.GONE);
editTextMobile.setError("Enter a valid mobile number");
editTextMobile.requestFocus();
return;
} else {
mUserDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(mobile)) {
Random random = new Random();
randomNumber = random.nextInt(99999);
Intent intent = new Intent(LoginActivity.this, OTPLogin.class);
intent.putExtra("OTP", randomNumber);
intent.putExtra("mobile", mobile);
startActivity(intent);
/*Bean b = (Bean) getApplicationContext();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.level(HttpLoggingInterceptor.Level.HEADERS);
logging.level(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().writeTimeout(1000, TimeUnit.SECONDS).readTimeout(1000, TimeUnit.SECONDS).connectTimeout(1000, TimeUnit.SECONDS).addInterceptor(logging).build();
base = b.baseurl;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(b.baseurl)
.client(client)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
AllApiIneterface cr = retrofit.create(AllApiIneterface.class);
Call<OtpBean> call = cr.getOtp(sender_id, "english", "qt", editTextMobile.getText().toString(),
message, "{#AA#}", String.valueOf(randomNumber), authorization);
call.enqueue(new Callback<OtpBean>() {
@Override
public void onResponse(@NotNull Call<OtpBean> call, @NotNull Response<OtpBean> response) {
if (response.body().getMessage().get(0).equals("Message sent successfully")) {
Intent intent = new Intent(Login.this, OTPLogin.class);
intent.putExtra("OTP", randomNumber);
intent.putExtra("mobile", mobile);
startActivity(intent);
} else {
Toast.makeText(Login.this, "Please try again", Toast.LENGTH_SHORT).show();
}
progressbar.setVisibility(View.GONE);
}
@Override
public void onFailure(Call<OtpBean> call, Throwable t) {
progressbar.setVisibility(View.GONE);
Toast.makeText(LoginActivity.this, "Some error occurred", Toast.LENGTH_SHORT).show();
}
});*/
} else {
Toast.makeText(LoginActivity.this, "This Number is not Registered. ", Toast.LENGTH_LONG).show();
progressbar.setVisibility(View.GONE);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
progressbar.setVisibility(View.GONE);
}
});
}
}
});
}
} |
package handlers;
import packets.data.Organisation;
import database.DataBase;
import services.*;
import java.io.*;
import java.net.*;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
/**
* Главный класс сервера
*/
public class Server {
/**
* Поле времени
*/
private static LocalDateTime time;
/**
* Менеджер сервера. Принимает подключения, организовывает чтение из канала, запись в канал.
*/
private static ServerManager serverManager;
/**
* Канал сервера
*/
private static ServerSocketChannel channel;
/**
* Селектор. Будет мониторить подключающиеся каналы
*/
private static Selector selector;
/**
* База данных
*/
private final static DataBase database = DataBase.getInstance();
/**
* Пул потоков для отправки ответов и обработки запросов
*/
public static final ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
/**
* Пул потоков для чтения запросов
*/
private static ExecutorService threadPool = Executors.newFixedThreadPool(1);
/**
* Флаг, является ли селектор закрытым
*/
private static boolean selectorIsClosed = false;
/**
* Главный метод сервера
* @param args - аргументы командной строки
*/
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
log(" Здравствуйте.");
log("INFO: Настройка всех систем...");
PriorityQueue<Organisation> organisations = database.getAllElements();
log("INFO: Элементы из базы данных успешно загружены в память");
try {
log("INFO: Сервер запускается...");
ServerInterpreter interpreter = new ServerInterpreter(organisations, database);
log("INFO: Введите свободный порт для подключения:");
int port = getPort(scanner);
InetAddress hostIP = InetAddress.getLocalHost();
channel = ServerSocketChannel.open();
selector = Selector.open();
InetSocketAddress address = new InetSocketAddress(hostIP,port);
channel.configureBlocking(false);
channel.bind(address);
channel.register(selector, SelectionKey.OP_ACCEPT);
serverManager = new ServerManager(channel, selector, interpreter);
log("INFO: Сервер запущен.");
log("INFO: Сервер готов к работе.");
boolean selectorIsOffline = false;
threadPool.execute(()->{
while(true) {
try{
selector.selectNow();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
keyIterator.remove();
if (!key.isValid()){
continue;
}
if(key.isAcceptable()) {
log("INFO: Запрос на подключение клиента...");
serverManager.accept(key);
log("INFO: Клиент успешно подключен.");
} else if(key.isReadable()) {
log("INFO: Попытка чтения из канала...");
try{
serverManager.read(key);
log("INFO: Чтение из канала прошло успешно.");
}
catch (SocketException e){
log("WARNING: Клиент отключился");
key.cancel();
}
catch (ClosedSelectorException e){
if (!selectorIsClosed){
log("WARNING: Селектор прекращает работу.");
selectorIsClosed = true;
//Чтобы не была неразбериха в консоли
}
}
catch (Exception e){
log("ERROR: " + e.toString());
key.cancel();
}
} else if(key.isWritable()) {
key.interestOps(SelectionKey.OP_READ);
forkJoinPool.execute(()->{
try{
log("INFO: Попытка отправки ответа клиенту...");
serverManager.write(key);
log("INFO: Сообщение клиенту успешно отправлено.");
}
catch (ClosedSelectorException e){
if (!selectorIsClosed){
log("WARNING: Селектор прекращает работу.");
selectorIsClosed = true;
//Чтобы не была неразбериха в консоли
}
}
catch (Exception e){
log("ERROR: " + e.toString());
}
});
}
}
}
catch (SocketException e){
log("WARNING: Пользователь отключился.");
}
catch (ClosedSelectorException e){
if (!selectorIsClosed){
log("WARNING: Селектор прекращает работу.");
selectorIsClosed = true;
//Чтобы не была неразбериха в консоли
}
}
catch (Exception ignore){
log("ERROR: " + ignore.toString());
}
}
});
checkConsole();
}
catch (SocketException e){
log("WARNING: Пользователь отключился.");
}
catch (ClosedSelectorException e){
if (!selectorIsClosed){
log("WARNING: Селектор прекращает работу.");
selectorIsClosed = true;
//Чтобы не была неразбериха в консоли
}
}
catch (Exception e){
e.printStackTrace();
}
}
/**
* Метод для проверки консоли сервера
*/
private static void checkConsole(){
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try{
while (true){
String command = bufferedReader.readLine();
if(command.equals("exit")){
bufferedReader.close();
selector.close();
threadPool.shutdown();
forkJoinPool.shutdown();
log("WARNING: Все потоки закрыты.");
channel.close();
log("WARNING: Сетевой канал закрыт.");
log(" Завершение работы.");
System.exit(0);
}
}
}
catch (Exception e){
}
}
/**
* Приватный метод для логирования
* @param message - сообщение
*/
private static void log(String message){
time = LocalDateTime.now();
System.out.println(time.format(DateTimeFormatter.ofPattern("dd.MM.yyyy-HH:mm:ss ")) + message);
}
/**
* Статический метод для ввода порта для подключения
* @param scanner - сканер
* @return возвращает порт
*/
private static int getPort(Scanner scanner){
int port = -1;
do {
try {
port = Integer.parseInt(scanner.nextLine());
if (port < 0) {
System.out.println("Порт не может быть меньше 0.");
System.out.println("Повторите ввод:");
}
else{
break;
}
}
catch (NumberFormatException ex) {
System.out.println("Неправильный формат ввода. Вводите число без пробелов и разделителей.");
System.out.println("Повторите ввод:");
}
}while (port < 0);
return port;
}
}
|
package com.soldevelo.vmi.communication;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.lang.StringUtils;
import javax.annotation.PreDestroy;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Session;
public abstract class Gateway {
private Connection connection;
private Session session;
public void init(String brokerUrl) throws JMSException {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
sessionCreated(session);
connection.start();
}
@PreDestroy
public void destroy() throws JMSException {
if (session != null) {
session.close();
}
if (connection != null) {
connection.close();
}
}
public String getProducerID() throws JMSException {
String clientID = connection.getClientID();
StringBuffer buffer = new StringBuffer();
if (!StringUtils.isEmpty(clientID)) {
String[] arr = clientID.split("-");
for (int i = 0; i < arr.length - 1; i++) {
if (i != 0) {
buffer.append("-");
}
buffer.append(arr[i]);
}
}
return buffer.toString();
}
protected Session getSession() {
return session;
}
public abstract void sessionCreated(Session session) throws JMSException;
public abstract String getTopicName();
}
|
package com.example.faisal.repositories;
import com.example.faisal.models.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends Base<User, Long> {
// Add custom methods to be included in this repo
}
|
package compiler.virtualMachine.Visitor;
import compiler.nodes.*;
import compiler.virtualMachine.VirtualMachine;
public class NodeVisitor implements Visitor{
public Action node;
VirtualMachine vm;
public NodeVisitor(VirtualMachine virtualMachine){
this.vm = virtualMachine;
}
public Action getNode() {
return node;
}
@Override
public void visit(ConditionalJump conditionalJump) {
if(vm.returnValue.equals("true")){
node = (conditionalJump).getNextTrue();
}
else if(vm.returnValue.equals("false")){
node = ((ConditionalJump) conditionalJump).getNextFalse();
}
else{
throw new RuntimeException("expected true or false, found : " + vm.returnValue);
}
}
@Override
public void visit(DirectFunctionCall directFunctionCall) {
vm.commands.get(directFunctionCall.parameters.get(0)).Execute(directFunctionCall, vm);
this.node = directFunctionCall.getNext();
}
@Override
public void visit(DoNothing doNothing) {
node = doNothing.getNext();
}
@Override
public void visit(FunctionCall functionCall) {
vm.commands.get(functionCall.parameters.get(0)).Execute(functionCall, vm);
this.node = functionCall.getNext();
}
@Override
public void visit(Jump jump) {
node = jump.JumpToNode;
}
}
|
package dsp;
public class MyLList {
int count = 0;
node head = null;
class node {
int data;
node next = null;
node (int i) {
data = i;
}
}
public void insert(int key) {
count++;
if(head == null) {
head = new node(key);
return;
}
node q = head;
node p = head;
while(p != null) {
q = p;
p = p.next;
}
q.next = new node(key);
}
public void print() {
if(head == null)
return;
node p = head;
while(p != null) {
System.out.print(" " + p.data);
p = p.next;
}
}
public void delete(int key) {
if(head == null)
return;
node q = head;
node p = head;
while(p != null) {
if(p.data == key) {
q.next = p.next;
return;
}
q = p;
p = p.next;
}
}
public void reverse() {
if(head == null)
return;
node q = head;
node p = head;
node r = head;
while(p != null) {
r = p.next;
p.next = q;
if(q == head)
q.next = null;
q = p;
p = r;
}
head = q;
}
public boolean isPresentKey(int key) {
node p = head;
while(p != null) {
if(p.data == key)
return true;
p = p.next;
}
return false;
}
}
|
/*
* Copyright 2002-2018 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.servlet.mvc.condition;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
/**
* Supports "name=value" style expressions as described in:
* {@link org.springframework.web.bind.annotation.RequestMapping#params()} and
* {@link org.springframework.web.bind.annotation.RequestMapping#headers()}.
*
* @author Rossen Stoyanchev
* @author Arjen Poutsma
* @since 3.1
* @param <T> the value type
*/
abstract class AbstractNameValueExpression<T> implements NameValueExpression<T> {
protected final String name;
@Nullable
protected final T value;
protected final boolean isNegated;
AbstractNameValueExpression(String expression) {
int separator = expression.indexOf('=');
if (separator == -1) {
this.isNegated = expression.startsWith("!");
this.name = (this.isNegated ? expression.substring(1) : expression);
this.value = null;
}
else {
this.isNegated = (separator > 0) && (expression.charAt(separator - 1) == '!');
this.name = (this.isNegated ? expression.substring(0, separator - 1) : expression.substring(0, separator));
this.value = parseValue(expression.substring(separator + 1));
}
}
@Override
public String getName() {
return this.name;
}
@Override
@Nullable
public T getValue() {
return this.value;
}
@Override
public boolean isNegated() {
return this.isNegated;
}
public final boolean match(HttpServletRequest request) {
boolean isMatch;
if (this.value != null) {
isMatch = matchValue(request);
}
else {
isMatch = matchName(request);
}
return this.isNegated != isMatch;
}
protected abstract boolean isCaseSensitiveName();
protected abstract T parseValue(String valueExpression);
protected abstract boolean matchName(HttpServletRequest request);
protected abstract boolean matchValue(HttpServletRequest request);
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
AbstractNameValueExpression<?> that = (AbstractNameValueExpression<?>) other;
return ((isCaseSensitiveName() ? this.name.equals(that.name) : this.name.equalsIgnoreCase(that.name)) &&
ObjectUtils.nullSafeEquals(this.value, that.value) && this.isNegated == that.isNegated);
}
@Override
public int hashCode() {
int result = (isCaseSensitiveName() ? this.name.hashCode() : this.name.toLowerCase().hashCode());
result = 31 * result + (this.value != null ? this.value.hashCode() : 0);
result = 31 * result + (this.isNegated ? 1 : 0);
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (this.value != null) {
builder.append(this.name);
if (this.isNegated) {
builder.append('!');
}
builder.append('=');
builder.append(this.value);
}
else {
if (this.isNegated) {
builder.append('!');
}
builder.append(this.name);
}
return builder.toString();
}
}
|
import com.sun.org.apache.xpath.internal.SourceTree;
public class Main {
public static void main(String[] args) {
Figure Square1 = new Figure(8,5);
Figure Square2 = new Figure(12,5);
Figure Square3 = new Figure(12,5);
Figure Rectangle2 = new Figure(4,5);
Figure Rectangle1 = new Figure(4,5);
Figure Triangle2 = new Figure(2,5);
Figure Triangle1 = new Figure(5,5);
int a[] = new int[7];
Figure arr[] = {Square1,Square2,Square3,Rectangle1,Rectangle2,Triangle2, Triangle1};
for (int i = 0; i < arr.length; i++) {
for (int j = i; i < arr.length; j++) {
if ((arr[i].area == arr[j].area) && (arr[i].perimetr == arr[j].perimetr) &&(arr[i] != null) &&(arr[j] != null)) {
arr[j] = null;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[i]" + " ");
}
System.out.println("Hello");
}
}
|
package io.mosip.tf.t5.cryptograph.model;
import lombok.Data;
@Data
public class StatusEvent {
private String id;
private String requestId;
private String timestamp;
private String status;
private String url;
}
|
package com.zxt.compplatform.skip.entity;
public class MenuSetting {
public String ioc;
public String style;
public String event;
public String url;
public String text;
public String id;
public String menuLayout;
public String formUrl;
public String getMenuLayout() {
return menuLayout;
}
public void setMenuLayout(String menuLayout) {
this.menuLayout = menuLayout;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getIoc() {
return ioc;
}
public void setIoc(String ioc) {
this.ioc = ioc;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFormUrl() {
return formUrl;
}
public void setFormUrl(String formUrl) {
this.formUrl = formUrl;
}
}
|
/*
* (c) 2009 Thomas Smits
*/
package de.smits_net.tpe.vererbung5;
public class Klasse {
int i;
}
|
package com.prep.quiz83;
import java.util.Random;
//Shuffle an array with equal probability of generating any of the possible permutations
public class Drill10 {
public static void main(String[] args){
int[] input={1,2,3,4,5};
for(int i=0;i<10;i++){
shuffle(input);
//shuffle2(input);
//shuffle3(input);
}
}
public static void shuffle(int[] input){
Random random= new Random(System.currentTimeMillis());
for(int i=input.length-1;i>0;i--){
int j= random.nextInt(i+1);
swap(i,j,input);
}
for(int i=0;i<input.length;i++){
System.out.print(input[i] + " , ");
}
System.out.println("\r\n");
}
public static void swap(int i,int j, int[] input){
int tmp=input[j];
input[j]=input[i];
input[i]=tmp;
}
public static void shuffle2(int[] input){
int[] output=new int[input.length];
for(int i=0;i<output.length;i++){
output[i]=-1;
}
int count=0;
while(count<input.length){
// 0 ~4
int tmp=(int)(Math.random()*(input.length - count));
if(!isContains(input[tmp],output))
output[count++]=input[tmp];
}
for(int i=0;i<output.length;i++){
System.out.print(output[i] + " , ");
}
System.out.println("\r\n");
}
public static boolean isContains(int k,int[] input){
for(int i=0;i<input.length;i++){
if(k==input[i])
return true;
}
return false;
}
public static void shuffle3(int[] input){
int[] output=new int[input.length];
int[] tmp=trim(-1,input);
for(int i=0;i<input.length;i++){
int idx=byRandomClass(tmp);
output[i]=tmp[idx];
tmp=trim(idx,tmp);
}
for(int i=0;i<output.length;i++){
System.out.print(output[i] + " , ");
}
System.out.println("\r\n");
}
public static int byRandomClass(int[] input){
int probability = 1/input.length;
Random random = new Random();
for(int i=0;i<input.length;i++){
boolean b=random.nextBoolean();
if(b)
return i;
}
return input.length-1;
}
public static int[] trim(int index,int[] input){
if(index==-1)
return input;
int[] tmp=new int[input.length-1];
int count=0;
for(int i=0;i<input.length;i++){
if(i!=index)
tmp[count++]=input[i];
}
return tmp;
}
}
|
package ua.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ua.domain.*;
import ua.services.ContactService;
import ua.services.SessionService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
@Controller
@RequestMapping("/")
public class MyController {
@Autowired
private ContactService contactService;
@Autowired
private SessionService sessionService;
@RequestMapping("/")
public String index(Model model) {
model.addAttribute("categories", contactService.listCategories());
return "index_categories";
}
@RequestMapping("/edit")
public String editPage(Model model) {
model.addAttribute("categories", contactService.listCategories());
model.addAttribute("products", contactService.listProducts());
model.addAttribute("orders", contactService.listOrders());
return "edit_page";
}
@RequestMapping("/category/{id}")
public String listCategory(@PathVariable(value = "id") long categoryId, Model model) {
Category category = contactService.findCategory(categoryId);
model.addAttribute("categories", contactService.listCategories());
model.addAttribute("products", contactService.listProducts(category));
return "index_products";
}
@RequestMapping(value = "/search", method = RequestMethod.POST)
public String search(@RequestParam String pattern, Model model) {
model.addAttribute("categories", contactService.listCategories());
model.addAttribute("products", contactService.searchProducts(pattern));
return "index_products";
}
/*PRODUCT ADD-DELETE*/
@RequestMapping(value = "/edit/product/delete", method = RequestMethod.POST)
public String searchProd(@RequestParam(value = "product") long toDeleteId, Model model) {
contactService.deleteProduct(toDeleteId);
model.addAttribute("categories", contactService.listCategories());
model.addAttribute("products", contactService.listProducts());
return "index_categories";
}
@RequestMapping(value="/edit/product/add", method = RequestMethod.POST)
public String productAdd(@RequestParam(value = "category") long categoryId,
@RequestParam String name,
@RequestParam String description,
@RequestParam int price,
Model model)
{
Category category = contactService.findCategory(categoryId);
Product product = new Product(category, name, description, price);
contactService.addProduct(product);
model.addAttribute("categories", contactService.listCategories());
return "index_categories";
}
/*CATEGORY ADD-DELETE*/
@RequestMapping(value = "/edit/category/delete", method = RequestMethod.POST)
public String searchCat(@RequestParam(value = "category") long toDeleteId, Model model) {
contactService.deleteCategory(toDeleteId);
model.addAttribute("categories", contactService.listCategories());
return "index_categories";
}
@RequestMapping(value="/edit/category/add", method = RequestMethod.POST)
public String groupAdd(@RequestParam String name,
@RequestParam(value = "picture") MultipartFile picture,
Model model)
{
try {
Category category = new Category(
name,
picture.isEmpty() ? null : new Picture(picture.getOriginalFilename(), picture.getBytes())
);
contactService.addCategory(category);
} catch (IOException ex){
ex.printStackTrace();
return null;
}
model.addAttribute("categories", contactService.listCategories());
return "index_categories";
}
/*CART*/
@RequestMapping(value = "/product/buy/{id}", method = RequestMethod.POST)
public String buyProduct(@PathVariable(value = "id") long productId,
Model model,
HttpServletRequest request)
{
HttpSession session = request.getSession();
sessionService.checkCartSession(session);
Product product = contactService.findProduct(productId);
ArrayList<Product> cart = sessionService.getCart(session);
cart.add(product);
//Counting order price
int price = 0;
for (Product p : cart) {
price = price + p.getPrice();
}
model.addAttribute("price", price);
model.addAttribute("cart", cart);
model.addAttribute("categories", contactService.listCategories());
return "cart";
}
@RequestMapping("/cart")
public String showCart(Model model, HttpServletRequest request) {
HttpSession session = request.getSession();
sessionService.checkCartSession(session);
List<Product> cart = sessionService.getCart(session);
//Counting order price
int price = 0;
for (Product p : cart) {
price = price + p.getPrice();
}
model.addAttribute("price", price);
model.addAttribute("cart", cart);
model.addAttribute("categories", contactService.listCategories());
return "cart";
}
@RequestMapping(value = "/cart/delete/{id}", method = RequestMethod.POST)
public String cartDelete(@PathVariable(value = "id") long productId,
Model model,
HttpServletRequest request)
{
HttpSession session = request.getSession();
sessionService.checkCartSession(session);
List<Product> cart = sessionService.getCart(session);
//Deleting product by its id from cart
Iterator<Product> iterator = cart.iterator();
while (iterator.hasNext()) {
Product currentProduct = iterator.next();
if (currentProduct.getId() == productId){
iterator.remove();
break;
}
}
//Counting order price
int price = 0;
for (Product p : cart) {
price = price + p.getPrice();
}
model.addAttribute("price", price);
model.addAttribute("cart", cart);
model.addAttribute("categories", contactService.listCategories());
return "cart";
}
@RequestMapping(value="/cart/pay", method = RequestMethod.POST)
public String cartPay(@RequestParam String name,
@RequestParam String email,
@RequestParam String phone,
Model model,
HttpServletRequest request)
{
HttpSession session = request.getSession();
sessionService.checkCartSession(session);
if (sessionService.getCart(session).isEmpty()) {
model.addAttribute("categories", contactService.listCategories());
model.addAttribute("session_error", "Session error.");
return "cart";
} else {
List<Product> cart = sessionService.getCart(session);
//Counting order price
int price = 0;
for (Product p : cart) {
price = price + p.getPrice();
}
//Checking user's phone number length
if ((phone.length() > 13) || (phone.length() < 4)) {
model.addAttribute("error", "Incorrect phone number. Please enter valid phone number.");
model.addAttribute("price", price);
model.addAttribute("cart", cart);
model.addAttribute("categories", contactService.listCategories());
return "cart";
//Checking user's input length
} else if ((email.length() > 70) || (name.length() > 70) || (email.length() < 4) || (name.length() < 2)) {
model.addAttribute("error", "Incorrect input. Please enter valid information.");
model.addAttribute("price", price);
model.addAttribute("cart", cart);
model.addAttribute("categories", contactService.listCategories());
return "cart";
} else {
Client client = null;
List<Client> clients = contactService.listClients();
//Checking if the same client already exists in database
for (Client c : clients) {
if (c.getName().equalsIgnoreCase(name) && c.getEmail().equalsIgnoreCase(email) && c.getPhone().equalsIgnoreCase(phone)) {
client = c;
break;
}
}
//If client doesn't exists in database, adding a new client and getting the reference to it from database
if (client == null) {
client = new Client(name, email, phone);
contactService.addClient(client);
clients = contactService.listClients();
for (Client c : clients) {
if (c.getName().equalsIgnoreCase(name) && c.getEmail().equalsIgnoreCase(email) && c.getPhone().equalsIgnoreCase(phone)) {
client = c;
break;
}
}
}
//Creating an order by putting to it product from cart, client and current time (1 product = 1 order)
for (Product c : cart) {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String time = sdf.format(date);
Order order = new Order(c, client, time);
contactService.addOrder(order);
}
cart.clear();
model.addAttribute("categories", contactService.listCategories());
return "thanks";
}
}
}
/*PICTURES*/
@RequestMapping("/picture/{file_id}")
public void getPicture(HttpServletRequest request,
HttpServletResponse response,
@PathVariable("file_id") long fileId)
{
try {
byte[] body = contactService.findPicture(fileId);
response.setContentType("image/png");
response.getOutputStream().write(body);
} catch (IOException ex) {
ex.printStackTrace();
}
}
/*OTHER*/
@RequestMapping("/logout")
public String logout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "index_categories";
}
@RequestMapping("/about")
public String contact(Model model) {
model.addAttribute("categories", contactService.listCategories());
return "about";
}
@RequestMapping(value = "/thanks", method = RequestMethod.POST)
public String thankYou(Model model) {
model.addAttribute("categories", contactService.listCategories());
return "thanks";
}
}
|
/*
* 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 dto;
import java.sql.Date;
/**
*
* @author hienl
*/
public class HistoryDTO {
private String historyID;
private String email;
private String questID;
private String updateContent;
private Date updateDate;
public HistoryDTO(String historyID, String email, String questID, String updateContent, Date updateDate) {
this.historyID = historyID;
this.email = email;
this.questID = questID;
this.updateContent = updateContent;
this.updateDate = updateDate;
}
public HistoryDTO() {
}
public String getHistoryID() {
return historyID;
}
public void setHistoryID(String historyID) {
this.historyID = historyID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getQuestID() {
return questID;
}
public void setQuestID(String questID) {
this.questID = questID;
}
public String getUpdateContent() {
return updateContent;
}
public void setUpdateContent(String updateContent) {
this.updateContent = updateContent;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
}
|
package com.intentsg.service.tour.model;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.persistence.*;
@Entity
@Table(name = "tours")
@Component
@Scope("prototype")
public class Tour {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Column(name = "price")
private int price;
@Column(name = "image_url")
private String imageUrl;
public Tour(Long id, String title, String description, int price, String imageUrl) {
this.id = id;
this.title = title;
this.description = description;
this.price = price;
this.imageUrl = imageUrl;
}
public Tour() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
@Override
public String toString() {
return "Tour{" +
"id=" + id +
", title='" + title + '\'' +
", price=" + price +
", imageUrl='" + imageUrl + '\'' +
'}';
}
}
|
/**
*/
package iso20022.impl;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Map;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.DiagnosticChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;
import iso20022.Iso20022Package;
import iso20022.MessageInstance;
import iso20022.MessagingEndpoint;
import iso20022.TransportMessage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Transport Message</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link iso20022.impl.TransportMessageImpl#getSender <em>Sender</em>}</li>
* <li>{@link iso20022.impl.TransportMessageImpl#getMessageInstance <em>Message Instance</em>}</li>
* <li>{@link iso20022.impl.TransportMessageImpl#getReceiver <em>Receiver</em>}</li>
* </ul>
*
* @generated
*/
public class TransportMessageImpl extends ModelEntityImpl implements TransportMessage {
/**
* The cached value of the '{@link #getSender() <em>Sender</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSender()
* @generated
* @ordered
*/
protected MessagingEndpoint sender;
/**
* The cached value of the '{@link #getMessageInstance() <em>Message Instance</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMessageInstance()
* @generated
* @ordered
*/
protected MessageInstance messageInstance;
/**
* The cached value of the '{@link #getReceiver() <em>Receiver</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReceiver()
* @generated
* @ordered
*/
protected EList<MessagingEndpoint> receiver;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected TransportMessageImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Iso20022Package.eINSTANCE.getTransportMessage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MessagingEndpoint getSender() {
if (sender != null && sender.eIsProxy()) {
InternalEObject oldSender = (InternalEObject)sender;
sender = (MessagingEndpoint)eResolveProxy(oldSender);
if (sender != oldSender) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, Iso20022Package.TRANSPORT_MESSAGE__SENDER, oldSender, sender));
}
}
return sender;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MessagingEndpoint basicGetSender() {
return sender;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetSender(MessagingEndpoint newSender, NotificationChain msgs) {
MessagingEndpoint oldSender = sender;
sender = newSender;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Iso20022Package.TRANSPORT_MESSAGE__SENDER, oldSender, newSender);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSender(MessagingEndpoint newSender) {
if (newSender != sender) {
NotificationChain msgs = null;
if (sender != null)
msgs = ((InternalEObject)sender).eInverseRemove(this, Iso20022Package.MESSAGING_ENDPOINT__SENT_MESSAGE, MessagingEndpoint.class, msgs);
if (newSender != null)
msgs = ((InternalEObject)newSender).eInverseAdd(this, Iso20022Package.MESSAGING_ENDPOINT__SENT_MESSAGE, MessagingEndpoint.class, msgs);
msgs = basicSetSender(newSender, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.TRANSPORT_MESSAGE__SENDER, newSender, newSender));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MessageInstance getMessageInstance() {
if (messageInstance != null && messageInstance.eIsProxy()) {
InternalEObject oldMessageInstance = (InternalEObject)messageInstance;
messageInstance = (MessageInstance)eResolveProxy(oldMessageInstance);
if (messageInstance != oldMessageInstance) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, Iso20022Package.TRANSPORT_MESSAGE__MESSAGE_INSTANCE, oldMessageInstance, messageInstance));
}
}
return messageInstance;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MessageInstance basicGetMessageInstance() {
return messageInstance;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetMessageInstance(MessageInstance newMessageInstance, NotificationChain msgs) {
MessageInstance oldMessageInstance = messageInstance;
messageInstance = newMessageInstance;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Iso20022Package.TRANSPORT_MESSAGE__MESSAGE_INSTANCE, oldMessageInstance, newMessageInstance);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMessageInstance(MessageInstance newMessageInstance) {
if (newMessageInstance != messageInstance) {
NotificationChain msgs = null;
if (messageInstance != null)
msgs = ((InternalEObject)messageInstance).eInverseRemove(this, Iso20022Package.MESSAGE_INSTANCE__TRANSPORT_MESSAGE, MessageInstance.class, msgs);
if (newMessageInstance != null)
msgs = ((InternalEObject)newMessageInstance).eInverseAdd(this, Iso20022Package.MESSAGE_INSTANCE__TRANSPORT_MESSAGE, MessageInstance.class, msgs);
msgs = basicSetMessageInstance(newMessageInstance, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.TRANSPORT_MESSAGE__MESSAGE_INSTANCE, newMessageInstance, newMessageInstance));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<MessagingEndpoint> getReceiver() {
if (receiver == null) {
receiver = new EObjectWithInverseResolvingEList.ManyInverse<MessagingEndpoint>(MessagingEndpoint.class, this, Iso20022Package.TRANSPORT_MESSAGE__RECEIVER, Iso20022Package.MESSAGING_ENDPOINT__RECEIVED_MESSAGE);
}
return receiver;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public boolean sameMessageTransportSystem(Map context, DiagnosticChain diagnostics) {
// TODO: implement this method >>> DONE
// Ensure that you remove @generated or mark it @generated NOT
return true;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.TRANSPORT_MESSAGE__SENDER:
if (sender != null)
msgs = ((InternalEObject)sender).eInverseRemove(this, Iso20022Package.MESSAGING_ENDPOINT__SENT_MESSAGE, MessagingEndpoint.class, msgs);
return basicSetSender((MessagingEndpoint)otherEnd, msgs);
case Iso20022Package.TRANSPORT_MESSAGE__MESSAGE_INSTANCE:
if (messageInstance != null)
msgs = ((InternalEObject)messageInstance).eInverseRemove(this, Iso20022Package.MESSAGE_INSTANCE__TRANSPORT_MESSAGE, MessageInstance.class, msgs);
return basicSetMessageInstance((MessageInstance)otherEnd, msgs);
case Iso20022Package.TRANSPORT_MESSAGE__RECEIVER:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getReceiver()).basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.TRANSPORT_MESSAGE__SENDER:
return basicSetSender(null, msgs);
case Iso20022Package.TRANSPORT_MESSAGE__MESSAGE_INSTANCE:
return basicSetMessageInstance(null, msgs);
case Iso20022Package.TRANSPORT_MESSAGE__RECEIVER:
return ((InternalEList<?>)getReceiver()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Iso20022Package.TRANSPORT_MESSAGE__SENDER:
if (resolve) return getSender();
return basicGetSender();
case Iso20022Package.TRANSPORT_MESSAGE__MESSAGE_INSTANCE:
if (resolve) return getMessageInstance();
return basicGetMessageInstance();
case Iso20022Package.TRANSPORT_MESSAGE__RECEIVER:
return getReceiver();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Iso20022Package.TRANSPORT_MESSAGE__SENDER:
setSender((MessagingEndpoint)newValue);
return;
case Iso20022Package.TRANSPORT_MESSAGE__MESSAGE_INSTANCE:
setMessageInstance((MessageInstance)newValue);
return;
case Iso20022Package.TRANSPORT_MESSAGE__RECEIVER:
getReceiver().clear();
getReceiver().addAll((Collection<? extends MessagingEndpoint>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Iso20022Package.TRANSPORT_MESSAGE__SENDER:
setSender((MessagingEndpoint)null);
return;
case Iso20022Package.TRANSPORT_MESSAGE__MESSAGE_INSTANCE:
setMessageInstance((MessageInstance)null);
return;
case Iso20022Package.TRANSPORT_MESSAGE__RECEIVER:
getReceiver().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Iso20022Package.TRANSPORT_MESSAGE__SENDER:
return sender != null;
case Iso20022Package.TRANSPORT_MESSAGE__MESSAGE_INSTANCE:
return messageInstance != null;
case Iso20022Package.TRANSPORT_MESSAGE__RECEIVER:
return receiver != null && !receiver.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
switch (operationID) {
case Iso20022Package.TRANSPORT_MESSAGE___SAME_MESSAGE_TRANSPORT_SYSTEM__MAP_DIAGNOSTICCHAIN:
return sameMessageTransportSystem((Map)arguments.get(0), (DiagnosticChain)arguments.get(1));
}
return super.eInvoke(operationID, arguments);
}
} //TransportMessageImpl
|
package jarjestaminen.ui;
import jarjestaminen.ui.Commands;
import java.util.Arrays;
import java.util.Random;
public class SuoritusTestit {
public static void suoritusTestitSuorita(int pituus) {
System.out.println("Kouluarvosanat: ");
System.out.println("");
SuoritusTestit.kouluarvosanat(pituus);
System.out.println("");
System.out.println("- - - - - - - - - ");
System.out.println("");
System.out.println("Päinvastainen järjestys: ");
System.out.println("");
SuoritusTestit.painvastainenJarjestys(pituus);
System.out.println("");
System.out.println("- - - - - - - - - ");
System.out.println("");
System.out.println("Valmiiksi järjestetty: ");
System.out.println("");
SuoritusTestit.valmiiksiJarjestetty(pituus);
System.out.println("");
System.out.println("- - - - - - - - - ");
System.out.println("");
System.out.println("Syklittäinen järjestys: ");
System.out.println("");
SuoritusTestit.sykleittainenJarjestys(pituus);
System.out.println("");
System.out.println("- - - - - - - - - ");
System.out.println("");
}
public static int[] luoArvosanaTaulukko(int pituus) {
int[] arr = new int[pituus];
Random rand = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt((10 - 4) + 1) + 4;
}
return arr;
}
public static void kouluarvosanat(int pituus) {
int[] arrIn = luoArvosanaTaulukko(pituus);
long time = 0;
try {
time = Commands.insertionSort(arrIn);
System.out.println("insertionsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrQuick = luoArvosanaTaulukko(pituus);
time = Commands.quickSort(arrQuick);
System.out.println("quicksort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrHeap = luoArvosanaTaulukko(pituus);
time = Commands.heapSort(arrHeap);
System.out.println("heapsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrMerge = luoArvosanaTaulukko(pituus);
time = Commands.mergeSort(arrMerge);
System.out.println("mergesort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrTim = luoArvosanaTaulukko(pituus);
time = Commands.timSort(arrTim);
System.out.println("timsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrIntro = luoArvosanaTaulukko(pituus);
time = Commands.introSort(arrIntro);
System.out.println("introsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
}
public static int[] luoValmiiksiJarjestettyTaulukko(int pituus) {
int[] arr = new int[pituus];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
return arr;
}
public static void valmiiksiJarjestetty(int pituus) {
int[] arrIn = luoValmiiksiJarjestettyTaulukko(pituus);
long time = 0;
try {
time = Commands.insertionSort(arrIn);
System.out.println("insertionsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrQuick = luoValmiiksiJarjestettyTaulukko(pituus);
time = Commands.quickSort(arrQuick);
System.out.println("quicksort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrHeap = luoValmiiksiJarjestettyTaulukko(pituus);
time = Commands.heapSort(arrHeap);
System.out.println("heapsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrMerge = luoValmiiksiJarjestettyTaulukko(pituus);
time = Commands.mergeSort(arrMerge);
System.out.println("mergesort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrTim = luoValmiiksiJarjestettyTaulukko(pituus);
time = Commands.timSort(arrTim);
System.out.println("timsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrIntro = luoValmiiksiJarjestettyTaulukko(pituus);
time = Commands.introSort(arrIntro);
System.out.println("introsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
}
public static int[] luoPainVastainenTaulukko(int pituus) {
int[] arr = new int[pituus];
for (int i = 0; i < arr.length; i++) {
arr[i] = arr.length - i;
}
return arr;
}
public static void painvastainenJarjestys(int pituus) {
int[] arrIn = luoPainVastainenTaulukko(pituus);
long time = 0;
try {
time = Commands.insertionSort(arrIn);
System.out.println("insertionsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrQuick = luoPainVastainenTaulukko(pituus);
time = Commands.quickSort(arrQuick);
System.out.println("quicksort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrHeap = luoPainVastainenTaulukko(pituus);
time = Commands.heapSort(arrHeap);
System.out.println("heapsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrMerge = luoPainVastainenTaulukko(pituus);
time = Commands.mergeSort(arrMerge);
System.out.println("mergesort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrTim = luoPainVastainenTaulukko(pituus);
time = Commands.timSort(arrTim);
System.out.println("timsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrIntro = luoPainVastainenTaulukko(pituus);
time = Commands.introSort(arrIntro);
System.out.println("introsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
}
public static int[] luoSykleittainenTaulukko(int pituus) {
int[] arr = new int[pituus];
int[] minus = {-20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2 - 1};
int[] plus = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25};
Random rand = new Random();
for (int i = 0; i < arr.length - 1; i++) {
for (int ii = 0; ii < minus.length; ii++) {
if (i >= arr.length) {
break;
}
arr[i] = minus[ii] + rand.nextInt(3 - -2 + 1) + -2;
i++;
}
for (int iii = 0; iii < plus.length; iii++) {
if (i >= arr.length) {
break;
}
arr[i] = plus[iii] + rand.nextInt(3 - -2 + 1) + -2;
i++;
}
}
return arr;
}
public static void sykleittainenJarjestys(int pituus) {
int[] arrIn = luoSykleittainenTaulukko(pituus);
long time = 0;
try {
time = Commands.insertionSort(arrIn);
System.out.println("insertionsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrQuick = luoSykleittainenTaulukko(pituus);
time = Commands.quickSort(arrQuick);
System.out.println("quicksort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrHeap = luoSykleittainenTaulukko(pituus);
time = Commands.heapSort(arrHeap);
System.out.println("heapsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrMerge = luoSykleittainenTaulukko(pituus);
time = Commands.mergeSort(arrMerge);
System.out.println("mergesort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrTim = luoSykleittainenTaulukko(pituus);
time = Commands.timSort(arrTim);
System.out.println("timsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
try {
int[] arrIntro = luoSykleittainenTaulukko(pituus);
time = Commands.introSort(arrIntro);
System.out.println("introsort: " + time);
} catch (StackOverflowError e) {
System.err.println("Stackoverflowerror!");
}
System.out.println("");
}
}
|
package Pro461.HammingDistance;
public class Solution {
public static void main(String[] args) {
System.out.println(hammingDistance(1, 4));
}
/**
* 计算x和y的二进制不同内容的位数, 实际将x和y取异或, 求出异或后的数有多少个1
*
* @param x
* @param y
* @return
*/
public static int hammingDistance(int x, int y) {
int i = x ^ y;
int count = 0;
while (i != 0) {
++count;
i = (i - 1) & i;
}
return count;
}
}
|
package com.freakybyte.movies.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.freakybyte.movies.data.tables.FavoriteEntry;
import com.freakybyte.movies.data.tables.MovieEntry;
import com.freakybyte.movies.data.tables.PopularEntry;
import com.freakybyte.movies.util.DebugUtils;
/**
* Created by Jose Torres on 10/11/2016.
*/
public class MovieDbHelper extends SQLiteOpenHelper {
public static final String TAG = "MovieDbHelper";
private static final int DATABASE_VERSION = 2;
public static final long FAIL_DB_MODIFY = -1L;
public static final String DATABASE_NAME = "udacity_pop_movie.db";
public MovieDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
DebugUtils.logDebug(TAG, "OnCreate DB");
sqLiteDatabase.execSQL(MovieEntry.SQL_CREATE_TABLE);
sqLiteDatabase.execSQL(PopularEntry.SQL_CREATE_TABLE);
sqLiteDatabase.execSQL(FavoriteEntry.SQL_CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
DebugUtils.logDebug(TAG, "OnUpdate DB");
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + MovieEntry.TABLE_NAME);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + PopularEntry.TABLE_NAME);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + FavoriteEntry.TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
|
/*
* 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 BO;
import DAO.ConnectionFactory;
import DAO.DAOCarrinho;
import DAO.DAOPedido;
import PO.carrinho;
import java.sql.Connection;
import java.util.List;
/**
*
* @author 20161863120268
*/
public class CarrinhoBO {
private static CarrinhoBO myInstance;
private CarrinhoBO() {
}
public static synchronized CarrinhoBO getInstance() {
if (myInstance == null) {
myInstance = new CarrinhoBO();
}
return myInstance;
}
public List<carrinho> getAll() throws Exception {
ConnectionFactory connFac = new ConnectionFactory();
try {
Connection con = connFac.getConnection(true);
List<carrinho> list = new DAOCarrinho(con).getAll();
//new DAOPedido(con);
for (int i = 0; i < list.size(); i++) {
carrinho car = list.get(i);
//capsdifi
}
connFac.commit();
} catch (Exception e) {
connFac.rolback();
throw e;
} finally {
connFac.close();
}
return null;
}
}
|
@Local
public interface gestionUsagerLocal {
public usager addUsager(int idUser, string psw) throws userAlreadyExistsException;
public usager identify(int iduser, String psw) throws userNotFoundException;
}
|
package com.wangban.yzbbanban.test_updatadownload.update;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.lang.*;
import static android.content.ContentValues.TAG;
/**
* Created by YZBbanban on 16/8/7.
* 真正负责处理文件的下载以及线程间的通信
*/
public class UpdateDownloadRequest implements Runnable {
private String downloadUrl;
private String localFilePath;
private UpdateDownloadListener listener;
private boolean isDownloading = false;
private long currentLenth;
private DownloadResponseHandler downloadHandler;
public UpdateDownloadRequest(String downloadUrl, String localFilePath, UpdateDownloadListener listener) {
this.downloadUrl = downloadUrl;
this.localFilePath = localFilePath;
this.listener = listener;
}
//真正去建立连接的方法
private void makeRequst() throws IOException, InterruptedException {
if (!Thread.currentThread().isInterrupted()) {
try {
URL url = new URL(downloadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.connect();//阻塞当前线程
currentLenth = connection.getContentLength();
if (!Thread.currentThread().isInterrupted()) {
//真正完成下载
downloadHandler.sendResponseMessage(connection.getInputStream());
}
} catch (IOException e) {
throw e;
}
}
}
@Override
public void run() {
try {
Log.i(TAG, "run: "+"执行Run()方法");
makeRequst();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 格式化数字
*
* @param value
* @return
*/
private String getTwoPointFloatStr(float value) {
DecimalFormat fnum = new DecimalFormat("0.00");
return fnum.format(value);
}
/**
* 下载过程中有可能会出现的所有异常
*/
public enum FailureCode {
UnKnownHost, Socket, SocketTimeOut, ConnectTimeOut, IO, HttpResponse, JSON, Interrupted
}
public class DownloadResponseHandler {
protected static final int SUCCESS_MESSAGE = 0;
protected static final int FAILURE_MESSAGE = 1;
protected static final int START_MESSAGE = 2;
protected static final int FINISH_MESSAGE = 3;
protected static final int NETWORK_OFF = 4;
private static final int PROGRESS_CHANGED = 5;
private int mConpleteSize = 0;
private int progress = 0;
private Handler handler;
public DownloadResponseHandler() {
handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
handleSelfMessage(msg);
}
};
}
protected void sendFinishMessage() {
sendMessage(obtainMessage(FINISH_MESSAGE, null));
}
private void sendProgressChangedMessage(int progress) {
sendMessage(obtainMessage(PROGRESS_CHANGED, new Object[]{progress}));
}
protected void sendFailureMessage(FailureCode failureCode) {
sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[]{failureCode}));
}
private void sendMessage(Message msg) {
}
/**
* 获取一个消息对象
*
* @param responseMessage
* @param response
* @return
*/
protected Message obtainMessage(int responseMessage, Object response) {
Message msg = null;
if (handler != null) {
msg = handler.obtainMessage(responseMessage, response);
} else {
msg = Message.obtain();
msg.what = responseMessage;
msg.obj = response;
}
return msg;
}
private void handleSelfMessage(Message msg) {
Object[] response;
switch (msg.what) {
case FAILURE_MESSAGE:
response = (Object[]) msg.obj;
handleFailureMessage((FailureCode) response[0]);
break;
case PROGRESS_CHANGED:
response = (Object[]) msg.obj;
handleProgressChangedMessage(((Integer) response[0]).intValue());
break;
case FINISH_MESSAGE:
onFinish();
break;
}
}
/**
* 各种消息的处理逻辑
*/
protected void handleProgressChangedMessage(int progress) {
listener.onProgressChanged(progress, "");
}
protected void handleFailureMessage(FailureCode failureCode) {
onFailure(failureCode);
}
public void onFinish() {
listener.onFinished(mConpleteSize, "");
}
public void onFailure(FailureCode failCode) {
listener.onFailure();
}
//文件下载方法,会发送各种消息类型事件
void sendResponseMessage(InputStream is) {
RandomAccessFile randomAccessFile = null;
mConpleteSize = 0;
try {
byte[] buffer = new byte[1024];
int lenth = -1;
int limit = 0;
randomAccessFile = new RandomAccessFile(localFilePath, "rwd");
while ((lenth = is.read(buffer)) != -1) {
if (isDownloading) {
randomAccessFile.write(buffer, 0, lenth);
mConpleteSize += lenth;
if (mConpleteSize < currentLenth) {
progress = (int) Float.parseFloat(getTwoPointFloatStr(mConpleteSize / currentLenth));
if (limit / 30 == 0 || progress <= 100) {
sendProgressChangedMessage(progress);
}
limit++;
}
}
}
sendFinishMessage();
} catch (Exception e) {
sendFailureMessage(FailureCode.IO);
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
package common.util;
public class Log4jLogger implements Logger {
private org.apache.log4j.Logger logger;
public Log4jLogger(org.apache.log4j.Logger logger) {
this.logger = logger;
}
public void debug(String message) {
logger.debug(message);
}
public void info(String message) {
logger.info(message);
}
public void warn(String message) {
logger.warn(message);
}
public void error(String message) {
logger.error(message);
}
public void error(String message, Throwable t) {
logger.error(message, t);
}
public void fatal(String message) {
logger.fatal(message);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model.bean.user;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import util.BeanValidator;
import util.exceptions.BeanException;
/**
*
* @author Andriy
*/
@Entity
@Table(name = "user_info", catalog = "testfield")
public class UserInfo implements Serializable {
@Id
@Column(name = "USER_NICK", unique = true, nullable = false, length = 30)
private String userNick;
@Column(name = "EMAIL", nullable = true, length = 80)
private String email;
public String getUserNick() {
return userNick;
}
public void setUserNick(String userNick) throws BeanException {
BeanValidator.validateEmpty(userNick, "User");
BeanValidator.validateLength(userNick, 30, "User");
this.userNick = userNick;
}
public String getEmail() {
return email;
}
public void setEmail(String email) throws BeanException {
if (email != null) {
BeanValidator.validateLength(email, 80, "Email");
}
this.email = email;
}
@Override
public String toString() {
return String.format(
"USER_INFO (\nuserNick: %s, \nEmail: %s\n)",
userNick, email);
}
}
|
package com.crmiguez.aixinainventory.entities;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.hibernate.annotations.ColumnDefault;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Entity(name = "user")
@Table
public class User implements Serializable, UserDetails {
@Id
@GeneratedValue
@Column(name = "userId")
private Long userId;
@JoinColumn(name = "employeeId", referencedColumnName = "employeeId")
@ManyToOne
@JsonInclude(JsonInclude.Include.NON_NULL)
private Employee employee;
@Column(name = "userName")
private String userName;
@Column(name = "userEmail")
private String userEmail;
@Column(name = "userPassword")
private String userPassword;
@Column(name = "lastLogin")
private String lastLogin;
@Column(name = "userRegisterDate")
private String userRegisterDate;
@Column(name = "userShutDate")
private String userShutDate;
@Column(name="admin")
@ColumnDefault(value = "0")
private byte admin;
@Column(name="enabled")
@ColumnDefault(value = "true")
private boolean enabled;
public User() {
}
public User(Long userId, Employee employee, String userName, String userEmail, String userPassword, String lastLogin, String userRegisterDate, String userShutDate, byte admin, boolean enabled) {
this.userId = userId;
this.employee = employee;
this.userName = userName;
this.userEmail = userEmail;
this.userPassword = userPassword;
this.lastLogin = lastLogin;
this.userRegisterDate = userRegisterDate;
this.userShutDate = userShutDate;
this.admin = admin;
this.enabled = enabled;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getLastLogin() {
return lastLogin;
}
public void setLastLogin(String lastLogin) {
this.lastLogin = lastLogin;
}
public String getUserRegisterDate() {
return userRegisterDate;
}
public void setUserRegisterDate(String userRegisterDate) {
this.userRegisterDate = userRegisterDate;
}
public String getUserShutDate() {
return userShutDate;
}
public void setUserShutDate(String userShutDate) {
this.userShutDate = userShutDate;
}
public byte getAdmin() {
return admin;
}
public void setAdmin(byte admin) {
this.admin = admin;
}
public boolean getEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
//Override methods UserDetails
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
// Extract list of permissions (name)
this.getPermissionList().forEach(p -> {
GrantedAuthority authority = new SimpleGrantedAuthority(p);
authorities.add(authority);
});
// Extract list of roles (ROLE_name)
this.getRoleList().forEach(r -> {
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + r);
authorities.add(authority);
});
return authorities;
}
@Override
public String getPassword() {
return userPassword;
}
@Override
public String getUsername() {
return userName;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return this.getEnabled() == true;
}
public List<String> getRoleList(){
List<String> userRoleList = new ArrayList<>();
if (this.getAdmin() == 1)
userRoleList.add("ADMIN");
else
userRoleList.add("GUEST");
return userRoleList;
}
public List<String> getPermissionList(){
List<String> userPermissionsList = new ArrayList<>();
if (this.getAdmin() == 1) {
userPermissionsList.add("PERM_CREATE_INVENTORY");
userPermissionsList.add("PERM_READ_INVENTORY");
userPermissionsList.add("PERM_READ_ALL_INVENTORIES");
userPermissionsList.add("PERM_UPDATE_INVENTORY");
userPermissionsList.add("PERM_DELETE_INVENTORY");
userPermissionsList.add("PERM_CREATE_MOVEMENT");
userPermissionsList.add("PERM_READ_MOVEMENT");
userPermissionsList.add("PERM_READ_ALL_MOVEMENTS");
userPermissionsList.add("PERM_UPDATE_MOVEMENT");
userPermissionsList.add("PERM_READ_ALL_DOWNS");
userPermissionsList.add("PERM_CREATE_MOVE_TYPE");
userPermissionsList.add("PERM_READ_MOVE_TYPE");
userPermissionsList.add("PERM_READ_ALL_MOVE_TYPES");
userPermissionsList.add("PERM_UPDATE_MOVE_TYPE");
userPermissionsList.add("PERM_DELETE_MOVE_TYPE");
userPermissionsList.add("PERM_CREATE_INVOICE");
userPermissionsList.add("PERM_READ_INVOICE");
userPermissionsList.add("PERM_READ_ALL_INVOICES");
userPermissionsList.add("PERM_UPDATE_INVOICE");
userPermissionsList.add("PERM_DELETE_INVOICE");
userPermissionsList.add("PERM_CREATE_LINE");
userPermissionsList.add("PERM_READ_LINE");
userPermissionsList.add("PERM_READ_ALL_LINES");
userPermissionsList.add("PERM_UPDATE_LINE");
userPermissionsList.add("PERM_DELETE_LINE");
userPermissionsList.add("PERM_CREATE_ITEM");
userPermissionsList.add("PERM_READ_ITEM");
userPermissionsList.add("PERM_READ_ALL_ITEMS");
userPermissionsList.add("PERM_UPDATE_ITEM");
userPermissionsList.add("PERM_DELETE_ITEM");
userPermissionsList.add("PERM_CREATE_ITEM_SET");
userPermissionsList.add("PERM_READ_ITEM_SET");
userPermissionsList.add("PERM_READ_ALL_ITEM_SETS");
userPermissionsList.add("PERM_UPDATE_ITEM_SET");
userPermissionsList.add("PERM_DELETE_ITEM_SET");
userPermissionsList.add("PERM_CREATE_ITEM_TYPE");
userPermissionsList.add("PERM_READ_ITEM_TYPE");
userPermissionsList.add("PERM_READ_ALL_ITEM_TYPES");
userPermissionsList.add("PERM_UPDATE_ITEM_TYPE");
userPermissionsList.add("PERM_DELETE_ITEM_TYPE");
userPermissionsList.add("PERM_CREATE_ITEM_IMAGE");
userPermissionsList.add("PERM_READ_ITEM_IMAGE");
userPermissionsList.add("PERM_READ_ALL_ITEM_IMAGES");
userPermissionsList.add("PERM_UPDATE_ITEM_IMAGE");
userPermissionsList.add("PERM_DELETE_ITEM_IMAGE");
userPermissionsList.add("PERM_CREATE_BRAND");
userPermissionsList.add("PERM_READ_BRAND");
userPermissionsList.add("PERM_READ_ALL_BRANDS");
userPermissionsList.add("PERM_UPDATE_BRAND");
userPermissionsList.add("PERM_DELETE_BRAND");
userPermissionsList.add("PERM_CREATE_EMPLOYEE");
userPermissionsList.add("PERM_READ_EMPLOYEE");
userPermissionsList.add("PERM_READ_ALL_EMPLOYEES");
userPermissionsList.add("PERM_UPDATE_EMPLOYEE");
userPermissionsList.add("PERM_DELETE_EMPLOYEE");
userPermissionsList.add("PERM_CREATE_HEADQUARTER");
userPermissionsList.add("PERM_READ_HEADQUARTER");
userPermissionsList.add("PERM_READ_ALL_HEADQUARTERS");
userPermissionsList.add("PERM_UPDATE_HEADQUARTERS");
userPermissionsList.add("PERM_DELETE_HEADQUARTERS");
userPermissionsList.add("PERM_CREATE_DEPARTMENT");
userPermissionsList.add("PERM_READ_DEPARTMENT");
userPermissionsList.add("PERM_READ_ALL_DEPARTMENTS");
userPermissionsList.add("PERM_UPDATE_DEPARTMENT");
userPermissionsList.add("PERM_DELETE_DEPARTMENT");
userPermissionsList.add("PERM_CREATE_LOCATION");
userPermissionsList.add("PERM_READ_LOCATION");
userPermissionsList.add("PERM_READ_ALL_LOCATIONS");
userPermissionsList.add("PERM_UPDATE_LOCATION");
userPermissionsList.add("PERM_DELETE_LOCATION");
}
else if (this.getAdmin() == 0) {
userPermissionsList.add("PERM_CREATE_INVENTORY");
userPermissionsList.add("PERM_READ_INVENTORY");
userPermissionsList.add("PERM_READ_ALL_INVENTORIES");
userPermissionsList.add("PERM_UPDATE_INVENTORY");
userPermissionsList.add("PERM_DELETE_INVENTORY");
userPermissionsList.add("PERM_CREATE_MOVEMENT");
userPermissionsList.add("PERM_READ_MOVEMENT");
userPermissionsList.add("PERM_READ_ALL_MOVEMENTS");
userPermissionsList.add("PERM_UPDATE_MOVEMENT");
userPermissionsList.add("PERM_READ_ALL_DOWNS");
userPermissionsList.add("PERM_CREATE_MOVE_TYPE");
userPermissionsList.add("PERM_READ_MOVE_TYPE");
userPermissionsList.add("PERM_READ_ALL_MOVE_TYPES");
userPermissionsList.add("PERM_UPDATE_MOVE_TYPE");
userPermissionsList.add("PERM_DELETE_MOVE_TYPE");
userPermissionsList.add("PERM_CREATE_INVOICE");
userPermissionsList.add("PERM_READ_INVOICE");
userPermissionsList.add("PERM_READ_ALL_INVOICES");
userPermissionsList.add("PERM_UPDATE_INVOICE");
userPermissionsList.add("PERM_DELETE_INVOICE");
userPermissionsList.add("PERM_CREATE_LINE");
userPermissionsList.add("PERM_READ_LINE");
userPermissionsList.add("PERM_READ_ALL_LINES");
userPermissionsList.add("PERM_UPDATE_LINE");
userPermissionsList.add("PERM_DELETE_LINE");
userPermissionsList.add("PERM_CREATE_ITEM");
userPermissionsList.add("PERM_READ_ITEM");
userPermissionsList.add("PERM_READ_ALL_ITEMS");
userPermissionsList.add("PERM_UPDATE_ITEM");
userPermissionsList.add("PERM_DELETE_ITEM");
userPermissionsList.add("PERM_CREATE_ITEM_SET");
userPermissionsList.add("PERM_READ_ITEM_SET");
userPermissionsList.add("PERM_READ_ALL_ITEM_SETS");
userPermissionsList.add("PERM_UPDATE_ITEM_SET");
userPermissionsList.add("PERM_DELETE_ITEM_SET");
userPermissionsList.add("PERM_CREATE_ITEM_TYPE");
userPermissionsList.add("PERM_READ_ITEM_TYPE");
userPermissionsList.add("PERM_READ_ALL_ITEM_TYPES");
userPermissionsList.add("PERM_UPDATE_ITEM_TYPE");
userPermissionsList.add("PERM_DELETE_ITEM_TYPE");
userPermissionsList.add("PERM_CREATE_ITEM_IMAGE");
userPermissionsList.add("PERM_READ_ITEM_IMAGE");
userPermissionsList.add("PERM_READ_ALL_ITEM_IMAGES");
userPermissionsList.add("PERM_UPDATE_ITEM_IMAGE");
userPermissionsList.add("PERM_DELETE_ITEM_IMAGE");
userPermissionsList.add("PERM_CREATE_BRAND");
userPermissionsList.add("PERM_READ_BRAND");
userPermissionsList.add("PERM_READ_ALL_BRANDS");
userPermissionsList.add("PERM_UPDATE_BRAND");
userPermissionsList.add("PERM_DELETE_BRAND");
//AL EMPLEADO SOLAMENTE PUEDE HACER LECTURA DE LAS SIGUIENTES ENTIDADES
userPermissionsList.add("PERM_READ_HEADQUARTER");
userPermissionsList.add("PERM_READ_ALL_HEADQUARTERS");
userPermissionsList.add("PERM_READ_DEPARTMENT");
userPermissionsList.add("PERM_READ_ALL_DEPARTMENTS");
userPermissionsList.add("PERM_READ_LOCATION");
userPermissionsList.add("PERM_READ_ALL_LOCATIONS");
userPermissionsList.add("PERM_READ_EMPLOYEE");
userPermissionsList.add("PERM_READ_ALL_EMPLOYEES");
}
return userPermissionsList;
}
}
|
package com.dongh.baselib.mvp;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.View;
import com.dongh.baselib.R;
public class BaseFragment<T extends BasePresenter> extends Fragment implements BaseView<T>{
private T mBasePresenter;
protected BaseActivity context = null;
public T getmBasePresenter() {
return mBasePresenter;
}
@Override
public void setPresenter(T presenter) {
mBasePresenter = presenter;
}
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onDestroy() {
if (mBasePresenter != null) {
mBasePresenter.destroy();
}
super.onDestroy();
}
}
|
package com.mr.pojo;
/**
* Created by Lenovo on 2019/4/29.
*/
public class testtwq {
public static void main(String[] args) {
System.err.println(1);
}
}
|
package com.citibank.ods.persistence.pl.dao.rdb.oracle;
import com.citibank.ods.persistence.util.CitiStatement;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.Date;
import com.citibank.ods.common.connection.rdb.ManagedRdbConnection;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.exception.UnexpectedException;
import com.citibank.ods.common.util.BaseConstraintDecoder;
import com.citibank.ods.entity.pl.BaseTplPlayerEntity;
import com.citibank.ods.entity.pl.TplPlayerHistEntity;
import com.citibank.ods.entity.pl.valueobject.TplPlayerHistEntityVO;
import com.citibank.ods.persistence.pl.dao.TplPlayerHistDAO;
import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* [Class description]
*
* @see package com.citibank.ods.persistence.pl.dao.rdb.oracle;
* @version 1.0
* @author acacio.domingos,05/04/2007
*
* <PRE>
*
* <U>Updated by: </U> <U>Description: </U>
*
* </PRE>
*/
public class OracleTplPlayerHistDAO extends BaseOracleTplPlayerDAO implements
TplPlayerHistDAO
{
/*
* Constante que identifica o nome da tabela de histórico
*/
private static final String C_TPL_PLAYER_HIST = C_PL_SCHEMA + "TPL_PLAYER_HIST";
/*
* Campos específicos da tabela
*/
private String C_PLYR_REF_DATE = "PLYR_REF_DATE";
private String C_LAST_AUTH_DATE = "LAST_AUTH_DATE";
private String C_LAST_AUTH_USER_ID = "LAST_AUTH_USER_ID";
private String C_REC_STAT_CODE = "REC_STAT_CODE";
/**
* Realiza a consulta de registros de acordo com um filtro pré-determinado.
* @see com.citibank.ods.persistence.pl.dao.TplProdRiskCatPrvtHistDAO#list(java.math.BigInteger,
* java.lang.String, java.util.Date)
*/
public DataSet list( String plyrCnpjNbr_, String plyrName_, Date plyrRefDate_ )
{
return null;
}
/**
* Insere um registro de historico do player
* @see com.citibank.ods.persistence.pl.dao.TplPlayerHistDAO#insert(com.citibank.ods.entity.pl.TplPlayerHistEntity)
*/
public TplPlayerHistEntity insert( TplPlayerHistEntity tplPlayerHistEntity_ )
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "INSERT INTO " + C_TPL_PLAYER_HIST + " (" );
query.append( C_PLYR_CNPJ_NBR + ", " );
query.append( C_PLYR_REF_DATE + ", " );
query.append( C_PLYR_NAME + ", " );
query.append( C_PLYR_ADDR_TEXT + ", " );
query.append( C_PLYR_DUE_DLG_DATE + ", " );
query.append( C_PLYR_DUE_DLG_EXEC_IND + ", " );
query.append( C_PLYR_DUE_DLG_END_DATE + ", " );
query.append( C_PLYR_DUE_DLG_RNW_DATE + ", " );
query.append( C_PLYR_INVST_CMTTE_APPRV_DATE + ", " );
query.append( C_PLYR_APPRV_RSTRN_TEXT + ", " );
query.append( C_PLYR_SUPL_SERV_TEXT + ", " );
query.append( C_PLYR_CMNT_TEXT + ", " );
query.append( C_REC_STAT_CODE + ", " );
query.append( C_LAST_UPD_USER_ID + ", " );
query.append( C_LAST_UPD_DATE + ", " );
query.append( C_LAST_AUTH_DATE + ", " );
query.append( C_LAST_AUTH_USER_ID );
query.append( ") VALUES ( " );
query.append( "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )" );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( tplPlayerHistEntity_.getData().getPlyrCnpjNbr() != null )
{
preparedStatement.setString( count++,
tplPlayerHistEntity_.getData().getPlyrCnpjNbr() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( ( ( TplPlayerHistEntityVO ) tplPlayerHistEntity_.getData() ).getPlyrRefDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
( ( TplPlayerHistEntityVO ) tplPlayerHistEntity_.getData() ).getPlyrRefDate().getTime() ) );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplPlayerHistEntity_.getData().getPlyrName() != null )
{
preparedStatement.setString( count++,
tplPlayerHistEntity_.getData().getPlyrName() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplPlayerHistEntity_.getData().getPlyrAddrText() != null )
{
preparedStatement.setString( count++,
tplPlayerHistEntity_.getData().getPlyrAddrText() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplPlayerHistEntity_.getData().getPlyrDueDlgDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
tplPlayerHistEntity_.getData().getPlyrDueDlgDate().getTime() ) );
}
else
{
preparedStatement.setTimestamp( count++, null );
}
if ( tplPlayerHistEntity_.getData().getPlyrDueDlgExecInd() != null )
{
preparedStatement.setString(
count++,
tplPlayerHistEntity_.getData().getPlyrDueDlgExecInd() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplPlayerHistEntity_.getData().getPlyrDueDlgEndDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
tplPlayerHistEntity_.getData().getPlyrDueDlgEndDate().getTime() ) );
}
else
{
preparedStatement.setTimestamp( count++, null );
}
if ( tplPlayerHistEntity_.getData().getPlyrDueDlgRnwDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
tplPlayerHistEntity_.getData().getPlyrDueDlgRnwDate().getTime() ) );
}
else
{
preparedStatement.setTimestamp( count++, null );
}
if ( tplPlayerHistEntity_.getData().getPlyrInvstCmtteApprvDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
tplPlayerHistEntity_.getData().getPlyrInvstCmtteApprvDate().getTime() ) );
}
else
{
preparedStatement.setTimestamp( count++, null );
}
if ( tplPlayerHistEntity_.getData().getPlyrApprvRstrnText() != null )
{
preparedStatement.setString(
count++,
tplPlayerHistEntity_.getData().getPlyrApprvRstrnText() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplPlayerHistEntity_.getData().getPlyrSuplServText() != null )
{
preparedStatement.setString(
count++,
tplPlayerHistEntity_.getData().getPlyrSuplServText() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplPlayerHistEntity_.getData().getPlyrCmntText() != null )
{
preparedStatement.setString( count++,
tplPlayerHistEntity_.getData().getPlyrCmntText() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( ( ( TplPlayerHistEntityVO ) tplPlayerHistEntity_.getData() ).getRecStatCode() != null )
{
preparedStatement.setString(
count++,
( ( TplPlayerHistEntityVO ) tplPlayerHistEntity_.getData() ).getRecStatCode() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplPlayerHistEntity_.getData().getLastUpdUserId() != null )
{
preparedStatement.setString( count++,
tplPlayerHistEntity_.getData().getLastUpdUserId() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplPlayerHistEntity_.getData().getLastUpdDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
tplPlayerHistEntity_.getData().getLastUpdDate().getTime() ) );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( ( ( TplPlayerHistEntityVO ) tplPlayerHistEntity_.getData() ).getLastAuthDate() != null )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
( ( TplPlayerHistEntityVO ) tplPlayerHistEntity_.getData() ).getLastAuthDate().getTime() ) );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( ( ( TplPlayerHistEntityVO ) tplPlayerHistEntity_.getData() ).getLastAuthUserId() != null )
{
preparedStatement.setString(
count++,
( ( TplPlayerHistEntityVO ) tplPlayerHistEntity_.getData() ).getLastAuthUserId() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
preparedStatement.executeUpdate();
preparedStatement.replaceParametersInQuery(query.toString());
}
catch ( Exception e )
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return tplPlayerHistEntity_;
}
/**
* Recupera um player conforme a chave determinada
* @see com.citibank.ods.persistence.pl.dao.BaseTplPlayerDAO#find(com.citibank.ods.entity.pl.BaseTplPlayerEntity)
*/
public BaseTplPlayerEntity find( BaseTplPlayerEntity baseTplPlayerEntity_ )
{
return null;
}
} |
package com.bairuitech.anychat;
public class AnyChatDefine {
// 消息通知类型定义
static final int WM_GV = 1224;
static final int WM_GV_CONNECT = WM_GV + 1;
static final int WM_GV_LOGINSYSTEM = WM_GV + 2;
static final int WM_GV_ENTERROOM = WM_GV + 3;
static final int WM_GV_MICSTATECHANGE = WM_GV + 4;
static final int WM_GV_USERATROOM = WM_GV + 5;
static final int WM_GV_LINKCLOSE = WM_GV + 6;
static final int WM_GV_ONLINEUSER = WM_GV + 7;
static final int WM_GV_CAMERASTATE = WM_GV + 11;
static final int WM_GV_CHATMODECHG = WM_GV + 12;
static final int WM_GV_ACTIVESTATE = WM_GV + 13;
static final int WM_GV_P2PCONNECTSTATE = WM_GV + 14;
static final int WM_GV_VIDEOSIZECHG = WM_GV + 15;
static final int WM_GV_USERINFOUPDATE = WM_GV + 16;
static final int WM_GV_FRIENDSTATUS = WM_GV + 17;
static final int WM_GV_PRIVATEREQUEST = WM_GV + 21;
static final int WM_GV_PRIVATEECHO = WM_GV + 22;
static final int WM_GV_PRIVATEEXIT = WM_GV + 23;
static final int WM_GV_AUDIOPLAYCTRL = WM_GV + 100;
static final int WM_GV_AUDIORECCTRL = WM_GV + 101;
static final int WM_GV_VIDEOCAPCTRL = WM_GV + 102;
// 视频图像格式定义
public static final int BRAC_PIX_FMT_RGB24 = 0; ///< Packed RGB 8:8:8, 24bpp, RGBRGB...(MEDIASUBTYPE_RGB24)
public static final int BRAC_PIX_FMT_RGB32 = 1; ///< 对应于:MEDIASUBTYPE_RGB32,Packed RGB 8:8:8, 32bpp, (msb)8A 8R 8G 8B(lsb), in cpu endianness
public static final int BRAC_PIX_FMT_YV12 = 2; ///< 对应于:MEDIASUBTYPE_YV12,Planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
public static final int BRAC_PIX_FMT_YUY2 = 3; ///< 对应于:MEDIASUBTYPE_YUY2,Packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr
public static final int BRAC_PIX_FMT_YUV420P = 4; ///< Planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
public static final int BRAC_PIX_FMT_RGB565 = 5; ///< 对应于:MEDIASUBTYPE_RGB565
public static final int BRAC_PIX_FMT_RGB555 = 6; ///< 对应于:MEDIASUBTYPE_RGB555
public static final int BRAC_PIX_FMT_NV12 = 7; ///< Planar YUV 4:2:0, 12bpp, Two arrays, one is all Y, the other is U and V
public static final int BRAC_PIX_FMT_NV21 = 8; ///< Planar YUV 4:2:0, 12bpp, Two arrays, one is all Y, the other is V and U
public static final int BRAC_PIX_FMT_NV16 = 9; ///< YUV422SP
// 视频采集驱动
public static final int VIDEOCAP_DRIVER_JAVA = 3; ///< Java视频采集驱动
// 视频显示驱动
public static final int VIDEOSHOW_DRIVER_JAVA = 5; ///< Java视频显示驱动
// 音频采集驱动
public static final int AUDIOREC_DRIVER_JAVA = 3; ///< Java音频采集驱动
// 音频播放驱动
public static final int AUDIOPLAY_DRIVER_JAVA = 3; ///< Java音频播放驱动
// 内核参数定义
public static final int BRAC_SO_AUDIO_VADCTRL = 1; ///< 音频静音检测控制(参数为:int型:1打开,0关闭)
public static final int BRAC_SO_AUDIO_NSCTRL = 2; ///< 音频噪音抑制控制(参数为:int型:1打开,0关闭)
public static final int BRAC_SO_AUDIO_ECHOCTRL = 3; ///< 音频回音消除控制(参数为:int型:1打开,0关闭)
public static final int BRAC_SO_AUDIO_AGCCTRL = 4; ///< 音频自动增益控制(参数为:int型:1打开,0关闭)
public static final int BRAC_SO_AUDIO_CPATUREMODE = 5; ///< 音频采集模式设置(参数为:int型:0 发言模式,1 放歌模式,2 卡拉OK模式,3 线路输入模式)
public static final int BRAC_SO_AUDIO_MICBOOST = 6; ///< 音频采集Mic增强控制(参数为:int型:0 取消,1 选中,2 设备不存在[查询时返回值])
public static final int BRAC_SO_AUDIO_AUTOPARAM = 7; ///< 根据音频采集模式,自动选择合适的相关参数,包括编码器、采样参数、码率参数等(参数为int型:1 启用,0 关闭[默认])
public static final int BRAC_SO_AUDIO_MONOBITRATE = 8; ///< 设置单声道模式下音频编码目标码率(参数为:int型,单位:bps)
public static final int BRAC_SO_AUDIO_STEREOBITRATE = 9; ///< 设置双声道模式下音频编码目标码率(参数为:int型,单位:bps)
public static final int BRAC_SO_AUDIO_PLAYDRVCTRL = 70; ///< 音频播放驱动选择(参数为:int型,0默认驱动, 1 DSound驱动, 2 WaveOut驱动, 3 Java播放[Android平台使用])
public static final int BRAC_SO_AUDIO_SOFTVOLMODE = 73; ///< 设置软件音量模式控制(参数为int型,1打开,0关闭[默认]),使用软件音量模式,将不会改变系统的音量设置
public static final int BRAC_SO_AUDIO_RECORDDRVCTRL = 74; ///< 音频采集驱动控制(参数为int型,0默认驱动, 1 DSound驱动, 2 WaveIn驱动, 3 Java采集[Android平台使用])
public static final int BRAC_SO_AUDIO_ECHODELAY = 75; ///< 音频回声消除延迟参数设置(参数为int型,单位:ms)
public static final int BRAC_SO_AUDIO_NSLEVEL = 76; ///< 音频噪音抑制水平参数设置(参数为int型,0 - 3,默认为2,值越大抑制水平越高,抑制噪音的能力越强)
public static final int BRAC_SO_RECORD_VIDEOBR = 10; ///< 录像视频码率设置(参数为:int型,单位:bps)
public static final int BRAC_SO_RECORD_AUDIOBR = 11; ///< 录像音频码率设置(参数为:int型,单位:bps)
public static final int BRAC_SO_RECORD_TMPDIR = 12; ///< 录像文件临时目录设置(参数为字符串TCHAR类型,必须是完整的绝对路径)
public static final int BRAC_SO_SNAPSHOT_TMPDIR = 13; ///< 快照文件临时目录设置(参数为字符串TCHAR类型,必须是完整的绝对路径)
public static final int BRAC_SO_RECORD_FILETYPE = 140;///< 录制文件类型设置(参数为:int型, 0 MP4[默认], 1 WMV, 2 FLV, 3 MP3)
public static final int BRAC_SO_RECORD_WIDTH = 141;///< 录制视频宽度设置(参数为:int型,如:320)
public static final int BRAC_SO_RECORD_HEIGHT = 142;///< 录制文件高度设置(参数为:int型,如:240)
public static final int BRAC_SO_RECORD_FILENAMERULE = 143;///< 录制文件名命名规则(参数为:int型)
public static final int BRAC_SO_RECORD_CLIPMODE = 144;///< 录制视频裁剪模式(参数为:int型)
public static final int BRAC_SO_RECORD_DISABLEDATEDIR = 145;///< 录制文件不按日期分目录保存,全部生成在指定文件夹中(参数为:int型, 0禁止[默认] 1 开启)
public static final int BRAC_SO_RECORD_INSERTIMAGE = 146;///< 录制过程中插入图片,Json字符串参数
public static final int BRAC_SO_CORESDK_TMPDIR = 14; ///< 设置AnyChat Core SDK临时目录(参数为字符串TCHAR类型,必须是完整的绝对路径)
public static final int BRAC_SO_CORESDK_LOADCODEC = 16; ///< 加载外部编解码器(参数为字符串TCHAR类型,必须是完整的绝对路径,包含文件名,或包含文件名的绝对路径)
public static final int BRAC_SO_CORESDK_USEARMV6LIB = 17; ///< 强制使用ARMv6指令集的库,android平台使用(参数为:int型,1使用ARMv6指令集, 0内核自动判断[默认])
public static final int BRAC_SO_CORESDK_USEHWCODEC = 18; ///< 使用平台内置硬件编解码器(参数为int型,0 不使用硬件编解码器[默认] 1 使用内置硬件编解码器)
public static final int BRAC_SO_CORESDK_PATH = 20; ///< 设置AnyChat Core SDK相关组件路径(参数为字符串TCHAR类型,必须是完整的绝对路径)
public static final int BRAC_SO_CORESDK_DUMPCOREINFO = 21; ///< 输出内核信息到日志文件中,便于分析故障原因(参数为:int型:1 输出)
public static final int BRAC_SO_CORESDK_MAINVERSION = 22; ///< 查询SDK主版本号号(参数为int型)
public static final int BRAC_SO_CORESDK_SUBVERSION = 23; ///< 查询SDK从版本号(参数为int型)
public static final int BRAC_SO_CORESDK_BUILDTIME = 24; ///< 查询SDK编译时间(参数为字符串TCHAR类型)
public static final int BRAC_SO_CORESDK_EXTVIDEOINPUT = 26; ///< 外部扩展视频输入控制(参数为int型, 0 关闭外部视频输入[默认], 1 启用外部视频输入)
public static final int BRAC_SO_CORESDK_EXTAUDIOINPUT = 27; ///< 外部扩展音频输入控制(参数为int型, 0 关闭外部音频输入[默认], 1 启用外部音频输入)
public static final int BRAC_SO_CORESDK_LOWDELAYCTRL = 28; ///< 低延迟模式控制(参数为int型,0 关闭低延迟模式[默认], 1 启用低延迟模式)
public static final int BRAC_SO_CORESDK_NEWGUID = 29; ///< 产生新的GUID字符串
public static final int BRAC_SO_LOCALVIDEO_BITRATECTRL = 30; ///< 本地视频编码码率设置(参数为int型,单位bps,同服务器配置:VideoBitrate)
public static final int BRAC_SO_LOCALVIDEO_QUALITYCTRL = 31; ///< 本地视频编码质量因子控制(参数为int型,同服务器配置:VideoQuality)
public static final int BRAC_SO_LOCALVIDEO_GOPCTRL = 32; ///< 本地视频编码关键帧间隔控制(参数为int型,同服务器配置:VideoGOPSize)
public static final int BRAC_SO_LOCALVIDEO_FPSCTRL = 33; ///< 本地视频编码帧率控制(参数为int型,同服务器配置:VideoFps)
public static final int BRAC_SO_LOCALVIDEO_PRESETCTRL = 34; ///< 本地视频编码预设参数控制(参数为int型,1-5)
public static final int BRAC_SO_LOCALVIDEO_APPLYPARAM = 35; ///< 应用本地视频编码参数,使得前述修改即时生效(参数为int型:1 使用新参数,0 使用默认参数)
public static final int BRAC_SO_LOCALVIDEO_VIDEOSIZEPOLITIC=36; ///< 本地视频采集分辩率控制策略(参数为int型,0 自动向下逐级匹配[默认];1 使用采集设备默认分辩率),当配置的分辩率不被采集设备支持时有效
public static final int BRAC_SO_LOCALVIDEO_DEINTERLACE = 37; ///< 本地视频反交织参数控制(参数为int型: 0 不进行反交织处理[默认];1 反交织处理),当输入视频源是隔行扫描源(如电视信号)时通过反交织处理可以提高画面质量
public static final int BRAC_SO_LOCALVIDEO_WIDTHCTRL = 38; ///< 本地视频采集分辨率宽度控制(参数为int型,同服务器配置:VideoWidth)
public static final int BRAC_SO_LOCALVIDEO_HEIGHTCTRL = 39; ///< 本地视频采集分辨率高度控制(参数为int型,同服务器配置:VideoHeight)
public static final int BRAC_SO_LOCALVIDEO_FOCUSCTRL = 90; ///< 本地视频摄像头对焦控制(参数为int型,1表示自动对焦, 0表示手动对焦)
public static final int BRAC_SO_LOCALVIDEO_PIXFMTCTRL = 91; ///< 本地视频采集优先格式控制(参数为int型,-1表示智能匹配,否则优先采用指定格式,参考:BRAC_PixelFormat)
public static final int BRAC_SO_LOCALVIDEO_OVERLAY = 92; ///< 本地视频采用Overlay模式(参数为int型,1表示采用Overlay模式, 0表示普通模式[默认])
public static final int BRAC_SO_LOCALVIDEO_CODECID = 93; ///< 本地视频编码器ID设置(参数为int型,-1表示默认,如果设置的编码器ID不存在,则内核会采用默认的编码器)
public static final int BRAC_SO_LOCALVIDEO_ROTATECTRL = 94; ///< 本地视频旋转控制(参数为int型,0表示不进行旋转,1表示垂直翻转)
public static final int BRAC_SO_LOCALVIDEO_CAPDRIVER = 95; ///< 本地视频采集驱动设置(参数为int型,0表示自动选择[默认], 1 Video4Linux, 2 DirectShow, 3 Java采集[Android平台使用])
public static final int BRAC_SO_LOCALVIDEO_FIXCOLORDEVIA= 96; ///< 修正视频采集颜色偏色(参数为int型,0表示关闭[默认],1 开启)
public static final int BRAC_SO_LOCALVIDEO_ORIENTATION = 97; ///< 本地视频设备方向(参数为:int型,定义为常量:ANYCHAT_DEVICEORIENTATION_XXXX)
public static final int BRAC_SO_LOCALVIDEO_AUTOROTATION = 98; ///< 本地视频自动旋转控制(参数为int型, 0表示关闭, 1 开启[默认],视频旋转时需要参考本地视频设备方向参数)
public static final int BRAC_SO_LOCALVIDEO_SURFACEROTATION= 99; ///< 设置本地视频预览显示旋转角度(参数为int型,角度)
public static final int BRAC_SO_LOCALVIDEO_CAMERAFACE = 100;///< 本地摄像头方向(前置、后置)
public static final int BRAC_SO_LOCALVIDEO_DEVICEMODE = 103;///< 设备类型
public static final int BRAC_SO_LOCALVIDEO_OVERLAYTIMESTAMP=105;///< 迭加时间戳到本地视频(参数为:int型, 0 不迭加[默认], 1 迭加)
public static final int BRAC_SO_LOCALVIDEO_DEVICENAME = 106;///< 本地视频采集设备名称,用于设置打开指定摄像头设备(参数为字符串类型)
public static final int BRAC_SO_LOCALVIDEO_CLIPMODE = 107;///< 本地视频裁剪模式(参数为int型, 0 自动[默认],禁止自动旋转时有效)
public static final int BRAC_SO_LOCALVIDEO_SCREENHWND = 108;///< 屏幕采集窗口句柄
public static final int BRAC_SO_LOCALVIDEO_SCREENFLAGS = 109;///< 屏幕采集标志(参数为int型)
public static final int BRAC_SO_LOCALVIDEO_VIRTUALBK = 111;///< 本地视频迭加虚拟背景(字符串类型,JSON格式,包括虚拟背景路径、是否开启以及其它参数项)
public static final int BRAC_SO_NETWORK_P2PPOLITIC = 40; ///< 本地网络P2P策略控制(参数为:int型:0 禁止本地P2P,1 服务器控制P2P[默认],2 上层应用控制P2P连接,3 按需建立P2P连接)
public static final int BRAC_SO_NETWORK_P2PCONNECT = 41; ///< 尝试与指定用户建立P2P连接(参数为int型,表示目标用户ID),连接建立成功后,会通过消息反馈给上层应用,P2P控制策略=2时有效
public static final int BRAC_SO_NETWORK_P2PBREAK = 42; ///< 断开与指定用户的P2P连接(参数为int型,表示目标用户ID)[暂不支持,保留]
public static final int BRAC_SO_NETWORK_TCPSERVICEPORT = 43; ///< 设置本地TCP服务端口(参数为int型),连接服务器之前设置有效
public static final int BRAC_SO_NETWORK_UDPSERVICEPORT = 44; ///< 设置本地UDP服务端口(参数为int型),连接服务器之前设置有效
public static final int BRAC_SO_NETWORK_MULTICASTPOLITIC= 45; ///< 组播策略控制(参数为int型:0 执行服务器路由策略,禁止组播发送[默认], 1 忽略服务器路由策略,只向组播组广播媒体流, 2 执行服务器路由策略,同时组播)
public static final int BRAC_SO_NETWORK_TRANSBUFMAXBITRATE= 46; ///< 传输缓冲区、文件最大码率控制(参数为int型,0 不限制,以最快速率传输[默认], 否则表示限制码率,单位为:bps)
public static final int BRAC_SO_NETWORK_AUTORECONNECT = 47; ///< 网络掉线自动重连功能控制(参数为int型,0 关闭, 1 开启[默认])
public static final int BRAC_SO_NETWORK_MTUSIZE = 48; ///< 设置网络层MTU大小(参数为int型)
public static final int BRAC_SO_NETWORK_UDPSTATUS = 49; ///< UDP网络通信状态查询(参数为int型)
public static final int BRAC_SO_NETWORK_LARGEDELAY = 53; ///< 网络高延迟模式,适用于卫星网络环境(参数为int型)
public static final int BRAC_SO_NETWORK_IPV6DNS = 54; ///< IPv6域名解析控制(参数为int型,0 关闭, 1开启[默认]),传统网络(IPv4)下,禁用IPv6可提高域名解析速度
public static final int BRAC_SO_PROXY_FUNCTIONCTRL = 50; ///< 本地用户代理功能控制,(参数为:int型,1启动代理,0关闭代理[默认])
public static final int BRAC_SO_PROXY_VIDEOCTRL = 51; ///< 本地用户代理视频控制,将本地视频变为指定用户的视频对外发布(参数为int型,表示其它用户的userid)
public static final int BRAC_SO_PROXY_AUDIOCTRL = 52; ///< 本地用户代理音频控制,将本地音频变为指定用户的音频对外发布(参数同BRAC_SO_PROXY_VIDEOCTRL)
public static final int BRAC_SO_STREAM_BUFFERTIME = 60; ///< 流缓冲时间(参数为int型,单位:毫秒,取值范围:500 ~ 5000,默认:800)
public static final int BRAC_SO_STREAM_SMOOTHPLAYMODE = 61; ///< 平滑播放模式(参数为int型,0 关闭[默认], 1 打开),打开状态下遇到视频丢帧时会继续播放(可能出现马赛克),不会卡住
public static final int BRAC_SO_VIDEOSHOW_MODECTRL = 80; ///< 视频显示模式控制(参数为:int型,0 单画面显示,1 视频迭加显示)
public static final int BRAC_SO_VIDEOSHOW_SETPRIMARYUSER= 81; ///< 设置主显示用户编号(参数为:int型,用户ID号)
public static final int BRAC_SO_VIDEOSHOW_SETOVERLAYUSER= 82; ///< 设置迭加显示用户编号(参数为:int型,用户ID号)
public static final int BRAC_SO_VIDEOSHOW_DRIVERCTRL = 83; ///< 视频显示驱动控制(参数为:int型,0 默认驱动, 1 Windows DirectShow,2 Windows GDI,3 SDL, 4 Android2X, 5 Android Java)
public static final int BRAC_SO_VIDEOSHOW_GPUDIRECTRENDER = 84; ///< 视频数据经过GPU直接渲染,将解码后的视频数据直接传输到GPU的物理地址(参数为:int型, 0 关闭[默认], 1 打开),与硬件平台相关
public static final int BRAC_SO_VIDEOSHOW_AUTOROTATION = 85; ///< 远程视频显示自动旋转控制(参数为int型, 0表示关闭, 1 开启[默认],视频旋转时需要参考本地视频设备方向参数)
public static final int BRAC_SO_VIDEOSHOW_CLIPMODE = 86; ///< 远程视频显示旋转裁剪模式(参数为int型, 0 自动[默认])
public static final int BRAC_SO_CORESDK_DEVICEMODE = 130; ///< 设备模式控制(局域网设备之间可以互相通信,不依赖服务器;参数为int型,0 关闭[默认],1 开启)
public static final int BRAC_SO_CORESDK_SCREENCAMERACTRL= 131; ///< 桌面共享功能控制(参数为:int型, 0 关闭[默认], 1 开启)
public static final int BRAC_SO_CORESDK_DATAENCRYPTION = 132; ///< 数据加密控制(参数为:int型, 0 关闭[默认], 1 开启)
public static final int BRAC_SO_CORESDK_UPLOADLOGINFO = 134; ///< 上传日志信息到服务器(参数为:int型,0 关闭[默认], 1 开启)
public static final int BRAC_SO_CORESDK_WRITELOG = 135; ///< 写入调试信息到客户端日志文件中
public static final int BRAC_SO_CORESDK_NEWLOGFILE = 136; ///< 产生新的日志文件
public static final int BRAC_SO_CORESDK_SUPPORTVIDEOCODEC = 210; ///< 设置支持的视频编码器
public static final int BRAC_SO_CORESDK_SUPPORTAUDIOCODEC = 211; ///< 设置支持的音频编码器
public static final int BRAC_SO_CORESDK_DISABLEMEDIACONSUL= 212; ///< 禁止媒体协商
public static final int BRAC_SO_CORESDK_QUERYTIMEOUTTIME= 213; ///< 信息查询超时时间(参数为:int型,单位:ms,默认值1000)
public static final int BRAC_SO_CORESDK_REMOTEASSISTHWND= 214; ///< 远程协助窗口句柄
public static final int BRAC_SO_CORESDK_REMOTEASSISTXPOS= 215; ///< 远程协助窗口滚动条位置(X)
public static final int BRAC_SO_CORESDK_REMOTEASSISTYPOS= 216; ///< 远程协助窗口滚动条位置(Y)
public static final int BRAC_SO_CORESDK_FITTENCENTLIVE = 217; ///< 兼容腾讯视频直播SDK
public static final int BRAC_SO_CORESDK_DFCFLIVE = 218;
public static final int BRAC_SO_CORESDK_DISABLEDNSCONNECT = 219; ///< 屏蔽DNS寻址
public static final int BRAC_SO_CORESDK_LOGFILEROOTPATH = 220; ///< 日志文件保存根路径(日志重定向,参数为字符串,绝对路径)
public static final int BRAC_SO_CORESDK_LOGFILERULE = 221; ///< 客户端日志文件保存规则(参数为int型,0 自动覆盖[默认] 1 按日期保存,不覆盖)
public static final int BRAC_SO_UDPTRACE_MODE = 160; ///< UDP数据包跟踪模式
public static final int BRAC_SO_UDPTRACE_PACKSIZE = 161; ///< UDP数据包跟踪的大小,单位:BYTE
public static final int BRAC_SO_UDPTRACE_BITRATE = 162; ///< UDP数据包跟踪的包速率,单位:bps
public static final int BRAC_SO_UDPTRACE_START = 163; ///< UDP数据包跟踪控制(参数为int型,1 启动, 0 停止)
public static final int BRAC_SO_UDPTRACE_LOCALRECVNUM = 164; ///< UDP数据包跟踪本地接收包数量
public static final int BRAC_SO_UDPTRACE_SERVERRECVNUM = 165; ///< UDP数据包跟踪服务器接收包数量
public static final int BRAC_SO_UDPTRACE_SOURCESENDNUM = 166; ///< UDP数据包跟踪源发包数量
public static final int BRAC_SO_UDPTRACE_SENDUSERID = 167; ///< UDP数据包跟踪源用户ID
public static final int BRAC_SO_OBJECT_INITFLAGS = 200; ///< 业务对象身份初始化
public static final int BRAC_SO_CLOUD_APPGUID = 300; ///< 云平台应用GUID(参数为:字符串类型,连接服务器之前设置)
// 传输任务信息参数定义
public static final int BRAC_TRANSTASK_PROGRESS = 1; ///< 传输任务进度查询(参数为:int型(0 ~ 100))
public static final int BRAC_TRANSTASK_BITRATE = 2; ///< 传输任务当前传输码率(参数为:int型,单位:bps)
public static final int BRAC_TRANSTASK_STATUS = 3; ///< 传输任务当前状态(参数为:int型)
// 录像功能标志定义(API:StreamRecordCtrl传入参数,目前Android平台暂时只支持服务器端录制)
public static final int BRAC_RECORD_FLAGS_VIDEO = 0x00000001; ///< 录制视频
public static final int BRAC_RECORD_FLAGS_AUDIO = 0x00000002; ///< 录制音频
public static final int BRAC_RECORD_FLAGS_SERVER = 0x00000004; ///< 服务器端录制
public static final int BRAC_RECORD_FLAGS_MIXAUDIO = 0x00000010; ///< 录制音频时,将其它人的声音混音后录制
public static final int BRAC_RECORD_FLAGS_MIXVIDEO = 0x00000020; ///< 录制视频时,将其它人的视频迭加后录制(画中画模式)
public static final int BRAC_RECORD_FLAGS_ABREAST = 0x00000100; ///< 录制视频时,将其它人的视频并列录制
public static final int BRAC_RECORD_FLAGS_STEREO = 0x00000200; ///< 录制音频时,将其它人的声音混合为立体声后录制
public static final int BRAC_RECORD_FLAGS_STREAM = 0x00001000; ///< 对视频流进行录制(效率高,但可能存在视频方向旋转的问题)
public static final int BRAC_RECORD_FLAGS_USERFILENAME = 0x00002000; ///< 用户自定义文件名
// 用户状态标志定义(API:BRAC_QueryUserState 传入参数)
public static final int BRAC_USERSTATE_CAMERA = 1; ///< 用户摄像头状态(参数为DWORD型)
public static final int BRAC_USERSTATE_HOLDMIC = 2; ///< 用户音频设备状态(参数为DWORD型,返回值:0 音频采集关闭, 1 音频采集开启)
public static final int BRAC_USERSTATE_SPEAKVOLUME = 3; ///< 用户当前说话音量(参数为DOUBLE类型(0.0 ~ 100.0))
public static final int BRAC_USERSTATE_RECORDING = 4; ///< 用户录像(音)状态(参数为DWORD型)
public static final int BRAC_USERSTATE_LEVEL = 5; ///< 用户级别(参数为DWORD型)
public static final int BRAC_USERSTATE_NICKNAME = 6; ///< 用户昵称(参数为字符串TCHAR类型)
public static final int BRAC_USERSTATE_LOCALIP = 7; ///< 用户本地IP地址(内网,参数为字符串TCHAR类型)
public static final int BRAC_USERSTATE_INTERNETIP = 8; ///< 用户互联网IP地址(参数为字符串TCHAR类型)
public static final int BRAC_USERSTATE_VIDEOBITRATE = 9; ///< 用户当前的视频码率(参数为DWORD类型,Bps)
public static final int BRAC_USERSTATE_AUDIOBITRATE = 10; ///< 用户当前的音频码率(参数为DWORD类型,Bps)
public static final int BRAC_USERSTATE_P2PCONNECT = 11; ///< 查询本地用户与指定用户的当前P2P连接状态(参数为DWORD类型,返回值:0 P2P不通, 1 P2P连接成功[TCP],2 P2P连接成功[UDP],3 P2P连接成功[TCP、UDP])
public static final int BRAC_USERSTATE_NETWORKSTATUS = 12; ///< 查询指定用户的网络状态(参数为DWORD类型,返回值:0 优良,1 较好,2 一般,3 较差,4 非常差),注:查询间隔需要>1s
public static final int BRAC_USERSTATE_VIDEOSIZE = 13; ///< 查询指定用户的视频分辨率(参数为DWORD类型,返回值:低16位表示宽度,高16位表示高度)
public static final int BRAC_USERSTATE_PACKLOSSRATE = 14; ///< 查询指定用户的网络流媒体数据丢包率(参数为DWORD类型,返回值:0 - 100,如:返回值为5,表示丢包率为5%)
public static final int BRAC_USERSTATE_DEVICETYPE = 15; ///< 查询指定用户的终端类型(参数为DWORD类型,返回值:0 Unknow, 1 Windows,2 Android,3 iOS,4 Web,5 Linux,6 Mac,7 Win Phone,8 WinCE)
public static final int BRAC_USERSTATE_SELFUSERSTATUS = 16; ///< 查询本地用户的当前状态(参数为DWORD类型,返回值:0 Unknow,1 Connected,2 Logined,3 In Room,4 Logouted,5 Link Closed)
public static final int BRAC_USERSTATE_SELFUSERID = 17; ///< 查询本地用户的ID(参数为DWORD类型,若用户登录成功,返回用户实际的userid,否则返回-1)
public static final int BRAC_USERSTATE_VIDEOROTATION = 18; ///< 查询指定用户的当前视频旋转角度(参数为DWORD类型,返回角度值)
public static final int BRAC_USERSTATE_VIDEOMIRRORED = 19; ///< 查询指定用户的视频是否需要镜像翻转
// 房间状态标志定义(API:BRAC_QueryRoomState 传入参数)
public static final int BRAC_ROOMSTATE_ROOMNAME = 1; ///< 房间名称(参数为字符串TCHAR类型)
public static final int BRAC_ROOMSTATE_ONLINEUSERS = 2; ///< 房间在线用户数(参数为DWORD型,不包含自己)
// 视频呼叫事件类型定义(API:BRAC_VideoCallControl 传入参数、VideoCallEvent回调参数)
public static final int BRAC_VIDEOCALL_EVENT_REQUEST = 1; ///< 呼叫请求
public static final int BRAC_VIDEOCALL_EVENT_REPLY = 2; ///< 呼叫请求回复
public static final int BRAC_VIDEOCALL_EVENT_START = 3; ///< 视频呼叫会话开始事件
public static final int BRAC_VIDEOCALL_EVENT_FINISH = 4; ///< 挂断(结束)呼叫会话
// 视频呼叫标志定义(API:BRAC_VideoCallControl 传入参数)
public static final int BRAC_VIDEOCALL_FLAGS_AUDIO = 0x01; ///< 语音通话
public static final int BRAC_VIDEOCALL_FLAGS_VIDEO = 0x02; ///< 视频通话
public static final int BRAC_VIDEOCALL_FLAGS_FBSRCAUDIO = 0x10; ///< 禁止源(呼叫端)音频
public static final int BRAC_VIDEOCALL_FLAGS_FBSRCVIDEO = 0x20; ///< 禁止源(呼叫端)视频
public static final int BRAC_VIDEOCALL_FLAGS_FBTARAUDIO = 0x40; ///< 禁止目标(被呼叫端)音频
public static final int BRAC_VIDEOCALL_FLAGS_FBTARVIDEO = 0x80; ///< 禁止目标(被呼叫端)视频
// 视频方向修正标志定义
public static final int BRAC_ROTATION_FLAGS_MIRRORED = 0x1000;///< 图像需要镜像翻转
public static final int BRAC_ROTATION_FLAGS_ROTATION90 = 0x2000;///< 顺时针旋转90度
public static final int BRAC_ROTATION_FLAGS_ROTATION180 = 0x4000;///< 顺时针旋转180度
public static final int BRAC_ROTATION_FLAGS_ROTATION270 = 0x8000;///< 顺时针旋转270度
// 用户信息控制类型定义(API:BRAC_UserInfoControl 传入参数)
public static final int BRAC_USERINFO_CTRLCODE_ROTATION = 8; ///< 让指定的用户视频在显示时旋转,wParam为旋转角度参数
public static final int BRAC_USERINFO_CTRLCODE_DEBUGLOG = 9; ///< 输出本地用户的调试日志,wParam为调试日志类型
public static final int BRAC_USERINFO_CTRLCODE_LVORIENTFIX= 10; ///< 本地视频采集方向修正,wParam为方向参数,lParam为修正角度
// 服务器信息查询常量定义(API:BRAC_QueryInfoFromServer 传入参数)
public static final int ANYCHAT_SERVERQUERY_USERIDBYNAME = 1; ///< 根据用户昵称查询用户ID
public static final int ANYCHAT_SERVERQUERY_USERIDBYSTRID= 2; ///< 根据字符串ID查询用户ID
public static final int ANYCHAT_SERVERQUERY_STRIDBYUSERID= 3; ///< 根据用户ID查询字符串ID
// 常见出错代码定义
public static final int BRAC_ERRORCODE_SUCCESS = 0; ///< 没有错误
public static final int BRAC_ERRORCODE_SESSION_QUIT = 100101;///< 源用户主动放弃会话
public static final int BRAC_ERRORCODE_SESSION_OFFLINE = 100102;///< 目标用户不在线
public static final int BRAC_ERRORCODE_SESSION_BUSY = 100103;///< 目标用户忙
public static final int BRAC_ERRORCODE_SESSION_REFUSE = 100104;///< 目标用户拒绝会话
public static final int BRAC_ERRORCODE_SESSION_TIMEOUT = 100105;///< 会话请求超时
public static final int BRAC_ERRORCODE_SESSION_DISCONNECT=100106;///< 网络断线
// 录像功能标志定义(API:BRAC_StreamRecordCtrl 传入参数)
public static final int ANYCHAT_RECORD_FLAGS_VIDEO = 0x00000001; ///< 录制视频
public static final int ANYCHAT_RECORD_FLAGS_AUDIO = 0x00000002; ///< 录制音频
public static final int ANYCHAT_RECORD_FLAGS_SERVER = 0x00000004; ///< 服务器端录制
public static final int ANYCHAT_RECORD_FLAGS_MIXAUDIO = 0x00000010; ///< 录制音频时,将其它人的声音混音后录制
public static final int ANYCHAT_RECORD_FLAGS_MIXVIDEO = 0x00000020; ///< 录制视频时,将其它人的视频迭加后录制
public static final int ANYCHAT_RECORD_FLAGS_ABREAST = 0x00000100; ///< 录制视频时,将其它人的视频并列录制
public static final int ANYCHAT_RECORD_FLAGS_STEREO = 0x00000200; ///< 录制音频时,将其它人的声音混合为立体声后录制
public static final int ANYCHAT_RECORD_FLAGS_SNAPSHOT = 0x00000400; ///< 拍照
public static final int ANYCHAT_RECORD_FLAGS_LOCALCB = 0x00000800; ///< 触发本地回调
public static final int ANYCHAT_RECORD_FLAGS_STREAM = 0x00001000; ///< 对视频流进行录制(效率高,但可能存在视频方向旋转的问题)
public static final int ANYCHAT_RECORD_FLAGS_USERFILENAME=0x00002000; ///< 用户自定义文件名
public static final int ANYCHAT_RECORD_FLAGS_ERRORCODE = 0x00004000; ///< 支持出错代码
public static final int ANYCHAT_RECORD_FLAGS_MULTISTREAM= 0x00008000; ///< 支持多路流的录制(拍照)
// 媒体播放事件类型定义
public static final int ANYCHAT_STREAMPLAY_EVENT_START = 3; ///< 播放开始事件
public static final int ANYCHAT_STREAMPLAY_EVENT_FINISH = 4; ///< 播放结束事件
// 媒体播放标志定义(API:BRAC_StreamPlayInit 传入参数)
public static final int ANYCHAT_STREAMPLAY_FLAGS_REPLACEAUDIOINPUT= 0x00000001; ///< 播放音频流代替本地音频输入(Mic)
public static final int ANYCHAT_STREAMPLAY_FLAGS_REPLACEVIDEOINPUT= 0x00000002; ///< 播放视频流代替本地视频输入(Camera)
public static final int ANYCHAT_STREAMPLAY_FLAGS_CALLBACKDATA = 0x00000010; ///< 回调数据给上层
// 媒体播放信息类型定义(API:BRAC_StreamPlayGetInfo 传入参数)
public static final int ANYCHAT_STREAMPLAY_INFO_JSONVALUE= 1; ///< 包含所有播放信息的Json字符串
// 媒体播放控制类型定义(API:BRAC_StreamPlayControl 传入参数)
public static final int ANYCHAT_STREAMPLAY_CTRL_START = 1; ///< 开始播放
public static final int ANYCHAT_STREAMPLAY_CTRL_PAUSE = 2; ///< 暂停播放
public static final int ANYCHAT_STREAMPLAY_CTRL_STOP = 3; ///< 停止播放
public static final int ANYCHAT_STREAMPLAY_CTRL_SEEK = 4; ///< 位置拖动
public static final int ANYCHAT_STREAMPLAY_CTRL_SPEEDCTRL= 5; ///< 速度调整
public static final int ANYCHAT_STREAMPLAY_CTRL_OPENLOOP= 6; ///< 打开循环播放
public static final int ANYCHAT_STREAMPLAY_CTRL_CLOSELOOP= 7; ///< 关闭循环播放
// CoreSDK事件类型定义(回调函数:BRAC_CoreSDKEvent_CallBack参数)
public static final int ANYCHAT_CORESDKEVENT_STREAMPLAY = 30; ///< 媒体播放事件
// CoreSDK回调数据类型定义(回调函数:BRAC_CoreSDKData_CallBack参数)
public static final int ANYCHAT_CORESDKDATA_AUDIO = 1; ///< 音频数据
public static final int ANYCHAT_CORESDKDATA_VIDEO = 2; ///< 视频数据
public static final int ANYCHAT_CORESDKDATA_MESSAGE = 3; ///< 文字数据
public static final int ANYCHAT_CORESDKDATA_BUFFER = 4; ///< 缓冲区数据
} |
package com.soldevelo.vmi.ex;
public class PacketParseException extends Exception {
public PacketParseException(String message) {
super(message);
}
public PacketParseException(Exception cause) {
super(cause);
}
public PacketParseException(String message, Exception cause) {
super(message, cause);
}
}
|
package com.example.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@SpringApplicationConfiguration(RedisBootApplication.class)
public class RedisBootApplicationTests {
// @Autowired
// private StringRedisTemplate stringRedisTemplate;
//
// @Test
// public void test() throws Exception {
// // 保存字符串
// stringRedisTemplate.opsForValue().set("bbb", "111");
// System.out.println(stringRedisTemplate.opsForValue().get("aaa"));
// Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
// }
@Test
public void contextLoads() {
}
}
|
package de.amr.games.pacman.model.world;
import java.util.Objects;
import de.amr.games.pacman.lib.V2i;
/**
* A portal is a tunnel end that is connected to the tunnel end on the opposite
* side of the world.
*
* @author Armin Reichert
*/
public class Portal {
public final V2i left; // x == -1
public final V2i right; // x == world.numCols()
public Portal(V2i left, V2i right) {
this.left = left;
this.right = right;
}
@Override
public int hashCode() {
return Objects.hash(left, right);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Portal other = (Portal) obj;
return Objects.equals(left, other.left) && Objects.equals(right, other.right);
}
} |
package com.hfjy.framework.net.socket;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import com.google.gson.JsonObject;
import com.hfjy.framework.common.util.JsonUtil;
import com.hfjy.framework.logging.LoggerFactory;
import com.hfjy.framework.net.http.entity.ControllerMapping;
import com.hfjy.framework.net.transport.ResponseBody;
import com.hfjy.framework.net.util.ControllerUril;
public class BaseSocketHandler {
private final static Logger logger = LoggerFactory.getLogger(BaseSocketHandler.class);
private final Map<String, SocketSession> serverSockets = new ConcurrentHashMap<>();
private final Map<String, ControllerMapping> controllers = new HashMap<String, ControllerMapping>();
private final List<DestructionFilter> destructionFilterList = new ArrayList<>();
protected void initControllers(String[] paths) {
ControllerUril.initControllers(controllers, paths);
}
protected <T extends DestructionFilter> void addDestructionFilter(Class<T> destructionFilter) throws InstantiationException, IllegalAccessException {
destructionFilterList.add((DestructionFilter) destructionFilter.newInstance());
}
protected Map<String, SocketSession> getServerSockets() {
return serverSockets;
}
protected void putSocketSession(String remote, SocketSession socketSession) {
if (!serverSockets.containsValue(socketSession)) {
serverSockets.put(remote, socketSession);
}
}
protected void removeSocketSession(String remote) {
for (int i = 0; i < destructionFilterList.size(); i++) {
try {
destructionFilterList.get(i).onClose(remote);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
serverSockets.remove(remote);
}
protected Object handleController(SocketSession socketSession, DataMessage data) {
try {
String name = data.getType();
String type = data.getCode();
ControllerMapping cm = controllers.get(name);
if (cm != null && type != null) {
Object execObject = cm.getObject();
Method method = cm.getControllerMethod(type);
if (method != null) {
Class<?>[] classInfos = cm.getMethodParameters(method);
Object[] objects = classInfos == null ? null : new Object[classInfos.length];
if (classInfos != null && classInfos.length > 0) {
for (int i = 0; i < classInfos.length; i++) {
if (classInfos[i] == JsonObject.class) {
if (data.getData() instanceof JsonObject) {
objects[i] = data.getData();
} else {
objects[i] = data.getData() == null ? null : JsonUtil.toJsonObject(data.getData());
}
} else if (classInfos[i] == String.class) {
objects[i] = data.getData() == null ? null : data.getData().toString();
} else if (classInfos[i] == SocketSession.class) {
objects[i] = socketSession;
} else {
objects[i] = data.getData() == null ? null : JsonUtil.toObject(JsonUtil.toJsonElement(data.getData()), classInfos[i]);
}
}
}
long begin = System.currentTimeMillis();
logger.debug(cm.getClassInfo().getName() + " the " + method.getName() + " method begin ");
Object reObject = null;
if (objects == null) {
reObject = method.invoke(execObject);
} else {
reObject = method.invoke(execObject, objects);
}
logger.debug(cm.getClassInfo().getName() + " the " + method.getName() + " method end " + " with time " + (System.currentTimeMillis() - begin) + " ms");
return reObject;
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return ResponseBody.createBody(0, e.getMessage());
}
return ResponseBody.createBody(0, "the controller you requested could not be found");
}
} |
package servlet;
import bbdd.Sala;
import bbdd.Sesion;
import bbdd.Proxy;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author jesus
*/
public class sesionPelicula extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String id = request.getParameter("inputName");
//Ponemos como atributo de sesion el id de la película
HttpSession sesion = request.getSession();
sesion.setAttribute("idSesion", id);
//Obtenemos tambien la sala
Proxy bd = Proxy.getInstancia();
Sesion sesion2 = bd.getSesion(id);
Sala sala = bd.getSala(sesion2.getSala());
sesion.setAttribute("sala", sala);
response.sendRedirect(response.encodeRedirectURL("asiento.jsp"));
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
/**
* Project
Name:market
* File Name:BillMysqlImpl.java
* Package
Name:com.market.mysql.impl
* Date:2020年4月29日下午5:40:57
* Copyright (c) 2020,
277809183@qq.com All Rights Reserved.
*
*/
/**
* Project Name:market
* File Name:BillMysqlImpl.java
*
Package Name:com.market.mysql.impl
* Date:2020年4月29日下午5:40:57
* Copyright (c)
2020, 837806955@qq.com All Rights Reserved.
*
*/
package com.market.mysql.impl;
/**
* ClassName:BillMysqlImpl <br/>
*
Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD
REASON. <br/>
* Date: 2020年4月29日 下午5:40:57 <br/>
* @author
Future
* @version
* @since JDK 1.8
* @see
*/
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.market.entity.Bill;
import com.market.mysql.BaseMysql;
import com.market.mysql.BillMysql;
/**
* ClassName: BillMysqlImpl <br/>
* Function: TODO ADD
FUNCTION. <br/>
* Reason: TODO ADD REASON(可选). <br/>
*
date: 2020年4月29日 下午5:40:57 <br/>
*
* @author Li Zhengyu
* @version
* @since JDK 1.8
*/
public class BillMysqlImpl extends BaseMysql implements BillMysql{
public List<Bill> queryAll() {
List<Bill> bills = new ArrayList<Bill>();
Bill bill = null;
String sql = "select * from billinfo";
Object[] params = {};
rs = this.executeQuery(sql, params);
try {
while (rs.next()) {
String bname = rs.getString("bname");
String bdate = rs.getString("bdate");
String bid = rs.getString("bid");
String binfo = rs.getString("binfo");
double bprice=rs.getDouble("bprice");
double bamount=rs.getDouble("bamount");
double btotal=rs.getDouble("btotal");
String bprovider = rs.getString("bprovider");
bill = new Bill(bid, bname, bprice, bamount, btotal, bprovider, binfo,bdate);
bills.add(bill);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeResource(rs, pstmt, conn);
}
return bills;
}
public List<Bill> search(String bname) {
List<Bill> bills = new ArrayList<Bill>();
Bill bill = null;
String sql = "select * from billinfo where bname=?";
Object[] params = { bname };
rs = this.executeQuery(sql, params);
try {
while (rs.next()) {
String name = rs.getString("bname");
String bdate = rs.getString("bdate");
String bid = rs.getString("bid");
String binfo = rs.getString("binfo");
double bprice=rs.getDouble("bprice");
double bamount=rs.getDouble("bamount");
double btotal=rs.getDouble("btotal");
String bprovider = rs.getString("bprovider");
bill = new Bill(bid, name, bprice, bamount, btotal, bprovider, binfo,bdate);
bills.add(bill);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeResource(rs, pstmt, conn);// �ر���Դ
}
return bills;
}
public List<Bill> searchProvider(String bprovider) {
List<Bill> bills = new ArrayList<Bill>();
Bill bill = null;
String sql = "select * from billinfo where bprovider=?";
Object[] params = {bprovider};
rs = this.executeQuery(sql, params);
try {
while (rs.next()) {
String bname = rs.getString("bname");
String bdate = rs.getString("bdate");
String bid = rs.getString("bid");
String binfo = rs.getString("binfo");
double bprice=rs.getDouble("bprice");
double bamount=rs.getDouble("bamount");
double btotal=rs.getDouble("btotal");
String provider = rs.getString("bprovider");
bill = new Bill(bid, bname, bprice, bamount, btotal, provider, binfo,bdate);
bills.add(bill);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeResource(rs, pstmt, conn);
}
return bills;
}
public List<Bill> searchInfo(String binfo) {
List<Bill> bills = new ArrayList<Bill>();
Bill bill = null;
String sql = "select * from billinfo where binfo=?";
Object[] params = {binfo};
rs = this.executeQuery(sql, params);
try {
while (rs.next()) {
String bname = rs.getString("bname");
String bdate = rs.getString("bdate");
String bid = rs.getString("bid");
String info = rs.getString("binfo");
double bprice=rs.getDouble("bprice");
double bamount=rs.getDouble("bamount");
double btotal=rs.getDouble("btotal");
String provider = rs.getString("bprovider");
bill = new Bill(bid, bname, bprice, bamount, btotal, provider, info,bdate);
bills.add(bill);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeResource(rs, pstmt, conn);
}
return bills;
}
@Override
public boolean register(Bill bill) {
boolean flag = false;
try {
String sql = "insert into billinfo values(?,?,?,?,?,?,?,?)";
Object[] params = { bill.getBid(), bill.getBname(), bill.getBprice(),bill.getBamount(),bill.getBtotal(),
bill.getBprovider(), bill.getBinfo(), bill.getBdate() };
result = this.executeUpdate(sql, params);
if (result != 0) {
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
this.closeResource(null, pstmt, conn);
}
return flag;
}
public boolean delete(String name) {
boolean flag = false;
try {
String sql = "delete from billinfo where bname=?";
Object[] params = { name };
result = this.executeUpdate(sql, params);
if (result != 0) {
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
this.closeResource(null, pstmt, conn);
}
return flag;
}
public List<String> selectProvider(){
List<String> bproviders = new ArrayList<String>();
String sql = "select sname from suppinfo";
Object[] params = {};
rs = this.executeQuery(sql, params);
try {
while (rs.next()) {
String bprovider = rs.getString("sname");
bproviders.add(bprovider);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeResource(rs, pstmt, conn);
}
return bproviders;
}
}
|
package PA165.language_school_manager;
import PA165.language_school_manager.Dao.CourseDao;
import PA165.language_school_manager.Dao.LectureDao;
import PA165.language_school_manager.Dao.LecturerDAO;
import PA165.language_school_manager.Entities.Course;
import PA165.language_school_manager.Entities.Lecture;
import PA165.language_school_manager.Entities.Lecturer;
import PA165.language_school_manager.Enums.Language;
import PA165.language_school_manager.Enums.ProficiencyLevel;
import org.junit.Before;
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.transaction.annotation.Transactional;
import javax.persistence.PersistenceException;
import javax.validation.ConstraintViolationException;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Viktor Slaný
*/
@ContextConfiguration(classes = ApplicationContext.class)
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class LectureDaoTest {
@Autowired
private LectureDao lectureDao;
@Autowired
private CourseDao courseDao;
@Autowired
private LecturerDAO lecturerDAO;
private Lecture lecture1;
private Lecture lecture2;
@Before
public void setup() {
lecture1 = new Lecture();
lecture1.setTopic("jamesBond");
lecture1.setTime(LocalDateTime.of(2017, Month.JULY, 29, 19, 30, 40).plusDays(2));
Lecturer lecturer = new Lecturer();
lecturer.setUserName("lecturer123");
lecturer.setLastName("Bond");
lecturer.setFirstName("James");
lecturer.setMiddleName("007");
lecturer.setNativeSpeaker(true);
lecturer.setLanguage(Language.ENGLISH);
lecturerDAO.create(lecturer);
Course course = new Course();
course.setName("agent007");
course.setLanguage(Language.ENGLISH);
course.setProficiencyLevel(ProficiencyLevel.A1);
course.addLecture(lecture1);
courseDao.create(course);
lecture1.setCourse(course);
lecture1.setLecturer(lecturer);
lecture2 = new Lecture();
lecture2.setTopic("topic");
lecture2.setTime(LocalDateTime.of(2016, Month.JULY, 29, 19, 30, 40).plusDays(2));
lecture2.setCourse(course);
lecture2.setLecturer(lecturer);
}
@Test
public void createLecture() {
lectureDao.create(lecture1);
assertThat(lectureDao.findById(lecture1.getId())).isNotNull();
assertThat(lecture1.getTopic()).isEqualTo("jamesBond");
}
@Test(expected = PersistenceException.class)
public void createWithSameId() {
lecture1.setId(1L);
lecture2.setId(1L);
lectureDao.create(lecture1);
lectureDao.create(lecture2);
}
@Test(expected = IllegalArgumentException.class)
public void createNullLecture() {
lectureDao.create(null);
}
@Test(expected = PersistenceException.class)
public void createLectureWithNullDate() {
Lecture lecture2 = new Lecture();
lecture2.setTopic("jamesBond");
Lecturer lecturer = new Lecturer();
lecturer.setUserName("lecturer");
lecturer.setLastName("Bond");
lecturer.setFirstName("James");
lecturer.setMiddleName("007");
lecturer.setNativeSpeaker(true);
lecturer.setLanguage(Language.ITALIAN);
lecturerDAO.create(lecturer);
Course course = new Course();
course.setName("agent007");
course.setLanguage(Language.ENGLISH);
course.setProficiencyLevel(ProficiencyLevel.A1);
course.addLecture(lecture2);
courseDao.create(course);
lecture2.setCourse(course);
lecture2.setLecturer(lecturer);
lectureDao.create(lecture2);
}
@Test(expected = ConstraintViolationException.class)
public void createLectureWithNullCourse() {
Lecture lecture3 = new Lecture();
lecture3.setTopic("jamesBond");
Lecturer lecturer = new Lecturer();
lecturer.setLastName("Bond");
lecturer.setFirstName("James");
lecturer.setMiddleName("007");
lecturer.setNativeSpeaker(true);
lecturer.setLanguage(Language.ENGLISH);
lecturerDAO.create(lecturer);
lecture3.setLecturer(lecturer);
lectureDao.create(lecture3);
}
@Test(expected = PersistenceException.class)
public void createLectureWithNullLecturer() {
Lecture lecture2 = new Lecture();
lecture2.setTopic("jamesBond");
Course course = new Course();
course.setName("agent007");
course.setLanguage(Language.ENGLISH);
course.setProficiencyLevel(ProficiencyLevel.A1);
course.addLecture(lecture2);
courseDao.create(course);
lecture2.setCourse(course);
lectureDao.create(lecture2);
}
@Test
public void findLectureById() {
lectureDao.create(lecture1);
Lecture lecture = lectureDao.findById(lecture1.getId());
assertThat(lecture.getTopic()).isNotNull().isEqualTo("jamesBond");
}
@Test(expected = IllegalArgumentException.class)
public void findLectureByIdNull() {
lectureDao.findById(null);
}
@Test
public void findLectureByIdNonExisting() {
lectureDao.create(lecture1);
Lecture lecture = lectureDao.findById(1000000L);
assertThat(lecture).isNull();
}
@Test
public void findAllLectures() {
lectureDao.create(lecture1);
lectureDao.create(lecture2);
List<Lecture> lectures = lectureDao.findAll();
assertThat(lectures).isNotNull().isNotEmpty().hasSize(2);
}
@Test
public void deleteLecture() {
lectureDao.create(lecture1);
assertThat(lectureDao.findById(lecture1.getId())).isNotNull();
lectureDao.delete(lecture1);
assertThat(lectureDao.findById(lecture1.getId())).isNull();
}
@Test(expected = IllegalArgumentException.class)
public void deleteNullLecture() {
lectureDao.delete(null);
}
@Test(expected = ConstraintViolationException.class)
public void deleteNotExistingLecture() {
lectureDao.delete(new Lecture());
}
@Test
public void updateLecture() {
lecture1.setTopic("secondTopic");
lectureDao.update(lecture1);
assertThat(lecture1.getTopic()).isEqualTo("secondTopic");
}
@Test(expected = IllegalArgumentException.class)
public void updateNullLecture() {
lectureDao.update(null);
}
@Test(expected = PersistenceException.class)
public void updateLectureWithNullDate() {
Lecture lecture2 = new Lecture();
lecture2.setTopic("jamesBond");
Lecturer lecturer = new Lecturer();
lecturer.setUserName("lecturer");
lecturer.setLastName("Bond");
lecturer.setFirstName("James");
lecturer.setMiddleName("007");
lecturer.setNativeSpeaker(true);
lecturer.setLanguage(Language.ITALIAN);
lecturerDAO.create(lecturer);
Course course = new Course();
course.setName("agent007");
course.setLanguage(Language.ENGLISH);
course.setProficiencyLevel(ProficiencyLevel.A1);
course.addLecture(lecture2);
courseDao.create(course);
lecture2.setCourse(course);
lecture2.setLecturer(lecturer);
lectureDao.update(lecture2);
}
@Test(expected = ConstraintViolationException.class)
public void updateLectureWithNullCourse() {
Lecture lecture3 = new Lecture();
lecture3.setTopic("jamesBond");
Lecturer lecturer = new Lecturer();
lecturer.setLastName("Bond");
lecturer.setFirstName("James");
lecturer.setMiddleName("007");
lecturer.setNativeSpeaker(true);
lecturer.setLanguage(Language.ENGLISH);
lecturerDAO.create(lecturer);
lecture3.setLecturer(lecturer);
lectureDao.update(lecture3);
}
@Test(expected = PersistenceException.class)
public void updateLectureWithNullLecturer() {
Lecture lecture2 = new Lecture();
lecture2.setTopic("jamesBond");
Course course = new Course();
course.setName("agent007");
course.setLanguage(Language.ENGLISH);
course.setProficiencyLevel(ProficiencyLevel.A1);
course.addLecture(lecture2);
courseDao.create(course);
lecture2.setCourse(course);
lectureDao.update(lecture2);
}
@Test
public void findLectureByTopic() {
lectureDao.create(lecture1);
Lecture lecture = lectureDao.findByTopic("jamesBond");
assertThat(lecture).isEqualTo(lecture1);
}
@Test
public void findLectureByLecturer(){
lectureDao.create(lecture1);
List<Lecture> lectures = lectureDao.findByLecturer(lecture1.getLecturer());
assertThat(lectures.get(0)).isEqualTo(lecture1);
}
}
|
/*
* 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.
*/
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
/**
*
* @author Sammy Guergachi <sguergachi at gmail.com>
*/
public class tris implements ActionListener{
Random random = new Random();
JFrame frame = new JFrame();
JPanel titolo = new JPanel();
JPanel bottone = new JPanel();
JLabel testo = new JLabel();
JButton[] bottoni = new JButton[9];
boolean p1Girata;
public tris() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,800);
frame.getContentPane().setBackground(Color.black);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
testo.setBackground(Color.red);
testo.setForeground(Color.green);
testo.setFont(new Font("Ink Free",Font.BOLD,75));
testo.setHorizontalAlignment(JLabel.CENTER);
testo.setText("TRIS");
testo.setOpaque(true);
titolo.setLayout(new BorderLayout());
titolo.setBounds(0,0,800,100);
bottone.setLayout(new GridLayout(3, 3));
bottone.setBackground(Color.blue);
for(int i = 0; i<9; i++){
bottoni[i] = new JButton();
bottone.add(bottoni[i]);
bottoni[i].setFont(new Font("MV Boli",Font.BOLD,120));
bottoni[i].setFocusable(false);
bottoni[i].addActionListener(this);
}
titolo.add(testo);
frame.add(titolo,BorderLayout.NORTH);
frame.add(bottone);
primaMossa();
}
@Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 9; i++) {
if(e.getSource()==bottoni[i]){
if(p1Girata){
if (bottoni[i].getText() == "") {
bottoni[i].setForeground(Color.GRAY);
bottoni[i].setText("X");
p1Girata = false;
testo.setText("0 turno");
controlla();
}
}
else{
if (bottoni[i].getText() == "") {
bottoni[i].setForeground(Color.yellow);
bottoni[i].setText("0");
p1Girata = true;
testo.setText("X turno");
controlla();
}
}
}
}
}
public void primaMossa() {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
if(random.nextInt(2) == 0){
p1Girata = true;
testo.setText("x turno");
}
else{
p1Girata = false;
testo.setText("0 turno");
}
}
public void controlla() {
boolean c = true;
if((bottoni[0].getText() == "X") && (bottoni[1].getText() == "X") && (bottoni[2].getText() == "X")){
xvittoria(0, 1, 2);
c = false;
}
if((bottoni[3].getText() == "X") && (bottoni[4].getText() == "X") && (bottoni[5].getText() == "X")){
xvittoria(3, 4, 5);
c = true;
}
if((bottoni[6].getText() == "X") && (bottoni[7].getText() == "X") && (bottoni[8].getText() == "X")){
xvittoria(6, 7, 8);
c = true;
}
if((bottoni[0].getText() == "X") && (bottoni[3].getText() == "X") && (bottoni[6].getText() == "X")){
xvittoria(0, 3, 6);
c = true;
}
if((bottoni[1].getText() == "X") && (bottoni[4].getText() == "X") && (bottoni[7].getText() == "X")){
xvittoria(1, 4, 7);
c = true;
}
if((bottoni[2].getText() == "X") && (bottoni[5].getText() == "X") && (bottoni[8].getText() == "X")){
xvittoria(2, 5, 8);
c = true;
}
if((bottoni[0].getText() == "X") && (bottoni[4].getText() == "X") && (bottoni[8].getText() == "X")){
xvittoria(0, 4, 8);
c = true;
}
if((bottoni[2].getText() == "X") && (bottoni[4].getText() == "X") && (bottoni[6].getText() == "X")){
xvittoria(2, 4, 6);
c = true;
}
//controlla altro giocatore;
if((bottoni[0].getText() == "0") && (bottoni[1].getText() == "0") && (bottoni[2].getText() == "0")){
ovittoria(0, 1, 2);
c = true;
}
if((bottoni[3].getText() == "0") && (bottoni[4].getText() == "0") && (bottoni[5].getText() == "0")){
ovittoria(3, 4, 5);
c = true;
}
if((bottoni[6].getText() == "0") && (bottoni[7].getText() == "0") && (bottoni[8].getText() == "0")){
ovittoria(6, 7, 8);
c = true;
}
if((bottoni[0].getText() == "0") && (bottoni[3].getText() == "0") && (bottoni[6].getText() == "0")){
ovittoria(0, 3, 6);
c = true;
}
if((bottoni[1].getText() == "0") && (bottoni[4].getText() == "0") && (bottoni[7].getText() == "0")){
ovittoria(1, 4, 7);
c = true;
}
if((bottoni[2].getText() == "0") && (bottoni[5].getText() == "0") && (bottoni[8].getText() == "0")){
ovittoria(2, 5, 8);
c = true;
}
if((bottoni[0].getText() == "0") && (bottoni[4].getText() == "0") && (bottoni[8].getText() == "0")){
ovittoria(0, 4, 8);
c = true;
}
if((bottoni[2].getText() == "0") && (bottoni[4].getText() == "0") && (bottoni[6].getText() == "0")){
ovittoria(2, 4, 6);
c = true;
}
}
public void xvittoria(int a, int b, int c) {
bottoni[a].setBackground(Color.green);
bottoni[b].setBackground(Color.green);
bottoni[c].setBackground(Color.green);
for(int i = 0; i < 9; i++){
bottoni[i].setEnabled(false);
}
testo.setText("X ha vinto, 0 sparati");
}
public void ovittoria(int a, int b, int c) {
bottoni[a].setBackground(Color.green);
bottoni[b].setBackground(Color.green);
bottoni[c].setBackground(Color.green);
for(int i = 0; i < 9; i++){
bottoni[i].setEnabled(false);
}
testo.setText("0 ha vinto, X sparati");
}
}
|
package com.infohold.elh.base.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.annotations.GenericGenerator;
import com.infohold.bdrp.org.model.Org;
import com.infohold.core.model.BaseModel;
/**
* 机构(医院)
* @author Administrator
*
*/
@Entity
@Table(name="ELH_ORG")
public class ElhOrg extends BaseModel {
private static final long serialVersionUID = 1826210740042076986L;
private String code ; //机构代码
private String name ; //机构名称
//1 - 综合医院 2 - 专科医院
private String hosType ; //医院类型
/*1A - 一级甲等
1B - 一级乙等
1C - 一级丙等
2A - 二级甲等
2B - 二级乙等
2C - 二级丙等
3A - 三级甲等
3B - 三级乙等
3C - 三级丙等*/
private String hosLevel ; //医院级别
private String linkman ; //联系人
private String lmContactWay; //联系人联系方式
private String zipcode ; //邮编
private String address ; //地址
private String salesman ; //客户专员
private String smContactWay; //客户专员联系方式
//1 - 正常2 - 已下线
private String state ; //状态
private String memo ; //备注
private String logo ; //医院
private String hosHomeBg ; //医院微主页背景图
private String createdAt ; //创建时间
private Org org;
private String id;//
@Id
@Column(name="ID",length = 32)
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy="assigned")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Transient
public Org getOrg() {
return org;
}
public void setOrg(Org org) {
this.org = org;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHosType() {
return hosType;
}
public void setHosType(String hosType) {
this.hosType = hosType;
}
public String getHosLevel() {
return hosLevel;
}
public void setHosLevel(String hosLevel) {
this.hosLevel = hosLevel;
}
public String getLinkman() {
return linkman;
}
public void setLinkman(String linkman) {
this.linkman = linkman;
}
public String getLmContactWay() {
return lmContactWay;
}
public void setLmContactWay(String lmContactWay) {
this.lmContactWay = lmContactWay;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSalesman() {
return salesman;
}
public void setSalesman(String salesman) {
this.salesman = salesman;
}
public String getSmContactWay() {
return smContactWay;
}
public void setSmContactWay(String smContactWay) {
this.smContactWay = smContactWay;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getHosHomeBg() {
return hosHomeBg;
}
public void setHosHomeBg(String hosHomeBg) {
this.hosHomeBg = hosHomeBg;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
@Transient
@Override
public boolean _newObejct() {
return null == this.getId();
}
/**
* 重载toString;
*/
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
/**
* 重载hashCode;
*/
public int hashCode() {
return new HashCodeBuilder().append(this.getId()).toHashCode();
}
/**
* 重载equals
*/
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
}
|
package winkelman.powerswitch;
import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by eric on 8/21/16.
*/
public interface IConnectionEventListener {
public void onEventCompleted(JSONObject result, View triggeringView) throws JSONException;
public void onEventFailed();
}
|
package br.gov.dataprev.caged.captacao.negocio.exceptions;
public class CompetenciaAtualException
extends BusinessException
{
private static final long serialVersionUID = -2111305047876794506L;
public CompetenciaAtualException(String message)
{
super(message);
}
}
|
package com.portal.util;
import com.portal.bean.Databean;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zhangzheming on 2014/4/17.
*/
public class testUtil {
public testUtil(){}
public static Connection getMySQLConnection(){
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名scutcs
String url = "jdbc:mysql://172.18.108.102:3306/esanalysis";
// MySQL配置时的用户名
String user = "root";
// Java连接MySQL配置时的密码
String password = "bigdata_mysql";
Connection conn = null;
try {
// 加载驱动程序
Class.forName(driver);
// 连续数据库
conn = DriverManager.getConnection(url, user, password);
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
public static JSONObject getData(){
Databean bean = new Databean();
Connection conn = null;
List<String> timelist = new ArrayList<String>();
List<String> UVlist = new ArrayList<String>();
List<String> PVlist = new ArrayList<String>();
//获取数据库连接
conn = getMySQLConnection();
try{
if (!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
// statement用来执行SQL语句
Statement statement = conn.createStatement();
// 要执行的SQL语句
String sql = "select date,count(distinct bd_user_uuid) as UV,sum(pv) as PV from ebusi_daily_report group by date order by date ;";
ResultSet rs = statement.executeQuery(sql);
String date = "";
String UV = "";
String PV = "";
while (rs.next()){
date = rs.getString("date");
UV = rs.getString("UV");
PV = rs.getString("PV");
if(PV == null || PV.length() == 0){
PV = "0";
}
timelist.add(date);
UVlist.add(UV);
PVlist.add(PV);
}
bean.setTime(timelist.toString());
bean.setUv(UVlist.toString());
bean.setPv(PVlist.toString());
rs.close();
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject object = JSONObject.fromObject(bean);
return object;
}
}
|
package com.j1902.shopping.pojo;
public class OrderFrom {
private String orderNumber;
private String orderTime;
private Item item;
private Integer itemNumber;
private double moneys;
private String countMethod;
private String countSat;
private Integer countId;
private Integer orderId;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public Integer getCountId() {
return countId;
}
public void setCountId(Integer countId) {
this.countId = countId;
}
public Integer getOrderId() {
return orderId;
}
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
public OrderFrom() {
}
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
public Integer getItemNumber() {
return itemNumber;
}
public void setItemNumber(Integer itemNumber) {
this.itemNumber = itemNumber;
}
public double getMoneys() {
return moneys;
}
public void setMoneys(double moneys) {
this.moneys = moneys;
}
public String getCountMethod() {
return countMethod;
}
public void setCountMethod(String countMethod) {
this.countMethod = countMethod;
}
public String getCountSat() {
return countSat;
}
public void setCountSat(String countSat) {
this.countSat = countSat;
}
@Override
public String toString() {
return "OrderFrom{" +
"orderNumber='" + orderNumber + '\'' +
", orderTime='" + orderTime + '\'' +
", item=" + item +
", itemNumber=" + itemNumber +
", moneys=" + moneys +
", countMethod='" + countMethod + '\'' +
", countSat='" + countSat + '\'' +
", countId=" + countId +
", orderId=" + orderId +
'}';
}
}
|
package com.sjquechao.cashier.presenter.PCore;
import com.sjquechao.cashier.bean.UserBean;
import com.sjquechao.cashier.model.api.Api;
import com.sjquechao.cashier.model.callback.AppResponse;
import com.sjquechao.cashier.presenter.IView.ILoginView;
/**
* Created by Administrator on 2017/2/26.
*/
public class PLogin extends PBase {
private ILoginView iLoginView;
public PLogin(ILoginView iLoginView) {
this.iLoginView = iLoginView;
}
public void login(String username, String pwd) {
Api.login(username, pwd, new AppResponse<UserBean>() {
@Override
protected void onError(int codeError, Throwable e) {
iLoginView.onError(codeError,e);
}
@Override
protected void onSuccess(int codeSuccess, UserBean userBean) {
iLoginView.saveUserInfo(userBean);
}
});
}
}
|
package DataStructures.binarysearch;
/**
* Created by senthil on 1/9/16.
*/
public class FindMax {
/**
* array is increasing and then decreasing find max in it
* 5, 12, 15, 4, 3, 2 ,1
* 4, 5, 6, 7, 2, 1 ,0
* @param a
* @return
*/
public int findmax(int a[]) {
if (a == null || a.length == 0) return -1;
int s = 0;
int e = a.length - 1;
while (s <= e) {
int mid = s + (e-s)/2;
if (mid > 0 && a[mid] < a[mid -1])
e = mid - 1;
else if (mid < a.length - 1 && a[mid] < a[mid + 1]) {
s = mid + 1;
}
else
return a[mid];
}
return -1;
}
public int findMin(int a[]) {
if (a == null || a.length == 0) return -1;
int s = 0;
int e = a.length - 1;
while (s <= e) {
if (e - s == 1) return a[e];
int mid = s + (e-s)/2;
if (a[e] > a[mid])
e = mid;
else if (a[e] < a[mid]) {
s = mid;
}
else
return a[s];
}
return -1;
}
public int findMin1(int[] nums) {
if(nums==null || nums.length==0)
return -1;
int i=0;
int j=nums.length-1;
while(i<=j){
if(nums[i]<=nums[j])
return nums[i];
int m=(i+j)/2;
if(nums[m]>=nums[i]){
i=m+1;
}else{
j=m;
}
}
return -1;
}
public static void main(String a[]) {
//System.out.println(new FindMax().findmax(new int[]{7,8,9,10}));
System.out.println(new FindMax().findMin1(new int[]{11, 12, 15, 20, 21, 0, 1, 7, 9}));
}
}
|
package dataset;
public class DatasetDocument {
private int id;
private String title;
private String category;
private String text;
private Datasets dataset;
private int indexId;
public int getIndexId() {
return indexId;
}
public void setIndexId(int indexId) {
this.indexId = indexId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Datasets getDataset() {
return dataset;
}
public void setDataset(Datasets dataset) {
this.dataset = dataset;
}
}
|
package com.arpit.equityposition.utilities;
/**
* Enum of the valid Sides.
* @author : Arpit
* @version 1.0
* @since : 23-Jun-2020
*/
public enum ValidSides {
BUY,SELL;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.