text stringlengths 10 2.72M |
|---|
package io.indreams.ecommerceuserinfoservice.dao;
import io.indreams.ecommerceuserinfoservice.model.UserDAO;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface UserRepo extends MongoRepository<UserDAO,String> {
}
|
package com.starfall.datastructure.tree;
import org.junit.Test;
/**
* @author StarFall
* @project JavaProject
* @package com.starfall.datastructure.tree
* @className BalanceBinaryTreeTest
* @date 2019/6/23 17:47
* @description BalanceBinaryTreeTest 平衡二叉树测试
*/
public class BalanceBinaryTreeTest {
@Test
public void test01() {
BalanceBinaryTree<Integer> bbt = new BalanceBinaryTree<>();
// int arr[] = { 3, 2, 1, 4, 5, 6, 7, 16, 15, 14, 13, 12, 11, 10, 8, 9 };
int arr[] = { 1, 2, 3, 4, 5, 6 };
for (int i = 0; i < arr.length; i++) {
bbt.insert(arr[i]);
}
bbt.preOrder();
bbt.midOrder();
bbt.backOrder();
bbt.levelOrder();
}
@Test
public void test02() {
BalanceBinaryTree<Integer> bbt = new BalanceBinaryTree<>();
int arr[] = { 8, 4, 12, 2, 6, 1 };
for (int i = 0; i < arr.length; i++) {
bbt.insert(arr[i]);
}
bbt.preOrder();
bbt.midOrder();
bbt.backOrder();
bbt.levelOrder();
System.out.println("***********搜索节点数据***********");
System.out.println(bbt.searchTree(4).getHeight());
}
@Test
public void test03() {
BalanceBinaryTree<Integer> bbt = new BalanceBinaryTree<>();
int arr[] = { 3, 2, 1, 4, 5, 6, 7, 16, 15, 14, 13, 12, 11, 10, 8, 9, 17 };
for (int i = 0; i < arr.length; i++) {
bbt.insert(arr[i]);
}
bbt.preOrder();
bbt.midOrder();
bbt.backOrder();
bbt.levelOrder();
System.out.println("***********删除节点数据***********");
bbt.deleteNode(14);
bbt.preOrder();
bbt.midOrder();
bbt.backOrder();
bbt.levelOrder();
}
} |
package holder;
import java.util.*;
class SumObject {
int sumValue;
HashSet<Integer> sumPairs = new HashSet<>();
public SumObject() {
}
public SumObject(int sumValue, int sumPair) {
this.sumValue = sumValue;
this.sumPairs.add(sumPair);
}
public void addPair(int pair) {
this.sumPairs.add(pair);
}
}
public class SolverAs {
public static void main(String[] args) {
int nums[] = {42,33,60};
// {42,33,60};
// {51,32,43};
// { 51,71,17,42 };
// solutionOld(10410);
System.out.println(solution(nums));
HashMap<Integer, Integer> nMap = new HashMap<>();
SumObject resultMap = new SumObject(10, 5);
resultMap.addPair(92);
// System.out.println(resultMap.sumPairs);
}
public class sumObject {
int sumValue;
HashSet<Integer> sumPairs = new HashSet<>();
public sumObject(int sumValue, int sumPair) {
this.sumValue = sumValue;
this.sumPairs.add(sumPair);
}
}
public static int solution(int[] A) {
int leftCounter = 0;
int currSum = 0;
int sumMax = 0;
HashMap<Integer, Integer> sumMap = new HashMap<>();
while (leftCounter < A.length) {
int sumOfDigits = 0;
int value = A[leftCounter];
while (value > 0) {
sumOfDigits += value % 10;
value = value / 10;
}
if (sumMap.containsKey(sumOfDigits)) {
currSum = A[leftCounter] + sumMap.get(sumOfDigits);
sumMax = Math.max(sumMax, currSum);
} else {
sumMap.put(sumOfDigits, A[leftCounter]);
}
leftCounter++;
}
if (sumMax == 0) {
sumMax = -1;
}
return sumMax;
}
}
|
package sort;
public class Insertion extends AbstractSort{
public static void sort(Comparable[] a) {
for(int p=1; p<a.length; p++)
for(int j=p; j>0; j--)
if(less(a[j-1],a[j]) == false)
exch(a,j-1,j);
}
}
|
/*
* 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 conexion;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
/**
* Contiene los datos para poderrealizar una conexión con la base de datos.
*
* @author PREDATOR 15 G9-78Q
*/
class Credenciales {
private static String usuario;
private static String contrasenia;
private static String baseDatos;
private static String host;
private static int port;
public static String getCredencialUno() {
return Credenciales.usuario;
}
public static String getCredencialDos() {
return Credenciales.contrasenia;
}
public static String getCredencialTres() {
return Credenciales.baseDatos;
}
public static String getCredencialCuatro() {
return Credenciales.host;
}
public static int getCredencialCinco() {
return Credenciales.port;
}
public static void iniciarCredenciales() throws SQLException {
Credenciales.muestraContenido("encryp.txt");
}
private static void muestraContenido(String archivo) throws SQLException {
try (FileReader file = new FileReader(archivo);
BufferedReader b = new BufferedReader(file)) {
Credenciales.usuario = b.readLine();
Credenciales.contrasenia = b.readLine();
Credenciales.baseDatos = b.readLine();
Credenciales.host = b.readLine();
int puerto = Integer.parseInt(b.readLine());
Credenciales.port = puerto;
b.close();
} catch (FileNotFoundException ex) {
throw new SQLException();
} catch (IOException ex) {
throw new SQLException();
}
}
} |
package com.hc.element_ec.main;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import com.hc.element_ec.main.index.IndexFragment;
import com.heyskill.element_core.fragments.BaseFragment;
import com.heyskill.element_core.fragments.bottom.BaseBottomFragment;
import com.heyskill.element_core.fragments.bottom.BottomItemFragment;
import com.heyskill.element_core.fragments.bottom.BottomTabBean;
import com.heyskill.element_core.fragments.bottom.ItemBuilder;
import java.util.LinkedHashMap;
public class EcBottomFragment extends BaseBottomFragment {
@Override
public LinkedHashMap<BottomTabBean, BottomItemFragment> setItems(ItemBuilder builder) {
final LinkedHashMap<BottomTabBean,BottomItemFragment> items = new LinkedHashMap<>();
items.put(new BottomTabBean("{fa-home}","主页"),new IndexFragment());
items.put(new BottomTabBean("{fa-sort}","分类"),new IndexFragment());
items.put(new BottomTabBean("{fa-compass}","发现"),new IndexFragment());
items.put(new BottomTabBean("{fa-shopping-cart}","购物车"),new IndexFragment());
items.put(new BottomTabBean("{fa-user}","我的"),new IndexFragment());
return builder.addItems(items).build();
}
@Override
public int setIndexFragment() {
return 0;
}
@Override
public int setClickColor() {
return Color.parseColor("#ffff8800");
}
}
|
package map;
import java.awt.Color;
import java.awt.Insets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.ToolTipManager;
import map.model.Tile;
public class PaletteTile extends JButton
{
private static final long serialVersionUID = 1L;
private DynamicPalette palette; // used to get the dynamic highlight pattern
private Tile tile;
private Map<String, Object> properties; // used for the tool-tip table and refining
public PaletteTile (final DynamicPalette palette, final String relativePath)
{
properties = new LinkedHashMap<String, Object>();
putFile (relativePath);
this.tile = new Tile (relativePath);
setIcon (new ImageIcon (tile.getImage()));
put ("Image", tile.getImage());
setBackground (Color.white);
setMargin (new Insets (0, 0, 0, 0));
if (palette != null)
addActionListener (palette.getButtonListener());
// enable lazy-loaded tool-tips for this component
this.palette = palette;
ToolTipManager.sharedInstance().registerComponent (this);
}
public Tile getTile()
{
return tile;
}
public void putFile (final String file)
{
put ("FILE", file);
}
public String getFile()
{
return (String) get ("FILE");
}
public void put (final String key, final Object value)
{
properties.put (key, value);
}
public Object get (final String key)
{
return properties.get (key);
}
public Map<String, Object> getProperties()
{
return properties;
}
public boolean matches (final Pattern pattern)
{
for (Object value : properties.values())
if (value instanceof String && pattern.matcher ((String) value).find())
return true;
return false;
}
@Override
public String getToolTipText()
{
StringBuilder sb = new StringBuilder();
sb.append ("<html>\n");
sb.append ("<table border=1 cellspacing=1 width=400>\n");
for (Entry<String, Object> entry : properties.entrySet())
if (entry.getValue() instanceof String && !entry.getValue().equals (""))
{
sb.append ("<tr>");
sb.append ("<td>" + entry.getKey());
sb.append ("<td>" + hilightPattern ((String) entry.getValue()));
sb.append ("</tr>\n");
}
sb.append ("</table>\n");
sb.append ("</html>");
return sb.toString();
}
// highlight the matching pattern(s)
private String hilightPattern (final String target)
{
Pattern pattern = palette.getHighlightPattern();
if (pattern != null)
{
Matcher m = pattern.matcher (target);
String replacement = "<b style=\"background-color:yellow\">$0</b>";
return m.replaceAll (replacement);
}
return target;
}
@Override
public String toString()
{
return getFile();
}
}
|
/*
* Copyright 1999-2011 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.bvt.sql.mysql.select;
import com.alibaba.druid.sql.MysqlTest;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelect;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.sql.parser.ParserException;
import com.alibaba.druid.stat.TableStat;
public class MySqlSelectTest_ads_keywords_1 extends MysqlTest {
String[] keywords = new String[]{
"any",
"begin",
"cast",
"compute",
"escape",
"except",
"full",
"identified",
"intersect",
"merge",
"minus",
"open",
"some",
"truncate",
"until",
"view",
"lable",
"status",
"option",
"restrict",
"connection",
"character",
"offset"
};
public void test_create() throws Exception {
for (int i = 0; i < keywords.length; i++) {
String keyword = keywords[i];
String sql = "create table t (" + keyword + " bigint)";
try {
SQLUtils.parseSingleMysqlStatement(sql);
} catch (ParserException ex) {
System.out.println(keyword);
throw ex;
}
}
}
public void test_select() throws Exception {
for (int i = 0; i < keywords.length; i++) {
String keyword = keywords[i];
String sql = "select " + keyword + " from t where label = 1";
try {
SQLUtils.parseSingleMysqlStatement(sql);
} catch (ParserException ex) {
System.out.println(keyword);
throw ex;
}
}
}
public void test_select_alais() throws Exception {
for (int i = 0; i < keywords.length; i++) {
String keyword = keywords[i];
String sql = "select " + keyword + " " + keyword + " from t where label = 1";
try {
SQLUtils.parseSingleMysqlStatement(sql);
} catch (ParserException ex) {
System.out.println(keyword);
throw ex;
}
}
}
public void test_select_alais_2() throws Exception {
for (int i = 0; i < keywords.length; i++) {
String keyword = keywords[i];
String sql = "select " + keyword + " AS " + keyword + " from t where label = 1";
try {
SQLUtils.parseSingleMysqlStatement(sql);
} catch (ParserException ex) {
System.out.println(keyword);
throw ex;
}
}
}
public void test_where() throws Exception {
for (int i = 0; i < keywords.length; i++) {
String keyword = keywords[i];
String sql = "select 1 from t where " + keyword + " = 1";
try {
SQLUtils.parseSingleMysqlStatement(sql);
} catch (ParserException ex) {
System.out.println(keyword);
throw ex;
}
}
}
public void test_where_2() throws Exception {
for (int i = 0; i < keywords.length; i++) {
String keyword = keywords[i];
String sql = "select 1 from t where max(" + keyword + ") = 1";
try {
SQLUtils.parseSingleMysqlStatement(sql);
} catch (ParserException ex) {
System.out.println(keyword);
throw ex;
}
}
}
}
|
package main.java.pane.simulation;
import java.util.ArrayList;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import main.java.algorithms.tsp.HungarianAssignment;
import main.java.algorithms.tsp.NearestNeighbour;
import main.java.algorithms.tsp.ScissorEdge;
import main.java.algorithms.tsp.TotalEnumeration;
import main.java.constant.ColorConstants;
import main.java.constant.Constants;
import main.java.graphs.grid.GridTile;
import main.java.graphs.grid.TSPGrid;
import main.java.main.ScreenProperties;
import main.java.main.Vector2;
import main.java.pane.base.StyledChoiceBox;
public class TspSimulation extends BaseSimulation
{
public TSPGrid grid;
private boolean isInteractive = true;
public ConsolePane consolePane;
public ProgressBar progression;
public CheckBox isFancy;
public Label lblProgSec;
private TotalEnumeration algorithm = new TotalEnumeration(this);
public TspSimulation()
{
super();
getStyleClass().add("background");
setPrefHeight(ScreenProperties.getScreenHeight() - 92);
AddControls();
// Add a default grid
AddGrid(Constants.baseWareHouseSize);
AddConsolePane();
AddFancyMode();
AddProgressBar();
}
private void AddConsolePane()
{
consolePane = new ConsolePane(15, 320);
getChildren().add(consolePane);
}
private void AddProgressBar()
{
this.progression = new ProgressBar(0);
progression.setLayoutX(15);
progression.setLayoutY(285);
progression.setPrefWidth(ScreenProperties.getScreenWidth() / 4);
progression.setPrefHeight(30);
progression.setProgress(0);
getChildren().add(progression);
}
private void AddFancyMode(){
isFancy = new CheckBox("Fancy mode (Beta)");
isFancy.setLayoutX(205);
isFancy.setLayoutY(175);
getChildren().add(isFancy);
}
/**
*
*/
public void AddControls()
{
String[] algorithmNames =
{ "btn.nearestNeighbour", "btn.hungarianAssignment", "btn.totalEnumeration", "btn.ownAlgorithm" };
SimulationControls simulationControls = new SimulationControls(algorithmNames, this);
getChildren().add(simulationControls);
addColorChoicebox();
addGridSizeChoicebox();
}
/**
*
* @param size
*/
public void AddGrid(int size)
{
if (grid != null)
{
getChildren().remove(grid);
}
grid = new TSPGrid(size, isInteractive);
grid.setLayoutX((ScreenProperties.getScreenWidth() / 2) - Constants.drawnGridSize / 2);
grid.setLayoutY(15);
getChildren().add(grid);
}
/**
*
* @param newSize
*/
public void UpdateGrid(int newSize)
{
getChildren().remove(grid);
AddGrid(newSize);
}
public void updatePath(ArrayList<Vector2> shortestPath)
{
grid.Redraw(shortestPath, 0);
}
/**
*
* @param interactive
*/
public void SetInteractive(boolean interactive)
{
isInteractive = interactive;
}
// Nearest Noughbour
@Override
public void ExecuteAlgorithmOne()
{
if (grid.isActive())
{
addConsoleItem("Algorithm blocked, thread is already running", "ERROR");
}
else
{
consolePane.getItems().clear();
grid.setActive(true);
ArrayList<GridTile> activeTiles = grid.getSelectedTiles();
addConsoleItem("Starting Algorithm 'nearest neighbour'", "INFO");
addConsoleItem("Searching for Coordinates", "INFO");
if (activeTiles.size() > 0)
{
addConsoleItem(String.format("%s coordinates found, starting algorithm", activeTiles.size()), "ALERT");
long startTime = System.nanoTime();
NearestNeighbour algoritme = new NearestNeighbour(activeTiles);
ArrayList<Vector2> shortestPath = algoritme.getShortestPath();
long stopTime = System.nanoTime();
addConsoleItem("Kortste pad gevonden", "INFO");
float duration = (stopTime - startTime) / 100000f;
double pathLength = CalculatePathLength(shortestPath);
addConsoleItem("duration: " + duration + " ms", "INFO");
addConsoleItem("Total path distance: " + pathLength, "INFO");
if (ColorConstants.GetBlzitNumber(pathLength))
{
addConsoleItem("420 Blaze it!", "DANK");
}
if(ColorConstants.GetNootianNumber(pathLength))
{
addConsoleItem("Noot Noot!", "DANK");
}
if(ColorConstants.GetNootianNumber(pathLength))
{
addConsoleItem("Noot Noot!", "DANK");
}
if (ColorConstants.GetBlzitNumber(pathLength))
{
addConsoleItem("420 Blaze it!", "DANK");
}
grid.Redraw(shortestPath, pathLength);
}
else
{
addConsoleItem(String.format("%s coordinates found, algorithm has been cancelled", activeTiles.size()),
"ERROR");
}
grid.setActive(false);
}
}
// Hungarian Assignment
@Override
public void ExecuteAlgorithmTwo()
{
ArrayList<GridTile> activeTiles = grid.getSelectedTiles();
addConsoleItem("Starting Algorithm 'Hungarian Assignment'", "DEBUG");
addConsoleItem("Searching for Coordinates", "DEBUG");
// ArrayList<GridTile> activeTiles = newGrid.getSelectedTiles();
addConsoleItem(String.format("%s coordinates found, starting algorithm", activeTiles.size()), "DEBUG");
@SuppressWarnings("unused")
long startTime = System.nanoTime();
HungarianAssignment algoritme = new HungarianAssignment(activeTiles);
ArrayList<Vector2> vector = algoritme.runHungarian();
// TODO GET PATHLENGTH
if (ColorConstants.GetBlzitNumber(0))
{
addConsoleItem("420 Blaze it!", "DANK");
}
if(ColorConstants.GetNootianNumber(0))
{
addConsoleItem("Noot Noot!", "DANK");
}
grid.Redraw(vector, 0);
for (Vector2 vect : vector)
{
System.out.println(String.format("x: %s y: %s ", vect.getX(), vect.getY()));
}
}
// Brute Force
@Override
public void ExecuteAlgorithmThree()
{
if (algorithm.showState() == 1)
{
algorithm.resumeII();
addConsoleItem("Resuming thread", "ALERT");
}
else
{
if (grid.isActive())
{
addConsoleItem("Algorithm blocked, thread is already running", "ERROR");
}
else
{
grid.setActive(true);
ArrayList<GridTile> activeTiles = grid.getSelectedTiles();
consolePane.getItems().clear();
addConsoleItem("Starting Algorithm 'Total Enumeration'", "INFO");
addConsoleItem("Searching for Coordinates", "INFO");
if (activeTiles.size() > 0)
{
algorithm = new TotalEnumeration(activeTiles, this);
algorithm.start();
if (algorithm.getState() == Thread.State.TERMINATED)
{
addConsoleItem("Process has stopped unexpectly", "ERROR");
}
}
else
{
addConsoleItem(
String.format("%s coordinates found, algorithm has been cancelled", activeTiles.size()),
"ERROR");
grid.setActive(false);
}
}
}
}
// Own Algorithm, ScissorEdge
@Override
public void ExecuteAlgorithmFour()
{
consolePane.getItems().clear();
ArrayList<GridTile> activeTiles = grid.getSelectedTiles();
if (activeTiles.size() > 0)
{
ScissorEdge scissorEdge = new ScissorEdge(grid.GetTileAmount());
ArrayList<Vector2> pointList1 = new ArrayList<Vector2>();
ArrayList<Vector2> pointList2 = new ArrayList<Vector2>();
for (GridTile tile : activeTiles)
{
pointList1.add(tile.GetPos());
pointList2.add(tile.GetPos());
}
// Try Left
long startTime = System.nanoTime();
ArrayList<Vector2> shortestPathLeft = scissorEdge.GetShortestPath(pointList1);
long stopTime = System.nanoTime();
float durationRight = (stopTime - startTime) / 100000f;
addConsoleItem("duration left: " + durationRight + " ms", "INFO");
addConsoleItem("Total path distance left: " + CalculatePathLength(shortestPathLeft), "INFO");
// Try Right
scissorEdge.currentIndex = 1;
startTime = System.nanoTime();
ArrayList<Vector2> shortestPathRight = scissorEdge.GetShortestPath(pointList2);
stopTime = System.nanoTime();
float durationLeft = (stopTime - startTime) / 100000f;
addConsoleItem("duration right: " + durationLeft + " ms", "INFO");
addConsoleItem("Total path distance right: " + CalculatePathLength(shortestPathRight), "INFO");
addConsoleItem("Total duration: " + (durationLeft + durationRight) + " ms", "INFO");
ArrayList<Vector2> shortestPath = CalculatePathLength(shortestPathLeft) < CalculatePathLength(
shortestPathRight) ? shortestPathLeft : shortestPathRight;
grid.SetAlgorithm(scissorEdge);
if (ColorConstants.GetBlzitNumber(CalculatePathLength(shortestPath)))
{
addConsoleItem("420 Blaze it!", "DANK");
}
grid.Redraw(shortestPath, CalculatePathLength(shortestPath));
grid.SetAlgorithm(null);
}
}
@Override
public void pauseAlgorithm()
{
algorithm.suspendII();
// algorithm.pauseThread();
addConsoleItem("Thread has been paused", "ALERT");
}
@Override
public void stopAlgorithm()
{
addConsoleItem("Attempting to murder Thread 'algorithm' in his sleep.", "INFO");
algorithm.killII();
}
public void clearField()
{
for (GridTile tile : grid.getSelectedTiles())
{
tile.SetSelected(false);
}
grid.resetPathList();
grid.Redraw();
}
public void addConsoleItem(String message, String msgType)
{
consolePane.getItems().add(consolePane.getItems().size(), String.format("[%s] %s", msgType, message));
}
private void addColorChoicebox()
{
String[] colorOptions =
{ "black", "Red", "Green", "blue" };
StyledChoiceBox cb = new StyledChoiceBox(colorOptions, new Vector2(340, 250), new Vector2(100, 25));
cb.getSelectionModel().selectFirst();
cb.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>()
{
public void changed(ObservableValue<? extends Number> ov, Number value, Number new_value)
{
switch (new_value.intValue())
{
case 0:
grid.SetGridColor("black");
break;
case 1:
grid.SetGridColor("red");
break;
case 2:
grid.SetGridColor("green");
break;
case 3:
grid.SetGridColor("blue");
break;
default:
grid.SetGridColor("black");
break;
}
}
});
getChildren().add(cb);
}
private void addGridSizeChoicebox()
{
String[] numberOptions = new String[18];
for (int i = 0; i < numberOptions.length; i++)
{
numberOptions[i] = Integer.toString(i + 3);
}
StyledChoiceBox choiceBox = new StyledChoiceBox(numberOptions, new Vector2(445, 250), new Vector2(50, 25));
choiceBox.getSelectionModel().selectFirst();
choiceBox.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>()
{
public void changed(ObservableValue<? extends Number> ov, Number value, Number new_value)
{
AddGrid(Integer.parseInt(choiceBox.getItems().get((Integer) new_value)));
}
});
getChildren().add(choiceBox);
choiceBox.getSelectionModel().select(2);
}
public void changeProgression(int progress)
{
progression.setProgress(progress);
}
public static double CalculatePathLength(ArrayList<Vector2> shortestPath)
{
// Calculate the total path distance
double totalPathDistance = 0;
for (int i = 0; i < shortestPath.size() - 1; i++)
{
double x = (shortestPath.get(i).getX() - shortestPath.get(i + 1).getX());
double y = (shortestPath.get(i).getY() - shortestPath.get(i + 1).getY());
totalPathDistance += Math.sqrt(x * x + y * y);
}
return totalPathDistance;
}
}
|
package com.pdd.pop.sdk.http.api.response;
import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty;
import com.pdd.pop.sdk.http.PopBaseHttpResponse;
public class PddLogisticsCsSessionCloseResponse extends PopBaseHttpResponse{
/**
* response
*/
@JsonProperty("logistics_cs_session_close_response")
private LogisticsCsSessionCloseResponse logisticsCsSessionCloseResponse;
public LogisticsCsSessionCloseResponse getLogisticsCsSessionCloseResponse() {
return logisticsCsSessionCloseResponse;
}
public static class LogisticsCsSessionCloseResponse {
/**
* 是否成功
*/
@JsonProperty("is_success")
private Boolean isSuccess;
public Boolean getIsSuccess() {
return isSuccess;
}
}
} |
package it.univr.domain.safe.original;
import org.junit.Assert;
import org.junit.Test;
import it.univr.domain.safe.original.Bool;
import it.univr.domain.safe.original.Interval;
import it.univr.domain.safe.original.SAFEAbstractDomain;
import it.univr.main.Analyzer;
import it.univr.state.AbstractEnvironment;
import it.univr.state.Variable;
public class SAFEBooleanTest {
SAFEAbstractDomain domain = new SAFEAbstractDomain();
String dir = "src/test/resources/bool/";
@Test
public void testBool001() throws Exception {
String file = dir + "bool001.js";
AbstractEnvironment state = Analyzer.analyze(file, domain, false);
// State size
Assert.assertEquals(state.sizeStore(), 1);
Assert.assertEquals(state.sizeHeap(), 0);
// State values
Assert.assertEquals(state.getValue(new Variable("x")), new Bool(1));
}
@Test
public void testBool002() throws Exception {
String file = dir + "bool002.js";
AbstractEnvironment state = Analyzer.analyze(file, domain, false);
// State size
Assert.assertEquals(state.sizeStore(), 1);
Assert.assertEquals(state.sizeHeap(), 0);
// State values
Assert.assertEquals(state.getValue(new Variable("x")), new Bool(0));
}
@Test
public void testBool003() throws Exception {
String file = dir + "bool003.js";
AbstractEnvironment state = Analyzer.analyze(file, domain, false);
// State size
Assert.assertEquals(state.sizeStore(), 1);
Assert.assertEquals(state.sizeHeap(), 0);
// State values
Assert.assertEquals(state.getValue(new Variable("x")), new Bool(1));
}
@Test
public void testBool004() throws Exception {
String file = dir + "bool004.js";
AbstractEnvironment state = Analyzer.analyze(file, domain, false);
// State size
Assert.assertEquals(state.sizeStore(), 1);
Assert.assertEquals(state.sizeHeap(), 0);
// State values
Assert.assertEquals(state.getValue(new Variable("x")), new Bool(0));
}
@Test
public void testBool005() throws Exception {
String file = dir + "bool005.js";
AbstractEnvironment state = Analyzer.analyze(file, domain, false);
// State size
Assert.assertEquals(state.sizeStore(), 1);
Assert.assertEquals(state.sizeHeap(), 0);
// State values
Assert.assertEquals(state.getValue(new Variable("x")), new Bool(1));
}
@Test
public void testBool006() throws Exception {
String file = dir + "bool006.js";
AbstractEnvironment state = Analyzer.analyze(file, domain, false);
// State size
Assert.assertEquals(state.sizeStore(), 1);
Assert.assertEquals(state.sizeHeap(), 0);
// State values
Assert.assertEquals(state.getValue(new Variable("x")), new Bool(1));
}
@Test
public void testBool007() throws Exception {
String file = dir + "bool007.js";
AbstractEnvironment state = Analyzer.analyze(file, domain, false);
// State size
Assert.assertEquals(state.sizeStore(), 1);
Assert.assertEquals(state.sizeHeap(), 0);
// State values
Assert.assertEquals(state.getValue(new Variable("x")), new Bool(0));
}
@Test
public void testBool008() throws Exception {
String file = dir + "bool008.js";
AbstractEnvironment state = Analyzer.analyze(file, domain, false);
// State size
Assert.assertEquals(state.sizeStore(), 2);
Assert.assertEquals(state.sizeHeap(), 0);
// State values
Assert.assertEquals(state.getValue(new Variable("a")), new Interval("0", "+Inf"));
Assert.assertEquals(state.getValue(new Variable("x")), new Bool(2));
}
@Test
public void testBool009() throws Exception {
String file = dir + "bool009.js";
AbstractEnvironment state = Analyzer.analyze(file, domain, false);
// State size
Assert.assertEquals(state.sizeStore(), 1);
Assert.assertEquals(state.sizeHeap(), 0);
// State values
Assert.assertEquals(state.getValue(new Variable("x")), new Bool(1));
}
}
|
package practise;
public class GenericsTest<T>
{
T a;
T b;
public GenericsTest(T a, T b) {
super();
this.a = a;
this.b = b;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package human;
/**
*
* @author hugo
*/
public class FysikerDemo {
public static void main(String[] args) {
Fysiker numberOne = new Fysiker(25,"Achilles",2013);
Human numberTwo = new Human(22,"Johan");
System.out.println(numberOne.compareTo(numberTwo));
}
}
|
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* User: dexctor
* Date: 12-12-13
* Time: 下午4:18
* To change this template use File | Settings | File Templates.
*/
public class LoadingBalancing {
private static class Job implements Comparable<Job>
{
private String name;
private double time;
public Job(String name, double time)
{
this.name = name;
this.time = time;
}
public int compareTo(Job that)
{
if(time < that.time)
return -1;
else if(time > that.time)
return 1;
else
return 0;
}
public String toString()
{
return name + " : " + time;
}
}
private static class Process implements Comparable<Process>
{
public double time;
public int compareTo(Process that)
{
if(time < that.time)
return -1;
else if(time > that.time)
return 1;
else
return 0;
}
public void add(Job job)
{
time += job.time;
}
public String toString()
{
return time + "";
}
}
public static void main(String[] args)
{
int M = StdIn.readInt();
MinPQ<Process> pq =new MinPQ<Process>(M);
for(int i =0 ; i < M; ++i)
pq.insert(new Process());
int N = StdIn.readInt();
Job[] jobs = new Job[N];
for(int i = 0; i < N; ++i)
{
String name = StdIn.readString();
double time = StdIn.readDouble();
jobs[i] = new Job(name, time);
}
Arrays.sort(jobs);
for(int i = N - 1; i >= 0; --i)
{
Process p = pq.delMin();
p.add(jobs[i]);
pq.insert(p);
}
while(!pq.isEmpty())
{
StdOut.println(pq.delMin());
}
}
}
|
package hu.cehessteg.Stage;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import hu.cehessteg.Screen.MenuScreen;
import hu.csanyzeg.master.MyBaseClasses.Assets.AssetList;
import hu.csanyzeg.master.MyBaseClasses.Game.MyGame;
import hu.csanyzeg.master.MyBaseClasses.Scene2D.OneSpriteStaticActor;
import hu.csanyzeg.master.MyBaseClasses.Scene2D.PrettyStage;
import hu.csanyzeg.master.MyBaseClasses.Scene2D.ResponseViewport;
import hu.csanyzeg.master.MyBaseClasses.UI.MyLabel;
import static hu.cehessteg.Hud.TextBox.RETRO_FONT;
import static hu.cehessteg.Stage.MenuStage.BACKGROUND_TEXTURE;
public class IntroStage extends PrettyStage {
public static final String GDX_TEXTURE = "pic/logos/gdx.png";
public static final String CSANY_TEXTURE = "pic/logos/csany.png";
public static final String CSAPAT_TEXTURE = "pic/logos/csapat.png";
public static final String PENDROID_TEXTURE = "pic/logos/pendroid.png";
public static AssetList assetList = new AssetList();
static {
assetList.addTexture(GDX_TEXTURE);
assetList.addTexture(CSANY_TEXTURE);
assetList.addTexture(CSAPAT_TEXTURE);
assetList.addTexture(PENDROID_TEXTURE);
assetList.addFont(RETRO_FONT, RETRO_FONT, 32, Color.WHITE, AssetList.CHARS);
}
private OneSpriteStaticActor gdxLogo;
private OneSpriteStaticActor csanyLogo;
private OneSpriteStaticActor csapatLogo;
private OneSpriteStaticActor pendroidLogo;
private OneSpriteStaticActor bg;
private MyLabel copyright;
//endregion
//region Konstruktor
public IntroStage(MyGame game) {
super(new ResponseViewport(900), game);
}
//endregion
//region Absztrakt metódusok
@Override
public void assignment() {
bg = new OneSpriteStaticActor(game, BACKGROUND_TEXTURE);
gdxLogo = new OneSpriteStaticActor(game, GDX_TEXTURE);
csanyLogo = new OneSpriteStaticActor(game, CSANY_TEXTURE);
csapatLogo = new OneSpriteStaticActor(game, CSAPAT_TEXTURE);
pendroidLogo = new OneSpriteStaticActor(game, PENDROID_TEXTURE);
copyright = new MyLabel(game,"Copyright 2021 Céhessteg. Minden jog fenntartva.", new Label.LabelStyle(game.getMyAssetManager().getFont(RETRO_FONT), Color.WHITE)) {
@Override
public void init() {
setFontScale(1);
setAlignment(0);
}
};
}
@Override
public void setSizes() {
bg.setSize(getViewport().getWorldWidth(),getViewport().getWorldHeight());
}
@Override
public void setPositions() {
gdxLogo.setPosition(getViewport().getWorldWidth()/2-gdxLogo.getWidth()/2,getViewport().getWorldHeight()/2-gdxLogo.getHeight()/2);
pendroidLogo.setPosition(getViewport().getWorldWidth()/2-pendroidLogo.getWidth()-50, getViewport().getWorldHeight()/2-pendroidLogo.getHeight()/2);
csanyLogo.setPosition(getViewport().getWorldWidth()/2+50, getViewport().getWorldHeight()/2-csanyLogo.getHeight()/2);
copyright.setPosition(getViewport().getWorldWidth()/2-copyright.getWidth()/2, 20);
csapatLogo.setPosition(getViewport().getWorldWidth()/2-csapatLogo.getWidth()/2, getViewport().getWorldHeight()/2-csapatLogo.getHeight()/2);
}
@Override
public void addListeners() {
}
@Override
public void setZIndexes() {
}
@Override
public void addActors() {
addActor(bg);
addActor(gdxLogo);
addActor(csanyLogo);
addActor(copyright);
addActor(pendroidLogo);
addActor(csapatLogo);
for (Actor actor : getActors()) actor.setColor(1,1,1,0);
}
//endregion
//region Áttűnés metódusai
private float pElapsed;
private byte index = 0;
private float alpha = 0;
@Deprecated
private void fadeIn(OneSpriteStaticActor... actor) {
if (alpha < 0.95) alpha += 0.05;
else alpha = 1;
for (OneSpriteStaticActor actor1 : actor)
{
actor1.setAlpha(alpha);
}
}
@Deprecated
private void fadeOut(OneSpriteStaticActor... actor) {
if (alpha > 0.05) alpha -= 0.05;
else {
alpha = 0;
pElapsed = 0;
index++;
}
for (OneSpriteStaticActor actor1 : actor)
{
actor1.setAlpha(alpha);
}
}
//endregion
//region Act metódusai
@Override
public void act(float delta) {
super.act(delta);
if((1/6.0f) * elapsedTime < 1) bg.setAlpha((1/6.0f) * elapsedTime);
else bg.setAlpha(1);
switch (index) {
case 0: {
pElapsed += delta;
if (pElapsed < 0.75) fadeIn(gdxLogo);
else if (pElapsed > 1.5) fadeOut(gdxLogo);
break;
}
case 1: {
pElapsed += delta;
if (pElapsed < 0.75) fadeIn(csanyLogo,pendroidLogo);
else if (pElapsed > 1.5) fadeOut(csanyLogo,pendroidLogo);
break;
}
case 2:{
pElapsed += delta;
if (pElapsed < 0.75) {
fadeIn(csapatLogo);
} else if (pElapsed > 1){
copyright.setColor(1,1,1,elapsedTime-4.8f);
if (pElapsed > 2.5) {
fadeOut(csapatLogo);
copyright.setColor(1,1,1, alpha);
}
}
break;
}
}
if(elapsedTime > 6) {
csapatLogo.remove();
game.setScreenWithPreloadAssets(MenuScreen.class, true, new LoadingStage(game));
}
}
}
|
package com.example.hotel.service.paymethods;
import com.example.hotel.exceptions.EntityNotFoundException;
import com.example.hotel.model.paymethods.PayMethod;
import com.example.hotel.repository.paymethods.PayMethodRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@RequiredArgsConstructor
public class PayMethodServiceImpl implements PayMethodService {
private final PayMethodRepository payMethodRepository;
@Override
@Transactional(readOnly = true)
public List<PayMethod> findAll() {
List<PayMethod> payMethodList = payMethodRepository.findAll();
if(payMethodList.isEmpty()) throw new EntityNotFoundException("Pay Method not found");
return payMethodList;
}
}
|
package com.huaxiao47.just4fun.ui.home.recommend.banner;
import java.util.ArrayList;
import java.util.List;
public class BannerBean {
public String imgUrl;
public String title;
public String gotoUrl;
public BannerBean(String imgUrl, String title, String gotoUrl) {
this.imgUrl = imgUrl;
this.title = title;
this.gotoUrl = gotoUrl;
}
private static List<BannerBean> banners;
public static List<BannerBean> getTestData(){
if (banners == null){
banners = new ArrayList<>();
banners.add(new BannerBean("https://i0.hdslb.com/bfs/archive/6c472210a2f0f3be44ba4428dd40037d1a0d70a2.jpg@412w_232h_1c_100q.jpg","lla","sdf"));
banners.add(new BannerBean("https://i0.hdslb.com/bfs/archive/6c472210a2f0f3be44ba4428dd40037d1a0d70a2.jpg@412w_232h_1c_100q.jpg","lla","sdf"));
banners.add(new BannerBean("https://i0.hdslb.com/bfs/archive/6c472210a2f0f3be44ba4428dd40037d1a0d70a2.jpg@412w_232h_1c_100q.jpg","lla","sdf"));
banners.add(new BannerBean("https://i0.hdslb.com/bfs/archive/6c472210a2f0f3be44ba4428dd40037d1a0d70a2.jpg@412w_232h_1c_100q.jpg","lla","sdf"));
}
return banners;
}
}
|
package homework1.tasks;
import java.util.Scanner;
/**
* По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
* составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним,
* равнобедренным или равносторонним.
*/
public class Triangle {
public static void main(String[] args) {
int a, b, c;
try (Scanner in = new Scanner(System.in)){
System.out.println("Введите длины трех отрезков : ");
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
if (a + b > c && a + c > b && b + c > a){
if (a != b && b != c && a != c){
System.out.println(" Это разносторонний треугольник");
}else if (a == b && b == c ){
System.out.println("Это равносторонний треугольник");
}else {
System.out.println("Это равнобедренный треугольник");
}
}else{
System.out.println("Это не может быть треугольником");
}
}catch (Exception e){
System.out.println(e);
}
}
}
|
package com.gsccs.sme.test;
import java.util.Date;
import java.util.List;
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 com.gsccs.sme.api.domain.Sneed;
import com.gsccs.sme.api.domain.shop.Product;
import com.gsccs.sme.api.domain.site.Info;
import com.gsccs.sme.api.exception.ApiException;
import com.gsccs.sme.api.service.InfoServiceI;
import com.gsccs.sme.api.service.ProductServiceI;
import com.gsccs.sme.api.service.AccountServiceI;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:dubbo-server-consumer.xml")
public class ProductServiceTest {
@Autowired
private AccountServiceI userAPI;
@Autowired
private ProductServiceI productAPI;
@Test
public void add() throws Throwable {
Product product = new Product();
product.setAddtime(new Date());
product.setTitle("20160313测试");
productAPI.addProduct(product);
}
@Test
public void list() {
int page = 1;
int pagesize = 10;
try {
List<Product> list = productAPI.queryProductList(null, "addtime desc", page, pagesize);
System.out.println("end ###############"+list.size());
} catch (ApiException e) {
e.printStackTrace();
}
}
}
|
package com.aut.yuxiang.lbs_middleware.lbs_net.entity;
import java.util.ArrayList;
/**
* Created by yuxiang on 16/12/16.
*/
public class GeolocationRequestEntity {
public static final String API_KEY = "AIzaSyBpRDMmaOkiZoQduKGGCyhthwlofCDiFLg";
public static final String GEOLOCATION_URL = "https://www.googleapis.com/geolocation/v1/geolocate?key=" + API_KEY;
private int homeMobileCountryCode;
private int homeMobileNetworkCode;
private String radioType;
private String carrier;
private String considerIp;
private ArrayList<CellTower> cellTowers;
public GeolocationRequestEntity() {
}
public static class CellTower {
private int cellId;
private int locationAreaCode;
private int mobileCountryCode;
private int mobileNetworkCode;
private int age;
private int signalStrength;
private int timingAdvance;
public CellTower() {
}
public void setCellId(int cellId) {
this.cellId = cellId;
}
public void setLocationAreaCode(int locationAreaCode) {
this.locationAreaCode = locationAreaCode;
}
public void setMobileCountryCode(int mobileCountryCode) {
this.mobileCountryCode = mobileCountryCode;
}
public void setMobileNetworkCode(int mobileNetworkCode) {
this.mobileNetworkCode = mobileNetworkCode;
}
public void setAge(int age) {
this.age = age;
}
public void setSignalStrength(int signalStrength) {
this.signalStrength = signalStrength;
}
public void setTimingAdvance(int timingAdvance) {
this.timingAdvance = timingAdvance;
}
}
public void setHomeMobileCountryCode(int homeMobileCountryCode) {
this.homeMobileCountryCode = homeMobileCountryCode;
}
public void setHomeMobileNetworkCode(int homeMobileNetworkCode) {
this.homeMobileNetworkCode = homeMobileNetworkCode;
}
public void setRadioType(String radioType) {
this.radioType = radioType;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
public void setConsiderIp(String considerIp) {
this.considerIp = considerIp;
}
public void setCellTowers(ArrayList<CellTower> cellTowers) {
this.cellTowers = cellTowers;
}
}
|
package de.varylab.discreteconformal.functional.node;
import de.jtem.halfedge.Edge;
public class ConformalEdge <
V extends ConformalVertex<V, E, F>,
E extends ConformalEdge<V, E, F>,
F extends ConformalFace<V, E, F>
> extends Edge<V, E, F> {
protected double
lambda = 1.0,
alpha = 0.0,
beta = 0.0,
theta = 0.0,
phi = Math.PI;
protected Integer
solverIndex = -1;
public Integer getSolverIndex() {
return solverIndex;
}
public void setSolverIndex(Integer solverIndex) {
this.solverIndex = solverIndex;
}
public double getLambda() {
return lambda;
}
public void setLambda(double lambda) {
this.lambda = lambda;
}
public double getAlpha() {
return alpha;
}
public void setAlpha(double alpha) {
this.alpha = alpha;
}
public double getPhi() {
return phi;
}
public void setPhi(double phi) {
this.phi = phi;
}
public double getTheta() {
return theta;
}
public void setTheta(double theta) {
this.theta = theta;
}
public double getBeta() {
return beta;
}
public void setBeta(double beta) {
this.beta = beta;
}
@Override
public void copyData(E e) {
lambda = e.lambda;
alpha = e.alpha;
beta = e.beta;
theta = e.theta;
solverIndex = e.solverIndex;
};
}
|
package go;
import java.awt.geom.Point2D;
import java.util.Scanner;
/**
*Classe Joueur
* @author bchevill
*/
public class Joueur {
private String couleur;
private int pionCapture;
// Constructeur
/**
*
*/
public Joueur(String couleur){
this.couleur=couleur;
this.pionCapture=0;
}
//Getters and Setters
/**
*
* @return couleur La couleur du joueur
*/
public String getCouleur(){
return couleur;
}
public int getPionCapture(){
return pionCapture;
}
public void addPionCapture(int nb){
this.pionCapture+=nb;
}
public int entrerX(int pierre, int taille){
int pierreX = pierre;
//On demande à l'utilisateur de rentrer l'abcisse de la pierre qu'il veut poser ou s'il veut passer son tour
while (pierreX < -1 || pierreX > taille || pierreX == 0) {
Scanner scannerPosX = new Scanner(System.in);
System.out.println("L'abscisse de la case où vous voulez poser votre pierre : (Entre 1 et " + Integer.toString(taille) + " ou -1 pour passer son tour) :"); //NOSONAR
while (!scannerPosX.hasNextInt()) {
System.out.println("Ce n'est pas un nombre !"); //NOSONAR
System.out.println("L'abscisse de la case où vous voulez poser votre pierre : (Entre 1 et " + Integer.toString(taille) + " ou -1 pour passer son tour) :"); //NOSONAR
scannerPosX.next();
}
pierreX = scannerPosX.nextInt();
}
System.out.println("Vous avez rentré l'abscisse : " + pierreX); //NOSONAR
return pierreX;
}
public int entrerY(int taille){
//On demande à l'utilisateur de rentrer l'ordonnée de la pierre qu'il veut poser
int pierreY = -1;
while (pierreY < 0 || pierreY > taille) {
Scanner scannerPosY = new Scanner(System.in);
System.out.println("L'ordonnée de la case où vous voulez poser votre pierre : (Entre 1 et " + Integer.toString(taille) + " ou -1 pour passer son tour) :"); //NOSONAR
while (!scannerPosY.hasNextInt()) {
System.out.println("Ce n'est pas un nombre !"); //NOSONAR
System.out.println("L'ordonnée de la case où vous voulez poser votre pierre : (Entre 1 et " + Integer.toString(taille) + " ou -1 pour passer son tour) :"); //NOSONAR
scannerPosY.next();
}
pierreY = scannerPosY.nextInt();
}
System.out.println("Vous avez rentré l'ordonné : " + pierreY); //NOSONAR
return pierreY;
}
public void jouer(PlateauDeJeu plateau, boolean[] passerTour, int taille){
//int qui permet de vérfier que la pose de pierre s'est bien passé
int okAjouterPierre = -1;
//int qui permet de déterminer l'ordonnée de la nouvelle pierre OU d'indiquer que le joueur veut passer son tour (dans ce cas là =-1)
// Sonar se plaint de la présence d'un "magic number", mais nous n'allons pas créer une constante d'initialisation de la variable...
int pierreX = -2; //NOSONAR
while (okAjouterPierre != 0 && pierreX != -1) {
//On demande à l'utilisateur de rentrer l'abcisse de la pierre qu'il veut poser ou s'il veut passer son tour
pierreX = this.entrerX(pierreX, taille);
//Le joueur passe son tour ?
if (pierreX == -1) {
//On retient que le joueur passe son tour
if (Go.BLANC.equals(this.getCouleur())) {
System.out.println("Le Joueur Blanc passe son tour \n"); //NOSONAR
passerTour[0] = true;
} else {
System.out.println("Le Joueur Noir passe son tour \n"); //NOSONAR
passerTour[1] = true;
}
} else {
//On demande à l'utilisateur de rentrer l'ordonnée de la pierre qu'il veut poser
int pierreY=this.entrerY(taille);
//On ajoute la pierre au plateau
Point2D position = new Point2D.Double(pierreX - 1, pierreY - 1);
Pierre pierre = new Pierre(this.getCouleur(), position);
// On ajoute la pierre. Si ce n'est pas possible, on boucle
okAjouterPierre = plateau.ajouterPierre(pierre, this);
plateau.afficherPose(okAjouterPierre);
}
}
}
}
|
package com.onlyu.reactiveprog.repositories.reactive;
import com.onlyu.reactiveprog.domain.User;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
public interface UserReactiveRepository extends ReactiveMongoRepository<User, String> {
}
|
package com.programapprentice.app;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* User: program-apprentice
* Date: 8/22/15
* Time: 11:06 PM
*/
public class PermutationSequence_Test {
PermutationSequence_60 obj = new PermutationSequence_60();
@Test
public void test1() {
int n = 2;
int k = 1;
String expected = "12";
String actual = obj.getPermutation(n, k);
assertEquals(expected, actual);
}
@Test
public void test2() {
int n = 4;
int k = 3;
String expected = "1324";
String actual = obj.getPermutation(n, k);
assertEquals(expected, actual);
}
@Test
public void test3() {
int n = 3;
int k = 4;
String expected = "231";
String actual = obj.getPermutation(n, k);
assertEquals(expected, actual);
}
@Test
public void test4() {
int n = 4;
int k = 2;
String expected = "1243";
String actual = obj.getPermutation(n, k);
assertEquals(expected, actual);
}
@Test
public void test5() {
int n = 4;
int k = 9;
String expected = "2314";
String actual = obj.getPermutation(n, k);
assertEquals(expected, actual);
}
} |
package falcons.plugin;
import java.io.Serializable;
public class PluginCall implements Serializable {
private String pluginID;
private AbstractPluginData pluginData;
private int destination;
private int sender;
/**
* Creates a new PluginCall based on a plugin.
*
* @param plugin
* The plugin sending the call.
* @param pluginData
* The AbstractPluginData-object that contains all the relevant
* information for the call.
* @param destination
* The int that is an ID from the servers list of clients.
* @param sender
* The ID of the client that's sending the PluginCall.
*/
public PluginCall(AbstractPlugin plugin, AbstractPluginData pluginData, int destination, int sender) {
this.pluginID = plugin.getClass().getAnnotation(Plugin.class).pluginID();
this.pluginData = pluginData;
this.destination = destination;
this.sender = sender;
}
/**
* Creates a new PluginCall based on the name of a plugin as a String.
*
* @param pluginID
* The ID of the plugin sending the call.
* @param pluginData
* The AbstractPluginData-object that contains all the relevant
* information for the call.
* @param destination
* The int that is an ID from the servers list of clients.
* @param sender
* The ID of the client that's sending the PluginCall.
*/
public PluginCall(String pluginID, AbstractPluginData pluginData, int destination, int sender) {
this.pluginID = pluginID;
this.pluginData = pluginData;
this.destination = destination;
this.sender = sender;
}
/**
*
* @return Returns the PluginID as a String.
*/
public String getPluginID() {
return pluginID;
}
/**
*
* @return Returns the AbstractPluginData associated with the PluginCall.
*/
public AbstractPluginData getPluginData() {
return pluginData;
}
/**
*
* @return Returns the destination of the PluginCall as an int.
*/
public int getDestination() {
return destination;
}
/**
*
* @return Returns the ID of the client that sent the PluginCall.
*/
public int getSender() {
return sender;
}
/**
*
* @param sender
* Sets the sender of the PluginCall.
*/
public void setSender(int sender) {
this.sender = sender;
}
}
|
package com.test;
public class Test5 {
int id;
String name;
public static void main(String[] args) {
Test5 t5=new Test5();
System.out.println(t5.id);
System.out.println(t5.name);
}
}
|
package vnfoss2010.smartshop.serverside.database;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* <code>ServiceResult</code> presents a response from <code>RemoteService</code> <br/>
* <b>Usage</b>:
* <ul><li><code>isOK</code> check RPC service call is OK or not
* <li><code>result</code> developer can use generic type for return type. Before getting the result, call isOK() to make sure everything 's OK
* <li><code>message</code> the message server returns to indicate any error here
* </ul>
* @author Tam Vo
*/
public class ServiceResult<ResultType> implements IsSerializable{
private boolean isOK = false;
private String message = "";
private ResultType result = null;
/**
* Default constructor
*/
public ServiceResult() {
}
/**
* @param isOK successes or fails
* @param message message return from <code>RemoteService</code>
*/
public ServiceResult(boolean isOK, String message) {
this.isOK = isOK;
this.message = message;
}
/**
* Specify this <code>ServiceResult</code> successes or not
* @param isOK <code>true</code> if successes
* <br /><code>false</code> if fails
*/
public void setOK(boolean isOK) {
this.isOK = isOK;
}
/**
* Determine this <code>ServiceResult</code> is successes or not
* @return <code>true</code> if successes
* <br /><code>false</code> if fails
*/
public boolean isOK() {
return isOK;
}
/**
* Change message from <code>RemoteService</code>
* @param message <code>message</code> is message from <code>RemoteService</code>
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Get message from <code>RemoteService</code>
* @return message from <code>RemoteService</code>
*/
public String getMessage() {
return message;
}
/**
* Get object that <code>RemoteService</code> return
* @return object that <code>RemoteService</code> return
*/
public ResultType getResult() {
return result;
}
/**
* Change object that <code>RemoteService</code> return
* @param result <code>result</code> is an object that <code>RemoteService</code> return
*/
public void setResult(ResultType result) {
this.result = result;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ServiceResult [isOK=" + isOK + ", message=" + message
+ ", result=" + result + "]";
}
}
|
package com.devpmts.dropaline.gui;
public class DROPALINE_GUI {
public static final String LINE_INPUT = "line_input";
public static final String NOTE_INPUT = "note_input";
public static final String ACTIVE_FIELD = "active_field";
public static final String SETTINGS_WINDOW_ID = "com.devpmts.dropaline.window.settings";
public static final String CREDENTIALS_WINDOW_ID = "com.devpmts.dropaline.window.credentials";
}
|
package org.vkedco.mobappdev.bindsumlib;
import android.os.Parcel;
import android.os.Parcelable;
public class SumResponse implements Parcelable {
long mSum = 0;
public SumResponse(long sum) {
mSum = sum;
}
public long getSum() { return mSum; }
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeLong(mSum);
}
public static final Parcelable.Creator<SumResponse> CREATOR = new Parcelable.Creator<SumResponse>() {
// both these methods must be implemented
public SumResponse createFromParcel(Parcel in) {
long sum = in.readLong();
return new SumResponse(sum);
}
public SumResponse[] newArray(int size) {
return new SumResponse[size];
}
};
}
|
package com.androidvoyage.bmc.utils;
import android.util.Log;
import com.androidvoyage.bmc.common.CommonConstants;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* @Author Siddhesh
* @Contributor Mayuri
*/
public class DateTimeUtils {
/**
* returns true if compareDate is after start(date)
*
* @param date
* @param dateToCompare
* @return
*/
public static boolean isAfterDate(String date, String dateToCompare) {
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT, Locale.getDefault());
Date strDate = null, compareDate = null;
try {
compareDate = sdf.parse(dateToCompare);
strDate = sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return (compareDate != null && strDate != null
&& (compareDate.after(strDate)));
}
public static boolean isOneDayEvent(String date, String dateToCompare) {
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_TIME_FORMAT, Locale.getDefault());
long oneDay = 1000 * 60 * 60 * 24;
long startLongTime = 0, endLongTime = 0;
Date strDate = null, compareDate = null;
try {
compareDate = sdf.parse(dateToCompare);
startLongTime = compareDate.getTime();
strDate = sdf.parse(date);
endLongTime = strDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
long diff = startLongTime - endLongTime;
return diff < oneDay;
}
public static boolean isSameDate(String date, String dateToCompare) {
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT, Locale.getDefault());
Date strDate = null, compareDate = null;
try {
compareDate = sdf.parse(dateToCompare);
strDate = sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return compareDate.compareTo(strDate) == 0;
}
public static boolean isAfterTime(String date, String dateToCompare) {
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_TIME_FORMAT, Locale.ENGLISH);
Date strDate = null, compareDate = null;
try {
compareDate = sdf.parse(dateToCompare);
strDate = sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return (strDate.getTime() <= compareDate.getTime());
}
public static boolean isOldDate(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT);
Date strDate = sdf.parse(date);
return new Date().before(strDate);
} catch (ParseException e) {
Log.d("CATH OLD DATE", "isOldDate: " + e.getMessage());
}
return false;
}
public static boolean isOldReadableDate(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT);
Date strDate = sdf.parse(date);
return strDate.before(new Date());
} catch (ParseException e) {
Log.d("CATH OLD DATE", "isOldDate: " + e.getMessage());
}
return false;
}
public static boolean isOldTime(String time) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_TIME_FORMAT, Locale.getDefault());
Calendar now = Calendar.getInstance();
Date c_date = sdf.parse(now.get(Calendar.HOUR) + ":"
+ now.get(Calendar.MINUTE)
+ " " + ((now.get(Calendar.AM_PM) == Calendar.AM) ? "am" : "pm"));
return sdf.parse(time).before(c_date);
} catch (ParseException e) {
return false;
}
}
/*
* @author Mayuri*/
public static String convertUTCToReadableDateTimeFormat(String UTCFormatDateTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
try {
Date d1 = format.parse(UTCFormatDateTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_TIME_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = UTCFormatDateTime;
} catch (NullPointerException e) {
e.printStackTrace();
date = UTCFormatDateTime;
}
return date;
}
public static String convertReadableDateTimeToUTCFormat(String ReadableFormatDateTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.READABLE_DATE_TIME_FORMAT, Locale.getDefault());
try {
Date d1 = format.parse(ReadableFormatDateTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
// sdf.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = ReadableFormatDateTime;
}
return date;
}
public static String getUTCDateTimeFormat(String ReadableFormatDateTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.READABLE_DATE_TIME_FORMAT, Locale.getDefault());
try {
Date d1 = format.parse(ReadableFormatDateTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = ReadableFormatDateTime;
}
return date;
}
public static String getFormattedDateTime(String dateTime, String fromFormat, String toFormat, boolean toUTC) {
String date = null;
DateFormat format = new SimpleDateFormat(fromFormat, Locale.getDefault());
try {
Date d1 = format.parse(dateTime);
SimpleDateFormat sdf = new SimpleDateFormat(toFormat, Locale.getDefault());
if (toUTC) {
sdf.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
}
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = dateTime;
}
return date;
}
public static String convertUTCDateToReadableDateFormat(String UTCFormatDate) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.UTC_DATE_FORMAT, Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
try {
Date d1 = format.parse(UTCFormatDate);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = UTCFormatDate;
}
return date;
}
public static String convertReadableDateToUTCDateFormat(String UTCFormatDate) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT, Locale.getDefault());
try {
Date d1 = format.parse(UTCFormatDate);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.UTC_DATE_FORMAT, Locale.getDefault());
// sdf.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = UTCFormatDate;
}
return date;
}
public static String convertReadableDateToUTCDateTimeFormat(String UTCFormatDate) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT, Locale.getDefault());
try {
Date d1 = format.parse(UTCFormatDate);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
// sdf.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = UTCFormatDate;
}
return date;
}
public static String convertUTCTimeToReadableTimeFormat(String UTCFormatTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.UTC_TIME_FORMAT, Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
try {
Date d1 = format.parse(UTCFormatTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_TIME_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = UTCFormatTime;
}
return date;
}
public static String convertUTCTimeDateToReadableTimeFormat(String UTCFormatTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
try {
Date d1 = format.parse(UTCFormatTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_TIME_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = UTCFormatTime;
}
return date;
}
public static String convertUTCTimeDateToReadableDateFormat(String UTCFormatTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
try {
Date d1 = format.parse(UTCFormatTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = UTCFormatTime;
}
return date;
}
public static String convertReadableTimeToUTCTimeFormat(String ReadableFormatTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.READABLE_TIME_FORMAT, Locale.getDefault());
try {
Date d1 = format.parse(ReadableFormatTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.UTC_TIME_FORMAT, Locale.getDefault());
// sdf.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = ReadableFormatTime;
}
return date;
}
public static String getReadableDateFromUTCDateTimeFormat(String ReadableFormatTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
try {
Date d1 = format.parse(ReadableFormatTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = ReadableFormatTime;
}
return date;
}
public static String getReadableTimeFromUTCDateTimeFormat(String ReadableFormatTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
try {
Date d1 = format.parse(ReadableFormatTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_TIME_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = ReadableFormatTime;
}
return date;
}
/**
* @param ReadableFormatTime : CommonConstants.DATE_TIME_PICKER_FORMAT
* @return : CommonConstants.READABLE_DATE_TIME_FORMAT in string format
* @author Mayuri
* should be used only from Date time picker,
* always check incoming format
* keep CommonConstants.DATE_TIME_PICKER_FORMAT as incoming format
*/
public static String convertDateTimePickerToReadableDateTimeFormat(String ReadableFormatTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.DATE_TIME_PICKER_FORMAT, Locale.getDefault());
try {
Date d1 = format.parse(ReadableFormatTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_TIME_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = ReadableFormatTime;
}
return date;
}
/**
* @param ReadableFormatTime : CommonConstants.DATE_PICKER_FORMAT
* @return : CommonConstants.READABLE_DATE_FORMAT in string format
* @author Mayuri
* should be used only from Date time picker,
* always check incoming format
* keep CommonConstants.DATE_PICKER_FORMAT as incoming format
*/
public static String convertDatePickerToReadableDateFormat(String ReadableFormatTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.DATE_PICKER_FORMAT, Locale.getDefault());
try {
Date d1 = format.parse(ReadableFormatTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = ReadableFormatTime;
}
return date;
}
/**
* @param ReadableFormatTime : CommonConstants.DATE_PICKER_FORMAT
* @return : CommonConstants.READABLE_DATE_FORMAT in string format
* @author Mayuri
* should be used only from Date time picker,
* always check incoming format
* keep CommonConstants.DATE_PICKER_FORMAT as incoming format
*/
public static String convertTimePickerToReadableTimeFormat(String ReadableFormatTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.TIME_PICKER_FORMAT, Locale.getDefault());
try {
Date d1 = format.parse(ReadableFormatTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_TIME_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = ReadableFormatTime;
}
return date;
}
public static Date getDateFromUTCString(String UTCFormatDate) {
Date date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
try {
date = format.parse(UTCFormatDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static String getCurrentReadableDateTimeFormat() {
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_TIME_FORMAT, Locale.getDefault());
return sdf.format(currentTime);
}
public static String getCurrentUTCDateTimeFormat() {
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone(CommonConstants.UTC));
return sdf.format(currentTime);
}
public static String getCurrentReadableDateFormat() {
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT, Locale.getDefault());
return sdf.format(currentTime);
}
public static String getCurrentReadableTimeFormat() {
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_TIME_FORMAT, Locale.getDefault());
return sdf.format(currentTime);
}
public static String hoursFormat(String ReadableHours) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.READABLE_TIME_FORMAT, Locale.getDefault());
try {
Date d1 = format.parse(ReadableHours);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.HOURS_PICKER_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = ReadableHours;
}
return date;
}
public static long getTimeDifference(String startDate) {
Date eData = getDateFromUTCString(startDate);
return Calendar.getInstance().getTime().getTime() - eData.getTime();
}
public static int getTimeDifference(Date startDate) {
Calendar a = Calendar.getInstance();
a.setTime(startDate);
Calendar b = Calendar.getInstance();
int diff = b.get(Calendar.YEAR) - a.get(Calendar.YEAR);
if (a.get(Calendar.MONTH) > b.get(Calendar.MONTH) ||
(a.get(Calendar.MONTH) == b.get(Calendar.MONTH) && a.get(Calendar.DATE) > b.get(Calendar.DATE))) {
diff--;
}
return diff;
}
public static String getAgeFromDate(int dob) {
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, - dob);
c.add(Calendar.DAY_OF_MONTH, - 1); // removed extra day to get approx age grater then 18.
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
return sdf.format(c.getTime());
}
public static Calendar getSelectedDate(String apiDateTime) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat parser = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT);
Date date;
try {
date = parser.parse(apiDateTime);
calendar.setTime(date);
} catch (Exception e) {
e.printStackTrace();
}
return calendar;
}
public static Calendar getReadableDate(String apiDateTime) {
Calendar calendar = Calendar.getInstance();
Date date;
try {
date = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT).parse(apiDateTime);
calendar.setTime(date);
} catch (Exception e) {
e.printStackTrace();
}
return calendar;
}
public static String convertUTCTimeDateToReadableDateFormatWithoutFormat(String UTCFormatTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
try {
Date d1 = format.parse(UTCFormatTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.READABLE_DATE_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = UTCFormatTime;
}
return date;
}
public static String convertUTCDateToUTCTimeDateTimeWithoutFormat(String UTCFormatTime) {
String date = null;
DateFormat format = new SimpleDateFormat(CommonConstants.UTC_DATE_FORMAT, Locale.getDefault());
try {
Date d1 = format.parse(UTCFormatTime);
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstants.UTC_DATE_TIME_FORMAT, Locale.getDefault());
date = sdf.format(d1);
} catch (ParseException e) {
e.printStackTrace();
date = UTCFormatTime;
}
return date;
}
}
|
package com.mobiquityinc.packer;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import com.mobiquityinc.exception.APIException;
public class Packer {
private Packer() {
}
public static String pack(String filePath) throws APIException {
List<Package> packageList = extractPackagesFromFile(filePath); // Extract the packages from file
StringBuilder sb = new StringBuilder(); // Holds the result of the pack processing
// Loop through packages and get the best set for each one
packageList.stream()
.forEach(p -> {
sb.append(p.getBestSet() + "\n");
});
return sb.toString();
}
/**
* This method receive a file with the input nedded to mount packages. Each line of the file should
* represent a Package with its max weight and its items. Eg: 34 : (1,23.45,€45.0) (2,45.5,€89)
* @param filePath - The absolute path of the input file
* @return A list of Package with it items
* @throws APIException
*/
public static List<Package> extractPackagesFromFile(String filePath) throws APIException {
try (Stream<String> str = Files.lines(Paths.get(filePath))) {
return Packer.extractPackagesFromStream(str);
} catch(IOException ioEx) {
throw new APIException(
String.format("An exception occurred reading file: '%s'",
filePath), ioEx);
}
}
/**
* Parses the package information from a Stream of Strings. It will consider each line separeted by a line break as
* a Package information so it can parse it and mount the package.
* @param str
* @return
* @throws APIException
*/
public static List<Package> extractPackagesFromStream(Stream<String> str) throws APIException {
final List<Package> packageList = new ArrayList<>();
// Loop through the lines (\n) inside the str
str.forEach(apiExceptionThrower(l -> {
// Check if the current line l is in the expected format.
if (!isLineSyntaxOk(l)) {
throw new APIException(String.format("The syntax of line '%s' is incorrect.", l));
}
final String[] weightAndItems = l.split(":"); // Split the line by the colon so we can separete the package weight and items
final String[] items = weightAndItems[1].trim().split(" "); // Split the right side of the above split by space to get the individual items
final Package pkg = new Package(Double.parseDouble(weightAndItems[0])); // Start to mount the Package
// Insert items into the package
Arrays.stream(items)
.forEach(apiExceptionThrower((String item) -> {
// Remove (, ) and € characteres and split by ,
String[] itemParts =
item.replace("(", "")
.replace(")", "")
.replace("€", "")
.trim().split(",");
// Mount the Package Item
pkg.addItem(new PackageItem(Integer.parseInt(itemParts[0]),
Double.parseDouble(itemParts[1]),
Double.parseDouble(itemParts[2])));
}));
packageList.add(pkg);
}));
return packageList;
}
/**
* This method is responsible to check if a line has the correct syntax
* @param line A string representing a line from a file
* @return true if the line has the correct syntax, false otherwise.
*/
public static boolean isLineSyntaxOk(String line) {
return Pattern
.matches("\\d+ ?\\: ?(\\(\\d+\\,\\d+\\.?\\d{0,2}\\,\\€?\\d+\\.?\\d{0,2}\\) )*(\\(\\d+\\,\\d+\\.?\\d{0,2}\\,\\€?\\d+\\.?\\d{0,2}\\)) ?\\n?",
line);
}
/**
* Method to be called on lambda to throw an Checked Exception
* @author Lucas Henrique Vicente <lucashv@gmail.com>
*/
private static <T> Consumer<T> apiExceptionThrower(Readable<T, APIException> obj) throws APIException {
return i -> {
try {
obj.accept(i);
} catch (APIException e) {
throw new RuntimeException(e);
}
};
}
/**
* Wrapper interface so we can throw a Checked Exception from inside a lambda
* @author lucas
*/
@FunctionalInterface
private interface Readable<T, E extends Exception> {
void accept(T l) throws E;
}
}
|
package com.edgit.server.jsf;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.stream.Collectors;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import com.edgit.server.domain.User;
import com.edgit.server.jsf.handlers.FilePathHandler;
@RequestScoped
public class FileUploader {
@Inject
private UserManager userManager;
@EJB
private FilePathHandler filepathHandler;
@EJB
private RepositoryManager repositoryManager;
private User getCurrentUser() {
return userManager.getCurrentUser();
}
public String upload(Part part) throws ServletException, IOException {
File userRepository = filepathHandler.getUserRepository(getCurrentUser());
for (Part p : getAllParts(part)) {
String path = p.getSubmittedFileName();
File file = new File(userRepository, path);
writeOnDisk(p, file);
persist(path);
}
// No redirection anymore. Just using AJAX to refresh a component
return "homepage"; /* ?faces-redirect=true */
}
private void writeOnDisk(Part p, File file) throws IOException {
try (InputStream input = p.getInputStream()) {
filepathHandler.push(getCurrentUser(), input, file.toPath());
}
}
private void persist(String filepath) {
Path path = Paths.get(filepath);
Path directory = filepathHandler.getDirectory(path);
String filename = filepathHandler.getFilename(path);
repositoryManager.createEntry(directory, filename, "(Todo)");
}
private static Collection<Part> getAllParts(Part part) throws ServletException, IOException {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
return request.getParts().stream().filter(p -> part.getName().equals(p.getName())).collect(Collectors.toList());
}
} |
package be.tcla.bookinventory.repository;
import be.tcla.bookinventory.mapper.EnumMapper;
import be.tcla.bookinventory.model.Book;
import be.tcla.bookinventory.model.Genre;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Types;
import java.util.List;
@Repository
public class BookRepositoryJDBCImpl implements BookRepository {
private final JdbcTemplate jdbcTemplate;
@Autowired
public BookRepositoryJDBCImpl(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public int addBook(Book book) {
String sql ="INSERT INTO spring.book VALUES (null, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
return
jdbcTemplate.update(sql, ps -> {
ps.setString(1,book.getISBN());
ps.setString(2,book.getAuthor());
ps.setBoolean(3,book.isEbook());
if(book.getGenre() == null){
ps.setNull(4,java.sql.Types.INTEGER);
}
else ps.setInt(4,book.getGenre().ordinal());
if(book.getGenre() == null){
ps.setNull(5, Types.INTEGER);
}else ps.setInt(5,book.getLanguage().ordinal());
ps.setInt(6,book.getPages());
ps.setString(7,book.getPublisher());
ps.setString(8,book.getSubject());
ps.setString(9,book.getTitle());
});
//return 1;}
// catch (Exception ex){
// return 0;
// }
}
@Override
public int updateBook(Book book) {
String sql = "UPDATE book SET author=?, ebook=?, genre= ?, isbn= ?, language= ?, pages= ?,publisher=?, subject= ?, title= ?" +
" WHERE id = ? ";
return
jdbcTemplate.update(sql, ps -> {
ps.setString(4,book.getISBN());
ps.setString(1,book.getAuthor());
ps.setBoolean(2,book.isEbook());
if(book.getGenre() == null){
ps.setNull(3,java.sql.Types.INTEGER);
}
else ps.setInt(3,book.getGenre().ordinal());
if(book.getGenre() == null){
ps.setNull(5, Types.INTEGER);
}else ps.setInt(5,book.getLanguage().ordinal());
ps.setInt(6,book.getPages());
ps.setString(7,book.getPublisher());
ps.setString(8,book.getSubject());
ps.setString(9,book.getTitle());
ps.setInt(10,book.getId());
});
}
@Override
public int deleteBook(Book book) {
String sql = "DELETE FROM book WHERE id=?";
return
jdbcTemplate.update(sql,ps->{
ps.setInt(1,book.getId());
});
}
@Override
public List<Book> findAll() {
return jdbcTemplate.query("SELECT * FROM book", (resultSet, i) -> {
Book book = new Book();
book.setAuthor(resultSet.getString("author"));
book.setTitle(resultSet.getString("title"));
book.setEbook(resultSet.getBoolean("ebook"));
book.setISBN(resultSet.getString("isbn"));
book.setPages(resultSet.getInt("pages"));
book.setPublisher(resultSet.getString("publisher"));
book.setSubject(resultSet.getString("subject"));
book.setId(resultSet.getInt("id"));
//TODO: ENUMS MAPPEN
//System.out.println(resultSet.getInt("genre"));
if(resultSet.getString("genre")!= null) {
book.setGenre(EnumMapper.mapToGenre(Integer.parseInt(resultSet.getString("genre"))));
}
if(resultSet.getString("language")!=null){
book.setLanguage(EnumMapper.mapToLanguage(Integer.parseInt(resultSet.getString("language"))));
}
return book;
});
}
@Override
public List<Book> findByAuthor(String author) {
// String sql = "Select * from book where author like ?";
// return jdbcTemplate.query(sql,(rs,i)->{
// rs.setString(1,author);
// });
return null;
}
@Override
public List<be.tcla.bookinventory.model.Book> findByGenre(Genre genre) {
return null;
}
@Override
public List<be.tcla.bookinventory.model.Book> findByKeyword(String keyword) {
return null;
}
@Override
public List<be.tcla.bookinventory.model.Book> findByEbooks(boolean ebook) {
return null;
}
@Override
public be.tcla.bookinventory.model.Book findByISBN(String isbn) {
return null;
}
@Override
public be.tcla.bookinventory.model.Book findByTitleAndAuthor(String title, String author) {
return null;
}
}
|
package irix.measurement.service;
public interface MeasuringPeriodImp {
public String getStartTime();
public String getEndTime() ;
}
|
package ua.siemens.dbtool.dao.hibernate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import ua.siemens.dbtool.dao.ActivityDAO;
import ua.siemens.dbtool.model.entities.Activity;
import ua.siemens.dbtool.model.entities.User;
import ua.siemens.dbtool.model.enums.ActivityType;
import javax.persistence.Query;
import java.time.LocalDate;
import java.util.Collection;
/**
* The impementation of {@link ActivityDAO} interface
*
* @author Perevoznyk Pavlo
* creation date 10 May 2017
* @version 1.0
*/
@Repository
public class ActivityDAOhiber extends GenericDAOhiber<Activity, Long> implements ActivityDAO {
private static final Logger LOG = LoggerFactory.getLogger(ActivityDAOhiber.class);
private final String FIND_BY_PERIOD_PLANED = "from Activity where startDate <= :toDate and endDate >= :fromDate";
private final String FIND_BY_PERIOD_FACT = "from Activity where actualStartDate <= :toDate and actualEndDate >= :fromDate";
private final String FIND_BY_USER_AND_PERIOD = "from Activity where startDate <= :toDate and endDate >= :fromDate and executor = :user";
private final String FIND_BY_JOB_ID = "from Activity where job_id = :jobId";
private final String FIND_MAX_ORDINAL = "select max(act.ordinalNumber) from Activity act where job_id = :jobId and act.activityType = :actType";
public ActivityDAOhiber() {
super(Activity.class);
}
@Override
public Collection<Activity> findByPeriodPlaned(LocalDate fromDate, LocalDate toDate) {
Query query = entityManager.createQuery(FIND_BY_PERIOD_PLANED);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
return query.getResultList();
}
@Override
public Collection<Activity> findByPeriodFact(LocalDate fromDate, LocalDate toDate) {
Query query = entityManager.createQuery(FIND_BY_PERIOD_FACT);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
return query.getResultList();
}
@Override
public Collection<Activity> findByUserAndPeriod(User user, LocalDate fromDate, LocalDate toDate) {
Query query = entityManager.createQuery(FIND_BY_USER_AND_PERIOD);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
query.setParameter("user", user);
return query.getResultList();
}
@Override
public Collection<Activity> findByJobID(Long jobId) {
Query query = entityManager.createQuery(FIND_BY_JOB_ID);
query.setParameter("jobId", jobId);
return query.getResultList();
}
@Override
public Integer getMaxOrdinalNumber(Long jobId, ActivityType activityType) {
Query query = entityManager.createQuery(FIND_MAX_ORDINAL);
query.setParameter("jobId", jobId);
query.setParameter("actType", activityType);
return (Integer) query.getSingleResult();
}
}
|
package com.company.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.company.Maintenance;
import com.company.Ticket;
class Maintenance_Test {
@Test
void test() {
Maintenance test = new Maintenance();
assertNotNull(test.CompleteTicket(new Ticket("test", 0, new java.util.Date(), false)));
assertNotNull(test.generateOrderRequest());
}
}
|
/*
* 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 View;
import Controller.*;
import Controller.HibernateUtil;
import Controller.Medium_controller;
import Controller.Item_controller;
import Model.Item;
import Model.Medium;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
/**
*
* @author Anthony
*/
public class ItemsView extends javax.swing.JFrame {
private Application_controller app = new Application_controller();
private Item_controller itemController = new Item_controller();
private static Medium_controller mediumController = new Medium_controller();
public ItemsView() {
initComponents();
// JSONclass jsonClass = new JSONclass();
// List<Item> listOfItems = new ArrayList<Item>();
// try {
// listOfItems = jsonClass.getItemsJSON();
// } catch (IOException ex) {
// Logger.getLogger(ItemsView.class.getName()).log(Level.SEVERE, null, ex);
// }
// System.out.println(listOfItems);
List<Medium> mediums = mediumController.getMediums();
//System.out.println(mediums);
this.mediumBox.setModel(new DefaultComboBoxModel(mediums.toArray()));
this.mediumBox.insertItemAt("", 0);
this.mediumBox.setSelectedIndex(0);
}
private static String QUERY_START = "from Item i ";
private static String QUERY_TITLE="where i.title like '";
private static String QUERY_MEDIUM="where i.medium.typeMedium = '";
private void runQueryBasedOnTitle(String query)
{
executeHQLQuery(query);
}
private void executeHQLQuery(String hql)
{
try
{
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query q = session.createQuery(hql);
List resultList = q.list();
displayResult(resultList);
session.getTransaction().commit();
}
catch (HibernateException he)
{
he.printStackTrace();
}
}
private void displayResult(List resultList)
{
Vector<String> tableHeaders = new Vector<String>();
Vector tableData = new Vector();
tableHeaders.add("Id");
tableHeaders.add("Medium");
tableHeaders.add("Author");
tableHeaders.add("Title");
tableHeaders.add("Date Released");
for(Object o : resultList)
{
Item item = (Item)o;
Vector<Object> oneRow = new Vector<Object>();
oneRow.add(item.getId());
oneRow.add(item.getMedium().getTypeMedium());
oneRow.add(item.getAuthor());
oneRow.add(item.getTitle());
oneRow.add(item.getDateReleased());
tableData.add(oneRow);
}
resultTable.setModel(new DefaultTableModel(tableData, tableHeaders));
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
addFormLink = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
itemName = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
mediumBox = new javax.swing.JComboBox();
queryButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
resultTable = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Items");
addFormLink.setText("Add Item");
addFormLink.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addFormLinkActionPerformed(evt);
}
});
jLabel2.setText("Title");
jLabel3.setText("Medium");
mediumBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
queryButton.setText("Search");
queryButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
queryButtonActionPerformed(evt);
}
});
resultTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(resultTable);
jButton1.setText("Items to Console");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 78, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(127, 127, 127)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(itemName, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(mediumBox, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(queryButton)
.addComponent(addFormLink)))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)))
.addGap(62, 62, 62))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(addFormLink)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jButton1)))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(itemName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(mediumBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(queryButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void queryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_queryButtonActionPerformed
if(!itemName.getText().trim().equals(""))
{
if(!mediumBox.getSelectedItem().equals(""))
{
String query = QUERY_START + QUERY_TITLE + itemName.getText() + "%' and " + QUERY_MEDIUM + mediumBox.getSelectedItem() + "'";
runQueryBasedOnTitle(query);
}
else
{
String query = QUERY_START + QUERY_TITLE + itemName.getText() + "%'";
runQueryBasedOnTitle(query);
}
}
else if(!mediumBox.getSelectedItem().equals(""))
{
String query = QUERY_START + QUERY_MEDIUM + mediumBox.getSelectedItem() + "'";
runQueryBasedOnTitle(query);
}
}//GEN-LAST:event_queryButtonActionPerformed
private void addFormLinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addFormLinkActionPerformed
app.getAddItemView(this);
}//GEN-LAST:event_addFormLinkActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
itemController.listItems();
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
// public static void main(String args[]) {
// /* Set the Nimbus look and feel */
// //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
// /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
// * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
// */
// try {
// for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
// if ("Nimbus".equals(info.getName())) {
// javax.swing.UIManager.setLookAndFeel(info.getClassName());
// break;
// }
// }
// } catch (ClassNotFoundException ex) {
// java.util.logging.Logger.getLogger(ItemsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (InstantiationException ex) {
// java.util.logging.Logger.getLogger(ItemsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (IllegalAccessException ex) {
// java.util.logging.Logger.getLogger(ItemsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (javax.swing.UnsupportedLookAndFeelException ex) {
// java.util.logging.Logger.getLogger(ItemsView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// }
// //</editor-fold>
//// Medium medium = new Medium();
//// List<Medium> mediums = medium.mediums();
//// System.out.println(mediums);
// /* Create and display the form */
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
// new ItemsView().setVisible(true);
// }
// });
//
// }
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addFormLink;
private javax.swing.JTextField itemName;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JComboBox mediumBox;
private javax.swing.JButton queryButton;
private javax.swing.JTable resultTable;
// End of variables declaration//GEN-END:variables
}
|
package de.mneifercons.webdriver;
/*
* Copyright (c) 2020 Markus Neifer
* Licensed under the MIT License.
* See file LICENSE in parent directory of project root.
*/
import io.cucumber.java.After;
import io.cucumber.java.Before;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;
public class StepDefinitions {
private WebDriver _driver;
public StepDefinitions() {
System.setProperty("webdriver.chrome.driver", "lib/chromedriver");
}
@Before
public void setUp() {
_driver = new ChromeDriver();
}
@When("I search for cheese")
public void iSearchForCheese() {
_driver.get("https://google.com/ncr");
_driver.findElement(By.name("q")).sendKeys("cheese" + Keys.ENTER);
}
@Then("I find cheese")
public void iFindCheese() {
WebDriverWait wait = new WebDriverWait(_driver, 10);
WebElement firstResult = wait.until(presenceOfElementLocated(By.cssSelector("div.srg>div.g")));
String textContent = firstResult.getAttribute("textContent");
checkResponse(textContent);
assertThat(textContent, containsString("Cheese"));
}
@After
public void tearDown() {
_driver.quit();
_driver = null;
}
private void checkResponse(String text) {
System.out.println(text);
Object response = ((JavascriptExecutor) _driver).executeScript(
"return document.getElementsByClassName('srg').length;");
assertEquals(2L, (long) response);
}
}
|
package com.lenovohit.ssm.base.web.rest;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.lenovohit.core.manager.GenericManager;
import com.lenovohit.core.utils.DateUtils;
import com.lenovohit.core.utils.JSONUtils;
import com.lenovohit.core.utils.StringUtils;
import com.lenovohit.core.web.MediaTypes;
import com.lenovohit.core.web.rest.BaseRestController;
import com.lenovohit.core.web.utils.Result;
import com.lenovohit.core.web.utils.ResultUtils;
import com.lenovohit.ssm.base.model.SmsMessage;
import com.lenovohit.ssm.base.utils.SmsMessageUtils;
/**
* 短信验证码管理
*/
@RestController
@RequestMapping("/ssm/base/sms")
public class SmsMessageRestController extends BaseRestController {
@Autowired
private GenericManager<SmsMessage, String> smsMessageManager;
@RequestMapping(value="/sendCode",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forSendCode(@RequestBody String data){
SmsMessage smsMessage = JSONUtils.deserialize(data, SmsMessage.class);
validSmsMessage(smsMessage);
buildSmsMessage(smsMessage);
//boolean sendFlag = true;//TODO
boolean sendFlag = SmsMessageUtils.sendMsg(smsMessage.getMobile(), smsMessage.getContent(), null);
if(sendFlag){
this.smsMessageManager.save(smsMessage);
return ResultUtils.renderSuccessResult(smsMessage);
} else {
return ResultUtils.renderFailureResult();
}
}
@RequestMapping(value="/validCode",method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forValidCode(@RequestBody String data){
SmsMessage smsMessage = JSONUtils.deserialize(data, SmsMessage.class);
if(null == smsMessage || StringUtils.isEmpty(smsMessage.getId())
|| StringUtils.isEmpty(smsMessage.getCode())){
return ResultUtils.renderFailureResult("参数错误!");
}
SmsMessage _smsMessage = this.smsMessageManager.get(smsMessage.getId());
if(null == _smsMessage ){
return ResultUtils.renderFailureResult("未找到对应记录!");
}
if(StringUtils.equals(_smsMessage.getCode(), smsMessage.getCode())){
return ResultUtils.renderSuccessResult();
} else {
return ResultUtils.renderFailureResult("验证码错误,请核对验证码!");
}
}
private void validSmsMessage(SmsMessage message){
if (null == message) {
throw new NullPointerException("message should not be NULL!");
}
if (StringUtils.isEmpty(message.getMobile())) {
throw new NullPointerException("mobile should not be NULL!");
}
if (StringUtils.isEmpty(message.getType())) {
throw new NullPointerException("type should not be NULL!");
}
//TODO 暂未做ip和次数校验
// if (!StringUtils.equals(SmsMessage.MESSAGE_TYPE_REG, message.getType()) &&
// !StringUtils.equals(SmsMessage.MESSAGE_TYPE_PWD, message.getType()) &&
// !StringUtils.equals(SmsMessage.MESSAGE_TYPE_RFO, message.getType())) {
// throw new NullPointerException(message.getType() +" is not supported!");
// }
}
private void buildSmsMessage(SmsMessage message){
if (null == message) {
throw new NullPointerException("message should not be NULL!");
}
message.setCode(SmsMessageUtils.createCode(true, 4));
message.setSendtime(DateUtils.getCurrentDate());
message.setStatus("0");
message.setValidNum(0);
message.setIp(getLocalIp(this.getRequest()));
if(StringUtils.equals(SmsMessage.MESSAGE_TYPE_REG, message.getType())){
message.setContent("验证码"+message.getCode()+"。尊敬的用户,您正在使用本院自助机进行建档,请勿向任何人提供您的短信验证码。");
} else if(StringUtils.equals(SmsMessage.MESSAGE_TYPE_REP, message.getType())){
message.setContent("验证码"+message.getCode()+"。尊敬的用户,您正在使用本院自助机进行补卡,请勿向任何人提供您的短信验证码。");
} else if(StringUtils.equals(SmsMessage.MESSAGE_TYPE_PAY, message.getType())){
message.setContent("验证码"+message.getCode()+"。尊敬的用户,您正在使用本院自助机进行缴费,请勿向任何人提供您的短信验证码。");
} else if(StringUtils.equals(SmsMessage.MESSAGE_TYPE_DEP, message.getType())){
message.setContent("验证码"+message.getCode()+"。尊敬的用户,您正在使用本院自助机进行预存,请勿向任何人提供您的短信验证码。");
} else if(StringUtils.equals(SmsMessage.MESSAGE_TYPE_RFO, message.getType())){
message.setContent("验证码"+message.getCode()+"。尊敬的用户,您正在使用本院自助机进行退款,请勿向任何人提供您的短信验证码。");
}else{
message.setContent("验证码"+message.getCode()+"。尊敬的用户,您正在使用本院自助机进行操作,请勿向任何人提供您的短信验证码。");
}
}
/**
* 获取客户端Ip
* @param request
* @return
*/
private String getLocalIp(HttpServletRequest request){
String ip = request.getHeader("X-Forwarded-For");
if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = ip.indexOf(",");
if(index != -1){
return ip.substring(0,index);
}else{
return ip;
}
}
ip = request.getHeader("X-Real-IP");
if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
return ip;
}
return request.getRemoteAddr();
}
}
|
package com.infohold.el.web.rest;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.infohold.core.dao.Page;
import com.infohold.core.manager.GenericManager;
import com.infohold.core.utils.JSONUtils;
import com.infohold.core.utils.StringUtils;
import com.infohold.core.web.MediaTypes;
import com.infohold.core.web.rest.BaseRestController;
import com.infohold.core.web.utils.Result;
import com.infohold.core.web.utils.ResultUtils;
import com.infohold.el.base.model.CardMenu;
/**
* 合作银行网点信息管理
*
* @author Administrator
*
*/
@RestController
@RequestMapping("/el/cardMenu")
public class CardMenuRestController extends BaseRestController {
@Autowired
private GenericManager<CardMenu, String> cardMenuManager;
/**
*
* 维护卡功能列表
*
* @param data
* @return
*/
@RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forCreate(@RequestBody String data) {
CardMenu model = JSONUtils.deserialize(data, CardMenu.class);
model = this.cardMenuManager.save(model);
return ResultUtils.renderSuccessResult(model);
}
/**
* 查询卡功能列表
*
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forInfo(@PathVariable("id") String id) {
CardMenu model = this.cardMenuManager.get(id);
return ResultUtils.renderSuccessResult(model);
}
/**
* 维护卡功能列表
*
* @param id
* @param data
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Result forUpdate(@PathVariable("id") String id,
@RequestBody String data) {
CardMenu model = this.cardMenuManager.get(id);
model = this.cardMenuManager.save(model);
return ResultUtils.renderSuccessResult(model);
}
/**
* 删除卡功能列表
*
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
public Result forDelete(@PathVariable("id") String id) {
CardMenu model = this.cardMenuManager.delete(id);
return ResultUtils.renderSuccessResult(model);
}
/**
* ELB_CARD_018 卡功能列表 P2.2
*
* @param start
* @param pageSize
* @param data
* @return
*/
@RequestMapping(value = "/list/{start}/{pageSize}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forList(@PathVariable(value = "start") int start,
@PathVariable(value = "pageSize") int pageSize,
@RequestParam(value = "data", defaultValue = "") String data) {
String jql = " from CardMenu where 1=1 ";
List<Object> values= new ArrayList<Object>();
if(StringUtils.isNotEmpty(data)){
jql += " and typeId = ? ";
values.add(data);
}
Page page = new Page();
page.setStart(start);
page.setPageSize(pageSize);
page.setQuery(jql);
page.setValues(values.toArray());
this.cardMenuManager.findPage(page);
return ResultUtils.renderSuccessResult(page);
}
}
|
package factoring.fermat.residue;
import factoring.math.PrimeMath;
import factoring.math.SquaresMod;
import java.util.Collection;
/**
* Created by Thilo Harich on 03.01.2018.
*/
public class FermatResiduesArray extends FermatResiduesRec {
int mod; // = 24
int repeat = 3;
public int xRange = mod * repeat;
public int xRangeM1 = mod * (repeat-1);
public int x4Mod[][];
boolean[] xMask;
public FermatResiduesArray(int mod) {
this.mod = mod;
residueClasses = new int[]{mod};
x4Mod = new int [mod][];
lastLevel = 1;
// TODO we need only one level
squares = new boolean [lastLevel][];
for (int level=0; level < residueClasses.length; level++) {
int residue = residueClasses[level];
initSquares(level, residue);
}
}
public void init(long n, int[] residueClasses) {
int nMod = PrimeMath.mod(n, mod);
if (x4Mod[nMod] != null)
return;
x4Mod[nMod] = new int[mod+1];
int prod = 1;
// modProd = new int [residueClasses.length];
// xArray = new int [lastLevel][];
// xMask = new boolean [lastLevel];
for (int level=0; level < residueClasses.length; level++) {
int mod = residueClasses[level];
// if (level < residueClasses.length-1 || level == 0)
initX(level, mod, n);
// else
// initXMask(level, mod, n);
// if (mod > 0) {
// modProd[level] = prod;
// prod *= mod;
// }
}
}
public void initX(int level, int mod, long n)
{
int nMod = PrimeMath.mod(n, mod);
int resIndex= 0;
int squareMinN = nMod == 0 ? 0 : mod-nMod;
for (int i = 1; i <2*mod; i += 2) {
if (squares[level][squareMinN]) {
x4Mod[nMod][resIndex++] = i / 2;
}
// we want to avoid the % and since (s+1)^2 = s^2 + 2s + 1, we always add i=2s+1
// we might move out the last call
squareMinN += i;
squareMinN -= squareMinN >= mod ? (squareMinN >= 2*mod ? 2*mod : mod) : 0;
}
x4Mod[nMod][resIndex] = -1;
}
// public void initX(int level, int mod, long n)
// {
// int resIndex= 0;
// int nMod = PrimeMath.mod(n, mod);
// int squareMinN = nMod == 0 ? 0 : mod - nMod;
// if (squares[level][squareMinN]) {
// x4Mod[nMod][resIndex++] = 0;
// }
// squareMinN += 1;
// squareMinN -= squareMinN >= mod ? mod : 0;
//// for (int j = 1; j < 2*mod+1; j += 2) {
// // since we only want to iterate over the first half of the possible values,
// // buy using (-xArray)^2 = xArray^2, we have to handle the special cases xArray=0 and xArray=mod/2
// for (int j = 3; j < mod+1; j += 2) {
// if (squares[level][squareMinN]) {
// x4Mod[nMod][resIndex++] = j/2;
// x4Mod[nMod][resIndex++] = mod - j/2;
// }
// squareMinN += j;
// squareMinN -= squareMinN >= mod ? mod : 0;
// }
// // since all primes different from 2 (which call xArray) are odd this will never be executed
// if ((mod & 1) == 0 && squares[level][squareMinN]) {
// x4Mod[nMod][resIndex++] = mod/2;
// }
// x4Mod[nMod][resIndex] = -1;
// }
// public void initXMask(int level, int mod, long n)
// {
// xMask = new boolean[mod];
// int nMod = PrimeMath.mod(n, mod);
// int squareMinN = nMod == 0 ? 0 : mod - nMod;
// for (int j = 1; j < 2* mod; j += 2) {
// if (squares[level][squareMinN]) {
// xMask[j/2] = true;
// }
// squareMinN += j;
// squareMinN -= squareMinN >= mod ? mod : 0;
// }
// }
public long findFactors(long n, Collection<Long> factors, long nOrig) {
// to be sure we do not have some bad effects with the merging
init(n, residueClasses);
int nMod = PrimeMath.mod(n, mod);
// we reuse the results
// if (x4Mod[nMod] == null)
// merge(0, nMod);
long sqrtN = PrimeMath.sqrt(n);
long xBegin = sqrtN;
xBegin = ((xBegin) / mod) * mod;
long xEnd = xBegin + xRangeM1;
for (int i=0; x4Mod[nMod][i] >= 0; i++) {
long x = xEnd + x4Mod[nMod][i];
while (x >= sqrtN) {
long right = x * x - n;
if (SquaresMod.isSquare(right)) {
long y = PrimeMath.sqrt(right);
long factor = PrimeMath.gcd(nOrig, x - y);
if (factor != 1) {
factors.add(factor);
return nOrig / factor;
}
}
x -= mod;
}
}
return n;
}
public void merge(int level, int nMod) {
x4Mod[nMod] = new int[modProd[level+1] * residueClasses[level+1] + 1];
int resIndex = 0;
// for (int l = 0; xArray[level][l] >= 0; l++ )
// {
// int x = xArray[level][l];
// for (int k = 0; xArray[level+1][k] >= 0; k++ ) {
// int i = mod((xArray[level+1][k] - x)*modOldInvert[level+1], residueClasses[level+1]);
// int xMerge = x + i * modProd[level+1];
// x4Mod[nMod][resIndex++] = xMerge;
// }
// }
int modOld = residueClasses[level];
int modNew = residueClasses[level+1];
final int step = ( modOld / modNew + 1) * modNew;
for (int l = 0; xArray[level][l] >= 0; l++ ) {
int x = xArray[level][l];
// avoid % here, maybe we can keep old xMod
int xMod = x;
while (xMod >= modNew)
xMod -= modNew;
while (x < modOld * modNew) {
if (xMask[xMod]) {
x4Mod[nMod][resIndex++] = x;
}
x += modOld;
xMod += modOld;
// We avoid calculating expensive % operation
xMod -= xMod >= step ? step : (step - modNew);
}
}
x4Mod[nMod][resIndex] = -1;
}
}
|
package com.movie.web.grade;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.moive.web.global.Command;
import com.moive.web.global.CommandFactory;
import com.movie.web.memer.MemberBean;
import com.movie.web.memer.MemberServiceImpl;
/**
* Servlet implementation class GradeController
*/
@WebServlet("/grade/my_grade.do")
public class GradeController extends HttpServlet {
private static final long serialVersionUID = 1L;
static GradeService service = GradeServiceImpl.getInstance();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Command command = new Command();
GradeBean Grade = new GradeBean();
String id="";
String path = request.getServletPath();
String temp = path.split("/")[2];
String directory = path.split("/")[1];
// arr[1] = temp3.split("\\.")[0]; 이 방법도 가능
String action = temp.substring(0, temp.indexOf("."));
//command = CommandFactory.createCommand(directory,action);
switch (action) {
case "my_grade":
request.setAttribute("score", service.getGradeById(request.getParameter("id")));
command = CommandFactory.createCommand(directory,action);
break;
default:
break;
}
RequestDispatcher dis =
request.getRequestDispatcher(command.getView());
dis.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
} |
package Praticando;
import java.util.Scanner;
public class folha_de_pagamento {
void salario (double hora,int mes){
Scanner scanner = new Scanner(System.in);
System.out.println("Digite quanto voce ganha por hora");
hora = scanner.nextDouble();
System.out.println("Digite quantas horas voce trabalha em um mes");
mes = scanner.nextInt();
var totalSalario = Math.floor(hora*mes);
System.out.println("salario bruto: "+"("+hora+" × "+mes+")"+" : R$ "+totalSalario);
if (totalSalario<=900){
var inss = totalSalario*10/100;
var fgts = totalSalario*11/100;
var desconto = 0+ inss;
var salario1 = totalSalario - desconto;
System.out.println("(-) IR (0%)"+" : R$ 0,00");
System.out.println("(-)INSS(10%)"+" : R$ "+inss);
System.out.println("(-) FGTS (11%)"+" : R$ "+fgts);
System.out.println("Total de desconto"+" : R$ "+desconto);
System.out.println("Salario liquido : R$ "+salario1);
}
else if (totalSalario >900 && totalSalario<=1500){
var inss = totalSalario*10/100;
var ir = totalSalario*5/100;
var fgts = totalSalario*11/100;
var desconto = ir + inss;
var salario1 = totalSalario - desconto;
System.out.println("(-) IR (5%)"+" : R$ "+ir);
System.out.println("(-) INSS (10%)"+" : R$ "+inss);
System.out.println("(-) FGTS (11%)"+" : R$ "+fgts);
System.out.println("Total de desconto"+" : R$ "+desconto);
System.out.println("Salario liquido : R$ "+salario1);
}
else if (totalSalario>1500 && totalSalario<=2500){
var inss = totalSalario*10/100;
var ir = totalSalario*10/100;
var fgts = totalSalario*11/100;
var desconto = ir + inss;
var salario1 = totalSalario - desconto;
System.out.println("(-) IR (10%)"+" : R$ "+ir);
System.out.println("(-) INSS (10%)"+" : R$ "+inss);
System.out.println("(-) FGTS (11%)"+" : R$ "+fgts);
System.out.println("Total de desconto"+" : R$ "+desconto);
System.out.println("Salario liquido : R$ "+salario1);
}
else if (totalSalario>2500){
var inss = totalSalario*10/100;
var ir = totalSalario*15/100;
var fgts = totalSalario*11/100;
var desconto = ir + inss;
var salario1 = totalSalario - desconto;
System.out.println("(-) IR (15%)"+" : R$ "+ir);
System.out.println("(-) INSS (10%)"+" : R$ "+inss);
System.out.println("(-) FGTS (11%)"+" : R$ "+fgts);
System.out.println("Total de desconto"+" : R$ "+desconto);
System.out.println("Salario liquido : R$ "+salario1);
}
}
public static void main(String[] args) {
folha_de_pagamento liquido = new folha_de_pagamento();
liquido.salario(0,0);
}
}
|
package com.jgermaine.fyp.rest.model.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import javax.transaction.Transactional;
import org.springframework.stereotype.Repository;
import com.jgermaine.fyp.rest.model.Employee;
import com.jgermaine.fyp.rest.model.Report;
/**
* This class is used to access data for the Employee entity.
*/
@Repository
@Transactional
public class EmployeeDao {
// An EntityManager will be automatically injected from entityManagerFactory
@PersistenceContext
private EntityManager entityManager;
private static final int SET_SIZE = 30;
/**
* Delete the Employee from the database.
*/
public void delete(Employee employee) throws Exception {
entityManager.remove(employee);
}
/**
* Return all the Employees stored in the database.
*/
@SuppressWarnings("unchecked")
public List<Employee> getAll(int index) throws Exception {
return entityManager.createQuery("from Employee").setFirstResult(index).setMaxResults(SET_SIZE).getResultList();
}
/**
* Return the Employee having the passed name.
*/
public Employee getByEmail(String email) throws NoResultException, NonUniqueResultException, Exception {
return (Employee) entityManager.createQuery("from Employee where email = :email").setParameter("email", email)
.getSingleResult();
}
public Long getAllCount() {
try {
return (Long) entityManager.createQuery("Select count(*) from Employee").getSingleResult();
} catch (Exception e) {
return (long) 0;
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Long getUnassignedCount() {
try {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
// Select count from employee
CriteriaQuery query = criteriaBuilder.createQuery(Long.class);
Root employee = query.from(Employee.class);
query.select(criteriaBuilder.count(employee));
// Create subquery for class
Subquery subquery = query.subquery(Report.class);
Root subRootEntity = subquery.from(Report.class);
subquery.select(subRootEntity);
// where employee does not exist in reports
Predicate correlatePredicate = criteriaBuilder.equal(subRootEntity.get("employee"), employee);
subquery.where(correlatePredicate);
query.where(criteriaBuilder.not(criteriaBuilder.exists(subquery)));
TypedQuery typedQuery = entityManager.createQuery(query);
return (Long) typedQuery.getSingleResult();
} catch (Exception e) {
return (long) 0;
}
}
/**
* Return the Employee having no job assigned.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Employee> getUnassigned(int index) throws Exception {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
// Select * from employee
CriteriaQuery query = criteriaBuilder.createQuery(Employee.class);
Root employee = query.from(Employee.class);
query.select(employee);
// Create subquery for class
Subquery subquery = query.subquery(Report.class);
Root subRootEntity = subquery.from(Report.class);
subquery.select(subRootEntity);
// where employee does exist in reports
Predicate correlatePredicate = criteriaBuilder.equal(subRootEntity.get("employee"), employee);
subquery.where(correlatePredicate);
query.where(criteriaBuilder.not(criteriaBuilder.exists(subquery)));
TypedQuery typedQuery = entityManager.createQuery(query);
return typedQuery.setFirstResult(index).setMaxResults(SET_SIZE).getResultList();
}
/**
* Update the passed Employee in the database.
*/
public void update(Employee employee) throws Exception {
entityManager.merge(employee);
}
/**
* Returns a list of unassigned reports sorted by closest proximity /**
*
* @see http://en.wikipedia.org/wiki/Haversine_formula
* @param lat
* @param lon
* @return list of report
*/
@SuppressWarnings("unchecked")
public List<Employee> getUnassignedNearestEmployee(double lat, double lon) throws Exception {
Query query = entityManager.createNativeQuery("SELECT *, "
+ "( 6371 * acos( cos( radians(:lat) ) * cos( radians( latitude ) )"
+ "* cos( radians( longitude ) - radians(:lon) ) "
+ "+ sin( radians(:lat) ) * sin( radians( latitude ) ) ) )" + "AS distance " + "FROM Employee "
+ "WHERE email not in(Select r.emp_email " + "from Reports r WHERE r.emp_email IS NOT NULL) "
+ "HAVING distance < 10 " + "ORDER BY distance " + "LIMIT 0 , 10;", Employee.class);
query.setParameter("lat", lat);
query.setParameter("lon", lon);
return query.getResultList();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Employee> getAssigned(int index) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
// Select * from employee
CriteriaQuery query = criteriaBuilder.createQuery(Employee.class);
Root employee = query.from(Employee.class);
query.select(employee);
// Create subquery for class
Subquery subquery = query.subquery(Report.class);
Root subRootEntity = subquery.from(Report.class);
subquery.select(subRootEntity);
// where employee does exist in reports
Predicate correlatePredicate = criteriaBuilder.equal(subRootEntity.get("employee"), employee);
subquery.where(correlatePredicate);
query.where(criteriaBuilder.exists(subquery));
TypedQuery typedQuery = entityManager.createQuery(query);
return typedQuery.setFirstResult(index).setMaxResults(SET_SIZE).getResultList();
}
} |
package com.tntdjs.midi.executer;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.tntdjs.midi.IMidiExecuter;
import com.tntdjs.midi.MidiTypeTypes;
import com.tntdjs.midi.controllers.data.config.objects.MidiButton;
/**
* ExecuterFactory
* A Factory and manager class to generate midi executers of the following types
* - midi bridge
* - midi triggered audio clips
* - key
* - execute
*
* @author tsenausk
*
*/
public class ExecuterFactory {
private static final Logger LOGGER = LogManager.getLogger(ExecuterFactory.class.getName());
private static ExecuterFactory INSTANCE;
private Map<Integer, IMidiExecuter> EXECUTERS = new Hashtable<Integer, IMidiExecuter>();
/**
*
*/
private ExecuterFactory() {}
/**
* Get Instance
* @return
*/
public static ExecuterFactory getInstance() {
if (null == INSTANCE) {
INSTANCE = new ExecuterFactory();
}
return INSTANCE;
}
/**
*
* @param id
*/
public IMidiExecuter getExecuterByID(String id) {
Iterator<Entry<Integer, IMidiExecuter>> it = EXECUTERS.entrySet().iterator();
while(it.hasNext()) {
IMidiExecuter me = it.next().getValue();
if (me.getMidiButton().getId().equalsIgnoreCase(id)) {
return me;
}
}
return null;
}
/**
*
* @param note
* @return
*/
public IMidiExecuter getExecuterByMidiNote(int note) {
return EXECUTERS.get(note);
}
/**
* Create the MAP of executers based on supplied XML configurations
* @return
*/
public int generateExecuters(List<MidiButton> midiButtons) throws Exception {
for (MidiButton midiButton : midiButtons) {
LOGGER.info(midiButton + " button is enabled [" + midiButton.getEnabled() +"]");
if (midiButton.getEnabled()) {
IMidiExecuter executer = null;
switch (midiButton.getType().toLowerCase()) {
case MidiTypeTypes.audio:
executer = new AudioMidiExecuter(midiButton);
break;
case MidiTypeTypes.bridge:
executer = new BridgeMidiExecuter(midiButton);
break;
case MidiTypeTypes.os:
if (midiButton.getAction().equalsIgnoreCase("cmd")) {
executer = new CommandExecuter(midiButton);
} else if (midiButton.getAction().equalsIgnoreCase("key")) {
executer = new KeyExecuter(midiButton);
}
break;
default:
executer = new MidiExecuter(new MidiButton());
}
// if (MidiTypeEnum.audio.toString().equals(midiButton.getType())) {
// executer = new AudioMidiExecuter(midiButton);
//
// } else if (MidiTypeEnum.bridge.toString().equals(midiButton.getType())) {
// executer = new BridgeMidiExecuter(midiButton);
//
// } else {
// executer = new MidiExecuter(new MidiButton());
// }
EXECUTERS.put(midiButton.getMidiNote(), executer);
}
}
if (EXECUTERS.size()==0) {
throw new Exception("Error generating executers, no Midi Buttons define check app device XML configurations");
}
return EXECUTERS.size();
}
}
|
package xplanner.model;
import network.model.response.CategoryResponse;
import network.model.response.EventResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import service.RestClient;
import java.util.*;
/**
* Created by qiaoruixiang on 15/05/2017.
*/
public class PoiData {
private ArrayList<PlainEvent> events;
private Set<Place> places;
private List<Poi> pois;
public PoiData() {
events = new ArrayList<>();
places = new HashSet<>();
pois = new ArrayList<>();
}
public void readDataFromFile(String f) {
CSVReader csvReader = new CSVReader(f);
while (csvReader.hasNext()) {
PlainEvent event = new PlainEvent();
event.bindData(csvReader.read());
events.add(event);
}
events.forEach( item -> places.add(item.getPlace()));
}
public void readDataFromWeb(String url) {
RestClient restClient = new RestClient(url);
String jsonStr = restClient.executeGet();
pois = parsePoisJson(jsonStr);
pois.forEach(item -> places.add(new Place(item.getLatitude(), item.getLongitude())));
}
public void readFromData(List<EventResponse> events) {
for (EventResponse e : events) {
Poi p = new Poi();
p.bindData(e);
pois.add(p);
}
pois.forEach(item -> places.add(new Place(item.getLatitude(), item.getLongitude())));
}
public ArrayList<PlainEvent> getEvents() {
return events;
}
public Set<Place> getPlaces() {
return places;
}
public List<Poi> getPois() {
return pois;
}
private static List<Poi> parsePoisJson(String jsonStr) {
ArrayList<Poi> result = new ArrayList<>();
try {
JSONObject root = new JSONObject(jsonStr);
JSONArray pois = root.getJSONArray("POIs");
for (int i = 0; i < pois.length(); i++) {
JSONObject poiJson = pois.getJSONObject(i);
Poi poi = new Poi(poiJson);
result.add(poi);
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
|
public class Solution{
//this method takes roughly O(n+km) time(k is occurences of t2's root in t1) and O(logn+logm) space.
public static boolean isSubTree(TreeNode t1,TreeNode t2){
if(t2==null){return true;}
return travseral(t1,t2);
}
private static boolean travseral(TreeNode t1,TreeNode t2){
if(t1==null){return false;}
boolean res = false;
if(t1.val==t2.val){
res = isSameTree(t1,t2);
if(res){return true};
}
res ||= travseral(t1.left,t2);
if(res){return true;}
res ||= travseral(t1.right,t2);
if(res){return true;}
return res;
}
private static boolean isSameTree(TreeNode t1,TreeNode t2){
if(t1==null&&t2==null){return true;}
if(t1==null||t2==null){return false;}
if(t1.val!=t2.val){return false;}
boolean left = isSameTree(t1.left,t2.left);
if(!left){return false;}
boolean right = isSameTree(t1.right,t2.right);
if(!right){return false;}
return true;
}
} |
package ua.com.dao;
import ua.com.model.User;
public interface UserDAO extends CommonDAO<User> {
}
|
/*
* @(#)Nameable.java 1.0 06/24/99
*
*/
package org.google.code.netapps.chat.primitive;
/**
* The ability to have some name.
*
* @version 1.0 06/24/99
* @author Alexander Shvets
*/
public interface Nameable {
/**
* Get name of object.
*
* @return name of object as a string
*/
public String getName();
/**
* Get qualified name of object.
*
* @return qualified name of object as a string
*/
public String getQualifiedName();
} |
package com.v.demo1;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Administrator on 2017/11/4.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Context context;
private Bean bean;
public RecyclerViewAdapter(Context context, Bean bean) {
this.context = context;
this.bean = bean;
}
//创建视图
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(context, R.layout.item, null);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
//绑定视图的数据
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tvitem.setText(bean.getApk().get(position).getCategoryName());
}
@Override
public int getItemCount() {
return bean.getApk().size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private final TextView tvitem;
public MyViewHolder(View itemView) {
super(itemView);
tvitem = itemView.findViewById(R.id.tvitem);
}
}
} |
package org.composant.vehicule;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.database.vehicule.Moto;
import org.database.vehicule.Vehicule;
import org.database.vehicule.Voiture;
/**
* Session Bean implementation class VehiculeComposant
*
* Permet d'ajouter le véhicule, de le récupérer
*/
@Stateless
@LocalBean
public class VehiculeComposant implements VehiculeComposantRemote, VehiculeComposantLocal {
@PersistenceContext(name = "DatabaseECommerce")
private EntityManager em;
/**
* Default constructor.
*/
public VehiculeComposant()
{
// TODO Auto-generated constructor stub
}
@Override
public Vehicule ajouterVehicule(String modele, String marque, String couleur, int nbKm, String typeCarburant, String typeVehicule, double prix, int quantite) {
// TODO Auto-generated method stub
Vehicule vehicule = null;
if(typeVehicule.equals("Voiture"))
{
vehicule = new Voiture(modele,marque,couleur,nbKm,typeCarburant,typeVehicule,prix,quantite);
}
else if(typeVehicule.equals("Moto"))
{
vehicule = new Moto(modele,marque,couleur,nbKm,typeCarburant,typeVehicule,prix,quantite);
}
if(vehicule != null)
em.persist(vehicule);
return null;
}
@Override
public Vehicule supprimerVehicule(String modele, String marque, String couleur, int nbKm, String typeCarburant, String typeVehicule, double prix, int quantite) {
// TODO Auto-generated method stub
Vehicule vehicule = null;
if(typeVehicule.equals("Voiture"))
{
vehicule = new Voiture(modele,marque,couleur,nbKm,typeCarburant,typeVehicule,prix,quantite);
}
else if(typeVehicule.equals("Moto"))
{
vehicule = new Moto(modele,marque,couleur,nbKm,typeCarburant,typeVehicule,prix,quantite);
}
em.remove(em.merge(vehicule));
return vehicule;
}
@Override
public Vehicule trouverVehicule(Object id)
{
return em.find(Vehicule.class, id);
}
}
|
package mx.santander.listener.model;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@EnableJpaAuditing
@Getter
@Setter
@RequiredArgsConstructor
public class TycsServiceMessage {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String buc;
private String applicationId;
private String tycVersion;
@Override
public String toString() {
return "TycsServiceMessage [buc=" + buc + ", applicationId=" + applicationId + ", tycVersion=" + tycVersion + "]";
}
}
|
package com.example.workstudy.thread;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
public class ThreadReturnImpl implements Callable<String> {
/**
* 实现Callable接口的两种启动方式
* 一种是通过FutureTask
*
* 一种是通过Executor
*/
private static final ThreadLocal<Map<String,String>> theadLocal = new ThreadLocal<Map<String, String>>();
@Override
public String call() throws Exception {
System.out.println("return is running");
ConcurrentHashMap<String,String> map= new ConcurrentHashMap<String,String>();
map.put("return",Thread.currentThread().getName());
try {
theadLocal.set(map);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(theadLocal.get().get("return"));
//theadLocal.remove();
return Thread.currentThread().getName();
}
}
|
package com.logicbig.example.componentscanfiltering;
public class MyBean2 {
} |
/*
* 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 stockmarket;
import java.util.ArrayList;
/**
*
* @author hugo
*/
public class Asset {
private String name;
private double weigth;
private ArrayList<Double> returns;
private String portfolioType;
public Asset(String name) {
this.name = name;
this.returns = new ArrayList<>();
}
public String getName() {
return this.name;
}
public ArrayList<Double> getReturns() {
return this.returns;
}
public void addReturn(Double r) {
this.returns.add(r);
}
public int size() {
return this.returns.size();
}
public Double getReturn(int i) {
return this.returns.get(i);
}
public void setReturns(ArrayList<Double> returns) {
this.returns = returns;
}
public double getWeigth() {
return weigth;
}
public void setWeigth(double weigth) {
this.weigth = weigth;
}
public String getPortfolioType() {
return portfolioType;
}
public void setPortfolioType(String portfolioType) {
this.portfolioType = portfolioType;
}
public void setReturn(int s, double enhancedReturn) {
this.returns.set(s, enhancedReturn);
}
}
|
public class Reverser extends Transpose{
public Reverser(String text)
{
super(text);
}
public String reverseText(String word)
{
String[] tokens = word.split(" ");
String reverse = "";
for (int i = tokens.length -1; i >=0; i--)
reverse = reverse + tokens[i] + "";
return reverse.trim();
}
@Override
public String decode(String word)
{
return super.decode(word);
}
}
|
package io.report.modules.ser.service;
import com.baomidou.mybatisplus.service.IService;
import io.report.common.utils.PageUtils;
import io.report.modules.ser.entity.DtTableRsEntity;
import java.util.Map;
/**
* 数据集引用表关系表
*
* @author jizh
* @email jzh15084102133@126.com
* @date 2018-08-29 18:01:10
*/
public interface DtTableRsService extends IService<DtTableRsEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
package FrontEnd;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import lk.sliitacademy.rustrepaircenter.ConnectionMSSQL;
import lk.sliitacademy.rustrepaircenter.SendEmail;
public class SendEmailToSupplier extends javax.swing.JFrame {
private final DefaultTableModel model_TableSupplierEmail;
public SendEmailToSupplier() {
initComponents();
model_TableSupplierEmail = (DefaultTableModel) tableSupplierEmail.getModel();
loadDetailsToTable();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tableSupplierEmail = new javax.swing.JTable();
textSPid = new javax.swing.JTextField();
textSPname = new javax.swing.JTextField();
textSPquantity = new javax.swing.JTextField();
textSupplierID = new javax.swing.JTextField();
textSupplierName = new javax.swing.JTextField();
textSupplierEmail = new javax.swing.JTextField();
buttonSendEmail = new javax.swing.JButton();
buttonBack = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
refreshButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tableSupplierEmail.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Spare part id", "Spare part name", "Quantity", "Supplier id", "Supplier name", "Supplier email"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tableSupplierEmail.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableSupplierEmailMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tableSupplierEmail);
textSPid.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textSPidActionPerformed(evt);
}
});
buttonSendEmail.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
buttonSendEmail.setText("Send Email");
buttonSendEmail.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonSendEmailActionPerformed(evt);
}
});
buttonBack.setText("Back");
buttonBack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonBackActionPerformed(evt);
}
});
jLabel1.setText("Spare Part ID : ");
jLabel2.setText("Spare Part Name : ");
jLabel3.setText("Quantity : ");
jLabel4.setText("Supplier ID : ");
jLabel5.setText("Supplier Name : ");
jLabel6.setText("Supplier Email : ");
refreshButton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
refreshButton.setText("Refresh");
refreshButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
refreshButtonActionPerformed(evt);
}
});
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(39, 39, 39)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(36, 36, 36)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(textSPid)
.addComponent(textSPname, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE)
.addComponent(textSPquantity))
.addGap(137, 137, 137)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addGap(51, 51, 51)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(textSupplierID)
.addComponent(textSupplierName, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
.addComponent(textSupplierEmail))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(refreshButton, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(buttonSendEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(buttonBack, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 857, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(32, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 345, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textSPid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textSupplierID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel4))
.addGap(26, 26, 26)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textSPname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textSupplierName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jLabel5))
.addGap(27, 27, 27)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(textSPquantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textSupplierEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jLabel6))
.addGap(30, 30, 30)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonSendEmail)
.addComponent(buttonBack)
.addComponent(refreshButton))
.addContainerGap(31, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void tableSupplierEmailMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableSupplierEmailMouseClicked
int i = tableSupplierEmail.getSelectedRow();
String sparepartID = tableSupplierEmail.getValueAt(i, 0).toString();
String sparepartName = tableSupplierEmail.getValueAt(i, 1).toString();
String sparepartquantity = tableSupplierEmail.getValueAt(i, 2).toString();
String supplierID = tableSupplierEmail.getValueAt(i, 3).toString();
String supplierName = tableSupplierEmail.getValueAt(i, 4).toString();
String supplierEmail = tableSupplierEmail.getValueAt(i, 5).toString();
textSPid.setText(sparepartID);
textSPname.setText(sparepartName);
textSPquantity.setText(sparepartquantity);
textSupplierID.setText(supplierID);
textSupplierName.setText(supplierName);
textSupplierEmail.setText(supplierEmail);
}//GEN-LAST:event_tableSupplierEmailMouseClicked
private void buttonSendEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSendEmailActionPerformed
sendSupplierNotificationEmail();
}//GEN-LAST:event_buttonSendEmailActionPerformed
private void textSPidActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textSPidActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_textSPidActionPerformed
private void buttonBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBackActionPerformed
MainWindow mw = new MainWindow();
mw.setVisible(true);
this.dispose();
}//GEN-LAST:event_buttonBackActionPerformed
private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
Refresh();
}//GEN-LAST:event_refreshButtonActionPerformed
private void Refresh(){
textSPid.setText("");
textSPname.setText("");
textSPquantity.setText("");
textSupplierID.setText("");
textSupplierName.setText("");
textSupplierEmail.setText("");
}
private void sendSupplierNotificationEmail() {
String sparepartid = textSPid.getText();
String sparepartname = textSPname.getText();
String sparepartquantity = textSPquantity.getText();
String supplierID = textSupplierID.getText();
String supplierName = textSupplierName.getText();
String supplierEmail = textSupplierEmail.getText();
SendEmail sm = new SendEmail();
sm.SendEmailToSupplier(sparepartid, sparepartname, sparepartquantity, supplierID, supplierName, supplierEmail);
}
private void loadDetailsToTable() {
try {
int rowCount = 0;
// RefreshTable();
Statement stmt = ConnectionMSSQL.connect().createStatement();
// String query = "select * from SupplierTable order by SupplierID";
String query = "select SparePartTable.SpartPartID AS SparePartTableSpartPartID,\n"
+ " SparePartTable.SparePartName AS SparePartTableSparePartName, \n"
+ " SparePartTable.StockQuantity AS SparePartTableStockQuantity,\n"
+ " SupplierTable.SupplierID AS SupplierTableSupplierID,\n"
+ " SupplierTable.SupplierName AS SupplierTableSupplierName,\n"
+ " SupplierTable.SupplierEmail AS SupplierTableSupplierEmail\n"
+ "FROM SparePartTable INNER JOIN SupplierTable ON SparePartTable.SupplierID = SupplierTable.SupplierID ";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
model_TableSupplierEmail.addRow(new Object[model_TableSupplierEmail.getColumnCount()]);
tableSupplierEmail.setValueAt(rs.getString("SparePartTableSpartPartID"), rowCount, 0);
tableSupplierEmail.setValueAt(rs.getString("SparePartTableSparePartName"), rowCount, 1);
tableSupplierEmail.setValueAt(rs.getString("SparePartTableStockQuantity"), rowCount, 2);
tableSupplierEmail.setValueAt(rs.getString("SupplierTableSupplierID"), rowCount, 3);
tableSupplierEmail.setValueAt(rs.getString("SupplierTableSupplierName"), rowCount, 4);
tableSupplierEmail.setValueAt(rs.getString("SupplierTableSupplierEmail"), rowCount, 5);
rowCount++;
}
rs.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(this, "Please contact for support.");
} catch (ClassNotFoundException ex) {
Logger.getLogger(SendEmailToSupplier.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SendEmailToSupplier.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SendEmailToSupplier.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SendEmailToSupplier.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SendEmailToSupplier.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SendEmailToSupplier().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton buttonBack;
private javax.swing.JButton buttonSendEmail;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton refreshButton;
private javax.swing.JTable tableSupplierEmail;
private javax.swing.JTextField textSPid;
private javax.swing.JTextField textSPname;
private javax.swing.JTextField textSPquantity;
private javax.swing.JTextField textSupplierEmail;
private javax.swing.JTextField textSupplierID;
private javax.swing.JTextField textSupplierName;
// End of variables declaration//GEN-END:variables
}
|
package onlineMall.web.publicController;
import onlineMall.web.dao.DateConvert;
import onlineMall.web.dao.Impl.ShopDaoImpl;
import onlineMall.web.dao.Impl.UserDaoImpl;
import onlineMall.web.pojo.Shop;
import onlineMall.web.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* @ Package: onlineMall.web.publicController
* @ Author :linsola
* @ Date :Created in 21:24 2018/12/23
* @ Description:
* @ Modified By:
* @ Version:
*/
@Controller
@ResponseBody
@RequestMapping("/login")
public class LoginController {
@Autowired
private UserDaoImpl userDaoImpl;
@Autowired
private ShopDaoImpl shopDaoImpl;
private String redirectPage = "";
/**
* 用户登录
* */
@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
public void userLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
HttpSession session = request.getSession();
//获取输入的用户名和密码
String userName = request.getParameter("userName");
String password = request.getParameter("password");
User user = null;
user = userDaoImpl.userLogin(userName,password);
//判断用户是否登录成功
if(user!=null){
if (user.getPassword().equals(password)) {
//登录成功 将user对象存到session中
session.setAttribute("user",user);
//重新定向到首页
redirectPage = "/index.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}else {
//密码错误
request.setAttribute("loginError","密码错误");
redirectPage = "/userLogin.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}
}else {
request.setAttribute("loginError","用户名不存在");
redirectPage = "/userLogin.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}
}
/**
* 用户注销
* */
@RequestMapping(value = "/userLoginOut",method = RequestMethod.POST)
public void userLoginOut(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
HttpSession session = request.getSession();
//从session中将user删除
session.removeAttribute("user");
redirectPage = "/index.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}
/**
* 用户注册
* */
@RequestMapping(value = "/userRegister",method = RequestMethod.POST)
@ResponseBody
public void userRegister(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
User user = new User();
DateConvert dateConvert = new DateConvert();
user.setUserId(null);
user.setUserName(request.getParameter("userName"));
user.setPassword(request.getParameter("password"));
user.setName(request.getParameter("name"));
user.setEmail(request.getParameter("email"));
user.setPhone(request.getParameter("phone"));
user.setBirthday(dateConvert.convert(request.getParameter("birthday")));
user.setSex(request.getParameter("sex"));
user.setType(request.getParameter("type"));
userDaoImpl.userRegister(user);
//注册成功,跳转到userLogin.jsp
redirectPage = "/userLogin.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}
/**
* 管理员登录
* */
@RequestMapping(value = "/administratorLogin", method = RequestMethod.POST)
public void administratorLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
HttpSession session = request.getSession();
//获取输入的用户名和密码
String userName = request.getParameter("userName");
String password = request.getParameter("password");
User user = null;
user = userDaoImpl.administratorLogin(userName,password);
//判断用户是否登录成功
if(user!=null){
if (user.getPassword().equals(password)) {
//登录成功 将user对象存到session中
session.setAttribute("admin",user);
//重新定向到首页
redirectPage = "/WEB-INF/views/administrator.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}else {
//密码错误
request.setAttribute("loginError","密码错误");
redirectPage = "/administratorLogin.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}
}else {
request.setAttribute("loginError","用户名不存在");
redirectPage = "/administratorLogin.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}
}
/**
* 管理员注销
* */
@RequestMapping(value = "/administratorLoginOut",method = RequestMethod.POST)
public void administratorLoginOut(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
HttpSession session = request.getSession();
//从session中将user删除
session.removeAttribute("user");
redirectPage = "/administratorLogin.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}
/**
* 商家登录
* */
@RequestMapping(value = "/shopLogin", method = RequestMethod.POST)
public void shopLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
HttpSession session = request.getSession();
//获取输入的用户名和密码
String shopName = request.getParameter("shopName");
String password = request.getParameter("password");
Shop shop = null;
shop = shopDaoImpl.shopLogin(shopName,password);
//判断用户是否登录成功
if(shop!=null){
if (shop.getPassword().equals(password)) {
//登录成功 将shop对象存到session中
session.setAttribute("shop",shop);
//重新定向到首页
redirectPage = "/WEB-INF/views/shop.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}else {
//密码错误
request.setAttribute("loginError","密码错误");
redirectPage = "/shopLogin.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}
}else {
request.setAttribute("loginError","商店名不存在");
redirectPage = "/shopLogin.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}
}
/**
* 商家注销
* */
@RequestMapping(value = "/shopLoginOut",method = RequestMethod.POST)
public void shopLoginOut(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
HttpSession session = request.getSession();
//从session中将shop删除
session.removeAttribute("shop");
redirectPage = "/shopLogin.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}
/**
* 商家注册
* */
@RequestMapping(value = "/shopRegister",method = RequestMethod.POST)
@ResponseBody
public void shopRegister(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
Shop shop = new Shop();
shop.setShopId(null);
shop.setShopName(request.getParameter("shopName"));
shop.setPassword(request.getParameter("password"));
shop.setEmail(request.getParameter("email"));
shop.setPhone(request.getParameter("phone"));
shop.setOwnerName(request.getParameter("ownerName"));
shopDaoImpl.shopRegister(shop);
//注册成功,跳转到shopLogin.jsp
redirectPage = "/shopLogin.jsp";
request.getRequestDispatcher(redirectPage).forward(request, response);
}
/**
* 商家,管理员跳转到主页
* */
@RequestMapping(value = "/redirectIndex", method = RequestMethod.POST)
@ResponseBody
public void redirectIndex(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
//跳转
redirectPage = "/index.jsp";
response.sendRedirect(redirectPage);
/*request.getRequestDispatcher(redirectPage).forward(request, response);*/
}
}
|
package pwnbrew.socks;
import java.io.IOException;
import java.net.InetAddress;
import pwnbrew.misc.Constants;
import pwnbrew.misc.DebugPrinter;
public class Socks4Impl {
private static final String NAME_Class = Socks4Impl.class.getSimpleName();
public byte SOCKS_Version = 0;
public SocksHandler m_Parent = null;
public byte socksCommand;
public byte DST_Port[] = null;
public byte DST_Addr[] = null;
public byte UserID[] = null;
public String UID = "";
//-------------------
protected String m_ServerAddr = null;
protected int m_nServerPort = 0;
public InetAddress m_ExtLocalIP = null;
//========================================================================
/**
*
* @param Parent
*/
public Socks4Impl( SocksHandler Parent ){
m_Parent = Parent;
DST_Addr = new byte[4];
DST_Port = new byte[2];
}
//========================================================================
/**
*
* @param code
* @return
*/
public String commName( byte code ) {
switch( code ) {
case 0x01: return "CONNECT";
case 0x02: return "BIND";
case 0x03: return "UDP Association";
default: return "Unknown Command";
}
}
//========================================================================
/**
*
* @param code
* @return
*/
public String replyName( byte code ){
switch( code ) {
case 0: return "SUCCESS";
case 1: return "General SOCKS Server failure";
case 2: return "Connection not allowed by ruleset";
case 3: return "Network Unreachable";
case 4: return "HOST Unreachable";
case 5: return "Connection Refused";
case 6: return "TTL Expired";
case 7: return "Command not supported";
case 8: return "Address Type not Supported";
case 9: return "to 0xFF UnAssigned";
case 90: return "Request GRANTED";
case 91: return "Request REJECTED or FAILED";
case 92: return "Request REJECTED - SOCKS server can't connect to Identd on the client";
case 93: return "Request REJECTED - Client and Identd report diff user-ID";
default: return "Unknown Command";
}
}
//========================================================================
/**
*
*/
public void calculateUserID(){
String s = UID + " ";
UserID = s.getBytes();
UserID[UserID.length-1] = 0x00;
}
//========================================================================
/**
*
* @return
*/
public byte getSuccessCode() {
return 90;
}
//========================================================================
/**
*
* @return
*/
public byte getFailCode(){
return 91;
}
//========================================================================
/**
*
* @return
*/
public String getServerAddress(){
return m_ServerAddr;
}
//========================================================================
/**
*
* @return
*/
public int getServerPort(){
return m_nServerPort;
}
//=========================================================================
/**
*
* @return
*/
public boolean calculateAddress() {
// IP v4 Address Type
InetAddress serverInet = Utils.getInstance().calcInetAddress( DST_Addr );
m_ServerAddr = serverInet.getHostAddress();
m_nServerPort = Utils.getInstance().calcPort( DST_Port[0], DST_Port[1] );
return ( (m_ServerAddr != null) && (m_nServerPort >= 0) );
}
//=========================================================================
/**
*
* @return
*/
protected byte getByte(){
byte b;
try{
b = m_Parent.getByteFromClient();
} catch( Exception e ) {
b = 0;
}
return b;
}
//=========================================================================
/**
*
* @param SOCKS_Ver
* @throws Exception
*/
public void authenticate( byte SOCKS_Ver ) throws Exception {
SOCKS_Version = SOCKS_Ver;
}
//=========================================================================
/**
*
* @throws Exception
*/
public void getClientCommand() throws Exception {
// Version was get in method Authenticate()
socksCommand = getByte();
DST_Port[0] = getByte();
DST_Port[1] = getByte();
for( int i=0; i<4; i++ ){
DST_Addr[i] = getByte();
}
byte b;
while( (b=getByte()) != 0x00 ){
UID += (char)b;
}
calculateUserID();
if( (socksCommand < Constants.SC_CONNECT) || (socksCommand > Constants.SC_BIND) ) {
refuseCommand( (byte)91 );
throw new Exception( "Socks 4 - Unsupported Command : "+commName( socksCommand ) );
}
if( !calculateAddress() ){ // Gets the IP Address
refuseCommand( (byte)92 ); // Host Not Exists...
throw new Exception( "Socks 4 - Unknown Host/IP address '"+m_ServerAddr.toString() );
}
//DebugPrinter.printMessage( NAME_Class , "getClientCommand", "Accepted SOCKS 4 Command: \""+ commName( socksCommand )+"\"", null );
}
//=========================================================================
/**
*
* @param ReplyCode
*/
public void replyCommand( byte ReplyCode ){
// DebugPrinter.printMessage( NAME_Class , "getClientCommand", "Socks 4 reply: \""+replyName( ReplyCode)+"\"", null );
byte[] retBytes = new byte[8];
retBytes[0]= 0;
retBytes[1]= ReplyCode;
retBytes[2]= DST_Port[0];
retBytes[3]= DST_Port[1];
retBytes[4]= DST_Addr[0];
retBytes[5]= DST_Addr[1];
retBytes[6]= DST_Addr[2];
retBytes[7]= DST_Addr[3];
m_Parent.sendToClient( retBytes, retBytes.length );
}
//=========================================================================
/**
*
* @param errorCode
*/
protected void refuseCommand( byte errorCode ){
DebugPrinter.printMessage( NAME_Class, "refuseCommand", "Socks 4 - Refuse Command: \""+replyName(errorCode)+"\"", null );
replyCommand( errorCode );
}
//=========================================================================
/**
*
* @throws Exception
*/
public void connect() throws Exception {
// DebugPrinter.printMessage( NAME_Class , "connect","Connecting...", null );
// //Connect to the Remote Host
boolean retVal;
try{
retVal = m_Parent.connectToServer(m_ServerAddr, m_nServerPort );
} catch( IOException e ) {
refuseCommand( getFailCode() ); // Connection Refused
throw new Exception("Socks 4 - Can't connect to " + m_ServerAddr + ":" + m_nServerPort );
}
//
// DebugPrinter.printMessage( NAME_Class, "Connected to "+ m_ServerIP.getHostAddress() + ":" + m_nServerPort );
byte retCode = getSuccessCode();
if( !retVal )
retCode = getFailCode();
replyCommand( retCode );
}
//========================================================================
/**
*
* @throws java.io.IOException
*/
public void udp() throws IOException {
DebugPrinter.printMessage(UID, "udp","Error - Socks 4 don't support UDP Association!", null );
DebugPrinter.printMessage(UID, "udp","Check your Software please...", null );
refuseCommand( (byte)91 ); // SOCKS4 don't support UDP
}
}
|
package code.demo.dao;
import java.util.List;
import org.hibernate.criterion.Criterion;
import code.demo.model.TestRecord;
public interface ITestRecordDao {
public List<TestRecord> selectAllTestRecord();
public List<TestRecord> selectTestRecordByRestrictions(Criterion criterion);
}
|
/*
* 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 domain;
import java.util.Date;
/**
*
* @author Marcos
*/
public class Pago {
private Integer idPago;
private String cedula;
private String direccion;
private String concepto;
private Date fechaSalida;
private Double total;
private Reservacion reservacion;
public Integer getIdPago() {
return idPago;
}
public void setIdPago(Integer idPago) {
this.idPago = idPago;
}
public String getCedula() {
return cedula;
}
public void setCedula(String cedula) {
this.cedula = cedula;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getConcepto() {
return concepto;
}
public void setConcepto(String concepto) {
this.concepto = concepto;
}
public Date getFechaSalida() {
return fechaSalida;
}
public void setFechaSalida(Date fechaSalida) {
this.fechaSalida = fechaSalida;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
public Reservacion getReservacion() {
return reservacion;
}
public void setReservacion(Reservacion reservacion) {
this.reservacion = reservacion;
}
}
|
package StepsDef;
import Utils.BoardUtils;
import com.jayway.restassured.response.Response;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import static junit.framework.TestCase.assertEquals;
import static com.jayway.restassured.RestAssured.given;
public class BoardsSteps {
// String key;
// String token;
// private String url = "https://api.trello.com/1/";
// Response response;
BoardUtils boardUtils = new BoardUtils();
@Given("I use {string} and {string}")
public void i_use_and(String key, String token) {
// this.key = key;
// this.token = token;
boardUtils.setKey(key);
boardUtils.setToken(token);
}
@When("I get board {string}")
public void i_get_board(String boardId) {
// response = given()
// .when()
//// .log().all()
// .get(url + "boards/"+boardId+"?key=" + key + "&token=" + token)
// .then()
// .extract()
// .response();
boardUtils.getBoard(boardId);
}
@Then("Response code is <{int}>")
public void response_code_is(int responseCode) {
//assertEquals(responseCode,response.statusCode());
assertEquals(responseCode,boardUtils.getResponseCode());
}
@Then("Board privacy is {string}")
public void boardPrivacyIs(String privacy) {
//assertEquals(privacy,response.path("prefs.permissionLevel"));
assertEquals(privacy,boardUtils.getPrivacy());
}
@When("I create board {string}")
public void iCreateBoard(String boardName) {
boardUtils.createBoard(boardName);
}
}
|
package pack.cd;
import pack.cd.exceptions.EmptyCdAlbumException;
import pack.cd.exceptions.NullAlbumObjectException;
import pack.cd.interfaces.DBable;
import pack.cd.interfaces.Library;
import pack.cd.interfaces.Sortable;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
public class CdLibrary implements Library, Sortable, DBable, Serializable {
public CdLibrary() {
readDb();
}
private List<CdAlbum> cdAlbumsList = new ArrayList<>();
List<CdAlbum> getCdAlbumsList() {
return cdAlbumsList;
}
private void checkForEmptyCdAlbumException() {
if (cdAlbumsList == null || cdAlbumsList.size() == 0) {
throw new EmptyCdAlbumException("Album list is null or empty!");
}
}
@Override
public void printRecords() {
checkForEmptyCdAlbumException();
for (CdAlbum album : cdAlbumsList) {
System.out.println(album);
}
}
public void printRecords(List<CdAlbum> cdAlbumsSortList) {
checkForEmptyCdAlbumException();
for (CdAlbum album : cdAlbumsSortList) {
System.out.println(album);
}
}
@Override
public void addRecord(CdAlbum album) {
if (album == null) {
throw new NullAlbumObjectException("Album object is null!");
}
cdAlbumsList.add(album);
}
@Override
public void editRecord(int id, CdAlbum newAlbum) {
checkForEmptyCdAlbumException();
if (newAlbum == null) {
throw new NullAlbumObjectException("Album object is null!");
}
int index = getIndexById(id);
cdAlbumsList.set(index, newAlbum);
System.out.println("Album correctly edited!");
}
public List<CdAlbum> searchFor(String search) {
checkForEmptyCdAlbumException();
return cdAlbumsList.stream()
.filter(e -> e.getArtist().toLowerCase().contains(search.toLowerCase()) ||
e.getTitle().toLowerCase().contains(search.toLowerCase())).collect(Collectors.toList());
}
@Override
public void deleteRecord(int id) {
checkForEmptyCdAlbumException();
boolean isDeleted = cdAlbumsList.removeIf(album -> album.getCdId() == id);
if (isDeleted) {
System.out.printf("Album with id : %d removed succesfully! \n", id);
} else {
System.out.printf("Album with id : %d not found! \n", id);
}
}
@Override
public String getStatistics() {
checkForEmptyCdAlbumException();
DoubleSummaryStatistics priceStat =
cdAlbumsList.stream().mapToDouble(CdAlbum::getPriceBought).summaryStatistics();
return "\nNumber of CD's on the shelf : " + priceStat.getCount() +
"\nThe cheapest CD: " + priceStat.getMin() +
"\nThe most expensive CD: " + priceStat.getMax() +
"\nAvg bought price CD: " + priceStat.getAverage();
}
@Override
public List<CdAlbum> getSortedByTitleRecords() {
checkForEmptyCdAlbumException();
return cdAlbumsList.stream()
.sorted()
.collect(Collectors.toList());
}
@Override
public List<CdAlbum> getSortedByArtistRecords() {
checkForEmptyCdAlbumException();
return cdAlbumsList.stream()
.sorted(Comparator.comparing(CdAlbum::getArtist))
.collect(Collectors.toList());
}
@Override
public List<CdAlbum> getSortedByIdAsc() {
checkForEmptyCdAlbumException();
return cdAlbumsList.stream()
.sorted(Comparator.comparingInt(CdAlbum::getCdId))
.collect(Collectors.toList());
}
@Override
public List<CdAlbum> getSortedByIdDesc() {
checkForEmptyCdAlbumException();
return cdAlbumsList.stream()
.sorted((x, y) -> y.getCdId() - x.getCdId())
.collect(Collectors.toList());
}
@Override
public List<CdAlbum> getSortedByRecordPrice() {
checkForEmptyCdAlbumException();
return cdAlbumsList.stream()
.sorted(Comparator.comparingInt(x -> (int) x.getPriceBought()))
.collect(Collectors.toList());
}
@Override
public void readDb() {
try (InputStream is = Files.newInputStream(Paths.get("albumlist.ser"))) {
try (ObjectInputStream input = new ObjectInputStream(is)){
cdAlbumsList = (List<CdAlbum>) input.readObject();
System.out.println("\nDatabase read successfull...");
getMaxIdFromDbList().ifPresentOrElse(e -> CdAlbum.setId(e + 1), () -> CdAlbum.setId(1));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void writeDb() {
checkForEmptyCdAlbumException();
try (OutputStream os = Files.newOutputStream(Paths.get("albumlist.ser"))) {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
objectOutputStream.writeObject(cdAlbumsList);
System.out.println("Database write successful...");
} catch (IOException e) {
e.printStackTrace();
}
}
private int getIndexById(int id) {
checkForEmptyCdAlbumException();
int indexOfAlbum = -1;
for (CdAlbum album : cdAlbumsList) {
if (album.getCdId() == id) {
indexOfAlbum = cdAlbumsList.indexOf(album);
}
}
return indexOfAlbum;
}
public boolean isAlbumInList(int id) {
checkForEmptyCdAlbumException();
for (CdAlbum album : cdAlbumsList) {
if (album.getCdId() == id) {
return true;
}
}
return false;
}
private Optional<Integer> getMaxIdFromDbList() {
return cdAlbumsList.stream()
.max((Comparator.comparingInt(CdAlbum::getCdId)))
.map(CdAlbum::getCdId);
}
}
// POPULATE IN CASE OF EMPTY DB / OR DB DEGUG
// private void populateAlbumsList() {
// addRecord(new CdAlbum("Jerry Cantrell", "Bogy Depot", "rock album", 36.99));
// addRecord(new CdAlbum("Alice in Chains", "Facelift", "grunge album", 43.19));
// addRecord(new CdAlbum("Nirvana", "Nevermind", "grunge album", 59.69));
// addRecord(new CdAlbum("Stone temple pilots", "Core", "rock album", 13.99));
// addRecord(new CdAlbum("Death", "Scream Bloody Gore", "metal album", 29.99));
// } |
package com.navarromugas.models;
public class Dios {
private Mundo mundo;
private Gps gps;
public Dios(Gps gps) {
this.gps = gps;
mundo = new Mundo(gps);
}
public void avanzarUnaGeneracion() {
Mundo viejoMundo = mundo.clonar();
for (int i = 0; i < gps.getParalelos(); i++)
for (int j = 0; j < gps.getMeridianos(); j++) {
Coordenada ubicacion = new Coordenada(i, j);
if (Reglas.isCelulaVivaEnProximaGeneracion(viejoMundo.getParcela(ubicacion)))
mundo.revivirCelula(ubicacion);
else
mundo.matarCelula(ubicacion);
}
}
public Mundo mundoCreado() {
return mundo;
}
public void darMundo(Mundo mundo) {
this.mundo = mundo;
}
}
|
//package com.pshc.cmg.service;
//
//import java.io.FileInputStream;
//import java.io.IOException;
//import java.util.Arrays;
//import java.util.List;
//
//import org.springframework.stereotype.Service;
//
//import com.google.auth.oauth2.GoogleCredentials;
//import com.google.firebase.FirebaseApp;
//import com.google.firebase.FirebaseOptions;
//import com.google.firebase.messaging.FirebaseMessaging;
//import com.google.firebase.messaging.FirebaseMessagingException;
//import com.google.firebase.messaging.Message;
//import com.google.firebase.messaging.TopicManagementResponse;
//import com.pshc.cmg.dto.PostDto;
//
//@Service
//public class FirebaseService {
// private FileInputStream serviceAccount;
// private FirebaseOptions options;
// private final String TOPIC_NAME = "cmg";
//
// public FirebaseService() throws IOException {
//
// serviceAccount = new FileInputStream(
// "C:/firebasejson/sens-9b12a-firebase-adminsdk-iz13g-f76efe3625.json");
//
// options = new FirebaseOptions.Builder()
// .setCredentials(GoogleCredentials.fromStream(serviceAccount)).setProjectId("sens-9b12a")
// .setDatabaseUrl("https://sens-9b12a.firebaseio.com").build();
//
// FirebaseApp.initializeApp(options);
//
// }
//
// public void topic(String token) {
// List<String> registrationTokens = Arrays.asList(token);
// try {
// TopicManagementResponse response = FirebaseMessaging.getInstance().subscribeToTopic(registrationTokens,
// "cmg");
// System.out.println(response.getSuccessCount() + "tokens were subctibed successfully");
// System.out.println(response.getFailureCount() + "fail count");
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// public void sendMessaging() {
// String token = "f1yeB4ge4Sw:APA91bHdO3Gkg6F2F4_1VrPl1-9UZViPrrKVfRlGNcxvkVPkT09SPjqc6zKB5y6FVaputsJxZo_DXwBEAvNY-ydHB6XMPNmZAmjU2kXbxqfDCBB8AmRFiwgLV9RBrgnMkGF8LRzF5tfx";
//
// Message message = Message.builder().putData("관리자 알림", "공지사항이 등록되었습니다 확인하세요").setToken(token).build();
// try {
// String response = FirebaseMessaging.getInstance().send(message);
// System.out.println("Successfully sent message: " + response);
// } catch (FirebaseMessagingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
// public void sendTopicsMessaging(PostDto postDto) {
// Message message = Message.builder().putData("관리자 알림:", "공지사항이 등록되었습니다 확인하세요").setTopic(TOPIC_NAME).build();
//
// try {
// String response = FirebaseMessaging.getInstance().send(message);
// System.out.println("Successfully sent message: " + response);
//
// } catch (FirebaseMessagingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
//
//}
|
package com.weathair.dto;
import com.weathair.entities.Role;
import com.weathair.entities.Township;
public class UserResponseDto {
private String pseudo;
private String email;
private String password;
private Township township;
private Role role;
public UserResponseDto() {
super();
}
public String getPseudo() {
return pseudo;
}
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Township getTownship() {
return township;
}
public void setTownship(Township township) {
this.township = township;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
|
package com.git.cloud.excel.service.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.git.cloud.appmgt.service.IDeployunitService;
import com.git.cloud.common.dao.ICommonDAO;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.excel.model.po.ExcelInfoPo;
import com.git.cloud.excel.model.vo.DataStoreVo;
import com.git.cloud.excel.model.vo.HostVo;
import com.git.cloud.excel.model.vo.VmVo;
import com.git.cloud.excel.service.IExcelWriteDataBaseService;
import com.git.cloud.foundation.util.UUIDGenerator;
import com.git.cloud.request.tools.SrDateUtil;
import com.git.cloud.resmgt.common.dao.ICmPasswordDAO;
import com.git.cloud.resmgt.common.model.po.CmDevicePo;
import com.git.cloud.resmgt.common.model.po.CmPasswordPo;
import com.git.cloud.resmgt.common.model.po.RmDatacenterPo;
import com.git.cloud.resmgt.common.service.IRmDatacenterService;
import com.git.cloud.resmgt.compute.model.po.RmClusterPo;
import com.git.cloud.resmgt.network.model.po.RmNwIpAddressPo;
import com.git.support.util.PwdUtil;
public class ExcelWriteDataBaseServiceImpl implements
IExcelWriteDataBaseService {
private ICommonDAO iCommonDAO;
private IRmDatacenterService rmDataCenterService;
private IDeployunitService deployunitServiceImpl;
private ICmPasswordDAO cmPasswordDAO;
public ICmPasswordDAO getCmPasswordDAO() {
return cmPasswordDAO;
}
public void setCmPasswordDAO(ICmPasswordDAO cmPasswordDAO) {
this.cmPasswordDAO = cmPasswordDAO;
}
public void setDeployunitServiceImpl(IDeployunitService deployunitServiceImpl) {
this.deployunitServiceImpl = deployunitServiceImpl;
}
public void setRmDataCenterService(IRmDatacenterService rmDataCenterService) {
this.rmDataCenterService = rmDataCenterService;
}
public void setiCommonDAO(ICommonDAO iCommonDAO) {
this.iCommonDAO = iCommonDAO;
}
@Override
public String saveDataCenterByCode(List<HostVo> hostVoList,List<VmVo> vmList,List<DataStoreVo> dsList,String fileName) throws Exception {
boolean resultflag = true;
String result = "";
if(hostVoList.size() > 0 ){
for (int i = 0; i < hostVoList.size(); i++) {
HostVo vo = hostVoList.get(i);
List<RmDatacenterPo> datacenterPoList = iCommonDAO.findListByParam("selectDataCenterByCode", vo.getDataCenterCode());
if(datacenterPoList.size() > 0){
resultflag = true;
List<RmClusterPo> clusterPoList = iCommonDAO.findListByParam("selectClusterByEname", vo.getClusterCode());
if(clusterPoList.size() > 0){
resultflag = true;
}else{
result = "物理机中的集群编码:"+vo.getClusterCode()+"不存在";
resultflag = false;
return result;
}
}else{
resultflag = false;
result = "物理机中的数据中心编码:"+vo.getDataCenterCode()+"不存在";
return result;
}
}
}
if(vmList.size() > 0){
for(int i =0;i<vmList.size();i++){
VmVo vo = vmList.get(i);
List<RmClusterPo> clusterPoList = iCommonDAO.findListByParam("selectClusterByEname", vo.getClusterCode());
if(clusterPoList.size() > 0 ){
resultflag = true;
}
}
}
if(resultflag){
Map hostIdMap = new HashMap();
for(int i=0;i<hostVoList.size();i++){
List<RmClusterPo> clusterPoList = iCommonDAO.findListByParam("selectClusterByEname", hostVoList.get(i).getClusterCode());
RmClusterPo clu = clusterPoList.get(0);
HostVo hostVo = hostVoList.get(i);
CmDevicePo cmDevicePo = new CmDevicePo();
cmDevicePo.setId(UUIDGenerator.getUUID());
cmDevicePo.setDeviceName(hostVo.getHostName());
cmDevicePo.setSn(hostVo.getHostSn());
cmDevicePo.setResPoolId(clu.getResPoolId());
cmDevicePo.setDeviceModelId(hostVo.getDeviceModelId());
cmDevicePo.setSeatId(hostVo.getSeatId());
hostIdMap.put(cmDevicePo.getDeviceName(), cmDevicePo.getId());
//向CM_LOCAL_DISK表中添加数据
for(int j=0;j<dsList.size();j++){
DataStoreVo dataStoreVo = dsList.get(j);
if(dataStoreVo.getHostName().equals(hostVo.getHostIp())){
dataStoreVo.setId(UUIDGenerator.getUUID());
dataStoreVo.setDeviceId(cmDevicePo.getId());
hostVo.setDefaultDatastoreId(dataStoreVo.getId());
iCommonDAO.save("insertLocalDisk", dataStoreVo);
}
}
//向CM_DEVICE表中插入数据
iCommonDAO.save("insertCmDevicePo", cmDevicePo);
//向CM_HOST表中插入数据
hostVo.setId(cmDevicePo.getId());
hostVo.setClusterId(clu.getId());
hostVo.setDefaultDatastoreType("LOCAL_DISK");
iCommonDAO.save("insertCmHostPo", hostVo);
//向CM_PASSWORD表中填写用户名、密码等信息
CmPasswordPo cmPasswordPo = new CmPasswordPo(UUIDGenerator.getUUID());
cmPasswordPo.setResourceId(cmDevicePo.getId());
cmPasswordPo.setUserName(hostVo.getHostUser());
cmPasswordPo.setPassword(PwdUtil.encryption(hostVo.getHostPwd()));
cmPasswordPo.setLastModifyTime(SrDateUtil.getSrFortime(new Date()));
cmPasswordDAO.insertCmPassword(cmPasswordPo);
//占用网络资源池
String[] ips = hostVo.getHostIp().split(",");
List<RmNwIpAddressPo> rmNwIpList = null; //(此处代码需要进行改造) iCommonDAO.findListByParam("selectRmNwIpAddressByIp", ips[0]);
if(rmNwIpList.size() > 0){
RmNwIpAddressPo addressPo = rmNwIpList.get(0);
addressPo.setDeviceId(cmDevicePo.getId());
addressPo.setAllocedStatusCode("A2DV");
addressPo.setNwRuleListId(hostVo.getNwRuleListId());
iCommonDAO.update("updateIpAddress", addressPo);
// 更新资源池可用ip(此处代码需要进行改造)
//RmNwResPoolPo resPo = null;//nwResPoolDAO.findResPool(addressPo.getNwResPoolId());
//resPo.setIpAvailCnt(resPo.getIpAvailCnt() - 1);
//nwResPoolDAO.updateAvailCnt(resPo);
}else{
result = "没有可分配的网络资源池";
return result;
}
}
/*for(int i=0;i<dsList.size();i++){
DataStoreVo dataStoreVo = dsList.get(i);
dataStoreVo.setId(UUIDGenerator.getUUID());
iCommonDAO.save("insertCmDataStorePo", dataStoreVo);
}*/
/*if(vmList.size() > 0){
for(int i=0;i<vmList.size();i++){
VmVo vmVo = vmList.get(i);
// iCommonDAO.save("insertCmVmPo", vmVo);
CmDevicePo cmDevicePo = new CmDevicePo();
cmDevicePo.setId(UUIDGenerator.getUUID());
cmDevicePo.setDeviceName(vmVo.getVmName());
iCommonDAO.save("insertCmDevicePo", cmDevicePo);
CmVmPo cmVmPo = new CmVmPo();
cmVmPo.setId(cmDevicePo.getId());
cmVmPo.setCpu(Integer.parseInt(vmVo.getVmCpu()));
cmVmPo.setHostId(vmVo.getId());
cmVmPo.setMem(Integer.parseInt(vmVo.getVmMem()));
cmVmPo.setDuId(vmVo.getDuId());
iCommonDAO.save("insertCmVmPo", cmVmPo);
String datacenterCode = vmVo.getDataCenterCode();
DeployUnitVo deployUnitVo = deployunitServiceImpl.getDeployUnitById(vmVo.getDuId());
RmDatacenterPo rmDatacenterPo = rmDataCenterService.selectDCenamefortrim(datacenterCode);
AppStatVo appStatVo =new AppStatVo();
appStatVo.setDataCenterID(rmDatacenterPo.getId());
appStatVo.setCpu(Integer.parseInt(vmVo.getVmCpu()));
appStatVo.setDisk(0);
appStatVo.setMem(Integer.parseInt(vmVo.getVmMem()));
appStatVo.setServiceID("0");
appStatVo.setDuID(vmVo.getDuId());
appStatVo.setSrStatusCode("REQUEST_CLOSED");
appStatVo.setSrTypeMark(SrTypeMarkEnum.VIRTUAL_NEW.getValue());
appStatVo.setDiviceID(UUIDGenerator.getUUID());
appStatVo.setAppID(deployUnitVo.getAppId());
appMagServiceImpl.addAppStat(appStatVo);
String[] ips = vmVo.getVmIp().split(",");
List<RmNwIpAddressPo> rmNwIpList = iCommonDAO.findListByParam("selectRmNwIpAddressByIp", ips[0]);
if(rmNwIpList.size() > 0){
RmNwIpAddressPo addressPo = rmNwIpList.get(0);
addressPo.setDeviceId((String) hostIdMap.get(vmVo.getHostName()));
iCommonDAO.update("updateIpAddress", addressPo);
}
}
}*/
ExcelInfoPo excelInfoPo = iCommonDAO.findObjectByID("selectExcelInfoByName", fileName);
if(excelInfoPo != null){
excelInfoPo.setIsInput("Y");
iCommonDAO.update("updateExcelInfoByName", excelInfoPo);
result = "写入成功";
return result;
}
}else{
}
return result;
}
@Override
public String selecthostIdByName(String name) throws RollbackableBizException {
HostVo v = iCommonDAO.findObjectByID("selecthostIdByName", name);
return v.getId();
}
}
|
/**
* @Author: Mahmoud Abdelrahman
* User Entity is where all User specifications are declared.
*/
package com.easylearn.easylearn.entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // Auto Increament
protected Long id;
@Column(nullable = false)
protected String firstName;
@Column(nullable = false)
protected String lastName;
@Column(unique = true, nullable = false)
protected String username;
@Column(nullable = false)
protected String password;
}
|
package com.soft1841.bookdemo;
import javax.swing.*;
/**
* 进度条的滚动
* @author 黄敬理
* 2019.04.11
*/
public class JoinThreadTest1 implements Runnable {
private JProgressBar jProgressBar1;
public void setjProgressBar1(JProgressBar jProgressBar1) {
this.jProgressBar1 = jProgressBar1;
}
@Override
public void run() {
int count = 0;
while (true){
jProgressBar1.setValue(++count);
try {
Thread.sleep(100);
if (count == 80){
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
package com.leinad.web.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public class HelloDto {
@JsonProperty("name")
public String name;
@JsonProperty("message")
public String message;
}
|
package org.apache.hadoop.hdfs.server.namenode.lock;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hdfs.protocol.UnresolvedPathException;
import org.apache.hadoop.hdfs.server.namenode.FinderType;
import org.apache.hadoop.hdfs.server.namenode.INode;
import org.apache.hadoop.hdfs.server.namenode.lock.TransactionLockManager.*;
import org.apache.hadoop.hdfs.server.namenode.persistance.EntityManager;
import org.apache.hadoop.hdfs.server.namenode.persistance.PersistanceException;
/**
*
* @author Hooman <hooman@sics.se>
*/
public class TransactionLockAcquirer {
public static ConcurrentHashMap<String, ReentrantLock> datanodeLocks = new ConcurrentHashMap<String, ReentrantLock>();
private final static Log LOG = LogFactory.getLog(TransactionLockAcquirer.class);
public static void addToDataNodeLockMap(String storageId) {
datanodeLocks.put(storageId, new ReentrantLock(true));
}
public static void removeFromDataNodeLockMap(String storageId) {
throw new UnsupportedOperationException("removing datanodes from locks is not supported.");
}
public boolean lockDataNode(String storageId) {
if (datanodeLocks.contains(this)) {
datanodeLocks.get(storageId).lock();
return true;
}
return false;
}
public static <T> Collection<T> acquireLockList(TransactionLockManager.LockType lock, FinderType<T> finder, Object... param) throws PersistanceException {
setLockMode(lock);
if (param == null) {
return EntityManager.findList(finder);
} else {
return EntityManager.findList(finder, param);
}
}
public static <T> T acquireLock(TransactionLockManager.LockType lock, FinderType<T> finder, Object... param) throws PersistanceException {
setLockMode(lock);
if (param == null) {
return null;
}
return EntityManager.find(finder, param);
}
public static LinkedList<INode> acquireLockOnRestOfPath(INodeLockType lock, INode baseInode,
String fullPath, String prefix, boolean resolveLink) throws PersistanceException, UnresolvedPathException {
LinkedList<INode> resolved = new LinkedList<INode>();
byte[][] fullComps = INode.getPathComponents(fullPath);
byte[][] prefixComps = INode.getPathComponents(prefix);
int[] count = new int[]{prefixComps.length - 1};
boolean lastComp;
lockINode(lock);
INode[] curInode = new INode[]{baseInode};
while (count[0] < fullComps.length && curInode[0] != null) {
lastComp = INodeUtil.getNextChild(
curInode,
fullComps,
count,
resolved,
resolveLink,
true);
if (lastComp) {
break;
}
}
return resolved;
}
public static LinkedList<INode> acquireInodeLockByPath(INodeLockType lock, String path, boolean resolveLink) throws UnresolvedPathException, PersistanceException {
LinkedList<INode> resolvedInodes = new LinkedList<INode>();
if (path == null) {
return resolvedInodes;
}
byte[][] components = INode.getPathComponents(path);
INode[] curNode = new INode[1];
int[] count = new int[]{0};
boolean lastComp = (count[0] == components.length - 1);
if (lastComp) // if root is the last directory, we should acquire the write lock over the root
{
resolvedInodes.add(acquireLockOnRoot(lock));
return resolvedInodes;
} else if ((count[0] == components.length - 2) && lock == INodeLockType.WRITE_ON_PARENT) // if Root is the parent
{
curNode[0] = acquireLockOnRoot(lock);
} else {
curNode[0] = acquireLockOnRoot(INodeLockType.READ_COMMITED);
}
while (count[0] < components.length && curNode[0] != null) {
// TODO - memcached - primary key lookup for the row.
if (((lock == INodeLockType.WRITE || lock == INodeLockType.WRITE_ON_PARENT) && (count[0] + 1 == components.length - 1))
|| (lock == INodeLockType.WRITE_ON_PARENT && (count[0] + 1 == components.length - 2))) {
EntityManager.writeLock(); // if the next p-component is the last one or is the parent (in case of write on parent), acquire the write lock
} else if (lock == INodeLockType.READ_COMMITED) {
EntityManager.readCommited();
} else {
EntityManager.readLock();
}
lastComp = INodeUtil.getNextChild(
curNode,
components,
count,
resolvedInodes,
resolveLink,
true);
if (lastComp) {
break;
}
}
// TODO - put invalidated cache values in memcached.
return resolvedInodes;
}
// TODO - use this method when there's a hit in memcached
// Jude's verification function
public static INode acquireINodeLockById(INodeLockType lock, long id) throws PersistanceException {
lockINode(lock);
return EntityManager.find(INode.Finder.ByPKey, id);
}
public static INode acquireINodeLockByNameAndParentId(
INodeLockType lock,
String name,
long parentId)
throws PersistanceException {
lockINode(lock);
return EntityManager.find(INode.Finder.ByNameAndParentId, name, parentId);
}
private static void lockINode(INodeLockType lock) {
switch (lock) {
case WRITE:
case WRITE_ON_PARENT:
EntityManager.writeLock();
break;
case READ:
EntityManager.readLock();
break;
case READ_COMMITED:
EntityManager.readCommited();
break;
}
}
private static INode acquireLockOnRoot(INodeLockType lock) throws PersistanceException {
lockINode(lock);
INode inode = EntityManager.find(INode.Finder.ByPKey, 0L);
LOG.debug("Acquired " + lock + " on the root node");
return inode;
}
private static void setLockMode(LockType mode) {
switch (mode) {
case WRITE:
EntityManager.writeLock();
break;
case READ:
EntityManager.readLock();
break;
case READ_COMMITTED:
EntityManager.readCommited();
break;
}
}
}
|
package com.sun.xml.bind.v2.model.core;
/**
* Reference to a {@link NonElement}.
*
* This interface defines properties of a reference.
*
* @author Kohsuke Kawaguchi
*/
public interface NonElementRef<T,C> {
/**
* Target of the reference.
*
* @return never null
*/
NonElement<T,C> getTarget();
/**
* Gets the property which is the source of this reference.
*
* @return never null
*/
PropertyInfo<T,C> getSource();
}
|
package java8.functional_interface;
@FunctionalInterface
public interface SummableInterface {
public int sum(int a, int b);
}
|
package fr.utt.if26.memoria;
import android.content.Context;
import android.media.MediaPlayer;
import java.io.IOException;
public class SoundBox {
private static SoundBox instance = null;
private Context context;
private boolean soundsOn;
private MediaPlayer music;
private MediaPlayer bip;
private MediaPlayer cardFlip;
private SoundBox(Context ctx) {
this.context = ctx;
this.music = MediaPlayer.create(this.context,R.raw.miisong);
this.bip = MediaPlayer.create(this.context, R.raw.bip);
this.cardFlip = MediaPlayer.create(this.context, R.raw.cardflip);
this.soundsOn = true;
}
public static SoundBox getInstance(Context ctx) {
if( SoundBox.instance == null )
SoundBox.instance = new SoundBox(ctx);
else
SoundBox.instance.setContext(ctx);
return SoundBox.instance;
}
public void setContext(Context ctx) {
this.context = ctx;
}
public void toggleSounds(){
this.toggleSounds(!this.soundsOn);
}
public void toggleSounds(boolean flag){
this.soundsOn = flag;
}
public void bip() {
if( ! this.soundsOn ) return;
this.bip.start();
}
public void cardFlip() {
if( ! this.soundsOn ) return;
this.cardFlip.start();
}
public void startMusic() {
this.music.start();
this.music.setLooping(true);
}
public void stopMusic() {
this.music.pause();
}
}
|
package com.lumpofcode.expression;
import com.lumpofcode.utils.NumberFormatter;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by emurphy on 11/30/16.
*/
public class ExpressionTreeHelperTest
{
@Test
public void testEvaluateNextOperation()
{
// formatter truncates doubles to ints
final NumberFormatter numberFormatter = (d) -> String.valueOf((int)d);
assertEquals("1 + 2 evaluates to 3", "3", ExpressionTreeHelper.evaluateNextOperation("1 + 2", numberFormatter));
assertEquals("(1 + 2) evaluates to 3", "3", ExpressionTreeHelper.evaluateNextOperation("1 + 2", numberFormatter));
assertEquals("(3) evaluates to 3", "3", ExpressionTreeHelper.evaluateNextOperation("1 + 2", numberFormatter));
assertEquals("1 + 2 + 3 evaluates to 3 + 3", "3 + 3", ExpressionTreeHelper.evaluateNextOperation("1 + 2 + 3", numberFormatter));
assertEquals("1 + 2 * 3 evaluates to 1 + 6", "1 + 6", ExpressionTreeHelper.evaluateNextOperation("1 + 2 * 3", numberFormatter));
assertEquals("(1 + 2) * 3 evaluates to 3 * 3", "3 * 3", ExpressionTreeHelper.evaluateNextOperation("(1 + 2) * 3", numberFormatter));
assertEquals("1 + (2 * 3) evaluates to 1 + 6", "1 + 6", ExpressionTreeHelper.evaluateNextOperation("1 + (2 * 3)", numberFormatter));
assertEquals("(1 + (2 * 3)) evaluates to (1 + 6)", "(1 + 6)", ExpressionTreeHelper.evaluateNextOperation("(1 + (2 * 3))", numberFormatter));
//
// the process reformats with space around operators
//
assertEquals("1+2+3 evaluates to 3 + 3", "3 + 3", ExpressionTreeHelper.evaluateNextOperation("1+2+3", numberFormatter));
//
// shows how to evaluate to a final answer one step at a time
// 4 + ((1 + 2) * 3) * 5
// 4 + (3 * 3) * 5
// 4 + 9 * 5
// 4 + 45
// 49
//
assertEquals("4 + ((1 + 2) * 3) * 5 evaluates to 4 + (3 * 3) * 5", "4 + (3 * 3) * 5", ExpressionTreeHelper.evaluateNextOperation("4 + ((1 + 2) * 3) * 5", numberFormatter));
assertEquals("4 + (3 * 3) * 5 evaluates to 4 + 9 * 5", "4 + 9 * 5", ExpressionTreeHelper.evaluateNextOperation("4 + (3 * 3) * 5", numberFormatter));
assertEquals("4 + 9 * 5 evaluates to 4 + 45", "4 + 45", ExpressionTreeHelper.evaluateNextOperation("4 + 9 * 5", numberFormatter));
assertEquals("4 + 45 evaluates to 49", "49", ExpressionTreeHelper.evaluateNextOperation("4 + 45", numberFormatter));
assertEquals("49 evaluates to 49", "49", ExpressionTreeHelper.evaluateNextOperation("49", numberFormatter));
String theExpression = "4 + ((1 + 2) * 3) * 5";
String theSimplifiedExpression = ExpressionTreeHelper.evaluateNextOperation(theExpression, numberFormatter);
//
// simplify until we have a literal value
//
System.out.println(theExpression);
while(!theExpression.equals(theSimplifiedExpression))
{
theExpression = theSimplifiedExpression;
System.out.println(theExpression);
theSimplifiedExpression = ExpressionTreeHelper.evaluateNextOperation(theExpression, numberFormatter);
}
//
// illegal expressions will throw a parse error
//
try
{
ExpressionTreeHelper.evaluateNextOperation("2 + 3 +", numberFormatter);
fail("A ParseException should be thrown, we should not get here.");
}
catch(ExpressionParser.ParseException e)
{
assertTrue(true);
}
catch(Throwable e)
{
fail("Unexpected exception thrown.");
}
}
@Test
public void testNextParenthesisOperation()
{
final String expressionText = "10 + 5 * -6 - (-20 / (-2 + 3)) + -100 - 50";
final ExpressionParser.Expression expressionTree = ExpressionParser.parse(expressionText);
final ExpressionParser.Expression operation = ExpressionTreeHelper.nextOperation(expressionTree);
assertNotNull("There should be an operation", operation);
assertTrue("It should be a parenthesis operation", operation instanceof ExpressionParser.ParenthesisExpression);
assertEquals("It should be at index 21 of input", 21, operation.startIndex());
assertEquals("It should extent up to (not including) index 29 of input", 29, operation.endIndex());
assertEquals("It should format to (-2 + 3)", "(-2 + 3)", operation.format());
}
@Test
public void testNextMultiplicationOperation()
{
final String expressionText = "10 + 5 * -6 - -20 / -2 + 3 + -100 - 50";
final ExpressionParser.Expression expressionTree = ExpressionParser.parse(expressionText);
final ExpressionParser.Expression operation = ExpressionTreeHelper.nextOperation(expressionTree);
assertNotNull("There should be an operation", operation);
assertTrue("It should be a multiplication operation", operation instanceof ExpressionParser.MultiplicationExpression);
assertEquals("It should start at index 5 of input", 5, operation.startIndex());
assertEquals("It should extend to index 11 of input.", 11, ((ExpressionParser.MultiplicationExpression)operation).right().endIndex());
assertEquals("Operator should be at index 7 of input", 7, ((ExpressionParser.MultiplicationExpression)operation).right().startIndex());
assertEquals("Operator is a multiplication", "*", ((ExpressionParser.MultiplicationExpression)operation).right().operator());
}
@Test
public void testNextAdditionOperation()
{
final String expressionText = "10 - 5 + -6 - -20";
final ExpressionParser.Expression expressionTree = ExpressionParser.parse(expressionText);
final ExpressionParser.Expression operation = ExpressionTreeHelper.nextOperation(expressionTree);
assertNotNull("There should be an operation", operation);
assertTrue("It should be an addition operation", operation instanceof ExpressionParser.AdditionExpression);
assertEquals("It should start at index 0 of input", 0, operation.startIndex());
assertEquals("It should extend to index 6 of input.", 6, ((ExpressionParser.AdditionExpression)operation).right().endIndex());
assertEquals("Operator should be at index 3 of input", 3, ((ExpressionParser.AdditionExpression)operation).right().startIndex());
assertEquals("Operator is a subtraction", "-", ((ExpressionParser.AdditionExpression)operation).right().operator());
}
@Test
public void removeParenthesisTest()
{
assertEquals("2 + 3", ExpressionTreeHelper.removeParenthesis("(((2)+(3)))"));
assertEquals("1 + 2 + 3", ExpressionTreeHelper.removeParenthesis("1 + (((2)+(3)))"));
assertEquals("1 + 2 + 3", ExpressionTreeHelper.removeParenthesis("(1+2+3)"));
assertEquals("1 + 2 + 3", ExpressionTreeHelper.removeParenthesis("((1+2+3))"));
assertEquals("1 + 2 + 3", ExpressionTreeHelper.removeParenthesis("((1+2)+3)"));
assertEquals("1 + 2 + 3", ExpressionTreeHelper.removeParenthesis("(1+(2)+3)"));
assertEquals("1 + 2 + 3", ExpressionTreeHelper.removeParenthesis("(1+(2+3))"));
assertEquals("1 + 2 + 3", ExpressionTreeHelper.removeParenthesis("(((1)+(((2)+(3)))))"));
assertEquals("1 * 2 * 3 / 6", ExpressionTreeHelper.removeParenthesis("1 * 2 * (3 / 6)"));
}
}
|
package chess;
/**
* Class performs all the functionality of the rook piece and inherits from the
* class ChessPiece.
*
* @author Andrew Olesak
* @version February 23, 2016
*/
public class Rook extends ChessPiece {
/**
* Constructor calls the super class to set the type of the player black or
* white
*
* @param player
* the type of player black or white
*/
public Rook(Player player) {
super(player);
}
/**
* @return a string representing the type of the piece
*/
public String type() {
return "Rook";
}
/**
* Verifies whether the suggested move for a rook is allowed or not
*
* @param move
* the move of the piece
* @param board
* a two dimensional array of the chess board
* @return true if the move is valid, otherwise false
*/
public boolean isValidMove(Move move, IChessPiece[][] board) {
if (!super.isValidMove(move, board)) {
return false;
}
if (move.fromRow != move.toRow && move.fromColumn != move.toColumn) {
return false;
}
if (move.fromRow == move.toRow) {
if (move.fromColumn < move.toColumn) {
for (int col = move.fromColumn + 1; col < move.toColumn; col++) {
if (board[move.toRow][col] != null) {
return false;
}
}
} else {
for (int col = move.toColumn + 1; col < move.fromColumn; col++) {
if (board[move.toRow][col] != null) {
return false;
}
}
}
} else {
if (move.fromRow < move.toRow) {
for (int row = move.fromRow + 1; row < move.toRow; row++) {
if (board[row][move.toColumn] != null) {
return false;
}
}
} else {
for (int row = move.toRow + 1; row < move.fromRow; row++) {
if (board[row][move.toColumn] != null) {
return false;
}
}
}
}
return true;
}
}
|
package uk.co.mtford.jalp.abduction.logic.instance.term;
import choco.kernel.model.variables.Variable;
import choco.kernel.model.variables.set.SetVariable;
import uk.co.mtford.jalp.abduction.logic.instance.*;
import uk.co.mtford.jalp.abduction.tools.NameGenerator;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static choco.Choco.makeSetVar;
/**
* A list of integer constants e.g. [1,2,3]
*/
public class IntegerConstantListInstance extends ListInstance<IntegerConstantInstance> {
public IntegerConstantListInstance() {
super();
}
public IntegerConstantListInstance(Collection<IntegerConstantInstance> integers) {
super();
this.getList().addAll(integers);
}
public IntegerConstantListInstance(IntegerConstantInstance[] integers) {
super();
for (IntegerConstantInstance instance:integers) {
this.getList().add(instance);
}
}
public IntegerConstantListInstance(int ... integers) {
super();
for (int i:integers) {
this.list.add(new IntegerConstantInstance(i));
}
}
public IFirstOrderLogicInstance performSubstitutions(Map<VariableInstance, IUnifiableInstance> substitutions) {
IntegerConstantListInstance newListInstance = new IntegerConstantListInstance();
for (IntegerConstantInstance term:list) {
IntegerConstantInstance newTerm = (IntegerConstantInstance) term.performSubstitutions(substitutions);
newListInstance.getList().add(newTerm);
}
list = newListInstance.getList();
return this;
}
public IFirstOrderLogicInstance deepClone(Map<VariableInstance, IUnifiableInstance> substitutions) {
IntegerConstantListInstance newListInstance = new IntegerConstantListInstance();
for (IntegerConstantInstance term:list) {
newListInstance.getList().add((IntegerConstantInstance) term.deepClone(substitutions));
}
return newListInstance;
}
public IFirstOrderLogicInstance shallowClone() {
IntegerConstantListInstance newListInstance = new IntegerConstantListInstance();
for (IntegerConstantInstance term:list) {
newListInstance.getList().add((IntegerConstantInstance) term.shallowClone());
}
return newListInstance;
}
public boolean reduceToChoco(List<Map<VariableInstance, IUnifiableInstance>> possSubst, HashMap<ITermInstance, Variable> termToVarMap) {
if (!termToVarMap.containsKey(this)) {
SetVariable setVariable = makeSetVar(NameGenerator.upperCaseNameGen.getNextName(), getMin(), getMax());
termToVarMap.put(this,setVariable);
}
return true;
}
public boolean inList(CharConstantListInstance constantList, List<Map<VariableInstance, IUnifiableInstance>> possSubst) {
throw new UnsupportedOperationException();
}
public int getMax() {
int max = Integer.MIN_VALUE;
for (IntegerConstantInstance constantInstance:list) {
if (constantInstance.getValue()>max) max = constantInstance.getValue();
}
return max;
}
public int getMin() {
int min = Integer.MAX_VALUE;
for (IntegerConstantInstance constantInstance:list) {
if (constantInstance.getValue()<min) min = constantInstance.getValue();
}
return min;
}
public int[] getIntArray() {
int[] ints = new int[list.size()];
int i =0;
for (IntegerConstantInstance c:list) {
ints[i]=c.getValue();
i++;
}
return ints;
}
}
|
package dk.webbies.tscreate.main.patch;
import dk.au.cs.casa.typescript.types.SimpleType;
import dk.au.cs.casa.typescript.types.SimpleTypeKind;
import dk.au.cs.casa.typescript.types.Type;
import dk.webbies.tscreate.BenchMark;
import dk.webbies.tscreate.analysis.declarations.DeclarationPrinter;
import dk.webbies.tscreate.analysis.declarations.types.*;
import dk.webbies.tscreate.declarationReader.DeclarationParser;
import dk.webbies.tscreate.evaluation.DebugEvaluation;
import dk.webbies.tscreate.evaluation.descriptions.*;
import dk.webbies.tscreate.jsnap.JSNAPUtil;
import dk.webbies.tscreate.jsnap.Snap;
import dk.webbies.tscreate.jsnap.classes.ClassHierarchyExtractor;
import dk.webbies.tscreate.jsnap.classes.LibraryClass;
import dk.webbies.tscreate.main.CompareVersions;
import dk.webbies.tscreate.main.Main;
import dk.webbies.tscreate.paser.AST.FunctionExpression;
import dk.webbies.tscreate.paser.JavaScriptParser;
import dk.webbies.tscreate.util.LookupDeclarationType;
import dk.webbies.tscreate.util.LookupType;
import dk.webbies.tscreate.util.Util;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import static dk.webbies.tscreate.declarationReader.DeclarationParser.getTypeSpecification;
import static dk.webbies.tscreate.declarationReader.DeclarationParser.parseNatives;
import static java.util.Collections.*;
/**
* Created by erik1 on 09-06-2016.
*/
public class PatchFileFactory {
public static PatchFile fromImplementation(BenchMark oldBench, BenchMark newBench) throws Throwable {
final BenchmarkInformation[] oldInfo = new BenchmarkInformation[1];
final BenchmarkInformation[] newInfo = new BenchmarkInformation[1];
Util.runAll(() -> {
try {
oldInfo[0] = getInfo(oldBench);
} catch (IOException e) {
throw new RuntimeException(e);
}
}, () -> {
try {
newInfo[0] = getInfo(newBench);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
List<PatchStatement> patchStatements = FindPatchStatementsVisitor.generateStatements(oldInfo[0].globalObject, newInfo[0].globalObject, newBench.getOptions(), oldInfo[0].handwritten, newInfo[0].handwritten, newInfo[0].nativeClasses);
// For braekPoint: Break on NullPointerException.
return new PatchFile(patchStatements, oldInfo[0], newInfo[0]);
}
public static PatchFile fromHandwritten(BenchMark oldBench, BenchMark newBench) throws IOException {
List<DebugEvaluation.EvaluationStatement> evaluations = CompareVersions.compareHandWritten(oldBench, newBench);
BenchmarkInformation oldInfo = getInfo(oldBench);
BenchmarkInformation newInfo = getInfo(newBench);
oldInfo.printedDeclaration = Util.readFile(oldBench.declarationPath);
newInfo.printedDeclaration = Util.readFile(newBench.declarationPath);
Type oldHandwritten = getTypeSpecification(oldBench.languageLevel.environment, oldBench.dependencyDeclarations(), oldBench.declarationPath).getGlobal();
List<PatchStatement> patchStatements = evaluations.stream().map(stmt -> toPatchStatement(stmt, oldInfo, newInfo, oldHandwritten)).collect(Collectors.toList());
return new PatchFile(patchStatements, oldInfo, newInfo);
}
public static final class BenchmarkInformation {
public final BenchMark benchMark;
public final UnnamedObjectType globalObject;
public final DeclarationPrinter printer;
public String printedDeclaration;
public DeclarationParser.NativeClassesMap nativeClasses;
public final Type handwritten;
public Snap.Obj snapshot;
public BenchmarkInformation(BenchMark benchMark, UnnamedObjectType globalObject, DeclarationPrinter printer, String printedDeclaration, DeclarationParser.NativeClassesMap nativeClasses, Type handwritten, Snap.Obj snapshot) {
this.benchMark = benchMark;
this.globalObject = globalObject;
this.printer = printer;
this.printedDeclaration = printedDeclaration;
this.nativeClasses = nativeClasses;
this.handwritten = handwritten;
this.snapshot = snapshot;
}
}
public static BenchmarkInformation getInfo(BenchMark benchMark) throws IOException {
FunctionExpression AST = new JavaScriptParser(benchMark.languageLevel).parse(benchMark.name, Main.getScript(benchMark)).toTSCreateAST();
Snap.Obj globalObjectJsnapObject = JSNAPUtil.getStateDump(JSNAPUtil.getJsnapRaw(benchMark.scriptPath, benchMark.getOptions(), benchMark.dependencyScripts(), benchMark.testFiles, benchMark.getOptions().asyncTest), AST);
Snap.Obj emptySnap = JSNAPUtil.getEmptyJSnap(benchMark.getOptions(), benchMark.dependencyScripts(), AST); // Not empty, just the one without the library we are analyzing.
HashMap<Snap.Obj, LibraryClass> libraryClasses = new ClassHierarchyExtractor(globalObjectJsnapObject, benchMark.getOptions()).extract();
DeclarationParser.NativeClassesMap nativeClasses = parseNatives(globalObjectJsnapObject, benchMark.languageLevel.environment, benchMark.dependencyDeclarations(), libraryClasses, emptySnap);
UnnamedObjectType globalObject = new UnnamedObjectType(Main.createDeclaration(benchMark, AST, globalObjectJsnapObject, emptySnap, libraryClasses, nativeClasses), EMPTY_SET);
DeclarationPrinter printer = new DeclarationPrinter(globalObject.getDeclarations(), nativeClasses, benchMark.getOptions());
String printedDeclaration = printer.print();
Type handwritten = null;
if (benchMark.declarationPath != null) {
handwritten = getTypeSpecification(benchMark.languageLevel.environment, benchMark.dependencyDeclarations(), benchMark.declarationPath).getGlobal();
}
return new BenchmarkInformation(benchMark, globalObject, printer, printedDeclaration, nativeClasses, handwritten, globalObjectJsnapObject);
}
public static boolean isAny(DeclarationType type) {
type = type.resolve();
return type instanceof PrimitiveDeclarationType && (((PrimitiveDeclarationType) type).getType() == PrimitiveDeclarationType.Type.ANY || ((PrimitiveDeclarationType) type).getType() == PrimitiveDeclarationType.Type.NON_VOID);
}
public static boolean isVoid(DeclarationType type) {
type = type.resolve();
return type instanceof PrimitiveDeclarationType && (((PrimitiveDeclarationType) type).getType() == PrimitiveDeclarationType.Type.VOID);
}
private static PatchStatement toPatchStatement(DebugEvaluation.EvaluationStatement stmt, BenchmarkInformation oldInfo, BenchmarkInformation newInfo, Type oldHandwrittenType) {
if (stmt.description.getType() == Description.DescriptionType.TRUE_POSITIVE) {
return null;
}
return stmt.description.accept(new ToPatchStatementVisitor(stmt.typePath, oldInfo, newInfo, oldHandwrittenType));
}
private static final class ToPatchStatementVisitor implements DescriptionVisitor<PatchStatement> {
private final String typePath;
private final BenchmarkInformation oldInfo;
private final BenchmarkInformation newInfo;
private final Type oldHandWrittenType;
public ToPatchStatementVisitor(String typePath, BenchmarkInformation oldInfo, BenchmarkInformation newInfo, Type oldHandWrittenType) {
this.typePath = typePath;
this.oldInfo = oldInfo;
this.newInfo = newInfo;
this.oldHandWrittenType = oldHandWrittenType;
}
private DeclarationType lookUpNew(String path) {
return lookUp(path, newInfo.globalObject);
}
private DeclarationType lookUpOld(String path) {
return lookUp(path, oldInfo.globalObject);
}
private DeclarationType lookUp(String path, UnnamedObjectType globalObject) {
if (path.equals("window")) {
return globalObject;
}
DeclarationType result = new LookupDeclarationType(Util.removePrefix(path, "window.")).find(globalObject);
if (result == null) {
result = PrimitiveDeclarationType.Any(Collections.EMPTY_SET);
}
return result;
}
@Override
public PatchStatement visit(Description.SimpleDescription description) {
switch (description.getSimpleType()) {
case EXPECTED_INTERFACE:
case SHOULD_NOT_BE_CONSTRUCTOR:
case SHOULD_BE_CONSTRUCTOR:
case WRONG_NATIVE_TYPE:
case EXCESS_INDEXER:
case MISSING_INDEXER:
DeclarationType newType = lookUpNew(typePath);
DeclarationType oldType = lookUpOld(typePath);
if (newType == null || oldType == null) {
System.err.println("error, simple, at " + typePath);
return null;
}
newType = newType.resolve();
oldType = oldType.resolve();
if (newType instanceof PrimitiveDeclarationType && ((PrimitiveDeclarationType) newType).getType() == PrimitiveDeclarationType.Type.NON_VOID) {
return null;
}
// If any of them are any (or NON_VOID), lookup in the old handwritten declaration file. It it states something specific, skip this one.
if (isAny(newType) || isAny(oldType)) {
Type handwrittenType = oldHandWrittenType.accept(new LookupType(Util.removePrefix(typePath, "window.")));
if (handwrittenType instanceof SimpleType) {
SimpleType simple = (SimpleType) handwrittenType;
if (simple.getKind() == SimpleTypeKind.Any || simple.getKind() == SimpleTypeKind.Null || simple.getKind() == SimpleTypeKind.Void || simple.getKind() == SimpleTypeKind.Undefined) {
return null;
}
}
}
return new ChangedTypeStatement(typePath, newType, oldType, lookUpNew(withoutLastPart(typePath)));
default:
throw new RuntimeException(description.getSimpleType().name() + " is not implemented here yet. Path: " + typePath);
}
}
@Override
public PatchStatement visit(PropertyMissingDescription description) {
DeclarationType oldType = lookUpOld(typePath);
if (oldType == null) {
System.err.println("Error, property missing, at " + typePath);
return null;
}
return new RemovedPropertyStatement(withoutLastPart(typePath), description.getPropertyName(), lookUpNew(withoutLastPart(typePath)));
}
@Override
public PatchStatement visit(ExcessPropertyDescription description) {
DeclarationType newType = lookUpNew(typePath);
if (newType == null) {
System.err.println("Error, excess property, at " + typePath);
return null;
}
if (isVoid(newType)) {
return null;
}
return new AddedPropertyStatement(withoutLastPart(typePath), description.getPropertyName(), lookUpNew(typePath), lookUpNew(withoutLastPart(typePath)));
}
private String withoutLastPart(String typePath) {
if (!typePath.contains(".")) {
return typePath;
} else {
return typePath.substring(0, typePath.lastIndexOf("."));
}
}
@Override
public PatchStatement visit(RightPropertyDescription description) {
return null;
}
@Override
public PatchStatement visit(WrongNumberOfArgumentsDescription description) {
DeclarationType newFunction = lookUpNew(typePath);
DeclarationType oldFunction = lookUpOld(typePath);
if (newFunction == null || oldFunction == null) {
System.err.println("error, arg count, " + typePath);
}
return new ChangedNumberOfArgumentsStatement(typePath, oldFunction, newFunction, lookUpNew(withoutLastPart(typePath)), description.getOldArgCount(), description.getNewArgCount());
}
@Override
public PatchStatement visit(WrongSimpleTypeDescription description) {
if (description.getExpected().getKind() == SimpleTypeKind.Void) {
return Description.ExcessProperty(lastPart(typePath)).accept(this);
}
DeclarationType newType = lookUpNew(typePath);
DeclarationType oldType = lookUpOld(typePath);
if (newType == null || oldType == null) {
System.err.println("error, wrong simple, " + typePath);
}
if (isAny(newType) || isAny(oldType)) {
return null;
}
return new ChangedTypeStatement(typePath, newType, oldType, lookUpNew(withoutLastPart(typePath)));
}
private String lastPart(String typePath) {
if (typePath.indexOf('.') == -1) {
return typePath;
}
return typePath.substring(typePath.lastIndexOf('.') + 1, typePath.length());
}
}
}
|
package capaPresentacion;
import java.io.Serializable;
import java.util.Date;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import capaDatos.Persona;
@Named
@RequestScoped
public class PersonaMB implements Serializable
{
private static final long serialVersionUID = 1L;
private Persona persona = new Persona();
private boolean dentro;
public Persona getPersona()
{
return persona;
}
public void setPersona(Persona persona)
{
this.persona = persona;
}
public boolean isDentro()
{
return dentro;
}
public void setDentro(boolean dentro)
{
this.dentro = dentro;
}
public String getIdPersona()
{
return persona.getIdPersona();
}
public void setIdPersona(String idPersona)
{
persona.setIdPersona(idPersona);
}
public String getApellidos()
{
return persona.getApellidos();
}
public void setApellidos(String apellidos)
{
persona.setApellidos(apellidos);
}
public String getDireccion()
{
return persona.getDireccion();
}
public void setDireccion(String direccion)
{
persona.setDireccion(direccion);
}
public Date getNacimiento()
{
return persona.getNacimiento();
}
public void setNacimiento(Date nacimiento)
{
persona.setNacimiento(nacimiento);
}
public String getNombre()
{
return persona.getNombre();
}
public void setNombre(String nombre)
{
persona.setNombre(nombre);
}
}
|
package ua.com.dao;
import ua.com.model.Address;
public interface AddressDAO extends CommonDAO<Address> {
}
|
package br.com.vitormarcal.gestao_consulta.consulta.request;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDate;
public class FiltroConsultaDisponivelRequest {
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate data;
private Integer idEspecialidade;
public LocalDate getData() {
return data;
}
public void setData(LocalDate data) {
this.data = data;
}
public Integer getIdEspecialidade() {
return idEspecialidade;
}
public void setIdEspecialidade(Integer idEspecialidade) {
this.idEspecialidade = idEspecialidade;
}
}
|
package tailminuseff.fx.model;
import java.util.regex.Pattern;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javax.inject.Singleton;
@Singleton
public class UserSearchModel {
private final ObjectProperty<Pattern> pattern = new SimpleObjectProperty<>();
public Pattern getPattern() {
return pattern.get();
}
public void setPattern(Pattern value) {
pattern.set(value);
}
public ObjectProperty<Pattern> patternProperty() {
return pattern;
}
private final ObjectProperty<InlineTextStyle> style = new SimpleObjectProperty<>(new InlineTextStyle());
public InlineTextStyle getStyle() {
return style.get();
}
public void setStyle(InlineTextStyle value) {
style.set(value);
}
public ObjectProperty<InlineTextStyle> styleProperty() {
return style;
}
}
|
package sjtu.csdi.AndroidIOTool;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class MainAty extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startActivity(new Intent(MainAty.this, AppListAty.class));
// startActivity(new Intent(MainAty.this, BarChartAty.class));
this.finish();
}
}
|
package tarea.ordenamiento;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Empleado daniel = new Empleado();
daniel.setNombre("Daniel");
daniel.setApellido("Torres");
daniel.setEdad(19);
daniel.setSalario(500);
Empleado cristina = new Empleado();
cristina.setNombre("Cristina");
cristina.setApellido("Alba");
cristina.setEdad(20);
cristina.setSalario(400);
Empleado michael = new Empleado();
michael.setNombre("Michael");
michael.setApellido("Alvarado");
michael.setEdad(21);
michael.setSalario(550);
Empleado gladys = new Empleado();
gladys.setNombre("Gladys");
gladys.setApellido("Fernandez");
gladys.setEdad(23);
gladys.setSalario(800);
Empleado amanda = new Empleado();
amanda.setNombre("Amanda");
amanda.setApellido("Rodriguez");
amanda.setEdad(25);
amanda.setSalario(900);
Empleado patricio = new Empleado();
patricio.setNombre("Patricio");
patricio.setApellido("Perez");
patricio.setEdad(20);
patricio.setSalario(300);
Empleado matias = new Empleado();
matias.setNombre("Matias");
matias.setApellido("Carrion");
matias.setEdad(24);
matias.setSalario(600);
Empleado oscar = new Empleado();
oscar.setNombre("Oscar");
oscar.setApellido("Salazar");
oscar.setEdad(28);
oscar.setSalario(950);
Empleado bruno = new Empleado();
bruno.setNombre("Bruno");
bruno.setApellido("Tejera");
bruno.setEdad(26);
bruno.setSalario(750);
Empleado valentina = new Empleado();
valentina.setNombre("Valentina");
valentina.setApellido("Soto");
valentina.setEdad(30);
valentina.setSalario(1250);
Empleado salariosEmpleados[] = new Empleado[10];
salariosEmpleados[0]=daniel;
salariosEmpleados[1]=cristina;
salariosEmpleados[2]=michael;
salariosEmpleados[3]=gladys;
salariosEmpleados[4]=amanda;
salariosEmpleados[5]=patricio;
salariosEmpleados[6]=matias;
salariosEmpleados[7]=oscar;
salariosEmpleados[8]=bruno;
salariosEmpleados[9]=valentina;
System.out.println("Empleados antes de ordenar");
System.out.println(Arrays.toString(salariosEmpleados));
Arrays.sort(salariosEmpleados);
System.out.println("Empleados despues de ordenar");
System.out.println(Arrays.toString(salariosEmpleados));
}
}
|
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.Applet;
/*<applet code="Registration" height=800 width=800>
</applet>*/
public class Registration extends Applet implements ActionListener,ItemListener{
String str="";
String s="";
String msg="";
Label l1,l2,l3,List,Choice;
TextField tf1,tf2;
Button Reset,Submit;
Checkbox male,female;
Choice qual;
public void init(){
l1=new Label("student name");
l2=new Label("Roll no");
tf1=new TextField(30);
tf2=new TextField(30);
l3=new Label("Gender");
male=new Checkbox("Male");
female=new Checkbox("Female");
Choice =new Label("Qualification");
qual=new Choice();
qual.add("B.tech");
qual.add("BE");
qual.add("Bsc");
/*List=new Label("Branch");
branch.add("cse");
branch.add("it");
branch.add("ece");*/
Submit=new Button("Submit");
Reset=new Button("reset");
//setLayout(null);
add(l1);
add(tf1);
add(l2);
add(tf2);
add(l3);
add(male);
add(female);
add(Choice);
add(qual);
add(Submit);
add(Reset);
//add(List);
//add(branch);
Submit.addActionListener(this);
Reset.addActionListener(this);
male.addItemListener(this);
female.addItemListener(this);
//branch.addItemListener(this);
qual.addItemListener(this);
}//close of init
public void actionPerformed(ActionEvent ae){
String str=ae.getActionCommand();
if(str.equals("Submit")){
showStatus("APPLICATION SUBMITTED");
}//close of if
else if(str.equals("reset")){
tf1.setText(" ");
tf2.setText(" ");
showStatus("RESETED");
}
}//ap
public void itemStateChanged(ItemEvent ie){
str=ie.getItem().toString();
if(str.equals("Male")){
str+=" "+male.getState();
repaint();
}
else if(str.equals("Female")){
str+=" "+female.getState();
repaint();
}
msg=" "+qual.getSelectedItem();
//s=" "+branch.getSelectedItem();
repaint();
}//it
public void paint(Graphics g){
g.drawString(str,600,600);
g.drawString(s,700,700);
g.drawString(msg,800,800);
}
}
|
package no.nav.vedtak.sikkerhet.abac.pdp;
public interface RessursDataKey {
String getKey();
}
|
package artgallery.Actors;
import java.util.ArrayList;
import artgallery.geometricalElements.Edge;
import artgallery.geometricalElements.RoutePoint;
public class Thief extends Actor{
private int x;
private int y;
private int currentPointIndex;
private int orientation;
private int maxSpeed;
private int observationTime;
private ArrayList<RoutePoint> routePoints = new ArrayList<RoutePoint>();
private ArrayList<Edge> routeEdges = new ArrayList<Edge>();
private int routeLength;
public Thief(){
routePoints = new ArrayList<RoutePoint>();
}
public Thief(RoutePoint r, int ms, int ot){
this.maxSpeed = ms;
this.observationTime = ot;
routePoints = new ArrayList<RoutePoint>();
routePoints.add(r);
currentPointIndex = 0;
this.setPosition(routePoints.get(currentPointIndex));
}
public void addPointToRoute(RoutePoint r){
routePoints.add(r);
if(routePoints.size() == 1){
this.setX(routePoints.get(0).getX());
this.setY(routePoints.get(0).getY());
}
}
public int getRouteLength() {
return routeLength;
}
public void setRouteLength(int routeLength) {
this.routeLength = routeLength;
}
public ArrayList<RoutePoint> getRoutePoints(){
return routePoints;
}
public ArrayList<Edge> getRouteEdges(){
if(routePoints.size() > 1){
for(int i = 0; i < routePoints.size()-1; ++i){
RoutePoint r1 = routePoints.get(i);
RoutePoint r2 = routePoints.get((i+1));
routeEdges.add(new Edge(r1.toVertex(), r2.toVertex()));
}
}
return routeEdges;
}
public void advance(int time){
if(currentPointIndex < routePoints.size() - 1){
RoutePoint nextPoint = routePoints.get(currentPointIndex + 1);
if (nextPoint.getTimeStamp() == time){
setPosition(nextPoint);
currentPointIndex = (currentPointIndex + 1) ;
}
}
}
public void advanceWithInterpolation(int time){
RoutePoint nextPoint = getNext();
if(nextPoint != null){
RoutePoint currentPoint = routePoints.get(currentPointIndex);
int step = time - currentPoint.getTimeStamp() * 100;
int interpolatedX = currentPoint.getX() + (nextPoint.getX() - currentPoint.getX()) / 100 * step;
int interpolatedY = currentPoint.getY() + (nextPoint.getY() - currentPoint.getY()) / 100 * step;
setPosition(interpolatedX, interpolatedY);
if(time == nextPoint.getTimeStamp() * 100 && time > 0){
currentPointIndex ++;
}
}
}
private RoutePoint getNext(){
return (currentPointIndex < routePoints.size() - 1 ? routePoints.get(currentPointIndex + 1) : null);
}
private void setPosition(RoutePoint r){
this.setX(r.getX());
this.setY(r.getY());
}
private void setPosition(int x, int y){
this.setX(x);
this.setY(y);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
|
package com.github.tobby48.java.scene3.scatchbook;
/**
* <pre>
* com.github.tobby48.java.scene3.scatchbook
* Scatchbook.java
*
* 설명 :추상클래스와 인터페이스 예제
* </pre>
*
* @since : 2017. 11. 16.
* @author : tobby48
* @version : v1.0
*/
public class Scatchbook {
private String name;
private Drawing[] drawList; // 배열은 크기를 동적으로 조절하기가 힘들다. Chap23, 24 제네릭과 컬렉션을 통해 동적으로 크기를 조정하는 것을 배우게 된다.
public Scatchbook(String name, int size) {
this.name = name;
this.drawList = new Drawing[size];
}
public void addDrawing(Drawing d){
for(int index = 0; index < drawList.length; index++){
if(drawList[index] == null) {
drawList[index] = d;
break;
}
}
}
public void draw(){
for(Drawing d : drawList) System.out.println(d.draw());
}
public static void main(String args[]) {
Scatchbook scatchbook = new Scatchbook("SWH아카데미 스케치북", 2);
Circle circle = new Circle(5000);
Line line = new Line(5);
Rectangle rectangle = new Rectangle();
scatchbook.addDrawing(circle);
scatchbook.addDrawing(rectangle);
// scatchbook.addDrawing(line); // 컴파일 오류
scatchbook.draw();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package TimerScratch;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* @author lemij7026
*/
public class PanMain extends JPanel implements ActionListener {
JLabel label;
JLabel gameOverLabel;
int counter = 0;
String labelTxt;
public PanMain() {
//The label
label = new JLabel();
label.setSize(400,400);
add(label, BorderLayout.CENTER);
//a
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
counter+=10;
label.setText(String.valueOf(counter));
label.repaint();
label.revalidate();
if("0".equals(label.getText())){
}
}
}, 0, 1);
}
@Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
package com.example.workstudy.hauwei;
import com.example.workstudy.pattern.decorate.Man;
import java.util.Scanner;
public class Levenshtein {
/**
* 相关连接:https://www.iteye.com/blog/wdhdmx-1343856
* 编辑距离算法
* 最短编辑距离
* 两个字符串之间的相识度
* abc a b c
* abd 0 1 2 3
* a 1 0 1 2
* b 2 1 0 1
* d 3 2 1 1
*
* 左右值加一
* 左上角的值,如果两个值相等就加0 ,不等就加1
* 取左,右,左上角 3个值中的最小值
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String str01 = scanner.nextLine();
String str02 = scanner.nextLine();
char[] chars01 = str01.toCharArray();
char[] chars02 = str02.toCharArray();
int [][] dynamicArray = new int[str01.length()+1][str02.length()+1];
for (int i = 0; i <= str01.length(); i++) {
dynamicArray[i][0] = i;
}
for (int j = 0; j <= str02.length(); j++) {
dynamicArray[0][j] = j;
}
int temp = 0;
for (int i = 1; i <= str01.length(); i++) {
for (int j = 1; j <= str02.length(); j++) {
if (chars01[i-1] != chars02[j-1]){
temp = 1;
}else {
temp = 0;
}
dynamicArray[i][j] = min(dynamicArray[i-1][j-1]+temp,dynamicArray[i][j-1]+1,
dynamicArray[i-1][j]+1);
}
}
System.out.println(dynamicArray[str01.length()][str02.length()]);
}
}
private static int min(int i, int i1, int i2) {
int min01 = Math.min(i,i1);
int min02 = Math.min(i1,i2);
return Math.min(min01,min02);
}
}
|
package _09_automated_testing_tdd.triangle_type;
import org.junit.Test;
import org.junit.jupiter.api.DisplayName;
import static org.junit.Assert.assertEquals;
public class TriangleTypeTest {
@Test
@DisplayName("Testing case1")
public void testCase1() {
int a = 2, b = 2, c = 2;
String expected = "Tam giac deu";
String result = TriangleType.triangleClassifier(a, b, c);
assertEquals(expected, result);
}
@Test
@DisplayName("Testing case2")
public void testCase2() {
int a = 2, b = 2, c = 3;
String expected = "Tam giac can";
String result = TriangleType.triangleClassifier(a, b, c);
assertEquals(expected, result);
}
@Test
@DisplayName("Testing case3")
public void testCase3() {
int a = 2, b = 4, c = 5;
String expected = "Tam giac thuong";
String result = TriangleType.triangleClassifier(a, b, c);
assertEquals(expected, result);
}
@Test
@DisplayName("Testing case4")
public void testCase4() {
int a = 8, b = 2, c = 3;
String expected = "khong phai tam giac";
String result = TriangleType.triangleClassifier(a, b, c);
assertEquals(expected, result);
}
}
|
package com.cs.messaging.email;
import com.cs.player.Player;
import com.cs.user.User;
import com.google.common.base.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import java.io.Serializable;
import java.util.Date;
import static javax.persistence.EnumType.STRING;
import static javax.persistence.GenerationType.IDENTITY;
import static javax.persistence.TemporalType.TIMESTAMP;
/**
* @author Omid Alaepour
*/
@Entity
@Table(name = "bronto_contacts")
public class BrontoContact implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", nullable = false, unique = true)
@Nonnull
private Long id;
@OneToOne
@JoinColumn(name = "player_id", nullable = false)
@Nonnull
private Player player;
@Column(name = "bronto_id", nullable = false, length = 200)
@Nonnull
private String brontoId;
@Column(name = "status", nullable = false, length = 20)
@Nonnull
@Enumerated(STRING)
private BrontoContactStatus status;
@Column(name = "created_date", nullable = false)
@Temporal(TIMESTAMP)
@Nonnull
private Date createdDate;
@ManyToOne
@JoinColumn(name = "modified_by")
@Nullable
private User modifiedBy;
@Column(name = "modified_date")
@Temporal(TIMESTAMP)
@Nullable
private Date modifiedDate;
@Nonnull
public Long getId() {
return id;
}
public void setId(@Nonnull final Long id) {
this.id = id;
}
@Nonnull
public Player getPlayer() {
return player;
}
public void setPlayer(@Nonnull final Player player) {
this.player = player;
}
@Nonnull
public String getBrontoId() {
return brontoId;
}
public void setBrontoId(@Nonnull final String brontoId) {
this.brontoId = brontoId;
}
@Nonnull
public BrontoContactStatus getStatus() {
return status;
}
public void setStatus(@Nonnull final BrontoContactStatus status) {
this.status = status;
}
@Nonnull
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(@Nonnull final Date createdDate) {
this.createdDate = createdDate;
}
@Nullable
public User getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(@Nullable final User modifiedBy) {
this.modifiedBy = modifiedBy;
}
@Nullable
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(@Nullable final Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final BrontoContact that = (BrontoContact) o;
return Objects.equal(id, that.id);
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.addValue(id)
.addValue(player.getId())
.addValue(brontoId)
.addValue(status)
.addValue(createdDate)
.addValue(modifiedBy != null ? modifiedBy.getId() : null)
.addValue(modifiedDate)
.toString();
}
}
|
package com.stk123.repository;
import com.stk123.entity.StkFnDataUsEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StkFnDataUsRepository extends StkFnData<StkFnDataUsEntity>, JpaRepository<StkFnDataUsEntity, StkFnDataUsEntity.CompositeKey> {
}
|
package example;
import iboxdb.localserver.*;
import iboxdb.localserver.replication.*;
import java.io.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.text.*;
import java.util.*;
public class KeyOnly {
public static void main(String[] args) throws InterruptedException {
System.out.println("MEM: " + helper.format(java.lang.Runtime.getRuntime().maxMemory()));
System.out.println("CPU: " + java.lang.Runtime.getRuntime().availableProcessors());
String path = "../DATA_TEST";
new File(path).mkdirs();
System.out.println("Path: " + new File(path).getAbsolutePath());
DB.root(path);
helper.deleteDB();
DB db = new DB(1);
// JVM=2G, DB=0.5G
DatabaseConfig cfg = db.getConfig();
cfg.CacheLength = cfg.mb(512);
cfg.ensureTable(ShortMSG.class, "/shortmsg", "productId", "time", "userId", "msg(30)");
final AutoBox auto = db.open();
final long count = 100;
//Insert
long begin = System.currentTimeMillis();
//long total = SingleInsert(auto, count);
long total = BatchInsert(auto, count);
double sec = (System.currentTimeMillis() - begin) / 1000.0;
long avg = (long) (total / sec);
IBStreamReader reader = auto.getDatabase().createFileReader();
long length = reader.length();
System.out.println("Insert TotalObjects: " + helper.format(total)
+ " FileSize: " + helper.format(length / 1024.0 / 1024.0) + "MB");
System.out.println("Elapsed " + helper.getDou(sec) + "s, AVG "
+ helper.format(avg) + " o/sec");
reader.close();
System.out.println();
//Select
begin = System.currentTimeMillis();
total = SelectObjects(auto, count);
total += SelectObjects(auto, count);
sec = (System.currentTimeMillis() - begin) / 1000.0;
avg = (long) (total / sec);
System.out.println("Select TotalObjects: " + helper.format(total));
System.out.println("Elapsed " + helper.getDou(sec) + "s, AVG "
+ helper.format(avg) + " o/sec");
//Reopen Select
db.close();
System.gc();
System.out.println();
AutoBox auto2 = db.open();
begin = System.currentTimeMillis();
total = SelectObjects(auto2, count);
total += SelectObjects(auto2, count);
sec = (System.currentTimeMillis() - begin) / 1000.0;
avg = (long) (total / sec);
System.out.println("Select TotalObjects: " + helper.format(total) + " -Reopen");
System.out.println("Elapsed " + helper.getDou(sec) + "s, AVG "
+ helper.format(avg) + " o/sec");
System.out.println();
begin = System.currentTimeMillis();
total = SelectObjects(auto2, count);
total += SelectObjects(auto2, count);
sec = (System.currentTimeMillis() - begin) / 1000.0;
avg = (long) (total / sec);
System.out.println("Select TotalObjects: " + helper.format(total) + " -Reopen2");
System.out.println("Elapsed " + helper.getDou(sec) + "s, AVG "
+ helper.format(avg) + " o/sec");
}
private static long SelectObjects(final AutoBox auto, final long count) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(
java.lang.Runtime.getRuntime().availableProcessors() * 2);
final AtomicLong total = new AtomicLong(0);
for (long proId = 1; proId <= count; proId++) {
final long fproId = proId;
pool.execute(() -> {
try (Box box = auto.cube()) {
for (ShortMSG smsg : box.select(ShortMSG.class, "from /shortmsg where productId==?", fproId)) {
if (smsg.productId != fproId) {
System.out.println("Unreachable");
}
String cs = smsg.productId + "-" + (smsg.time.getTime()) + "-" + smsg.userId;
if (!smsg.msg.equals(cs)) {
System.out.println("Unreachable");
}
total.incrementAndGet();
}
}
});
}
pool.shutdown();
pool.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
return total.get();
}
private static long BatchInsert(final AutoBox auto, final long count) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(
java.lang.Runtime.getRuntime().availableProcessors() * 2);
final long fakeTime = System.currentTimeMillis();
final AtomicLong total = new AtomicLong(0);
for (long proId = 1; proId <= count; proId++) {
for (long ft = 1; ft <= count; ft++) {
final long fproId = proId;
final long fft = ft;
pool.execute(() -> {
try (Box box = auto.cube()) {
for (long userid = 1; userid <= count; userid++) {
ShortMSG smsg = new ShortMSG();
smsg.productId = fproId;
smsg.time = new Date(fakeTime + fft);
smsg.userId = userid;
smsg.msg = smsg.productId + "-" + (fakeTime + fft) + "-" + smsg.userId;
box.d("/shortmsg").insert(smsg);
}
if (box.commit().equals(CommitResult.OK)) {
total.addAndGet(count);
}
}
});
}
}
pool.shutdown();
pool.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
return total.get();
}
private static long SingleInsert(final AutoBox auto, long count) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(
java.lang.Runtime.getRuntime().availableProcessors() * 2);
final long fakeTime = System.currentTimeMillis();
final AtomicLong total = new AtomicLong(0);
for (long proId = 1; proId <= count; proId++) {
for (long ft = 1; ft <= count; ft++) {
for (long userid = 1; userid <= count; userid++) {
final long fproId = proId;
final long fft = ft;
final long fuserid = userid;
pool.execute(() -> {
ShortMSG smsg = new ShortMSG();
smsg.productId = fproId;
smsg.time = new Date(fakeTime + fft);
smsg.userId = fuserid;
smsg.msg = smsg.productId + "-" + (fakeTime + fft) + "-" + smsg.userId;
if (auto.insert("/shortmsg", smsg)) {
total.incrementAndGet();
}
});
}
}
}
pool.shutdown();
pool.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
return total.get();
}
public static class ShortMSG {
public long productId;
public java.util.Date time;
public long userId;
public String msg;
}
private static class helper {
public static void deleteDB() {
BoxSystem.DBDebug.DeleteDBFiles(1);
}
public static String getDou(double d) {
long l = (long) (d * 1000);
return Double.toString(l / 1000.0);
}
public static String format(double d) {
return NumberFormat.getInstance().format((int) d);
}
}
}
|
package info;
import edit.DriverInsertionDialog;
import edit.InspectorInsertionDialog;
import edit.CheckupInsertionDialog;
import edit.DriverDeletion;
import edit.InspectorDeletion;
import edit.CheckupDeletion;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class InfoTable{
public static String[] driverTitles = {"Car ID", "Engine ID", "Color", "Brand", "Passport ID", "Licence",
"Full Name", "Address", "Birthday", "Sex"};
public static String[] inspectorTitles = {"Full Name", "Inspector ID", "Post", "Rank"};
public static String[] checkupTitles = {"Date", "Result", "Car ID", "Inspector ID"};
private String shellTitle;
private String driverTitle = "driver";
private String inspectorTitle = "inspector";
private String checkupTitle = "checkup";
Table table;
Shell subShell;
Button addRecordButton;
Button editRecordButton;
Button deleteRecordButton;
public InfoTable(Shell parent, String shellTitle){
subShell = new Shell(parent);
this.shellTitle = shellTitle;
subShell.setText(shellTitle);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
gridLayout.horizontalSpacing = 50;
subShell.setLayout(gridLayout);
table = new Table(subShell, SWT.FULL_SELECTION);
addRecordButton = new Button(subShell, SWT.PUSH);
editRecordButton = new Button(subShell, SWT.PUSH);
deleteRecordButton = new Button(subShell, SWT.PUSH);
}
public InfoTable getInfoTable() {
return this;
}
public Table getTable() {
return table;
}
public void drawTable(String[] titles){
GridData tableGridData = new GridData(1000, 250);
tableGridData.horizontalSpan = 3;
table.setLayoutData(tableGridData);
GridData buttonGridData = new GridData(300, 60);
addRecordButton.setLayoutData(buttonGridData);
editRecordButton.setLayoutData(buttonGridData);
deleteRecordButton.setLayoutData(buttonGridData);
table.setHeaderVisible(true);
for (int i = 0; i < titles.length; i++) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(titles[i]);
table.getColumn(i).setWidth(100);
}
addRecordButton.setText("Add");
editRecordButton.setText("Edit");
deleteRecordButton.setText("Delete");
addRecordButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(shellTitle == driverTitle) {
DriverInsertionDialog insertDriverWindow = new DriverInsertionDialog(subShell, getInfoTable());
insertDriverWindow.insertDriver();
}
else if (shellTitle == inspectorTitle){
InspectorInsertionDialog insertInspectorWindow = new InspectorInsertionDialog(subShell, getInfoTable());
insertInspectorWindow.insertInspector();
}
else if (shellTitle == checkupTitle) {
CheckupInsertionDialog insertCheckupWindow = new CheckupInsertionDialog(subShell, getInfoTable());
insertCheckupWindow.insertCheckup();
}
}
});
editRecordButton.addSelectionListener(new SelectionAdapter(){
@Override
public void widgetSelected(SelectionEvent e){
if(shellTitle == driverTitle) {
String passportID = table.getSelection()[0].getText(4);
DriverDeletion driverDeletion = new DriverDeletion(getInfoTable());
driverDeletion.deleteDriver(passportID);
DriverInsertionDialog insertWindow = new DriverInsertionDialog(subShell, getInfoTable());
insertWindow.insertDriver();
}
else if(shellTitle == inspectorTitle){
String inspectorID = table.getSelection()[0].getText(1);
InspectorDeletion inspectorDeletion = new InspectorDeletion(getInfoTable());
inspectorDeletion.deleteInspector(inspectorID);
InspectorInsertionDialog insertInspectorWindow = new InspectorInsertionDialog(subShell, getInfoTable());
insertInspectorWindow.insertInspector();
}
else if(shellTitle == checkupTitle){
String checkupDate = table.getSelection()[0].getText(0);
String carID = table.getSelection()[0].getText(2);
CheckupDeletion checkupDeletion = new CheckupDeletion(getInfoTable());
checkupDeletion.deleteCheckup(checkupDate, carID);
CheckupInsertionDialog insertCheckupWindow = new CheckupInsertionDialog(subShell, getInfoTable());
insertCheckupWindow.insertCheckup();
}
}
});
deleteRecordButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(shellTitle == driverTitle) {
String passportID = table.getSelection()[0].getText(4);
DriverDeletion driverDeletion = new DriverDeletion(getInfoTable());
driverDeletion.deleteDriver(passportID);
driverDeletion.redrawTable();
}
else if(shellTitle == inspectorTitle){
String inspectorID = table.getSelection()[0].getText(1);
InspectorDeletion inspectorDeletion = new InspectorDeletion(getInfoTable());
inspectorDeletion.deleteInspector(inspectorID);
inspectorDeletion.redrawTable();
}
else if(shellTitle == checkupTitle){
String checkupDate = table.getSelection()[0].getText(0);
String carID = table.getSelection()[0].getText(2);
CheckupDeletion checkupDeletion = new CheckupDeletion(getInfoTable());
checkupDeletion.deleteCheckup(checkupDate, carID);
checkupDeletion.redrawTable();
}
}
});
subShell.setBounds(400, 230, 1030, 400);
subShell.open();
}
public void updateDriverTable(ResultSet resultSet, Table table) throws SQLException { //extend for all 3 tables
while (resultSet.next()) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(0, String.valueOf(resultSet.getInt(1)));
item.setText(1, String.valueOf(resultSet.getInt(2)));
item.setText(2, resultSet.getString(3));
item.setText(3, resultSet.getString(4));
item.setText(4, String.valueOf(resultSet.getInt(5)));
item.setText(5, String.valueOf(resultSet.getInt(6)));
item.setText(6, resultSet.getString(7));
item.setText(7, resultSet.getString(8));
item.setText(8, String.valueOf(resultSet.getDate(9)));
item.setText(9, resultSet.getString(10));
}
}
public void updateInspectorTable(ResultSet resultSet, Table table) throws SQLException {
while (resultSet.next()) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(0, resultSet.getString(1));
item.setText(1, String.valueOf(resultSet.getInt(2)));
item.setText(2, resultSet.getString(3));
item.setText(3, resultSet.getString(4));
}
}
public void updateCheckupTable(ResultSet resultSet, Table table) throws SQLException {
while (resultSet.next()) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(0, String.valueOf(resultSet.getDate(1)));
item.setText(1, String.valueOf(resultSet.getInt(2)));
item.setText(2, String.valueOf(resultSet.getInt(3)));
item.setText(3, String.valueOf(resultSet.getInt(4)));
}
}
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neuro4j.studio.core.diagram.edit.shapes;
import org.eclipse.draw2d.BorderLayout;
import org.eclipse.draw2d.Ellipse;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.swt.graphics.Image;
import org.neuro4j.studio.core.diagram.part.Neuro4jDiagramEditorPlugin;
/**
* @generated
*/
public class CallNodeFigure extends BaseImageFigure {
public static final Image DEFAULT_IMAGE = Neuro4jDiagramEditorPlugin.imageDescriptorFromPlugin(Neuro4jDiagramEditorPlugin.ID, "icons/images/CallNode.png").createImage();
/**
* @generated
*/
private WrappingLabel fFigureCallNodeFlowNameFigure;
private Ellipse input, output;
/**
* @generated
*/
public CallNodeFigure() {
super(DEFAULT_IMAGE, 0);
BorderLayout layoutThis = new BorderLayout();
this.setLayoutManager(layoutThis);
createContents();
}
/**
* @generated
*/
private void createContents() {
fFigureCallNodeFlowNameFigure = new WrappingLabel();
fFigureCallNodeFlowNameFigure.setText("<...>");
this.add(fFigureCallNodeFlowNameFigure);
input = new Ellipse();
input.setFill(true);
input.setBackgroundColor(ellipseBGColor);
input.setPreferredSize(new Dimension(ELLIPSE_SIZE, ELLIPSE_SIZE));
this.add(input);
output = new Ellipse();
output.setFill(true);
output.setBackgroundColor(ellipseBGColor);
output.setPreferredSize(new Dimension(ELLIPSE_SIZE, ELLIPSE_SIZE));
}
/**
* @generated
*/
public WrappingLabel getFigureCallNodeFlowNameFigure() {
return fFigureCallNodeFlowNameFigure;
}
public IFigure getFigureCallNodeMainInput() {
return input;
}
public IFigure getFigureCallNodeMainOutput() {
return output;
}
} |
package com.camila.web.dominio.models;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Compra {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Cliente cliente;
@ManyToOne
private Carrinho carrinho;
private BigDecimal totalPago;
private OffsetDateTime dataFeita;
@Enumerated(EnumType.STRING)
private StatusVenda status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public Carrinho getCarrinho() {
return carrinho;
}
public void setCarrinho(Carrinho carrinho) {
this.carrinho = carrinho;
}
public BigDecimal getTotalPago() {
return totalPago;
}
public void setTotalPago(BigDecimal totalPago) {
this.totalPago = totalPago;
}
public OffsetDateTime getDataFeita() {
return dataFeita;
}
public void setDataFeita(OffsetDateTime dataFeita) {
this.dataFeita = dataFeita;
}
public StatusVenda getStatus() {
return status;
}
public void setStatus(StatusVenda status) {
this.status = status;
}
}
|
/*
* Copyright 2012 GitHub Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.sieunhan.github_client;
import android.accounts.Account;
import android.content.Context;
import android.util.Log;
import com.github.mobile.accounts.AccountUtils;
import com.github.mobile.accounts.AuthenticatedUserLoader;
/**
* Loader that support throwing an exception when loading in the background
*
* @param <D>
*/
public abstract class ThrowableLoader<D> extends AuthenticatedUserLoader<D> {
private static final String TAG = "ThrowableLoader";
private final D data;
private Exception exception;
/**
* Create loader for context and seeded with initial data
*
* @param context
* @param data
*/
public ThrowableLoader(Context context, D data) {
super(context);
this.data = data;
}
@Override
protected D getAccountFailureData() {
return data;
}
@Override
public D load(final Account account) {
exception = null;
try {
return loadData();
} catch (Exception e) {
if (AccountUtils.isUnauthorized(e)
&& AccountUtils.updateAccount(account, activity))
try {
return loadData();
} catch (Exception e2) {
e = e2;
}
Log.d(TAG, "Exception loading data", e);
exception = e;
return data;
}
}
/**
* @return exception
*/
public Exception getException() {
return exception;
}
/**
* Clear the stored exception and return it
*
* @return exception
*/
public Exception clearException() {
final Exception throwable = exception;
exception = null;
return throwable;
}
/**
* Load data
*
* @return data
* @throws Exception
*/
public abstract D loadData() throws Exception;
}
|
package dynamic_programming;
import java.util.Arrays;
/**
* Created by gouthamvidyapradhan on 27/01/2018.
* In a N x N grid representing a field of cherries, each cell is one of three possible integers.
0 means the cell is empty, so you can pass through;
1 means the cell contains a cherry, that you can pick up and pass through;
-1 means the cell contains a thorn that blocks your way.
Your task is to collect maximum number of cherries possible by following the rules below:
Starting at the position (0, 0) and reaching (N-1, N-1) by moving right or down through valid path cells (cells
with value 0 or 1);
After reaching (N-1, N-1), returning to (0, 0) by moving left or up through valid path cells;
When passing through a path cell containing a cherry, you pick it up and the cell becomes an empty cell (0);
If there is no valid path between (0, 0) and (N-1, N-1), then no cherries can be collected.
Example 1:
Input: grid =
[[0, 1, -1],
[1, 0, -1],
[1, 1, 1]]
Output: 5
Explanation:
The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.
Note:
grid is an N by N 2D array, with 1 <= N <= 50.
Each grid[i][j] is an integer in the set {-1, 0, 1}.
It is guaranteed that grid[0][0] and grid[N-1][N-1] are not -1.
Solution O(N ^ 3) time-complexity. Traversing from (0, 0) -> (n - 1, n - 1) or the other way around both are the same.
The key point to note here is the traversal should be done by two person simultaneously starting from (0, 0).
Notice after t steps, each position (r, c) we could be, is on the line r + c = t (along the diagonal). So if we have
two people at positions (r1, c1) and (r2, c2), then r2 = r1 + c1 - c2.
*/
public class CherryPickup {
/**
* Main method
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception{
int[][] A = {{0 ,1,-1},{1, 0,-1},{1,1,1}};
System.out.println(new CherryPickup().cherryPickup(A));
}
public int cherryPickup(int[][] grid) {
int[][][] DP = new int[grid.length][grid.length][grid.length];
for(int i = 0; i < grid.length; i ++){
for(int j = 0; j < grid.length; j ++){
Arrays.fill(DP[i][j], -1);
}
}
int result = dp(grid.length, 0, 0, 0, DP, grid);
if(result < 0) return 0;
else return result;
}
private int dp(int N, int r1, int c1, int c2, int[][][] DP, int[][] grid){
int r2 = r1 + (c1 - c2);
if(r1 >= N || c1 >= N || c2 >= N || r2 >= N || grid[r1][c1] == -1 || grid[r2][c2] == -1) return Integer.MIN_VALUE;
else if(DP[r1][c1][c2] != -1) return DP[r1][c1][c2];
else if(r1 == N - 1 && c1 == N - 1) return grid[N - 1][N - 1];
else{
int max = (c1 == c2) ? grid[r1][c1] : (grid[r1][c1] + grid[r2][c2]);
//verify all the 4 possibilities. (P1 down + P2 right), (P1 right, P2 right), (P1 right + P2 down),
// (P1 down, P2 down)
max += Math.max(Math.max(Math.max(dp(N, r1 + 1, c1, c2, DP, grid), dp(N, r1 + 1, c1, c2 + 1, DP, grid)), dp(N,
r1, c1 + 1, c2, DP, grid)), dp(N, r1, c1 + 1, c2 + 1, DP, grid));
DP[r1][c1][c2] = max;
return max;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.