text
stringlengths 10
2.72M
|
|---|
/**
* Created with IntelliJ IDEA.
* User: daixing
* Date: 12-11-15
* Time: 下午11:16
* To change this template use File | Settings | File Templates.
*/
public class p1_1_33 {
public static void main(String[] args)throws MatrixSizeNotMatch
{
double[] x = {1,2,3,4,5};
double[] y = {1,2,3,4,5};
double[] z = {1,2,3,4};
StdOut.println(Matrix.dot(x, y));
double[][] a = {
{1,1,1,1},
{2,2,2,2},
{3,3,3,3},
{4,4,4,4},
{5,5,5,5}
};
double[][] c = Matrix.transpose(a);
for(int i = 0 ; i < c.length; ++i)
{
for(int j = 0; j < c[0].length; ++j)
StdOut.print(c[i][j] +" ");
StdOut.println();
}
double[] d = Matrix.mult(a, z);
for(int i = 0; i < d.length; ++i)
StdOut.print(d[i] + " ");
StdOut.println();
double[] e = Matrix.mult(z, Matrix.transpose(a));
for(int i = 0 ; i < e.length; ++i)
StdOut.print(e[i] + " ");
StdOut.println();
double[][] f = Matrix.mult(a, Matrix.transpose(a));
for(int i = 0 ; i < c.length; ++i)
{
for(int j = 0; j < c[0].length; ++j)
StdOut.print(f[i][j] +" ");
StdOut.println();
}
}
}
class MatrixSizeNotMatch extends Exception
{
}
class Matrix
{
static double dot(double[] x, double[] y)throws MatrixSizeNotMatch
{
if(x.length != y.length)
throw new MatrixSizeNotMatch();
double sum = 0;
for(int i = 0 ; i < x.length; ++i)
{
sum += x[i] * y[i];
}
return sum;
}
static double[][] mult(double[][] a, double[][] b)throws MatrixSizeNotMatch
{
if(a[0].length != b.length)
throw new MatrixSizeNotMatch();
double[][] c = new double[a.length][b[0].length];
for(int i = 0 ; i < a.length; ++i)
{
for(int j = 0; j < b[0].length; ++j)
{
for(int k = 0; k < b.length; ++k)
c[i][j] += a[i][k] * b[k][j];
}
}
return c;
}
static double [][] transpose(double[][] a)
{
double[][] b = new double[a[0].length][a.length];
for(int i = 0 ; i < a.length; ++i)
for(int j = 0; j < a[0].length; ++j)
b[j][i] = a[i][j];
return b;
}
static double[] mult(double[][] a, double[] x)throws MatrixSizeNotMatch
{
if(a[0].length != x.length)
throw new MatrixSizeNotMatch();
double[] b = new double[a.length];
for(int i = 0; i < a.length; ++i)
{
for(int j = 0; j < a[0].length; ++j)
b[i] += a[i][j] * x[j];
}
return b;
}
static double [] mult(double [] y, double[][] a)throws MatrixSizeNotMatch
{
if(y.length != a.length)
throw new MatrixSizeNotMatch();
double[] c = new double[a[0].length];
for(int i = 0; i < a[0].length; ++i)
{
for(int j = 0; j < a.length; ++j)
{
c[i] += y[j] * a[j][i];
}
}
return c;
}
}
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class IfTest2 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
/*int jumsu =7;
if(jumsu>=90)
System.out.println("수");
else if (jumsu>=80)
System.out.println("우");
else if(jumsu>=70)
System.out.println("미");
else if (jumsu>=60)
System.out.println("양");
else System.out.println("가");*/
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("이름입력");
String name=in.readLine();
System.out.println("국어");
int kor=Integer.parseInt(in.readLine());
System.out.println("영어");
int eng=Integer.parseInt(in.readLine());
System.out.println(name);
if (kor>=90 &&eng >=90)
System.out.println("very good");
else if(kor>=90||eng>=90)
System.out.println("good");
else System.out.println("bad");
String result="";
if (kor>89 && eng>89)
result="very good";
else if (kor>89 || eng>89)
result="good";
else result="bad";
System.out.println("이름:"+name);
System.out.println("국어:"+kor);
System.out.println("영어:"+eng);
System.out.println("결과:"+result);
}
}
|
package com.ifeng.recom.mixrecall.prerank.entity;
import com.ifeng.recom.mixrecall.prerank.constant.Constant;
import com.ifeng.recom.mixrecall.prerank.executor.Operator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.Serializable;
/**
* 特征类:定义特征抽取的方式和操作算子,对应特征配置文件每行数据
* Created by zhaozp on 2017/5/11.
*/
public class Feature implements Serializable {
private static final long serialVersionUID = 2430881983334036432L;
protected static final Log LOG = LogFactory.getLog(Feature.class);
protected Long featureId ;//特征ID(数字字符串)
protected String featureName;//特征名称
protected int type;//特征类型:0(指标),1(连续),2(离散),3(GBDT),4(评分),5(LDA),6(fm);
protected String attrDimension; // 特征作用维度,相当于特征采用的数据维度字段,及作用方式;
protected Operator operator;//特征提取的计算算子的名称
protected boolean status;//特征是否使用: 1(使用),0(不使用)
public Long getFeatureId() {
return featureId;
}
public void setFeatureId(Long featureId) {
this.featureId = featureId;
}
public String getFeatureName() {
return featureName;
}
public void setFeatureName(String featureName) {
this.featureName = featureName;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Operator getOperator() {
return operator;
}
public void setOperator(Operator operator) {
this.operator = operator;
}
public boolean getStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getAttrDimension() {
return attrDimension;
}
public void setAttrDimension(String attrDimension) {
this.attrDimension = attrDimension;
}
public Feature(){
}
public Feature(Long featureId, String featureName, int type,
Operator operator, String attrDimension,boolean status) {
super();
this.featureId = featureId;
this.featureName = featureName;
this.type = type;
this.operator = operator;
this.attrDimension=attrDimension;
this.status = status;
}
public Feature(Long featureId, String featureName, int type,
Operator operator, boolean status) {
this(featureId,featureName,type,operator,"-",status);
}
public Feature(Long featureId, String featureName,
Operator operator,String attrDimension, boolean status) {
this(featureId,featureName,0,operator,attrDimension,status);
}
public Feature(Long featureId, String featureName,
Operator operator, boolean status) {
this(featureId,featureName,0,operator,"-",status);
}
/**
* 解析特征配置文档
* @param line
* @return
*/
public static Feature parse(String line){
String[] array = line.split("\\s+");
if (array.length < 6) {
LOG.warn("请注意本行小于6列. line: " + line);
return null;
}
try {
StringBuffer sb = new StringBuffer();
if (!array[3].contains(".")) {
sb.append(Constant.GENERAL_FEATURE_PACKAGE).append(".");
}
sb.append(array[3]);
Class<?> cl = Class.forName(sb.toString());
Operator operator = (Operator)cl.newInstance();
long featureId = Long.parseLong(array[0]);
if (featureId >= 0) {
Feature item = null;
if(array.length == 6){
item = new Feature(featureId,array[1],Integer.parseInt(array[2]),operator,array[4],(array[5].equals("1"))?true:false);
}else{
item = new Feature(featureId,array[1],0,operator,"-",(array[5].equals("1"))?true:false);
}
return item;
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
LOG.info("特征配置转换为实体错误. line: " + line);
return null;
}
}
|
package portal.listener;
import com.codeborne.selenide.Selenide;
import io.qameta.allure.Attachment;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import static com.codeborne.selenide.WebDriverRunner.getWebDriver;
import static org.openqa.selenium.logging.LogType.BROWSER;
public class AttachmentsHelper {
@Attachment(value = "{attachName}", type = "text/plain")
public static String attachAsText(String attachName, String message) {
return message;
}
@Attachment(value = "{attachName}", type = "image/png")
public static byte[] attachScreenshot(String attachName) {
return ((TakesScreenshot) getWebDriver()).getScreenshotAs(OutputType.BYTES);
}
public static String getBrowserConsoleLogs() {
return String.join("\n", Selenide.getWebDriverLogs(BROWSER));
}
}
|
package irix.measurement.structure;
import irix.convertor.sections.MeasurementsSectional;
public class MeasurementsSectionalAttributes extends MeasurementsSectional /*implements MeasurementsSectionalAttributesImp*/ {
private String validAt;
public MeasurementsSectionalAttributes() {
}
public MeasurementsSectionalAttributes(String validAt) {
this.validAt = validAt;
}
public String getValidAt() {
return validAt;
}
public void setValidAt(String validAt) {
this.validAt = validAt;
}
@Override
public String toString() {
return "validAt=" + validAt;
}
}
|
package com.blog.dusk.utils;
public class CodeStatus {
public final static String CODE_SUCCESS = "success";
public final static String CODE_FAILURE = "failure";
}
|
package ru.serdyuk.diff.entities;
import java.util.Optional;
import lombok.Builder;
import lombok.Value;
/**
* Main pojo class for the {@link ru.serdyuk.diff.controllers.DiffControllerV1}
* id - unique string
* left - first value
* right - second value
*/
@Value
@Builder
public class Diff {
String id;
@Builder.Default
Optional<String> left = Optional.empty();
@Builder.Default
Optional<String> right = Optional.empty();
}
|
package domain;
import data.model.user.Message;
import java.util.Date;
import java.util.List;
public interface UserRepository {
void createNewMessage(String userName, String text, Date date);
List<Message> getMessagesListByUser(String userName);
void createFollow(String userName, String followedUserName);
List<Message> getUserAndFollowedUserMessagesListByUser(String userName);
}
|
package com.company;
public class Main {
public static void main(String[] args) {
System.out.println(hasEqualSum(1,1,1));
System.out.println(hasEqualSum(1,1,2));
System.out.println(hasEqualSum(1,-1,0));
}
public static boolean hasEqualSum(int num1,int num2,int num3){
return (num1 + num2 == num3);
}
}
|
package lotro.my.reports;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import file.FileUtils;
import model.NumericMap;
import web.Firewall;
import web.GoogleChart;
import web.GoogleChart.ChartType;
public final class PvMP
{
private static final String ENCODING = "UTF8";
private GoogleChart chart;
private NumericMap<String, Integer> classMap =
new NumericMap<String, Integer>(Integer.class);
public PvMP()
{
String url;
// for (int page = 1; page <= 5; page++)
{
// url = "http://my.lotro.com/home/leaderboard/pvmp?lp[sf]=renown&lp[sd]=DESC&lp[f][wd]=5&lp[pp]=" + page;
url = "http://my.lotro.com/home/leaderboard/pvmp?lp[f][wd]=5&lp[f][kt]=The+Palantiri&lp[sf]=rating&lp[sd]=DESC";
try
{
CharSequence text = scrape (url);
parsePage (text);
}
catch (IOException x)
{
x.printStackTrace();
}
}
chartMap ("Top 100 Renown By Class", classMap);
}
public static CharSequence scrape (final String path) throws IOException
{
StringBuilder response = new StringBuilder();
BufferedReader buf = null;
try
{
// Firewall.defineProxy();
InputStream is;
if (path.startsWith ("http://"))
is = new URL (path).openStream();
else
is = new FileInputStream (path);
InputStreamReader isr = new InputStreamReader (is, ENCODING);
buf = new BufferedReader (isr);
String line;
while ((line = buf.readLine()) != null)
response.append (line);
}
catch (MalformedURLException x)
{
x.printStackTrace (System.err);
}
finally
{
FileUtils.close (buf);
}
return response;
}
/*
<a class="class" href="http://lorebook.lotro.com/wiki/Class:Hunter">
<img src="http://content.turbine.com/sites/playerportal/modules/lotro-base/images/icons/class/hunter.png" />
</a>
<a href="/home/character/5/146929937843041923">
Budhorn
</a></td>
<td class="rank"><img src="http://content.turbine.com/sites/playerportal/modules/lotro-base/images/icons/rank/freep_rank_14.png" title="Rank 14" /></td>
<td class="kinship">The Gank Squad</td>
<td class="renown">2562419</td>
<td class="rating">1306</td>
</tr>
*/
private final static Pattern CLASS =
Pattern.compile ("<a class=\"class\" href=\"http://lorebook.lotro.com/wiki/Class:([-A-Za-z]+)\">");
private final static Pattern RENOWN =
Pattern.compile ("<td class=\"renown\">([0-9]+)</td>");
void parsePage(final CharSequence page)
{
int i = 0;
Matcher m = CLASS.matcher (page);
while (m.find())
{
String klass = m.group (1);
System.out.println ((i++) + ") Class: " + klass);
classMap.plus (klass, 1);
}
}
void chartMap(final String title, final NumericMap<String, Integer> map)
{
/*
chart = new GoogleChart (title, ChartType.BarVerticalGrouped);
for (Entry<String, Integer> entry : map.entrySet ())
chart.addValue(entry.getKey(), entry.getValue() / 20);
chart.setColorsUsingGradient();
chart.show();
*/
chart = new GoogleChart (title, ChartType.Pie);
for (Entry<String, Integer> entry : map.entrySet ())
{
System.out.println (entry.getKey() + " - " + entry.getValue());
chart.addValue(entry.getKey(), entry.getValue());
}
chart.setColorsUsingGradient();
chart.show();
}
public static void main (final String[] args) throws Exception
{
PvMP pvmp = new PvMP();
}
}
|
/*
* Copyright 2017 Goldman Sachs.
* 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.gs.tablasco.verify;
import java.io.Serializable;
public class VarianceCellComparator extends CellComparator implements Serializable
{
private final double varianceThreshold;
public VarianceCellComparator(CellFormatter formatter, double varianceThreshold)
{
super(formatter);
this.varianceThreshold = varianceThreshold;
}
@Override
public boolean compare(Object actual, Object expected)
{
if (isFloatingPoint(expected) && isFloatingPoint(actual))
{
double variance = getVariance(actual, expected);
return Math.abs(variance) <= this.varianceThreshold;
}
return false;
}
static double getVariance(Object actual, Object expected)
{
double number1 = ((Number) actual).doubleValue();
double number2 = ((Number) expected).doubleValue();
return (number1 - number2) * 100.0d / number2;
}
}
|
package com.mediafire.sdk.response_models.user;
import com.mediafire.sdk.response_models.ApiResponse;
public class UserSetAvatarResponse extends ApiResponse {
private String quick_key;
private String upload_key;
public String getQuickKey() {
return quick_key;
}
public String getUploadKey() {
return upload_key;
}
}
|
package saboteur.state;
import java.util.LinkedList;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import saboteur.GameStateMachine;
import saboteur.model.Game;
import saboteur.model.Operation;
import saboteur.model.Player;
import saboteur.model.Card.ActionCardToPlayer;
import saboteur.model.Card.Card;
import saboteur.model.Card.DoubleRescueCard;
import saboteur.model.Card.RescueCard;
import saboteur.model.Card.SabotageCard;
import saboteur.model.Card.Tool;
import saboteur.view.GameCardContainer;
import saboteur.view.PlayerArc;
import saboteur.view.TrashAndPickStackContainer;
public class PlayerSelectedActionCardToPlayerState extends State{
private GameCardContainer gameCardContainer;
private ActionCardToPlayer card;
private PlayerArc playersArc;
private TrashAndPickStackContainer trashAndPickStackContainer;
private LinkedList<Player> playerList;
private int toolValue1 = -1;
private int toolValue2 = -1;
private Player playerSelected;
private Tool toolSelected;
public PlayerSelectedActionCardToPlayerState(GameStateMachine gsm, Game game, Stage primaryStage){
super(gsm, game, primaryStage);
}
@Override
public void update() {
}
@Override
public void render() {
}
@Override
public void onEnter(Object param) {
this.trashAndPickStackContainer = (TrashAndPickStackContainer) this.primaryStage.getScene().lookup("#trashAndPickStackContainer");
this.gameCardContainer = (GameCardContainer) this.primaryStage.getScene().lookup("#gameCardContainer");
this.playersArc = (PlayerArc) this.primaryStage.getScene().lookup("#playersArc");
this.playersArc.refreshPlayersArcsAndCircles();
EventHandler<MouseEvent> mouseEvent = this::selectedActionCardToPlayer;
//Put a correct value on toolValue depending of the selected card.
this.toolValue1 = -1;
this.toolValue2 = -1;
Card selectedCard = this.gameCardContainer.getSelectedCard();
this.card = (ActionCardToPlayer) selectedCard;
if(selectedCard.isSabotageCard()) {
this.toolValue1 = ((SabotageCard)selectedCard).getSabotageType().getValue();
this.playersArc.activateHandicapCircle(this.toolValue1, this.game.getPlayers(this.card), mouseEvent, true);
}
else if(selectedCard.isRescueCard()) {
this.toolValue1 = ((RescueCard)selectedCard).getTool().getValue();
this.playersArc.activateHandicapCircle(this.toolValue1, this.game.getPlayers(this.card), mouseEvent, false);
}
else if(selectedCard.isDoubleRescueCard()) {
this.toolValue1 = ((DoubleRescueCard)selectedCard).getTool1().getValue();
this.toolValue2 = ((DoubleRescueCard)selectedCard).getTool2().getValue();
this.playersArc.activateHandicapCircle(this.toolValue1, this.game.getPlayers( new RescueCard(Tool.intToTool(this.toolValue1))), mouseEvent, false);
this.playersArc.activateHandicapCircle(this.toolValue2, this.game.getPlayers( new RescueCard(Tool.intToTool(this.toolValue2))), mouseEvent, false);
}
}
@Override
public void onExit() {
this.trashAndPickStackContainer.disablePickAndEndTurnButton();
this.trashAndPickStackContainer.setEventToPickAndEndTurnButton(null);
//Delete event on click
this.playersArc.desactivateHandicapCircle(this.toolValue1, this.toolValue2);
}
private void selectedActionCardToPlayer(MouseEvent event) {
this.playersArc.refreshPlayersArcsAndCircles();
if(this.gameCardContainer.getSelectedCard().isSabotageCard()) {
Circle circle = (Circle) event.getTarget();
this.playersArc.refreshCircles(circle, this.toolValue1, true);
for(Player p : this.game.getPlayers(this.card)) {
if( this.playersArc.getCircles(p)[this.toolValue1] == circle ){
this.playerSelected = p;
}
}
}
else {
Circle circle = (Circle) event.getTarget();
for(Player p : this.game.getPlayers(this.card)) {
if( this.playersArc.getCircles(p)[this.toolValue1] == circle ){
this.playerSelected = p;
this.toolSelected = Tool.intToTool(toolValue1);
this.playersArc.refreshCircles(circle, this.toolValue1, false);
}
if( this.toolValue2 != -1 && this.playersArc.getCircles(p)[this.toolValue2] == circle ) {
this.playerSelected = p;
this.toolSelected = Tool.intToTool(toolValue2);
this.playersArc.refreshCircles(circle, this.toolValue2, false);
}
}
}
this.trashAndPickStackContainer.enablePickAndEndTurnButton();
this.trashAndPickStackContainer.setEventToPickAndEndTurnButton(e -> endOfTurn());
}
private void endOfTurn() {
Operation op;
if (this.toolSelected == null){
op = this.game.getCurrentPlayer().playCard(this.playerSelected);
} else{
op = this.game.getCurrentPlayer().playCard(this.playerSelected, this.toolSelected);
}
this.gsm.changePeek("playerPlayCard", op);
}
}
|
package com.karya.bean;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
public class MonthlyAttendSheetReportBean {
private int atsId;
@NotNull
@NotEmpty(message = "Please enter year")
private String attYear;
@NotNull
@NotEmpty(message = "Please enter employee number")
private String empNumber;
@NotNull
@NotEmpty(message = "Please enter employee name")
private String empName;
@NotNull
@NotEmpty(message = "Please enter employee branch")
private String branch;
@NotNull
@NotEmpty(message = "Please enter employee department")
private String deptName;
@NotNull
@NotEmpty(message = "Please enter employee designation")
private String empDesign;
@NotNull
@NotEmpty(message = "Please enter employee company")
private String empCompany;
private String one1;
private String two2;
private String three3;
private String four4;
private String five5;
private String six6;
private String seven7;
private String eight8;
private String nine9;
private String ten10;
private String eleven11;
private String twelve12;
private String thirteen13;
private String fourteen14;
private String fifteen15;
private String sixteen16;
private String seventeen17;
private String eighteen18;
private String nineteen19;
private String twenty20;
private String twentyone21;
private String twentytwo22;
private String twentythree23;
private String twentyfour24;
private String twentyfive25;
private String twentysix26;
private String twentyseven27;
private String twentyeight28;
private String twentynine29;
private String thirty30;
private String totalPresent;
private String totalAbsent;
private String months;
public String getMonths() {
return months;
}
public void setMonths(String months) {
this.months = months;
}
public int getAtsId() {
return atsId;
}
public void setAtsId(int atsId) {
this.atsId = atsId;
}
public String getAttYear() {
return attYear;
}
public void setAttYear(String attYear) {
this.attYear = attYear;
}
public String getEmpNumber() {
return empNumber;
}
public void setEmpNumber(String empNumber) {
this.empNumber = empNumber;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getEmpDesign() {
return empDesign;
}
public void setEmpDesign(String empDesign) {
this.empDesign = empDesign;
}
public String getEmpCompany() {
return empCompany;
}
public void setEmpCompany(String empCompany) {
this.empCompany = empCompany;
}
public String getOne1() {
return one1;
}
public void setOne1(String one1) {
this.one1 = one1;
}
public String getTwo2() {
return two2;
}
public void setTwo2(String two2) {
this.two2 = two2;
}
public String getThree3() {
return three3;
}
public void setThree3(String three3) {
this.three3 = three3;
}
public String getFour4() {
return four4;
}
public void setFour4(String four4) {
this.four4 = four4;
}
public String getFive5() {
return five5;
}
public void setFive5(String five5) {
this.five5 = five5;
}
public String getSix6() {
return six6;
}
public void setSix6(String six6) {
this.six6 = six6;
}
public String getSeven7() {
return seven7;
}
public void setSeven7(String seven7) {
this.seven7 = seven7;
}
public String getEight8() {
return eight8;
}
public void setEight8(String eight8) {
this.eight8 = eight8;
}
public String getNine9() {
return nine9;
}
public void setNine9(String nine9) {
this.nine9 = nine9;
}
public String getTen10() {
return ten10;
}
public void setTen10(String ten10) {
this.ten10 = ten10;
}
public String getEleven11() {
return eleven11;
}
public void setEleven11(String eleven11) {
this.eleven11 = eleven11;
}
public String getTwelve12() {
return twelve12;
}
public void setTwelve12(String twelve12) {
this.twelve12 = twelve12;
}
public String getThirteen13() {
return thirteen13;
}
public void setThirteen13(String thirteen13) {
this.thirteen13 = thirteen13;
}
public String getFourteen14() {
return fourteen14;
}
public void setFourteen14(String fourteen14) {
this.fourteen14 = fourteen14;
}
public String getFifteen15() {
return fifteen15;
}
public void setFifteen15(String fifteen15) {
this.fifteen15 = fifteen15;
}
public String getSixteen16() {
return sixteen16;
}
public void setSixteen16(String sixteen16) {
this.sixteen16 = sixteen16;
}
public String getSeventeen17() {
return seventeen17;
}
public void setSeventeen17(String seventeen17) {
this.seventeen17 = seventeen17;
}
public String getEighteen18() {
return eighteen18;
}
public void setEighteen18(String eighteen18) {
this.eighteen18 = eighteen18;
}
public String getNineteen19() {
return nineteen19;
}
public void setNineteen19(String nineteen19) {
this.nineteen19 = nineteen19;
}
public String getTwenty20() {
return twenty20;
}
public void setTwenty20(String twenty20) {
this.twenty20 = twenty20;
}
public String getTwentyone21() {
return twentyone21;
}
public void setTwentyone21(String twentyone21) {
this.twentyone21 = twentyone21;
}
public String getTwentytwo22() {
return twentytwo22;
}
public void setTwentytwo22(String twentytwo22) {
this.twentytwo22 = twentytwo22;
}
public String getTwentythree23() {
return twentythree23;
}
public void setTwentythree23(String twentythree23) {
this.twentythree23 = twentythree23;
}
public String getTwentyfour24() {
return twentyfour24;
}
public void setTwentyfour24(String twentyfour24) {
this.twentyfour24 = twentyfour24;
}
public String getTwentyfive25() {
return twentyfive25;
}
public void setTwentyfive25(String twentyfive25) {
this.twentyfive25 = twentyfive25;
}
public String getTwentysix26() {
return twentysix26;
}
public void setTwentysix26(String twentysix26) {
this.twentysix26 = twentysix26;
}
public String getTwentyseven27() {
return twentyseven27;
}
public void setTwentyseven27(String twentyseven27) {
this.twentyseven27 = twentyseven27;
}
public String getTwentyeight28() {
return twentyeight28;
}
public void setTwentyeight28(String twentyeight28) {
this.twentyeight28 = twentyeight28;
}
public String getTwentynine29() {
return twentynine29;
}
public void setTwentynine29(String twentynine29) {
this.twentynine29 = twentynine29;
}
public String getThirty30() {
return thirty30;
}
public void setThirty30(String thirty30) {
this.thirty30 = thirty30;
}
public String getTotalPresent() {
return totalPresent;
}
public void setTotalPresent(String totalPresent) {
this.totalPresent = totalPresent;
}
public String getTotalAbsent() {
return totalAbsent;
}
public void setTotalAbsent(String totalAbsent) {
this.totalAbsent = totalAbsent;
}
}
|
package com.wd.myinfo;
public class textone {
}
|
import java.util.Scanner;
public class SumSeconds {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int firstTime = Integer.parseInt(scan.nextLine());
int secondTime = Integer.parseInt(scan.nextLine());
int thirdTime = Integer.parseInt(scan.nextLine());
int allSeconds = firstTime + secondTime + thirdTime;
int minutes = allSeconds / 60;
int seconds = allSeconds % 60;
if (seconds < 10) {
System.out.println(minutes + ":0" + seconds);
} else {
System.out.printf("%d:%d", minutes, seconds);
}
}
}
|
/*
* Copyright 2003-2005 the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jdon.jivejdon.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.jdon.util.UtilDateTime;
/**
* tools for this project.
* @author <a href="mailto:banqJdon<AT>jdon.com">banq</a>
*
*/
public class ToolsUtil {
private static final long ROOT_PARENTMESSAGEID = 0;
private static final char[] zeroArray = "0000000000000000".toCharArray();
public static final String zeroPadString(String string, int length) {
if (string == null || string.length() > length) {
return string;
}
StringBuffer buf = new StringBuffer(length);
buf.append(zeroArray, 0, length - string.length()).append(string);
return buf.toString();
}
public static final String dateToMillis(long now) {
return zeroPadString(Long.toString(now), 15);
}
public static String getDateTimeDisp(String datetime) {
if ((datetime == null) || (datetime.equals("")))
return "";
DateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
;
long datel = Long.parseLong(datetime);
return formatter.format(new Date(datel));
}
public static Long getParentIDOfRoot() {
return new Long(ROOT_PARENTMESSAGEID);
}
public static boolean isRoot(Long parentID) {
if (parentID.longValue() == ROOT_PARENTMESSAGEID)
return true;
else
return false;
}
public static final String dateToMillis(Date date) {
return zeroPadString(Long.toString(date.getTime()), 15);
}
/**
* the String can be as the key of cache
* @param date
* @return a long string with no Hour/Minute/Mills
*/
public static String dateToNoMillis(Date date) {
//001184284800000
String s = dateToMillis(date);
StringBuffer sb = new StringBuffer(s.substring(0, 10));
sb.append("00000");
return sb.toString();
}
/** Converts a date String and a time String into a Date
* @param date The date String: YYYY-MM-DD
* @param time The time String: either HH:MM or HH:MM:SS
* @return A Date made from the date and time Strings
*/
public static java.util.Date toDate(String date, String time, String split) {
if (date == null || time == null)
return null;
String month;
String day;
String year;
String hour;
String minute;
String second;
int dateSlash1 = date.indexOf(split);
int dateSlash2 = date.lastIndexOf(split);
if (dateSlash1 <= 0 || dateSlash1 == dateSlash2)
return null;
int timeColon1 = time.indexOf(":");
int timeColon2 = time.lastIndexOf(":");
if (timeColon1 <= 0)
return null;
year = date.substring(0, dateSlash1);
month = date.substring(dateSlash1 + 1, dateSlash2);
day = date.substring(dateSlash2 + 1);
hour = time.substring(0, timeColon1);
if (timeColon1 == timeColon2) {
minute = time.substring(timeColon1 + 1);
second = "0";
} else {
minute = time.substring(timeColon1 + 1, timeColon2);
second = time.substring(timeColon2 + 1);
}
return UtilDateTime.toDate(month, day, year, hour, minute, second);
}
public static String toDateString(java.util.Date date, String splite) {
if (date == null)
return "";
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int year = calendar.get(Calendar.YEAR);
String monthStr;
String dayStr;
String yearStr;
if (month < 10) {
monthStr = "0" + month;
} else {
monthStr = "" + month;
}
if (day < 10) {
dayStr = "0" + day;
} else {
dayStr = "" + day;
}
yearStr = "" + year;
return yearStr + splite + monthStr + splite + dayStr;
}
public static String toDateHourString(java.util.Date date) {
if (date == null)
return "";
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
StringBuffer sb = new StringBuffer(UtilDateTime.toDateString(date));
sb.append(toHourString(calendar.get(Calendar.HOUR_OF_DAY)));
return sb.toString();
}
private static String toHourString(int hour) {
String hourStr;
if (hour < 10) {
hourStr = "0" + hour;
} else {
hourStr = "" + hour;
}
return hourStr;
}
/**
* Used by the hash method.
*/
private static MessageDigest digest = null;
public synchronized static final String hash(String data) {
if (digest == null) {
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException nsae) {
System.err.println("Failed to load the MD5 MessageDigest. " + "Jive will be unable to function normally.");
nsae.printStackTrace();
}
}
// Now, compute hash.
digest.update(data.getBytes());
return encodeHex(digest.digest());
}
/**
* Turns an array of bytes into a String representing each byte as an
* unsigned hex number.
* <p>
* Method by Santeri Paavolainen, Helsinki Finland 1996<br>
* (c) Santeri Paavolainen, Helsinki Finland 1996<br>
* Distributed under LGPL.
*
* @param bytes an array of bytes to convert to a hex-string
* @return generated hex string
*/
public static final String encodeHex(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
int i;
for (i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buf.toString();
}
}
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.neuron.mytelkom.fragment;
import android.app.ProgressDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.neuron.mytelkom.utils.Utils;
import org.apache.http.Header;
// Referenced classes of package com.neuron.mytelkom.fragment:
// DetailConferenceFragment
class val.dialog extends AsyncHttpResponseHandler
{
final DetailConferenceFragment this$0;
private final ProgressDialog val$dialog;
public void onFailure(int i, Header aheader[], byte abyte0[], Throwable throwable)
{
super.onFailure(i, aheader, abyte0, throwable);
val$dialog.dismiss();
}
public void onSuccess(int i, Header aheader[], byte abyte0[])
{
super.onSuccess(i, aheader, abyte0);
val$dialog.dismiss();
String s = new String(abyte0);
Utils.printLog(s);
fetchCancelResponse(s);
}
()
{
this$0 = final_detailconferencefragment;
val$dialog = ProgressDialog.this;
super();
}
}
|
package com.maliang.core.model;
public class Block extends MongodbModel {
public static final int TYPE_CODE = 1;
public static final int TYPE_HTML = 2;
private String name;
private String code;
/**
* 1:code
* 2:html
* ***/
private Integer type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
}
|
package week3day1;
public class LearnOverload {
public void employeeInfo() {
String name = "Indhu";
System.out.println("employee info " + name);
}
public void employeeInfo(int id, String name) {
System.out.println("id: " + id);
System.out.println("name of the employee: " + name);
}
public void employeeInfo(String name, int id) {
System.out.println("id :" + id);
System.out.println("name of the employee: " + name);
}
public static void main(String[] args) {
LearnOverload lol=new LearnOverload();
lol.employeeInfo();
lol.employeeInfo(10, "Indhu");
lol.employeeInfo("IndhujaPrabu", 11);
}
}
|
package com.inn.catalogapplication.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.inn.catalogapplication.model.Category;
@Repository
public interface CategoryRepository extends JpaRepository<Category, Integer>{
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public *
* License as published by the Free Software Foundation; either *
* version 3 of the License, or any later version. *
* *
* Data Crow is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this program. If not, see http://www.gnu.org/licenses *
* *
******************************************************************************/
package net.datacrow.settings.definitions;
import net.datacrow.core.modules.DcModule;
public class QuickViewFieldDefinition extends Definition {
private int field;
private boolean enabled;
private String direction = "";
private int maxLength = 0;
public QuickViewFieldDefinition(int field, boolean enabled, String direction, int maxLength) {
super();
this.field = field;
this.enabled = enabled;
this.direction = direction;
this.maxLength = maxLength;
}
public int getMaxLength() {
return maxLength;
}
public String getDirectrion() {
return direction;
}
public int getField() {
return field;
}
public boolean isEnabled() {
return enabled;
}
@Override
public String toSettingValue() {
return field + "/&/" + enabled + "/&/" + direction + "/&/" + maxLength;
}
public Object[] getDisplayValues(DcModule module) {
return new Object[] {module.getField(field).getLabel(),
enabled, direction, module.getField(field), maxLength};
}
@Override
public boolean equals(Object o) {
if (o instanceof QuickViewFieldDefinition) {
QuickViewFieldDefinition def = (QuickViewFieldDefinition) o;
return def.getField() == getField();
}
return false;
}
}
|
/*
* 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 ITPM;
import static ITPM.Dashboard.Dash_UploadSpace;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import static ITPM.complexityControlStructure.CSTableOutput;
/**
*
* @author Chanuka
*/
public class WeightControlStructure extends javax.swing.JFrame {
/**
* Creates new form WeightControlStructure
*/
public WeightControlStructure() {
initComponents();
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabelChange = new javax.swing.JLabel();
jTextChange = new javax.swing.JTextField();
jButtonChange = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(0, 102, 102));
setMaximumSize(new java.awt.Dimension(660, 432));
setMinimumSize(new java.awt.Dimension(660, 432));
setPreferredSize(new java.awt.Dimension(660, 432));
jTable1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"A conditional control structure such as an ‘if’ or ‘else-if’ condition", "2"},
{"An iterative control structure such as a ‘for’, ‘while’, or ‘do-while’ loop", "3"},
{"The ‘switch’ statement in a ‘switch-case’ control structure", "2"},
{"Each ‘case’ statement in a ‘switch-case’ control structure", "1"}
},
new String [] {
"Control Structure Type", "Weight"
}
) {
boolean[] canEdit = new boolean [] {
false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setRowHeight(24);
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0) {
jTable1.getColumnModel().getColumn(1).setMaxWidth(150);
}
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setText("Weights related to the control structure factor");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel2.setText("Change Weight :");
jLabelChange.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jTextChange.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jButtonChange.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jButtonChange.setText("Change");
jButtonChange.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonChangeActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton2.setText("Start Measuring");
jButton2.setMaximumSize(new java.awt.Dimension(147, 25));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelChange, javax.swing.GroupLayout.PREFERRED_SIZE, 451, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jTextChange, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(jButtonChange, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGap(50, 50, 50))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(252, 252, 252))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabelChange, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextChange, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE))
.addComponent(jButtonChange, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(23, 23, 23))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonChangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonChangeActionPerformed
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
int i = jTable1.getSelectedRow();
if(i >= 0){
model.setValueAt(jTextChange.getText(),i,1);
}else{
JOptionPane.showMessageDialog(null,"Click on a row to change");
} // TODO add your handling code here:
}//GEN-LAST:event_jButtonChangeActionPerformed
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
int selectedRow = jTable1.getSelectedRow();
jLabelChange.setText(model.getValueAt(selectedRow,0).toString());
jTextChange.setText(model.getValueAt(selectedRow,1).toString()); // TODO add your handling code here:
}//GEN-LAST:event_jTable1MouseClicked
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
complexityControlStructure cs = new complexityControlStructure();
cs.setVisible(true);
//creating objects of tables
DefaultTableModel model_input = (DefaultTableModel)jTable1.getModel();
DefaultTableModel model_output = (DefaultTableModel)CSTableOutput.getModel();
Reader inputString = new StringReader(Dash_UploadSpace.getText().toString());
//creating an object of buffer reader
BufferedReader br = new BufferedReader(inputString);
//defining variables
String text;
int count_if = 0;
int count_elseif = 0;
int count_for = 0;
int count_while = 0;
int count_switch = 0;
int count_case = 0;
int weight = 0;
int countLine = 0;
String previous_complexity ;
String previous_complexityIF = null;
String previousTextIF = null;
String no_of_cs;
String previousComplex;
String wCs;
String line60IF = null;
int lineIF = 0;
int countNC = 0;
int pc = 0;
int nc = 1;
int Ccs = 0;
int Wtcs = 0;
int Ccspps = 0;
int CcsSwitch = 0;
int OBrackets = 0;
int CBrackets = 0;
int previousCountLine = 0;
String w;
String previous = "";
try{
//Reading lines
while((text = br.readLine()) != null){
if(text.contains("if") || text.contains("for") || text.contains("while") || text.contains("do") || text.contains("switch")){
// if(!text.contains("{")){
// model_output.setValueAt(text,countLine,1);
// model_output.setValueAt(countLine+1,countLine,0);
// countLine++;
// text = br.readLine();
// }
Ccspps = Integer.parseInt(model_output.getValueAt(countLine-1,5).toString());
previous = text;
OBrackets++;
model_output.setValueAt(text,countLine,1);
model_output.setValueAt(countLine+1,countLine,0);
//get weigths from weights table
if(text.contains("if")){
Wtcs = Integer.parseInt(model_input.getValueAt(0,1).toString());
}else if(text.contains("for") || text.contains("while") || text.contains("do")){
Wtcs = Integer.parseInt(model_input.getValueAt(1,1).toString());
}else if(text.contains("switch")){
Wtcs = Integer.parseInt(model_input.getValueAt(2,1).toString());
}
//Search && in if
String[] newString = text.split("\\s+");
for(String ss : newString){
if(ss.contains("&&")){
nc++;
}
}
//Setting values to table
model_output.setValueAt(Wtcs,countLine,2);
model_output.setValueAt(nc,countLine,3);
Ccs = (Wtcs * nc) + Ccspps;
model_output.setValueAt(Ccs,countLine,5);
model_output.setValueAt(Ccspps,countLine,4);
CcsSwitch = Integer.parseInt(model_output.getValueAt(countLine,5).toString());
model_output.setValueAt(text,countLine,1);
model_output.setValueAt(countLine+1,countLine,0);
countLine++;
nc = 1;
text = br.readLine();
//Go inside
while(OBrackets != CBrackets){
//Checking nested
//for,while,do
if(text.contains("for") || text.contains("while") || text.contains("do")){
Ccspps = Integer.parseInt(model_output.getValueAt(countLine-1,5).toString());
if(previous.contains("for") && text.contains("for")){
Ccspps = Integer.parseInt(model_output.getValueAt(countLine-1,5).toString());
}if(previous.contains("while") && text.contains("while")){
Ccspps = Integer.parseInt(model_output.getValueAt(countLine-1,5).toString());
}if(previous.contains("do") && text.contains("do")){
Ccspps = Integer.parseInt(model_output.getValueAt(countLine-1,5).toString());
}
String[] string = text.split("\\s+");
for(String ss : string){
if(ss.contains("&&")){
nc++;
}
}
//Setting values to table
OBrackets++;
model_output.setValueAt(nc,countLine,3);
Wtcs = Integer.parseInt(model_input.getValueAt(1,1).toString());
model_output.setValueAt(Wtcs,countLine,2);
Ccs = (Wtcs * nc) + Ccspps;
model_output.setValueAt(Ccs,countLine,5);
model_output.setValueAt(text,countLine,1);
model_output.setValueAt(countLine+1,countLine,0);
model_output.setValueAt(Ccspps,countLine,4);
text = br.readLine();
previous = text;
countLine++;
}
//if
else if(text.contains("if") && !text.contains("//")){
if(previous.contains("if") && text.contains("if")){
Ccspps = Integer.parseInt(model_output.getValueAt(countLine-1,5).toString());
}
String[] string = text.split("\\s+");
for(String ss : string){
if(ss.contains("&&")){
nc++;
}
}
//Setting values to table
OBrackets++;
model_output.setValueAt(nc,countLine,3);
Wtcs = Integer.parseInt(model_input.getValueAt(0,1).toString());
model_output.setValueAt(Wtcs,countLine,2);
Ccs = (Wtcs * nc) + Ccspps;
model_output.setValueAt(Ccs,countLine,5);
model_output.setValueAt(text,countLine,1);
model_output.setValueAt(countLine+1,countLine,0);
model_output.setValueAt(Ccspps,countLine,4);
text = br.readLine();
previous = text;
countLine++;
}
//else if
else if(text.contains("else") && !text.contains("//")){
OBrackets++;
Ccspps = Integer.parseInt(model_output.getValueAt(countLine-1,5).toString());
model_output.setValueAt(text,countLine,1);
model_output.setValueAt(countLine+1,countLine,0);
model_output.setValueAt(Ccs,countLine,5);
text = br.readLine();
countLine++;
}
//Switch
else if(text.contains("switch") && !text.contains("//")){
Ccspps = Integer.parseInt(model_output.getValueAt(countLine-1,5).toString());
model_output.setValueAt(text,countLine,1);
model_output.setValueAt(countLine+1,countLine,0);
model_output.setValueAt(1,countLine,3);
Wtcs = Integer.parseInt(model_input.getValueAt(2,1).toString());
model_output.setValueAt(Ccspps,countLine,4);
model_output.setValueAt(Wtcs,countLine,2);
Ccs = (Wtcs * nc) + Ccspps;
model_output.setValueAt(Ccs,countLine,5);
text = br.readLine();
previous = text;
CcsSwitch = Integer.parseInt(model_output.getValueAt(countLine,5).toString());
countLine++;
}
//Case
else if(text.contains("case") && !text.contains("//")){
Ccspps = Integer.parseInt(model_output.getValueAt(countLine-1,5).toString());
model_output.setValueAt(text,countLine,1);
model_output.setValueAt(countLine+1,countLine,0);
model_output.setValueAt(1,countLine,3);
Wtcs = Integer.parseInt(model_input.getValueAt(3,1).toString());
model_output.setValueAt(CcsSwitch,countLine,4);
model_output.setValueAt(Wtcs,countLine,2);
Ccs = (Wtcs * nc) + CcsSwitch;
model_output.setValueAt(Ccs,countLine,5);
text = br.readLine();
countLine++;
}else if(text.contains("}")){
CBrackets++;
if(OBrackets == CBrackets){
model_output.setValueAt(text,countLine,1);
model_output.setValueAt(countLine+1,countLine,0);
Ccs = (Wtcs * nc) + Ccspps;
model_output.setValueAt(Ccs,countLine,5);
//set wtcs,NC,CCspps,Ccs
//text = br.readLine();
countLine++;
}else{
model_output.setValueAt(text,countLine,1);
model_output.setValueAt(countLine+1,countLine,0);
Ccs = (Wtcs * nc) + Ccspps;
model_output.setValueAt(Ccs,countLine,5);
text = br.readLine();
countLine++;
}
}else{
Wtcs = 0;
Ccs = 0;
Ccspps = 0;
nc = 1;
model_output.setValueAt(text,countLine,1);
model_output.setValueAt(countLine+1,countLine,0);
Ccs = (Wtcs * nc) + Ccspps;
model_output.setValueAt(Ccs,countLine,5);
text = br.readLine();
countLine++;
}
Wtcs = 0;
Ccs = 0;
Ccspps = 0;
nc = 1;
}
Wtcs = 0;
Ccs = 0;
Ccspps = 0;
}
//printing lines which are not containing any control structure
else{
model_output.setValueAt(text,countLine,1);
model_output.setValueAt(countLine+1,countLine,0);
Ccs = (Wtcs * nc) + Ccspps;
model_output.setValueAt(Ccs,countLine,5);
countLine++;
Wtcs = 0;
Ccs = 0;
Ccspps = 0;
}
}
}catch(IOException e){
Logger.getLogger(WeightControlStructure.class.getName()).log(Level.SEVERE, null, e);
}
//
//
}//GEN-LAST:event_jButton2ActionPerformed
// /**
// * @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(WeightControlStructure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (InstantiationException ex) {
// java.util.logging.Logger.getLogger(WeightControlStructure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (IllegalAccessException ex) {
// java.util.logging.Logger.getLogger(WeightControlStructure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (javax.swing.UnsupportedLookAndFeelException ex) {
// java.util.logging.Logger.getLogger(WeightControlStructure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// }
// //</editor-fold>
// //</editor-fold>
//
// /* Create and display the form */
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
// new WeightControlStructure().setVisible(true);
// }
// });
// }
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton2;
private javax.swing.JButton jButtonChange;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabelChange;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextChange;
// End of variables declaration//GEN-END:variables
}
|
package com.atmecs.employeedatabase.crudoperations;
import java.util.Scanner;
import org.hibernate.Session;
import org.hibernate.SessionException;
import com.atmecs.employeedatabase.entity.Employee;
import com.atmecs.employeedatabase.util.HibernateUtil;
public class DeleteData {
public void deleteData() {
Session session = HibernateUtil.currentSession();
Scanner sc = new Scanner(System.in);
try {
session.beginTransaction();
System.out.println("Enter id to delete record:");
Employee emp = (Employee) session.get(Employee.class, sc.nextInt());
if (emp != null) {
session.delete(emp);
session.getTransaction().commit();
System.out.println("Record deleted successfully..!!");
} else {
System.out.println("Record not found for given id, please enter a correct id");
}
} catch (SessionException e) {
System.out.println(e);
} finally {
HibernateUtil.closeSession();
}
}
}
|
package hard;
import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
/**
*
* @author xiebi
*服务端
*功能:接受客户端发来的消息,然后发送给所有在线的客户端
*/
public class Server
{
public static ArrayList<Socket> sockets=new ArrayList<Socket>();
public static ArrayList<String> names=new ArrayList<String>();
public static void main(String[] args) {
try {
names.add("小明");
names.add("小红");
names.add("小军");
names.add("小李");
names.add("小赵");
System.out.println("服务器启动");
ServerSocket server=new ServerSocket(1995);
int count=0;
while(true)
{
System.out.println("等待客户端连接");
Socket s = server.accept();//等待客户端连接
sockets.add(s);
System.out.println("客户端已连接,目前在线人数"+sockets.size());
new ServerThread(s,names.get(count++)).start();//服务器为每一个线程开启线程
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ServerThread extends Thread
{
private Socket s;
private String name;
public ServerThread(Socket s, String name)
{
this.s=s;
this.name=name;
}
public void run()
{
try {
BufferedReader br=new BufferedReader
(new InputStreamReader(s.getInputStream()));
while(true)
{
String content=br.readLine();
System.out.println(this.name+":"+content);
for(Socket socket:Server.sockets)
{
OutputStreamWriter osw =
new OutputStreamWriter(socket.getOutputStream());
osw.write(this.name+":"+content+'\n');
osw.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.yan.coupons.dto;
public class UserDto {
long id;
String name;
}
|
package com.ism.projects.th;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.ism.common.Common;
import com.ism.common.database.CommonDatabase;
import com.ism.common.exception.ErrorCode;
import com.ism.common.exception.ErrorMessage;
import com.ism.common.exception.ExUtil;
import com.ism.common.exception.ISMException;
import com.ism.common.util.Utility;
import com.ism.online.target.exception.TargetException;
import com.ism.rule.entity.Field;
import com.ism.rule.entity.FieldGroup;
import com.ism.rule.entity.constant.Constants;
import com.ism.rule.entity.data.FieldGroupMap;
import com.ism.rule.exception.RuleInterfaceException;
import com.ism.transformer.exception.TransformerException;
/**
* EKL Business Service.
* abstract method <b>executeService(byte[])</b> <br/>
* EKL Error Code define, input data parse, output data make.
*
* @author HJ KANG
* @version 1.0
*/
public abstract class EKLService extends ParameterCall {
/**
* ERROR CODE - {@value #EKL_SUCCESS}
*/
public final static String EKL_SUCCESS = "0000";
/**
* ERROR CODE : {@value #EKL_ACCOUNT_GENERAL_REGISTRATION_FAILURE}
*/
public final static String EKL_ACCOUNT_GENERAL_REGISTRATION_FAILURE = "1000";
/**
* ERROR CODE : {@value #EKL_FREQUENCY_CHECK_FAIL}
*/
public final static String EKL_FREQUENCY_CHECK_FAIL = "4100";
/**
* ERROR CODE : {@value #EKL_PERSONAL_CHECK_FAIL}
*/
public final static String EKL_PERSONAL_CHECK_FAIL = "4200";
/**
* ERROR CODE : {@value #EKL_EXCEEDING_NUMBER_ACCOUNT_HOLDERS_GROUP}
*/
public final static String EKL_EXCEEDING_NUMBER_ACCOUNT_HOLDERS_GROUP = "4300";
/**
* ERROR CODE : {@value #HAJJ_AGE_DISQUALIFIED}
*/
public final static String HAJJ_AGE_LIMIT_DISQUALIFIED = "4400";
/**
* ERROR CODE : {@value #EKL_INSUFFICIENT_ACCOUNT_BALANCE}
*/
public final static String EKL_INSUFFICIENT_ACCOUNT_BALANCE = "5000";
/**
* ERROR CODE : {@value #EKL_NO_HAJJ_REGISTRATION_RECOEDS}
*/
public final static String EKL_NO_HAJJ_REGISTRATION_RECOEDS = "5500";
/**
* ERROR CODE : {@value #EKL_ACCOUNT_ALREADY_REGISTERED_FOR_HAJJ}
*/
public final static String EKL_ACCOUNT_ALREADY_REGISTERED_FOR_HAJJ = "7000";
/**
* ERROR CODE : {@value #EKL_ACCOUNT_REGISTERED_BY_ANOTHER_USER}
*/
public final static String EKL_ACCOUNT_REGISTERED_BY_ANOTHER_USER = "7100";
/**
* ERROR CODE : {@value #EKL_INVALID_ACCOUNT_NUMBER}
*/
public final static String EKL_INVALID_ACCOUNT_NUMBER = "9000";
/**
* ERROR CODE : {@value #EKL_INVALID_ACCOUNT_TYPE}
*/
public final static String EKL_INVALID_ACCOUNT_TYPE = "9200";
/**
* ERROR CODE : {@value #EKL_UNKNOWN_ERROR}
*/
public final static String EKL_UNKNOWN_ERROR = "9999";
/**
* QUERY : get value ELIGIBLE year.<br/>
* <span id="query">SELECT MIN(JPAFCE) FROM HJJPREP WHERE (JPEPNB - JPEQNB) > ? </span>
*/
public static String QUERY_ELIGIBLE_YEAR =
"SELECT MIN(JPAFCE) FROM HJJPREP WHERE (JPEPNB - JPEQNB) > ? ";
/**
* QUERY : get value GREGORIAN year. <br/>
* <span id="query">SELECT JPAGCE, JPAFCE FROM HJJPREP WHERE JPAFCE = ? </span>
*/
public static String QUERY_GREGORIAN_YEAR =
"SELECT JPAGCE, JPAFCE FROM HJJPREP WHERE JPAFCE = ? ";
/**
* <span id="query">SQL - {@value #QUERY_CURRENT_BALANCE}</span><br/>
* @see #getBalanceBigDecimal(String acct)
* @see #getBalanceDouble(String acct)
* @see #getBalanceLong(String acct)
*/
private static final String QUERY_CURRENT_BALANCE =
"SELECT AOAOVA FROM DPAOCPP WHERE AOBFCD = ?";
/**
* key eligible year.
*/
protected static String KEY_ELIGIBLE_YEAR = "ELIGIBLE_YEAR";
/**
* key gregorian year.
*/
protected static String KEY_GREGORIAN_YEAR = "GREGORIAN_YEAR";
/**
* exception.
*/
protected ISMException exception = null;
/**
* output data length.
*/
private int totalOutDataLen = 0;
/*
* (non-Javadoc)
* @see com.ism.projects.th.THBizService#init(byte[])
*/
protected void init(byte[] msg) {
try {
super.init(msg);
parseInput(reqmsg.getMessage());
Field [] flds = getMasterFields(outDS);
int totalOutLen = 0;
for(int i=0; i<flds.length; i++) {
int length = flds[i].getLength();
totalOutLen += length;
}
totalOutDataLen = totalOutLen;
} catch (Exception e) {
logE("init failed.", e );
}
}
/*
* (non-Javadoc)
* @see com.ism.projects.th.THBizService#execute(byte[])
*/
@Override
public byte[] execute(byte[] input) {
if(Common._fissLogLevel >= Constants.LOG_VERBOSE) {
logV(this.getClass().getName() + " start.");
}
init(input);
logS02(reqmsg.getMessage(), System.currentTimeMillis(), null);
byte[] r_val = null;
try {
logN(this.getClass().getName() + " in message [" + reqmsg.getMessage().length + "]["+ new String(reqmsg.getMessage()) + "]");
r_val = executeService(reqmsg.getMessage());
if(r_val != null) {
logN(this.getClass().getName() + " out message [" + r_val.length + "]["+ new String(r_val) + "]");
byte[] result = new byte[4];
System.arraycopy(r_val, 0, result, 0, 4);
if(new String(result).equals(EKL_SUCCESS) ) {
reqmsg.setError(false);
logR03(r_val, System.currentTimeMillis(), null, 0);
reqmsg.setMessage(r_val);
}
else {
reqmsg.setError(false);
Exception e = getException();
ISMException isme = null;
if(e == null) {
isme = new ISMException(ErrorCode.ONL_COMMON_BIZ_ERRORCODE, "UNKNOWN Exception");
}
else if( e instanceof ISMException ) {
isme = new TargetException( ((ISMException) e).getErrorCode(), e.getMessage(), e);
}
else {
isme = new ISMException(ErrorCode.ONL_COMMON_BIZ_ERRORCODE, e.getMessage(), e);
}
logR03(r_val, System.currentTimeMillis(), isme, Integer.parseInt(new String(result)));
byte[] returnMessage = new byte[totalOutDataLen];
for(int i=0; i<returnMessage.length; i++) {
returnMessage[i] = ' ';
}
System.arraycopy(r_val, 0, returnMessage, 0, r_val.length);
if(Common._fissLogLevel >= Constants.LOG_VERBOSE) {
logV("return message[" + totalOutDataLen + "][" + returnMessage.length + "][" + new String(returnMessage) + "]");
}
reqmsg.setMessage(returnMessage);
}
}
} catch (Throwable t) {
r_val = EKL_UNKNOWN_ERROR.getBytes();
logE("execute service failed.", t);
reqmsg.setError(false);
ISMException isme = null;
if( t instanceof ISMException ) {
isme = (ISMException) t;
}
else {
isme = new ISMException(ErrorCode.ONL_COMMON_BIZ_ERRORCODE, t);
}
logR03(r_val, System.currentTimeMillis(), isme, Integer.parseInt(EKL_UNKNOWN_ERROR));
reqmsg.setMessage(EKL_UNKNOWN_ERROR.getBytes());
} finally {
try {
free();
} catch (Exception e) {
logE("db connection free failed.", e);
}
}
if(Common._fissLogLevel >= Constants.LOG_VERBOSE) {
logV(this.getClass().getName() + " end.");
}
byte[] rtn = Utility.getBytes(reqmsg);
return rtn;
}
/**
* EKL Business execute.
* @param input input data
* @return output data
* @throws ISMException
*/
public abstract byte[] executeService(byte[] input) throws ISMException;
/**
* returned exception or <i>null</i>.
* @return the exception or <i>null</i> if the exception is nonexistent or unknown.
*/
public Exception getException() {
return exception;
}
/**
* insert / update / select query make
* @param crudType crud type
* <ul>
* <li>Constants.CRUD_CREATE - insert </li>
* <li>Constants.CRUD_UPDATE - update </li>
* <li>Constants.CRUD_READ - select </li>
* </ul>
* @param tableName table name
* @param outFields ISM output field
* @param input ISM output data
* @return query
* @throws TransformerException crud .
* @throws RuleInterfaceException rule select fail.
*/
protected String makeQuery(int crudType, String tableName, FieldGroup outFields, String[] input) throws TransformerException, RuleInterfaceException {
String sqlResult = null;
FieldGroupMap [] fgm = outFields.getFields();
Field [] flds = new Field[fgm.length];
for ( int x = 0 ; x < fgm.length ; x++ ) {
flds[x] = rmgr.getField(fgm[x].getFieldId());
}
switch (crudType) {
case Constants.CRUD_CREATE:
sqlResult = "INSERT into " + tableName + " (" + appendPreparedColumnName(fgm, flds) + ") values (" + appendPreparedColumnValue(fgm, input) + ")";
break;
case Constants.CRUD_UPDATE:
sqlResult = "UPDATE " + tableName + " set " + appendPreparedColumnSet(fgm, input, flds) + " where " + appendPreparedWhere(outFields.getFields(), input, flds);
break;
case Constants.CRUD_READ:
sqlResult = "SELECT " + appendPreparedColumnName(fgm, flds) + " from " + tableName + " where " + appendPreparedWhere(fgm, input, flds);
break;
default:
logE("EKLService.makeQuery() - cannot accpet crudTypeCd : " + crudType);
String[] params = ExUtil.params(crudType);
throw new TransformerException(ErrorCode.TRNS_CRUD_TYPE_ERROR, ErrorMessage.getMessage(ErrorCode.TRNS_CRUD_TYPE_ERROR, params), params);
}
return sqlResult;
}
/**
* append column names.
* @param fMap ISM Field group map array.
* @param flds ISM Field array.
* @return column name query string. ex) field1, field2, field3
* @throws RuleInterfaceException rule select fail.
*/
private String appendPreparedColumnName(FieldGroupMap[] fMap, Field [] flds) {
StringBuffer ret_val = new StringBuffer();
if (fMap.length > 0) {
int i = 0;
for ( ; i < fMap.length - 1; i++) {
ret_val.append(flds[i].getName()).append(",");
}
ret_val.append(flds[i].getName());
}
return ret_val.toString();
}
/**
* append prepared column value.
* ISM Field group isSQL : Y - value <br/>
* ISM Field group isSQL : N - ?
* @param fMap ISM Field group map array.
* @param input Input data.
* @return column value qurey string. ex) ?, ?, value3
*/
private String appendPreparedColumnValue(FieldGroupMap[] fMap, String[] input) {
StringBuffer ret_val = new StringBuffer("");
String val;
for (int i = 0; i < fMap.length; i++) {
val = "?";
if (fMap[i].isSql()) {
val = input[i];
}
if (i == 0) {
ret_val.append(val);
} else {
ret_val.append(" , ").append(val);
}
}
return ret_val.toString();
}
/**
* append prepared column names and value. ( only ISM field group property isKey 'N' )
* @param fMap ISM Field group map array.
* @param input input data array.
* @param flds ISM Field array.
* @return column name and value string. ex) [field1_name] = ?, [filed2_name] = ? ( only ISM field group property isKey 'N' )
* @throws RuleInterfaceException
*/
private String appendPreparedColumnSet(FieldGroupMap[] fMap, String[] input, Field [] flds) throws RuleInterfaceException {
StringBuffer ret_val = new StringBuffer();
boolean isFirst = true;
for (int i = 0; i < fMap.length; i++) {
if (fMap[i].getKeyType() != Constants.KEY_NOTKEY) {
continue;
} else {
if (!isFirst) {
ret_val.append(", ");
}
isFirst = false;
}
if (fMap[i].isSql()) {
ret_val.append(flds[i].getName()).append(" = ").append(input[i]);
} else {
ret_val.append(flds[i].getName()).append(" = ? ");
}
}
return ret_val.toString();
}
/**
* append prepared column names and valus. ( only ISM field group property isKey 'Y' )
* @param fMap ISM Field group map array.
* @param input input data array.
* @param flds ISM Field array.
* @return column name and value string. ex) [field1_name] = ?, [filed2_name] = ? ( only ISM field group property isKey 'Y' )
* @throws TransformerException
* @throws RuleInterfaceException
*/
private String appendPreparedWhere(FieldGroupMap[] fMap, String[] input, Field [] flds) throws TransformerException, RuleInterfaceException {
StringBuffer ret_val = new StringBuffer();
boolean isFirst = true;
for (int i = 0; i < fMap.length; i++) {
if (fMap[i].getKeyType() != Constants.KEY_NOTKEY) {
if (isFirst) {
if (fMap[i].isSql()) {
ret_val.append(flds[i].getName()).append(" = ").append(input[i]);
} else {
ret_val.append(flds[i].getName()).append(" = ? ");
}
isFirst = false;
} else {
if (fMap[i].isSql()) {
ret_val.append(" and ").append(flds[i].getName()).append(" = ").append(input[i]);
} else {
ret_val.append(" and ").append(flds[i].getName()).append(" = ? ");
}
}
}
}
if (isFirst) {
logE("EKLService.appendPreparedWhere(MessageItem[], DBInfo,boolean) - there is no key field. so Transformer can't write where clause.");
throw new TransformerException(ErrorCode.TRNS_NO_KEY_FIELD, ErrorMessage.getMessage(ErrorCode.TRNS_NO_KEY_FIELD));
}
return ret_val.toString();
}
/**
* Target database insert / update
* ISM Mapping data insert.
* @param inDataIndex ISM target input data structure - field group index
* @param tablename target database table name
* @param crudType insert/update crud type
* <ul>
* <li>Constants.CRUD_CREATE - insert </li>
* <li>Constants.CRUD_UPDATE - update </li>
* </ul>
* @return success - EKL_SUCCESS, fail - EKL_UNKNOWN_ERROR
*/
protected String executeUpdate(int inDataIndex, String tablename, int crudType) {
logN("executeUpdate[" + crudType + "] " + tablename );
String result = EKL_UNKNOWN_ERROR;
FieldGroup fg = inDS.getData()[inDataIndex].getMaster();
String[] values = new String[fg.getFields().length];
for(int i=0; i < values.length; i++) {
values[i] = new String(ai.getData()[inDataIndex][i]).trim();
}
Object[] params = null;
try {
params = makeValue(values, fg.getFields());
} catch (Exception e) {
errorHandle("make value failed. - " + tablename, e);
result = EKL_UNKNOWN_ERROR;
return result;
}
return executeUpdate(inDataIndex, tablename, crudType, params);
}
/**
* Target database insert / update.
* @param inDataIndex ISM target input data structure - field group index
* @param tablename target database table name
* @param crudType insert/update crud type
* <ul>
* <li>Constants.CRUD_CREATE - insert </li>
* <li>Constants.CRUD_UPDATE - update </li>
* </ul>
* @param params insert/update values
* @return
*/
protected String executeUpdate(int inDataIndex, String tablename, int crudType, Object[] params) {
logN("Parameters int inDataIndex = ["+inDataIndex+"] String tablename =["+tablename+"] int crudType = ["+crudType+"]");
logN("executeUpdate with params[" + crudType + "] " + tablename );
String result = EKL_UNKNOWN_ERROR;
FieldGroup fg = inDS.getData()[inDataIndex].getMaster();
String[] values = new String[fg.getFields().length];
for(int i=0; i < values.length; i++) {
values[i] = new String(ai.getData()[inDataIndex][i]).trim();
}
String query = null;
try {
query = makeQuery(crudType, tablename, fg, values);
} catch (Exception e) {
errorHandle("make query failed. - " + tablename, e);
result = EKL_UNKNOWN_ERROR;
return result;
}
PreparedStatement pstmt = null;
try {
logN("query : " + query);
pstmt = target.createPreparedStatement(query);
if(!setParameters(target, pstmt, params)) {
if(exception == null) {
errorHandle("set parameter failed.");
}
throw exception;
}
int count = pstmt.executeUpdate();
if ( count < 1 ) {
logE(query);
errorHandle("insert/update count is less than 1.", exception);
result = EKL_UNKNOWN_ERROR;
}
else {
logN(tablename + " executeUpdate success.");
result = EKLService.EKL_SUCCESS;
}
} catch (Exception e) {
logE("SQL[" + query + "]", e);
if(exception == null) {
errorHandle("failed to communicate with TH core.", e);
}
result = EKL_UNKNOWN_ERROR;
} finally {
close(pstmt);
}
return result;
}
/**
* convert ISM field data type ( object array ) from input data array ( string array ).
* @param in input data array.
* @param fieldMap ISM Field group map.
* @return convert data object array.
* @throws TransformerException transform fail.
*/
protected Object[] makeValue(String[] in, FieldGroupMap[] fieldMap) throws TransformerException {
ArrayList valList = new ArrayList();
if (in != null && in.length > 0) {
for (int i = 0; i < fieldMap.length; i++) {
if (!fieldMap[i].isSql()) {
Field field = null;
try {
field = rmgr.getField(fieldMap[i].getFieldId());
} catch (RuleInterfaceException e) {
logE("rule interface failed.", e);
throw new TransformerException(ErrorCode.RULE_CACHE_ACCESS_FAIL, ErrorMessage.getMessage(ErrorCode.RULE_CACHE_ACCESS_FAIL));
}
logT("convert type for data[" + i + "]");
valList.add(convertType(in[i], field, fieldMap[i]));
}
}
}
return valList.toArray(new Object[0]);
}
/**
* convert input data type.
* @param source input data.
* @param fld ISM Field.
* @param fmap ISM Field group map.
* @return convert data object.
* @throws TransformerException
*/
protected Object convertType(String source, Field fld, FieldGroupMap fmap) throws TransformerException {
if(Common._fissLogLevel >= Constants.LOG_VERBOSE) {
logV("convert type [" + fld.getId() + "][" + fld.getName() + "]");
}
if (source == null || source.length() == 0) {
if(fmap.isNull()) {
return source;
}
}
switch (fld.getType()) {
case Constants.TYPE_DATE:
try {
if(source == null || source.length() == 0) {
return new Date();
}
String dateFormat = fld.getFormat();
if(dateFormat == null || dateFormat.length() == 0) {
throw new TransformerException(ErrorCode.TRNS_CONVERT_DATEFORMAT_ERROR, ErrorMessage.getMessage(ErrorCode.TRNS_CONVERT_DATEFORMAT_ERROR));
}
return new SimpleDateFormat(fld.getFormat()).parse(source);
} catch (ParseException e) {
String[] params = ExUtil.params(fld.getFormat(), source);
throw new TransformerException(ErrorCode.TRNS_CONVERT_DATEFORMAT_ERROR, ErrorMessage.getMessage(ErrorCode.TRNS_CONVERT_DATEFORMAT_ERROR, params), params, e);
}
case Constants.TYPE_NUMBER:
if(source == null || source.length() == 0) {
return new BigDecimal(0);
}
return new BigDecimal(source);
}
return source;
}
/**
* database rollback.
*/
protected void rollback() {
try {
target.rollback();
} catch (Exception e) {
logE("db rollback failed. skip.", e);
}
}
/**
* ResultSet close.
* @param rs ResultSet object.
*/
protected void close(ResultSet rs) {
if(rs != null) {
try {
rs.close();
} catch (Exception e) {
logE("result set close error. skip.");
}
}
}
/**
* Statement close.
* @param stmt Statement object.
*/
protected void close(Statement stmt) {
if(stmt != null) {
try {
stmt.close();
} catch (Exception e) {
logE("result set close error. skip.");
}
}
}
/**
* Statment and ResultSet close.
* @param stmt Statement object.
* @param rs ResultSet object.
*/
protected void close(Statement stmt, ResultSet rs) {
close(stmt);
close(rs);
}
/**
* error logging and make exception.
* @param message error message.
*/
protected void errorHandle(String message) {
exception = new ISMException(ErrorCode.ONL_COMMON_BIZ_ERRORCODE, message);
logE(message, exception);
}
/**
* Error Logging and make exception.
* @param message error message.
* @param t error throwable object.
*/
protected void errorHandle(String message, Throwable t) {
exception = new ISMException(ErrorCode.ONL_COMMON_BIZ_ERRORCODE, message, t);
logE(message, exception);
}
/**
* Prepare statement parameter setting.
*
* @param db target database connection object.
* @param pstmt PreparedStatement.
* @param params setting object array.
* @return true - success , false - fail.
*/
protected boolean setParameters(CommonDatabase db, PreparedStatement pstmt, Object[] params) {
for(int i=0; i<params.length; i++) {
if(params[i] == null) {
if(!db.setParameter(pstmt, i + 1, "")) {
errorHandle("parameter setting false [NULL][" + (i + 1) + "]" , db.getException());
return false;
}
}
else if(params[i] instanceof String) {
if(!db.setParameter(pstmt, i + 1, (String)params[i])) {
errorHandle("parameter setting false [String][" + (i + 1) + "][" + (String)params[i] + "]", db.getException());
return false;
}
}
else if( params[i] instanceof BigDecimal) {
if(!db.setParameter(pstmt, i + 1, (BigDecimal)params[i])) {
errorHandle("parameter setting false [BigDecimal][" + (i + 1) + "][" + (BigDecimal)params[i] + "]", db.getException());
return false;
}
}
else if( params[i] instanceof Double) {
if(!db.setParameter(pstmt, i + 1, (Double)params[i])) {
errorHandle("parameter setting false [Double][" + (i + 1) + "][" + (Double)params[i] + "]", db.getException());
return false;
}
}
else if( params[i] instanceof Long) {
if(!db.setParameter(pstmt, i + 1, (Long)params[i])) {
errorHandle("parameter setting false [Long][" + (i + 1) + "][" + (Long)params[i] + "]", db.getException());
return false;
}
}
else if( params[i] instanceof Integer) {
if(!db.setParameter(pstmt, i + 1, (Integer)params[i])) {
errorHandle("parameter setting false [Integer][" + (i + 1) + "][" + (Integer)params[i] + "]", db.getException());
return false;
}
}
else if( params[i] instanceof Date) {
if(!db.setParameter(pstmt, i + 1, (Date)params[i])) {
errorHandle("parameter setting false [Integer][" + (i + 1) + "][" + (Integer)params[i] + "]", db.getException());
return false;
}
}
else if( params[i] instanceof Timestamp) {
if(!db.setParameter(pstmt, i + 1, (Timestamp)params[i])) {
errorHandle("parameter setting false [Timestamp][" + (i + 1) + "][" + (Timestamp)params[i] + "]", db.getException());
return false;
}
}
else {
if(!db.setParameter(pstmt, i + 1, params[i].toString())) {
errorHandle("parameter setting false [" + params[i].getClass().getName() + "][" + (i + 1) + "][" + params[i].toString() + "]", db.getException());
return false;
}
}
}
return true;
}
/**
* get ELIGIBLE year.
* <li><span id="query">SELECT MIN(JPAFCE) FROM HJJPREP WHERE (JPEPNB - JPEQNB) > [input count] </span></li>
*
* @param count input count.
* @return ELIGIBLE year.
* @throws SQLException query failed.
* @throws ISMException parameter setting fail or result count is 0.
*/
protected int getEligibleYear(int count) throws SQLException, ISMException {
String method = "getEligibleYear";
String query = QUERY_ELIGIBLE_YEAR;
PreparedStatement pstmt = null;
ResultSet rs = null;
int year = 0;
try {
if(Common._fissLogLevel >= Constants.LOG_VERBOSE) {
logV(method + " : query - " + query + "[" + count + "]");
}
pstmt = target.createPreparedStatement(query);
Object[] params = {
count,
};
if(!setParameters(target, pstmt, params)) {
if(exception == null) {
errorHandle(method + " : parameter setting failed.", target.getException());
}
throw exception;
}
rs = pstmt.executeQuery();
if(rs.next()) {
year = rs.getInt(1);
}
else {
errorHandle(method + " : select count 0.[" + query + "][" + count + "]");
throw exception;
}
} catch (SQLException e) {
logE(method + " : SQL[" + query + "]", e);
if(exception == null) {
errorHandle(method + " : failed to communicate with TH core [" + count + "]", e);
}
throw e;
} finally {
close(pstmt, rs);
}
return year;
}
/**
* GREGORIAN year.
* <li><span id="query">SELECT JPAGCE, JPAFCE FROM HJJPREP WHERE JPAFCE = [year] </span></li>
* @param year ELIGIBLE year
* @return GREGORIAN year
* @throws SQLException query failed.
* @throws ISMException parameter setting fail or result count is 0.
*/
protected int getGregorianYear(int year) throws SQLException, ISMException {
String method = "getGregorianYear";
String query = QUERY_GREGORIAN_YEAR;
PreparedStatement pstmt = null;
ResultSet rs = null;
int gyear = 0;
try {
if(Common._fissLogLevel >= Constants.LOG_VERBOSE) {
logV(method + " : query - " + query + "[" + year + "]");
}
pstmt = target.createPreparedStatement(query);
Object[] params = {
"" + year,
};
if(!setParameters(target, pstmt, params)) {
if(exception == null) {
errorHandle(method + " parameter setting failed. year[" + year + "]", target.getException());
}
throw exception;
}
rs = pstmt.executeQuery();
if(rs.next()) {
gyear = rs.getInt(1);
}
else {
errorHandle(method + " select count is 0. year[" + year + "]");
throw exception;
}
} catch (SQLException e) {
logE(method + " : SQL[" + query + "]", e);
if(exception == null) {
errorHandle(method + " failed to communicate with TH core [" + e.getMessage() + "]", e);
}
throw e;
} finally {
close(pstmt, rs);
}
return gyear;
}
/**
* get balance value.
*
* return Double value.
* @param acct account number
* @return balance.
*/
protected Double getBalanceDouble(String acct) {
Double amount = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = target.createPreparedStatement(QUERY_CURRENT_BALANCE);
pstmt.setString(1, acct);
rs = pstmt.executeQuery();
if(rs.next()) {
amount = rs.getDouble(1);
}
} catch (SQLException e) {
logE("failed to communicate with TH core [" + e.getMessage() + "]", e);
} finally {
close(pstmt, rs);
}
logV("balance[" + acct + "][" + amount + "]");
return amount;
}
/**
* get balance value.
*
* return BigDecimal value.
* @param acct account number
* @return balance.
*/
protected BigDecimal getBalanceBigDecimal(String acct) {
BigDecimal amount = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = target.createPreparedStatement(QUERY_CURRENT_BALANCE);
pstmt.setString(1, acct);
rs = pstmt.executeQuery();
if(rs.next()) {
amount = rs.getBigDecimal(1);
}
} catch (SQLException e) {
logE("failed to communicate with TH core[" + e.getMessage() + "]", e);
} finally {
close(pstmt, rs);
}
logV("balance[" + acct + "][" + amount.toPlainString() + "]");
return amount;
}
/**
* get balance value.
*
* return Long value.
* @param acct account number
* @return balance.
*/
protected Long getBalanceLong(String acct) {
Long amount = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = target.createPreparedStatement(QUERY_CURRENT_BALANCE);
pstmt.setString(1, acct);
rs = pstmt.executeQuery();
if(rs.next()) {
amount = rs.getLong(1);
}
} catch (SQLException e) {
logE("failed to communicate with TH core [" + e.getMessage() + "]", e);
} finally {
close(pstmt, rs);
}
return amount;
}
}
|
package vistas;
import objetos.proyectiles.Torpedo;
import ar.uba.fi.algo3.titiritero.ControladorJuego;
/*
* Vista para los torpedos simples
*/
public class VistaTorpedo extends VistaProyectiles {
public VistaTorpedo(Torpedo torpedo, ControladorJuego controlador) {
super(torpedo, controlador);
this.setearImagen();
}
@Override
public void setearImagen() {
if (this.getObjeto().getVelocidad().getComponenteY() > 0) {
this
.setNombreArchivoImagen("../images/proyectiles/torpedoAbajo.png");
} else {
this
.setNombreArchivoImagen("../images/proyectiles/torpedoArriba.png");
}
}
}
|
/**
*
*/
package myProject.second;
public class grassTileLevel1 extends TileLevel1{
public grassTileLevel1( int id) {
super(loadImageLevel1.grass, id);
}
}
|
package com.lingtorp.characters.personalities;
import java.util.HashMap;
/**
* Created by AlexanderLingtorp on 03/12/14.
*/
public class AggressivePersonalityType implements PersonalityType {
private HashMap<String, String> dialogSet;
// Setup the approaches and replies.
public AggressivePersonalityType()
{
dialogSet = new HashMap<String, String>();
dialogSet.put("hello", "Hello, now go away.");
dialogSet.put("bye", "Fuck off ...");
dialogSet.put("why are you here", "Because I fucking like it here. Retard..");
}
@Override
public HashMap<String, String> getDialogSet() {
return dialogSet;
}
}
|
package com.training.utils;
import javax.xml.ws.Endpoint;
import com.training.services.DonationRequestService;
public class MyPublisher {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Endpoint.publish("http://localhost:5000/converter", new CurrencyConverterImpl());
Endpoint.publish("http://localhost:8080/donor", new DonationRequestService());
System.out.println("Service Running");
}
}
|
/**
*
*/
package com.zhouqi.service;
import com.zhouqi.entity.CfgTaskDetail;
import java.util.List;
/**
*
* <p>Title: TaskDetailService.java</p>
* <p>Description:</p>
* <p>Company:康成投资(中国)有线公司</p>
*
* @author zhouqi
* @date 2018年3月9日 上午11:49:39
*
*/
public interface TaskDetailService {
List<CfgTaskDetail> selectByGroupName(String groupName);
}
|
package com.klaytn.caver.common;
import com.klaytn.caver.Caver;
import com.klaytn.caver.contract.SendOptions;
import com.klaytn.caver.kct.kip7.KIP7;
import com.klaytn.caver.kct.kip7.KIP7DeployParams;
import com.klaytn.caver.methods.response.TransactionReceipt;
import com.klaytn.caver.utils.Utils;
import com.klaytn.caver.wallet.keyring.KeyringFactory;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.web3j.protocol.exceptions.TransactionException;
import org.web3j.utils.Numeric;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import static com.klaytn.caver.base.Accounts.*;
import static org.junit.Assert.*;
public class KIP7Test {
public static KIP7 kip7contract;
public static final String CONTRACT_NAME = "Kale";
public static final String CONTRACT_SYMBOL = "KALE";
public static final int CONTRACT_DECIMALS = 18;
public static final BigInteger CONTRACT_INITIAL_SUPPLY = BigInteger.valueOf(100_000).multiply(BigInteger.TEN.pow(CONTRACT_DECIMALS)); // 100000 * 10^18
public static void deployContract() throws IOException, NoSuchMethodException, TransactionException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
Caver caver = new Caver(Caver.DEFAULT_URL);
caver.wallet.add(KeyringFactory.createFromPrivateKey("0x2359d1ae7317c01532a58b01452476b796a3ac713336e97d8d3c9651cc0aecc3"));
caver.wallet.add(KeyringFactory.createFromPrivateKey("0x734aa75ef35fd4420eea2965900e90040b8b9f9f7484219b1a06d06394330f4e"));
KIP7DeployParams kip7DeployParam = new KIP7DeployParams(CONTRACT_NAME, CONTRACT_SYMBOL, CONTRACT_DECIMALS, CONTRACT_INITIAL_SUPPLY);
SendOptions sendOptions = new SendOptions(LUMAN.getAddress(), BigInteger.valueOf(45000));
kip7contract = KIP7.deploy(caver, kip7DeployParam, LUMAN.getAddress());
}
public static class ConstructorTest {
@BeforeClass
public static void init() throws NoSuchMethodException, IOException, InstantiationException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, TransactionException {
KIP7Test.deployContract();
}
@Test
public void name(){
try {
String name = kip7contract.name();
assertEquals(CONTRACT_NAME, name);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void symbol(){
try {
String symbol = kip7contract.symbol();
assertEquals(CONTRACT_SYMBOL, symbol);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void decimals(){
try {
int decimals = kip7contract.decimals();
assertEquals(CONTRACT_DECIMALS, decimals);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void totalSupply(){
try {
BigInteger totalSupply = kip7contract.totalSupply();
assertEquals(CONTRACT_INITIAL_SUPPLY, totalSupply);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
public static class PausableTest {
@BeforeClass
public static void init() throws NoSuchMethodException, IOException, InstantiationException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, TransactionException {
KIP7Test.deployContract();
}
@Before
public void setUnpause() {
try {
kip7contract.setDefaultSendOptions(new SendOptions());
if(kip7contract.paused()) {
SendOptions options = new SendOptions(LUMAN.getAddress(), BigInteger.valueOf(4000000));
TransactionReceipt.TransactionReceiptData receiptData = kip7contract.unpause(options);
}
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void pause() {
try {
SendOptions options = new SendOptions(LUMAN.getAddress(), BigInteger.valueOf(4000000));
kip7contract.pause(options);
assertTrue(kip7contract.paused());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void pausedDefaultOptions() {
try{
SendOptions options = new SendOptions(LUMAN.getAddress(), BigInteger.valueOf(4000000));
kip7contract.setDefaultSendOptions(options);
kip7contract.pause();
assertTrue(kip7contract.paused());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void pausedNoDefaultGas() {
try {
kip7contract.getDefaultSendOptions().setFrom(LUMAN.getAddress());
kip7contract.pause();
assertTrue(kip7contract.paused());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void pausedNoGas() {
try {
SendOptions sendOptions = new SendOptions(LUMAN.getAddress(), (String)null);
kip7contract.pause(sendOptions);
assertTrue(kip7contract.paused());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void unPause() {
try {
SendOptions options = new SendOptions(LUMAN.getAddress(), BigInteger.valueOf(4000000));
kip7contract.pause(options);
assertTrue(kip7contract.paused());
kip7contract.unpause(options);
assertFalse(kip7contract.paused());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void addPauser() {
try {
SendOptions options = new SendOptions(LUMAN.getAddress(), BigInteger.valueOf(4000000));
kip7contract.addPauser(BRANDON.getAddress(), options);
assertTrue(kip7contract.isPauser(BRANDON.getAddress()));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void renouncePauser() {
try {
if(!kip7contract.isPauser(BRANDON.getAddress())) {
SendOptions options = new SendOptions(LUMAN.getAddress(), BigInteger.valueOf(4000000));
kip7contract.addPauser(BRANDON.getAddress(), options);
}
SendOptions options = new SendOptions(BRANDON.getAddress(), BigInteger.valueOf(4000000));
kip7contract.renouncePauser(options);
assertFalse(kip7contract.isPauser(BRANDON.getAddress()));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void paused() {
try {
assertFalse(kip7contract.paused());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
public static class BurnableTest {
@BeforeClass
public static void init() throws NoSuchMethodException, IOException, InstantiationException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, TransactionException {
KIP7Test.deployContract();
}
@Test
public void burn() {
try {
BigInteger totalSupply = kip7contract.totalSupply();
SendOptions sendOptions = new SendOptions(LUMAN.getAddress(), (String)null);
String burnAmount = Utils.convertToPeb("100", "KLAY");
kip7contract.burn(new BigInteger(burnAmount), sendOptions);
BigInteger afterSupply = kip7contract.totalSupply();
assertEquals(afterSupply, totalSupply.subtract(new BigInteger(burnAmount)));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void burnFrom() {
try {
BigInteger beforeBalance = kip7contract.balanceOf(LUMAN.getAddress());
SendOptions sendOptions = new SendOptions(LUMAN.getAddress(), (String)null);
String burnAmount = Utils.convertToPeb("100", "KLAY");
kip7contract.approve(BRANDON.getAddress(), Numeric.toBigInt(burnAmount), sendOptions);
kip7contract.burnFrom(LUMAN.getAddress(), new BigInteger(burnAmount), new SendOptions(BRANDON.getAddress(), (String)null));
BigInteger afterBalance = kip7contract.balanceOf(LUMAN.getAddress());
assertEquals(afterBalance, beforeBalance.subtract(new BigInteger(burnAmount)));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
public static class MintableTest {
@BeforeClass
public static void init() throws NoSuchMethodException, IOException, InstantiationException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, TransactionException {
KIP7Test.deployContract();
}
@Test
public void mint() {
try {
BigInteger beforeTotalSupply = kip7contract.totalSupply();
SendOptions sendOptions = new SendOptions(LUMAN.getAddress(), (String)null);
String mintAmount = Utils.convertToPeb("100", "KLAY");
kip7contract.mint(LUMAN.getAddress(), new BigInteger(mintAmount), sendOptions);
BigInteger afterTotalSupply = kip7contract.totalSupply();
assertEquals(afterTotalSupply, beforeTotalSupply.add(new BigInteger(mintAmount)));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void isMinter() {
try {
assertTrue(kip7contract.isMinter(LUMAN.getAddress()));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void addMinter() {
try {
if(kip7contract.isMinter(BRANDON.getAddress())) {
SendOptions sendOptions = new SendOptions(BRANDON.getAddress(), (String)null);
kip7contract.renounceMinter(sendOptions);
}
SendOptions sendOptions = new SendOptions(LUMAN.getAddress(), (String)null);
kip7contract.addMinter(BRANDON.getAddress(), sendOptions);
assertTrue(kip7contract.isMinter(BRANDON.getAddress()));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void renounceMinter() {
try {
if(!kip7contract.isMinter(BRANDON.getAddress())) {
SendOptions sendOptions = new SendOptions(LUMAN.getAddress(), (String)null);
kip7contract.addMinter(BRANDON.getAddress(), sendOptions);
}
SendOptions sendOptions = new SendOptions(BRANDON.getAddress(), (String)null);
kip7contract.renounceMinter(sendOptions);
assertFalse(kip7contract.isMinter(BRANDON.getAddress()));
} catch (Exception e) {
}
}
}
public static class CommonTest {
@BeforeClass
public static void init() throws NoSuchMethodException, IOException, InstantiationException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, TransactionException {
KIP7Test.deployContract();
}
@Test
public void balanceOf() {
try {
assertNotNull(kip7contract.balanceOf(LUMAN.getAddress()));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void allowance() {
try {
BigInteger allowance = kip7contract.allowance(LUMAN.getAddress(), WAYNE.getAddress());
assertEquals(allowance, BigInteger.ZERO);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void approve() {
try {
BigInteger allowance = kip7contract.allowance(LUMAN.getAddress(), BRANDON.getAddress());
SendOptions sendOptions = new SendOptions(LUMAN.getAddress(), (String)null);
BigInteger approveAmount = BigInteger.TEN.multiply(BigInteger.TEN.pow(CONTRACT_DECIMALS)); // 10 * 10^18
kip7contract.approve(BRANDON.getAddress(), approveAmount, sendOptions);
BigInteger afterAllowance = kip7contract.allowance(LUMAN.getAddress(), BRANDON.getAddress());
assertEquals(afterAllowance, allowance.add(approveAmount));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void transfer() {
try {
BigInteger beforeBalance = kip7contract.balanceOf(BRANDON.getAddress());
SendOptions sendOptions = new SendOptions(LUMAN.getAddress(), (String)null);
BigInteger transferAmount = BigInteger.TEN.multiply(BigInteger.TEN.pow(CONTRACT_DECIMALS)); // 10 * 10^18
kip7contract.transfer(BRANDON.getAddress(), transferAmount, sendOptions);
BigInteger afterBalance = kip7contract.balanceOf(BRANDON.getAddress());
assertEquals(afterBalance, beforeBalance.add(transferAmount));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void transferFrom() {
SendOptions ownerOptions = new SendOptions(LUMAN.getAddress(), (String)null);
SendOptions allowanceOptions = new SendOptions(BRANDON.getAddress(), (String)null);
BigInteger allowAmount = BigInteger.TEN.multiply(BigInteger.TEN.pow(CONTRACT_DECIMALS)); // 10 * 10^18
try{
//reset
kip7contract.approve(BRANDON.getAddress(), BigInteger.ZERO, ownerOptions);
//Test
kip7contract.approve(BRANDON.getAddress(), allowAmount, ownerOptions);
BigInteger preBalance = kip7contract.balanceOf(WAYNE.getAddress());
kip7contract.transferFrom(LUMAN.getAddress(), WAYNE.getAddress(), allowAmount, allowanceOptions);
BigInteger afterBalance = kip7contract.balanceOf(WAYNE.getAddress());
assertEquals(afterBalance, preBalance.add(allowAmount));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void safeTransfer() {
SendOptions ownerOptions = new SendOptions(LUMAN.getAddress(), (String)null);
BigInteger amount = BigInteger.TEN.multiply(BigInteger.TEN.pow(CONTRACT_DECIMALS));
try {
BigInteger beforeBalance = kip7contract.balanceOf(BRANDON.getAddress());
SendOptions sendOptions = new SendOptions(LUMAN.getAddress(), (String)null);
BigInteger transferAmount = BigInteger.TEN.multiply(BigInteger.TEN.pow(CONTRACT_DECIMALS)); // 10 * 10^18
kip7contract.safeTransfer(BRANDON.getAddress(), transferAmount, sendOptions);
BigInteger afterBalance = kip7contract.balanceOf(BRANDON.getAddress());
assertEquals(afterBalance, beforeBalance.add(transferAmount));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void safeTransferWithData() {
SendOptions ownerOptions = new SendOptions(LUMAN.getAddress(), (String)null);
BigInteger amount = BigInteger.TEN.multiply(BigInteger.TEN.pow(CONTRACT_DECIMALS));
String data = "buffered data";
try {
BigInteger beforeBalance = kip7contract.balanceOf(BRANDON.getAddress());
SendOptions sendOptions = new SendOptions(LUMAN.getAddress(), (String)null);
BigInteger transferAmount = BigInteger.TEN.multiply(BigInteger.TEN.pow(CONTRACT_DECIMALS)); // 10 * 10^18
kip7contract.safeTransfer(BRANDON.getAddress(), transferAmount, data, sendOptions);
BigInteger afterBalance = kip7contract.balanceOf(BRANDON.getAddress());
assertEquals(afterBalance, beforeBalance.add(transferAmount));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void safeTransferFrom() {
SendOptions ownerOptions = new SendOptions(LUMAN.getAddress(), (String)null);
SendOptions allowanceOptions = new SendOptions(BRANDON.getAddress(), (String)null);
BigInteger allowAmount = BigInteger.TEN.multiply(BigInteger.TEN.pow(CONTRACT_DECIMALS)); // 10 * 10^18
try{
//reset
kip7contract.approve(BRANDON.getAddress(), BigInteger.ZERO, ownerOptions);
//Test
kip7contract.approve(BRANDON.getAddress(), allowAmount, ownerOptions);
BigInteger preBalance = kip7contract.balanceOf(WAYNE.getAddress());
kip7contract.safeTransferFrom(LUMAN.getAddress(), WAYNE.getAddress(), allowAmount, allowanceOptions);
BigInteger afterBalance = kip7contract.balanceOf(WAYNE.getAddress());
assertEquals(afterBalance, preBalance.add(allowAmount));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void safeTransferFromWithData() {
SendOptions ownerOptions = new SendOptions(LUMAN.getAddress(), (String)null);
SendOptions allowanceOptions = new SendOptions(BRANDON.getAddress(), (String)null);
BigInteger allowAmount = BigInteger.TEN.multiply(BigInteger.TEN.pow(CONTRACT_DECIMALS)); // 10 * 10^18
String data = "buffered data";
try{
//reset
kip7contract.approve(BRANDON.getAddress(), BigInteger.ZERO, ownerOptions);
//Test
kip7contract.approve(BRANDON.getAddress(), allowAmount, ownerOptions);
BigInteger preBalance = kip7contract.balanceOf(WAYNE.getAddress());
kip7contract.safeTransferFrom(LUMAN.getAddress(), WAYNE.getAddress(), allowAmount, data, allowanceOptions);
BigInteger afterBalance = kip7contract.balanceOf(WAYNE.getAddress());
assertEquals(afterBalance, preBalance.add(allowAmount));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void supportsInterface() {
final String INTERFACE_ID_KIP13 = "0x01ffc9a7";
final String INTERFACE_ID_KIP7_PAUSABLE = "0x4d5507ff";
final String INTERFACE_ID_KIP7_BURNABLE = "0x3b5a0bf8";
final String INTERFACE_ID_KIP7_MINTABLE = "0xeab83e20";
final String INTERFACE_ID_KIP7_METADATA = "0xa219a025";
final String INTERFACE_ID_KIP7 = "0x65787371";
final String INTERFACE_ID_FALSE = "0xFFFFFFFF";
try {
boolean isSupported_KIP13 = kip7contract.supportInterface(INTERFACE_ID_KIP13);
assertTrue(isSupported_KIP13);
boolean isSupported_KIP7_PAUSABLE = kip7contract.supportInterface(INTERFACE_ID_KIP7_PAUSABLE);
assertTrue(isSupported_KIP7_PAUSABLE);
boolean isSupported_KIP7_BURNABLE = kip7contract.supportInterface(INTERFACE_ID_KIP7_BURNABLE);
assertTrue(isSupported_KIP7_BURNABLE);
boolean isSupported_KIP7_MINTABLE = kip7contract.supportInterface(INTERFACE_ID_KIP7_MINTABLE);
assertTrue(isSupported_KIP7_MINTABLE);
boolean isSupported_KIP7_METADATA = kip7contract.supportInterface(INTERFACE_ID_KIP7_METADATA);
assertTrue(isSupported_KIP7_METADATA);
boolean isSupported_KIP7 = kip7contract.supportInterface(INTERFACE_ID_KIP7);
assertTrue(isSupported_KIP7);
boolean isSupported_FALSE = kip7contract.supportInterface(INTERFACE_ID_FALSE);
assertFalse(isSupported_FALSE);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
}
|
package co.sblock.effects.effect.godtier.active;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import co.sblock.Sblock;
import co.sblock.effects.effect.BehaviorActive;
import co.sblock.effects.effect.BehaviorGodtier;
import co.sblock.effects.effect.Effect;
import co.sblock.users.UserAspect;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.Event;
import org.bukkit.event.entity.EntityDeathEvent;
import net.md_5.bungee.api.ChatColor;
/**
* Gives bonus experience for entity kills.
*
* @author Jikoo
*/
public class EffectBonusExperience extends Effect implements BehaviorActive, BehaviorGodtier {
public EffectBonusExperience(Sblock plugin) {
super(plugin, 250, 5, 5, "Veteran");
}
@Override
public Collection<UserAspect> getAspects() {
return Arrays.asList(UserAspect.MIND);
}
@Override
public List<String> getDescription(UserAspect aspect) {
ArrayList<String> list = new ArrayList<>();
if (aspect == UserAspect.MIND) {
list.add(aspect.getColor() + "Deep Thinker");
}
list.add(ChatColor.WHITE + "Learn faster.");
list.add(ChatColor.GRAY + "Gain bonus experience from mob kills.");
return list;
}
@Override
public Collection<Class<? extends Event>> getApplicableEvents() {
return Arrays.asList(EntityDeathEvent.class);
}
@Override
public void handleEvent(Event event, LivingEntity entity, int level) {
EntityDeathEvent death = (EntityDeathEvent) event;
if (death.getEntity().getType() == EntityType.PLAYER
|| death.getEntity().getType() == EntityType.ENDER_DRAGON) {
// Players drop all exp, don't multiply
// Ender dragon drops 12000 exp, we do not need to make that number larger
return;
}
death.setDroppedExp((int) (death.getDroppedExp() * (level * .25 + 1)));
}
}
|
package com.zhanwei.java.test1;
public class Clazz {
public static void main(String[] args) throws Exception {
Class<Cat> c = Cat.class;
Class<Dog> g = (Class<Dog>) Class.forName("com.zhanwei.java.test1.Dog");
}
}
class Cat {
static{
System.out.println("cat is load");
}
}
class Dog{
static {
System.out.println("dog is load");
}
}
|
package basicpractice;
public class Seven26{
public static void main(String[] args) {
}
static boolean addMatrix(int [][]x,int[][]y,int[][]z){
if(x.length != y.length ||y.length!=z.length)
{
return false;
}
for(int i=0;i<x.length;i++){
if(x[i].length !=y[i].length || y[i].length!=z[i].length){
return false;
}
}
for(int i=0;i<x.length;i++){
for(int j=0;j<x[i].length;j++){
z[i][j]=x[i][j]+y[i][j];
}
}
return true;
}
}
|
package com.Test.Testclass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.BaseClass.BaseClass1;
import walmartHomepage.Homepage;
public class TestHompage extends BaseClass1 {
Homepage home;
@BeforeClass
public void before() {
home = new Homepage(driver);
}
@Test
public void TestNavlinks() {
Assert.assertEquals(5, home.findHomePagelinks());
}
/*
* @Test public void TestSignINClick(){ Homepage home=new Homepage(driver);
* home.checksignINlink();
*
* Assert.
* assertEquals("Walmart.com: Free 2-Day Shipping on Millions of Items",
* driver.getTitle() );
*
* }
*/
}
|
package com.uu.searchengine.entity;
import javax.persistence.*;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@Entity(name = "Image")
@Table(name = "image")
public class Image {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
long id;
@Column(columnDefinition="VARCHAR(2083)")
String src;
@ManyToMany(fetch = FetchType.LAZY , mappedBy = "images", cascade = {CascadeType.ALL})
Set<Document> documents = new HashSet<>();
public Image() {
}
public Image(String src) {
this.src = src;
}
public Image(long id, String src) {
this.id = id;
this.src = src;
}
public Image(String src , Set<Document> documents) {
this.src = src;
this.documents = documents;
}
public void addDocument(Document document)
{
documents.add(document);
}
public void removeDocument(Document document) {
documents.remove(document);
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public Set<Document> getDocuments() {
return documents;
}
public void setDocuments(Set<Document> documents) {
this.documents = documents;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
|
package com.lxm.smartbutler.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
/**
* Created by lxm on 17/2/15.
*/
public class PicassoUtils {
public static void loadImageView(Context mContext, String url, ImageView imageView){
Picasso.with(mContext)
.load(url)
.into(imageView);
}
public static void loadImageViewSize(Context mContext, String url, int width,int height,ImageView imageView) {
Picasso.with(mContext)
.load(url)
.resize(width, height)
.centerCrop()
.into(imageView);
}
public static void loadImageViewHolder(Context mContext, String url,int holder,int error, ImageView imageView){
Picasso.with(mContext)
.load(url)
.placeholder(holder)
.error(error)
.into(imageView);
}
public static void loadImageViewCrop(Context mContext, String url, ImageView imageView){
Picasso.with(mContext)
.load(url)
.transform(new CropSquareTransformation())
.into(imageView);
}
public static class CropSquareTransformation implements Transformation {
@Override public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap result = Bitmap.createBitmap(source, x, y, size, size);
if (result != source) {
source.recycle();
}
return result;
}
@Override public String key() { return "square()"; }
}
}
|
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.mvc.method.annotation;
import java.util.List;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.annotation.InitBinderDataBinderFactory;
import org.springframework.web.method.support.InvocableHandlerMethod;
/**
* Creates a {@code ServletRequestDataBinder}.
*
* @author Rossen Stoyanchev
* @since 3.1
*/
public class ServletRequestDataBinderFactory extends InitBinderDataBinderFactory {
/**
* Create a new instance.
* @param binderMethods one or more {@code @InitBinder} methods
* @param initializer provides global data binder initialization
*/
public ServletRequestDataBinderFactory(@Nullable List<InvocableHandlerMethod> binderMethods,
@Nullable WebBindingInitializer initializer) {
super(binderMethods, initializer);
}
/**
* Returns an instance of {@link ExtendedServletRequestDataBinder}.
*/
@Override
protected ServletRequestDataBinder createBinderInstance(
@Nullable Object target, String objectName, NativeWebRequest request) throws Exception {
return new ExtendedServletRequestDataBinder(target, objectName);
}
}
|
package in.prashant.springsecurity.entities;
import lombok.Data;
import javax.persistence.*;
import java.util.Set;
@Entity
@Data
@Table(name = "user_table")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;
private String password;
@ManyToMany
@JoinTable(name = "user_role",joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
|
package com.wxt.designpattern.iterator.test01;
/**
* @Author: weixiaotao
* @ClassName ConcreteAggregate
* @Date: 2018/12/3 19:24
* @Description: 具体的聚合对象,实现创建相应迭代器对象的功能
*/
public class ConcreteAggregate extends Aggregate {
/**
* 示意,表示聚合对象具体的内容
*/
private String[] ss = null;
/**
* 构造方法,传入聚合对象具体的内容
* @param ss 聚合对象具体的内容
*/
public ConcreteAggregate(String[] ss){
this.ss = ss;
}
public Iterator createIterator() {
//实现创建Iterator的工厂方法
return new ConcreteIterator(this);
}
/**
* 获取索引所对应的元素
* @param index 索引
* @return 索引所对应的元素
*/
public Object get(int index){
Object retObj = null;
if(index < ss.length){
retObj = ss[index];
}
return retObj;
}
/**
* 获取聚合对象的大小
* @return 聚合对象的大小
*/
public int size(){
return this.ss.length;
}
}
|
package com.school.sms.controller;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.school.sms.constants.Constants;
import com.school.sms.model.FixedFeeBatchYearMonth;
import com.school.sms.model.Student;
import com.school.sms.model.VariableFeeBatchYearMonth;
import com.school.sms.service.FeeManagementService;
@Controller
public class AdminController {
@RequestMapping(value = "admin/databackupNrestore")
public ModelAndView dataBackAndRestore(
@RequestParam(value = "backup", required = false) String backup,
@RequestParam(value = "restore", required = false) String restore,/*ServletContext sc,*/HttpServletRequest request ) {
ModelAndView model = new ModelAndView();
/*
* model.addObject("title", "Spring Security Custom Login Form");
* model.addObject("message", "This is protected page!");
*/
if(null!= backup && (null==request.getParameter("file") || request.getParameter("file").isEmpty())){
model.addObject("fileSelectionError", "error");
}
else if (backup != null && null!=request.getParameter("file") && !request.getParameter("file").isEmpty()) {
Process p = null;
try {
Runtime runtime = Runtime.getRuntime();
String path="";
if("windows".equals(System.getProperty("os.name"))){
path ="C:\\" +request.getParameter("file");
}
else{
path ="/tmp/"+request.getParameter("file");
}
p = runtime
.exec(new String[]{"/bin/sh" ,"-c", "mysqldump -u root -proot --databases school_admission-system > " + path});
// change the dbpass and dbname with your dbpass and dbname
int processComplete = p.waitFor();
if (processComplete == 0) {
model.addObject("backup_status", "Success,BackUp Location: " +path);
System.out.println("Backup created successfully!");
} else {
model.addObject("backup_status", "Fail");
}
} catch (Exception e) {
e.printStackTrace();
}
}
model.setViewName("database");
return model;
}
}
|
package tm.controller;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import tm.dao.HotelDao;
import tm.dao.InfoDao;
import tm.dao.TouristDao;
import tm.pojo.Hotel;
import tm.pojo.Info;
import tm.pojo.Tourist;
import tm.service.HotelService;
import tm.service.InfoService;
import tm.service.TouristService;
import tm.service.UserService;
import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.List;
@Controller
@RequestMapping("hotel/checkIn")
public class CheckInController {
private Info info;
private SqlSession sqlSession;
private HotelDao hotelDao;
private TouristDao touristDao;
private InfoDao infoDao;
private List<Hotel> hotelList;
private List<Tourist> touristList;
private HotelService hotelService;
private InfoService infoService;
private TouristService touristService;
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@Autowired
public void setTouristService(TouristService touristService) {
this.touristService = touristService;
}
@Autowired
public void setHotelService(HotelService hotelService) {
this.hotelService = hotelService;
}
@Autowired
public void setInfoService(InfoService infoService) {
this.infoService = infoService;
}
@Autowired
public void setHotelList(List<Hotel> hotelList) {
this.hotelList = hotelList;
}
@Autowired
public void setTouristList(List<Tourist> touristList) {
this.touristList = touristList;
}
@Autowired
public void setInfo(Info info) {
this.info = info;
}
@RequestMapping(method = RequestMethod.GET)
public String checkIn(Model model) {
model.addAttribute(info);
return "checkIn";
}
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submit(Info info, HttpSession session) {
SecurityContextImpl securityContextImpl = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");
String userName = securityContextImpl.getAuthentication().getName();
info.setCheckIn(Calendar.getInstance().getTime());
int userId = userService.findByName(userName).getId();
info.setHotelId(hotelService.findByUserId(userId).getId());
touristService.add(info.getTourist());
info.setTouristId(info.getTourist().getId());
infoService.add(info);
return "redirect:/hotel/checkQuery";
}
}
|
package org.andrill.conop.core.constraints;
import org.andrill.conop.core.AbstractConfigurable;
import org.andrill.conop.core.Solution;
/**
* Performs no constraint checking.
*
* @author Josh Reed (jareed@andrill.org)
*/
public class NullConstraints extends AbstractConfigurable implements Constraints {
@Override
public boolean isValid(final Solution solution) {
return true;
}
@Override
public String toString() {
return "Null Constraints";
}
}
|
package egovframework.adm.lcms.cts.service;
import java.util.Map;
public interface LcmsContentManageService {
public String selectContentPath( Map<String, Object> commandMap) throws Exception;
}
|
package com.springtraining.web;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.springtraining.common.CommonClass;
import com.springtraining.common.Const.DispMode;
import com.springtraining.form.UserCreateForm;
import com.springtraining.model.MSection;
import com.springtraining.model.MUser;
import com.springtraining.service.KbnchService;
import com.springtraining.service.SectionService;
import com.springtraining.service.UserService;
import com.springtraining.vallidation.GroupOrder;
import com.springtraining.vallidation.UserCreateValidator;
@Controller
@RequestMapping(value = "/create")
public class UserCreateController {
@Autowired
private UserService userService;
@Autowired
private KbnchService kbnchService;
@Autowired
private SectionService sectionService;
@Autowired
private UserCreateValidator validator;
@InitBinder
public void validatorBinder(WebDataBinder binder) {
binder.addValidators(validator);
}
@ModelAttribute("userCreateForm")
public UserCreateForm initForm() {
UserCreateForm form = new UserCreateForm();
return form;
}
@RequestMapping(method=RequestMethod.GET)
public String userCreate(Model model, @ModelAttribute("userCreateForm") UserCreateForm form) {
System.out.println("userCreate");
setSelectBox(form);
model.addAttribute("userCreateForm", form);
model.addAttribute("dispMode", DispMode.INPUT.getValue());
model.addAttribute("url", "confirm");
return "userCreate";
}
@RequestMapping(value="/confirm", params="confirm", method=RequestMethod.POST)
public String userCreateConfirm(Model model,
@Validated(GroupOrder.class) @ModelAttribute("userCreateForm") UserCreateForm form, BindingResult result) {
setSelectBox(form);
model.addAttribute("userCreateForm", form);
model.addAttribute("dispMode", DispMode.INPUT.getValue());
model.addAttribute("url", "confirm");
if (result.hasErrors()) {
return "userCreate";
}
model.addAttribute("dispMode", DispMode.CONFIRM.getValue());
model.addAttribute("url", "complete");
System.out.println("userCreateConfirm");
return "userCreate";
}
@RequestMapping(value="/complete", params="complete", method=RequestMethod.POST)
public String userCreateComplete(@ModelAttribute("userCreateForm") UserCreateForm form, Model model) {
System.out.println("userCreateComplete");
insertMUser(form);
setSelectBox(form);
model.addAttribute("dispMode", DispMode.COMPLETE.getValue());
return "userCreate";
}
private void setSelectBox(UserCreateForm form) {
form.setYearList(CommonClass.getYearList());
form.setMonthList(CommonClass.getMonthList());
form.setDayList(CommonClass.getDayList());
form.setAuthMap(kbnchService.getKbnchMap("AUTH"));
form.setSectionMap(sectionService.getSectionMap());
form.setSexMap(kbnchService.getKbnchMap("SEX"));
}
private void insertMUser(UserCreateForm form) {
System.out.println(form.getUserId());
MUser muser = new MUser();
muser.setUserId(form.getUserId());
muser.setPassword(form.getPassword());
muser.setAuth(new BigDecimal(form.getAuth()));
muser.setName(form.getName());
MSection msection = new MSection();
msection.setSectionId(form.getSectionId());
muser.setMSection(msection);
try {
String dateStr =
form.getBirthdayYear()
+ "/"
+ form.getBirthdayMonth()
+ "/"
+ form.getBirthdayDay();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date formatDate;
formatDate = sdf.parse(dateStr);
muser.setBirthday(formatDate);
} catch (ParseException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
muser.setSex(form.getSex());
muser.setAddress(form.getAddress());
muser.setMailAddress(form.getMailAddress());
muser.setQualify(form.getQualify());
muser.setCreateUser(form.getUserId());
muser.setCreateDate(new Timestamp(System.currentTimeMillis()));
muser.setUpdateUser(form.getUserId());
muser.setUpdateDate(new Timestamp(System.currentTimeMillis()));
muser.setInvalidFlg("0");
userService.save(muser);
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.thread.command;
import xyz.noark.core.ioc.wrap.method.AbstractControllerMethodWrapper;
import xyz.noark.core.thread.ThreadCommand;
import java.io.Serializable;
/**
* 抽象的线程处理指令.
*
* @author 小流氓[176543888@qq.com]
* @since 3.0
*/
public class AbstractThreadCommand implements ThreadCommand {
private final AbstractControllerMethodWrapper method;
private final Object[] args;
private final Serializable playerId;
public AbstractThreadCommand(AbstractControllerMethodWrapper method, Serializable playerId, Object... args) {
this.method = method;
this.args = args;
this.playerId = playerId;
}
@Override
public Object exec() {
return method.invoke(args);
}
@Override
public String code() {
return method.logCode();
}
@Override
public boolean isPrintLog() {
return method.isPrintLog();
}
public Serializable getPlayerId() {
return playerId;
}
}
|
package com.wdl.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.internal.CriteriaImpl.Subcriteria;
public class ObjectUtil {
/**
* 根据属性名获取getter setter方法名
*
* @param field
* 字段名
* @param prefix
* 前缀
* @return
*/
public static String methodName(String field, String prefix) {
if (field == null)
return null;
if (field.length() > 1 && Character.isUpperCase(field.charAt(1)))
return prefix + field;
else
return prefix + field.substring(0, 1).toUpperCase()
+ field.substring(1);
}
/**
* 根据属性名获取值
*
* @param obj
* 对象
* @param field
* 字段名
* @return
*/
public static Object getValueByKey(Object obj, String field) {
try {
Method method = null;
if (obj == null || StrUtil.isBlank(field))
return null;
String[] fieldArr = field.split("[.]");
for (String str : fieldArr) {
method = obj.getClass().getMethod(methodName(str, "get"));
obj = method.invoke(obj);
}
// System.out.println("value:"+value);
return obj;
} catch (Exception e) {
return null;
}
}
public static Object setValueByKey(Object obj, String field,Object value) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method method = null;
if (obj == null || StrUtil.isBlank(field))
return null;
String[] fieldArr = field.split("[.]");
for (String str : fieldArr) {
method = obj.getClass().getMethod(methodName(str, "set"),value.getClass());
obj = method.invoke(obj,value);
}
// System.out.println("value:"+value);
return obj;
}
/**
* 将对象object特定方法的返回值(
*
* @param object
* 对象
* @param method
* 方法
* @param format
* 格式
* @return
*/
public static String ObjectToString(Object obj, String field, String format)
throws Exception {
try {
Method method = null;
if (obj == null || StrUtil.isBlank(field))
return null;
String[] fieldArr = field.split("[.]");
for (String str : fieldArr) {
if (method != null)
obj = method.invoke(obj);
method = obj.getClass().getMethod(methodName(str, "get"));
}
// System.out.println("value:"+value);
return ObjectToString(obj, method, format);
} catch (Exception e) {
return null;
}
}
/**
* 将对象object特定方法的返回值(主要是get方法)按照format格式转化为字符串类型
*
* @param object
* 对象
* @param method
* 方法
* @param format
* 格式
* @return
*/
public static String ObjectToString(Object object, Method method,
String format) throws Exception {
if (object == null || method == null)
return null;
// 时间类型
if (method.getReturnType().getName().equals(Date.class.getName())) {
if (StrUtil.isEmpty(format))
return DateUtil.format((Date) method.invoke(object));
else
return DateUtil.format((Date) method.invoke(object), format);
}
return method.invoke(object).toString();
}
public static DetachedCriteria getCriteriaWithAlias(
DetachedCriteria criteria, String columnName) {
if (columnName.indexOf(".") == -1)
return criteria;
String[] nameArr = columnName.split("[.]");
for (int index = 0; index < nameArr.length - 1; index++) {
String str = nameArr[index];
if (index > 0
&& !isExistAlias((DetachedCriteria) criteria, ""
+ nameArr[index - 1] + "." + str + "")) {
criteria.createAlias("" + nameArr[index - 1] + "." + str + "",
"" + str + "", DetachedCriteria.LEFT_JOIN);
}
if (index == 0 && !isExistAlias((DetachedCriteria) criteria, str)) {
criteria.createAlias("" + str + "", "" + str + "",
DetachedCriteria.LEFT_JOIN);
}
}
return criteria;
}
@SuppressWarnings("unused")
public static boolean isExistAlias(DetachedCriteria impl, String path) {
try {
Field field = DetachedCriteria.class.getDeclaredField("impl");
field.setAccessible(true);
CriteriaImpl criteriaImpl = (CriteriaImpl) field.get(impl);
Iterator iterator = criteriaImpl.iterateSubcriteria();
for (; iterator.hasNext();) {
Subcriteria subcriteria = (Subcriteria) iterator.next();
if (subcriteria.getPath().equals(path)) {
return true;
}
}
return false;
} catch (Exception e) {
return false;
}
}
/**
* 获取类实例的属性值
*
* @param clazz
* 类名
* @param includeParentClass
* 是否包括父类的属性值
* @return 类名.属性名=属性类型
*/
public static Object getClassFields(String className,String attr,
boolean includeParentClass) {
Class clazz=null;
try {
clazz = Class.forName(className);
Map<String, Class> map = new HashMap<String, Class>();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
map.put(field.getName(), field.getType());
}
if (includeParentClass)
getParentClassFields(map, clazz.getSuperclass());
if(map.get(attr)!=null){
return map.get(attr).getCanonicalName();
}else{
return null;
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("获取"+className+"错误!!!");
}
}
/**
* 获取类实例的父类的属性值
*
* @param map
* 类实例的属性值Map
* @param clazz
* 类名
* @return 类名.属性名=属性类型
*/
private static Map<String, Class> getParentClassFields(
Map<String, Class> map, Class clazz) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
map.put(field.getName(), field.getType());
}
if (clazz.getSuperclass() == null) {
return map;
}
getParentClassFields(map, clazz.getSuperclass());
return map;
}
/**
* 获取类实例的方法
*
* @param clazz
* 类名
* @param includeParentClass
* 是否包括父类的方法
* @return List
*/
public static List<Method> getMothds(Class clazz, boolean includeParentClass) {
List<Method> list = new ArrayList<Method>();
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
list.add(method);
}
if (includeParentClass) {
getParentClassMothds(list, clazz.getSuperclass());
}
return list;
}
/**
* 获取类实例的父类的方法
*
* @param list
* 类实例的方法List
* @param clazz
* 类名
* @return List
*/
private static List<Method> getParentClassMothds(List<Method> list,
Class clazz) {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
list.add(method);
}
if (clazz.getSuperclass() == Object.class) {
return list;
}
getParentClassMothds(list, clazz.getSuperclass());
return list;
}
public static void main(String[] args) {
System.out.println(getClassFields("com.eigpay.base.entity.DemoEntity","id", true));
}
}
|
package com.project.personaddress.domain.service;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public abstract class AbstractService<T, ID> implements ServiceInterface<T, ID> {
abstract JpaRepository<T, ID> getRepository();
protected abstract Class<T> getEntityClass();
public Page<T> findAll(Pageable pageable) {
return getRepository().findAll(pageable);
}
public T findById(ID id) {
getRepository().existsById(id);
return getRepository().getOne(id);
}
public T create(T model) {
return getRepository().saveAndFlush(model);
}
public T update(T model, ID id) {
T savedModel = this.findById(id);
BeanUtils.copyProperties(model, savedModel, "id");
return getRepository().saveAndFlush(savedModel);
}
public void delete(ID id) {
getRepository().existsById(id);
getRepository().deleteById(id);
}
}
|
package org.cocos2dx.lib;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* 控制Cocos2dx图层 添加和删除动画
* Created by Dk on 16/6/2.
*/
public class Cocos2dxLayerContorl {
private static List<String> queue = new ArrayList<String>();
private String path;
private static boolean needAddLayer;
private static boolean needDelLayer;
private static boolean isPlay;
/**
* 添加图层
* strName,作为该图层的唯一标示
*
* @param type
*/
public void addLayer(int type) {
if (queue.size() > 0 && !isPlay) {
//System.out.println("setEndListener----addLayer---" + queue.size());
Cocos2dxLayerManager.addLayer(queue.get(0), type);
isPlay = true;
needAddLayer = false;
}
// if( needAddLayer ){
// //Cocos2dxLayerManager.addLayer("/storage/emulated/0", Cocos2dxLayerManager.EnLayerType.LAYER_TYPE_SKELETON.nCode);
// Cocos2dxLayerManager.addLayer(queue.get(0), type);
// needAddLayer = false;
// }
}
/**
* 通过唯一标示<strName>删除图层
*/
public void delLayer() {
if (needDelLayer) {
if (queue.size() > 0) {
Cocos2dxLayerManager.delLayer(queue.get(0));
queue.remove(0);
}
needDelLayer = false;
isPlay = false;
}
// if(needDelLayer){
// Cocos2dxLayerManager.delLayer(queue.get(0));
// needDelLayer = false;
// if (queue.size() > 0) {
// queue.remove(0);
// }
// }
}
/**
* 添加到队列中
*
* @param path
*/
public void addGift(String path) {
queue.add(path);
needAddLayer = true;
//System.out.println("setEndListener----addGift---" + queue.size());
}
public void onActivityDestroy(){
if(isPlay){
needDelLayer = true;
delLayer();
}
isPlay = false;
queue.clear();
needAddLayer = false;
needDelLayer = false;
}
public static void skeletonEnd(String strName) {
needDelLayer = true;
// if (queue.size() > 0) {
// if (queue.size() == 1) {
// needAddLayer = false;
// }
// queue.remove(0);
//System.out.println("setEndListener----addGift---" + queue.size());
// }
}
}
|
package com.sferion.whitewater.ui.views.pigging;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.sferion.whitewater.backend.admin.PiggingEventAdmin;
import com.sferion.whitewater.backend.admin.PiggingUserAdmin;
import com.sferion.whitewater.backend.admin.PipelineAdmin;
import com.sferion.whitewater.backend.admin.PlantsAdmin;
import com.sferion.whitewater.backend.domain.*;
import com.sferion.whitewater.backend.domain.enums.Acknowledgment;
import com.sferion.whitewater.backend.domain.enums.UnitOfMeasure;
import com.sferion.whitewater.ui.MainLayout;
import com.sferion.whitewater.ui.SessionData;
import com.sferion.whitewater.ui.components.FlexBoxLayout;
import com.sferion.whitewater.ui.components.SearchBar;
import com.sferion.whitewater.ui.views.ViewFrame;
import com.vaadin.flow.component.*;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.formlayout.FormLayout.ResponsiveStep;
import com.vaadin.flow.component.grid.ColumnTextAlign;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.select.Select;
import com.vaadin.flow.component.textfield.IntegerField;
import com.vaadin.flow.component.textfield.NumberField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.component.treegrid.TreeGrid;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.provider.hierarchy.AbstractBackEndHierarchicalDataProvider;
import com.vaadin.flow.data.provider.hierarchy.HierarchicalDataProvider;
import com.vaadin.flow.data.provider.hierarchy.HierarchicalQuery;
import com.vaadin.flow.data.renderer.TemplateRenderer;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.*;
import com.vaadin.flow.server.StreamResource;
import com.vaadin.flow.server.VaadinSession;
import org.vaadin.olli.FileDownloadWrapper;
import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.sferion.whitewater.backend.domain.enums.Acknowledgment.NO;
import static com.sferion.whitewater.backend.domain.enums.Acknowledgment.YES;
import static com.sferion.whitewater.backend.domain.enums.PiggingEventStatus.INACTIVE;
import static com.sferion.whitewater.ui.views.pigging.PiggingView.PAGE_NAME;
import static com.sferion.whitewater.ui.views.pigging.PiggingView.PAGE_TITLE;
import static com.sferion.whitewater.ui.views.pigging.SessionVariable.CURRENTLY_SELECTED_PLANT;
@PageTitle(PAGE_TITLE)
@Route(value = PAGE_NAME, layout = MainLayout.class)
public class PiggingView extends ViewFrame {
public static final String PAGE_TITLE = "Pigging";
public static final String PAGE_NAME = "pigging";
private final PlantsAdmin plantsAdmin;
private final PipelineAdmin pipelineAdmin;
private final PiggingEventAdmin piggingEventAdmin;
private final PiggingUserAdmin piggingUserAdmin;
private final Provider<SessionData> sessionDataProvider;
private Select<Plants> plants;
private TreeGrid<HierarchicalPipeline> grid;
private final List<HierarchicalPipeline> pipelineList;
private PiggingEventDetails piggingEventDetails;
@Inject
public PiggingView(PlantsAdmin plantsAdmin, PipelineAdmin pipelineAdmin, PiggingEventAdmin piggingEventAdmin, PiggingUserAdmin piggingUserAdmin, Provider<SessionData> sessionDataProvider) {
this.plantsAdmin = plantsAdmin;
this.pipelineAdmin = pipelineAdmin;
this.piggingEventAdmin = piggingEventAdmin;
this.piggingUserAdmin = piggingUserAdmin;
this.sessionDataProvider = sessionDataProvider;
pipelineList = new ArrayList<>();
}
@Override
protected void onAttach(AttachEvent attachEvent) {
setViewHeader(createHeader());
Plants currentlySelectedPlant = (Plants)VaadinSession.getCurrent().getAttribute(CURRENTLY_SELECTED_PLANT);
if (currentlySelectedPlant == null) {
List<Plants> items = plantsAdmin.listAll().stream().sorted(Comparator.comparing(Plants::getPlantDisplayName)).collect(Collectors.toList());
if (!items.isEmpty())
currentlySelectedPlant = items.get(0);
}
plants.setValue(currentlySelectedPlant);
getGridItems();
createGrid();
piggingEventDetails = new PiggingEventDetails();
VerticalLayout layout = new VerticalLayout(grid, piggingEventDetails.getLayout());
layout.setHorizontalComponentAlignment(FlexComponent.Alignment.CENTER, piggingEventDetails.getLayout());
setViewContent(layout);
updateGrid();
}
private Component createHeader() {
List<Plants> items = plantsAdmin.listAll().stream().sorted(Comparator.comparing(Plants::getPlantDisplayName)).collect(Collectors.toList());
plants = new Select<>();
plants.setItems(items);
plants.setItemLabelGenerator(Plants::getPlantDisplayName);
plants.addValueChangeListener(e -> {
VaadinSession.getCurrent().setAttribute(CURRENTLY_SELECTED_PLANT, plants.getValue());
updateGrid();
});
Select<Span> actions = new Select<>();
actions.setPlaceholder("Actions");
Span setupPipelineRuns = new Span("Setup Pipeline Runs");
setupPipelineRuns.addClickListener(e -> UI.getCurrent().navigate(SetupPipelineRunsView.class));
actions.add(setupPipelineRuns);
Span setupPipelines = new Span("Setup Pipelines");
setupPipelines.addClickListener(e -> UI.getCurrent().navigate(SetupPipelinesView.class));
actions.add(setupPipelines);
Span reviewPiggingRecords = new Span("Review Pigging Records");
reviewPiggingRecords.addClickListener(e -> UI.getCurrent().navigate(PiggingRecordsView.class));
actions.add(reviewPiggingRecords);
Span exportData = new Span("Export Data");
FileDownloadWrapper buttonWrapper = new FileDownloadWrapper(new StreamResource(getExportFilename(), () -> new ByteArrayInputStream(getExportFileData())));
buttonWrapper.wrapComponent(exportData);
actions.add(buttonWrapper);
HorizontalLayout selectLayout = new HorizontalLayout(plants, actions);
selectLayout.setWidthFull();
selectLayout.setJustifyContentMode(FlexComponent.JustifyContentMode.END);
SearchBar searchBar = new SearchBar();
TextField searchText = searchBar.getTextField();
searchText.addValueChangeListener(e -> {
pipelineList.clear();
if (searchText.getValue().isEmpty())
pipelineList.addAll(pipelineAdmin.getHierarchicalPipelinesByPlant(plants.getValue().getId()));
else
pipelineList.addAll(pipelineAdmin.getHierarchicalPipelinesByPlantAndFilter(plants.getValue().getId(), searchText.getValue()));
grid.getDataProvider().refreshAll();
grid.expand(pipelineList);
});
searchText.setValueChangeMode(ValueChangeMode.EAGER);
searchBar.setPlaceHolder("Search");
searchBar.setActionText("Pigging Event" );
searchBar.getActionButton().getElement().setAttribute("new-button", true);
searchBar.addActionClickListener(e -> UI.getCurrent().navigate(NewPiggingEventView.class));
FlexBoxLayout searchContainer = new FlexBoxLayout(searchBar);
searchContainer.setWidthFull();
return new VerticalLayout(selectLayout, searchContainer);
}
private void createGrid() {
grid = new TreeGrid<>();
HierarchicalDataProvider<HierarchicalPipeline, Void> dataProvider = new AbstractBackEndHierarchicalDataProvider<>() {
@Override
public int getChildCount(HierarchicalQuery<HierarchicalPipeline, Void> query) {
return (int) pipelineList.stream().filter(i -> Objects.equals(query.getParent(), i.getParent())).count();
}
@Override
public boolean hasChildren(HierarchicalPipeline item) {
return pipelineList.stream().anyMatch(i -> Objects.equals(item, i.getParent()));
}
@Override
protected Stream<HierarchicalPipeline> fetchChildrenFromBackEnd(HierarchicalQuery<HierarchicalPipeline, Void> query) {
return pipelineList.stream().filter(i -> Objects.equals(query.getParent(), i.getParent()));
}
};
grid.setDataProvider(dataProvider);
grid.asSingleSelect().addValueChangeListener(e -> handleGridValueChange());
grid.addComponentHierarchyColumn(e -> {
Span column = new Span(e.getPipelineRunName());
column.getStyle().set("font-weight", "bold");
return column;
});
grid.addColumn(TemplateRenderer.<HierarchicalPipeline> of("<div title='[[item.from]]'>[[item.from]]</div>")
.withProperty("from", HierarchicalPipeline::getFromLocation))
.setHeader("From Location")
.setTextAlign(ColumnTextAlign.CENTER);
grid.addColumn(TemplateRenderer.<HierarchicalPipeline> of("<div title='[[item.to]]'>[[item.to]]</div>")
.withProperty("to", HierarchicalPipeline::getToLocation))
.setHeader("To Location")
.setTextAlign(ColumnTextAlign.CENTER);
grid.addColumn(TemplateRenderer.<HierarchicalPipeline> of("<div title='[[item.length]]'>[[item.length]]</div>")
.withProperty("length", HierarchicalPipeline::getLength))
.setHeader(new Html(String.format("<div style='text-align:center;'>%s</div>", String.format("<div>%s<br>%s</div>", "Length", "(km)"))))
.setTextAlign(ColumnTextAlign.CENTER);
grid.addColumn(TemplateRenderer.<HierarchicalPipeline> of("<div title='[[item.diameter]]'>[[item.diameter]]</div>")
.withProperty("diameter", HierarchicalPipeline::getDiameter))
.setHeader(new Html(String.format("<div style='text-align:center;'>%s</div>", String.format("<div>%s<br>%s</div>", "Diameter", "(mm)"))))
.setTextAlign(ColumnTextAlign.CENTER);
grid.addColumn(TemplateRenderer.<HierarchicalPipeline> of("<div title='[[item.substance]]'>[[item.substance]]</div>")
.withProperty("substance", HierarchicalPipeline::getSubstance))
.setHeader("Substance")
.setTextAlign(ColumnTextAlign.CENTER);
grid.addColumn(TemplateRenderer.<HierarchicalPipeline> of("<div title='[[item.status]]'>[[item.status]]</div>")
.withProperty("status", HierarchicalPipeline::getStatus))
.setHeader("Status")
.setTextAlign(ColumnTextAlign.CENTER);
grid.addColumn(TemplateRenderer.<HierarchicalPipeline> of("<div title='[[item.frequency]]'>[[item.frequency]]</div>")
.withProperty("frequency", HierarchicalPipeline::getFrequency))
.setHeader(new Html(String.format("<div style='text-align:center;'>%s</div>", String.format("<div>%s<br>%s</div>", "Pigging", "Frequency"))))
.setTextAlign(ColumnTextAlign.CENTER);
grid.addColumn(TemplateRenderer.<HierarchicalPipeline> of("<div title='[[item.last]]'>[[item.last]]</div>")
.withProperty("last", HierarchicalPipeline::getLastPigDateString))
.setHeader("Last Pigged Date")
.setTextAlign(ColumnTextAlign.CENTER);
grid.addColumn(TemplateRenderer.<HierarchicalPipeline> of("<div title='[[item.next]]'>[[item.next]]</div>")
.withProperty("next", HierarchicalPipeline::getNextPigDateString))
.setHeader("Next Pig Date Target")
.setTextAlign(ColumnTextAlign.CENTER);
grid.addComponentColumn(HierarchicalPipeline::getStatusFlag).setHeader("Status");
}
private void handleGridValueChange() {
HierarchicalPipeline selectedPipeline = grid.asSingleSelect().getValue();
if (selectedPipeline == null)
return;
piggingEventDetails.getLayout().setVisible(selectedPipeline.getLastPigDate() != null);
piggingEventDetails.setPiggingEventDetails(selectedPipeline.getPipeline());
}
private void updateGrid() {
if (grid != null) {
getGridItems();
grid.getDataProvider().refreshAll();
if (pipelineList.size() >= 2) {
piggingEventDetails.getLayout().setVisible(true);
int index = 0;
for (HierarchicalPipeline pipeline : pipelineList) {
grid.expand(pipeline);
if (grid.isExpanded(pipeline)) {
grid.asSingleSelect().setValue(pipelineList.get(++index));
break;
}
++index;
}
} else
piggingEventDetails.getLayout().setVisible(false);
}
}
private void getGridItems() {
pipelineList.clear();
pipelineList.addAll(pipelineAdmin.getHierarchicalPipelinesByPlant(plants.getValue().getId()));
}
private String getExportFilename() {
return "PiggingExport-" + sessionDataProvider.get().getCurrentUser().getCompany().getName() + "-" + LocalDate.now();
}
private byte[] getExportFileData() {
/*
PlanGlobal Systems Export www.planglobal.ca
Company: <Clients Company Name>
Pipeline Run From Location To Location Length (km) Diameter (mm) Substance Status Pigging Frequency Last Pigged Date Next Pig Date
*/
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("PlanGlobal Systems Export" + "\t" + "www.planglobal.ca" + "\n")
.append("Company:" + "\t").append(sessionDataProvider.get().getCurrentUser().getCompany().getName()).append("\n");
stringBuilder.append("Pipeline Run" + "\t" + "From Location" + "\t" + "To Location" + "\t" + "Length (km)" + "\t" + "Diameter (mm)" + "\t" + "Substance" + "\t" + "Status" + "\t" + "Pigging Frequency" + "\t" + "Last Pigged Date" + "\t" + "Next Pig Date" + "\n");
for(HierarchicalPipeline pipeline : pipelineList)
stringBuilder.append(pipeline.getPipelineRunName()).append(",").append(pipeline.getFromLocation()).append(",").append(pipeline.getToLocation()).append(",").append(pipeline.getLength()).append(",").append(pipeline.getDiameter()).append(",").append(pipeline.getSubstance()).append(",").append(pipeline.getStatus()).append(",").append(pipeline.getFrequency()).append(",").append(pipeline.getLastPigDate()).append(",").append(pipeline.getNextPigDate()).append("\n");
return stringBuilder.toString().getBytes();
}
private class PiggingEventDetails {
private final VerticalLayout layout;
private TextField pipelineRun;
private TextField fromLocation;
private TextField toLocation;
private DatePicker dateSent;
private Select<String> sentBy;
private Select<Acknowledgment> sizingRingUsed;
private TextField pigType;
private NumberField pigSize;
private NumberField durometer;
private DatePicker dateRetrieved;
private Select<String> retrievedBy;
private IntegerField piggingTime;
private Select<Acknowledgment> batchFluidUsed;
private NumberField batchVolume;
private Select<UnitOfMeasure> units;
private TextField comment;
private Dialog confirmDialog;
private Button save;
private Binder<PiggingEvent> binder;
private PiggingEvent currentPiggingEvent;
public PiggingEventDetails() {
binder = new Binder<>();
layout = new VerticalLayout(createPiggingEventDetails(), createButtonLayout());
layout.setWidth("50%");
}
public VerticalLayout getLayout() {
return layout;
}
private Component createPiggingEventDetails() {
FormLayout columnLayout = new FormLayout();
columnLayout.setResponsiveSteps(
new ResponsiveStep("25em", 1),
new ResponsiveStep("32em", 2),
new ResponsiveStep("40em", 3));
pipelineRun = new TextField("Pipeline Run");
pipelineRun.setReadOnly(true);
pipelineRun.setRequiredIndicatorVisible(true);
columnLayout.add(pipelineRun,1);
fromLocation = new TextField("From Location");
fromLocation.setReadOnly(true);
fromLocation.setRequiredIndicatorVisible(true);
columnLayout.add(fromLocation,1);
toLocation = new TextField("To Location");
toLocation.setReadOnly(true);
toLocation.setRequiredIndicatorVisible(true);
columnLayout.add(toLocation,1);
dateSent = new DatePicker("Date Pig Sent");
dateSent.setRequiredIndicatorVisible(true);
columnLayout.add(dateSent,1);
sentBy = new Select<>();
sentBy.setLabel("Sent By");
sentBy.setRequiredIndicatorVisible(true);
List<String> userNames = piggingUserAdmin.getUserNames();
sentBy.setItems(userNames);
columnLayout.add(sentBy,2);
sizingRingUsed = new Select<>(YES, NO);
sizingRingUsed.setLabel("Was a Sizing Ring Used?");
sizingRingUsed.setRequiredIndicatorVisible(true);
columnLayout.add(sizingRingUsed,1);
columnLayout.add(new Html("<div> </div>"),2);
pigType = new TextField("Pig Type");
pigType.setRequiredIndicatorVisible(true);
columnLayout.add(pigType,1);
pigSize = new NumberField("Pig Size (inches)");
pigSize.setRequiredIndicatorVisible(true);
columnLayout.add(pigSize,1);
durometer = new NumberField("Durometer");
columnLayout.add(durometer,1);
dateRetrieved = new DatePicker("Date Pig Retrieved");
columnLayout.add(dateRetrieved,1);
retrievedBy = new Select<>();
retrievedBy.setLabel("Retrieved By");
retrievedBy.setItems(userNames);
columnLayout.add(retrievedBy,2);
piggingTime = new IntegerField("Pigging Time (minutes)");
columnLayout.add(piggingTime,1);
columnLayout.add(new Html("<div> </div>"),2);
batchFluidUsed = new Select<>(YES,NO);
batchFluidUsed.setLabel("Batch Fluid Used?");
batchFluidUsed.addValueChangeListener(this::handleBatchFluidUsedValueChanged);
columnLayout.add(batchFluidUsed,1);
batchVolume = new NumberField("Batch Volume");
batchVolume.setRequiredIndicatorVisible(true);
columnLayout.add(batchVolume,1);
units = new Select<>();
units.setLabel("Units");
units.setRequiredIndicatorVisible(true);
units.setItems(UnitOfMeasure.getVolumeUnitsOfMeasure());
columnLayout.add(units,1);
comment = new TextField("Comment");
columnLayout.add(comment,3);
binder = new Binder<>();
binder.forField(pipelineRun).bind(PiggingEvent::getPipelineRunName,null);
binder.forField(fromLocation).bind(PiggingEvent::getFromLocation,null);
binder.forField(toLocation).bind(PiggingEvent::getToLocation,null);
binder.forField(dateSent).withValidator(date -> date != null && !date.isAfter(LocalDate.now()),"Date sent cannot be in the future").bind(PiggingEvent::getDateSent,PiggingEvent::setDateSent);
binder.forField(sentBy).asRequired().bind(PiggingEvent::getSentBy,PiggingEvent::setSentBy);
binder.forField(sizingRingUsed).bind(PiggingEvent::getSizingRingUsed,PiggingEvent::setSizingRingUsed);
binder.forField(pigType).asRequired().bind(PiggingEvent::getPigType,PiggingEvent::setPigType);
binder.forField(pigSize).asRequired().bind(PiggingEvent::getPigSize,PiggingEvent::setPigSize);
binder.forField(durometer).bind(PiggingEvent::getDurometer,PiggingEvent::setDurometer);
binder.forField(dateRetrieved).withValidator(date -> date == null || (!date.isAfter(LocalDate.now()) && !date.isBefore(dateSent.getValue())), "Date Retrieved cannot be in the future or before the date sent").bind(PiggingEvent::getDateRetrieved,PiggingEvent::setDateRetrieved);
binder.forField(retrievedBy).bind(PiggingEvent::getRetrievedBy,PiggingEvent::setRetrievedBy);
binder.forField(piggingTime).bind(PiggingEvent::getPiggingTime,PiggingEvent::setPiggingTime);
binder.forField(batchFluidUsed).bind(PiggingEvent::getBatchFluidUsed,PiggingEvent::setBatchFluidUsed);
Binder.Binding<PiggingEvent, Double> batchVolumeBinding = binder.forField(batchVolume).withValidator(value -> batchFluidUsed.getValue() == null || batchFluidUsed.getValue() == NO || value != null, "").bind(PiggingEvent::getBatchVolume, PiggingEvent::setBatchVolume);
Binder.Binding<PiggingEvent, UnitOfMeasure> unitsBinding = binder.forField(units).withValidator(value -> batchFluidUsed.getValue() == null || batchFluidUsed.getValue() == NO || value != null, "").bind(PiggingEvent::getUnits, PiggingEvent::setUnits);
batchFluidUsed.addValueChangeListener(event -> {
batchVolumeBinding.validate();
unitsBinding.validate();
});
binder.forField(comment).bind(PiggingEvent::getComment,PiggingEvent::setComment);
binder.addValueChangeListener(e -> save.setEnabled(binder.validate().isOk()));
return columnLayout;
}
private void setPiggingEventDetails(Pipeline pipeline) {
PiggingEvent piggingEvent = piggingEventAdmin.getLastPiggingEventByPipeline(pipeline);
if (piggingEvent == null) {
layout.setVisible(false);
return;
}
currentPiggingEvent = piggingEvent;
layout.setVisible(true);
pipelineRun.setValue(piggingEvent.getPipelineRunName());
fromLocation.setValue(piggingEvent.getFromLocation());
toLocation.setValue(piggingEvent.getToLocation());
dateSent.setValue(piggingEvent.getDateSent());
sentBy.setValue(piggingEvent.getSentBy());
sizingRingUsed.setValue(piggingEvent.getSizingRingUsed());
pigType.setValue(piggingEvent.getPigType());
pigSize.setValue(piggingEvent.getPigSize());
durometer.setValue(piggingEvent.getDurometer());
dateRetrieved.setValue(piggingEvent.getDateRetrieved());
retrievedBy.setValue(piggingEvent.getRetrievedBy());
piggingTime.setValue(piggingEvent.getPiggingTime());
batchFluidUsed.setValue(piggingEvent.getBatchFluidUsed());
batchVolume.setValue(piggingEvent.getBatchVolume());
units.setValue(piggingEvent.getUnits());
comment.setValue(piggingEvent.getComment());
save.setEnabled(false);
}
private HorizontalLayout createButtonLayout() {
save = new Button("Save");
save.addClickListener(e -> handleSaveButtonClick());
Button remove = new Button("Remove");
remove.addClickListener(e -> confirmDialog.open());
confirmDialog = new Dialog();
confirmDialog.add(new Text("Are you sure you want to remove pigging event?"));
confirmDialog.setCloseOnEsc(false);
confirmDialog.setCloseOnOutsideClick(false);
confirmDialog.setDraggable(true);
confirmDialog.setResizable(true);
Button confirm = new Button("Yes", event -> {
confirmDialog.close();
handleRemoveButtonClick();
});
confirmDialog.add(new HorizontalLayout(confirm, new Button("No", event -> confirmDialog.close())));
return new HorizontalLayout(save,remove);
}
private void handleBatchFluidUsedValueChanged(HasValue.ValueChangeEvent<?> e) {
Acknowledgment action = (Acknowledgment)e.getValue();
batchVolume.setVisible(action == YES);
units.setVisible(action == YES);
}
private void handleSaveButtonClick() {
if (binder.writeBeanIfValid(currentPiggingEvent)) {
currentPiggingEvent.markUpdated();
piggingEventAdmin.save(currentPiggingEvent, sessionDataProvider.get());
Notification notification = new Notification("Pigging event has been updated", 5000);
notification.open();
}
}
private void handleRemoveButtonClick() {
if (binder.writeBeanIfValid(currentPiggingEvent)) {
currentPiggingEvent.setStatus(INACTIVE);
currentPiggingEvent.setDateInactive(LocalDateTime.now());
User currentUser = sessionDataProvider.get().getCurrentUser();
currentPiggingEvent.setRemovedBy(currentUser.getName() + " " + currentUser.getLastName());
piggingEventAdmin.save(currentPiggingEvent, sessionDataProvider.get());
updateGrid();
}
}
}
}
|
package com.tu.mysql.service;
import com.tu.mysql.model.Role;
/**
* @Auther: tuyongjian
* @Date: 2019/10/23 16:30
* @Description:
*/
public interface RoleService {
void add(Role role);
}
|
package com.gp.extract.twitter.labeler.models;
import com.gp.extract.twitter.Configuration;
import com.gp.extract.twitter.labeler.features.FeatureExtractor;
import com.gp.extract.twitter.labeler.features.Features;
import com.gp.extract.twitter.labeler.sequence.Sentence;
import com.gp.extract.twitter.labeler.sequence.Tags;
import com.gp.extract.twitter.util.IOUtil;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public abstract class SequenceModel implements IOUtil.Logger, IOUtil.Loadable{
private static final String DATA_FILE = "model.txt";
private static final String FEATURES_DIR = "features/";
protected int transitionWeightsOffset, transitionWeightsColLength, observationalWeightsOffset,
observationalWeightsColLength;
protected Tags tags;
protected Configuration.Task task;
protected Features features;
protected double [] weights;
protected boolean locked = false;
protected String saveDirectory;
public abstract String getLoggerId();
public SequenceModel(Configuration.Task task, Tags tags, ArrayList<FeatureExtractor> extractors,
String saveDirectory) {
this.tags = tags;
this.features = new Features(extractors, saveDirectory + FEATURES_DIR);
this.saveDirectory = saveDirectory;
this.task = task;
}
public Features getFeatures()
{
return features;
}
public Configuration.Task getTask() {
return task;
}
public abstract String getFeatureName(int index);
public void setupWeights() {
if(weights != null)
{
IOUtil.showError(this, "Weights are already setup.");
return;
}
//tags + tags*tags+1 + tags*obs_feat
//we have a weight for each tag excluding the start tag
int tags_size = tags.getSize();
//weight for each possible tag transition
int transitional_size = (tags.getSize()) * (tags.getSize()+1);
//weights for having the observation features with each tag excluding the start tag
int observational_size= features.getDimensions() * (tags.getSize());
weights = new double[tags_size + transitional_size+ observational_size];
//set offsets
transitionWeightsOffset = tags_size;
observationalWeightsOffset = tags_size + transitional_size;
//set row sizes
transitionWeightsColLength = (tags.getSize()+1);
observationalWeightsColLength = (tags.getSize());
}
public double [] getWeights()
{
return weights;
}
public void setWeights(double [] weights)
{
if(locked)
{
IOUtil.showError(this, "Can not set weights in locked mode.");
return;
}
this.weights = weights;
}
public void lock(){
locked = true;
features.lock();
}
public abstract double getLogLikelihood(ArrayList<Sentence> trainingSentences);
public abstract double[] computeGradient(ArrayList<Sentence> trainingSentences);
public Tags getTags() {
return tags;
}
public abstract void decode(Sentence sentence);
@Override
public String getLogId() {
return getLoggerId();
}
@Override
public void load() throws IOException {
features.load();
setupWeights();
String file = saveDirectory + DATA_FILE;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(IOUtil.getUTF8FileReader(file, false));
Scanner scanner = new Scanner(bufferedReader);
String line = "";
for (int i = 0; i < weights.length; i++){
line = scanner.nextLine();
String [] data = line.split("\\t");
weights[i] = Double.parseDouble(data[1]);
}
}
catch (IOException e)
{
throw e;
}
finally {
if (bufferedReader != null)
bufferedReader.close();
}
lock();
}
@Override
public void save() throws IOException {
features.save();
if(weights.length == 0) {
IOUtil.showError(this, "Model should be trained before it can be saved.");
return;
}
String file = saveDirectory + DATA_FILE;
BufferedWriter bufferedWriter = null;
try
{
bufferedWriter = new BufferedWriter(IOUtil.getUTF8FileWriter(file, true));
PrintWriter printWriter = new PrintWriter(bufferedWriter);
for(int i = 0 ; i < weights.length; i++)
{
printWriter.printf("%s\t%s",getFeatureName(i), Double.toString(weights[i]));
printWriter.println();
}
}
catch (IOException e)
{
throw e;
}
finally {
if(bufferedWriter != null)
{
bufferedWriter.close();
}
}
}
protected int getTagWeightIndex(int tag_index)
{
return tag_index;
}
protected int getTransitionTagWeightIndex(int tag_current_index, int tag_previous_index)
{
return transitionWeightsOffset + ((tag_current_index*(transitionWeightsColLength))
+ tag_previous_index);
}
protected int getObservationalTagWeightIndex(int tag_index, int feature_index)
{
return observationalWeightsOffset + ((feature_index*(observationalWeightsColLength))
+ tag_index);
}
protected double getTagWeight(int tag_index)
{
return weights[getTagWeightIndex(tag_index)];
}
protected double getTransitionTagWeight(int tag_current_index, int tag_previous_index)
{
return weights[getTransitionTagWeightIndex(tag_current_index, tag_previous_index)];
}
protected double getObservationalTagWeight(int tag_index, int feature_index)
{
return weights[getObservationalTagWeightIndex(tag_index, feature_index)];
}
}
|
package com.scriptingsystems.tutorialjava.poo.collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.scriptingsystems.tutorialjava.poo.interfaces.Racional;
public class SetTest {
/**
*
* @see Set para ordenar hace uso de "equals" y "hashCode"
*/
public static void main (String[] args) {
Set<String> myStringSet = new HashSet<>();
Set<Racional> myRacionalSet = new HashSet<>();
myStringSet.add("Luis");
myStringSet.add("Luis");
myStringSet.add("Manuel");
myStringSet.add("Jose");
myStringSet.add("Alberto");
System.out.println("\n\nRecorriendo con FOREACH...");
for (String s : myStringSet) {
System.out.println(s);
}
Iterator<String> i = myStringSet.iterator();
System.out.println("\n\nRecorriendo con un iterador...");
while ( i.hasNext() ) {
String str=i.next();
System.out.println( str );
}
System.out.println("\n\nInicializando pruebas de Racionales");
myRacionalSet.add(new Racional(2, 3));
myRacionalSet.add(new Racional(1, 3));
myRacionalSet.add(new Racional(2, 7));
myRacionalSet.add(new Racional(9, 3));
myRacionalSet.add(new Racional(2, 3));
myRacionalSet.add(new Racional(4, 6));
System.out.println("PENDIENTE DE VER RESULTADOS: Recorriendo la lista con un Iterator");
Iterator<Racional> it2=myRacionalSet.iterator();
while(it2.hasNext()){
System.out.println(it2.next());
}
System.out.println(new String("Luis").hashCode());
System.out.println(new String("Luis").hashCode());
System.out.println(new String("Manuel").hashCode());
}
}
|
package com.fgtit.app;
public class LogItem {
public int userid;
public String username="";
public int status1;
public int status2;
public String datetime;
}
|
package utils;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.archive.io.ArchiveReader;
import org.archive.io.ArchiveRecord;
import org.archive.io.warc.WARCRecord;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import utils.CommonCrawlSource.WARC_TYPE;
public class URLFinder {
public final static String WIKIPEDIA_REGEX = "^https?:\\/\\/([a-z]{1,4}).wikipedia.org\\/wiki\\/(.+)$";
public final static Pattern WIKIPEDIA_PATTERN = Pattern.compile(WIKIPEDIA_REGEX);
Iterator<ArchiveRecord> iterator;
ArchiveRecord currentWat;
public URLFinder(CommonCrawlSource source, String segment, String warcName) throws Exception {
try {
ArchiveReader reader = source.getArchive(segment, warcName, WARC_TYPE.WAT);
iterator = reader.iterator();
next();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void next() throws Exception {
while (iterator.hasNext()) {
currentWat = iterator.next();
if (currentWat.getHeader().getHeaderValue(WARCRecord.HEADER_KEY_TYPE).equals("metadata")) {
return;
}
}
throw new Exception("End of File");
}
public static String read(InputStream input) {
BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream(input)));
StringBuilder string = new StringBuilder();
String line;
try {
while ((line = br.readLine()) != null) {
string.append(line);
string.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return string.toString();
}
private static Map<String, Set<String>> getLinksFromJson(String json, boolean wikiLinksOnly) {
Map<String, Set<String>> map = new HashMap<String, Set<String>>();
JSONParser parser = new JSONParser();
JSONObject root;
try {
root = (JSONObject) parser.parse(json);
JSONObject envelope = (JSONObject) root.get("Envelope");
JSONObject payload = (JSONObject) envelope.get("Payload-Metadata");
JSONObject response = (JSONObject) payload.get("HTTP-Response-Metadata");
JSONObject html = (JSONObject) response.get("HTML-Metadata");
JSONArray links = (JSONArray) html.get("Links");
for (Object link: links) {
JSONObject linkObject = (JSONObject) link;
if (linkObject.containsKey("text") && linkObject.containsKey("url")) {
String text = (String) linkObject.get("text");
String url = (String) linkObject.get("url");
if (wikiLinksOnly) {
Matcher matcher = URLFinder.WIKIPEDIA_PATTERN.matcher(url);
if (matcher.find()) {
url = matcher.group(1) + "/" + matcher.group(2);
} else {
continue;
}
}
if (!map.containsKey(text)) {
map.put(text, new HashSet<String>());
}
map.get(text).add(url);
}
}
} catch (ParseException | NullPointerException e) {
//e.printStackTrace();
}
return map;
}
public Map<String, Set<String>> getLinks(String recordId, boolean wikiLinkOnly) {
try {
while (!currentWat.getHeader().getHeaderValue(WARCRecord.HEADER_KEY_REFERS_TO).equals(recordId)) {
next();
}
String record = read(currentWat);
return getLinksFromJson(record, wikiLinkOnly);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String name = CommonCrawlSource.getWarcName("CC-MAIN-20200117123339-20200117151339-00000.warc.wet.gz");
try {
URLFinder fetcher = new URLFinder(CommonCrawlSource.DEFAULT, "1579250589560.16", name);
System.out.println(fetcher.getLinks("<urn:uuid:84b02cb0-897f-439b-8c11-844597c7bdf0>", true));
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println(getRequestResponseMap());
}
}
|
package com.receiptify;
import android.Manifest;
import android.app.Application;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.google.android.material.navigation.NavigationView;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.vision.v1.Vision;
import com.google.api.services.vision.v1.VisionRequest;
import com.google.api.services.vision.v1.VisionRequestInitializer;
import com.google.api.services.vision.v1.model.AnnotateImageRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesResponse;
import com.google.api.services.vision.v1.model.Feature;
import com.google.api.services.vision.v1.model.Image;
import com.google.api.services.vision.v1.model.TextAnnotation;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.receiptify.activities.AddReceipt;
import com.receiptify.activities.Products;
import com.receiptify.activities.ReceiptsView;
import com.receiptify.activities.Settings;
import com.receiptify.activities.Statistics;
import com.receiptify.data.DBViewModel;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.lifecycle.ViewModelProvider;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import android.os.Environment;
import android.os.IBinder;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import static android.graphics.Color.argb;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static String CLOUD_VISION_API_KEY;
public static final String FILE_NAME = "temp.jpg";
private static final String ANDROID_CERT_HEADER = "X-Android-Cert";
private static final String ANDROID_PACKAGE_HEADER = "X-Android-Package";
private static final int MAX_LABEL_RESULTS = 10;
private static final int MAX_DIMENSION = 1200;
private static final String TAG = MainActivity.class.getSimpleName();
private static final int GALLERY_PERMISSIONS_REQUEST = 0;
private static final int GALLERY_IMAGE_REQUEST = 1;
public static final int CAMERA_PERMISSIONS_REQUEST = 2;
public static final int CAMERA_IMAGE_REQUEST = 3;
public static DBViewModel DBreference;
private DrawerLayout drawer;
public static TextView mImageDetails;
private ImageView mMainImage;
//private ReceiptsViewModel DBreference;
private DataSyncService dataSyncService;
@Override
protected void onCreate(Bundle savedInstanceState) {
CLOUD_VISION_API_KEY = getString(R.string.CLOUD_VISION_API_KEY);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
createFabMenu();
DBreference = new DBViewModel(this.getApplication());
startService(new Intent(this,DataSyncService.class).setAction("initialize"));
drawer = findViewById(R.id.drawer_layout);
setNavigationViewListener();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.nav_app_bar_open_drawer_description, R.string.nav_app_bar_navigate_up_description);
drawer.addDrawerListener(toggle);
toggle.syncState();
{
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.permitNetwork()
.permitCustomSlowCalls()
.permitAll()// or .detectAll() for all detectable problems
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.build());
}
mImageDetails = findViewById(R.id.image_details);
mMainImage = findViewById(R.id.main_image);
// Update the cached copy of the words to the TextView
DBreference.getAllCompanies().observe(this, words -> {
String s="";
for(int i=0;i<words.size();i++)
s += words.get(i).getName()+" ";
mImageDetails.setText(s);
});
}
public void onBackPressed() {
if (drawer.isDrawerOpen((GravityCompat.START))) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.receipts_message:
goReceipts();
break;
case R.id.stats_message:
goStatistics();
break;
case R.id.products_message:
goProducts();
break;
case R.id.settings_message:
goSettings();
break;
}
return true;
}
//listener for drawer items
private void setNavigationViewListener() {
NavigationView navigationView = (findViewById(R.id.nav_view));
navigationView.setNavigationItemSelectedListener(this);
}
void goReceipts() {
Intent a = new Intent(this,ReceiptsView.class);
startActivity(a);
}
void goStatistics() {
Intent a = new Intent(this, Statistics.class);
startActivity(a);
}
void goSettings() {
Intent a = new Intent(this, Settings.class);
startActivity(a);
}
void goProducts() {
Intent a = new Intent(this, Products.class);
startActivity(a);
}
void createFabMenu(){
final FloatingActionsMenu menuMultipleActions = findViewById(R.id.multiple_actions);
FloatingActionButton takePhoto = new FloatingActionButton(getBaseContext());
takePhoto.setColorNormal(argb(255,255,0,0));
takePhoto.setTitle("take a photo");
takePhoto.setOnClickListener(v -> {
Intent a = new Intent(this, AddReceipt.class).setAction("take a photo");
startActivity(a);
menuMultipleActions.collapse();});
FloatingActionButton loadPhoto = new FloatingActionButton(getBaseContext());
loadPhoto.setColorNormal(argb(255,0,255,0));
loadPhoto.setTitle("point app to an existing photo from the phone's storage");
loadPhoto.setOnClickListener(v -> {
Intent a = new Intent(this, AddReceipt.class).setAction("gallery");
startActivity(a);
menuMultipleActions.collapse();});
FloatingActionButton addDB = new FloatingActionButton(getBaseContext());
addDB.setColorNormal(argb(255,0,0,255));
addDB.setTitle("addDB");
addDB.setOnClickListener(v -> {
//startService(new Intent(this,DataSyncService.class).setAction("companies"));
//login();
Intent a = new Intent(this, AddReceipt.class).setAction("manually");
startActivity(a);
menuMultipleActions.collapse();
});
menuMultipleActions.addButton(takePhoto);
menuMultipleActions.addButton(loadPhoto);
menuMultipleActions.addButton(addDB);
}
}
|
package com.cskaoyan.service;
import com.cskaoyan.bean.AllVo;
import com.cskaoyan.bean.vo.StatusVo;
import com.cskaoyan.bean.user.UserRegisterVo;
import com.cskaoyan.bean.user.UserUpdate;
import com.cskaoyan.bean.vo.Vo;
/**
* @Author: yyc
* @Date: 2019/6/4 17:03
*/
public interface UserService {
StatusVo register(UserRegisterVo userRegisterVo);
StatusVo check(String username);
String getPwdByUsername(String credenceName);
Vo getUserInfo(String userName);
AllVo updateUserInfo(UserUpdate userUpdate);
int getUserIdByUsername(String username);
}
|
package com.almondtools.stringbench.incubation;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import com.almondtools.stringbench.BSBoyerMooreHorspoolBenchmark;
import com.almondtools.stringbench.CompareResultNotAccepted;
import com.almondtools.stringbench.SinglePatternMatcherBenchmark;
import com.almondtools.stringbench.SinglePatternSample;
import com.almondtools.stringbench.SinglePatternTest;
@Ignore //No algorithm should use longer than a minute for finding patterns
public class BSBoyerMooreHorspoolIncubationTest extends SinglePatternTest {
@Rule
public CompareResultNotAccepted compare = CompareResultNotAccepted.compare();
public SinglePatternMatcherBenchmark benchmark;
@Before
public void before() throws Exception {
benchmark = new BSBoyerMooreHorspoolBenchmark();
}
@Test (timeout=60_000)
public void test22() throws Exception {
SinglePatternSample sample = createSample(2, 2);
benchmark.setup(sample);
benchmark.benchmarkFind();
benchmark.tearDown();
}
}
|
package cn.jiucaituan.spider.script;
import java.util.List;
import java.util.Map;
import cn.jiucaituan.common.JdbcExecutor;
import cn.jiucaituan.common.QueueFactory;
import cn.jiucaituan.vo.Msg;
public class StockF10Script {
public StockF10Script() {
jdbcExecutor = new JdbcExecutor();
}
private JdbcExecutor jdbcExecutor;
String commandCode = "StockDeal";
public void invoke(String jobType, String date) {
// 抓取当天内,所有股票的交易详情信息。
List slist = jdbcExecutor.queryForList("select * from S_STOCK ", new Object[] {});
for (int i = 0; i < slist.size(); i++) {
Map row = (Map) slist.get(i);
String stockId = row.get("ID").toString();
Msg msg = new Msg();
msg.setStockId(stockId);
msg.setDate(date);
msg.setCommandCode(commandCode);
msg.setMsgType(jobType);
QueueFactory.getQueue(commandCode).add(msg);
}
}
}
|
package Resources;
import java.sql.Date;
/**
*
* @author krismaini
*/
public class PickUpOrder {
private int orderID, customerID;
private Date startDate, finishDate;
public PickUpOrder(int orderID, int customerID, Date startDate, Date finishDate) {
this.orderID = orderID;
this.customerID = customerID;
this.startDate = startDate;
this.finishDate = finishDate;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public void setFinishDate(Date finishDate) {
this.finishDate = finishDate;
}
public int getPickUPOrderID() {
return orderID;
}
public int getPickUpCustomerID() {
return customerID;
}
public Date getStartDate(){
return startDate;
}
public Date getFinishDate(){
return finishDate;
}
}
|
package net.sf.throughglass.utils;
/**
* Created by yowenlove on 14-8-2.
*/
public class CustomTag {
public static String make(String tag) {
return "throughglass." + tag;
}
}
|
package com.test.fei;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.view.View;
public class GeometryActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GeometryView(this));
}
class GeometryView extends View {
private Paint paint;
public GeometryView(Context context) {
super(context);
paint = new Paint();
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
// canvas.drawText("绘制无规则几何图形哦!!",200,300,paint);
paint.setStrokeWidth(4);
canvas.drawLine(0,0,50,50,paint);
paint.setColor(Color.YELLOW);
paint.setStyle(Paint.Style.FILL);
// canvas.drawRect(0,0,100,100,paint);
// canvas.drawCircle(150,150,25,paint);
paint.setColor(Color.BLACK);
Path path = new Path();
path.moveTo(400,400);
path.lineTo(200,500);
path.lineTo(300,600);
path.lineTo(500,600);
path.lineTo(600,500);
path.close();
canvas.drawPath(path, paint);
}
}
}
|
package domain;
import java.util.List;
public class StudentEntity {
private String name;
private List<GroupEntity> groups;
private List<String> phoneNumbers;
private List<ParentEntity> parents;
public StudentEntity(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package scl.oms.outagemap;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polygon;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OraclePreparedStatement;
import oracle.jdbc.OracleResultSet;
import oracle.jdbc.pool.OracleDataSource;
import oracle.spatial.geometry.JGeometry;
import oracle.sql.DATE;
import oracle.sql.STRUCT;
/**
*
* @author jstewart
*/
public class FeatureClassWriter {
public static final int WGS84_SRID = 4326; //WGS84
public static final int WSP83_SRID = 2926; //HARN/WO.WA-NF
private static OracleConnection targetGeoDBConn;
private static OracleConnection getDatabaseConnection() throws IOException, SQLException {
Logger log = Log.getLogger();
log.log(Level.FINEST, "Creating target Oracle geodatabase connection, using: {0} (environment={1})",
new Object[]{Config.INSTANCE.getGeoDbConn(), Config.INSTANCE.getEnvironmentLabel()});
OracleDataSource sourceODS = new OracleDataSource();
sourceODS.setURL("jdbc:oracle:thin:" + Config.INSTANCE.getGeoDbConn());
log.log(Level.FINEST, "Target OracleDataSource set to: {0} (environment={1})",
new Object[]{sourceODS.getURL(), Config.INSTANCE.getEnvironmentLabel()});
try {
return (OracleConnection) sourceODS.getConnection();
} catch (java.sql.SQLException e) {
log.severe(e.toString());
throw e;
} catch (Exception e) {
log.severe(e.toString());
throw e;
}
}
public static void writeFeatureClass(EventMap eventMap) throws IOException, SQLException, Exception {
targetGeoDBConn = FeatureClassWriter.getDatabaseConnection();
targetGeoDBConn.setDefaultExecuteBatch(Config.INSTANCE.getGeoDbBatchSize());
Logger log = Log.getLogger();
long geoDbUpdateStart = System.currentTimeMillis();
int eventsMapped = 0;
int polygonsMapped = 0;
int pointsMapped = 0;
// initiate iterator loop on events
Iterator<Long> eventKeyItr = eventMap.keySet().iterator();
Long eventKey;
String insertSql = "INSERT INTO " + Config.INSTANCE.getGeoDbFeatureClassTable()
+ "(SHAPE, EVENT_IDX) VALUES (?, ?)";
PreparedStatement insertStatement = targetGeoDBConn.prepareStatement(insertSql);
// iterate over events
while (eventKeyItr.hasNext()) {
eventKey = eventKeyItr.next();
// iterate over polygons for a single event
Polygon[] eventPolygons = null;
eventPolygons = eventMap.getEventPolygons(eventKey);
for (int eventPolygonIndex = 0; eventPolygonIndex < eventPolygons.length; eventPolygonIndex++) {
Polygon polygon = eventPolygons[eventPolygonIndex];
int coordsIndex = 0;
double[] coords = new double[polygon.getPointCount() * 2];
// iterate over points for a single polygon
for (int i = 0; i < polygon.getPointCount(); i++) {
Point point = polygon.getPoint(i);
coords[coordsIndex++] = point.getX();
coords[coordsIndex++] = point.getY();
pointsMapped++;
}
// the value '2' in the next line indicates 2D coordinates
JGeometry sdo_geometry = JGeometry.createLinearPolygon(coords, 2, FeatureClassWriter.WGS84_SRID);
STRUCT structuredObject = JGeometry.store(targetGeoDBConn, sdo_geometry);
log.log(Level.ALL, "STRUCT.dump() ==> {0}", structuredObject.dump());
((OraclePreparedStatement) insertStatement).setObject(1, structuredObject);
((OraclePreparedStatement) insertStatement).setLong(2, eventKey);
insertStatement.execute();
polygonsMapped++;
}
eventsMapped++;
}
insertStatement.close();
long geoDbUpdateTime = System.currentTimeMillis() - geoDbUpdateStart;
log.log(Level.INFO, "Geodatabase update metric: {0} event(s) mapped into {1} polygons with {2} polygon points in {3} milliseconds. (environment={4})",
new Object[]{eventsMapped, polygonsMapped, pointsMapped, geoDbUpdateTime, Config.INSTANCE.getEnvironmentLabel()});
FeatureClassWriter.closeDatabaseConnection();
}
/**
* Closes the database connection. Note that the database connection can not
* be closed while the OracleResultSet from .getCustomersOut () is or will
* be read.
*
* @throws IOException
*/
public static void closeDatabaseConnection() throws IOException {
try {
targetGeoDBConn.close();
} catch (SQLException ex) {
Logger log = Log.getLogger();
log.getLogger(OutageDataFactory.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
package kredivation.mrchai.component;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.StringRes;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import kredivation.mrchai.R;
/**
* Created by Natayan Semwal on 04-08-2017.
*/
public class ImageChoiceView extends LinearLayout {
private boolean isChecked;
protected TextView titleView,description;
protected ImageView imageView;
protected View view;
public ImageChoiceView(Context context) {
this(context, null, 0);
}
public ImageChoiceView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ImageChoiceView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.init();
}
protected void init() {
if (this.isInEditMode()) {
return;
}
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fn_img_choice_view, this, true);
titleView = (TextView) view.findViewById(R.id.title);
description= (TextView) view.findViewById(R.id.desription);
imageView = (ImageView) view.findViewById(R.id.bgimage);
}
public void setTitle(String title) {
if (this.titleView == null) {
return;
}
this.titleView.setText(title);
}
public void setDescription(String description) {
if (this.description == null) {
return;
}
this.titleView.setText(description);
}
public void setTitle(@StringRes int title) {
if (this.titleView == null) {
return;
}
this.titleView.setText(title);
}
public void setTitleColor(int colorId) {
if (this.titleView == null) {
return;
}
// int resId = FNUIUtil.getColor(getContext(), colorId);
if (colorId != 0) {
this.titleView.setTextColor(colorId);
} else {
this.titleView.setTextColor(colorId);
}
}
public void setImageDrawable(Drawable icon) {
if (this.imageView == null) {
return;
}
this.imageView.setVisibility(View.VISIBLE);
if (icon != null) {
this.imageView.setImageDrawable(icon);
}
}
public boolean isChecked() {
return isChecked;
}
public void setImageDrawable(int id) {
imageView.setImageResource(id);
}
}
|
//Jesus Rodriguez
//ITC 115 Winter 2020
// 2/09/2020
/* Write a method called season that takes as parameters two integers representing
* a month and day and returns a String indicating the season for that month and day.
* Assume that the month is specified as an integer between 1 and 12 (1 for January,
* 2 for February, and so on)and that the day of the month is a number between 1 and 31.
* If the date falls between 12/16 and 3/15 the method should return "winter".
* If the date falls between 3/16 and 6/15, the method should return "spring" .
* If the date falls between 6/16 and 9/15, the method should return "summer".
* If the date falls between 9/16 and 12/15, the method should return "fall".
*/
public class Season {
public static void main(String[] args) {
season(1, 16); //Calls the method season
}
public static void season(int month , int day) { // The method contains two parameter representing months and days
String months[] = {" ","January", "February","March", // An array containing the months of the year
"April", "May", "June", "July", "August", // It contains an empty space so the number enter
"September","October", "November", "December"}; // matches with month
if(month < 3 || (month ==3 && day <=15) || (month == 12 && day >= 16) ) { // conditions to print Winter
//It uses the array months and the parameter month to print the corresponding month.
System.out.print( months[month] + " " + day + " the season of the year is : Winter");
}
// conditions to print Spring
else if( month < 6 || (month == 6 && day <= 15) || (month == 3 && day >= 16 )) {
System.out.print( months[month] + " " + day + " the season of the year is: Spring");
}
// conditions to print Summer
else if ( month < 9 || (month ==9 && day <= 15) || (month == 6 && day >=16 )) {
System.out.print( months[month] +" " + day + " the season of the year is: Summer");
}
//if none of the conditions are true Fall will be printed.
else {
System.out.print( months[month] + " " + day + " the season of the year is: Fall");
}
}
}
|
package networking;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class EchoObjectServer extends EchoServer{
void processStream(InputStream is, OutputStream os)
{
System.out.println("EchoObjectServer.processStream begins");
ObjectInputStream input = null;
ObjectOutputStream output = null;
try
{
input = new ObjectInputStream(is);
output = new ObjectOutputStream(os);
UserInputs ui=(UserInputs)input.readObject();
while (ui != null)
{
System.out.println("EchoObjectServer read: "+ui);
output.writeObject(ui); // Echo data read
ui=(UserInputs)input.readObject();
}
}
catch (ClassNotFoundException e)
{
System.out.println("EchoObjectServer.processStream ClassNotFoundException: "+e);
}
catch (IOException e)
{
System.out.println("EchoObjectServer.processStream IOException: "+e);
}
finally
{
try
{ // I'm annoyed that I need try/catch for this
input.close();
output.close();
}
catch (IOException e)
{}
}
System.out.println("Exitting EchoObjectServer.processStream");
}
public static void main(String[] args) {
EchoObjectServer es = new EchoObjectServer();
es.monitorServer();
System.out.println("Exitting EchoServer");
}
}
|
package com.infoworks.lab.client.okhttp;
import com.infoworks.lab.exceptions.HttpInvocationException;
import com.infoworks.lab.rest.breaker.CircuitBreaker;
import com.infoworks.lab.rest.models.Message;
import com.infoworks.lab.rest.models.QueryParam;
import com.infoworks.lab.rest.template.HttpInteractor;
import com.infoworks.lab.rest.template.Invocation;
import com.infoworks.lab.rest.template.Route;
import com.it.soul.lab.sql.entity.EntityInterface;
import com.it.soul.lab.sql.query.models.Property;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class HttpTemplate<P extends com.infoworks.lab.rest.models.Response, C extends EntityInterface> extends HttpAbstractTemplate implements HttpInteractor<P,C> {
private Request.Builder target;
@Override
public Request.Builder getTarget() {
return target;
}
@Override
public void setTarget(Request.Builder target) {
this.target = target;
}
private String _domain;
private Class<P> inferredProduce;
private Class<C> inferredConsume;
private List<Property> properties = new ArrayList<>();
public HttpTemplate(){}
public HttpTemplate(Object... config){
try {
configure(config);
} catch (InstantiationException e) {
e.printStackTrace();
}
}
@Override @SuppressWarnings("Duplicates")
public void configure(Object... config) throws InstantiationException {
if (config == null) throw new InstantiationException();
for(Object o : config){
if (o instanceof URI){
_domain = ((URI)o).toString();
}else if(o instanceof Property) {
properties.add((Property) o);
}else if (o instanceof Class<?>){
if (inferredProduce == null) inferredProduce = (Class<P>) o;
else if (inferredConsume == null) inferredConsume = (Class<C>) o;
}
}
}
private Class<P> getInferredProduce(){
if (inferredProduce == null) inferredProduce = (Class<P>) com.infoworks.lab.rest.models.Response.class;
return inferredProduce;
}
private Class<? extends EntityInterface> getInferredConsume(){
if (inferredConsume == null) inferredConsume = (Class<C>) Message.class;
return inferredConsume;
}
public Property[] getProperties(){
return properties.toArray(new Property[0]);
}
@Override
protected synchronized String domain() throws MalformedURLException {
_domain = String.format("%s%s:%s%s", schema(), host(), port(), validatePaths(api()));
validateURL(_domain);
return _domain;
}
protected String schema(){
return "http://";
}
protected String host(){
return "localhost";
}
protected Integer port(){
return 8080;
}
protected String api(){
return "";
}
protected URL validateURL(String urlStr) throws MalformedURLException{
return new URL(urlStr);
}
protected String routePath() {
String routeTo = "/";
if (getClass().isAnnotationPresent(Route.class)){
routeTo = getClass().getAnnotation(Route.class).value();
}
return routeTo;
}
protected String urlencodedQueryParam(QueryParam...params){
if (params == null) return "";
StringBuffer buffer = new StringBuffer();
//Separate Paths:
List<String> pathsBag = new ArrayList<>();
for (QueryParam query : params) {
if (query.getValue() != null && !query.getValue().isEmpty()) {
continue;
}
pathsBag.add(query.getKey());
}
buffer.append(validatePaths(pathsBag.toArray(new String[0])));
//Incorporate QueryParams:
buffer.append("?");
for (QueryParam query : params){
if (query.getValue() == null || query.getValue().isEmpty()){
continue;
}
try {
buffer.append(query.getKey()
+ "="
+ URLEncoder.encode(query.getValue(), "UTF-8")
+ "&");
} catch (UnsupportedEncodingException e) {}
}
String value = buffer.toString();
value = value.substring(0, value.length()-1);
return value;
}
public P get(C consume , QueryParam...params) throws HttpInvocationException {
P produce = null;
Class<P> type = getInferredProduce();
try {
String queryParam = urlencodedQueryParam(params);
target = initializeTarget(queryParam);
Response response = null;
if (isSecure(consume)){
response = getAuthorizedJsonRequest(consume).get();
}else{
response = getJsonRequest().get();
}
produce = inflate(response, type);
}catch (IOException e) {
e.printStackTrace();
}
return produce;
}
public P post(C consume , String...paths) throws HttpInvocationException {
P produce = null;
Class<P> type = getInferredProduce();
try {
target = initializeTarget(paths);
Response response = null;
if (isSecure(consume)){
response = getAuthorizedJsonRequest(consume)
.post(consume, MediaType.parse("application/json;charset=utf-8"));
}else{
response = getJsonRequest().post(consume, MediaType.parse("application/json;charset=utf-8"));
}
produce = inflate(response, type);
}catch (IOException e) {
e.printStackTrace();
}
return produce;
}
public P put(C consume , String...paths) throws HttpInvocationException{
P produce = null;
Class<P> type = getInferredProduce();
try {
target = initializeTarget(paths);
Response response = null;
if (isSecure(consume)){
response = getAuthorizedJsonRequest(consume)
.put(consume, MediaType.parse("application/json;charset=utf-8"));
}else{
response = getJsonRequest().put(consume, MediaType.parse("application/json;charset=utf-8"));
}
produce = inflate(response, type);
}catch (IOException e) {
e.printStackTrace();
}
return produce;
}
public boolean delete(C consume, QueryParam...params) throws HttpInvocationException {
try {
String queryParam = urlencodedQueryParam(params);
target = initializeTarget(queryParam);
Response response = null;
if (isSecure(consume)){
response = getAuthorizedJsonRequest(consume)
.delete(consume, MediaType.parse("application/json;charset=utf-8"));
}else{
response = getJsonRequest().delete(consume, MediaType.parse("application/json;charset=utf-8"));
}
if (response.code() == 500) throw new HttpInvocationException("Internal Server Error!");
return response.code() == 200;
}catch (IOException e) {
e.printStackTrace();
}
return false;
}
@SuppressWarnings("Duplicates")
public void get(C consume
, List<QueryParam> query
, Consumer<P> consumer){
//Add to Queue
addConsumer(consumer);
submit(() -> {
P produce = null;
try {
QueryParam[] items = (query == null)
? new QueryParam[0]
: query.toArray(new QueryParam[0]);
produce = get(consume, items);
} catch (HttpInvocationException e) {
e.printStackTrace();
}
notify(produce);
});
}
@SuppressWarnings("Duplicates")
public void delete(C consume
, List<QueryParam> query
, Consumer<P> consumer){
//Add to Queue
addConsumer(consumer);
submit(() -> {
Boolean produce = null;
try {
QueryParam[] items = (query == null)
? new QueryParam[0]
: query.toArray(new QueryParam[0]);
produce = delete(consume, items);
} catch (HttpInvocationException e) {
e.printStackTrace();
}
notify(produce);
});
}
@Override
public <T> URI getUri(T... params) {
try {
if (params instanceof String[]){
return URI.create(resourcePath((String[]) params));
}else if (params instanceof QueryParam[]){
String queryParam = urlencodedQueryParam((QueryParam[])params);
return URI.create(resourcePath(queryParam));
}
} catch (MalformedURLException e) {}
return null;
}
@SuppressWarnings("Duplicates")
public void post(C consume
, List<String> paths
, Consumer<P> consumer){
//Add to queue
addConsumer(consumer);
submit(() -> {
P produce = null;
try {
String[] items = (paths == null)
? new String[0]
: paths.toArray(new String[0]);
produce = post(consume, items);
} catch (HttpInvocationException e) {
e.printStackTrace();
}
notify(produce);
});
}
@SuppressWarnings("Duplicates")
public void put(C consume
, List<String> paths
, Consumer<P> consumer){
//Add to queue
addConsumer(consumer);
submit(() -> {
P produce = null;
try {
String[] items = (paths == null)
? new String[0]
: paths.toArray(new String[0]);
produce = put(consume, items);
} catch (HttpInvocationException e) {
e.printStackTrace();
}
notify(produce);
});
}
protected <T extends Object> Response execute(EntityInterface consume, Invocation.Method method, T...params) throws MalformedURLException, HttpInvocationException {
if (params != null){
if (params instanceof String[]){
setTarget(initializeTarget((String[]) params));
}else if (params instanceof QueryParam[]){
String queryParam = urlencodedQueryParam((QueryParam[]) params);
setTarget(initializeTarget(queryParam));
}else{
//Means T...params are arbitrary value e.g. "/path-a", "path-b", QueryParam("offset","0"), QueryParam("limit","10") ... etc
//First: Separate Paths from mixed array:
List<String> paths = new ArrayList<>();
for (Object query : params) {
if (query instanceof String)
paths.add((String) query);
}
List<String> collector = new ArrayList<>(paths);
//Then: Separate QueryParam from mixed array:
List<QueryParam> queryParams = new ArrayList<>();
for (Object query : params) {
if (query instanceof QueryParam)
queryParams.add((QueryParam) query);
}
String queryParam = urlencodedQueryParam(queryParams.toArray(new QueryParam[0]));
collector.add(queryParam);
//Finally:
setTarget(initializeTarget(collector.toArray(new String[0])));
}
}else {
setTarget(initializeTarget());
}
//CircuitBreaker CODE:
Response response;
CircuitBreaker breaker = getCircuitBreaker(params);
Invocation invocation = isSecure(consume) ? getAuthorizedJsonRequest(consume) : getJsonRequest();
if (breaker != null) response = (Response) breaker.call(invocation, method, consume);
else response = callForwarding(invocation, method, consume);
//
return response;
}
protected <T extends Object> CircuitBreaker getCircuitBreaker(T...params){
//URI uri = getUri(params);//URI.create(resourcePath(params));
//CircuitBreaker breaker = GeoTrackerDroidKit.shared().getCircuitBreaker(uri, null);
CircuitBreaker breaker = null;
try {
breaker = CircuitBreaker.create(HttpCircuitBreaker.class);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return breaker;
}
@SuppressWarnings("Duplicates")
protected Response callForwarding(Invocation invocation, Invocation.Method method, EntityInterface consume) throws HttpInvocationException {
Response response = null;
switch (method){
case GET:
response = (Response) invocation.get();
break;
case POST:
response = (Response) invocation.post(consume, MediaType.parse("application/json;charset=utf-8"));
break;
case DELETE:
response = (Response) invocation.delete(consume, MediaType.parse("application/json;charset=utf-8"));
break;
case PUT:
response = (Response) invocation.put(consume, MediaType.parse("application/json;charset=utf-8"));
break;
}
return response;
}
}
|
package ui.system;
import controller.MainWindowController;
import javafx.scene.control.TextArea;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.loadui.testfx.GuiTest.find;
/**
* Created by Алексей on 06.01.2017.
*/
public class UserWorkingUiTesting extends UserWorkingTest {
@Test
public void fullWorkTest() {
openRegistryWindowAndTest();
registryTestUser();
authorizationTestUser();
assertEquals(MainWindowController.stage.getTitle(), "Добро пожаловать, Неизвестный");
writeTextArea();
integrationCipherEqualsTest();
}
private void registryTestUser() {
clickOn("#login").write("testUser");
clickOn("#password").write("1");
clickOn("#firstMethod").clickOn("побитовая перестановка");
clickOn("#signUp");
}
private void authorizationTestUser() {
clickOn(userName).write("testUser");
clickOn(password).write("1");
openMainWindowTest();
}
private void integrationCipherEqualsTest() {
clickOn("#encodeMenu").clickOn("#encodeMonoAlphabet")
.clickOn("#txtFieldDialog").write("24").clickOn("#okDialog");
clickOn("#decodeMenu").clickOn("#decodeBitRevers")
.clickOn("#txtFieldDialog").write("42351").clickOn("#okDialog");
clickOn("#encodeMenu").clickOn("#encodeBitRevers")
.clickOn("#txtFieldDialog").write("42351").clickOn("#okDialog");
clickOn("#decodeMenu").clickOn("#decodeMonoAlphabet")
.clickOn("#txtFieldDialog").write("24").clickOn("#okDialog");
TextArea textArea = find("#textArea");
Assert.assertEquals(textArea.getText(), actualText);
}
}
|
package cl.sportapp.evaluation.dao;
import cl.sportapp.evaluation.entitie.Paciente;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PacienteDao extends JpaRepository<Paciente, Long> {
}
|
package com.demo.nopcommerce.stepdefs;
import com.demo.nopcommerce.pages.CartPage;
import com.demo.nopcommerce.pages.HomePage;
import com.demo.nopcommerce.pages.LoginPage;
import cucumber.api.PendingException;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.junit.Assert;
public class LoginStepdefs {
@When("^I click on login link$")
public void iClickOnLoginLink() {
new HomePage().clickOnLoginLink();
}
@Then("^I should be navigate to login page successfully$")
public void iShouldBeNavigateToLoginPageSuccessfully() {
new LoginPage().getWelcomeText();
}
@And("^I enter email address \"([^\"]*)\"$")
public void iEnterEmailAddress(String email) {
new LoginPage().enterEmailId(email);
}
@And("^I click on login button$")
public void iClickOnLoginButton() {
new LoginPage().clickOnLoginButton();
}
@Then("^I should get en error message$")
public void iShouldGetEnErrorMessage() {
Assert.assertEquals("Login was unsuccessful. Please correct the errors and try again.\n" +
"No customer account found",new LoginPage().VerifyErrorMessage());
}
@And("^I click on log out button$")
public void iClickOnLogOutButton() {
new CartPage().clickOnLogOut();
}
@Then("^I should be able to login successfully$")
public void iShouldBeAbleToLoginSuccessfully() {
Assert.assertEquals("Welcome to our store",new HomePage().VerifyLoginSuccessfully());
}
}
|
package asa.client;
import asa.client.DTO.GameData;
import asa.client.resources.Resource;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.media.Buffer;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Format;
import javax.media.Manager;
import javax.media.Player;
import javax.media.control.FormatControl;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import org.apache.log4j.Logger;
import org.lwjgl.util.Dimension;
import org.newdawn.slick.Animation;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.opengl.EmptyImageData;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.util.BufferedImageUtil;
public class PhotoState extends ArduinoGameState implements ImageObserver{
private StateBasedGame stateBasedGame;
private ServerAdapter server;
private GameData gameData;
private Dimension center;
private Logger logger = Logger.getLogger(this.getClass());
private List<WheelOptionYesNo> wheelOptions = new ArrayList<WheelOptionYesNo>();
private UnicodeFont fontBlack;
private Timer liveFeed;
private boolean waitingForButton;
private boolean webcamAvailable = false;
private boolean updateCamera = false;
private boolean makePhoto = false;
private boolean drawCountdown = false;
private Image tandwiel1;
private Image tandwiel2;
private Image background;
private Image spinner;
private Image background_spinner;
private Image background_spinner_half;
private Image spinneroverlay;
private Image webcamFeed;
private Image countdown;
private Image selectImage;
private Image choise;
private java.awt.Image awtFrame;
private BufferedImage baseImage;
private Animation lens;
private Texture texture = null;
private int mode = 1;
private int targetrotation = 0;
private int selectedOption = 0;
private int tandwielOffset = 30;
private int lastHighscoreId;
private int secondsIdle;
private Timer clock;
private float rotation = 0;
private float rotationDelta = 0;
private double rotationEase = 5.0;
private CaptureDeviceInfo webcam;
private Player webcamPlayer;
private FrameGrabbingControl frameGrabber;
private Buffer buffer;
public PhotoState(int stateID, ServerAdapter server, GameData gameData) {
super(stateID);
this.server = server;
this.gameData = gameData;
wheelOptions.add(new WheelOptionYesNo("Ja", Resource.getPath(Resource.ICON_YES), true));
wheelOptions.add(new WheelOptionYesNo("Nee", Resource.getPath(Resource.ICON_NO), false));
initWebcam();
}
@Override
public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException {
this.stateBasedGame = stateBasedGame;
center = new Dimension(AsaGame.SOURCE_RESOLUTION.width / 2 - 100, AsaGame.SOURCE_RESOLUTION.height / 2);
resetGame();
tandwiel1 = new Image(Resource.getPath(Resource.TANDWIEL5));
tandwiel2 = new Image(Resource.getPath(Resource.TANDWIEL6));
spinner = new Image(Resource.getPath(Resource.SPINNER));
spinneroverlay = new Image(Resource.getPath(Resource.SPINNER_OVERLAY));
background_spinner = new Image(Resource.getPath(Resource.BACKGROUND_SPINNER));
background_spinner_half = new Image(Resource.getPath(Resource.BACKGROUND_SPINNER_HALF));
background_spinner_half.setAlpha(0.7f);
background = new Image(Resource.getPath(Resource.GAME_BACKGROUND));
selectImage = new Image(Resource.getPath(Resource.SAVE_SCORE));
choise = new Image(Resource.getPath(Resource.MAKE_YOUR_CHOISE));
fontBlack = Resource.getFont(Resource.FONT_SANCHEZ, 30, Color.BLACK);
lens = new Animation();
lens.setLooping(false);
for (int i = 0; i < 33; i++) {
if ((i + "").length() == 1) {
lens.addFrame(new Image(Resource.getPath("LENS/lens1_0000" + i + ".png")), 550 / 33);
} else if ((i + "").length() == 2) {
lens.addFrame(new Image(Resource.getPath("LENS/lens1_000" + i + ".png")), 550 / 33);
}
}
lens.stop();
}
@Override
public void enter(GameContainer gameContainer, StateBasedGame stateBasedGame) {
checkWebcam();
calculateSelected();
addListeners(stateBasedGame);
ActivateButton();
liveFeed = new Timer();
liveFeed.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
updateCamera = true;
}
}, 0, 250);
clock = new Timer();
clock.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
secondsIdle++;
if (secondsIdle > 120)
{
secondsIdle = 0;
enterHighscoreState();
}
}
}, 0, 1000);
}
@Override
public void leave(GameContainer container, StateBasedGame game) throws SlickException {
resetGame();
clock.cancel();
}
@Override
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException {
background.draw(0, 0);
tandwiel1.draw(-tandwiel1.getWidth() / 2, AsaGame.SOURCE_RESOLUTION.height / 2 - tandwiel1.getHeight() / 2);
tandwiel2.draw(tandwiel1.getWidth() / 2 - tandwielOffset - 40, AsaGame.SOURCE_RESOLUTION.height / 2 - tandwiel2.getHeight());
graphics.setFont(fontBlack);
if (baseImage != null) {
webcamFeed.getSubImage(80, 0, 480, 480).draw(center.getWidth()-((500)/2), center.getHeight()-(500/2), 500, 500);
background_spinner_half.draw(center.getWidth() - background_spinner.getWidth() / 2, center.getHeight() + 45);
}
else {
background_spinner.draw(center.getWidth() - background_spinner.getWidth() / 2, center.getHeight() - background_spinner.getHeight() / 2);
}
if (mode == 1) {
spinner.draw(center.getWidth() - spinner.getWidth() / 2, center.getHeight() - spinner.getHeight() / 2);
spinneroverlay.draw(center.getWidth() - spinner.getWidth() / 2, center.getHeight() - spinner.getHeight() / 2);
selectImage.draw(center.getWidth()/2-20, 60);
choise.draw(choise.getWidth()*0.15f, center.getHeight()*2 - choise.getHeight()*1.6f, pulseScale);
for (int i = 0; i < wheelOptions.size(); i++) {
float offsetDegree = 360 / wheelOptions.size();
float degrees = (270 + ((rotation + rotationDelta) % 360 + offsetDegree * i) % 360) % 360;
if (degrees < 0) {
degrees = degrees + 360;
}
float rad = (float) (degrees * (Math.PI / 180));
float radius = 313;
float x = (float) (center.getWidth() + radius * Math.cos(rad));
float y = (float) (center.getHeight() + radius * Math.sin(rad));
WheelOptionYesNo option = wheelOptions.get(i);
Image optionIcon = option.getIcon();
float biggerThanDegrees = 270 + (offsetDegree / 2);
if (biggerThanDegrees > 360) {
biggerThanDegrees = biggerThanDegrees - 360;
}
if (degrees >= 270 - (offsetDegree / 2) && degrees < biggerThanDegrees) {
x = x - (float) (optionIcon.getWidth() * 1.3 / 2);
y = y - (float) (optionIcon.getHeight() * 1.3 / 2);
option.getIcon().draw(x, y, (float) 1.3);
} else {
x = x - (float) (optionIcon.getWidth() * 1 / 2);
y = y - (float) (optionIcon.getHeight() * 1 / 2);
option.getIcon().draw(x, y);
}
if (degrees >= 270 - (offsetDegree / 2) && degrees < biggerThanDegrees) {
selectedOption = i;
}
}
} else {
lens.draw(center.getWidth() - (550 / 2), center.getHeight() - (550 / 2));
spinner.draw(center.getWidth() - spinner.getWidth() / 2, center.getHeight() - spinner.getHeight() / 2);
spinneroverlay.draw(center.getWidth() - spinner.getWidth() / 2, center.getHeight() - spinner.getHeight() / 2);
if (drawCountdown) {
countdown.draw(center.getWidth()-75, center.getHeight() + 75, 150, 150);
}
}
}
@Override
public void update(GameContainer gameContainer, StateBasedGame stateBasedGame, int delta) throws SlickException {
super.update(gameContainer, stateBasedGame, delta);
rotation += (targetrotation - rotation) / rotationEase;
tandwiel1.setRotation(rotation);
tandwiel2.setRotation((float) ((float) -(rotation * 1.818181818181818) + 16.36363636363636));
spinner.setRotation(rotation);
if (frameGrabber != null && updateCamera) {
updateCamera = false;
buffer = frameGrabber.grabFrame();
awtFrame = new BufferToImage((VideoFormat) buffer.getFormat()).createImage(buffer);
BufferedImage bufferedImage = new BufferedImage(awtFrame.getWidth(null), awtFrame.getHeight(null), BufferedImage.TYPE_INT_RGB);
bufferedImage.createGraphics().drawImage(awtFrame, 0, 0, this);
baseImage = bufferedImage;
try{
texture = BufferedImageUtil.getTexture("", baseImage);
webcamFeed.setTexture(texture);
} catch (IOException e){
logger.error(e);
}
}
calculatePulse();
}
private void MakePhoto() {
makePhoto = true;
mode = 2;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
drawCountdown = true;
setCountdownImage(3);
}
}, 1000);
timer.schedule(new TimerTask() {
@Override
public void run() {
setCountdownImage(2);
}
}, 2000);
timer.schedule(new TimerTask() {
@Override
public void run() {
setCountdownImage(1);
}
}, 3000);
timer.schedule(new TimerTask() {
@Override
public void run() {
liveFeed.cancel();
updateCamera = true;
drawCountdown = false;
lens.restart();
}
}, 4000);
timer.schedule(new TimerTask() {
@Override
public void run() {
SaveImage();
stateBasedGame.enterState(AsaGame.HIGHSCORESTATE, AsaGame.FADEOUT, AsaGame.FADEIN);
}
}, 7000);
}
public void SaveImage() {
if (makePhoto) {
lastHighscoreId = server.addHighscore(gameData.getPlayerScore(), "yes");
try {
File f = new File(lastHighscoreId + ".png");
ImageIO.write(baseImage, "png", f);
} catch (IOException ex) {
System.out.println("fail to save image:" + ex.getMessage());
}
}
else{
if (liveFeed != null)
{
liveFeed.cancel();
}
lastHighscoreId = server.addHighscore(gameData.getPlayerScore(), "no");
}
gameData.setLastHighscoreId(lastHighscoreId);
}
public void ActivateButton() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
waitingForButton = true;
}
}, 500);
}
private void calculateSelected() {
int selectionAreaSize = 360 / wheelOptions.size();
for (int i = 0; i < wheelOptions.size(); i++) {
int min = i * selectionAreaSize;
int max = (i + 1) * selectionAreaSize;
System.out.println(i + ": " + min + ", " + max);
if (min <= 0 && max > 0) {
selectedOption = i;
System.out.println("Initial selected option: " + i);
break;
}
}
}
@Override
public boolean imageUpdate(java.awt.Image img, int infoflags, int x, int y, int width, int height) {
throw new UnsupportedOperationException("Not supported yet.");
}
private void addListeners(final StateBasedGame stateBasedGame) {
arduino.addListener(new ArduinoAdapter() {
@Override
public void wheelEvent(int direction, int speed) {
if (direction == 1) {
targetrotation += speed * 1.145;
} else {
targetrotation -= speed * 1.145;
}
secondsIdle = 0;
}
@Override
public void buttonEvent() {
if (waitingForButton) {
waitingForButton = !waitingForButton;
if (mode == 1) {
WheelOptionYesNo selected = wheelOptions.get(selectedOption);
if (selected.getValue()) {
MakePhoto();
} else {
SaveImage();
stateBasedGame.enterState(AsaGame.HIGHSCORESTATE, AsaGame.FADEOUT, AsaGame.FADEIN);
}
}
}
}
});
}
private void resetGame() {
mode = 1;
makePhoto = false;
arduino.removeAllListeners();
baseImage = null;
texture = null;
drawCountdown = false;
liveFeed = null;
webcamFeed = new Image(new EmptyImageData(1, 1));
countdown = new Image(new EmptyImageData(1,1));
}
private void initWebcam() {
Vector videoDevices = CaptureDeviceManager.getDeviceList(new VideoFormat(null));
if (videoDevices.size()>0){
webcam = (CaptureDeviceInfo) videoDevices.get(0);
Format[] formats = webcam.getFormats();
Format selectedFormat = null;
try {
for(Format f : formats) {
if(f.toString().contains("640") && f.toString().contains("480")) {
selectedFormat = f;
break;
}
}
}
catch(Exception e)
{
logger.error("Failed to get required webcam resolution (640x480). Taking default format: " + e.getMessage());
selectedFormat = formats[0];
}
try {
webcamPlayer = Manager.createRealizedPlayer(webcam.getLocator());
FormatControl fc = (FormatControl)webcamPlayer.getControl("javax.media.control.FormatControl");
System.out.println("Selected webcam format: " + selectedFormat.toString());
fc.setFormat(selectedFormat);
webcamPlayer.start();
webcamAvailable = true;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
frameGrabber = (FrameGrabbingControl) webcamPlayer.getControl("javax.media.control.FrameGrabbingControl");
}
}, 2500);
} catch (Exception e) {
logger.error("Failed to get webcam feed: " + e.getMessage());
}
} else {
logger.error("No webcam available");
}
}
private void checkWebcam() {
Vector videoDevices = CaptureDeviceManager.getDeviceList(new VideoFormat(null));
if (videoDevices.size()>0){
if (webcamAvailable == false){
initWebcam();
}
} else {
webcamAvailable = false;
}
if (!webcamAvailable){
SaveImage();
stateBasedGame.enterState(AsaGame.HIGHSCORESTATE, AsaGame.FADEOUT, AsaGame.FADEIN);
}
}
private void setCountdownImage(int count)
{
try {
countdown = new Image(Resource.getPath(count + ".png"));
} catch (SlickException ex) {
logger.error("Could not get countdownImage " + count + ".png: " + ex.getMessage());
}
}
private void enterHighscoreState() {
stateBasedGame.enterState(AsaGame.INFOSTATE, AsaGame.FADEOUT, AsaGame.FADEIN);
}
}
|
package com.intel.realsense.librealsense;
public class FrameSet extends LrsClass {
private int mSize = 0;
public FrameSet(long handle) {
mHandle = handle;
mSize = nFrameCount(mHandle);
}
public Frame first(StreamType type) {
return first(type, StreamFormat.ANY);
}
public Frame first(StreamType type, StreamFormat format) {
for(int i = 0; i < mSize; i++) {
Frame f = new Frame(nExtractFrame(mHandle, i));
try(StreamProfile p = f.getProfile()){
if(p.getType() == type && (p.getFormat() == format || format == StreamFormat.ANY))
return f;
}
f.close();
}
return null;
}
public void foreach(FrameCallback callback) {
for(int i = 0; i < mSize; i++) {
try(Frame f = new Frame(nExtractFrame(mHandle, i))){
callback.onFrame(f);
}
}
}
public int getSize(){ return mSize; }
public FrameSet applyFilter(FilterInterface filter) {
return filter.process(this);
}
public FrameSet releaseWith(FrameReleaser frameReleaser){
frameReleaser.addFrame(this);
return this;
}
@Override
public void close() {
nRelease(mHandle);
}
@Override
public FrameSet clone() {
FrameSet rv = new FrameSet(mHandle);
nAddRef(mHandle);
return rv;
}
private static native void nAddRef(long handle);
private static native void nRelease(long handle);
private static native long nExtractFrame(long handle, int index);
private static native int nFrameCount(long handle);
}
|
package com.utils.streamjava7.classes;
import com.utils.streamjava7.collection.Pipeline;
import com.utils.streamjava7.interfaces.Function;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.*;
public class ParallelStream<T> extends Stream<T> {
private static final Integer chunkSize = 4;
private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(chunkSize);
private Stream<Stream<T>> chunked;
private ParallelStream(Collection<T> coll) {
super(coll);
chunked = super.split(chunkSize);
}
public ParallelStream(Pipeline<T> pipeline) {
super(pipeline);
this.chunked = super.split(chunkSize);
}
public static <T> ParallelStream<T> of(Collection<T> coll) {
return new ParallelStream<>(coll);
}
@Override
public <U> Stream<U> map(final Function<T, U> mapper) {
try {
final ArrayList<Callable<Stream<U>>> collect = chunked.map(new Function<Stream<T>, Callable<Stream<U>>>() {
@Override
public Callable<Stream<U>> apply(final Stream<T> start) {
return new Callable<Stream<U>>() {
@Override
public Stream<U> call() throws Exception {
return start.map(mapper);
}
};
}
}).collect(Collectors.toList(new ArrayList<Callable<Stream<U>>>()));
return Stream.of(EXECUTOR.invokeAll(collect)).flatMap(new Function<Future<Stream<U>>, Stream<U>>() {
@Override
public Stream<U> apply(Future<Stream<U>> start) {
try {
return start.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
|
/**
*
* @author Shashwat Koranne
*
*/
public class InsertionSort {
public static int[] insertSort(int[] array) {
int length = array.length;
for (int i = 1; i < length; i++) {
for (int j = i; j > 0; j--) {
if (array[j] >= array[j-1]) {
break;
} else {
array = swap(array, j, j-1);
}
}
}
return array;
}
public static int[] swap(int[] array, int a, int b) {
int temp = array[b];
array[b] = array[a];
array[a] = temp;
return array;
}
public static void main(String[] args) {
int[] array = {5, 2, 1, 4, 3, 6};
int[] sortedArray = insertSort(array);
for (int i = 0; i < array.length; i++) {
System.out.println(sortedArray[i]);
}
}
}
|
package com.kh.jd.account;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class AccountController {
@Autowired
StudentService sService;
@Autowired
TeacherService tService;
@Autowired
ManagerService mService;
private static final Logger logger = LoggerFactory.getLogger(SignUpController.class);
@RequestMapping("login")
public String login() {
return "account/login";
}
@RequestMapping(value = "loginCheck", method = RequestMethod.POST)
public String loginCheck(Student sDto, Teacher tDto, HttpSession session, HttpServletRequest request,
@RequestParam(name = "loginSelect") String check, Model model) {
System.out.println(check);
boolean result = false;
int accept = 0;
String teacher_id = request.getParameter("id");
if (check == "student" || check.equals("student")) {
result = sService.loginCheck(sDto, session);
} else if(check =="teacher" || check.equals("teacher")){
result = tService.loginCheck(tDto, session);
if(result == true) {
accept = tService.acceptCheck(teacher_id);
}else {
model.addAttribute("msg", "실패");
return "account/login";
}
}
if (result == true) {
System.out.println(result);
model.addAttribute("msg", "성공");
session = request.getSession();
if (check == "student" || check.equals("student")) {
Student list = new Student();
list = sService.infoStudent(sDto);
System.out.println(list);
request.getSession().setAttribute("DTO", list);
request.getSession().setAttribute("student_number", list.getStudent_number());
} else {
if (accept == 1) {
Teacher list = new Teacher();
list = tService.infoTeacher(tDto);
System.out.println(list);
request.getSession().setAttribute("DTO", list);
request.getSession().setAttribute("teacher_number", list.getTeacher_number());
} else {
System.out.println(accept);
model.addAttribute("msg", "승인대기");
tService.logout(session);
return "account/login";
}
}
} else {
System.out.println(result);
model.addAttribute("msg", "실패");
return "account/login";
}
return "common/main";
}
@RequestMapping("logout")
public ModelAndView logout(HttpSession session) {
sService.logout(session);
ModelAndView mav = new ModelAndView();
mav.setViewName("common/main");
mav.addObject("msg", "logout");
return mav;
}
@RequestMapping("managerLoginJDEDU")
public String managerLogin() {
return "account/managerLogin";
}
@RequestMapping(value = "managerIdCheck", method = RequestMethod.GET)
@ResponseBody
public String managerIdCheck(HttpServletRequest request) {
String manager_id = request.getParameter("id");
System.out.println(manager_id);
int result = mService.idCheck(manager_id);
return Integer.toString(result);
}
@RequestMapping(value = "managerLoginCheck", method = RequestMethod.POST)
public String loginCheck(Manager aDto, HttpSession session, HttpServletRequest request, Model model) {
boolean result = false;
result = mService.loginCheck(aDto, session);
System.out.println(result);
if (result == true) {
System.out.println(result);
model.addAttribute("msg", "성공");
session = request.getSession();
Manager list = new Manager();
list = mService.infoManager(aDto);
System.out.println(list);
request.getSession().setAttribute("DTO", list);
request.getSession().setAttribute("manager_number", list.getManager_number());
} else {
System.out.println(result);
model.addAttribute("msg", "실패");
return "account/managerLogin";
}
return "common/main";
}
@RequestMapping(value = "acceptTeacherForm")
public String teacherList(Model model) {
List<Teacher> list = mService.teacherList();
model.addAttribute("list", list);
return "account/acceptPage";
}
@RequestMapping(value="denyTeacher", method = RequestMethod.POST)
public String denyTeacher(Teacher teacherVO) {
String teacher_id = teacherVO.getId();
mService.denyTeacher(teacher_id);
return "redirect:/acceptTeacherForm";
}
@RequestMapping(value = "acceptTeacher", method = RequestMethod.POST)
public String acceptTeacher(Teacher teacherVO) {
String teacher_id = teacherVO.getId();
mService.acceptTeacher(teacher_id);
return "redirect:/acceptTeacherForm";
}
}
|
package e.eric.messengerv3;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
public class Contacts extends AppCompatActivity {
private static final String TAG = "Contacts";
private ArrayList<String> mImages = new ArrayList<>();
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mTexts = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
Log.d(TAG, "onCreate");
initImageBitmaps();
}
private void initImageBitmaps() {
Log.d(TAG, "initImageBitmaps");
// Access FireBase here
initRecyclerView();
}
private void initRecyclerView() {
Log.d(TAG, "initRecyclerView");
RecyclerView recyclerView = findViewById(R.id.recycler_view);
ContactsRecyclerViewAdapter adapter = new ContactsRecyclerViewAdapter(mImages, mNames, mTexts, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
|
package interview.huawei.B;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.sun.scenario.effect.impl.state.AccessHelper;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] input = sc.nextLine().split(" ");
String key = input[0];
String[] msgs = input[1].split("],");
int cnt = 0;
for(int i = 0; i < msgs.length; i++) {
// msg: read[addr=0x17,mask=0xff,val=0x7
if(i == msgs.length - 1) msgs[i] = msgs[i].substring(0, msgs[i].length()-1);
if(match(key, msgs[i])) cnt++;
}
if(cnt == 0) System.out.println("FAIL");
}
public static boolean match(String target, String msg) {
// 检查title
String title = msg.substring(0, msg.indexOf('['));
if(!title.equals(target)) return false;
// 检查三个值
msg = msg.substring(msg.indexOf('[') + 1);
String[] words = msg.split(",");
if(words.length != 3) return false; // 待定
// 记录三个值是否符合标准
Map<String, String> flag = new HashMap<>();
for(int i = 0; i < words.length; i++) {
String key = words[i].split("=")[0];
String value = words[i].split("=")[1];
if(key.equals("addr") && check(value)) {
flag.put("addr", value);
} else if(key.equals("mask") && check(value)) {
flag.put("mask", value);
} else if(key.equals("val") && check(value)) {
flag.put("val", value);
}
}
if(flag.size() != 3) return false;
System.out.println(flag.get("addr") + " " + flag.get("mask") + " " + flag.get("val"));
return true;
}
// 检查十六进制,value:0xf0
public static boolean check(String value) {
// 检查头部
String tou = value.substring(0, 2);
if(!tou.equals("0x") && !tou.equals("0X")) return false;
// 检查数字
char[] tails = value.substring(2).toCharArray();
if(tails.length == 0) return false;
for (char c : tails) {
if(!(c >= 'a' && c <= 'f' || c >= '0' && c <= '9' || c >= 'A' && c <= 'F')) return false;
}
return true;
}
}
|
package core.exception;
/**
* @框架唯一的升级和技术支持地址:https://item.taobao.com/item.htm?spm=a230r.7195193.1997079397.8.wNJFq2&id=551763724593&abbucket=20
*/
public interface ExceptionCode {
public String getCode();
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.result.method.annotation;
import java.time.Duration;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.testfixture.method.ResolvableMethod;
import org.springframework.web.testfixture.server.MockServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest.get;
/**
* Unit tests for {@link ModelMethodArgumentResolver}.
*
* @author Rossen Stoyanchev
*/
public class ModelMethodArgumentResolverTests {
private final ModelMethodArgumentResolver resolver =
new ModelMethodArgumentResolver(ReactiveAdapterRegistry.getSharedInstance());
private final ServerWebExchange exchange = MockServerWebExchange.from(get("/"));
private final ResolvableMethod resolvable = ResolvableMethod.on(getClass()).named("handle").build();
@Test
public void supportsParameter() {
assertThat(this.resolver.supportsParameter(this.resolvable.arg(Model.class))).isTrue();
assertThat(this.resolver.supportsParameter(this.resolvable.arg(ModelMap.class))).isTrue();
assertThat(this.resolver.supportsParameter(
this.resolvable.annotNotPresent().arg(Map.class, String.class, Object.class))).isTrue();
assertThat(this.resolver.supportsParameter(this.resolvable.arg(Object.class))).isFalse();
assertThat(this.resolver.supportsParameter(
this.resolvable.annotPresent(RequestBody.class).arg(Map.class, String.class, Object.class))).isFalse();
}
@Test
public void resolveArgument() {
testResolveArgument(this.resolvable.arg(Model.class));
testResolveArgument(this.resolvable.annotNotPresent().arg(Map.class, String.class, Object.class));
testResolveArgument(this.resolvable.arg(ModelMap.class));
}
private void testResolveArgument(MethodParameter parameter) {
BindingContext context = new BindingContext();
Object result = this.resolver.resolveArgument(parameter, context, this.exchange).block(Duration.ZERO);
assertThat(result).isSameAs(context.getModel());
}
@SuppressWarnings("unused")
void handle(
Model model,
Map<String, Object> map,
@RequestBody Map<String, Object> annotatedMap,
ModelMap modelMap,
Object object) {}
}
|
import java.util.Scanner;
/*Problem Statement:
Create a two dimensional character array which will accept only two characters X or O. populate
array with different combinations of X and O characters. If Same character appears at either
diagonal position or in the same line, return that character.
For eg.
X O O
O X O
O O X
X appears at diagonal position hence return X.*/
public class Array2D {
static void input(String[][] arr) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter X or O");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
arr[i][j]=sc.next();
System.out.println();
}
sc.close();
}
static void display(String[][] arr) {
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
System.out.print(arr[i][j]+" ");
System.out.println();
}
}
static String check(String[][] arr)
{
//rows
int sum=0;
for(int i=0;i<3;i++)
{
int val;
sum=0;
for(int j=0;j<3;j++)
{
//row-wise
if(arr[i][j] =="X")
val=1;
else
val=0;
sum+=val;
}
}
if(sum==3)
return "X";
else
return "O";
}
public static void main(String[] args) {
String[][] arr = new String[3][3];
input(arr);
display(arr);
String character =check(arr);
System.out.println("WINNER "+character);
}
}
|
package com.project.repos;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.project.entities.Category;
import com.project.entities.Product;
import com.project.entities.Provider;
import com.project.entities.Status;
//data access object interface for product
//implementation provided by spring
public interface ProductRepository extends MongoRepository<Product, String> {
//custom methods, implemented by spring, using reflection
public Product findByName(String name);
public List<Product> findAllByCategory(Category category);
public List<Product> findAllByProvider(Provider provider);
public List<Product> findAllByCategoryAndProductStatus(Category category, Status status);
public List<Product> findAllByProviderAndProductStatus(Provider provider, Status status);
public List<Product> findByProductStatus(Status status);
public List<Product> findByNameLikeAndProductStatus(String likeName, Status status);
public List<Product> findByNameLike(String likeName);
}
|
package com.tsuro.utils;
import com.tsuro.board.IBoard;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import lombok.experimental.UtilityClass;
/**
* Contains utility functions for {@link IBoard}.
*/
@UtilityClass
public class BoardUtils {
/**
* Gets all of the {@link Point}s on the edge of the board.
*/
public static List<Point> getEdgePoints(IBoard board) {
List<Point> returanble = new ArrayList<>();
for (int x = 1; x < board.getSize().width; x++) {
returanble.add(new Point(x, 0));
}
for (int y = 1; y < board.getSize().getHeight(); y++) {
returanble.add(new Point(board.getSize().width - 1, y));
}
for (int x = board.getSize().width - 2; x >= 0; x--) {
returanble.add(new Point(x, board.getSize().height - 1));
}
for (int y = board.getSize().height - 2; y > 0; y--) {
returanble.add(new Point(0, y));
}
return returanble;
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* 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.atlassian.connector.intellij.bamboo;
import com.atlassian.connector.cfg.ProjectCfgManager;
import com.atlassian.theplugin.commons.SchedulableChecker;
import com.atlassian.theplugin.commons.UIActionScheduler;
import com.atlassian.theplugin.commons.bamboo.BambooServerData;
import com.atlassian.theplugin.commons.configuration.PluginConfiguration;
import com.atlassian.theplugin.commons.exception.ServerPasswordNotProvidedException;
import com.atlassian.theplugin.commons.util.DateUtil;
import com.atlassian.theplugin.commons.util.LoggerImpl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
/**
* IDEA-specific class that uses to retrieve builds info and
* passes raw data to configured {@link BambooStatusListener}s.<p>
* <p/>
* Intended to be triggered by a {@link java.util.Timer} through the {@link #newTimerTask()}.<p>
* <p/>
* Thread safe.
*/
public final class BambooStatusChecker implements SchedulableChecker {
private final List<BambooStatusListener> listenerList = new ArrayList<BambooStatusListener>();
private UIActionScheduler actionScheduler;
private static Date lastActionRun = new Date();
private static SimpleDateFormat dateFormat = new SimpleDateFormat("H:mm:ss:SSS");
private static StringBuffer sb = new StringBuffer();
private static final String NAME = "Atlassian Bamboo checker";
// private BambooCfgManager bambooCfgManager;
private final IntelliJBambooServerFacade bambooServerFacade;
private ProjectCfgManager cfgManager;
private final PluginConfiguration pluginConfiguration;
private final Runnable missingPasswordHandler;
public void setActionScheduler(UIActionScheduler actionScheduler) {
this.actionScheduler = actionScheduler;
}
public BambooStatusChecker(UIActionScheduler actionScheduler,
ProjectCfgManager cfgManager, final PluginConfiguration pluginConfiguration,
Runnable missingPasswordHandler, final IntelliJBambooServerFacade facade) {
this.actionScheduler = actionScheduler;
this.cfgManager = cfgManager;
this.pluginConfiguration = pluginConfiguration;
this.missingPasswordHandler = missingPasswordHandler;
this.bambooServerFacade = facade;
}
public void registerListener(BambooStatusListener listener) {
synchronized (listenerList) {
listenerList.add(listener);
}
}
public void unregisterListener(BambooStatusListener listener) {
synchronized (listenerList) {
listenerList.remove(listener);
}
}
/**
* DO NOT use that method in 'dispatching thread' of IDEA. It can block GUI for several seconds.
*/
private void doRun() {
try {
final List<Exception> generalProblems = new ArrayList<Exception>();
// collect build info from each server
final Collection<BambooBuildAdapter> newServerBuildsStatus = new ArrayList<BambooBuildAdapter>();
for (BambooServerData server : cfgManager.getAllEnabledBambooServerss()) {
try {
Date newRun = new Date();
sb.delete(0, sb.length());
sb.append(server.getName()).append(":");
sb.append("last result time: ").append(dateFormat.format(lastActionRun));
sb.append(" current run time : ").append(dateFormat.format(newRun));
sb.append(" time difference: ")
.append(dateFormat.format((newRun.getTime() - lastActionRun.getTime())));
LoggerImpl.getInstance().debug(sb.toString());
newServerBuildsStatus.addAll(bambooServerFacade.getSubscribedPlansResults(server, server.getPlans(),
server.isUseFavourites(), server.isShowBranches(), server.isMyBranchesOnly(), server.getTimezoneOffset()));
lastActionRun = newRun;
} catch (ServerPasswordNotProvidedException exception) {
actionScheduler.invokeLater(missingPasswordHandler);
generalProblems.add(exception);
}
}
// dispatch to the listeners
actionScheduler.invokeLater(new Runnable() {
public void run() {
synchronized (listenerList) {
for (BambooStatusListener listener : listenerList) {
listener.updateBuildStatuses(newServerBuildsStatus, generalProblems);
}
}
}
});
} catch (Throwable t) {
LoggerImpl.getInstance().info(t);
}
}
/**
* Create a new instance of {@link java.util.TimerTask} for {@link java.util.Timer} re-scheduling purposes.
*
* @return new instance of TimerTask
*/
public TimerTask newTimerTask() {
return new TimerTask() {
@Override
public void run() {
doRun();
}
};
}
public boolean canSchedule() {
return cfgManager != null && !cfgManager.getAllEnabledBambooServerss().isEmpty();
}
public long getInterval() {
return pluginConfiguration.getBambooConfigurationData().getPollTime()
* DateUtil.SECONDS_IN_MINUTE * DateUtil.MILISECONDS_IN_SECOND;
}
/**
* Resets listeners (sets them to default state)
* Listeners should be set to default state if the checker topic list is empty
*/
public void resetListenersState() {
for (BambooStatusListener listener : listenerList) {
listener.resetState();
}
}
public String getName() {
return NAME;
}
// only for unit tests
public void updateConfiguration(ProjectCfgManager theCfgManager) {
cfgManager = theCfgManager;
}
}
|
package crushstudio.crush_studio.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import crushstudio.crush_studio.DTO.UserDTO;
import crushstudio.crush_studio.config.mapper.Mapper;
import crushstudio.crush_studio.entity.User;
import crushstudio.crush_studio.repository.UserRepository;
import crushstudio.crush_studio.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.persistence.EntityExistsException;
import java.time.LocalDate;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private Mapper mapper;
@Override
public void createUser(UserDTO userDTO) {
if(userDTO.getPassword()!=null){
User user = mapper.map(userDTO, User.class);
}else{
System.out.println("We not can create user");
}
}
@Override
public UserDTO getUserById(Long id) {
boolean exists=userRepository.existsById(id);
if(!exists){
throw new EntityExistsException("Try again");
}
User user = userRepository.findById(id).get();
UserDTO userDTO = mapper.map(user, UserDTO.class);
return userDTO;
}
@Override
public List<UserDTO> getAllUser() {
List<User> users = userRepository.findAll();
List<UserDTO>userDTOS = mapper.mapAll(users,UserDTO.class);
return userDTOS;
}
@Override
public UserDTO findByNickName(String nickName) {
UserDTO userDTO = mapper.map(userRepository.findByNickname(nickName),UserDTO.class);
return userDTO;
}
@Override
public UserDTO findByLocalDate(LocalDate localDate) {
UserDTO userDTO = mapper.map(userRepository.findByLocalDate(localDate),UserDTO.class);
return userDTO;
}
// @Override
// public UserDTO updateUserById(Long id, UserDTO userToUpdate) {
// boolean exist = userRepository.existsById(id);
// if (!exist){
// return null;
// }
// User userUpdate = mapper.map(userToUpdate, User.class);
// userUpdate.isDeleted();
// userRepository.save(userUpdate);
// return userUpdate;
// }
}
|
package edu.udacity.java.nano;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.*;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.net.URL;
@RunWith(SpringJUnit4ClassRunner.class) // @RunWith: integrate spring with junit
@SpringBootTest(classes = {WebSocketChatApplication.class},webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) // @SpringBootTest: this class is spring boot test.
public class WebSocketChatApplicationTest {
private WebDriver driver;
private WebDriver driver2;
@BeforeClass
public static void setupClass() {
WebDriverManager.chromedriver().setup();
}
@Before
public void setupTest() {
driver = new ChromeDriver();
driver2 = new ChromeDriver();
}
@After
public void teardown() throws Exception{
if (driver != null) {
driver.close();
}
if(driver2!=null){
driver2.close();
}
}
public void loginUser(WebDriver driver,String user){
driver.get("http://localhost:8080");
driver.findElement(By.id("username")).sendKeys(user);
driver.findElement(By.tagName("a")).click();
}
public String getChatNum(WebDriver driver){
return driver.findElement(By.className("chat-num")).getText();
}
public void leaveChat(WebDriver driver){
driver.findElement(By.xpath("/html/body/div[1]/div/a")).click();
}
public void sendText(WebDriver driver,String msg) throws Exception{
driver.findElement(By.id("msg")).sendKeys(msg);
driver.findElement(By.xpath("/html/body/div[2]/div/div/div[1]/div[2]/div[2]/button[1]")).click();
}
@Test
public void testlogin() throws Exception{
loginUser(driver,"Srini");
Assert.assertTrue("User is not redirected to index.html after login",driver.getCurrentUrl().contains("index?username=Srini"));
}
@Test
public void testJoinChat() throws Exception{
loginUser(driver,"Srini");
Assert.assertEquals("chat number is not incremented after user joins chat","1",getChatNum(driver));
loginUser(driver2,"Chella");
Assert.assertEquals("chat number is not incremented in the previous user page after new user joins chat","2",getChatNum(driver));
Assert.assertEquals("chat number is not shown properly in the new user page","2",getChatNum(driver2));
}
@Test
public void testLeaveChat() throws Exception{
loginUser(driver,"Srini");
loginUser(driver2,"Chella");
leaveChat(driver);
Assert.assertEquals("chat number is not decremented after a user leaves chat","1",getChatNum(driver2));
}
public String getMessageContent(WebDriver driver,int index){
return driver.findElements(By.className("message-content")).get(index).getText().toString().trim();
}
@Test
public void testChatMessage() throws Exception{
loginUser(driver,"Srini");
loginUser(driver2,"Chella");
sendText(driver,"I am User1");
sendText(driver2,"I am User2");
Thread.sleep(2000);
Assert.assertTrue("User1 Message should appear should appear in User1 chat window",getMessageContent(driver,0).contains("I am User1"));
Assert.assertTrue("User2 Message should appear should appear in User1 chat window",getMessageContent(driver,1).contains("I am User2"));
Assert.assertTrue("User1 Message should appear should appear in User2 chat window",getMessageContent(driver2,0).contains("I am User1"));
Assert.assertTrue("User2 Message should appear should appear in User2 chat window",getMessageContent(driver2,1).contains("I am User2"));
}
}
|
package org.point85.domain.proficy;
import java.util.List;
import com.google.gson.annotations.SerializedName;
/**
* Serialized list of tag names
*
*/
public class Tags extends TagError {
@SerializedName(value = "Tags")
private List<String> tagNames;
public List<String> getTags() {
return tagNames;
}
}
|
package monopoly;
public class Square {
private String name;
private Square nextSquare;
private int index;
public Square(String name, int index) {
this.name = name;
this.index = index;
}
public void setNextSquare(Square s) {
nextSquare = s;
}
public Square getNextSquare() {
return nextSquare;
}
public String getName() {
return name;
}
public int getIndex() {
return index;
}
}
|
/*
* (C) Mississippi State University 2009
*
* The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is
* a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries
* and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in
* http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in
* all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html.
*/
//AnimationEngine.java
//Defines the interface for an Animation's calculation engine
//Davis Herring
//Created July 20 2002
//Updated March 26 2004
//Version 1.0 (cosmetically different from 0.3)
package org.webtop.util;
/**
* An object that implements <code>AnimationEngine</code> can be given to an
* <code>Animation</code>, which will then use it for calculations.
*/
public interface AnimationEngine
{
/**
* Called when the <code>Animation</code> object is constructed. The
* <code>Animation<code> is completely established, but the thread has not
* been started. This will only be called once by <code>Animation</code>
* (although other code may of course call it).
*/
public void init(Animation a);
/**
* Called just before a calculation. The argument indicates how many
* animation periods have elapsed since last call. Ideally is always close
* to 1; may be greater if system is unable to keep up with animation. A
* value of 0 indicates that an update has been explicitly requested. This
* function should return false if the engine does not wish to execute this
* iteration (as might be appropriate if system load is too high).
*
* @param periods the number of periods that have elapsed since the last
* call to this function.
* @return true if execute() should be called for this iteration; false
* otherwise.
*/
public boolean timeElapsed(float periods);
/**
* Performs the calculation for the animation.
*
* <p>The data object supplied is guaranteed to remain unchanged throughout
* the call to this function; furthermore, successive calls to execute will
* use the same <code>Data</code> object if and only if no new
* <code>Data</code> object has been given to the <code>Animation</code>.
*
* @param d the client-specified data object containing parameters for the
* animation.
*/
public void execute(Animation.Data d);
}
|
package com.stk123.model;
import java.io.Serializable;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import com.stk123.service.ServiceConstant;
import com.stk123.model.bo.StkUser;
import com.stk123.common.db.util.sequence.SequenceUtils;
import com.stk123.common.util.JdbcUtils;
import com.stk123.common.CommonConstant;
public class User implements Serializable{
private StkUser stkUser;
public User(StkUser su){
this.stkUser = su;
}
private final static String SQL_LOAD_BY_NAME = "select * from stk_user where email=?";
public static User loadByEmail(Connection conn, String email){
StkUser su = JdbcUtils.load(conn, SQL_LOAD_BY_NAME, email, StkUser.class);
if(su == null)return null;
return new User(su);
}
private final static String SQL_LOAD_BY_NAME_OR_EMAIL = "select * from stk_user where nickname=? or email=lower(?)";
public static User loadByNameOrEmail(Connection conn, String name, String email){
List params = new ArrayList();
params.add(name);
params.add(email);
StkUser su = JdbcUtils.load(conn, SQL_LOAD_BY_NAME_OR_EMAIL, params, StkUser.class);
if(su == null)return null;
return new User(su);
}
public static User create(Connection conn, String name, String email, String pw){
long userId = SequenceUtils.getSequenceNextValue(SequenceUtils.SEQ_USER_ID);
List params = new ArrayList();
params.add(userId);
params.add(name);
params.add(pw);
params.add(email);
int i = JdbcUtils.insert(conn, "insert into stk_user(id,nickname,password,email) values (?,?,?,?)", params);
if(i > 0){
StkUser stkUser = new StkUser();
stkUser.setId((int)userId);
stkUser.setNickname(name);
stkUser.setEmail(email);
return new User(stkUser);
}else{
return null;
}
}
public void updateEarningSearchParams(Connection conn, String json) {
stkUser.setEarningSearchParams(json);
List params = new ArrayList();
params.add(json);
params.add(stkUser.getId());
JdbcUtils.update(conn, "update stk_user set earning_search_params=? where id=?", params);
}
public StkUser getStkUser() {
return stkUser;
}
public void setStkUser(StkUser stkUser) {
this.stkUser = stkUser;
}
public String getUserUploadImagePath(){
return ServiceConstant.WEB_IMAGE_PATH + this.getStkUser().getId() + CommonConstant.MARK_SLASH;
}
private final static String PATH_IMAGES = "/images/";
public String getUserUploadImageRelativePath(){
return PATH_IMAGES + this.getStkUser().getId() + CommonConstant.MARK_SLASH;
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.handler.annotation.reactive;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.core.MethodParameter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.invocation.ResolvableMethod;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.messaging.support.NativeMessageHeaderAccessor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Test fixture for {@link HeadersMethodArgumentResolver} tests.
* @author Rossen Stoyanchev
*/
public class HeadersMethodArgumentResolverTests {
private final HeadersMethodArgumentResolver resolver = new HeadersMethodArgumentResolver();
private Message<byte[]> message =
MessageBuilder.withPayload(new byte[0]).copyHeaders(Collections.singletonMap("foo", "bar")).build();
private final ResolvableMethod resolvable = ResolvableMethod.on(getClass()).named("handleMessage").build();
@Test
public void supportsParameter() {
assertThat(this.resolver.supportsParameter(
this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class))).isTrue();
assertThat(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaders.class))).isTrue();
assertThat(this.resolver.supportsParameter(this.resolvable.arg(MessageHeaderAccessor.class))).isTrue();
assertThat(this.resolver.supportsParameter(this.resolvable.arg(TestMessageHeaderAccessor.class))).isTrue();
assertThat(this.resolver.supportsParameter(this.resolvable.annotPresent(Headers.class).arg(String.class))).isFalse();
}
@Test
@SuppressWarnings("unchecked")
public void resolveArgumentAnnotated() {
MethodParameter param = this.resolvable.annotPresent(Headers.class).arg(Map.class, String.class, Object.class);
Map<String, Object> headers = resolveArgument(param);
assertThat(headers.get("foo")).isEqualTo("bar");
}
@Test
public void resolveArgumentAnnotatedNotMap() {
assertThatIllegalStateException().isThrownBy(() ->
resolveArgument(this.resolvable.annotPresent(Headers.class).arg(String.class)));
}
@Test
public void resolveArgumentMessageHeaders() {
MessageHeaders headers = resolveArgument(this.resolvable.arg(MessageHeaders.class));
assertThat(headers.get("foo")).isEqualTo("bar");
}
@Test
public void resolveArgumentMessageHeaderAccessor() {
MessageHeaderAccessor headers = resolveArgument(this.resolvable.arg(MessageHeaderAccessor.class));
assertThat(headers.getHeader("foo")).isEqualTo("bar");
}
@Test
public void resolveArgumentMessageHeaderAccessorSubclass() {
TestMessageHeaderAccessor headers = resolveArgument(this.resolvable.arg(TestMessageHeaderAccessor.class));
assertThat(headers.getHeader("foo")).isEqualTo("bar");
}
@SuppressWarnings({"unchecked", "ConstantConditions"})
private <T> T resolveArgument(MethodParameter param) {
return (T) this.resolver.resolveArgument(param, this.message).block(Duration.ofSeconds(5));
}
@SuppressWarnings("unused")
private void handleMessage(
@Headers Map<String, Object> param1,
@Headers String param2,
MessageHeaders param3,
MessageHeaderAccessor param4,
TestMessageHeaderAccessor param5) {
}
public static class TestMessageHeaderAccessor extends NativeMessageHeaderAccessor {
TestMessageHeaderAccessor(Message<?> message) {
super(message);
}
public static TestMessageHeaderAccessor wrap(Message<?> message) {
return new TestMessageHeaderAccessor(message);
}
}
}
|
package com.example.jwtdemo2.controllers;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.example.jwtdemo2.models.*;
import com.example.jwtdemo2.repository.CreatorRepository;
import com.example.jwtdemo2.services.MovieRatingService;
import com.example.jwtdemo2.services.TvRatingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import com.example.jwtdemo2.payload.request.LoginRequest;
import com.example.jwtdemo2.payload.request.SignupRequest;
import com.example.jwtdemo2.payload.response.JwtResponse;
import com.example.jwtdemo2.payload.response.MessageResponse;
import com.example.jwtdemo2.repository.RoleRepository;
import com.example.jwtdemo2.repository.UserRepository;
import com.example.jwtdemo2.security.jwt.JwtUtils;
import com.example.jwtdemo2.security.services.UserDetailsImpl;
import javax.servlet.http.HttpSession;
//part of code credit from
//https://bezkoder.com/spring-boot-jwt-authentication/#google_vignette
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
CreatorRepository creatorRepository;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
@Autowired
TestController controller;
@Autowired
MovieRatingService movieRatingService;
@Autowired
TvRatingService tvRatingService;
@GetMapping ("/movierating/{mid}")
public List<rateDemo> findRatingByMovieId(@PathVariable("mid") Integer mid){
Long l = new Long(mid);
List<MovieRating> rates= movieRatingService.findRatingByMovieId(l);
List<rateDemo> ratings=new ArrayList<>();
for (MovieRating r:rates){
ratings.add(new rateDemo(r.getRatingId(),r.getComment(),r.getRate(),r.getUser().getUsername(),r.getMovie().getMovieId()));
}
return ratings;
}
@GetMapping ("/tvrating/{tid}")
public List<rateDemo> findRatingByTvId(@PathVariable("tid") Integer tid){
Long l = new Long(tid);
List<TvRating> rates= tvRatingService.findRatingByTvId(l);
List<rateDemo> ratings=new ArrayList<>();
for (TvRating r:rates){
ratings.add(new rateDemo(r.getRatingId(),r.getComment(),r.getRate(),r.getUser().getUsername(),r.getTvId()));
}
return ratings;
}
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest, HttpSession session) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
Set<Role> r=new HashSet<>();
for(String s:roles){
Role role;
switch (s){
case "ROLE_ADMIN":
role=new Role(ERole.ROLE_ADMIN);
break;
case "ROLE_CREATOR":
role=new Role(ERole.ROLE_CREATOR);
break;
default:
role=new Role(ERole.ROLE_USER);
}
r.add(role);
}
User u=new User(userDetails.getId(),userDetails.getUsername(),
userDetails.getEmail(),r);
session.setAttribute("currentUser", u);
session.setAttribute("token", jwt);
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
}
@PostMapping("/signup")
public ResponseEntity<?> registerUser( @RequestBody SignupRequest signUpRequest) {
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Username is already taken!"));
}
if (userRepository.existsByEmail(signUpRequest.getEmail())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}
// Create new user's account
User user = new User(signUpRequest.getUsername(),
signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()),
signUpRequest.getFirstname(),signUpRequest.getLastname());
Set<String> strRoles = signUpRequest.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(adminRole);
break;
case "creator":
Role creatorRole = roleRepository.findByName(ERole.ROLE_CREATOR)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(creatorRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
}
});
}
user.setRoles(roles);
userRepository.save(user);
for(String s:strRoles){
if(s.equals("admin")){
Long id=userRepository.findByUsername(signUpRequest.getUsername()).get().getId();
userRepository.insertAdmin(id,signUpRequest.getPasscode());
}else if(s.equals("creator")){
Long id=userRepository.findByUsername(signUpRequest.getUsername()).get().getId();
userRepository.insertCreator(id,signUpRequest.getCompany());
}
}
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
}
|
package edu.student.page.javin;
import edu.jenks.dist.student.*;
/**
* Write a description of class Student here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Student extends AbstractStudent
{
private double testScore1 = 0.0;
private double testScore2 = 0.0;
private double testScore3 = 0.0;
public static void main(String[] args) {
String streetAddress = "123 Address St.";
int zipCode = 12345;
String city = "Idiotown";
String state = "Oregon";
String firstName = "John";
String lastName = "Doe";
Address homeAddress = new Address(streetAddress, city, state, zipCode);
Address schoolAddress = new Address(streetAddress, city, state, zipCode);
Student instance = new Student(firstName, lastName, homeAddress, schoolAddress, 0, 0, 0);
instance.setTestScore(1, 45);
instance.setTestScore(2, 98);
instance.setTestScore(3, 73);
System.out.println(instance.toString());
}
public Student(String firstName,String lastName, Address homeAddress, Address schoolAddress,double testScore1, double testScore2, double testScore3){
super(firstName, lastName, homeAddress, schoolAddress);
this.testScore1 = testScore1;
this.testScore2 = testScore2;
this.testScore3 = testScore3;
}
public void setTestScore(int testNumber, double score){
switch(testNumber) {
case 1:
testScore1 = score;
break;
case 2:
testScore2 = score;
break;
case 3:
testScore3 = score;
break;
default:
break;
}
}
public double getTestScore(int testNumber){
switch(testNumber) {
case 1:
return testScore1;
case 2:
return testScore2;
case 3:
return testScore3;
default:
return 0.0;
}
}
public double average(){
return (testScore1 + testScore2 + testScore3) / 3;
}
public String toString(){
return getFirstName() + " " + getLastName() + NEW_LINE + "Home Address:" + NEW_LINE + getHomeAddress() + NEW_LINE + "School Address:" + NEW_LINE + getSchoolAddress() + NEW_LINE + "Test score 1: " + getTestScore(1) + NEW_LINE + "Test score 2: " + getTestScore(2) + NEW_LINE + "Test score 3: " + getTestScore(3) + NEW_LINE + "Average test score: " + average();
}
}
|
package com.github.olly.workshop.trafficgen;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableFeignClients(basePackages = { "com.github" })
@EnableAsync
@EnableScheduling
public class TrafficGenApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(TrafficGenApplication.class, args);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
|
package com.hb.framework.system.service;
import java.text.ParseException;
import java.util.List;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hb.framework.superhelp.task.QuartzManager;
import com.hb.framework.superhelp.task.TargetJob;
import com.hb.framework.superhelp.util.PageView;
import com.hb.framework.system.dao.BaseDataDao;
import com.hb.framework.system.entity.BaseData;
@Transactional
@Service("baseDataService")
public class BaseDataService{
@Autowired
private BaseDataDao baseDataDao;
public void add(BaseData baseData) {
baseDataDao.add(baseData);
if("100".equals(baseData.getType())){
setTask(baseData);
}
}
public PageView query(PageView pageView, BaseData baseData) {
List<BaseData> list = baseDataDao.query(pageView, baseData);
pageView.setRecords(list);
return pageView;
}
public List<BaseData> findType(String type) {
return baseDataDao.findType(type);
}
public void delete(String id) {
BaseData baseData=this.getById(id);
if("100".equals(baseData.getType())){
shutdownTaskByEnName(baseData.getAlias());
}
baseDataDao.delete(id);
}
public BaseData getById(String id) {
return baseDataDao.getById(id);
}
public void modify(BaseData baseData) {
baseDataDao.modify(baseData);
if("100".equals(baseData.getType())){
setTask(baseData);
}
}
public BaseData findByAlias(String alias) {
return baseDataDao.findByAlias(alias);
}
/**
* 添加所有需要执行的任务
*/
public void setAllTask() {
List<BaseData> list = baseDataDao.findTask();
for (BaseData task : list) {
setTask(task);
}
}
/**
* 根据用户设定的值添加任务
* @param task
*/
private void setTask(BaseData task) {
String class_method_cron=task.getValue();
//判断配置参数是否符合条件
if(null!=class_method_cron && !"".equals(class_method_cron) && class_method_cron.indexOf("#")>-1){
String params[]=class_method_cron.split("#");
String targetObject = params[0];//执行的类
String targetMethod = params[1];//方法
String cronExpression = params[2];//时间配置
String alias = task.getAlias();//时间配置
try {
shutdownTaskByEnName(alias);
if(task.getStatus()==1){
Job job = new TargetJob();
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put(TargetJob.TARGET_OBJECT, targetObject);
jobDataMap.put(TargetJob.TARGET_METHOD, targetMethod);
QuartzManager.addJob(alias, job, cronExpression, jobDataMap);
}
} catch (SchedulerException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
/**
* 移除某个任务
* @param enName 添加任务时取的名称
*/
public void shutdownTaskByEnName(String class_method_cron) {
try {
Scheduler sched = QuartzManager.sf.getScheduler();
Trigger trigger = sched.getTrigger(class_method_cron,QuartzManager.TRIGGER_GROUP_NAME);
if (trigger != null) {
QuartzManager.removeJob(class_method_cron);
}
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
|
package question5_oneEditAway;
import java.util.Arrays;
public class Method1 {
public boolean oneEditAway(String first, String second) {
int firstLen = first.length();
int secondLen = second.length();
if (firstLen == 0 && secondLen == 0) {
return true;
}
int abs = Math.abs(firstLen - secondLen);
if (abs > 1) {
return false;
}
// insert or delete
if (abs == 1) {
return insertOrDelete(first, second);
}
// replace or equals
else {
return replaceOrEquals(first, second);
}
}
private static boolean insertOrDelete(String first, String second) {
char[] firstChars = first.toCharArray();
char[] secondChars = second.toCharArray();
int lenOfFirst = firstChars.length;
int lenOfSecond = secondChars.length;
if (lenOfFirst == 0 || lenOfSecond == 0) {
return true;
}
if (lenOfFirst > lenOfSecond) {
int i = 0; // first
int j = 0; // second
while (j < lenOfSecond && firstChars[i] == secondChars[j]) {
i++;
j++;
}
i++;
for (; j < lenOfSecond; j++, i++) {
if (firstChars[i] != secondChars[j]) {
return false;
}
}
return true;
} else {
// lenOfFirst < lenOfSecond
int i = 0; // first
int j = 0; // second
while (i < lenOfFirst && firstChars[i] == secondChars[j]) {
i++;
j++;
}
j++;
for (; i < lenOfFirst; j++, i++) {
if (firstChars[i] != secondChars[j]) {
return false;
}
}
return true;
}
}
private static boolean replaceOrEquals(String first, String second) {
char[] firstChars = first.toCharArray();
char[] secondChars = second.toCharArray();
if (Arrays.equals(firstChars, secondChars)) {
return true;
}
int differ = 0;
for (int i = 0; i < firstChars.length; i++) {
if (firstChars[i] != secondChars[i]) {
differ++;
}
}
return differ == 1;
}
}
|
package gil.server.data;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class PeopleData {
private List<Person> people = new ArrayList<>();
public Person addPerson(String name, String email) {
Person p = new Person(generateId(), name, email);
this.people.add(p);
return p;
}
private Integer generateId() {
Integer id = 0;
if(!this.people.isEmpty()){
List<Integer> listOfID = people.stream()
.map(Person::getId)
.collect(toList());
id = Collections.max(listOfID) + 1;
}
return id;
}
public JsonObject getPeople() {
JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
this.people.stream().forEach(person -> {
JsonObject jobj = jsonBuilder.add("id", person.getId())
.add("name", person.getName())
.add("email", person.getEmail()).build();
jsonArrayBuilder.add(jobj);
});
JsonArray jsonArray = jsonArrayBuilder.build();
JsonObject jsonData = jsonBuilder.add("people", jsonArray).build();
return jsonData;
}
public Person getPerson(int personId) {
List<Person> locatedPerson = this.people.stream()
.filter(person -> person.getId() == personId)
.collect(toList());
return locatedPerson.get(0);
}
public JsonObject getPersonJSONObject(String jsonString) {
JsonReader reader = Json.createReader(new StringReader(jsonString));
JsonObject jsonObject = reader.readObject();
return jsonObject;
}
public void updatePeople(JsonObject data) {
JsonArray peopleArray = data.getJsonArray("people");
if (!peopleArray.isEmpty()) {
this.people = peopleArray.stream()
.map(json ->
new Person(
json.asJsonObject().getInt("id"),
json.asJsonObject().getString("name"),
json.asJsonObject().getString("email"))).collect(toList());
}
}
}
|
package com.goldenasia.lottery.data;
import java.util.List;
/**
* Created by Gan on 2017/10/26.
*/
public class GaGameListResponse {
/**
* list : [{"ga_id":"39","user_id":"56911","username":"zdavy","top_id":"56911","belong_date":"2016-11-10","last_ga_balance":"0","ga_balance":"12010","game_id":"101","ga_buy_amount":"15700.00","ga_prize_amount":"17700.00","ga_rebate_amount":"0.00","ga_win_lose":"2000.00","frm":"1","ts":"2016-11-14 19:47:12","game_name":"游戏名称"}]
* param : {"curPage":1,"sum":"3"}
*/
private ParamBean param;
private List<ListBean> list;
public ParamBean getParam() {
return param;
}
public void setParam(ParamBean param) {
this.param = param;
}
public List<ListBean> getList() {
return list;
}
public void setList(List<ListBean> list) {
this.list = list;
}
public static class ParamBean {
/**
* curPage : 1
* sum : 3
*/
private int curPage;
private String sum;
public int getCurPage() {
return curPage;
}
public void setCurPage(int curPage) {
this.curPage = curPage;
}
public String getSum() {
return sum;
}
public void setSum(String sum) {
this.sum = sum;
}
}
public static class ListBean {
/**
* ga_id : 39
* user_id : 56911
* username : zdavy
* top_id : 56911
* belong_date : 2016-11-10
* last_ga_balance : 0
* ga_balance : 12010
* game_id : 101
* ga_buy_amount : 15700.00
* ga_prize_amount : 17700.00
* ga_rebate_amount : 0.00
* ga_win_lose : 2000.00
* frm : 1
* ts : 2016-11-14 19:47:12
* game_name : 游戏名称
*/
private String ga_id;
private String user_id;
private String username;
private String top_id;
private String belong_date;
private String last_ga_balance;
private String ga_balance;
private String game_id;
private String ga_buy_amount;
private String ga_prize_amount;
private String ga_rebate_amount;
private String ga_win_lose;
private String frm;
private String ts;
private String game_name;
public String getGa_id() {
return ga_id;
}
public void setGa_id(String ga_id) {
this.ga_id = ga_id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTop_id() {
return top_id;
}
public void setTop_id(String top_id) {
this.top_id = top_id;
}
public String getBelong_date() {
return belong_date;
}
public void setBelong_date(String belong_date) {
this.belong_date = belong_date;
}
public String getLast_ga_balance() {
return last_ga_balance;
}
public void setLast_ga_balance(String last_ga_balance) {
this.last_ga_balance = last_ga_balance;
}
public String getGa_balance() {
return ga_balance;
}
public void setGa_balance(String ga_balance) {
this.ga_balance = ga_balance;
}
public String getGame_id() {
return game_id;
}
public void setGame_id(String game_id) {
this.game_id = game_id;
}
public String getGa_buy_amount() {
return ga_buy_amount;
}
public void setGa_buy_amount(String ga_buy_amount) {
this.ga_buy_amount = ga_buy_amount;
}
public String getGa_prize_amount() {
return ga_prize_amount;
}
public void setGa_prize_amount(String ga_prize_amount) {
this.ga_prize_amount = ga_prize_amount;
}
public String getGa_rebate_amount() {
return ga_rebate_amount;
}
public void setGa_rebate_amount(String ga_rebate_amount) {
this.ga_rebate_amount = ga_rebate_amount;
}
public String getGa_win_lose() {
return ga_win_lose;
}
public void setGa_win_lose(String ga_win_lose) {
this.ga_win_lose = ga_win_lose;
}
public String getFrm() {
return frm;
}
public void setFrm(String frm) {
this.frm = frm;
}
public String getTs() {
return ts;
}
public void setTs(String ts) {
this.ts = ts;
}
public String getGame_name() {
return game_name;
}
public void setGame_name(String game_name) {
this.game_name = game_name;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.